From 223f41dcbea65fc3853b0653bb21e8a8463639df Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:03:16 -0500 Subject: [PATCH] fix(web): stabilize device streaming, recording handoff, and panel lifecycle Fixes client-runtime device transport and streaming issues (idle iOS 16-second reconnect loop, Android WebCodecs fallback and initial keyframe buffering, split CRLF SSE parsing, Android accessibility cap ordering, and transport error/close handling) along with web Device tab lifecycle, Android AVD boot selection, floating window coordinates, recording handoff preservation, and UI polish. --- .../web/src/components/device/DeviceChips.tsx | 5 +- .../device/DeviceFloatingWindow.tsx | 21 +- .../components/device/DevicePanel.browser.tsx | 37 ++++ .../web/src/components/device/DevicePanel.tsx | 26 ++- .../src/components/device/DevicePicker.tsx | 37 +++- .../components/device/DeviceStreamView.tsx | 141 ++++++++++--- .../components/device/DeviceToolsPanel.tsx | 22 +- .../src/components/device/DeviceWorkspace.tsx | 44 +++- .../device/deviceFloatLayout.test.ts | 11 + .../components/device/deviceFloatLayout.ts | 5 +- .../components/device/deviceInputObserver.ts | 10 +- .../src/components/device/deviceRecorder.ts | 95 ++++++--- .../device/deviceRecordingHandoff.browser.tsx | 24 +++ .../device/deviceRecordingHandoff.ts | 12 +- apps/web/src/components/device/deviceState.ts | 19 +- .../src/components/device/useAndroidFold.ts | 43 +++- .../device/useDeviceAccessibility.ts | 4 +- .../components/device/useDeviceControls.ts | 8 +- .../components/device/useDeviceRecording.ts | 2 +- .../components/settings/DevicesSettings.tsx | 6 +- .../composerDraftAttachmentSave.browser.tsx | 20 ++ apps/web/src/composerDraftAttachmentSave.ts | 93 ++++++--- .../routes/_chat.$environmentId.$threadId.tsx | 5 +- .../src/device/accessibility.test.ts | 42 +++- .../src/device/accessibility.ts | 40 ++-- .../client-runtime/src/device/appState.ts | 30 ++- .../client-runtime/src/device/duoControl.ts | 8 +- .../src/device/eventLog.test.ts | 5 + .../client-runtime/src/device/eventLog.ts | 34 +++- packages/client-runtime/src/device/fold.ts | 7 +- packages/client-runtime/src/device/frame.ts | 4 +- .../src/device/hubTransport.test.ts | 60 ++++++ .../client-runtime/src/device/hubTransport.ts | 58 +++++- packages/client-runtime/src/device/mjpeg.ts | 16 +- .../client-runtime/src/device/screenshot.ts | 6 + .../client-runtime/src/device/stream.test.ts | 192 ++++++++++++++++++ packages/client-runtime/src/device/stream.ts | 150 ++++++++++---- 37 files changed, 1103 insertions(+), 239 deletions(-) diff --git a/apps/web/src/components/device/DeviceChips.tsx b/apps/web/src/components/device/DeviceChips.tsx index e48055bff..ca3036dca 100644 --- a/apps/web/src/components/device/DeviceChips.tsx +++ b/apps/web/src/components/device/DeviceChips.tsx @@ -87,8 +87,9 @@ export function DeviceChips(props: { aria-label={`${chip.name} menu`} className={cn( "flex h-full w-5 shrink-0 items-center justify-center rounded-md focus-ring", - // Always there on the shown chip and on touch; on hover elsewhere. - !selected && "can-hover:opacity-0 can-hover:group-hover/chip:opacity-100", + // Always there on the shown chip, keyboard focus, and touch; on hover elsewhere. + !selected && + "can-hover:opacity-0 can-hover:group-hover/chip:opacity-100 can-hover:focus-visible:opacity-100", )} /> } diff --git a/apps/web/src/components/device/DeviceFloatingWindow.tsx b/apps/web/src/components/device/DeviceFloatingWindow.tsx index 6ef676b69..a18872761 100644 --- a/apps/web/src/components/device/DeviceFloatingWindow.tsx +++ b/apps/web/src/components/device/DeviceFloatingWindow.tsx @@ -100,7 +100,7 @@ export function DeviceFloatingWindow(props: { {float && device && column ? createPortal( (null); + const liveRef = useRef(null); const rect = live ?? fitDeviceFloat({ @@ -192,11 +193,12 @@ function FloatingDevice(props: { if (!held || held.gesture.pointerId !== event.pointerId) return; const dx = event.clientX - held.gesture.x; const dy = event.clientY - held.gesture.y; - setLive( + const nextRect = held.gesture.kind === "drag" ? dragDeviceFloat(held.start, dx, dy, aspect, viewport) - : resizeDeviceFloat(held.start, held.gesture.edge, dx, dy, aspect, viewport), - ); + : resizeDeviceFloat(held.start, held.gesture.edge, dx, dy, aspect, viewport); + liveRef.current = nextRect; + setLive(nextRect); }; const end = (event: PointerEvent) => { const held = gesture.current; @@ -205,10 +207,12 @@ function FloatingDevice(props: { if (event.currentTarget.hasPointerCapture(event.pointerId)) { event.currentTarget.releasePointerCapture(event.pointerId); } - if (live) { + const settled = liveRef.current; + liveRef.current = null; + if (settled) { placeDeviceFloat(threadKey, device.id, { - position: { x: live.x, y: live.y }, - width: live.width, + position: { x: settled.x, y: settled.y }, + width: settled.width, }); } setLive(null); @@ -275,6 +279,9 @@ function FloatingDevice(props: { deviceDescription={device.version} stream={stream} state={state} + deviceId={device.id} + model={device.model} + physical={device.physical} /> {EDGES.map(({ edge, className }) => ( diff --git a/apps/web/src/components/device/DevicePanel.browser.tsx b/apps/web/src/components/device/DevicePanel.browser.tsx index d02f1733d..ee292db0d 100644 --- a/apps/web/src/components/device/DevicePanel.browser.tsx +++ b/apps/web/src/components/device/DevicePanel.browser.tsx @@ -598,4 +598,41 @@ describe("DevicePanel", () => { computer.channels.filter((channel) => channel.input.path === "/vendor/serve-sim/helper/ws"), ).toHaveLength(1); }); + + it("selects the booted serial when an Android AVD boots, hides Shake on Android, and reopens setup from the picker", async () => { + const AVD = { + id: "Pixel_9_API_35", + platform: "android", + name: "Pixel 9", + version: "Android 16", + booted: false, + physical: false, + } as const; + const computer = fakeComputer(deviceState({ devices: [AVD] })); + computer.device.open.mockImplementationOnce(async () => session(PIXEL.id, "android", "user")); + await render(); + + // Picker gear icon reopens setup and Done returns to the picker. + await page.getByRole("button", { name: "Device settings" }).click(); + await expect.element(page.getByRole("heading", { name: "Set up devices" })).toBeVisible(); + await page.getByRole("button", { name: "Done" }).click(); + await expect.element(page.getByTestId("device-picker")).toBeVisible(); + + // Booting an AVD whose open returns its booted emulator serial selects that serial. + await page.getByRole("button", { name: "Start Pixel 9" }).click(); + computer.push( + deviceState({ + devices: [PIXEL], + sessions: [session(PIXEL.id, "android", "user")], + revision: 2, + }), + ); + await expect.element(page.getByRole("toolbar", { name: "Device controls" })).toBeVisible(); + expect(readThreadDeviceViews(THREAD_KEY).selected).toBe(PIXEL.id); + + // Android Tools hides the iOS-only Shake button. + await page.getByRole("button", { name: "Tools" }).click(); + await expect.element(page.getByRole("button", { name: "Close tools" })).toBeVisible(); + await expect.element(page.getByRole("button", { name: "Shake" })).not.toBeInTheDocument(); + }); }); diff --git a/apps/web/src/components/device/DevicePanel.tsx b/apps/web/src/components/device/DevicePanel.tsx index 186c18175..8910df81e 100644 --- a/apps/web/src/components/device/DevicePanel.tsx +++ b/apps/web/src/components/device/DevicePanel.tsx @@ -64,12 +64,16 @@ export function DevicePanel(props: { const [error, setError] = useState(null); // Devices on and nothing started yet: list them, which starts the hub. Once - // per panel, and only while the tab is on screen. + // per enable cycle, and only while the tab is on screen. const listed = useRef(false); const enabled = state?.enabled === true; const idle = state?.hostStatus === "idle"; useEffect(() => { - if (!visible || !enabled || !idle || listed.current) return; + if (!enabled) { + listed.current = false; + return; + } + if (!visible || !idle || listed.current) return; listed.current = true; refreshDevices(environmentId).catch((cause: unknown) => setError(deviceErrorText(cause))); }, [enabled, environmentId, idle, visible]); @@ -130,14 +134,21 @@ export function DevicePanel(props: { } setPending(device.id); void run(async () => { - await openDevice(environmentId, { threadId, deviceId: device.id, platform: device.platform }); - selectThreadDevice(threadKey, device.id); + // Android AVDs change id when they boot (AVD name → emulator serial), so use the returned session. + const session = await openDevice(environmentId, { + threadId, + deviceId: device.id, + platform: device.platform, + }); + selectThreadDevice(threadKey, session.deviceId); }).finally(() => setPending(null)); }; const close = (deviceId: string, shutdown: boolean) => { - removeDeviceChip(threadKey, deviceId, sessions); - void run(() => closeDevice(environmentId, { threadId, deviceId, shutdown })); + void run(async () => { + await closeDevice(environmentId, { threadId, deviceId, shutdown }); + removeDeviceChip(threadKey, deviceId, sessions); + }); }; const errorLine = error ? ( @@ -229,7 +240,7 @@ export function DevicePanel(props: { /> ) : ( refreshDevices(environmentId)).finally(() => setRefreshing(false)); }} + onOpenSetup={() => setInSetup(true)} /> )} diff --git a/apps/web/src/components/device/DevicePicker.tsx b/apps/web/src/components/device/DevicePicker.tsx index 781e4f04c..1b5a043aa 100644 --- a/apps/web/src/components/device/DevicePicker.tsx +++ b/apps/web/src/components/device/DevicePicker.tsx @@ -4,7 +4,7 @@ import { groupDevicesByPlatform, isDeviceHostBusy, } from "@threadlines/client-runtime/deviceState"; -import { PowerIcon, RefreshCwIcon, SmartphoneIcon } from "lucide-react"; +import { PowerIcon, RefreshCwIcon, SettingsIcon, SmartphoneIcon } from "lucide-react"; import { cn } from "~/lib/utils"; import { SETTINGS_GROUP_ROW_CLASS, SettingsGroup } from "../settings/settingsLayout"; @@ -26,6 +26,8 @@ export function DevicePicker(props: { readonly onOpen: (device: DeviceSummary) => void; readonly onPowerOff: (device: DeviceSummary) => void; readonly onRefresh: () => void; + /** Reopens this computer's device setup (closes the one-way door on linked computers / phone). */ + readonly onOpenSetup?: () => void; }) { const { state } = props; const groups = groupDevicesByPlatform(state.devices); @@ -53,16 +55,29 @@ export function DevicePicker(props: { ? "1 device" : `${state.devices.length} devices`} - +
+ + {props.onOpenSetup ? ( + + ) : null} +
{state.hostStatus !== "ready" && state.hostStatus !== "idle" ? ( diff --git a/apps/web/src/components/device/DeviceStreamView.tsx b/apps/web/src/components/device/DeviceStreamView.tsx index 9560eeb3a..4dffbb0c4 100644 --- a/apps/web/src/components/device/DeviceStreamView.tsx +++ b/apps/web/src/components/device/DeviceStreamView.tsx @@ -4,7 +4,14 @@ import { deviceAxElementAt, type DuoPanelId, } from "@threadlines/client-runtime/device"; -import { type CSSProperties, type PointerEvent, useEffect, useRef, useState } from "react"; +import { + type CSSProperties, + type PointerEvent, + useCallback, + useEffect, + useRef, + useState, +} from "react"; import { cn } from "~/lib/utils"; import { Button } from "../ui/button"; @@ -43,6 +50,8 @@ type ActivePointer = { readonly id: number; x: number; y: number; + /** Visual 0..1 coords on the active screen, for recording Duo gestures. */ + visual?: { readonly x: number; readonly y: number }; /** iPhone Duo: the display the gesture started on. */ readonly panel?: DuoPanelId; }; @@ -85,7 +94,7 @@ export function DeviceStreamView(props: { // Reads beside the stream (fold, accessibility) run only while it is on screen. const live = streaming && state.active; const [host, setHost] = useState({ width: 0, height: 0 }); - const hostRef = (element: HTMLDivElement | null) => { + const hostRef = useCallback((element: HTMLDivElement | null) => { if (!element) return; const update = () => { const rect = element.getBoundingClientRect(); @@ -99,12 +108,31 @@ export function DeviceStreamView(props: { const observer = new ResizeObserver(update); observer.observe(element); return () => observer.disconnect(); - }; - const mount = (canvas: HTMLCanvasElement) => (node: HTMLDivElement | null) => { - if (!node) return; - node.append(canvas); - return () => canvas.remove(); - }; + }, []); + const mountMainCanvas = useCallback( + (node: HTMLDivElement | null) => { + if (!node) return; + node.append(stream.canvas); + return () => stream.canvas.remove(); + }, + [stream.canvas], + ); + const mountCoverCanvas = useCallback( + (node: HTMLDivElement | null) => { + if (!node) return; + node.append(stream.panelCanvases.cover); + return () => stream.panelCanvases.cover.remove(); + }, + [stream.panelCanvases.cover], + ); + const mountInnerCanvas = useCallback( + (node: HTMLDivElement | null) => { + if (!node) return; + node.append(stream.panelCanvases.inner); + return () => stream.panelCanvases.inner.remove(); + }, + [stream.panelCanvases.inner], + ); // Android foldables: the fold controls, and the frame follows the posture. const fold = useAndroidFold({ @@ -145,6 +173,12 @@ export function DeviceStreamView(props: { readonly tapped: boolean; } | null>(null); const axShown = props.axOverlay === true; + const [prevAxShown, setPrevAxShown] = useState(axShown); + if (prevAxShown !== axShown) { + setPrevAxShown(axShown); + if (!axShown && axFocus !== null) setAxFocus(null); + } + const heldKeys = useRef(new Map()); // Lay the drawing out: where it sits, how it turns, and the screen as the user sees it. const drawing = (() => { @@ -224,6 +258,7 @@ export function DeviceStreamView(props: { /** 0..1 of the screen the user sees, for the plain and single frames and the overlay. */ const screenPoint = (event: PointerEvent) => { const rect = event.currentTarget.getBoundingClientRect(); + if (rect.width <= 0 || rect.height <= 0) return null; const x = (event.clientX - rect.left) / rect.width; const y = (event.clientY - rect.top) / rect.height; return { x: Math.min(1, Math.max(0, x)), y: Math.min(1, Math.max(0, y)) }; @@ -231,17 +266,24 @@ export function DeviceStreamView(props: { /** A point in the Duo drawing's points, from the stage the layer covers. */ const duoPoint = (event: PointerEvent) => { const rect = event.currentTarget.getBoundingClientRect(); - const scale = drawing.kind === "duo" ? drawing.fit.scale : 1; + const scale = drawing.kind === "duo" ? drawing.fit.scale : 0; + if (rect.width <= 0 || rect.height <= 0 || scale <= 0) return null; return { x: (event.clientX - rect.left) / scale, y: (event.clientY - rect.top) / scale }; }; - /** The overlay's element under a pointer, in the active screen's fractions. */ - const axElementUnder = (event: PointerEvent) => { + /** Visual 0..1 coords inside the active screen rect (for AX overlay and Duo recording). */ + const visualScreenPoint = (event: PointerEvent) => { const rect = drawing.screenRect; const layer = layerRef.current?.getBoundingClientRect(); - if (!rect || !layer) return null; + if (!rect || !layer || rect.width <= 0 || rect.height <= 0) return undefined; const x = (event.clientX - layer.left - (rect.x - layerOrigin.x)) / rect.width; const y = (event.clientY - layer.top - (rect.y - layerOrigin.y)) / rect.height; - return deviceAxElementAt(accessibility.elements, x, y); + return { x: Math.min(1, Math.max(0, x)), y: Math.min(1, Math.max(0, y)) }; + }; + /** The overlay's element under a pointer, in the active screen's fractions. */ + const axElementUnder = (event: PointerEvent) => { + const point = visualScreenPoint(event); + if (!point) return null; + return deviceAxElementAt(accessibility.elements, point.x, point.y); }; const begin = (event: PointerEvent) => { @@ -255,18 +297,27 @@ export function DeviceStreamView(props: { if (!state.input.connected) return; if (drawing.kind === "duo") { const point = duoPoint(event); + if (!point) return; const hit = duoTouchPoint(drawing.layout, point.x, point.y); // Touches on the display not in front never reach the device. if (!hit?.active) return; + const visual = visualScreenPoint(event); event.currentTarget.setPointerCapture(event.pointerId); - activePointer.current = { id: event.pointerId, x: hit.x, y: hit.y, panel: hit.panel }; - client.sendRawTouch("begin", hit.x, hit.y); + activePointer.current = { + id: event.pointerId, + x: hit.x, + y: hit.y, + ...(visual ? { visual } : {}), + panel: hit.panel, + }; + client.sendRawTouch("begin", hit.x, hit.y, visual); return; } + const point = screenPoint(event); + if (!point) return; event.currentTarget.setPointerCapture(event.pointerId); - const { x, y } = screenPoint(event); - activePointer.current = { id: event.pointerId, x, y }; - client.sendTouch("begin", x, y); + activePointer.current = { id: event.pointerId, x: point.x, y: point.y }; + client.sendTouch("begin", point.x, point.y); }; const move = (event: PointerEvent) => { const pointer = activePointer.current; @@ -277,24 +328,28 @@ export function DeviceStreamView(props: { if (pointer?.id !== event.pointerId) return; if (pointer.panel !== undefined && drawing.kind === "duo") { const point = duoPoint(event); + if (!point) return; // A drag that reaches the other display ends where it left this one: it never continues there. const over = duoTouchPoint(drawing.layout, point.x, point.y); if (over && over.panel !== pointer.panel) { activePointer.current = null; - client.sendRawTouch("end", pointer.x, pointer.y); + client.sendRawTouch("end", pointer.x, pointer.y, pointer.visual); return; } const raw = duoPanelPoint(drawing.layout, pointer.panel, point.x, point.y); if (!raw) return; + const visual = visualScreenPoint(event); pointer.x = raw.x; pointer.y = raw.y; - client.sendRawTouch("move", raw.x, raw.y); + if (visual) pointer.visual = visual; + client.sendRawTouch("move", raw.x, raw.y, visual); return; } - const { x, y } = screenPoint(event); - pointer.x = x; - pointer.y = y; - client.sendTouch("move", x, y); + const point = screenPoint(event); + if (!point) return; + pointer.x = point.x; + pointer.y = point.y; + client.sendTouch("move", point.x, point.y); }; const end = (event: PointerEvent) => { const pointer = activePointer.current; @@ -302,16 +357,18 @@ export function DeviceStreamView(props: { activePointer.current = null; if (pointer.panel !== undefined) { let { x, y } = pointer; + let visual = pointer.visual; if (event.type !== "lostpointercapture" && drawing.kind === "duo") { const point = duoPoint(event); - const raw = duoPanelPoint(drawing.layout, pointer.panel, point.x, point.y); + const raw = point ? duoPanelPoint(drawing.layout, pointer.panel, point.x, point.y) : null; if (raw) ({ x, y } = raw); + visual = visualScreenPoint(event) ?? visual; } - client.sendRawTouch("end", x, y); + client.sendRawTouch("end", x, y, visual); return; } - const { x, y } = event.type === "lostpointercapture" ? pointer : screenPoint(event); - client.sendTouch("end", x, y); + const point = event.type === "lostpointercapture" ? pointer : (screenPoint(event) ?? pointer); + client.sendTouch("end", point.x, point.y); }; const loadingRect = drawing.kind === "duo" ? drawing.fit.box : drawing.screenRect; @@ -358,6 +415,12 @@ export function DeviceStreamView(props: { data-testid="device-screen" onKeyDown={(event) => { if (event.target !== event.currentTarget) return; + // Shift+Escape releases keyboard focus from the device screen (no keyboard trap). + if (event.shiftKey && event.key === "Escape") { + event.preventDefault(); + event.currentTarget.blur(); + return; + } if (event.metaKey) return; // Let paste chords fire the paste event. if ( @@ -367,12 +430,26 @@ export function DeviceStreamView(props: { return; } event.preventDefault(); + if (platform === "ios") heldKeys.current.set(event.code, event.nativeEvent); client.sendKey(event.nativeEvent, "down"); }} onKeyUp={(event) => { if (event.target !== event.currentTarget) return; + const hadKey = heldKeys.current.delete(event.code); + if (event.metaKey && !hadKey) return; + if ( + !hadKey && + ((event.ctrlKey && (event.key === "v" || event.key === "V")) || + (event.shiftKey && event.key === "Insert")) + ) { + return; + } client.sendKey(event.nativeEvent, "up"); }} + onBlur={() => { + for (const key of heldKeys.current.values()) client.sendKey(key, "up"); + heldKeys.current.clear(); + }} onPaste={(event) => { if (event.target !== event.currentTarget) return; event.preventDefault(); @@ -395,7 +472,7 @@ export function DeviceStreamView(props: { style={{ width: drawing.screenBox.width, height: drawing.screenBox.height }} >
)) ) : ( @@ -468,7 +543,7 @@ export function DeviceStreamView(props: { x={0} y={0} canvasTurn={drawing.turns.canvasTurn} - mountCanvas={mount(stream.canvas)} + mountCanvas={mountMainCanvas} /> )}
diff --git a/apps/web/src/components/device/DeviceToolsPanel.tsx b/apps/web/src/components/device/DeviceToolsPanel.tsx index 29cb2822a..5db141e53 100644 --- a/apps/web/src/components/device/DeviceToolsPanel.tsx +++ b/apps/web/src/components/device/DeviceToolsPanel.tsx @@ -162,16 +162,18 @@ export function DeviceToolsPanel(props: { disabled={disabled} onSubmit={(appId) => act({ type: "launchApp", appId })} /> -
- -
+ {ios ? ( +
+ +
+ ) : null}
diff --git a/apps/web/src/components/device/DeviceWorkspace.tsx b/apps/web/src/components/device/DeviceWorkspace.tsx index a19763823..2801aeb4e 100644 --- a/apps/web/src/components/device/DeviceWorkspace.tsx +++ b/apps/web/src/components/device/DeviceWorkspace.tsx @@ -65,7 +65,13 @@ export function DeviceWorkspace(props: { const [axOverlay, setAxOverlay] = useState(false); const [axInspect, setAxInspect] = useState(false); // Read while on screen, not only with Tools open: rotating Android goes through it too. - const controls = useDeviceControls({ environmentId, device, visible }); + // iOS `/foreground` only polls while Tools is open (avoids constant 2s background traffic). + const controls = useDeviceControls({ + environmentId, + device, + visible, + pollForeground: toolsOpen, + }); const recording = useDeviceRecording({ threadKey: props.threadKey, threadRef: props.threadRef, @@ -87,6 +93,7 @@ export function DeviceWorkspace(props: { const [notice, setNotice] = useState(null); // A capture always finishes, even if the panel hides meanwhile; the user asked for it. const capturing = useRef(false); + const composing = useRef(false); const inputReady = state.input.connected; // A touch screen has no hardware keys to send: the Keyboard button raises the @@ -269,16 +276,37 @@ export function DeviceWorkspace(props: {