Open History to see the last commit
1import { EnvironmentId, type DeviceDetail, type DeviceSummary } from "@t3tools/contracts";
2import type { DeviceHubAccess } from "@t3tools/client-runtime/device/hub-access";
3import * as Cause from "effect/Cause";
4import { act, useEffect } from "react";
5import { createRoot, type Root } from "react-dom/client";
6import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
7
8type Result = { _tag: "Success"; value: DeviceDetail } | { _tag: "Failure"; cause: unknown };
9const { read, action, subscribe } = vi.hoisted(() => ({
10 read: vi.fn<() => Promise<Result>>(),
11 action: vi.fn<() => Promise<Result>>(),
12 subscribe:
13 vi.fn<(_target: unknown, onChange: (app: { id: string } | null) => void) => () => void>(),
14}));
15vi.mock(import("~/state/use-atom-command"), async (original) => {
16 const { deviceEnvironment } = await import("~/state/device");
17 return {
18 ...(await original()),
19 useAtomCommand: ((command: unknown) =>
20 command === deviceEnvironment.detail ? read : action) as never,
21 };
22});
23vi.mock(import("./deviceHubApi"), async (original) => ({
24 ...(await original()),
25 subscribeDeviceForeground: subscribe as never,
26}));
27
28import { useDeviceControls, type DeviceControls } from "./useDeviceControls";
29
30const offline = Cause.fail(new Error("Device offline"));
31const device: DeviceSummary = {
32 hostId: "remote",
33 id: "phone",
34 name: "Phone",
35 platform: "ios",
36 version: "iOS",
37 booted: true,
38 physical: false,
39};
40const snapshot = (appearance: "light" | "dark"): Result => ({
41 _tag: "Success",
42 value: {
43 hostId: "remote",
44 deviceId: "phone",
45 settings: { appearance },
46 foregroundApp: null,
47 readAt: "2026-09-20T00:00:00Z",
48 },
49});
50function deferred() {
51 let resolve!: (value: Result) => void;
52 const promise = new Promise<Result>((done) => {
53 resolve = done;
54 });
55 return { promise, resolve };
56}
57let root: Root;
58let controls: DeviceControls;
59function Probe({ visible, access = null }: { visible: boolean; access?: DeviceHubAccess | null }) {
60 const next = useDeviceControls({
61 environmentId: EnvironmentId.make("environment"),
62 device,
63 access,
64 visible,
65 });
66 useEffect(() => {
67 controls = next;
68 }, [next]);
69 return null;
70}
71beforeEach(() => {
72 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
73 read.mockReset();
74 action.mockReset();
75 subscribe.mockReset();
76 subscribe.mockReturnValue(() => {});
77 read.mockResolvedValue(snapshot("light"));
78 root = createRoot(document.createElement("div"));
79});
80afterEach(async () => {
81 await act(async () => root.unmount());
82 vi.unstubAllGlobals();
83});
84async function mount() {
85 await act(async () => {
86 root.render(<Probe visible />);
87 });
88}
89
90it("serializes rapid actions and retains confirmed settings while pending or after failure", async () => {
91 await mount();
92 const response = deferred();
93 action.mockReturnValueOnce(response.promise);
94 let pending!: Promise<void>;
95 await act(async () => {
96 pending = controls.act({ type: "setAppearance", value: "dark" });
97 await controls.act({ type: "setAppearance", value: "light" });
98 });
99 expect(action).toHaveBeenCalledOnce();
100 expect(controls.disabled).toBe(true);
101 expect(controls.detail?.settings.appearance).toBe("light");
102 await act(async () => {
103 response.resolve(snapshot("dark"));
104 await pending;
105 });
106 expect(controls.detail?.settings.appearance).toBe("dark");
107 action.mockResolvedValueOnce({ _tag: "Failure", cause: offline });
108 await act(async () => controls.act({ type: "setAppearance", value: "light" }));
109 expect(controls.detail?.settings.appearance).toBe("dark");
110 expect(controls.error).toBe("Device offline");
111 expect(controls.disabled).toBe(false);
112});
113
114it("serializes host actions across hide/reopen and discards detached results", async () => {
115 await mount();
116 const response = deferred();
117 action.mockReturnValueOnce(response.promise);
118 let pending!: Promise<void>;
119 await act(async () => {
120 pending = controls.act({ type: "setAppearance", value: "dark" });
121 });
122 await act(async () => root.render(<Probe visible={false} />));
123 expect(controls.disabled).toBe(true);
124 await act(async () => root.render(<Probe visible />));
125 await act(async () => controls.act({ type: "setAppearance", value: "light" }));
126 expect(action).toHaveBeenCalledOnce();
127 expect(controls.disabled).toBe(true);
128 const confirmed = deferred();
129 read.mockReturnValueOnce(confirmed.promise);
130 await act(async () => {
131 response.resolve(snapshot("dark"));
132 await response.promise;
133 });
134 expect(controls.detail?.settings.appearance).toBe("light");
135 expect(controls.disabled).toBe(true);
136 await act(async () => {
137 confirmed.resolve(snapshot("dark"));
138 await pending;
139 });
140 expect(controls.detail?.settings.appearance).toBe("dark");
141 expect(controls.disabled).toBe(false);
142 action.mockResolvedValueOnce(snapshot("dark"));
143 await act(async () => controls.act({ type: "setAppearance", value: "dark" }));
144 expect(action).toHaveBeenCalledTimes(2);
145 expect(controls.detail?.settings.appearance).toBe("dark");
146});
147
148it("keeps actions disabled when settings cannot be confirmed after a detached command", async () => {
149 await mount();
150 const response = deferred();
151 action.mockReturnValueOnce(response.promise);
152 let pending!: Promise<void>;
153 await act(async () => {
154 pending = controls.act({ type: "setAppearance", value: "dark" });
155 });
156 await act(async () => root.render(<Probe visible={false} />));
157 await act(async () => root.render(<Probe visible />));
158 read.mockResolvedValueOnce({ _tag: "Failure", cause: offline });
159 await act(async () => {
160 response.resolve(snapshot("dark"));
161 await pending;
162 });
163 expect(controls.detail).toBeNull();
164 expect(controls.disabled).toBe(true);
165 expect(controls.error).toBe("Device offline");
166 await act(async () => controls.act({ type: "setAppearance", value: "light" }));
167 expect(action).toHaveBeenCalledOnce();
168 await act(async () => root.render(<Probe visible={false} />));
169 await act(async () => root.render(<Probe visible />));
170 expect(controls.disabled).toBe(false);
171 expect(controls.error).toBeNull();
172});
173
174it("disables stale settings after a failed reopen read and recovers on a successful read", async () => {
175 await mount();
176 await act(async () => root.render(<Probe visible={false} />));
177 read.mockResolvedValueOnce({ _tag: "Failure", cause: offline });
178 await act(async () => root.render(<Probe visible />));
179 expect(controls.detail).toBeNull();
180 expect(controls.disabled).toBe(true);
181 expect(controls.error).toBe("Device offline");
182 await act(async () => controls.act({ type: "setAppearance", value: "dark" }));
183 expect(action).not.toHaveBeenCalled();
184 await act(async () => root.render(<Probe visible={false} />));
185 await act(async () => root.render(<Probe visible />));
186 expect(controls.detail?.settings.appearance).toBe("light");
187 expect(controls.disabled).toBe(false);
188 expect(controls.error).toBeNull();
189});
190
191it("does not let an older refresh overwrite a newer confirmed action", async () => {
192 await mount();
193 await act(async () => root.render(<Probe visible={false} />));
194 const refresh = deferred();
195 read.mockReturnValueOnce(refresh.promise);
196 await act(async () => root.render(<Probe visible />));
197 action.mockResolvedValueOnce(snapshot("dark"));
198 await act(async () => controls.act({ type: "setAppearance", value: "dark" }));
199 await act(async () => {
200 refresh.resolve(snapshot("light"));
201 await refresh.promise;
202 });
203 expect(controls.detail?.settings.appearance).toBe("dark");
204});
205
206it.each(["hidden", "access renewed"] as const)(
207 "uses the detail snapshot until a new foreground event after the subscription is %s",
208 async (restart) => {
209 const access: DeviceHubAccess = {
210 httpBase: "https://remote.test/api/device-hub",
211 wsBase: "wss://remote.test/api/device-hub",
212 query: {},
213 credentials: false,
214 };
215 const detail = snapshot("light");
216 if (detail._tag !== "Success") throw new Error("Expected a successful snapshot");
217 read.mockResolvedValue({
218 ...detail,
219 value: { ...detail.value, foregroundApp: { id: "snapshot.app" } },
220 });
221 await act(async () => {
222 root.render(<Probe visible access={access} />);
223 });
224 const oldEvent = subscribe.mock.calls[0]![1];
225 await act(async () => oldEvent({ id: "previous.live.app" }));
226 expect(controls.foregroundApp?.id).toBe("previous.live.app");
227 if (restart === "hidden") {
228 await act(async () => root.render(<Probe visible={false} access={access} />));
229 await act(async () => root.render(<Probe visible access={access} />));
230 } else {
231 await act(async () =>
232 root.render(<Probe visible access={{ ...access, query: { ticket: "renewed" } }} />),
233 );
234 }
235 expect(controls.foregroundApp?.id).toBe("snapshot.app");
236 await act(async () => oldEvent({ id: "late.previous.app" }));
237 expect(controls.foregroundApp?.id).toBe("snapshot.app");
238 const newEvent = subscribe.mock.calls[1]![1];
239 await act(async () => newEvent({ id: "current.live.app" }));
240 expect(controls.foregroundApp?.id).toBe("current.live.app");
241 },
242);