@devries-cameron20 / t3code-1 / commits / 8ae53fd4db
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(web): keep device results in the thread that started them (#16040)

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Co-authored-by: SAPHID <saphid@users.noreply.github.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Alex Southwell committed Oct 19, 2026 at 16:43 UTC 8ae53fd4db0c30456b8275989e387fc393dfde30
2 files changed +289 -10
apps/web/src/components/device/DevicePanel.browser.test.tsx new
+260
@@ -0,0 +1,260 @@
1 +import {
2 + EnvironmentId,
3 + ThreadId,
4 + type DeviceServiceState,
5 + type ScopedThreadRef,
6 +} from "@t3tools/contracts";
7 +import { act, type ReactNode } from "react";
8 +import { createRoot, type Root } from "react-dom/client";
9 +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
10 +
11 +import type { RightPanelSurface } from "~/rightPanelStore";
12 +
13 +import { DevicePanel } from "./DevicePanel";
14 +
15 +type CommandResult =
16 + | { _tag: "Success"; value: { hostId: string; deviceId: string } }
17 + | { _tag: "Failure"; cause: unknown };
18 +const mocks = vi.hoisted(() => ({
19 + open: vi.fn<(request: unknown) => Promise<CommandResult>>(),
20 + close: vi.fn<(request: unknown) => Promise<CommandResult>>(),
21 + openDevice: vi.fn(),
22 + closeSurface: vi.fn(),
23 +}));
24 +const phone = {
25 + hostId: "local",
26 + id: "phone",
27 + name: "Phone",
28 + platform: "ios",
29 + version: "iOS 19",
30 + booted: false,
31 + physical: false,
32 +} as const;
33 +const deviceState: DeviceServiceState = {
34 + hosts: [
35 + {
36 + id: "local",
37 + kind: "local",
38 + label: "This Mac",
39 + platforms: [{ platform: "ios", available: true }],
40 + hubInstalled: true,
41 + agentDeviceInstalled: true,
42 + },
43 + ],
44 + hostStatus: "ready",
45 + hostStatuses: { local: { status: "ready" } },
46 + devices: [phone],
47 + sessions: [
48 + {
49 + threadId: ThreadId.make("thread-1"),
50 + hostId: "local",
51 + deviceId: "phone",
52 + platform: "ios",
53 + openedAt: "2026-01-01T00:00:00.000Z",
54 + },
55 + ],
56 + onboardingCompleted: true,
57 + agentAccessEnabled: true,
58 + hubBasePath: "/api/device-hub",
59 + revision: 1,
60 +};
61 +vi.mock("~/state/device", () => ({
62 + deviceEnvironment: { list: "list", open: "open", close: "close" },
63 + useDeviceState: () => ({ state: deviceState, loaded: true }),
64 +}));
65 +vi.mock("~/state/use-atom-command", () => ({
66 + useAtomCommand: (command: string) =>
67 + command === "open"
68 + ? mocks.open
69 + : command === "close"
70 + ? mocks.close
71 + : () => Promise.resolve({ _tag: "Success", value: {} }),
72 +}));
73 +vi.mock("~/state/query", () => ({ formatEnvironmentQueryError: () => "Device failed" }));
74 +vi.mock("~/rightPanelStore", () => ({
75 + useRightPanelStore: {
76 + getState: () => ({ openDevice: mocks.openDevice, closeSurface: mocks.closeSurface }),
77 + },
78 +}));
79 +vi.mock("~/components/device/DeviceHostUpdates", () => ({ DeviceHostUpdates: () => null }));
80 +vi.mock("~/components/device/DeviceLoadingView", () => ({ DeviceLoadingView: () => null }));
81 +vi.mock("~/components/device/DeviceWorkspace", () => ({
82 + DeviceWorkspace: ({ onPowerOff }: { onPowerOff: () => void }) => (
83 + <button onClick={onPowerOff}>Power off</button>
84 + ),
85 +}));
86 +vi.mock("~/components/preview/PreviewPanelShell", () => ({
87 + PreviewPanelShell: ({ children }: { children: ReactNode }) => children,
88 +}));
89 +
90 +const threadA = {
91 + environmentId: EnvironmentId.make("environment-a"),
92 + threadId: ThreadId.make("thread-1"),
93 +};
94 +// The panel stays mounted across both kinds of switch.
95 +const switches = [
96 + ["another thread", { environmentId: threadA.environmentId, threadId: ThreadId.make("thread-2") }],
97 + [
98 + "the same thread id in another environment",
99 + { ...threadA, environmentId: EnvironmentId.make("environment-b") },
100 + ],
101 +] as const;
102 +const threadB = switches[0][1];
103 +const otherEnvironment = switches[1][1];
104 +const picker: Extract<RightPanelSurface, { kind: "device" }> = { id: "device", kind: "device" };
105 +const streaming: Extract<RightPanelSurface, { kind: "device" }> = {
106 + id: "device:phone",
107 + kind: "device",
108 + target: { hostId: "local", deviceId: "phone", platform: "ios", name: "Phone" },
109 +};
110 +const phoneTarget = { hostId: "local", deviceId: "phone", platform: "ios", name: "Phone" };
111 +const opened = { _tag: "Success", value: { hostId: "local", deviceId: "phone" } } as const;
112 +const failed = { _tag: "Failure", cause: new Error("boom") } as const;
113 +
114 +const deferred = () => {
115 + let settle!: (result: CommandResult) => void;
116 + const promise = new Promise<CommandResult>((resolve) => (settle = resolve));
117 + return { promise, settle };
118 +};
119 +
120 +let root: Root;
121 +let container: HTMLDivElement;
122 +// Fixed key and a changing threadRef, as RightPanelSurfaceContent mounts it.
123 +const show = (threadRef: ScopedThreadRef, surface = picker) =>
124 + act(async () =>
125 + root.render(
126 + <DevicePanel
127 + key="device-panel"
128 + mode="embedded"
129 + threadRef={threadRef}
130 + surface={surface}
131 + visible
132 + onDismissSetup={() => undefined}
133 + />,
134 + ),
135 + );
136 +const startButton = () => container.querySelector<HTMLButtonElement>('[aria-label="Start Phone"]');
137 +const click = (button: HTMLButtonElement | null) =>
138 + act(async () => {
139 + button!.click();
140 + });
141 +const errors = () => container.querySelectorAll('[role="alert"]');
142 +
143 +beforeEach(() => {
144 + vi.resetAllMocks();
145 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
146 + container = document.createElement("div");
147 + document.body.append(container);
148 + root = createRoot(container);
149 +});
150 +afterEach(async () => {
151 + await act(() => root.unmount());
152 + container.remove();
153 + vi.unstubAllGlobals();
154 +});
155 +
156 +describe("DevicePanel thread switches", () => {
157 + it.each(switches)("does not carry a pending or failed pick to %s", async (_, target) => {
158 + const pick = deferred();
159 + mocks.open.mockReturnValue(pick.promise);
160 + await show(threadA);
161 + await click(startButton());
162 + expect(startButton()).toBeNull();
163 +
164 + await show(target);
165 + expect(startButton()?.disabled).toBe(false);
166 +
167 + await act(async () => pick.settle(failed));
168 + expect(errors()).toHaveLength(0);
169 + expect(mocks.openDevice).not.toHaveBeenCalled();
170 +
171 + await show(threadA);
172 + expect(startButton()?.disabled).toBe(false);
173 + expect(errors()).toHaveLength(1);
174 +
175 + await show(target);
176 + expect(startButton()?.disabled).toBe(false);
177 + expect(errors()).toHaveLength(0);
178 + });
179 +
180 + it.each([
181 + [
182 + "pick",
183 + picker,
184 + () => mocks.open,
185 + () => click(startButton()),
186 + () => expect(mocks.openDevice).toHaveBeenCalledExactlyOnceWith(threadA, phoneTarget),
187 + ],
188 + [
189 + "power-off",
190 + streaming,
191 + () => mocks.close,
192 + () => click(container.querySelector("button")),
193 + () => expect(mocks.closeSurface).toHaveBeenCalledExactlyOnceWith(threadA, streaming.id),
194 + ],
195 + ] as const)(
196 + "applies a late %s to its starting thread after switching environments with the same thread id",
197 + async (_, surface, command, start, expectApplied) => {
198 + const late = deferred();
199 + command().mockReturnValue(late.promise);
200 + await show(threadA, surface);
201 + await start();
202 +
203 + await show(otherEnvironment, surface);
204 + await act(async () => late.settle(opened));
205 +
206 + expectApplied();
207 + },
208 + );
209 +
210 + it("keeps a late power-off error in the environment that started it", async () => {
211 + const powerOff = deferred();
212 + mocks.close.mockReturnValue(powerOff.promise);
213 + await show(threadA, streaming);
214 + await click(container.querySelector("button"));
215 +
216 + await show(otherEnvironment, streaming);
217 + await act(async () => powerOff.settle(failed));
218 +
219 + expect(errors()).toHaveLength(0);
220 + expect(mocks.closeSurface).not.toHaveBeenCalled();
221 + await show(threadA, streaming);
222 + expect(errors()).toHaveLength(1);
223 + });
224 +
225 + it("keeps the latest pick pending across switches away and back", async () => {
226 + const first = deferred();
227 + const second = deferred();
228 + const latest = deferred();
229 + mocks.open
230 + .mockReturnValueOnce(first.promise)
231 + .mockReturnValueOnce(second.promise)
232 + .mockReturnValueOnce(latest.promise);
233 + await show(threadA);
234 + await click(startButton());
235 + await show(threadB);
236 + await click(startButton());
237 + await show(threadA);
238 + await click(startButton());
239 +
240 + await act(async () => first.settle(failed));
241 +
242 + expect(startButton()).toBeNull();
243 + expect(errors()).toHaveLength(0);
244 + expect(mocks.openDevice).not.toHaveBeenCalled();
245 +
246 + await act(async () => second.settle(opened));
247 +
248 + expect(startButton()).toBeNull();
249 + expect(mocks.openDevice.mock.calls).toEqual([[threadB, phoneTarget]]);
250 +
251 + await act(async () => latest.settle(opened));
252 +
253 + expect(startButton()?.disabled).toBe(false);
254 + expect(errors()).toHaveLength(0);
255 + expect(mocks.openDevice.mock.calls).toEqual([
256 + [threadB, phoneTarget],
257 + [threadA, phoneTarget],
258 + ]);
259 + });
260 +});
apps/web/src/components/device/DevicePanel.tsx
+29 -10
@@ -42,8 +42,16 @@ export function DevicePanel(props: {
42 const list = useAtomCommand(deviceEnvironment.list, { reportFailure: false });
43 const open = useAtomCommand(deviceEnvironment.open);
44 const close = useAtomCommand(deviceEnvironment.close);
45 - const [operationError, setOperationError] = useState<string | null>(null);
46 - const [pendingDevice, setPendingDevice] = useState<DeviceSummary | null>(null);
45 + // The panel stays mounted across thread switches, so an in-flight open or
46 + // power-off is tagged with the thread it belongs to and only shown there.
47 + const scope = `${environmentId}\u0000${threadId}`;
48 + const [operation, setOperation] = useState<{
49 + readonly scope: string;
50 + readonly pending: DeviceSummary | null;
51 + readonly error: string | null;
52 + } | null>(null);
53 + const pendingDevice = operation?.scope === scope ? operation.pending : null;
54 + const operationError = operation?.scope === scope ? operation.error : null;
55 const pendingDeviceKey = pendingDevice ? deviceKey(pendingDevice) : null;
56
57 const hostDisabled = state.hostStatus === "disabled";
@@ -70,11 +78,20 @@ export function DevicePanel(props: {
78
79 const grouped = groupDevices(state);
80
81 + const startOperation = (pending: DeviceSummary | null) => {
82 + const started = { scope, pending, error: null };
83 + setOperation(started);
84 + // Returning to the same thread can start a newer operation before this one settles.
85 + return (error: string | null) =>
86 + setOperation((current) =>
87 + current === started ? { ...started, pending: null, error } : current,
88 + );
89 + };
90 +
91 const selectDevice = async (value: string) => {
92 const device = state.devices.find((candidate) => deviceKey(candidate) === value);
93 if (!device) return;
76 - setOperationError(null);
77 - setPendingDevice(device);
94 + const settleOperation = startOperation(device);
95 const result = await open({
96 environmentId,
97 input: {
@@ -84,15 +101,17 @@ export function DevicePanel(props: {
101 platform: device.platform,
102 },
103 });
87 - if (result._tag === "Failure") setOperationError(formatEnvironmentQueryError(result.cause));
88 - else
104 + if (result._tag === "Failure") settleOperation(formatEnvironmentQueryError(result.cause));
105 + else {
106 + // The server opened the device for the starting thread, so its tab opens there.
107 useRightPanelStore.getState().openDevice(props.threadRef, {
108 hostId: result.value.hostId,
109 deviceId: result.value.deviceId,
110 platform: device.platform,
111 name: device.name,
112 });
95 - setPendingDevice(null);
113 + settleOperation(null);
114 + }
115 };
116
117 const floatActive = () => {
@@ -113,7 +132,7 @@ export function DevicePanel(props: {
132 return;
133 }
134 if (!activeSession) return;
116 - setOperationError(null);
135 + const settleOperation = startOperation(null);
136 void close({
137 environmentId,
138 input: {
@@ -123,7 +142,7 @@ export function DevicePanel(props: {
142 shutdown: powerOff,
143 },
144 }).then((result) => {
126 - if (result._tag === "Failure") setOperationError(formatEnvironmentQueryError(result.cause));
145 + if (result._tag === "Failure") settleOperation(formatEnvironmentQueryError(result.cause));
146 else useRightPanelStore.getState().closeSurface(props.threadRef, props.surface.id);
147 });
148 };
@@ -180,7 +199,7 @@ export function DevicePanel(props: {
199 size="icon-xs"
200 variant="ghost"
201 aria-label="Dismiss device error"
183 - onClick={() => setOperationError(null)}
202 + onClick={() => setOperation(null)}
203 >
204 <X className="size-3" />
205 </Button>