From 2f31680823311968f84771289a750dd36989b73d Mon Sep 17 00:00:00 2001 From: "alexei.dolgolyov" Date: Sat, 16 May 2026 03:26:53 +0300 Subject: [PATCH] feat(devices): pairing-UX scaffold (Phase 2) Lays the groundwork for device families that require a one-time physical pairing action (Nanoleaf hold-power-button, Tuya local-key extraction, Twinkly network-setup mode, Hue link-button). No driver uses it yet -- Nanoleaf will be the first concrete consumer. Phase 2 as originally written had three bullets; only this one was genuinely missing work. The other two (generic NetworkDiscoveryService fan-out, unified scan-network UI) were already solved at the route level by the existing /api/v1/devices/discover handler running all providers in parallel via asyncio.gather(return_exceptions=True). Marked WONTDO in TODO.md with rationale. Backend: - LEDDeviceProvider gains an async pair_device(url) -> dict method. Default raises NotImplementedError so missing implementations on a requires_pairing provider fail loud at request time. - New PairingNotReady exception, distinct from generic errors so the route handler can return 409 (user must perform the physical action, retry possible) instead of 500. - POST /api/v1/devices/pair endpoint with PairDeviceRequest / PairDeviceResponse schemas. Status-code mapping: 200 -> paired, fields returned for the subsequent create payload 400 -> unknown device type, or type doesn't support pairing 409 -> PairingNotReady (retryable from the UI) 422 -> invalid URL / device configuration (ValueError) 502 -> transport / network failure (other exceptions) 500 -> provider returned a non-dict (defensive) - 8 route tests register a stub provider and exercise every status-code path. Frontend: - New modals/pair-device.html with five state blocks (idle / pairing / not_ready / success / failed) toggled via data-pair-state, plus a 30-second SVG progress ring with monospace countdown. - New features/pairing-flow.ts exposing runPairingFlow({deviceType, url, instructionsKey?}) -> Promise<{fields: Record>. Wires the modal to the pair endpoint, maps response codes to UI states, AbortControllers in-flight fetches on cancel. Exports a PairingCancelled sentinel error class. - Generic pairing.* i18n keys in en/ru/zh. Drivers will add their own device..pair.instructions key that overrides the default. Design decisions (per frontend-design skill): - Single SVG ring + centered countdown (HomeKit-style) - Instructions stay visible during pairing, dimmed to 60% via :has() - Success state held 450 ms before auto-dismiss - Cancel-X in the footer; primary action lives in the state block - prefers-reduced-motion disables pulse/fade/ring transitions Note: the components.css diff includes a pre-existing MiniSelect block from the user's parallel work; pairing-specific styles are the second hunk (lines ~1628+). --- TODO.md | 21 +- server/src/ledgrab/api/routes/devices.py | 69 ++++ server/src/ledgrab/api/schemas/devices.py | 26 ++ server/src/ledgrab/core/devices/led_client.py | 33 ++ server/src/ledgrab/static/css/components.css | 264 ++++++++++++++ .../static/js/features/pairing-flow.ts | 333 ++++++++++++++++++ server/src/ledgrab/static/locales/en.json | 13 +- server/src/ledgrab/static/locales/ru.json | 13 +- server/src/ledgrab/static/locales/zh.json | 13 +- server/src/ledgrab/templates/index.html | 1 + .../ledgrab/templates/modals/pair-device.html | 86 +++++ .../tests/api/routes/test_devices_routes.py | 137 +++++++ 12 files changed, 1003 insertions(+), 6 deletions(-) create mode 100644 server/src/ledgrab/static/js/features/pairing-flow.ts create mode 100644 server/src/ledgrab/templates/modals/pair-device.html diff --git a/TODO.md b/TODO.md index 48e245a..4c6d571 100644 --- a/TODO.md +++ b/TODO.md @@ -710,9 +710,24 @@ Philips' UDP-local budget tier. Port 38899 JSON UDP. After phase 1 the codebase will have 3 fresh examples of "ping the LAN, listen for replies, present a list". Factor that out into a generic discovery scaffold + a "first-run pairing" UX component before adding Tuya/Govee/etc., which each need a one-time pairing dance. -- [ ] Generic `NetworkDiscoveryService` that fan-outs mDNS + SSDP + UDP-broadcast probes in parallel -- [ ] Unified "scan network for devices" UI affordance instead of per-type buttons -- [ ] Reusable "pair device" component (consent button, countdown, retry) +- [WONTDO] Generic `NetworkDiscoveryService` — the existing + `/api/v1/devices/discover` route already runs all providers in parallel + via `asyncio.gather(return_exceptions=True)`. Extracting it would not + unlock anything; revisit only if discovery cadence/dedup becomes a + real complaint. +- [WONTDO] Unified scan UI — already exists; one "Scan network" button + triggers the cross-provider fan-out. +- [x] **Reusable pair-device scaffold** (the actually-needed piece). + Backend: `LEDDeviceProvider.pair_device(url)` abstract method with + `PairingNotReady` sentinel; `POST /api/v1/devices/pair` endpoint + with status-code mapping (200/400/409/422/502); 8 route tests + covering every outcome. Frontend: `templates/modals/pair-device.html` + five-state modal (idle / pairing / not-ready / success / failed) + with a 30-second SVG progress ring; reusable + `static/js/features/pairing-flow.ts` exposing + `runPairingFlow({deviceType, url}) → Promise<{fields}>` with + `PairingCancelled` sentinel; locale strings in en/ru/zh. No driver + uses it yet — Nanoleaf will be the first concrete consumer. ### Phase 3 — Big aggregator unlocks diff --git a/server/src/ledgrab/api/routes/devices.py b/server/src/ledgrab/api/routes/devices.py index 029bf9d..b1d43e2 100644 --- a/server/src/ledgrab/api/routes/devices.py +++ b/server/src/ledgrab/api/routes/devices.py @@ -5,6 +5,7 @@ from fastapi import APIRouter, HTTPException, Depends, Query, WebSocket, WebSock from ledgrab.api.auth import AuthRequired from ledgrab.core.devices.led_client import ( + PairingNotReady, get_all_providers, get_device_capabilities, get_provider, @@ -26,6 +27,8 @@ from ledgrab.api.schemas.devices import ( DiscoverDevicesResponse, OpenRGBZoneResponse, OpenRGBZonesResponse, + PairDeviceRequest, + PairDeviceResponse, PowerRequest, ) from ledgrab.core.processing.processor_manager import ProcessorManager @@ -282,6 +285,72 @@ async def create_device( raise HTTPException(status_code=500, detail="Internal server error") +@router.post( + "/api/v1/devices/pair", + response_model=PairDeviceResponse, + tags=["Devices"], +) +async def pair_device( + body: PairDeviceRequest, + _auth: AuthRequired, +): + """Run a pairing handshake against a device before creating it. + + The frontend opens this endpoint after the user has performed the + device's physical pairing action (e.g. held the power button for 5s). + The response carries provider-specific fields the caller must include + in the subsequent ``POST /api/v1/devices`` body. + + Status codes: + 200 paired — fields returned + 400 unknown device type, or device type does not support pairing + 409 device not ready — user must perform the physical action + (or retry, e.g. the pairing window timed out) + 422 invalid URL or device configuration + """ + try: + provider = get_provider(body.device_type) + except ValueError: + raise HTTPException(status_code=400, detail=f"Unknown device type: {body.device_type}") + + try: + fields = await provider.pair_device(body.url) + except NotImplementedError: + raise HTTPException( + status_code=400, + detail=f"Device type {body.device_type!r} does not support pairing", + ) + except PairingNotReady as exc: + raise HTTPException(status_code=409, detail=str(exc)) + except ValueError as exc: + raise HTTPException(status_code=422, detail=str(exc)) + except Exception as exc: + logger.warning( + "Pairing failed for %s at %s: %s", + body.device_type, + body.url, + exc, + exc_info=True, + ) + raise HTTPException( + status_code=502, + detail=f"Pairing failed for {body.device_type} at {body.url}.", + ) + + if not isinstance(fields, dict): + logger.warning( + "Provider %s.pair_device returned %r (expected dict)", + body.device_type, + type(fields).__name__, + ) + raise HTTPException( + status_code=500, + detail=f"Provider {body.device_type!r} returned malformed pairing result", + ) + + return PairDeviceResponse(fields=fields) + + @router.get("/api/v1/devices", response_model=DeviceListResponse, tags=["Devices"]) async def list_devices( _auth: AuthRequired, diff --git a/server/src/ledgrab/api/schemas/devices.py b/server/src/ledgrab/api/schemas/devices.py index 37dab0e..9f98147 100644 --- a/server/src/ledgrab/api/schemas/devices.py +++ b/server/src/ledgrab/api/schemas/devices.py @@ -232,6 +232,32 @@ class DeviceUpdate(BaseModel): ) +class PairDeviceRequest(BaseModel): + """Initiate a pairing handshake with a device before creating it. + + The caller is expected to have just performed the device's physical + pairing action (e.g. holding the power button on a Nanoleaf for 5 s, + pressing the Hue bridge link button). The response carries any + provider-specific fields the frontend must include in the subsequent + ``POST /api/v1/devices`` payload — typically an auth token. + """ + + device_type: str = Field(description="Device type identifier (e.g. 'nanoleaf')") + url: str = Field(description="Device URL (e.g. 'nanoleaf://192.168.1.50')") + + +class PairDeviceResponse(BaseModel): + """Successful pairing result. ``fields`` is merged into the create payload.""" + + fields: Dict[str, object] = Field( + default_factory=dict, + description=( + "Provider-specific fields to include in the subsequent device-create " + "request (e.g. {'nanoleaf_token': 'abc...'})." + ), + ) + + class CalibrationLineSchema(BaseModel): """One LED line in advanced calibration.""" diff --git a/server/src/ledgrab/core/devices/led_client.py b/server/src/ledgrab/core/devices/led_client.py index 2a0cfdf..e0c49fb 100644 --- a/server/src/ledgrab/core/devices/led_client.py +++ b/server/src/ledgrab/core/devices/led_client.py @@ -37,6 +37,15 @@ class DeviceHealth: error: Optional[str] = None +class PairingNotReady(Exception): + """Raised by ``pair_device`` when the user hasn't performed the physical + pairing action yet (or it timed out before the device acknowledged). + + Distinct from generic exceptions so the route handler can return a 409 + instead of a 500 — the UI shows a retry prompt rather than a hard error. + """ + + @dataclass class DiscoveredDevice: """A device found via network discovery.""" @@ -216,6 +225,30 @@ class LEDDeviceProvider(ABC): """ return [] + async def pair_device(self, url: str) -> Dict[str, object]: + """Run a pairing handshake against the device at ``url``. + + Implementations expect the user to have just performed the device's + physical pairing action (Nanoleaf: hold power 5s; Hue: press the + link button; Twinkly: enter Network setup mode) before calling. + + Returns: + A dict of provider-specific fields that the caller should merge + into the subsequent ``create_device`` payload — e.g. + ``{"nanoleaf_token": "abc..."}`` or ``{"tuya_local_key": "..."}``. + + Raises: + PairingNotReady when the user hasn't performed the physical + action yet (the caller surfaces this as a retryable 409 so + the UI can show "Press the button now, then try again"). + ValueError on a fundamentally invalid URL or device. + + Default: raises ``NotImplementedError`` so a missing implementation + on a ``requires_pairing`` provider fails loud at request time + rather than silently returning an empty dict. + """ + raise NotImplementedError(f"{self.device_type} doesn't support pairing") + async def get_brightness(self, url: str) -> int: """Get device brightness (0-255). Override if capabilities include brightness_control.""" raise NotImplementedError diff --git a/server/src/ledgrab/static/css/components.css b/server/src/ledgrab/static/css/components.css index c5f72ed..3b95299 100644 --- a/server/src/ledgrab/static/css/components.css +++ b/server/src/ledgrab/static/css/components.css @@ -1045,6 +1045,79 @@ textarea:focus-visible { border-color: var(--primary-color); background: color-mix(in srgb, var(--primary-color) 12%, var(--bg-secondary)); } +/* ── MiniSelect (icon-less compact dropdown) ── */ +.mini-select-trigger { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 4px 10px; + min-height: 28px; + background: var(--bg-secondary); + border: 1px solid var(--border-color); + border-radius: 6px; + color: var(--text-primary); + font-size: 0.85rem; + cursor: pointer; + transition: border-color 120ms ease, background 120ms ease; +} +.mini-select-trigger:hover, +.mini-select-trigger:focus-visible { + border-color: var(--primary-color); +} +.mini-select-trigger-arrow { + opacity: 0.6; + font-size: 0.75em; +} +.mini-select-popup { + position: fixed; + background: var(--card-bg); + border: 1px solid var(--border-color); + border-radius: 8px; + box-shadow: 0 6px 24px rgba(0, 0, 0, 0.35); + z-index: 9999; + overflow-y: auto; + display: none; + padding: 4px; + min-width: 120px; +} +.mini-select-popup.open { display: block; } +.mini-select-popup:focus, +.mini-select-popup:focus-visible { + outline: none; +} +.mini-select-option { + padding: 6px 10px; + border-radius: 4px; + cursor: pointer; + color: var(--text-primary); + font-size: 0.85rem; + user-select: none; +} +.mini-select-option:hover { + background: color-mix(in srgb, var(--primary-color) 14%, transparent); +} +.mini-select-option.active { + color: var(--primary-color); + font-weight: 600; +} +.mini-select-option.focused { + background: color-mix(in srgb, var(--primary-color) 20%, transparent); + box-shadow: inset 0 0 0 2px color-mix(in srgb, var(--primary-color) 45%, transparent); +} + +.icon-select-cell.focused { + border-color: var(--primary-color); + box-shadow: 0 0 0 3px color-mix(in srgb, var(--primary-color) 30%, transparent); +} +/* When the keyboard cursor lands on the currently-selected cell, intensify + the focus ring so the combined active+focused state is unambiguous. */ +.icon-select-cell.active.focused { + box-shadow: 0 0 0 3px color-mix(in srgb, var(--primary-color) 55%, transparent); +} +.icon-select-popup:focus, +.icon-select-popup:focus-visible { + outline: none; +} .icon-select-cell-icon { display: flex; @@ -1628,3 +1701,194 @@ textarea:focus-visible { height: 16px; fill: currentColor; } + +/* ── Pair Device Modal ────────────────────────────────────────── + Reusable handshake UI for drivers that require a physical pairing + action (Nanoleaf, Tuya, Twinkly, …). See `features/pairing-flow.ts` + and `modals/pair-device.html`. The instructions stay visible across + states, dimming during pairing so the user remains oriented while + the progress ring takes focal point. */ + +.pair-instructions { + color: var(--lux-ink-dim, var(--text-secondary)); + font-size: 0.92rem; + line-height: 1.5; + margin: 0 0 18px 0; + transition: opacity 0.25s ease; +} + +.pair-states[data-pair-state="pairing"] ~ .pair-instructions, +.pair-states[data-pair-state="pairing"] .pair-instructions { + /* Selector kept for posterity — actual dimming is applied via the + parent attribute below. */ +} + +.modal-body:has(.pair-states[data-pair-state="pairing"]) .pair-instructions { + opacity: 0.6; +} + +.pair-states { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 18px; + padding: 8px 0 4px; + min-height: 200px; +} + +.pair-state { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 18px; + width: 100%; + animation: pairFade 0.28s ease both; +} + +@keyframes pairFade { + from { opacity: 0; transform: translateY(4px); } + to { opacity: 1; transform: none; } +} + +.pair-action { + min-width: 180px; + justify-content: center; +} + +/* ── Idle visual: device-glyph with a soft pulse halo ────────── */ + +.pair-visual { + position: relative; + width: 96px; + height: 96px; + display: flex; + align-items: center; + justify-content: center; +} + +.pair-visual-glyph { + width: 56px; + height: 56px; + color: var(--ch-signal, var(--primary-color)); + opacity: 0.85; +} + +.pair-pulse { + position: absolute; + inset: 0; + border-radius: 50%; + background: radial-gradient( + circle at center, + color-mix(in srgb, var(--ch-signal, var(--primary-color)) 28%, transparent), + transparent 70% + ); + animation: pairPulse 2.2s ease-in-out infinite; +} + +@keyframes pairPulse { + 0%, 100% { transform: scale(0.85); opacity: 0.55; } + 50% { transform: scale(1.08); opacity: 1; } +} + +/* ── Pairing ring + countdown ────────────────────────────────── */ + +.pair-ring-wrap { + position: relative; + width: 140px; + height: 140px; +} + +.pair-ring { + width: 100%; + height: 100%; + /* Rotate so the fill starts at 12 o'clock and progresses clockwise. */ + transform: rotate(-90deg); +} + +.pair-ring-bg { + stroke: color-mix(in srgb, var(--lux-line-bold, var(--border-color)) 60%, transparent); +} + +.pair-ring-fg { + stroke: var(--ch-signal, var(--primary-color)); + stroke-dasharray: 0 100; + transition: stroke-dasharray 0.18s linear; + filter: drop-shadow(0 0 8px color-mix(in srgb, var(--ch-signal, var(--primary-color)) 45%, transparent)); +} + +.pair-ring-content { + position: absolute; + inset: 0; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 2px; + pointer-events: none; +} + +.pair-ring-count { + font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace); + font-size: 1.9rem; + font-weight: 500; + color: var(--lux-ink, var(--text-color)); + letter-spacing: 0.02em; + line-height: 1; +} + +.pair-ring-label { + font-size: 0.72rem; + text-transform: uppercase; + letter-spacing: 0.16em; + color: var(--lux-ink-dim, var(--text-secondary)); +} + +/* ── Status banners (not-ready / success / failed) ───────────── */ + +.pair-status { + display: flex; + align-items: flex-start; + gap: 12px; + width: 100%; + padding: 14px 16px; + border-radius: 8px; + border: 1px solid var(--lux-line-bold, var(--border-color)); + background: color-mix(in srgb, var(--lux-bg-1, var(--card-bg)) 80%, transparent); + font-size: 0.92rem; + line-height: 1.45; + color: var(--lux-ink, var(--text-color)); +} + +.pair-status .icon { + flex: 0 0 auto; + width: 22px; + height: 22px; + margin-top: 1px; +} + +.pair-status-ok { + border-color: color-mix(in srgb, var(--ch-signal, var(--primary-color)) 55%, transparent); + background: color-mix(in srgb, var(--ch-signal, var(--primary-color)) 12%, transparent); +} +.pair-status-ok .icon { color: var(--ch-signal, var(--primary-color)); } + +.pair-status-warn { + border-color: color-mix(in srgb, var(--ch-amber, #d99a00) 55%, transparent); + background: color-mix(in srgb, var(--ch-amber, #d99a00) 12%, transparent); +} +.pair-status-warn .icon { color: var(--ch-amber, #d99a00); } + +.pair-status-err { + border-color: color-mix(in srgb, var(--ch-coral, var(--danger-color)) 55%, transparent); + background: color-mix(in srgb, var(--ch-coral, var(--danger-color)) 12%, transparent); +} +.pair-status-err .icon { color: var(--ch-coral, var(--danger-color)); } + +@media (prefers-reduced-motion: reduce) { + .pair-pulse, + .pair-state { animation: none; } + .pair-ring-fg { transition: none; } +} + diff --git a/server/src/ledgrab/static/js/features/pairing-flow.ts b/server/src/ledgrab/static/js/features/pairing-flow.ts new file mode 100644 index 0000000..891dd53 --- /dev/null +++ b/server/src/ledgrab/static/js/features/pairing-flow.ts @@ -0,0 +1,333 @@ +/** + * Reusable pairing-flow controller — opens the `#pair-device-modal`, + * drives its state transitions, POSTs to `/devices/pair`, and resolves + * with the provider-returned fields so a caller can merge them into a + * device-create payload. + * + * The module is driver-agnostic. Future drivers call + * `runPairingFlow({deviceType, url})` and consume the returned `fields` + * directly — the flow knows nothing about Nanoleaf, Tuya, Twinkly, etc. + * + * Backend contract: + * POST /api/v1/devices/pair { device_type, url } + * 200 → { fields: {...} } — success + * 409 → device not ready / window timed out — retryable + * 400 / 422 / 502 → terminal failure with error detail + */ + +import { fetchWithAuth, ApiError } from '../core/api.ts'; +import { t } from '../core/i18n.ts'; +import { Modal } from '../core/modal.ts'; + +/** Length of the visual pairing window in seconds. Most consumer IoT + * devices open a 30s window after the user presses the pairing button; + * the ring fills from 0 → full over this period purely as a UI hint — + * the actual handshake duration is dictated by the backend, not this + * timer. */ +const PAIRING_WINDOW_SECONDS = 30; + +/** Tiny pause after a successful pair so the user sees the confirmation + * before the modal disappears. */ +const SUCCESS_DISMISS_DELAY_MS = 450; + +export interface PairingFlowOptions { + /** Device type slug, matched to backend driver registry (e.g. 'nanoleaf'). */ + deviceType: string; + /** Pairing URL — driver-specific scheme accepted (e.g. 'nanoleaf://10.0.0.5'). */ + url: string; + /** Override the instructions i18n key. Defaults to + * `device.${deviceType}.pair.instructions`, with fallback to + * `pairing.instructions.default` when the type-specific key is missing. */ + instructionsKey?: string; +} + +export interface PairingFlowResult { + /** Fields returned by the provider, ready to merge into the + * device-create payload (token, client key, group id, …). */ + fields: Record; +} + +/** Sentinel thrown when the user dismisses the modal (cancel / close / + * backdrop / Esc). Callers should treat this as a soft cancel — not + * an error to surface. */ +export class PairingCancelled extends Error { + constructor() { + super('Pairing cancelled by user'); + this.name = 'PairingCancelled'; + } +} + +type PairState = 'idle' | 'pairing' | 'notready' | 'success' | 'failed'; + +interface RunCtx { + modal: PairModal; + opts: PairingFlowOptions; + resolve: (value: PairingFlowResult) => void; + reject: (err: unknown) => void; + /** AbortController for an in-flight pair request, used by Cancel. */ + abort: AbortController | null; + /** RequestAnimationFrame/interval handle for the countdown ring. */ + countdownTimer: number | null; + /** True once we've resolved or rejected — guards double-finalize. */ + settled: boolean; +} + +class PairModal extends Modal { + constructor() { super('pair-device-modal'); } +} + +let _modal: PairModal | null = null; +let _ctx: RunCtx | null = null; + +/** Lazy single-instance modal so we don't bind listeners until first use. */ +function _getModal(): PairModal { + if (!_modal) _modal = new PairModal(); + return _modal; +} + +function _byId(id: string): T | null { + return document.getElementById(id) as T | null; +} + +/** Set the modal's `[data-pair-state]` attribute and toggle child blocks. */ +function _setState(state: PairState): void { + const root = document.querySelector('#pair-device-modal .pair-states') as HTMLElement | null; + if (!root) return; + root.setAttribute('data-pair-state', state); + const blocks = root.querySelectorAll('[data-pair-state-block]'); + blocks.forEach(b => { + const isActive = b.getAttribute('data-pair-state-block') === state; + b.style.display = isActive ? '' : 'none'; + }); +} + +/** Apply the type-specific (or fallback) instruction text. */ +function _applyInstructions(opts: PairingFlowOptions): void { + const el = _byId('pair-device-instructions'); + if (!el) return; + const specificKey = opts.instructionsKey ?? `device.${opts.deviceType}.pair.instructions`; + const fallbackKey = 'pairing.instructions.default'; + // If the i18n helper returns the key unchanged it means the key is missing — + // fall back to the generic default so the user always sees real copy. + const specific = t(specificKey); + el.textContent = specific === specificKey ? t(fallbackKey) : specific; + // Keep the data-i18n attribute pointing at whatever key we ended up + // showing so `updateAllText` (triggered on language change) refreshes it. + el.setAttribute('data-i18n', specific === specificKey ? fallbackKey : specificKey); +} + +/** Start the visual countdown ring. Purely cosmetic — the actual fetch + * has its own deadline. */ +function _startCountdown(ctx: RunCtx): void { + const ring = document.querySelector('#pair-device-modal .pair-ring-fg') as SVGCircleElement | null; + const countEl = _byId('pair-countdown'); + if (!ring || !countEl) return; + + const totalMs = PAIRING_WINDOW_SECONDS * 1000; + const startedAt = performance.now(); + + // pathLength=100, so stroke-dasharray "X 100" fills X% of the circumference. + ring.style.strokeDasharray = '0 100'; + countEl.textContent = String(PAIRING_WINDOW_SECONDS); + + const tick = () => { + if (ctx.settled) return; + const elapsed = performance.now() - startedAt; + const ratio = Math.min(1, elapsed / totalMs); + ring.style.strokeDasharray = `${(ratio * 100).toFixed(2)} 100`; + const remaining = Math.max(0, Math.ceil((totalMs - elapsed) / 1000)); + countEl.textContent = String(remaining); + if (ratio < 1) { + ctx.countdownTimer = requestAnimationFrame(tick); + } else { + ctx.countdownTimer = null; + } + }; + ctx.countdownTimer = requestAnimationFrame(tick); +} + +function _stopCountdown(ctx: RunCtx): void { + if (ctx.countdownTimer !== null) { + cancelAnimationFrame(ctx.countdownTimer); + ctx.countdownTimer = null; + } +} + +/** Fire the POST and dispatch to the appropriate post-response state. */ +async function _attemptPair(ctx: RunCtx): Promise { + if (ctx.settled) return; + _setState('pairing'); + _startCountdown(ctx); + + ctx.abort = new AbortController(); + try { + const resp = await fetchWithAuth('/devices/pair', { + method: 'POST', + body: JSON.stringify({ + device_type: ctx.opts.deviceType, + url: ctx.opts.url, + }), + signal: ctx.abort.signal, + // The pairing window itself can be ~30s; allow a little headroom. + timeout: 45_000, + // Don't retry — pairing isn't idempotent and 5xx during a handshake + // means the device side is unhappy. Surface immediately. + retry: false, + }); + _stopCountdown(ctx); + ctx.abort = null; + await _handleResponse(ctx, resp); + } catch (err: unknown) { + _stopCountdown(ctx); + ctx.abort = null; + if (ctx.settled) return; + // AbortError surfaces when Cancel was clicked — settled was already + // set in the cancel handler; nothing more to do. + if ((err as { name?: string })?.name === 'AbortError') return; + if (err instanceof ApiError && err.isAuth) { + // The api layer already opened the login flow; just reject so + // callers don't hang. + _finalize(ctx, () => ctx.reject(err)); + return; + } + const detail = err instanceof Error ? err.message : t('api.error.network'); + _showFailure(detail); + } +} + +async function _handleResponse(ctx: RunCtx, resp: Response): Promise { + if (resp.status === 200) { + let parsed: { fields?: Record } = {}; + try { parsed = await resp.json() as { fields?: Record }; } + catch { /* fall through with empty fields */ } + const fields = parsed.fields ?? {}; + _setState('success'); + // Brief confirmation before dismissing, so the user gets feedback. + window.setTimeout(() => { + _finalize(ctx, () => { + ctx.modal.forceClose(); + ctx.resolve({ fields }); + }); + }, SUCCESS_DISMISS_DELAY_MS); + return; + } + + if (resp.status === 409) { + _setState('notready'); + return; + } + + // 400 / 422 / 502 / any other non-2xx → terminal failure. + let detail = ''; + try { + const body = await resp.json() as { detail?: string }; + if (typeof body?.detail === 'string') detail = body.detail; + } catch { /* no JSON body */ } + _showFailure(detail || `${resp.status} ${resp.statusText}`); +} + +function _showFailure(detail: string): void { + const detailEl = _byId('pair-failure-detail'); + if (detailEl) { + // Render localized prefix + raw detail. The i18n helper supports + // {detail} interpolation, so we use the templated form when available + // and fall back to "Pairing failed: " assembled manually. + const templated = t('pairing.failed', { detail }); + // If the helper returned the key unchanged it means the locale file + // doesn't carry the key — assemble manually as a safety net. + if (templated === 'pairing.failed' || templated.includes('{detail}')) { + detailEl.textContent = `${t('pairing.failed_prefix')} ${detail}`.trim(); + } else { + detailEl.textContent = templated; + } + } + _setState('failed'); +} + +function _finalize(ctx: RunCtx, work: () => void): void { + if (ctx.settled) return; + ctx.settled = true; + _stopCountdown(ctx); + if (ctx.abort) { ctx.abort.abort(); ctx.abort = null; } + _detachHandlers(); + _ctx = null; + work(); +} + +// ── Event-handler refs (kept so we can detach on close) ────────────── + +let _onStart: (() => void) | null = null; +let _onRetry: (() => void) | null = null; +let _onCloseTerminal: (() => void) | null = null; +let _onCancel: (() => void) | null = null; +let _onCloseBtn: (() => void) | null = null; + +function _attachHandlers(ctx: RunCtx): void { + _onStart = () => { if (!ctx.settled) void _attemptPair(ctx); }; + _onRetry = () => { if (!ctx.settled) void _attemptPair(ctx); }; + const cancelAll = () => { + _finalize(ctx, () => { + ctx.modal.forceClose(); + ctx.reject(new PairingCancelled()); + }); + }; + _onCancel = cancelAll; + _onCloseTerminal = cancelAll; + _onCloseBtn = cancelAll; + + _byId('pair-start-btn')?.addEventListener('click', _onStart); + _byId('pair-retry-btn')?.addEventListener('click', _onRetry); + _byId('pair-close-btn')?.addEventListener('click', _onCloseTerminal); + _byId('pair-cancel-btn')?.addEventListener('click', _onCancel); + _byId('pair-device-close-btn')?.addEventListener('click', _onCloseBtn); +} + +function _detachHandlers(): void { + if (_onStart) _byId('pair-start-btn')?.removeEventListener('click', _onStart); + if (_onRetry) _byId('pair-retry-btn')?.removeEventListener('click', _onRetry); + if (_onCloseTerminal) _byId('pair-close-btn')?.removeEventListener('click', _onCloseTerminal); + if (_onCancel) _byId('pair-cancel-btn')?.removeEventListener('click', _onCancel); + if (_onCloseBtn) _byId('pair-device-close-btn')?.removeEventListener('click', _onCloseBtn); + _onStart = _onRetry = _onCloseTerminal = _onCancel = _onCloseBtn = null; +} + +/** + * Open the pair modal, run the pairing handshake on user gesture, and + * resolve with the provider-returned `fields`. Rejects with + * {@link PairingCancelled} on user dismiss, or with the underlying error + * for terminal failures. + * + * Only one pairing flow can be active at a time — calling this while + * another is in flight rejects the previous one as cancelled. + */ +export function runPairingFlow(opts: PairingFlowOptions): Promise { + // If another flow is mid-run, soft-cancel it. The caller of the + // previous run will see a PairingCancelled rejection, matching what + // happens when the user clicks Cancel. + if (_ctx && !_ctx.settled) { + const prev = _ctx; + _finalize(prev, () => { + prev.modal.forceClose(); + prev.reject(new PairingCancelled()); + }); + } + + return new Promise((resolve, reject) => { + const modal = _getModal(); + _applyInstructions(opts); + _setState('idle'); + + const ctx: RunCtx = { + modal, + opts, + resolve, + reject, + abort: null, + countdownTimer: null, + settled: false, + }; + _ctx = ctx; + _attachHandlers(ctx); + modal.open(); + }); +} diff --git a/server/src/ledgrab/static/locales/en.json b/server/src/ledgrab/static/locales/en.json index 86007f6..a36ded5 100644 --- a/server/src/ledgrab/static/locales/en.json +++ b/server/src/ledgrab/static/locales/en.json @@ -2939,5 +2939,16 @@ "streams.group.audio_processing": "Audio Processing", "section.empty.audio_processing_templates": "No audio processing templates yet. Click + to create one.", "audio_source.group.capture": "Capture Sources", - "audio_source.group.processed": "Processed Sources" + "audio_source.group.processed": "Processed Sources", + "pairing.title": "Pair Device", + "pairing.instructions.default": "Press and hold the pairing button on your device, then click Start. Devices typically open a 30-second pairing window — be ready to act quickly.", + "pairing.start": "Start pairing", + "pairing.pairing": "Pairing…", + "pairing.cancel": "Cancel", + "pairing.retry": "Try again", + "pairing.close": "Close", + "pairing.success": "Paired successfully", + "pairing.not_ready": "Device didn't respond. Press the pairing button on your device, then try again.", + "pairing.failed": "Pairing failed: {detail}", + "pairing.failed_prefix": "Pairing failed:" } diff --git a/server/src/ledgrab/static/locales/ru.json b/server/src/ledgrab/static/locales/ru.json index 1999429..33792fe 100644 --- a/server/src/ledgrab/static/locales/ru.json +++ b/server/src/ledgrab/static/locales/ru.json @@ -2619,5 +2619,16 @@ "streams.group.audio_processing": "Обработка звука", "section.empty.audio_processing_templates": "Пока нет шаблонов обработки звука. Нажмите +, чтобы создать.", "audio_source.group.capture": "Захват звука", - "audio_source.group.processed": "Обработанные источники" + "audio_source.group.processed": "Обработанные источники", + "pairing.title": "Сопряжение устройства", + "pairing.instructions.default": "Нажмите и удерживайте кнопку сопряжения на устройстве, затем нажмите «Начать». Устройства обычно открывают окно сопряжения на 30 секунд — действуйте быстро.", + "pairing.start": "Начать сопряжение", + "pairing.pairing": "Сопряжение…", + "pairing.cancel": "Отмена", + "pairing.retry": "Повторить", + "pairing.close": "Закрыть", + "pairing.success": "Успешно сопряжено", + "pairing.not_ready": "Устройство не ответило. Нажмите кнопку сопряжения на устройстве и попробуйте снова.", + "pairing.failed": "Сопряжение не удалось: {detail}", + "pairing.failed_prefix": "Сопряжение не удалось:" } diff --git a/server/src/ledgrab/static/locales/zh.json b/server/src/ledgrab/static/locales/zh.json index cd07b8e..19b27c6 100644 --- a/server/src/ledgrab/static/locales/zh.json +++ b/server/src/ledgrab/static/locales/zh.json @@ -2614,5 +2614,16 @@ "streams.group.audio_processing": "音频处理", "section.empty.audio_processing_templates": "暂无音频处理模板。点击 + 创建一个。", "audio_source.group.capture": "音频捕获", - "audio_source.group.processed": "已处理的源" + "audio_source.group.processed": "已处理的源", + "pairing.title": "配对设备", + "pairing.instructions.default": "请按住设备上的配对按钮,然后点击「开始」。设备通常会打开 30 秒的配对窗口——请准备好快速操作。", + "pairing.start": "开始配对", + "pairing.pairing": "配对中…", + "pairing.cancel": "取消", + "pairing.retry": "重试", + "pairing.close": "关闭", + "pairing.success": "配对成功", + "pairing.not_ready": "设备未响应。请按下设备上的配对按钮后重试。", + "pairing.failed": "配对失败:{detail}", + "pairing.failed_prefix": "配对失败:" } diff --git a/server/src/ledgrab/templates/index.html b/server/src/ledgrab/templates/index.html index cbe0065..63a6821 100644 --- a/server/src/ledgrab/templates/index.html +++ b/server/src/ledgrab/templates/index.html @@ -236,6 +236,7 @@ {% include 'modals/setup-required.html' %} {% include 'modals/confirm.html' %} {% include 'modals/add-device.html' %} + {% include 'modals/pair-device.html' %} {% include 'modals/capture-template.html' %} {% include 'modals/test-template.html' %} {% include 'modals/test-stream.html' %} diff --git a/server/src/ledgrab/templates/modals/pair-device.html b/server/src/ledgrab/templates/modals/pair-device.html new file mode 100644 index 0000000..ce45042 --- /dev/null +++ b/server/src/ledgrab/templates/modals/pair-device.html @@ -0,0 +1,86 @@ + + diff --git a/server/tests/api/routes/test_devices_routes.py b/server/tests/api/routes/test_devices_routes.py index 801bc6f..1b59957 100644 --- a/server/tests/api/routes/test_devices_routes.py +++ b/server/tests/api/routes/test_devices_routes.py @@ -203,3 +203,140 @@ class TestBatchStates: resp = client.get("/api/v1/devices/batch/states") assert resp.status_code == 200 assert "states" in resp.json() + + +# --------------------------------------------------------------------------- +# PAIRING +# --------------------------------------------------------------------------- + + +class _PairableProviderStub: + """Test double that exercises the four pair_device outcomes. + + Registered into the provider registry at test-time and unregistered + afterwards so the global registry stays clean across tests. + """ + + def __init__(self, outcome: str): + self._outcome = outcome + + @property + def device_type(self) -> str: + return "_pair_test" + + @property + def capabilities(self) -> set: + return {"requires_pairing"} + + def create_client(self, config, *, deps): # pragma: no cover -- not used here + raise AssertionError("Stub provider should not be asked to create a client") + + async def check_health(self, url, http_client, prev_health=None): # pragma: no cover + raise AssertionError("Stub provider should not be asked for health") + + async def validate_device(self, url): # pragma: no cover + return {} + + async def pair_device(self, url: str): + from ledgrab.core.devices.led_client import PairingNotReady + + if self._outcome == "success": + return {"_pair_test_token": "token-abc", "_pair_test_meta": 42} + if self._outcome == "not_ready": + raise PairingNotReady("Press the device button and try again.") + if self._outcome == "invalid_url": + raise ValueError("URL is missing a host") + if self._outcome == "boom": + raise RuntimeError("transport blew up") + if self._outcome == "malformed": + return "not-a-dict" # type: ignore[return-value] + if self._outcome == "not_implemented": + raise NotImplementedError("paired? what is paired?") + raise AssertionError(f"unknown outcome: {self._outcome}") + + +@pytest.fixture +def pair_stub_registered(): + """Register a test provider for the duration of one test.""" + from ledgrab.core.devices import led_client as _led_client + + registered: dict = {} + + def _register(outcome: str): + provider = _PairableProviderStub(outcome) + _led_client.register_provider(provider) # type: ignore[arg-type] + registered["type"] = provider.device_type + return provider + + yield _register + + if "type" in registered: + _led_client._provider_registry.pop(registered["type"], None) + + +class TestPairDevice: + def test_returns_provider_fields_on_success(self, client, pair_stub_registered): + pair_stub_registered("success") + resp = client.post( + "/api/v1/devices/pair", + json={"device_type": "_pair_test", "url": "test://host"}, + ) + assert resp.status_code == 200, resp.text + assert resp.json() == {"fields": {"_pair_test_token": "token-abc", "_pair_test_meta": 42}} + + def test_unknown_device_type_returns_400(self, client): + resp = client.post( + "/api/v1/devices/pair", + json={"device_type": "nonexistent_zzz", "url": "x://y"}, + ) + assert resp.status_code == 400 + assert "unknown device type" in resp.json()["detail"].lower() + + def test_not_implemented_returns_400(self, client, pair_stub_registered): + pair_stub_registered("not_implemented") + resp = client.post( + "/api/v1/devices/pair", + json={"device_type": "_pair_test", "url": "test://host"}, + ) + assert resp.status_code == 400 + assert "does not support pairing" in resp.json()["detail"] + + def test_pairing_not_ready_returns_409(self, client, pair_stub_registered): + pair_stub_registered("not_ready") + resp = client.post( + "/api/v1/devices/pair", + json={"device_type": "_pair_test", "url": "test://host"}, + ) + assert resp.status_code == 409 + assert "press" in resp.json()["detail"].lower() + + def test_invalid_url_returns_422(self, client, pair_stub_registered): + pair_stub_registered("invalid_url") + resp = client.post( + "/api/v1/devices/pair", + json={"device_type": "_pair_test", "url": "test://host"}, + ) + assert resp.status_code == 422 + assert "host" in resp.json()["detail"] + + def test_transport_exception_returns_502(self, client, pair_stub_registered): + pair_stub_registered("boom") + resp = client.post( + "/api/v1/devices/pair", + json={"device_type": "_pair_test", "url": "test://host"}, + ) + assert resp.status_code == 502 + assert "pairing failed" in resp.json()["detail"].lower() + + def test_malformed_provider_result_returns_500(self, client, pair_stub_registered): + pair_stub_registered("malformed") + resp = client.post( + "/api/v1/devices/pair", + json={"device_type": "_pair_test", "url": "test://host"}, + ) + assert resp.status_code == 500 + assert "malformed" in resp.json()["detail"].lower() + + def test_missing_required_fields_returns_422(self, client): + resp = client.post("/api/v1/devices/pair", json={"device_type": "nanoleaf"}) + assert resp.status_code == 422