@devries-cameron20 / t3code-1 / commits / e4fb9f2ccf
Fork 0

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

test(web): hook-harness tests run in a real browser (#20866)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 17, 2026 at 02:49 UTC e4fb9f2ccfbb362e45e92e49a1939b87872dedc5
24 files changed +2431 -2813
apps/web/src/components/permissions/usePermissionStatus.browser.test.tsx new
+103
@@ -0,0 +1,103 @@
1 +import { act, useEffect } from "react";
2 +import { createRoot, type Root } from "react-dom/client";
3 +import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
4 +
5 +import { usePermissionStatus } from "./usePermissionStatus";
6 +
7 +type Status = { screen: boolean; accessibility: boolean };
8 +const check = vi.fn<() => Promise<Status>>();
9 +
10 +function deferred<T>() {
11 + let resolve!: (value: T) => void;
12 + const promise = new Promise<T>((done) => {
13 + resolve = done;
14 + });
15 + return { promise, resolve };
16 +}
17 +
18 +let root: Root | null;
19 +let current: ReturnType<typeof usePermissionStatus<keyof Status>>;
20 +let visibility: DocumentVisibilityState;
21 +
22 +function Probe() {
23 + const status = usePermissionStatus(check, { screen: false, accessibility: false });
24 + useEffect(() => {
25 + current = status;
26 + });
27 + return null;
28 +}
29 +
30 +beforeEach(() => {
31 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
32 + vi.useFakeTimers();
33 + visibility = "visible";
34 + Object.defineProperty(document, "visibilityState", {
35 + configurable: true,
36 + get: () => visibility,
37 + });
38 + check.mockReset().mockResolvedValue({ screen: false, accessibility: false });
39 + root = null;
40 +});
41 +afterEach(async () => {
42 + await unmount();
43 + vi.useRealTimers();
44 + vi.unstubAllGlobals();
45 + Reflect.deleteProperty(document, "visibilityState");
46 +});
47 +
48 +async function start() {
49 + root = createRoot(document.createElement("div"));
50 + await act(async () => root!.render(<Probe />));
51 +}
52 +async function unmount() {
53 + const mounted = root;
54 + root = null;
55 + if (mounted) await act(async () => mounted.unmount());
56 +}
57 +const tick = (ms: number) => act(() => vi.advanceTimersByTimeAsync(ms));
58 +
59 +it("unlocks Continue only for required grants and relocks on revocation", async () => {
60 + await start();
61 + expect(current.isReady(["screen"])).toBe(false);
62 + check.mockResolvedValue({ screen: true, accessibility: false });
63 + await tick(1500);
64 + expect(current.isReady(["screen"])).toBe(true);
65 + expect(current.isReady(["screen", "accessibility"])).toBe(false);
66 + check.mockResolvedValue({ screen: true, accessibility: true });
67 + await tick(1500);
68 + expect(current.isReady(["screen", "accessibility"])).toBe(true);
69 + check.mockResolvedValue({ screen: false, accessibility: true });
70 + await act(async () => window.dispatchEvent(new Event("focus")));
71 + expect(current.isReady(["screen"])).toBe(false);
72 +});
73 +
74 +it("does not overlap checks and discards completion after closing", async () => {
75 + const pending = deferred<Status>();
76 + check.mockReturnValue(pending.promise);
77 + await start();
78 + await tick(4500);
79 + window.dispatchEvent(new Event("focus"));
80 + expect(check).toHaveBeenCalledTimes(1);
81 + const last = current;
82 + await unmount();
83 + await act(async () => pending.resolve({ screen: true, accessibility: true }));
84 + expect(last.isReady(["screen"])).toBe(false);
85 + expect(vi.getTimerCount()).toBe(0);
86 +});
87 +
88 +it("pauses in the background and blocks stale grants after a check failure", async () => {
89 + check.mockResolvedValue({ screen: true, accessibility: true });
90 + await start();
91 + expect(current.isReady(["screen"])).toBe(true);
92 + visibility = "hidden";
93 + await tick(3000);
94 + expect(check).toHaveBeenCalledTimes(1);
95 + check.mockRejectedValue(new Error("IPC unavailable"));
96 + visibility = "visible";
97 + await act(async () => document.dispatchEvent(new Event("visibilitychange")));
98 + expect(current.isReady(["screen"])).toBe(false);
99 + expect(current.error).not.toBeNull();
100 + check.mockResolvedValue({ screen: true, accessibility: true });
101 + await tick(1500);
102 + expect(current.isReady(["screen"])).toBe(true);
103 +});
apps/web/src/components/permissions/usePermissionStatus.test.ts deleted
-96
@@ -1,96 +0,0 @@
1 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
2 -import { reactHookHarness as hooks } from "../../test/reactHookHarness";
3 -import { usePermissionStatus } from "./usePermissionStatus";
4 -
5 -const effects = vi.hoisted(() => [] as Array<() => (() => void) | undefined>);
6 -vi.mock("react", async (original) => {
7 - const actual = await original<typeof import("react")>();
8 - const { reactHookHarness } = await import("../../test/reactHookHarness");
9 - return {
10 - ...actual,
11 - useState: reactHookHarness.useState,
12 - useEffect: (effect: () => (() => void) | undefined) => effects.push(effect),
13 - useEffectEvent: <T>(callback: T) => callback,
14 - };
15 -});
16 -vi.mock("react/compiler-runtime", async () => {
17 - const { reactHookHarness } = await import("../../test/reactHookHarness");
18 - return { c: reactHookHarness.useMemoCache };
19 -});
20 -const check = vi.fn<() => Promise<{ screen: boolean; accessibility: boolean }>>();
21 -let cleanup: (() => void) | undefined;
22 -let page: EventTarget & { visibilityState: string };
23 -const render = () => {
24 - hooks.beginRender();
25 - return usePermissionStatus(check, { screen: false, accessibility: false });
26 -};
27 -beforeEach(() => {
28 - hooks.reset();
29 - effects.length = 0;
30 - vi.useFakeTimers();
31 - page = Object.assign(new EventTarget(), { visibilityState: "visible" });
32 - vi.stubGlobal("document", page);
33 - vi.stubGlobal("window", Object.assign(new EventTarget(), { setInterval, clearInterval }));
34 - check.mockReset().mockResolvedValue({ screen: false, accessibility: false });
35 -});
36 -afterEach(() => {
37 - cleanup?.();
38 - vi.useRealTimers();
39 - vi.unstubAllGlobals();
40 -});
41 -const start = async () => {
42 - render();
43 - cleanup = effects[0]!();
44 - await Promise.resolve();
45 -};
46 -
47 -it("unlocks Continue only for required grants and relocks on revocation", async () => {
48 - await start();
49 - expect(render().isReady(["screen"])).toBe(false);
50 - check.mockResolvedValue({ screen: true, accessibility: false });
51 - await vi.advanceTimersByTimeAsync(1500);
52 - expect(render().isReady(["screen"])).toBe(true);
53 - expect(render().isReady(["screen", "accessibility"])).toBe(false);
54 - check.mockResolvedValue({ screen: true, accessibility: true });
55 - await vi.advanceTimersByTimeAsync(1500);
56 - expect(render().isReady(["screen", "accessibility"])).toBe(true);
57 - check.mockResolvedValue({ screen: false, accessibility: true });
58 - window.dispatchEvent(new Event("focus"));
59 - await Promise.resolve();
60 - expect(render().isReady(["screen"])).toBe(false);
61 -});
62 -
63 -it("does not overlap checks and discards completion after closing", async () => {
64 - let resolve!: (status: { screen: boolean; accessibility: boolean }) => void;
65 - const promise = new Promise<{ screen: boolean; accessibility: boolean }>((done) => {
66 - resolve = done;
67 - });
68 - const pending = { promise, resolve };
69 - check.mockReturnValue(pending.promise);
70 - await start();
71 - await vi.advanceTimersByTimeAsync(4500);
72 - window.dispatchEvent(new Event("focus"));
73 - expect(check).toHaveBeenCalledTimes(1);
74 - cleanup?.();
75 - pending.resolve({ screen: true, accessibility: true });
76 - await pending.promise;
77 - expect(render().isReady(["screen"])).toBe(false);
78 - expect(vi.getTimerCount()).toBe(0);
79 -});
80 -
81 -it("pauses in the background and blocks stale grants after a check failure", async () => {
82 - check.mockResolvedValue({ screen: true, accessibility: true });
83 - await start();
84 - expect(render().isReady(["screen"])).toBe(true);
85 - page.visibilityState = "hidden";
86 - await vi.advanceTimersByTimeAsync(3000);
87 - expect(check).toHaveBeenCalledTimes(1);
88 - check.mockRejectedValue(new Error("IPC unavailable"));
89 - page.visibilityState = "visible";
90 - page.dispatchEvent(new Event("visibilitychange"));
91 - await Promise.resolve();
92 - expect(render().isReady(["screen"])).toBe(false);
93 - check.mockResolvedValue({ screen: true, accessibility: true });
94 - await vi.advanceTimersByTimeAsync(1500);
95 - expect(render().isReady(["screen"])).toBe(true);
96 -});
apps/web/src/components/settings/AcpRegistryIcon.browser.test.tsx new
+71
@@ -0,0 +1,71 @@
1 +import { act } from "react";
2 +import { createRoot, type Root } from "react-dom/client";
3 +import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
4 +
5 +import { AcpRegistryAgentIcon } from "./AcpRegistryIcon";
6 +
7 +const url = "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg";
8 +const fetchIcon = vi.fn<typeof fetch>();
9 +let root: Root;
10 +let container: HTMLDivElement;
11 +
12 +beforeEach(() => {
13 + vi.stubGlobal("caches", undefined);
14 + vi.stubGlobal("fetch", fetchIcon);
15 + fetchIcon.mockReset();
16 + container = document.createElement("div");
17 + document.body.append(container);
18 + root = createRoot(container);
19 +});
20 +afterEach(async () => {
21 + await act(async () => root.unmount());
22 + container.remove();
23 + vi.unstubAllGlobals();
24 +});
25 +
26 +const image = () => container.querySelector("img");
27 +const fallback = () => container.querySelector('[data-slot="acp-icon-fallback"]');
28 +
29 +it("falls back to the raw allowlisted CDN URL when the validating fetch is blocked", async () => {
30 + // The official CDN serves no CORS headers, so the fetch can reject even
31 + // though native <img> loading works.
32 + fetchIcon.mockRejectedValue(new TypeError("Failed to fetch"));
33 + await act(async () => root.render(<AcpRegistryAgentIcon icon={url} />));
34 +
35 + await vi.waitFor(() => expect(image()?.getAttribute("src")).toBe(url));
36 + expect(image()?.referrerPolicy).toBe("no-referrer");
37 + expect(fallback()).not.toBeNull();
38 +});
39 +
40 +function serve(body: string) {
41 + fetchIcon.mockResolvedValue(
42 + new Response(body, { status: 200, headers: { "content-type": "image/svg+xml" } }),
43 + );
44 +}
45 +
46 +it("swaps the fallback for the validated blob once the image loads", async () => {
47 + serve('<svg xmlns="http://www.w3.org/2000/svg" width="8" height="8"/>');
48 + await act(async () => root.render(<AcpRegistryAgentIcon icon={url} />));
49 +
50 + await vi.waitFor(() => expect(fallback()).toBeNull());
51 + expect(image()?.src).toMatch(/^blob:/);
52 + expect(image()?.checkVisibility()).toBe(true);
53 +});
54 +
55 +it("keeps the fallback and drops the image when the validated blob fails to decode", async () => {
56 + serve("not an svg");
57 + await act(async () => root.render(<AcpRegistryAgentIcon icon={url} />));
58 +
59 + await vi.waitFor(() => expect(fetchIcon).toHaveBeenCalledOnce());
60 + await vi.waitFor(() => expect(image()).toBeNull());
61 + expect(fallback()).not.toBeNull();
62 +});
63 +
64 +it("never renders an icon from outside the official CDN", async () => {
65 + await act(async () =>
66 + root.render(<AcpRegistryAgentIcon icon="https://cdn.agentclientprotocol.com.evil/icon.svg" />),
67 + );
68 + expect(fetchIcon).not.toHaveBeenCalled();
69 + expect(image()).toBeNull();
70 + expect(fallback()).not.toBeNull();
71 +});
apps/web/src/components/settings/AcpRegistryIcon.test.ts
-93
@@ -1,22 +1,6 @@
1 -import type { ReactElement } from "react";
1 import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
2
4 -import { visitElements } from "../../test/reactElementTree";
5 -import { reactHookHarness as hooks } from "../../test/reactHookHarness";
6 -
7 -vi.mock("react", async (importOriginal) => {
8 - const actual = await importOriginal<typeof import("react")>();
9 - const { reactHookHarness } = await import("../../test/reactHookHarness");
10 - return {
11 - ...actual,
12 - useEffect: (effect: () => void | (() => void)) => effect(),
13 - useState: reactHookHarness.useState,
14 - useId: () => "acp-icon-test-filter",
15 - };
16 -});
17 -
3 import {
19 - AcpRegistryAgentIcon,
4 loadCachedAcpRegistryIcon,
5 officialAcpRegistryIconUrlForAgentId,
6 resolveOfficialAcpRegistryIconUrl,
@@ -31,7 +15,6 @@ describe("ACP Registry icon cache", () => {
15 const fetchIcon = vi.fn();
16
17 beforeEach(() => {
34 - hooks.reset();
18 stored.clear();
19 match.mockClear();
20 put.mockClear();
@@ -125,80 +108,4 @@ describe("ACP Registry icon cache", () => {
108 );
109 expect(officialAcpRegistryIconUrlForAgentId("../kilo")).toBeNull();
110 });
128 -
129 - it("falls back to the raw allowlisted CDN URL when the validating fetch is blocked", async () => {
130 - const url = "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg";
131 - // The official CDN serves no CORS headers, so the fetch can reject even
132 - // though native <img> loading works.
133 - fetchIcon.mockRejectedValue(new TypeError("Failed to fetch"));
134 - hooks.beginRender();
135 - AcpRegistryAgentIcon({ icon: url });
136 -
137 - await new Promise((resolve) => setTimeout(resolve, 0));
138 - hooks.beginRender();
139 - const tree = AcpRegistryAgentIcon({ icon: url }) as ReactElement<Record<string, unknown>>;
140 - const image = visitElements(tree, (element) => element.type === "img");
141 - expect(image?.props).toMatchObject({ src: url, referrerPolicy: "no-referrer" });
142 - expect(
143 - visitElements(tree, (element) => element.props["data-slot"] === "acp-icon-fallback"),
144 - ).not.toBeNull();
145 - });
146 -
147 - it("renders only the validated blob object URL and keeps the fallback until load", async () => {
148 - const url = "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg";
149 - const objectUrl = "blob:t3/kilo-icon";
150 - Object.assign(URL, {
151 - createObjectURL: vi.fn(() => objectUrl),
152 - revokeObjectURL: vi.fn(),
153 - });
154 - fetchIcon.mockResolvedValue(
155 - new Response("<svg/>", {
156 - status: 200,
157 - headers: { "content-type": "image/svg+xml" },
158 - }),
159 - );
160 - hooks.beginRender();
161 - const validating = AcpRegistryAgentIcon({ icon: url }) as ReactElement<Record<string, unknown>>;
162 -
163 - expect(visitElements(validating, (element) => element.type === "img")).toBeNull();
164 - expect(
165 - visitElements(validating, (element) => element.props["data-slot"] === "acp-icon-fallback"),
166 - ).not.toBeNull();
167 -
168 - await new Promise((resolve) => setTimeout(resolve, 0));
169 - hooks.beginRender();
170 - const loading = AcpRegistryAgentIcon({ icon: url }) as ReactElement<Record<string, unknown>>;
171 - const loadingImage = visitElements(loading, (element) => element.type === "img");
172 -
173 - expect(loadingImage?.props).toMatchObject({
174 - src: objectUrl,
175 - alt: "",
176 - decoding: "async",
177 - referrerPolicy: "no-referrer",
178 - });
179 - expect(loadingImage?.props.className).not.toContain("dark:invert");
180 - expect(loadingImage?.props.className).toContain("invisible");
181 - expect(
182 - visitElements(loading, (element) => element.props["data-slot"] === "acp-icon-fallback"),
183 - ).not.toBeNull();
184 -
185 - (loadingImage?.props.onLoad as (() => void) | undefined)?.();
186 - hooks.beginRender();
187 - const loaded = AcpRegistryAgentIcon({ icon: url }) as ReactElement<Record<string, unknown>>;
188 - expect(
189 - visitElements(loaded, (element) => element.type === "img")?.props.className,
190 - ).not.toContain("invisible");
191 - expect(
192 - visitElements(loaded, (element) => element.props["data-slot"] === "acp-icon-fallback"),
193 - ).toBeNull();
194 -
195 - const loadedImage = visitElements(loaded, (element) => element.type === "img");
196 - (loadedImage?.props.onError as (() => void) | undefined)?.();
197 - hooks.beginRender();
198 - const failed = AcpRegistryAgentIcon({ icon: url }) as ReactElement<Record<string, unknown>>;
199 - expect(visitElements(failed, (element) => element.type === "img")).toBeNull();
200 - expect(
201 - visitElements(failed, (element) => element.props["data-slot"] === "acp-icon-fallback"),
202 - ).not.toBeNull();
203 - });
111 });
apps/web/src/components/settings/AcpSessionManagementSection.browser.test.tsx new
+294
@@ -0,0 +1,294 @@
1 +import {
2 + EnvironmentId,
3 + ProjectId,
4 + ProviderDriverKind,
5 + ProviderInstanceId,
6 + ThreadId,
7 + type ServerProvider,
8 +} from "@t3tools/contracts";
9 +import { act } from "react";
10 +import { createRoot, type Root } from "react-dom/client";
11 +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
12 +
13 +const commands = vi.hoisted(() => ({
14 + list: vi.fn(),
15 + import: vi.fn(),
16 + delete: vi.fn(),
17 + listProviders: vi.fn(),
18 + setProvider: vi.fn(),
19 + disableProvider: vi.fn(),
20 + logout: vi.fn(),
21 +}));
22 +const grants = vi.hoisted(() => ({ scopes: new Set<string>() }));
23 +const dialogs = vi.hoisted(() => ({ confirm: vi.fn() }));
24 +
25 +vi.mock(import("~/state/session"), async (original) => ({
26 + ...(await original()),
27 + useEnvironmentScope: ((_id: unknown, scope: string) => grants.scopes.has(scope)) as never,
28 + readEnvironmentScope: ((_id: unknown, scope: string) => grants.scopes.has(scope)) as never,
29 +}));
30 +vi.mock(import("../../state/use-atom-command"), async (original) => {
31 + const { serverEnvironment } = await import("../../state/server");
32 + const byAtom = new Map<unknown, unknown>([
33 + [serverEnvironment.listAcpRegistrySessions, commands.list],
34 + [serverEnvironment.importAcpRegistrySession, commands.import],
35 + [serverEnvironment.deleteAcpRegistrySession, commands.delete],
36 + [serverEnvironment.listAcpRegistryProviders, commands.listProviders],
37 + [serverEnvironment.setAcpRegistryProvider, commands.setProvider],
38 + [serverEnvironment.disableAcpRegistryProvider, commands.disableProvider],
39 + [serverEnvironment.logoutAcpRegistry, commands.logout],
40 + ]);
41 + return {
42 + ...(await original()),
43 + useAtomCommand: ((atom: unknown) => byAtom.get(atom)) as never,
44 + };
45 +});
46 +vi.mock(import("../../localApi"), async (original) => ({
47 + ...(await original()),
48 + ensureLocalApi: () => ({ dialogs }) as never,
49 +}));
50 +
51 +import { AcpSessionManagementSection } from "./AcpSessionManagementSection";
52 +
53 +const environmentId = EnvironmentId.make("remote-device");
54 +const instanceId = ProviderInstanceId.make("acpRegistry_antigravity");
55 +const projectId = ProjectId.make("project-antigravity");
56 +const session = {
57 + sessionId: "native-session-1",
58 + cwd: "/workspace/antigravity",
59 + additionalDirectories: [],
60 + title: "Native Antigravity session",
61 + updatedAt: "2026-08-23T00:00:00Z",
62 + importedThreadId: null,
63 +} as const;
64 +const provider = {
65 + instanceId,
66 + driver: ProviderDriverKind.make("acpRegistry"),
67 + enabled: true,
68 + installed: true,
69 + version: "1.0.0",
70 + status: "ready",
71 + auth: { status: "authenticated", canLogout: true },
72 + nativeSessions: { canList: true, canLoad: true, canResume: true, canDelete: true },
73 + configurableProviders: true,
74 + checkedAt: "2026-08-23T00:00:00.000Z",
75 + models: [],
76 + slashCommands: [],
77 + skills: [],
78 +} satisfies ServerProvider;
79 +
80 +function deferred<T>() {
81 + let resolve!: (value: T) => void;
82 + const promise = new Promise<T>((done) => {
83 + resolve = done;
84 + });
85 + return { promise, resolve };
86 +}
87 +
88 +let root: Root;
89 +let container: HTMLDivElement;
90 +
91 +function render(readOnly = false) {
92 + return act(async () =>
93 + root.render(
94 + <AcpSessionManagementSection
95 + environmentId={environmentId}
96 + instanceId={instanceId}
97 + provider={provider}
98 + projects={[{ id: projectId, title: "Antigravity", workspaceRoot: session.cwd }]}
99 + readOnly={readOnly}
100 + />,
101 + ),
102 + );
103 +}
104 +function button(label: string) {
105 + const found = [...container.querySelectorAll("button")].find(
106 + (element) => element.textContent === label,
107 + );
108 + expect(found, `button ${label}`).toBeDefined();
109 + return found!;
110 +}
111 +const click = (label: string) => act(async () => button(label).click());
112 +
113 +beforeEach(() => {
114 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
115 + grants.scopes = new Set(["orchestration:read", "orchestration:operate", "providers:manage"]);
116 + commands.list.mockReset().mockResolvedValue({
117 + _tag: "Success",
118 + value: {
119 + sessions: [session],
120 + nextCursor: null,
121 + canLoad: true,
122 + canResume: true,
123 + canDelete: true,
124 + },
125 + });
126 + commands.import.mockReset().mockResolvedValue({
127 + _tag: "Success",
128 + value: { threadId: ThreadId.make("thread-imported"), imported: true },
129 + });
130 + commands.delete.mockReset().mockResolvedValue({
131 + _tag: "Success",
132 + value: { deleted: true },
133 + });
134 + commands.listProviders.mockReset().mockResolvedValue({
135 + _tag: "Success",
136 + value: {
137 + providers: [
138 + {
139 + providerId: "google",
140 + supported: ["openai"],
141 + required: false,
142 + current: { apiType: "openai", baseUrl: "https://api.example.test/v1" },
143 + },
144 + ],
145 + },
146 + });
147 + commands.setProvider.mockReset().mockResolvedValue({
148 + _tag: "Success",
149 + value: { configured: true },
150 + });
151 + commands.disableProvider.mockReset().mockResolvedValue({
152 + _tag: "Success",
153 + value: { disabled: true },
154 + });
155 + commands.logout.mockReset().mockResolvedValue({
156 + _tag: "Success",
157 + value: { loggedOut: true },
158 + });
159 + dialogs.confirm.mockReset().mockResolvedValue(true);
160 + container = document.createElement("div");
161 + document.body.append(container);
162 + root = createRoot(container);
163 +});
164 +
165 +afterEach(async () => {
166 + await act(async () => root.unmount());
167 + container.remove();
168 + vi.unstubAllGlobals();
169 +});
170 +
171 +describe("AcpSessionManagementSection", () => {
172 + it("lists and imports native sessions through the owning environment", async () => {
173 + await render();
174 + await click("List sessions");
175 +
176 + expect(commands.list).toHaveBeenCalledWith({
177 + environmentId,
178 + input: { instanceId, projectId },
179 + });
180 + expect(container.textContent).toContain(session.title);
181 +
182 + await click("Import");
183 +
184 + expect(commands.import).toHaveBeenCalledWith({
185 + environmentId,
186 + input: {
187 + instanceId,
188 + projectId,
189 + sessionId: session.sessionId,
190 + title: session.title,
191 + updatedAt: session.updatedAt,
192 + },
193 + });
194 + expect(button("Imported").disabled).toBe(true);
195 + });
196 +
197 + it("logs out the provider instance through the owning environment", async () => {
198 + await render();
199 + await click("Log out");
200 +
201 + expect(commands.logout).toHaveBeenCalledWith({
202 + environmentId,
203 + input: { instanceId },
204 + });
205 + });
206 +
207 + it("deletes unimported native sessions after destructive confirmation", async () => {
208 + await render();
209 + await click("List sessions");
210 + await click("Delete");
211 +
212 + expect(dialogs.confirm).toHaveBeenCalledOnce();
213 + expect(commands.delete).toHaveBeenCalledWith({
214 + environmentId,
215 + input: { instanceId, projectId, sessionId: session.sessionId },
216 + });
217 + });
218 +
219 + it("locks the project picker while a project-scoped request is pending", async () => {
220 + const pending = deferred<{
221 + readonly _tag: "Success";
222 + readonly value: { readonly providers: [] };
223 + }>();
224 + commands.listProviders.mockReturnValueOnce(pending.promise);
225 + await render();
226 + const picker = () =>
227 + container.querySelector<HTMLElement>('[aria-label="Project for ACP sessions"]')!;
228 + expect(picker().hasAttribute("data-disabled")).toBe(false);
229 +
230 + await click("List providers");
231 +
232 + expect(picker().hasAttribute("data-disabled")).toBe(true);
233 + await act(async () => pending.resolve({ _tag: "Success", value: { providers: [] } }));
234 + expect(picker().hasAttribute("data-disabled")).toBe(false);
235 + });
236 +
237 + it("lists, saves, and disables configurable ACP providers", async () => {
238 + await render();
239 + await click("List providers");
240 +
241 + expect(commands.listProviders).toHaveBeenCalledWith({
242 + environmentId,
243 + input: { instanceId, projectId },
244 + });
245 + expect(
246 + container.querySelector<HTMLInputElement>('input[aria-label="google base URL"]')?.value,
247 + ).toBe("https://api.example.test/v1");
248 + await click("Save");
249 + expect(commands.setProvider).toHaveBeenCalledWith({
250 + environmentId,
251 + input: {
252 + instanceId,
253 + projectId,
254 + providerId: "google",
255 + apiType: "openai",
256 + baseUrl: "https://api.example.test/v1",
257 + },
258 + });
259 +
260 + await click("Disable");
261 + expect(commands.disableProvider).toHaveBeenCalledWith({
262 + environmentId,
263 + input: { instanceId, projectId, providerId: "google" },
264 + });
265 + });
266 +});
267 +
268 +it("imports with task access even when provider configuration is read-only", async () => {
269 + grants.scopes.delete("providers:manage");
270 + await render(true);
271 + await click("List sessions");
272 + await click("Import");
273 + expect(commands.import).toHaveBeenCalledOnce();
274 +});
275 +
276 +it("does not import with provider management alone", async () => {
277 + grants.scopes.delete("orchestration:operate");
278 + await render();
279 + await click("List sessions");
280 + expect(button("Import").disabled).toBe(true);
281 + await click("Import");
282 + expect(commands.import).not.toHaveBeenCalled();
283 +});
284 +
285 +it("rechecks task access after confirming deletion", async () => {
286 + await render();
287 + await click("List sessions");
288 + dialogs.confirm.mockImplementationOnce(async () => {
289 + grants.scopes.delete("orchestration:operate");
290 + return true;
291 + });
292 + await click("Delete");
293 + expect(commands.delete).not.toHaveBeenCalled();
294 +});
apps/web/src/components/settings/AcpSessionManagementSection.test.tsx deleted
-331
@@ -1,331 +0,0 @@
1 -import type { ReactElement } from "react";
2 -import {
3 - EnvironmentId,
4 - ProjectId,
5 - ProviderDriverKind,
6 - ProviderInstanceId,
7 - ThreadId,
8 - type ServerProvider,
9 -} from "@t3tools/contracts";
10 -import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
11 -
12 -import { visitElements } from "../../test/reactElementTree";
13 -import { reactHookHarness as hooks } from "../../test/reactHookHarness";
14 -
15 -const atoms = vi.hoisted(() => ({
16 - list: Symbol("list-acp-sessions"),
17 - import: Symbol("import-acp-session"),
18 - delete: Symbol("delete-acp-session"),
19 - listProviders: Symbol("list-acp-providers"),
20 - setProvider: Symbol("set-acp-provider"),
21 - disableProvider: Symbol("disable-acp-provider"),
22 - logout: Symbol("logout-acp"),
23 -}));
24 -
25 -const commands = vi.hoisted(() => ({
26 - list: vi.fn(),
27 - import: vi.fn(),
28 - delete: vi.fn(),
29 - listProviders: vi.fn(),
30 - setProvider: vi.fn(),
31 - disableProvider: vi.fn(),
32 - logout: vi.fn(),
33 -}));
34 -
35 -const grants = vi.hoisted(() => ({ scopes: new Set<string>() }));
36 -vi.mock("~/state/session", async (original) => ({
37 - ...(await original<typeof import("~/state/session")>()),
38 - useEnvironmentScope: (_id: unknown, scope: string) => grants.scopes.has(scope),
39 - readEnvironmentScope: (_id: unknown, scope: string) => grants.scopes.has(scope),
40 -}));
41 -const dialogs = vi.hoisted(() => ({ confirm: vi.fn() }));
42 -
43 -vi.mock("react", async (importOriginal) => {
44 - const actual = await importOriginal<typeof import("react")>();
45 - const { reactHookHarness } = await import("../../test/reactHookHarness");
46 - return {
47 - ...actual,
48 - useState: reactHookHarness.useState,
49 - };
50 -});
51 -
52 -vi.mock("react/compiler-runtime", async () => {
53 - const { reactHookHarness } = await import("../../test/reactHookHarness");
54 - return { c: reactHookHarness.useMemoCache };
55 -});
56 -
57 -vi.mock("../../state/server", () => ({
58 - serverEnvironment: {
59 - listAcpRegistrySessions: atoms.list,
60 - importAcpRegistrySession: atoms.import,
61 - deleteAcpRegistrySession: atoms.delete,
62 - listAcpRegistryProviders: atoms.listProviders,
63 - setAcpRegistryProvider: atoms.setProvider,
64 - disableAcpRegistryProvider: atoms.disableProvider,
65 - logoutAcpRegistry: atoms.logout,
66 - },
67 -}));
68 -
69 -vi.mock("../../state/use-atom-command", () => ({
70 - useAtomCommand: (atom: symbol) => {
71 - if (atom === atoms.list) return commands.list;
72 - if (atom === atoms.import) return commands.import;
73 - if (atom === atoms.delete) return commands.delete;
74 - if (atom === atoms.listProviders) return commands.listProviders;
75 - if (atom === atoms.setProvider) return commands.setProvider;
76 - if (atom === atoms.disableProvider) return commands.disableProvider;
77 - return commands.logout;
78 - },
79 -}));
80 -
81 -vi.mock("../../localApi", () => ({
82 - ensureLocalApi: () => ({ dialogs }),
83 -}));
84 -
85 -import { AcpSessionManagementSection } from "./AcpSessionManagementSection";
86 -
87 -const environmentId = EnvironmentId.make("remote-device");
88 -const instanceId = ProviderInstanceId.make("acpRegistry_antigravity");
89 -const projectId = ProjectId.make("project-antigravity");
90 -const session = {
91 - sessionId: "native-session-1",
92 - cwd: "/workspace/antigravity",
93 - additionalDirectories: [],
94 - title: "Native Antigravity session",
95 - updatedAt: "2026-08-23T00:00:00Z",
96 - importedThreadId: null,
97 -} as const;
98 -const provider = {
99 - instanceId,
100 - driver: ProviderDriverKind.make("acpRegistry"),
101 - enabled: true,
102 - installed: true,
103 - version: "1.0.0",
104 - status: "ready",
105 - auth: { status: "authenticated", canLogout: true },
106 - nativeSessions: { canList: true, canLoad: true, canResume: true, canDelete: true },
107 - configurableProviders: true,
108 - checkedAt: "2026-08-23T00:00:00.000Z",
109 - models: [],
110 - slashCommands: [],
111 - skills: [],
112 -} satisfies ServerProvider;
113 -
114 -function render(readOnly = false): ReactElement<Record<string, unknown>> {
115 - hooks.beginRender();
116 - return AcpSessionManagementSection({
117 - environmentId,
118 - instanceId,
119 - provider,
120 - projects: [{ id: projectId, title: "Antigravity", workspaceRoot: session.cwd }],
121 - readOnly,
122 - }) as ReactElement<Record<string, unknown>>;
123 -}
124 -
125 -function findByLabel(
126 - tree: ReactElement<Record<string, unknown>>,
127 - label: string,
128 -): ReactElement<Record<string, unknown>> {
129 - const found = visitElements(tree, (element) => element.props.children === label);
130 - expect(found).not.toBeNull();
131 - return found!;
132 -}
133 -
134 -function findByAriaLabel(
135 - tree: ReactElement<Record<string, unknown>>,
136 - label: string,
137 -): ReactElement<Record<string, unknown>> {
138 - const found = visitElements(tree, (element) => element.props["aria-label"] === label);
139 - expect(found).not.toBeNull();
140 - return found!;
141 -}
142 -
143 -async function flushPromises(): Promise<void> {
144 - await Promise.resolve();
145 - await Promise.resolve();
146 -}
147 -
148 -beforeEach(() => {
149 - hooks.reset();
150 - grants.scopes = new Set(["orchestration:read", "orchestration:operate", "providers:manage"]);
151 - commands.list.mockReset().mockResolvedValue({
152 - _tag: "Success",
153 - value: {
154 - sessions: [session],
155 - nextCursor: null,
156 - canLoad: true,
157 - canResume: true,
158 - canDelete: true,
159 - },
160 - });
161 - commands.import.mockReset().mockResolvedValue({
162 - _tag: "Success",
163 - value: { threadId: ThreadId.make("thread-imported"), imported: true },
164 - });
165 - commands.delete.mockReset().mockResolvedValue({
166 - _tag: "Success",
167 - value: { deleted: true },
168 - });
169 - commands.listProviders.mockReset().mockResolvedValue({
170 - _tag: "Success",
171 - value: {
172 - providers: [
173 - {
174 - providerId: "google",
175 - supported: ["openai"],
176 - required: false,
177 - current: { apiType: "openai", baseUrl: "https://api.example.test/v1" },
178 - },
179 - ],
180 - },
181 - });
182 - commands.setProvider.mockReset().mockResolvedValue({
183 - _tag: "Success",
184 - value: { configured: true },
185 - });
186 - commands.disableProvider.mockReset().mockResolvedValue({
187 - _tag: "Success",
188 - value: { disabled: true },
189 - });
190 - commands.logout.mockReset().mockResolvedValue({
191 - _tag: "Success",
192 - value: { loggedOut: true },
193 - });
194 - dialogs.confirm.mockReset().mockResolvedValue(true);
195 -});
196 -
197 -describe("AcpSessionManagementSection", () => {
198 - it("lists and imports native sessions through the owning environment", async () => {
199 - const initial = render();
200 - (findByLabel(initial, "List sessions").props.onClick as (() => void) | undefined)?.();
201 - await flushPromises();
202 -
203 - expect(commands.list).toHaveBeenCalledWith({
204 - environmentId,
205 - input: { instanceId, projectId },
206 - });
207 -
208 - const listed = render();
209 - (findByLabel(listed, "Import").props.onClick as (() => void) | undefined)?.();
210 - await flushPromises();
211 -
212 - expect(commands.import).toHaveBeenCalledWith({
213 - environmentId,
214 - input: {
215 - instanceId,
216 - projectId,
217 - sessionId: session.sessionId,
218 - title: session.title,
219 - updatedAt: session.updatedAt,
220 - },
221 - });
222 - expect(findByLabel(render(), "Imported")).not.toBeNull();
223 - });
224 -
225 - it("logs out the provider instance through the owning environment", async () => {
226 - const tree = render();
227 - (findByLabel(tree, "Log out").props.onClick as (() => void) | undefined)?.();
228 - await flushPromises();
229 -
230 - expect(commands.logout).toHaveBeenCalledWith({
231 - environmentId,
232 - input: { instanceId },
233 - });
234 - });
235 -
236 - it("deletes unimported native sessions after destructive confirmation", async () => {
237 - (findByLabel(render(), "List sessions").props.onClick as (() => void) | undefined)?.();
238 - await flushPromises();
239 - (findByLabel(render(), "Delete").props.onClick as (() => void) | undefined)?.();
240 - await flushPromises();
241 -
242 - expect(dialogs.confirm).toHaveBeenCalledOnce();
243 - expect(commands.delete).toHaveBeenCalledWith({
244 - environmentId,
245 - input: { instanceId, projectId, sessionId: session.sessionId },
246 - });
247 - });
248 -
249 - it("locks the project picker while a project-scoped request is pending", async () => {
250 - let resolveProviders!: (result: {
251 - readonly _tag: "Success";
252 - readonly value: { readonly providers: [] };
253 - }) => void;
254 - commands.listProviders.mockReturnValueOnce(
255 - new Promise((resolve) => {
256 - resolveProviders = resolve;
257 - }),
258 - );
259 - (findByLabel(render(), "List providers").props.onClick as (() => void) | undefined)?.();
260 -
261 - const projectSelect = visitElements(
262 - render(),
263 - (element) =>
264 - element.props.value === projectId && typeof element.props.onValueChange === "function",
265 - );
266 - expect(projectSelect?.props.disabled).toBe(true);
267 - resolveProviders({ _tag: "Success", value: { providers: [] } });
268 - await flushPromises();
269 - });
270 -
271 - it("lists, saves, and disables configurable ACP providers", async () => {
272 - (findByLabel(render(), "List providers").props.onClick as (() => void) | undefined)?.();
273 - await flushPromises();
274 -
275 - expect(commands.listProviders).toHaveBeenCalledWith({
276 - environmentId,
277 - input: { instanceId, projectId },
278 - });
279 - const providers = render();
280 - expect(findByAriaLabel(providers, "google protocol").props.size).toBe("sm");
281 - (findByLabel(providers, "Save").props.onClick as (() => void) | undefined)?.();
282 - await flushPromises();
283 - expect(commands.setProvider).toHaveBeenCalledWith({
284 - environmentId,
285 - input: {
286 - instanceId,
287 - projectId,
288 - providerId: "google",
289 - apiType: "openai",
290 - baseUrl: "https://api.example.test/v1",
291 - },
292 - });
293 -
294 - (findByLabel(render(), "Disable").props.onClick as (() => void) | undefined)?.();
295 - await flushPromises();
296 - expect(commands.disableProvider).toHaveBeenCalledWith({
297 - environmentId,
298 - input: { instanceId, projectId, providerId: "google" },
299 - });
300 - });
301 -});
302 -
303 -it("imports with task access even when provider configuration is read-only", async () => {
304 - grants.scopes.delete("providers:manage");
305 - (findByLabel(render(true), "List sessions").props.onClick as () => void)();
306 - await flushPromises();
307 - (findByLabel(render(true), "Import").props.onClick as () => void)();
308 - await flushPromises();
309 - expect(commands.import).toHaveBeenCalledOnce();
310 -});
311 -
312 -it("does not import with provider management alone", async () => {
313 - grants.scopes.delete("orchestration:operate");
314 - (findByLabel(render(), "List sessions").props.onClick as () => void)();
315 - await flushPromises();
316 - (findByLabel(render(), "Import").props.onClick as () => void)();
317 - await flushPromises();
318 - expect(commands.import).not.toHaveBeenCalled();
319 -});
320 -
321 -it("rechecks task access after confirming deletion", async () => {
322 - (findByLabel(render(), "List sessions").props.onClick as () => void)();
323 - await flushPromises();
324 - dialogs.confirm.mockImplementationOnce(async () => {
325 - grants.scopes.delete("orchestration:operate");
326 - return true;
327 - });
328 - (findByLabel(render(), "Delete").props.onClick as () => void)();
329 - await flushPromises();
330 - expect(commands.delete).not.toHaveBeenCalled();
331 -});
apps/web/src/components/settings/AddProviderInstanceDialog.environment.browser.test.tsx new
+357
@@ -0,0 +1,357 @@
1 +import { EnvironmentId, ProviderDriverKind, type AcpRegistrySearchAgent } from "@t3tools/contracts";
2 +import { act } from "react";
3 +import { createRoot, type Root } from "react-dom/client";
4 +import { userEvent } from "vite-plus/test/browser";
5 +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
6 +
7 +const actions = vi.hoisted(() => ({
8 + toast: vi.fn(),
9 + onOpenChange: vi.fn(),
10 + canManageProviders: true,
11 +}));
12 +const settingsHooks = vi.hoisted(() => ({
13 + read: vi.fn(() => ({ providerInstances: {} })),
14 + mutate: vi.fn(),
15 + useMutation: vi.fn(),
16 +}));
17 +const preparedAgent = vi.hoisted((): AcpRegistrySearchAgent => ({
18 + id: "kilo",
19 + name: "Kilo Code",
20 + version: "4.2.0",
21 + description: "Kilo ACP agent",
22 + authors: ["Kilo"],
23 + license: "Apache-2.0",
24 + website: null,
25 + repository: null,
26 + icon: "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg",
27 + distribution: "binary",
28 + integrity: "sha256",
29 +}));
30 +
31 +vi.mock(import("@t3tools/client-runtime/state/runtime"), async (original) => ({
32 + ...(await original()),
33 + squashAtomCommandFailure: () => new Error("The settings update failed."),
34 +}));
35 +vi.mock(import("../../hooks/useSettings"), async (original) => ({
36 + ...(await original()),
37 + useEnvironmentSettings: settingsHooks.read as never,
38 + usePersistEnvironmentProviderInstanceMutation: settingsHooks.useMutation as never,
39 +}));
40 +vi.mock(import("../../state/session"), async (original) => {
41 + const hasScope = (environmentId: EnvironmentId, scope: string) =>
42 + environmentId === "remote-device" && scope === "providers:manage" && actions.canManageProviders;
43 + return {
44 + ...(await original()),
45 + useEnvironmentScope: hasScope as never,
46 + readEnvironmentScope: hasScope as never,
47 + };
48 +});
49 +vi.mock(import("../ui/toast"), async (original) => {
50 + const actual = await original();
51 + return { ...actual, toastManager: { ...actual.toastManager, add: actions.toast } };
52 +});
53 +// The registry search and the sign-in step talk to the environment over RPC; these
54 +// stand-ins expose the choices a user makes there.
55 +vi.mock(import("./AcpRegistrySearchStep"), async (original) => ({
56 + ...(await original()),
57 + AcpRegistrySearchStep: ((props: {
58 + onPrepared: (agent: AcpRegistrySearchAgent) => void;
59 + onManualConfiguration: () => void;
60 + onLocalConfiguration: () => void;
61 + }) => (
62 + <div>
63 + <button type="button" onClick={() => props.onPrepared(preparedAgent)}>
64 + Use Kilo Code
65 + </button>
66 + <button type="button" onClick={props.onManualConfiguration}>
67 + Enter registry agent
68 + </button>
69 + <button type="button" onClick={props.onLocalConfiguration}>
70 + Use local command
71 + </button>
72 + </div>
73 + )) as never,
74 +}));
75 +vi.mock(import("./ProviderWizardAuthenticationStep"), async (original) => ({
76 + ...(await original()),
77 + ProviderWizardAuthenticationStep: (props: {
78 + environmentId: string;
79 + instanceId: string;
80 + onFinish: () => void;
81 + }) => (
82 + <section aria-label="Sign-in step">
83 + {props.environmentId}/{props.instanceId}
84 + <button type="button" onClick={props.onFinish}>
85 + Finish sign-in
86 + </button>
87 + </section>
88 + ),
89 +}));
90 +
91 +import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog";
92 +
93 +const remoteEnvironmentId = EnvironmentId.make("remote-device");
94 +
95 +function deferred<T>() {
96 + let resolve!: (value: T) => void;
97 + const promise = new Promise<T>((done) => {
98 + resolve = done;
99 + });
100 + return { promise, resolve };
101 +}
102 +
103 +let root: Root;
104 +
105 +function render(onOpenChange = actions.onOpenChange) {
106 + return act(async () =>
107 + root.render(
108 + <AddProviderInstanceDialog
109 + open
110 + environmentId={remoteEnvironmentId}
111 + environmentLabel="Remote device"
112 + onOpenChange={onOpenChange}
113 + />,
114 + ),
115 + );
116 +}
117 +function button(label: string) {
118 + const found = [...document.querySelectorAll("button")].find(
119 + (element) => element.textContent?.trim() === label,
120 + );
121 + expect(found, `button ${label}`).toBeDefined();
122 + return found!;
123 +}
124 +const click = (label: string) => act(async () => button(label).click());
125 +const input = (selector: string) => {
126 + const found = document.querySelector<HTMLInputElement>(selector);
127 + expect(found, selector).not.toBeNull();
128 + return found!;
129 +};
130 +async function type(selector: string, value: string) {
131 + await act(async () => userEvent.fill(input(selector), value));
132 + await act(async () => input(selector).blur());
133 +}
134 +const signInStep = () => document.querySelector('[aria-label="Sign-in step"]');
135 +
136 +async function prepareCodexInstance() {
137 + await render();
138 + await click("Configure manually");
139 + await type("#add-provider-label", "Work");
140 + await click("Next");
141 +}
142 +
143 +describe("AddProviderInstanceDialog environment routing", () => {
144 + beforeEach(() => {
145 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
146 + actions.canManageProviders = true;
147 + actions.toast.mockReset();
148 + actions.onOpenChange.mockReset();
149 + settingsHooks.read.mockReset().mockReturnValue({ providerInstances: {} });
150 + settingsHooks.mutate.mockReset().mockResolvedValue({ _tag: "Success", value: {} });
151 + settingsHooks.useMutation.mockReset().mockReturnValue(settingsHooks.mutate);
152 + root = createRoot(document.createElement("div"));
153 + });
154 + afterEach(async () => {
155 + await act(async () => root.unmount());
156 + vi.unstubAllGlobals();
157 + });
158 +
159 + it("creates a provider with its default identity without typing", async () => {
160 + await render();
161 + const grok = [...document.querySelectorAll('[role="radio"]')].find((radio) =>
162 + radio.textContent?.includes("Grok"),
163 + ) as HTMLElement;
164 + await act(async () => grok.click());
165 + await click("Next");
166 + await click("Next");
167 + await click("Add instance");
168 + expect(settingsHooks.mutate).toHaveBeenCalledWith({
169 + operation: "create",
170 + instanceId: "grok",
171 + instance: { driver: "grok", enabled: true, displayName: "Grok" },
172 + });
173 + });
174 +
175 + it("chooses an unused identity for another account without replacing configured instances", async () => {
176 + settingsHooks.read.mockReturnValue({
177 + providerInstances: { codex_2: { driver: "codex", enabled: false } },
178 + });
179 + await render();
180 + await click("Configure manually");
181 + await click("Next");
182 + await click("Add instance");
183 + expect(settingsHooks.mutate).toHaveBeenCalledWith({
184 + operation: "create",
185 + instanceId: "codex_3",
186 + instance: {
187 + driver: "codex",
188 + enabled: true,
189 + displayName: "Codex",
190 + config: { setupMode: "existing" },
191 + },
192 + });
193 + });
194 +
195 + it("reads and writes settings through the supplied environment", async () => {
196 + await render();
197 +
198 + expect(settingsHooks.read).toHaveBeenCalledWith(remoteEnvironmentId);
199 + expect(settingsHooks.useMutation).toHaveBeenCalledWith(remoteEnvironmentId);
200 + });
201 +
202 + it("awaits an atomic create before closing and retains prepared ACP metadata", async () => {
203 + const mutation = deferred<{ readonly _tag: "Success"; readonly value: unknown }>();
204 + settingsHooks.mutate.mockReturnValueOnce(mutation.promise);
205 + await render();
206 + await click("Use Kilo Code");
207 +
208 + expect(document.body.textContent).toContain("v4.2.0 · binary");
209 + await click("Continue to sign-in");
210 + expect(settingsHooks.mutate).toHaveBeenCalledWith({
211 + operation: "create",
212 + instanceId: "acpRegistry_kilo_code",
213 + instance: {
214 + driver: ProviderDriverKind.make("acpRegistry"),
215 + enabled: true,
216 + displayName: "Kilo Code",
217 + config: {
218 + agentId: "kilo",
219 + distribution: "auto",
220 + registryIconUrl: "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg",
221 + },
222 + },
223 + });
224 + expect(signInStep()).toBeNull();
225 +
226 + await act(async () => mutation.resolve({ _tag: "Success", value: {} }));
227 + expect(actions.onOpenChange).not.toHaveBeenCalled();
228 + expect(signInStep()?.textContent).toContain("remote-device/acpRegistry_kilo_code");
229 + expect(settingsHooks.mutate).toHaveBeenCalledTimes(1);
230 + await click("Finish sign-in");
231 + expect(actions.onOpenChange).toHaveBeenCalledWith(false);
232 + });
233 +
234 + it("configures a manually entered registry agent from the first provider screen", async () => {
235 + await render();
236 + await click("Enter registry agent");
237 + await type("#add-provider-acpRegistry-manual-agentId", "devin");
238 + await click("Next");
239 + await click("Continue to sign-in");
240 + expect(settingsHooks.mutate).toHaveBeenCalledWith({
241 + operation: "create",
242 + instanceId: "acpRegistry_custom",
243 + instance: {
244 + driver: "acpRegistry",
245 + enabled: true,
246 + config: { agentId: "devin" },
247 + },
248 + });
249 + expect(signInStep()).not.toBeNull();
250 + });
251 +
252 + it("creates a local command in the selected environment without a sign-in step", async () => {
253 + await render();
254 + await click("Use local command");
255 + await click("Next");
256 + expect(document.body.textContent).toContain("Executable is required.");
257 + expect(settingsHooks.mutate).not.toHaveBeenCalled();
258 +
259 + await type("#add-provider-acpRegistry-manual-commandPath", "dsh");
260 + const commandArgs = ["--profile", "acp", " literal $(value) ; ", ""];
261 + for (const [index, argument] of commandArgs.entries()) {
262 + await click("Add argument");
263 + if (argument) await type(`input[aria-label="Argument ${index + 1}"]`, argument);
264 + }
265 + await click("Add variable");
266 + await type('input[aria-label="Environment variable name 1"]', "DSH_PROFILE");
267 + await act(async () =>
268 + document
269 + .querySelector<HTMLButtonElement>(
270 + 'button[aria-label="Mark environment variable DSH_PROFILE as sensitive"]',
271 + )!
272 + .click(),
273 + );
274 + await type('input[aria-label="Environment variable value 1"]', "work");
275 + await click("Next");
276 + await type("#add-provider-label", "Deepseek Harness");
277 + await click("Add instance");
278 +
279 + expect(settingsHooks.useMutation).toHaveBeenCalledWith(remoteEnvironmentId);
280 + expect(settingsHooks.mutate).toHaveBeenCalledWith({
281 + operation: "create",
282 + instanceId: "acpRegistry_deepseek_harness",
283 + instance: {
284 + driver: "acpRegistry",
285 + enabled: true,
286 + displayName: "Deepseek Harness",
287 + config: { source: "local", commandPath: "dsh", commandArgs },
288 + environment: [
289 + expect.objectContaining({ name: "DSH_PROFILE", value: "work", sensitive: false }),
290 + ],
291 + },
292 + });
293 + expect(actions.onOpenChange).toHaveBeenCalledWith(false);
294 + expect(signInStep()).toBeNull();
295 + });
296 +
297 + it("keeps the dialog open when the atomic upsert fails", async () => {
298 + settingsHooks.mutate.mockResolvedValueOnce({ _tag: "Failure", cause: new Error("Conflict") });
299 + await render();
300 + await click("Use Kilo Code");
301 + await click("Continue to sign-in");
302 +
303 + expect(actions.onOpenChange).not.toHaveBeenCalled();
304 + expect(actions.toast).toHaveBeenCalledWith(
305 + expect.objectContaining({ type: "error", title: "Could not add provider instance" }),
306 + );
307 + expect(button("Continue to sign-in").disabled).toBe(false);
308 + });
309 +
310 + it("adds an instance with the selected environment's provider grant alone", async () => {
311 + await prepareCodexInstance();
312 + await click("Add instance");
313 +
314 + expect(settingsHooks.mutate).toHaveBeenCalledWith({
315 + operation: "create",
316 + instanceId: "codex_work",
317 + instance: {
318 + driver: "codex",
319 + enabled: true,
320 + displayName: "Work",
321 + config: { setupMode: "existing" },
322 + },
323 + });
324 + expect(actions.toast).toHaveBeenCalledWith(
325 + expect.objectContaining({ type: "success", title: "Provider instance added" }),
326 + );
327 + expect(actions.onOpenChange).toHaveBeenCalledWith(false);
328 + });
329 +
330 + it("rejects a queued save after the provider grant is revoked", async () => {
331 + await prepareCodexInstance();
332 + const save = button("Add instance");
333 + actions.canManageProviders = false;
334 + // The rendered button is still enabled; the click must recheck the live grant.
335 + await act(async () => save.click());
336 +
337 + expect(settingsHooks.mutate).not.toHaveBeenCalled();
338 + expect(actions.toast).not.toHaveBeenCalled();
339 + expect(actions.onOpenChange).not.toHaveBeenCalled();
340 + await render();
341 + expect(button("Add instance").disabled).toBe(true);
342 + });
343 +
344 + it("keeps a denied draft available when the provider grant arrives", async () => {
345 + actions.canManageProviders = false;
346 + await prepareCodexInstance();
347 + expect(button("Add instance").disabled).toBe(true);
348 + expect(settingsHooks.mutate).not.toHaveBeenCalled();
349 +
350 + actions.canManageProviders = true;
351 + await render();
352 + expect(button("Add instance").disabled).toBe(false);
353 + await click("Add instance");
354 + expect(settingsHooks.mutate).toHaveBeenCalledOnce();
355 + expect(actions.onOpenChange).toHaveBeenCalledWith(false);
356 + });
357 +});
apps/web/src/components/settings/AddProviderInstanceDialog.environment.test.tsx deleted
-424
@@ -1,424 +0,0 @@
1 -import { EnvironmentId, ProviderDriverKind, type AcpRegistrySearchAgent } from "@t3tools/contracts";
2 -import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
3 -
4 -import { visitElements } from "../../test/reactElementTree";
5 -import { reactHookHarness as hooks } from "../../test/reactHookHarness";
6 -
7 -const actions = vi.hoisted(() => ({
8 - update: vi.fn(),
9 - toast: vi.fn(),
10 - onOpenChange: vi.fn(),
11 - canManageProviders: true,
12 -}));
13 -
14 -const settingsHooks = vi.hoisted(() => ({
15 - read: vi.fn(() => ({ providerInstances: {} })),
16 - mutate: vi.fn(),
17 - useMutation: vi.fn(),
18 -}));
19 -
20 -vi.mock("react", async (importOriginal) => {
21 - const actual = await importOriginal<typeof import("react")>();
22 - const { reactHookHarness } = await import("../../test/reactHookHarness");
23 - return {
24 - ...actual,
25 - useMemo: reactHookHarness.useMemo,
26 - useState: reactHookHarness.useState,
27 - };
28 -});
29 -
30 -vi.mock("react/compiler-runtime", async () => {
31 - const { reactHookHarness } = await import("../../test/reactHookHarness");
32 - return { c: reactHookHarness.useMemoCache };
33 -});
34 -
35 -vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => ({
36 - ...(await importOriginal<typeof import("@t3tools/client-runtime/state/runtime")>()),
37 - squashAtomCommandFailure: () => new Error("The settings update failed."),
38 -}));
39 -
40 -vi.mock("../../hooks/useSettings", () => ({
41 - useEnvironmentSettings: settingsHooks.read,
42 - usePersistEnvironmentProviderInstanceMutation: settingsHooks.useMutation,
43 -}));
44 -
45 -vi.mock("../../state/session", async (importOriginal) => {
46 - const actual = await importOriginal<typeof import("../../state/session")>();
47 - const hasScope = (environmentId: EnvironmentId, scope: string) =>
48 - environmentId === "remote-device" && scope === "providers:manage" && actions.canManageProviders;
49 - return { ...actual, useEnvironmentScope: hasScope, readEnvironmentScope: hasScope };
50 -});
51 -
52 -vi.mock("../ui/toast", () => ({ toastManager: { add: actions.toast } }));
53 -
54 -import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog";
55 -
56 -const remoteEnvironmentId = EnvironmentId.make("remote-device");
57 -const preparedAgent: AcpRegistrySearchAgent = {
58 - id: "kilo",
59 - name: "Kilo Code",
60 - version: "4.2.0",
61 - description: "Kilo ACP agent",
62 - authors: ["Kilo"],
63 - license: "Apache-2.0",
64 - website: null,
65 - repository: null,
66 - icon: "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg",
67 - distribution: "binary",
68 - integrity: "sha256",
69 -};
70 -
71 -function render(onOpenChange = vi.fn()) {
72 - hooks.beginRender();
73 - return AddProviderInstanceDialog({
74 - open: true,
75 - environmentId: remoteEnvironmentId,
76 - environmentLabel: "Remote device",
77 - onOpenChange,
78 - });
79 -}
80 -
81 -function findByChildren(tree: ReturnType<typeof render>, children: string) {
82 - const result = visitElements(tree, (element) => element.props.children === children);
83 - expect(result).not.toBeNull();
84 - return result!;
85 -}
86 -
87 -async function selectPreparedAcp() {
88 - const searchStep = render();
89 - const search = visitElements(
90 - searchStep,
91 - (element) =>
92 - typeof element.type === "function" && element.type.name === "AcpRegistrySearchStep",
93 - );
94 - expect(search).not.toBeNull();
95 - (search?.props.onPrepared as ((agent: AcpRegistrySearchAgent) => void) | undefined)?.(
96 - preparedAgent,
97 - );
98 -}
99 -
100 -function renderDialog() {
101 - hooks.beginRender();
102 - return AddProviderInstanceDialog({
103 - open: true,
104 - environmentId: remoteEnvironmentId,
105 - environmentLabel: "Remote device",
106 - onOpenChange: actions.onOpenChange,
107 - });
108 -}
109 -
110 -function button(dialog: unknown, label: string) {
111 - const element = visitElements(
112 - dialog,
113 - (entry) => entry.props.children === label && typeof entry.props.onClick === "function",
114 - );
115 - if (!element) throw new Error(`Missing button: ${label}`);
116 - return element;
117 -}
118 -
119 -function prepareInstance() {
120 - let dialog = renderDialog();
121 - (button(dialog, "Configure manually").props.onClick as () => void)();
122 - dialog = renderDialog();
123 - const label = visitElements(dialog, (entry) => entry.props.placeholder === "e.g. Work");
124 - if (!label) throw new Error("Missing instance label input.");
125 - (label.props.onChange as (event: { target: { value: string } }) => void)({
126 - target: { value: "Work" },
127 - });
128 - dialog = renderDialog();
129 - (button(dialog, "Next").props.onClick as () => void)();
130 - return renderDialog();
131 -}
132 -
133 -describe("AddProviderInstanceDialog environment routing", () => {
134 - beforeEach(() => {
135 - hooks.reset();
136 - actions.canManageProviders = true;
137 - actions.toast.mockReset();
138 - actions.onOpenChange.mockReset();
139 - settingsHooks.read.mockReset().mockReturnValue({ providerInstances: {} });
140 - settingsHooks.mutate.mockReset().mockResolvedValue({ _tag: "Success", value: {} });
141 - settingsHooks.useMutation.mockReset().mockReturnValue(settingsHooks.mutate);
142 - });
143 -
144 - it("creates a provider with its default identity without typing", async () => {
145 - let tree = render();
146 - const group = visitElements(
147 - tree,
148 - (element) => element.props["aria-labelledby"] === "add-instance-driver-label",
149 - );
150 - (group!.props.onValueChange as (value: string) => void)("grok");
151 - tree = render();
152 - (findByChildren(tree, "Next").props.onClick as () => void)();
153 - tree = render();
154 - (findByChildren(tree, "Next").props.onClick as () => void)();
155 - tree = render();
156 - (findByChildren(tree, "Add instance").props.onClick as () => void)();
157 - await Promise.resolve();
158 - expect(settingsHooks.mutate).toHaveBeenCalledWith({
159 - operation: "create",
160 - instanceId: "grok",
161 - instance: { driver: "grok", enabled: true, displayName: "Grok" },
162 - });
163 - });
164 -
165 - it("chooses an unused identity for another account without replacing configured instances", async () => {
166 - settingsHooks.read.mockReturnValue({
167 - providerInstances: {
168 - codex_2: { driver: "codex", enabled: false },
169 - },
170 - });
171 - let tree = render();
172 - (findByChildren(tree, "Configure manually").props.onClick as () => void)();
173 - tree = render();
174 - (findByChildren(tree, "Next").props.onClick as () => void)();
175 - tree = render();
176 - (findByChildren(tree, "Add instance").props.onClick as () => void)();
177 - await Promise.resolve();
178 - expect(settingsHooks.mutate).toHaveBeenCalledWith({
179 - operation: "create",
180 - instanceId: "codex_3",
181 - instance: {
182 - driver: "codex",
183 - enabled: true,
184 - displayName: "Codex",
185 - config: { setupMode: "existing" },
186 - },
187 - });
188 - });
189 -
190 - it("reads and writes settings through the supplied environment", () => {
191 - render();
192 -
193 - expect(settingsHooks.read).toHaveBeenCalledWith(remoteEnvironmentId);
194 - expect(settingsHooks.useMutation).toHaveBeenCalledWith(remoteEnvironmentId);
195 - });
196 -
197 - it("awaits an atomic create before closing and retains prepared ACP metadata", async () => {
198 - const onOpenChange = vi.fn();
199 - let resolveMutation!: (value: { readonly _tag: "Success"; readonly value: unknown }) => void;
200 - settingsHooks.mutate.mockReturnValueOnce(
201 - new Promise((resolve) => {
202 - resolveMutation = resolve;
203 - }),
204 - );
205 - await selectPreparedAcp();
206 -
207 - const identityStep = render(onOpenChange);
208 - expect(
209 - visitElements(identityStep, (element) => {
210 - const content = JSON.stringify(element.props.children);
211 - return content?.includes("4.2.0") === true && content.includes("binary");
212 - }),
213 - ).not.toBeNull();
214 - (
215 - findByChildren(identityStep, "Continue to sign-in").props.onClick as (() => void) | undefined
216 - )?.();
217 - expect(settingsHooks.mutate).toHaveBeenCalledWith({
218 - operation: "create",
219 - instanceId: "acpRegistry_kilo_code",
220 - instance: {
221 - driver: ProviderDriverKind.make("acpRegistry"),
222 - enabled: true,
223 - displayName: "Kilo Code",
224 - config: {
225 - agentId: "kilo",
226 - distribution: "auto",
227 - registryIconUrl: "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg",
228 - },
229 - },
230 - });
231 - expect(onOpenChange).not.toHaveBeenCalled();
232 -
233 - resolveMutation({ _tag: "Success", value: {} });
234 - await Promise.resolve();
235 - await Promise.resolve();
236 - expect(onOpenChange).not.toHaveBeenCalled();
237 - const signInStep = render(onOpenChange);
238 - const authentication = visitElements(
239 - signInStep,
240 - (element) =>
241 - typeof element.type === "function" &&
242 - element.type.name === "ProviderWizardAuthenticationStep",
243 - );
244 - expect(authentication?.props.instanceId).toBe("acpRegistry_kilo_code");
245 - expect(authentication?.props.environmentId).toBe(remoteEnvironmentId);
246 - expect(settingsHooks.mutate).toHaveBeenCalledTimes(1);
247 - (authentication!.props.onFinish as () => void)();
248 - expect(onOpenChange).toHaveBeenCalledWith(false);
249 - });
250 -
251 - it("configures a manually entered registry agent from the first provider screen", async () => {
252 - let tree = render();
253 - const search = visitElements(
254 - tree,
255 - (element) =>
256 - typeof element.type === "function" && element.type.name === "AcpRegistrySearchStep",
257 - );
258 - (search!.props.onManualConfiguration as () => void)();
259 - tree = render();
260 - const configuration = visitElements(
261 - tree,
262 - (element) => element.props.idPrefix === "add-provider-acpRegistry-manual",
263 - );
264 - (configuration!.props.onChange as (value: Record<string, unknown>) => void)({
265 - agentId: "devin",
266 - });
267 - tree = render();
268 - (findByChildren(tree, "Next").props.onClick as () => void)();
269 - tree = render();
270 - (findByChildren(tree, "Continue to sign-in").props.onClick as () => void)();
271 - await Promise.resolve();
272 - await Promise.resolve();
273 - expect(settingsHooks.mutate).toHaveBeenCalledWith({
274 - operation: "create",
275 - instanceId: "acpRegistry_custom",
276 - instance: {
277 - driver: "acpRegistry",
278 - enabled: true,
279 - config: { agentId: "devin" },
280 - },
281 - });
282 - tree = render();
283 - expect(
284 - visitElements(
285 - tree,
286 - (element) =>
287 - typeof element.type === "function" &&
288 - element.type.name === "ProviderWizardAuthenticationStep",
289 - ),
290 - ).not.toBeNull();
291 - });
292 -
293 - it("creates a local command in the selected environment without a sign-in step", async () => {
294 - const onOpenChange = vi.fn();
295 - let tree = render(onOpenChange);
296 - const search = visitElements(
297 - tree,
298 - (element) =>
299 - typeof element.type === "function" && element.type.name === "AcpRegistrySearchStep",
300 - );
301 - (search!.props.onLocalConfiguration as () => void)();
302 - tree = render(onOpenChange);
303 - (findByChildren(tree, "Next").props.onClick as () => void)();
304 - tree = render(onOpenChange);
305 - expect(findByChildren(tree, "Executable is required.")).not.toBeNull();
306 - expect(settingsHooks.mutate).not.toHaveBeenCalled();
307 -
308 - const configuration = visitElements(
309 - tree,
310 - (element) => element.props.idPrefix === "add-provider-acpRegistry-manual",
311 - );
312 - const commandArgs = ["--profile", "acp", " literal $(value) ; ", ""];
313 - (configuration!.props.onChange as (value: Record<string, unknown>) => void)({
314 - source: "local",
315 - commandPath: "dsh",
316 - commandArgs,
317 - });
318 - const environmentEditor = visitElements(
319 - tree,
320 - (element) =>
321 - typeof element.type === "function" && element.type.name === "ProviderEnvironmentSection",
322 - );
323 - const environment = [{ name: "DSH_PROFILE", value: "work", sensitive: false }];
324 - (environmentEditor!.props.onChange as (value: typeof environment) => void)(environment);
325 - tree = render(onOpenChange);
326 - (findByChildren(tree, "Next").props.onClick as () => void)();
327 - tree = render(onOpenChange);
328 - const label = visitElements(tree, (element) => element.props.id === "add-provider-label");
329 - (label!.props.onChange as (event: { target: { value: string } }) => void)({
330 - target: { value: "Deepseek Harness" },
331 - });
332 - tree = render(onOpenChange);
333 - (findByChildren(tree, "Add instance").props.onClick as () => void)();
334 - await Promise.resolve();
335 - await Promise.resolve();
336 -
337 - expect(settingsHooks.useMutation).toHaveBeenCalledWith(remoteEnvironmentId);
338 - expect(settingsHooks.mutate).toHaveBeenCalledWith({
339 - operation: "create",
340 - instanceId: "acpRegistry_deepseek_harness",
341 - instance: {
342 - driver: "acpRegistry",
343 - enabled: true,
344 - displayName: "Deepseek Harness",
345 - config: { source: "local", commandPath: "dsh", commandArgs },
346 - environment,
347 - },
348 - });
349 - expect(onOpenChange).toHaveBeenCalledWith(false);
350 - tree = render(onOpenChange);
351 - expect(
352 - visitElements(
353 - tree,
354 - (element) =>
355 - typeof element.type === "function" &&
356 - element.type.name === "ProviderWizardAuthenticationStep",
357 - ),
358 - ).toBeNull();
359 - });
360 -
361 - it("keeps the dialog open when the atomic upsert fails", async () => {
362 - settingsHooks.mutate.mockResolvedValueOnce({ _tag: "Failure", cause: new Error("Conflict") });
363 - const onOpenChange = vi.fn();
364 - await selectPreparedAcp();
365 -
366 - const identityStep = render(onOpenChange);
367 - (
368 - findByChildren(identityStep, "Continue to sign-in").props.onClick as (() => void) | undefined
369 - )?.();
370 - await Promise.resolve();
371 - await Promise.resolve();
372 -
373 - expect(onOpenChange).not.toHaveBeenCalled();
374 - });
375 -
376 - it("adds an instance with the selected environment's provider grant alone", async () => {
377 - const dialog = prepareInstance();
378 - (button(dialog, "Add instance").props.onClick as () => void)();
379 -
380 - await Promise.resolve();
381 - expect(settingsHooks.mutate).toHaveBeenCalledWith({
382 - operation: "create",
383 - instanceId: "codex_work",
384 - instance: {
385 - driver: "codex",
386 - enabled: true,
387 - displayName: "Work",
388 - config: { setupMode: "existing" },
389 - },
390 - });
391 - expect(actions.toast).toHaveBeenCalledWith(
392 - expect.objectContaining({ type: "success", title: "Provider instance added" }),
393 - );
394 - expect(actions.onOpenChange).toHaveBeenCalledWith(false);
395 - });
396 -
397 - it("rejects a queued save after the provider grant is revoked", () => {
398 - const dialog = prepareInstance();
399 - const save = button(dialog, "Add instance").props.onClick as () => void;
400 - actions.canManageProviders = false;
401 - save();
402 -
403 - expect(settingsHooks.mutate).not.toHaveBeenCalled();
404 - expect(actions.toast).not.toHaveBeenCalled();
405 - expect(actions.onOpenChange).not.toHaveBeenCalled();
406 - expect(button(renderDialog(), "Add instance").props.disabled).toBe(true);
407 - });
408 -
409 - it("keeps a denied draft available when the provider grant arrives", async () => {
410 - actions.canManageProviders = false;
411 - let dialog = prepareInstance();
412 - (button(dialog, "Add instance").props.onClick as () => void)();
413 - expect(settingsHooks.mutate).not.toHaveBeenCalled();
414 - expect(actions.toast).not.toHaveBeenCalled();
415 -
416 - actions.canManageProviders = true;
417 - dialog = renderDialog();
418 - expect(button(dialog, "Add instance").props.disabled).toBe(false);
419 - (button(dialog, "Add instance").props.onClick as () => void)();
420 - await Promise.resolve();
421 - expect(settingsHooks.mutate).toHaveBeenCalledOnce();
422 - expect(actions.onOpenChange).toHaveBeenCalledWith(false);
423 - });
424 -});
apps/web/src/components/settings/CaptureShortcutConfig.browser.test.tsx new
+263
@@ -0,0 +1,263 @@
1 +import {
2 + DEFAULT_CLIENT_SETTINGS,
3 + type DesktopCaptureConfigPreview,
4 + type DesktopSnapShotState,
5 +} from "@t3tools/contracts";
6 +import { act } from "react";
7 +import { createRoot, type Root } from "react-dom/client";
8 +import { userEvent } from "vite-plus/test/browser";
9 +import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
10 +
11 +const bridge = vi.hoisted(() => ({
12 + previewSnapShotConfig: vi.fn(),
13 + applySnapShotConfig: vi.fn(),
14 + setSnapShotShortcutSuppressed: vi.fn(),
15 +}));
16 +const toast = vi.hoisted(() => vi.fn());
17 +vi.mock(import("../../lib/desktopSnapShot"), async (original) => ({
18 + ...(await original()),
19 + getDesktopSnapShotBridge: () => bridge as never,
20 +}));
21 +vi.mock(import("../ui/toast"), async (original) => {
22 + const actual = await original();
23 + return { ...actual, toastManager: { ...actual.toastManager, add: toast } };
24 +});
25 +
26 +import { CaptureShortcutConfig } from "./CaptureShortcutConfig";
27 +
28 +const preview: DesktopCaptureConfigPreview = {
29 + id: "approved-snapshot",
30 + path: "/config/niri/config.kdl",
31 + resolvedPath: "/config/niri/config.kdl",
32 + before: "binds {\n}\n",
33 + after: 'binds {\n Ctrl+Shift+2 { spawn "gdbus"; }\n}\n',
34 + shortcut: "Ctrl+Shift+2",
35 + operation: "install",
36 +};
37 +const complete = vi.fn<() => Promise<void>>();
38 +
39 +function deferred<T>() {
40 + let resolve!: (value: T) => void;
41 + const promise = new Promise<T>((done) => {
42 + resolve = done;
43 + });
44 + return { promise, resolve };
45 +}
46 +
47 +let root: Root;
48 +let container: HTMLDivElement;
49 +
50 +async function render(desktop: "niri" | "hyprland" = "niri") {
51 + const state: DesktopSnapShotState = {
52 + mode: "portal",
53 + linuxBackend: desktop,
54 + shortcut: DEFAULT_CLIENT_SETTINGS.snapShotShortcut,
55 + shortcutRegistered: false,
56 + shortcutActionRegistered: true,
57 + shortcutMessage: null,
58 + message: null,
59 + shortcutConfigPath: preview.path,
60 + shortcutBinding: "manual binding",
61 + };
62 + await act(async () => root.render(<CaptureShortcutConfig state={state} onComplete={complete} />));
63 +}
64 +function button(label: string) {
65 + return [...container.querySelectorAll("button")].find((element) => element.textContent === label);
66 +}
67 +async function click(label: string) {
68 + const target = button(label);
69 + expect(target, `button ${label}`).toBeDefined();
70 + await act(async () => target!.click());
71 +}
72 +const recorder = () => container.querySelector<HTMLButtonElement>("[data-keybinding-capture]")!;
73 +const diff = () => container.querySelector('[aria-label="Shortcut changes"]');
74 +const alert = () => container.querySelector('[role="alert"]');
75 +const advanced = () => container.querySelector("details")!;
76 +async function recordKeys(keys: string) {
77 + await act(async () => userEvent.click(recorder()));
78 + await act(async () => userEvent.keyboard(keys));
79 +}
80 +
81 +beforeEach(() => {
82 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
83 + Object.defineProperty(navigator, "platform", { configurable: true, get: () => "Linux" });
84 + bridge.setSnapShotShortcutSuppressed.mockReset().mockResolvedValue(undefined);
85 + bridge.previewSnapShotConfig.mockReset().mockResolvedValue(preview);
86 + bridge.applySnapShotConfig
87 + .mockReset()
88 + .mockResolvedValue({ backupPath: "/config/backup", warning: null });
89 + complete.mockReset().mockResolvedValue(undefined);
90 + toast.mockClear();
91 + container = document.createElement("div");
92 + document.body.append(container);
93 + root = createRoot(container);
94 +});
95 +afterEach(async () => {
96 + await act(async () => root.unmount());
97 + container.remove();
98 + Reflect.deleteProperty(navigator, "platform");
99 + vi.unstubAllGlobals();
100 +});
101 +
102 +it.each(["niri", "hyprland"] as const)(
103 + "shows the fallback before review and requires separate read and write approval on %s",
104 + async (desktop) => {
105 + await render(desktop);
106 + expect(recorder().getAttribute("aria-label")).toBe(
107 + "Record snapshot shortcut, currently Ctrl+Shift+2",
108 + );
109 + expect(advanced().textContent).toContain("manual binding");
110 + expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();
111 + await click("Review changes");
112 + expect(recorder().getAttribute("aria-label")).toBe(
113 + "Record snapshot shortcut, currently Ctrl+Shift+2",
114 + );
115 + expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
116 + expect(diff()).not.toBeNull();
117 + await click("Save shortcut");
118 + expect(bridge.applySnapShotConfig).toHaveBeenCalledExactlyOnceWith(preview.id);
119 + expect(complete).toHaveBeenCalledOnce();
120 + expect(toast).toHaveBeenCalledWith(expect.objectContaining({ type: "success" }));
121 + },
122 +);
123 +
124 +it.each(["niri", "hyprland"] as const)(
125 + "lets users choose %s keys without opening Advanced, then approve the matching diff",
126 + async (desktop) => {
127 + await render(desktop);
128 + expect(advanced().contains(recorder())).toBe(false);
129 + await recordKeys("{Control>}{Alt>}y{/Alt}{/Control}");
130 + expect(bridge.setSnapShotShortcutSuppressed).toHaveBeenNthCalledWith(1, true);
131 + expect(bridge.setSnapShotShortcutSuppressed).toHaveBeenLastCalledWith(false);
132 + expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();
133 + const custom = {
134 + ...preview,
135 + id: "custom-keys",
136 + shortcut: "Ctrl+Alt+Y",
137 + after: preview.after.replace("Ctrl+Shift+2", "Ctrl+Alt+Y"),
138 + };
139 + bridge.previewSnapShotConfig.mockResolvedValue(custom);
140 + await click("Review changes");
141 + expect(bridge.previewSnapShotConfig).toHaveBeenCalledExactlyOnceWith({
142 + operation: "install",
143 + chooseFile: false,
144 + shortcut: "ctrl+alt+y",
145 + });
146 + expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
147 + await click("Save shortcut");
148 + expect(bridge.applySnapShotConfig).toHaveBeenCalledExactlyOnceWith(custom.id);
149 + expect(toast).toHaveBeenCalledWith(
150 + expect.objectContaining({ description: "Use Ctrl+Alt+Y from another app." }),
151 + );
152 + },
153 +);
154 +
155 +it("uses the existing config keys when no replacement was chosen", async () => {
156 + bridge.previewSnapShotConfig.mockResolvedValue({ ...preview, shortcut: "Super+F8" });
157 + await render();
158 + await click("Review changes");
159 + expect(bridge.previewSnapShotConfig).toHaveBeenCalledExactlyOnceWith({
160 + operation: "install",
161 + chooseFile: false,
162 + });
163 + expect(recorder().getAttribute("aria-label")).toContain("F8");
164 +});
165 +
166 +it("requires a new diff after changing keys during review", async () => {
167 + await render();
168 + await click("Review changes");
169 + expect(diff()).not.toBeNull();
170 + await recordKeys("{Meta>}{F8}{/Meta}");
171 + expect(diff()).toBeNull();
172 + expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
173 + const replacement = { ...preview, id: "replacement", shortcut: "Super+F8" };
174 + bridge.previewSnapShotConfig.mockResolvedValue(replacement);
175 + await click("Review changes");
176 + expect(bridge.previewSnapShotConfig).toHaveBeenLastCalledWith({
177 + operation: "install",
178 + chooseFile: false,
179 + shortcut: "meta+f8",
180 + });
181 + await click("Save shortcut");
182 + expect(bridge.applySnapShotConfig).toHaveBeenCalledExactlyOnceWith(replacement.id);
183 +});
184 +
185 +it.each(["Escape", "blur"])(
186 + "keeps the reviewed diff when recording is cancelled with %s",
187 + async (cancel) => {
188 + await render();
189 + await click("Review changes");
190 + await act(async () => userEvent.click(recorder()));
191 + expect(button("Save shortcut")?.disabled).toBe(true);
192 + if (cancel === "Escape") await act(async () => userEvent.keyboard("{Escape}"));
193 + else await act(async () => recorder().blur());
194 + expect(button("Save shortcut")?.disabled).toBe(false);
195 + expect(bridge.previewSnapShotConfig).toHaveBeenCalledOnce();
196 + await click("Save shortcut");
197 + expect(bridge.applySnapShotConfig).toHaveBeenCalledExactlyOnceWith(preview.id);
198 + },
199 +);
200 +
201 +it("cancelling a reviewed diff does not write or finish setup", async () => {
202 + await render();
203 + await click("Review changes");
204 + await click("Cancel");
205 + expect(recorder().getAttribute("aria-label")).toBe(
206 + "Record snapshot shortcut, currently Ctrl+Shift+2",
207 + );
208 + expect(button("Review changes")).toBeDefined();
209 + expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
210 + expect(complete).not.toHaveBeenCalled();
211 +});
212 +
213 +it("shows reading feedback until a proposal arrives", async () => {
214 + const pending = deferred<DesktopCaptureConfigPreview>();
215 + bridge.previewSnapShotConfig.mockReturnValue(pending.promise);
216 + await render();
217 + await click("Review changes");
218 + expect(button("Preparing changes…")?.disabled).toBe(true);
219 + await act(async () => pending.resolve(preview));
220 + expect(button("Save shortcut")?.disabled).toBe(false);
221 +});
222 +
223 +it("keeps read failures actionable with technical details in Advanced, then permits retry", async () => {
224 + bridge.previewSnapShotConfig.mockRejectedValueOnce(new Error("EACCES: /config/niri/config.kdl"));
225 + await render();
226 + await click("Review changes");
227 + expect(alert()?.textContent).toBe("Couldn't prepare the changes. Check Advanced for help.");
228 + expect(advanced().textContent).toContain("EACCES: /config/niri/config.kdl");
229 + await click("Review changes");
230 + expect(alert()).toBeNull();
231 + expect(button("Save shortcut")?.disabled).toBe(false);
232 + expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
233 +});
234 +
235 +it("withdraws a stale diff and requires another read instead of retrying its write", async () => {
236 + await render();
237 + await click("Review changes");
238 + bridge.applySnapShotConfig.mockRejectedValue(
239 + new Error("Your config changed since this preview."),
240 + );
241 + await click("Save shortcut");
242 + expect(alert()?.textContent).toContain("Review the changes and try again");
243 + expect(advanced().textContent).toContain("Your config changed since this preview.");
244 + expect(button("Review changes")).toBeDefined();
245 + expect(diff()).toBeNull();
246 + expect(complete).not.toHaveBeenCalled();
247 +});
248 +
249 +it("does not finish or claim success when the desktop could not reload", async () => {
250 + await render();
251 + await click("Review changes");
252 + bridge.applySnapShotConfig.mockResolvedValue({
253 + backupPath: "/config/backup",
254 + warning: "Config saved, but reload failed.",
255 + });
256 + await click("Save shortcut");
257 + expect(container.querySelector('[role="status"]')?.textContent).toBe(
258 + "Saved, but the shortcut needs attention. Check Advanced for help.",
259 + );
260 + expect(advanced().textContent).toContain("Config saved, but reload failed.");
261 + expect(complete).not.toHaveBeenCalled();
262 + expect(toast).not.toHaveBeenCalled();
263 +});
apps/web/src/components/settings/CaptureShortcutConfig.test.tsx deleted
-320
@@ -1,320 +0,0 @@
1 -import {
2 - DEFAULT_CLIENT_SETTINGS,
3 - type DesktopCaptureConfigPreview,
4 - type DesktopSnapShotState,
5 -} from "@t3tools/contracts";
6 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
7 -import { reactHookHarness as hooks } from "../../test/reactHookHarness";
8 -import { visitElements } from "../../test/reactElementTree";
9 -
10 -vi.mock("react", async (original) => {
11 - const actual = await original<typeof import("react")>();
12 - const { reactHookHarness } = await import("../../test/reactHookHarness");
13 - return {
14 - ...actual,
15 - useCallback: reactHookHarness.useCallback,
16 - useRef: reactHookHarness.useRef,
17 - useEffect: () => undefined,
18 - useMemo: reactHookHarness.useMemo,
19 - useState: reactHookHarness.useState,
20 - };
21 -});
22 -vi.mock("react/compiler-runtime", async () => {
23 - const { reactHookHarness } = await import("../../test/reactHookHarness");
24 - return { c: reactHookHarness.useMemoCache };
25 -});
26 -const bridge = vi.hoisted(() => ({
27 - previewSnapShotConfig: vi.fn(),
28 - applySnapShotConfig: vi.fn(),
29 - setSnapShotShortcutSuppressed: vi.fn(),
30 -}));
31 -vi.mock("../../lib/desktopSnapShot", () => ({ getDesktopSnapShotBridge: () => bridge }));
32 -vi.mock("../../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "light" }) }));
33 -vi.mock("../../hooks/useCopyToClipboard", () => ({
34 - useCopyToClipboard: () => ({ copyToClipboard: vi.fn(), isCopied: false }),
35 -}));
36 -vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn() } }));
37 -import { CaptureShortcutConfig } from "./CaptureShortcutConfig";
38 -import { toastManager } from "../ui/toast";
39 -
40 -const preview: DesktopCaptureConfigPreview = {
41 - id: "approved-snapshot",
42 - path: "/config/niri/config.kdl",
43 - resolvedPath: "/config/niri/config.kdl",
44 - before: "binds {\n}\n",
45 - after: 'binds {\n Ctrl+Shift+2 { spawn "gdbus"; }\n}\n',
46 - shortcut: "Ctrl+Shift+2",
47 - operation: "install",
48 -};
49 -const complete = vi.fn<() => Promise<void>>();
50 -function render(desktop: "niri" | "hyprland" = "niri") {
51 - const state: DesktopSnapShotState = {
52 - mode: "portal",
53 - linuxBackend: desktop,
54 - shortcut: DEFAULT_CLIENT_SETTINGS.snapShotShortcut,
55 - shortcutRegistered: false,
56 - shortcutActionRegistered: true,
57 - shortcutMessage: null,
58 - message: null,
59 - shortcutConfigPath: preview.path,
60 - shortcutBinding: "manual binding",
61 - };
62 - hooks.beginRender();
63 - return CaptureShortcutConfig({ state, onComplete: complete });
64 -}
65 -function button(tree: ReturnType<typeof render>, label: string) {
66 - const node = visitElements(
67 - tree,
68 - (element) => element.props.children === label && typeof element.props.onClick === "function",
69 - );
70 - if (!node) throw new Error(`Missing button: ${label}`);
71 - return node.props as { onClick: () => void; disabled: boolean };
72 -}
73 -function shortcutInput(tree: ReturnType<typeof render>) {
74 - const node = visitElements(tree, (element) => "data-keybinding-capture" in element.props);
75 - if (!node) throw new Error("Missing shortcut recorder");
76 - return node.props as {
77 - "aria-label": string;
78 - onClick: () => void;
79 - onKeyDown: (event: object) => void;
80 - onBlur: () => void;
81 - };
82 -}
83 -async function recordKeys(desktop: "niri" | "hyprland", modifiers: object = {}) {
84 - shortcutInput(render(desktop)).onClick();
85 - await finish(bridge.setSnapShotShortcutSuppressed.mock.results.at(-1)!.value);
86 - shortcutInput(render(desktop)).onKeyDown({
87 - key: "y",
88 - code: "KeyY",
89 - ctrlKey: true,
90 - altKey: true,
91 - shiftKey: false,
92 - metaKey: false,
93 - repeat: false,
94 - preventDefault: vi.fn(),
95 - stopPropagation: vi.fn(),
96 - ...modifiers,
97 - });
98 -}
99 -async function finish(promise: Promise<unknown>) {
100 - await promise.catch(() => undefined);
101 - await Promise.resolve();
102 -}
103 -beforeEach(() => {
104 - hooks.reset();
105 - vi.stubGlobal("navigator", { platform: "Linux" });
106 - bridge.setSnapShotShortcutSuppressed.mockReset().mockResolvedValue(undefined);
107 - bridge.previewSnapShotConfig.mockReset().mockResolvedValue(preview);
108 - bridge.applySnapShotConfig
109 - .mockReset()
110 - .mockResolvedValue({ backupPath: "/config/backup", warning: null });
111 - complete.mockReset().mockResolvedValue(undefined);
112 - vi.mocked(toastManager.add).mockClear();
113 -});
114 -afterEach(() => vi.unstubAllGlobals());
115 -
116 -it.each(["niri", "hyprland"] as const)(
117 - "shows the fallback before review and requires separate read and write approval on %s",
118 - async (desktop) => {
119 - let tree = render(desktop);
120 - expect(shortcutInput(tree)["aria-label"]).toBe(
121 - "Record snapshot shortcut, currently Ctrl+Shift+2",
122 - );
123 - expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();
124 - expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
125 - expect(visitElements(tree, (element) => element.type === "details")).not.toBeNull();
126 - button(tree, "Review changes").onClick();
127 - await finish(bridge.previewSnapShotConfig.mock.results[0]!.value);
128 - tree = render(desktop);
129 - expect(shortcutInput(tree)["aria-label"]).toBe(
130 - "Record snapshot shortcut, currently Ctrl+Shift+2",
131 - );
132 - expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
133 - const diff = visitElements(tree, (element) => "fileDiff" in element.props);
134 - expect(diff).not.toBeNull();
135 - expect(diff?.props.fileDiff).toMatchObject({ name: preview.path });
136 - button(tree, "Save shortcut").onClick();
137 - await finish(bridge.applySnapShotConfig.mock.results[0]!.value);
138 - expect(bridge.applySnapShotConfig).toHaveBeenCalledExactlyOnceWith(preview.id);
139 - expect(complete).toHaveBeenCalledOnce();
140 - expect(toastManager.add).toHaveBeenCalledWith(expect.objectContaining({ type: "success" }));
141 - },
142 -);
143 -it.each(["niri", "hyprland"] as const)(
144 - "lets users choose %s keys without opening Advanced, then approve the matching diff",
145 - async (desktop) => {
146 - const tree = render(desktop);
147 - const advanced = visitElements(tree, (element) => element.type === "details");
148 - expect(
149 - visitElements(advanced, (element) => "data-keybinding-capture" in element.props),
150 - ).toBeNull();
151 - await recordKeys(desktop);
152 - expect(bridge.setSnapShotShortcutSuppressed).toHaveBeenNthCalledWith(1, true);
153 - expect(bridge.setSnapShotShortcutSuppressed).toHaveBeenLastCalledWith(false);
154 - expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();
155 - const custom = {
156 - ...preview,
157 - id: "custom-keys",
158 - shortcut: "Ctrl+Alt+Y",
159 - after: preview.after.replace("Ctrl+Shift+2", "Ctrl+Alt+Y"),
160 - };
161 - bridge.previewSnapShotConfig.mockResolvedValue(custom);
162 - button(render(desktop), "Review changes").onClick();
163 - await finish(bridge.previewSnapShotConfig.mock.results[0]!.value);
164 - expect(bridge.previewSnapShotConfig).toHaveBeenCalledExactlyOnceWith({
165 - operation: "install",
166 - chooseFile: false,
167 - shortcut: "ctrl+alt+y",
168 - });
169 - expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
170 - button(render(desktop), "Save shortcut").onClick();
171 - await finish(bridge.applySnapShotConfig.mock.results[0]!.value);
172 - expect(bridge.applySnapShotConfig).toHaveBeenCalledExactlyOnceWith(custom.id);
173 - expect(toastManager.add).toHaveBeenCalledWith(
174 - expect.objectContaining({ description: "Use Ctrl+Alt+Y from another app." }),
175 - );
176 - },
177 -);
178 -it("uses the existing config keys when no replacement was chosen", async () => {
179 - bridge.previewSnapShotConfig.mockResolvedValue({ ...preview, shortcut: "Super+F8" });
180 - button(render(), "Review changes").onClick();
181 - await finish(bridge.previewSnapShotConfig.mock.results[0]!.value);
182 - expect(bridge.previewSnapShotConfig).toHaveBeenCalledExactlyOnceWith({
183 - operation: "install",
184 - chooseFile: false,
185 - });
186 - expect(shortcutInput(render())["aria-label"]).toContain("F8");
187 -});
188 -it("requires a new diff after changing keys during review", async () => {
189 - button(render(), "Review changes").onClick();
190 - await finish(bridge.previewSnapShotConfig.mock.results[0]!.value);
191 - await recordKeys("niri", { key: "F8", code: "F8", ctrlKey: false, altKey: false, metaKey: true });
192 - expect(visitElements(render(), (element) => "fileDiff" in element.props)).toBeNull();
193 - expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
194 - const replacement = { ...preview, id: "replacement", shortcut: "Super+F8" };
195 - bridge.previewSnapShotConfig.mockResolvedValue(replacement);
196 - button(render(), "Review changes").onClick();
197 - await finish(bridge.previewSnapShotConfig.mock.results[1]!.value);
198 - expect(bridge.previewSnapShotConfig).toHaveBeenLastCalledWith({
199 - operation: "install",
200 - chooseFile: false,
201 - shortcut: "meta+f8",
202 - });
203 - button(render(), "Save shortcut").onClick();
204 - await finish(bridge.applySnapShotConfig.mock.results[0]!.value);
205 - expect(bridge.applySnapShotConfig).toHaveBeenCalledExactlyOnceWith(replacement.id);
206 -});
207 -it.each(["Escape", "blur"])(
208 - "keeps the reviewed diff when recording is cancelled with %s",
209 - async (cancel) => {
210 - button(render(), "Review changes").onClick();
211 - await finish(bridge.previewSnapShotConfig.mock.results[0]!.value);
212 - shortcutInput(render()).onClick();
213 - await finish(bridge.setSnapShotShortcutSuppressed.mock.results.at(-1)!.value);
214 - expect(button(render(), "Save shortcut").disabled).toBe(true);
215 - if (cancel === "Escape")
216 - shortcutInput(render()).onKeyDown({
217 - key: "Escape",
218 - preventDefault: vi.fn(),
219 - stopPropagation: vi.fn(),
220 - });
221 - else shortcutInput(render()).onBlur();
222 - expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
223 - expect(button(render(), "Save shortcut").disabled).toBe(false);
224 - expect(bridge.previewSnapShotConfig).toHaveBeenCalledOnce();
225 - button(render(), "Save shortcut").onClick();
226 - await finish(bridge.applySnapShotConfig.mock.results[0]!.value);
227 - expect(bridge.applySnapShotConfig).toHaveBeenCalledExactlyOnceWith(preview.id);
228 - },
229 -);
230 -it("cancelling a reviewed diff does not write or finish setup", async () => {
231 - button(render(), "Review changes").onClick();
232 - await finish(bridge.previewSnapShotConfig.mock.results[0]!.value);
233 - button(render(), "Cancel").onClick();
234 - expect(shortcutInput(render())["aria-label"]).toBe(
235 - "Record snapshot shortcut, currently Ctrl+Shift+2",
236 - );
237 - expect(button(render(), "Review changes")).toBeDefined();
238 - expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
239 - expect(complete).not.toHaveBeenCalled();
240 -});
241 -it("shows reading feedback until a proposal arrives", async () => {
242 - let resolvePreview!: (value: DesktopCaptureConfigPreview) => void;
243 - const pending = new Promise<DesktopCaptureConfigPreview>((resolve) => {
244 - resolvePreview = resolve;
245 - });
246 - bridge.previewSnapShotConfig.mockReturnValue(pending);
247 - button(render(), "Review changes").onClick();
248 - expect(button(render(), "Preparing changes…").disabled).toBe(true);
249 - expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
250 - resolvePreview(preview);
251 - await finish(pending);
252 - expect(button(render(), "Save shortcut").disabled).toBe(false);
253 -});
254 -it("keeps read failures actionable with technical details in Advanced, then permits retry", async () => {
255 - bridge.previewSnapShotConfig.mockRejectedValueOnce(new Error("EACCES: /config/niri/config.kdl"));
256 - button(render(), "Review changes").onClick();
257 - await finish(bridge.previewSnapShotConfig.mock.results[0]!.value);
258 - const failed = render();
259 - expect(visitElements(failed, (element) => element.props.role === "alert")?.props.children).toBe(
260 - "Couldn't prepare the changes. Check Advanced for help.",
261 - );
262 - const advanced = visitElements(failed, (element) => element.type === "details");
263 - expect(
264 - visitElements(
265 - advanced,
266 - (element) => element.props.children === "EACCES: /config/niri/config.kdl",
267 - ),
268 - ).not.toBeNull();
269 - expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
270 - button(failed, "Review changes").onClick();
271 - await finish(bridge.previewSnapShotConfig.mock.results[1]!.value);
272 - expect(visitElements(render(), (element) => element.props.role === "alert")).toBeNull();
273 - expect(button(render(), "Save shortcut").disabled).toBe(false);
274 - expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
275 -});
276 -it("withdraws a stale diff and requires another read instead of retrying its write", async () => {
277 - button(render(), "Review changes").onClick();
278 - await finish(bridge.previewSnapShotConfig.mock.results[0]!.value);
279 - bridge.applySnapShotConfig.mockRejectedValue(
280 - new Error("Your config changed since this preview."),
281 - );
282 - button(render(), "Save shortcut").onClick();
283 - await finish(bridge.applySnapShotConfig.mock.results[0]!.value);
284 - const tree = render();
285 - expect(
286 - visitElements(tree, (element) => element.props.role === "alert")?.props.children,
287 - ).toContain("Review the changes and try again");
288 - const advanced = visitElements(tree, (element) => element.type === "details");
289 - expect(
290 - visitElements(
291 - advanced,
292 - (element) => element.props.children === "Your config changed since this preview.",
293 - ),
294 - ).not.toBeNull();
295 - expect(button(tree, "Review changes")).toBeDefined();
296 - expect(visitElements(tree, (element) => "fileDiff" in element.props)).toBeNull();
297 - expect(complete).not.toHaveBeenCalled();
298 -});
299 -it("does not finish or claim success when the desktop could not reload", async () => {
300 - button(render(), "Review changes").onClick();
301 - await finish(bridge.previewSnapShotConfig.mock.results[0]!.value);
302 - bridge.applySnapShotConfig.mockResolvedValue({
303 - backupPath: "/config/backup",
304 - warning: "Config saved, but reload failed.",
305 - });
306 - button(render(), "Save shortcut").onClick();
307 - await finish(bridge.applySnapShotConfig.mock.results[0]!.value);
308 - expect(
309 - visitElements(render(), (element) => element.props.role === "status")?.props.children,
310 - ).toBe("Saved, but the shortcut needs attention. Check Advanced for help.");
311 - const advanced = visitElements(render(), (element) => element.type === "details");
312 - expect(
313 - visitElements(
314 - advanced,
315 - (element) => element.props.children === "Config saved, but reload failed.",
316 - ),
317 - ).not.toBeNull();
318 - expect(complete).not.toHaveBeenCalled();
319 - expect(toastManager.add).not.toHaveBeenCalled();
320 -});
apps/web/src/components/settings/KeybindingsSettings.environment.browser.test.tsx new
+135
@@ -0,0 +1,135 @@
1 +import type { EnvironmentId } from "@t3tools/contracts";
2 +import { act } from "react";
3 +import { createRoot, type Root } from "react-dom/client";
4 +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
5 +
6 +const state = vi.hoisted(() => ({
7 + canOperate: false,
8 + canWriteSettings: true,
9 + connected: true,
10 + openEditor: vi.fn(),
11 +}));
12 +
13 +vi.mock(import("@tanstack/react-router"), async (original) => ({
14 + ...(await original()),
15 + useLocation: (() => "") as never,
16 +}));
17 +vi.mock(import("./SettingsScopeContext"), async (original) => ({
18 + ...(await original()),
19 + useSettingsScope: () => {
20 + const environment = {
21 + environmentId: "primary-settings",
22 + serverConfig: {
23 + keybindings: [],
24 + keybindingsConfigPath: "/fixture/keybindings.json",
25 + availableEditors: [],
26 + },
27 + };
28 + return (
29 + state.connected
30 + ? { environment, connectedEnvironments: [environment] }
31 + : { environment: null, connectedEnvironments: [] }
32 + ) as never;
33 + },
34 +}));
35 +vi.mock(import("../../state/session"), async (original) => {
36 + const hasScope = (environmentId: EnvironmentId | null, scope: string) =>
37 + environmentId === "primary-settings" &&
38 + (scope === "orchestration:operate"
39 + ? state.canOperate
40 + : scope === "settings:write" && state.canWriteSettings);
41 + return {
42 + ...(await original()),
43 + useEnvironmentScope: hasScope as never,
44 + readEnvironmentScope: hasScope as never,
45 + useEnvironmentsWithScope: (() =>
46 + new Set(state.canWriteSettings ? ["primary-settings"] : [])) as never,
47 + };
48 +});
49 +vi.mock(import("../../editorPreferences"), async (original) => ({
50 + ...(await original()),
51 + useOpenInPreferredEditor: ((environmentId: EnvironmentId) => (path: string) =>
52 + state.openEditor({ environmentId, path })) as never,
53 +}));
54 +
55 +import { KeybindingsSettingsPanel } from "./KeybindingsSettings";
56 +
57 +let root: Root;
58 +let container: HTMLDivElement;
59 +
60 +const render = () => act(async () => root.render(<KeybindingsSettingsPanel />));
61 +const openButton = () => {
62 + const button = container.querySelector<HTMLButtonElement>(
63 + 'button[aria-label="Open keybindings.json"]',
64 + );
65 + expect(button).not.toBeNull();
66 + return button!;
67 +};
68 +
69 +beforeEach(() => {
70 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
71 + state.canOperate = false;
72 + state.canWriteSettings = true;
73 + state.connected = true;
74 + state.openEditor.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
75 + container = document.createElement("div");
76 + document.body.append(container);
77 + root = createRoot(container);
78 +});
79 +afterEach(async () => {
80 + await act(async () => root.unmount());
81 + container.remove();
82 + vi.unstubAllGlobals();
83 +});
84 +
85 +describe("KeybindingsSettings editor permission", () => {
86 + it("rejects editor launches when settings writes are the only write grant", async () => {
87 + await render();
88 + expect(openButton().disabled).toBe(true);
89 + await act(async () => openButton().click());
90 + expect(state.openEditor).not.toHaveBeenCalled();
91 + });
92 +
93 + it("opens the primary environment's file after operate is granted without settings writes", async () => {
94 + state.canWriteSettings = false;
95 + await render();
96 + state.canOperate = true;
97 + await render();
98 + expect(openButton().disabled).toBe(false);
99 + await act(async () => openButton().click());
100 +
101 + expect(state.openEditor).toHaveBeenCalledWith({
102 + environmentId: "primary-settings",
103 + path: "/fixture/keybindings.json",
104 + });
105 + });
106 +
107 + it("rejects a queued editor launch after operate is revoked", async () => {
108 + state.canOperate = true;
109 + await render();
110 + const button = openButton();
111 + state.canOperate = false;
112 + // The rendered button is still enabled; the click must recheck the live grant.
113 + await act(async () => button.click());
114 +
115 + expect(state.openEditor).not.toHaveBeenCalled();
116 + await render();
117 + expect(openButton().disabled).toBe(true);
118 + });
119 +});
120 +
121 +describe("KeybindingsSettings write notice", () => {
122 + it("asks for a connected environment when none is connected", async () => {
123 + state.connected = false;
124 + await render();
125 + expect(container.textContent).toContain("Connect an environment to change keybindings.");
126 + });
127 +
128 + it("names the permission when the connection cannot write settings", async () => {
129 + state.canWriteSettings = false;
130 + await render();
131 + expect(container.textContent).toContain(
132 + "This connection can view keybindings but cannot change them.",
133 + );
134 + });
135 +});
apps/web/src/components/settings/KeybindingsSettings.environment.test.tsx deleted
-172
@@ -1,172 +0,0 @@
1 -import type { EnvironmentId } from "@t3tools/contracts";
2 -import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
3 -
4 -import { visitElements } from "../../test/reactElementTree";
5 -import { reactHookHarness as hooks } from "../../test/reactHookHarness";
6 -
7 -const state = vi.hoisted(() => ({
8 - canOperate: false,
9 - canWriteSettings: true,
10 - connected: true,
11 - openEditor: vi.fn(),
12 - upsert: vi.fn(),
13 - remove: vi.fn(),
14 -}));
15 -
16 -vi.mock("react", async (importOriginal) => {
17 - const actual = await importOriginal<typeof import("react")>();
18 - const { reactHookHarness } = await import("../../test/reactHookHarness");
19 - return {
20 - ...actual,
21 - useCallback: reactHookHarness.useCallback,
22 - useEffect: () => undefined,
23 - useMemo: reactHookHarness.useMemo,
24 - useRef: reactHookHarness.useRef,
25 - useState: reactHookHarness.useState,
26 - };
27 -});
28 -
29 -vi.mock("react/compiler-runtime", async () => {
30 - const { reactHookHarness } = await import("../../test/reactHookHarness");
31 - return { c: reactHookHarness.useMemoCache };
32 -});
33 -
34 -vi.mock("@effect/atom-react", () => ({
35 - useAtomValue: (atom: string) => (atom === "config-path" ? "/fixture/keybindings.json" : []),
36 -}));
37 -
38 -vi.mock("@tanstack/react-router", () => ({ useLocation: () => "" }));
39 -vi.mock("../ProjectFavicon", () => ({ ProjectFavicon: () => null }));
40 -vi.mock("../../state/server", () => ({
41 - primaryServerKeybindingsAtom: "keybindings",
42 - primaryServerKeybindingsConfigPathAtom: "config-path",
43 - primaryServerAvailableEditorsAtom: "editors",
44 - serverEnvironment: { upsertKeybinding: state.upsert, removeKeybinding: state.remove },
45 -}));
46 -
47 -vi.mock("../../state/environments", () => ({
48 - usePrimaryEnvironment: () => ({ environmentId: "primary-settings" }),
49 -}));
50 -
51 -vi.mock("./SettingsScopeContext", () => ({
52 - useSettingsScope: () => {
53 - const environment = {
54 - environmentId: "primary-settings",
55 - serverConfig: {
56 - keybindings: [],
57 - keybindingsConfigPath: "/fixture/keybindings.json",
58 - availableEditors: [],
59 - },
60 - };
61 - return state.connected
62 - ? { environment, connectedEnvironments: [environment] }
63 - : { environment: null, connectedEnvironments: [] };
64 - },
65 -}));
66 -
67 -vi.mock("../../state/session", () => {
68 - const hasScope = (environmentId: EnvironmentId | null, scope: string) =>
69 - environmentId === "primary-settings" &&
70 - (scope === "orchestration:operate"
71 - ? state.canOperate
72 - : scope === "settings:write" && state.canWriteSettings);
73 - return {
74 - useEnvironmentScope: hasScope,
75 - readEnvironmentScope: hasScope,
76 - useEnvironmentsWithScope: () => new Set(state.canWriteSettings ? ["primary-settings"] : []),
77 - };
78 -});
79 -
80 -vi.mock("../../state/use-atom-command", () => ({
81 - useAtomCommand: (command: unknown) => command,
82 -}));
83 -
84 -vi.mock("../../editorPreferences", () => ({
85 - useOpenInPreferredEditor: (environmentId: EnvironmentId) => (path: string) =>
86 - state.openEditor({ environmentId, path }),
87 -}));
88 -
89 -import { KeybindingsSettingsPanel } from "./KeybindingsSettings";
90 -
91 -function renderPanel() {
92 - hooks.beginRender();
93 - return KeybindingsSettingsPanel();
94 -}
95 -
96 -function openButton(panel: unknown) {
97 - const button = visitElements(
98 - panel,
99 - (element) => element.props["aria-label"] === "Open keybindings.json",
100 - );
101 - if (!button) throw new Error("Missing Open keybindings.json action.");
102 - return button;
103 -}
104 -
105 -describe("KeybindingsSettings editor permission", () => {
106 - beforeEach(() => {
107 - hooks.reset();
108 - state.canOperate = false;
109 - state.canWriteSettings = true;
110 - state.connected = true;
111 - state.openEditor.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
112 - state.upsert.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
113 - state.remove.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
114 - });
115 -
116 - it("rejects editor launches when settings writes are the only write grant", () => {
117 - const button = openButton(renderPanel());
118 - (button.props.onClick as () => void)();
119 -
120 - expect(state.openEditor).not.toHaveBeenCalled();
121 - expect(button.props.disabled).toBe(true);
122 - });
123 -
124 - it("opens the primary environment's file after operate is granted without settings writes", () => {
125 - state.canWriteSettings = false;
126 - renderPanel();
127 - state.canOperate = true;
128 - const button = openButton(renderPanel());
129 - expect(button.props.disabled).toBe(false);
130 - (button.props.onClick as () => void)();
131 -
132 - expect(state.openEditor).toHaveBeenCalledWith({
133 - environmentId: "primary-settings",
134 - path: "/fixture/keybindings.json",
135 - });
136 - });
137 -
138 - it("rejects a queued editor launch after operate is revoked", () => {
139 - state.canOperate = true;
140 - const open = openButton(renderPanel()).props.onClick as () => void;
141 - state.canOperate = false;
142 - open();
143 -
144 - expect(state.openEditor).not.toHaveBeenCalled();
145 - expect(openButton(renderPanel()).props.disabled).toBe(true);
146 - });
147 -});
148 -
149 -function noticeText(panel: unknown) {
150 - const notice = visitElements(panel, (element) => element.type === "p");
151 - return notice?.props.children;
152 -}
153 -
154 -describe("KeybindingsSettings write notice", () => {
155 - beforeEach(() => {
156 - hooks.reset();
157 - state.canWriteSettings = true;
158 - state.connected = true;
159 - });
160 -
161 - it("asks for a connected environment when none is connected", () => {
162 - state.connected = false;
163 - expect(noticeText(renderPanel())).toBe("Connect an environment to change keybindings.");
164 - });
165 -
166 - it("names the permission when the connection cannot write settings", () => {
167 - state.canWriteSettings = false;
168 - expect(noticeText(renderPanel())).toBe(
169 - "This connection can view keybindings but cannot change them.",
170 - );
171 - });
172 -});
apps/web/src/components/settings/ProjectFaviconPickerDialog.browser.test.tsx new
+100
@@ -0,0 +1,100 @@
1 +import { EnvironmentId } from "@t3tools/contracts";
2 +import { act } from "react";
3 +import { createRoot, type Root } from "react-dom/client";
4 +import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
5 +
6 +const toast = vi.hoisted(() => vi.fn());
7 +vi.mock(import("../files/projectFilesQueryState"), async (original) => ({
8 + ...(await original()),
9 + useProjectFilePickerQuery: () => ({
10 + entries: [],
11 + error: null,
12 + isPending: false,
13 + matchedQuery: "",
14 + }),
15 +}));
16 +vi.mock(import("../ui/toast"), async (original) => {
17 + const actual = await original();
18 + return { ...actual, toastManager: { ...actual.toastManager, add: toast } };
19 +});
20 +
21 +import {
22 + canPickExternalProjectFavicon,
23 + ProjectFaviconPickerDialog,
24 +} from "./ProjectFaviconPickerDialog";
25 +
26 +let root: Root;
27 +let container: HTMLDivElement;
28 +
29 +beforeEach(() => {
30 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
31 + Object.defineProperty(navigator, "platform", { configurable: true, get: () => "MacIntel" });
32 + toast.mockClear();
33 + container = document.createElement("div");
34 + document.body.append(container);
35 + root = createRoot(container);
36 +});
37 +afterEach(async () => {
38 + await act(async () => root.unmount());
39 + container.remove();
40 + Reflect.deleteProperty(navigator, "platform");
41 + vi.unstubAllGlobals();
42 +});
43 +
44 +async function renderPicker(onPickExternal: () => Promise<string | null>) {
45 + const onOpenChange = vi.fn();
46 + const onSelect = vi.fn();
47 + await act(async () =>
48 + root.render(
49 + <ProjectFaviconPickerDialog
50 + cwd="/Users/me/project"
51 + environmentId={EnvironmentId.make("local")}
52 + onOpenChange={onOpenChange}
53 + onPickExternal={onPickExternal}
54 + onSelect={onSelect}
55 + open
56 + projectName="Project"
57 + />,
58 + ),
59 + );
60 + return { onOpenChange, onSelect };
61 +}
62 +async function clickOpenInFinder() {
63 + const button = [...document.querySelectorAll("button")].find((element) =>
64 + element.textContent?.includes("Open in Finder"),
65 + );
66 + expect(button, "Open in Finder").toBeDefined();
67 + await act(async () => button!.click());
68 +}
69 +
70 +it("selects an image from the native file picker", async () => {
71 + const onPickExternal = vi.fn().mockResolvedValue("/Users/me/Pictures/icon.png");
72 + const { onOpenChange, onSelect } = await renderPicker(onPickExternal);
73 +
74 + await clickOpenInFinder();
75 +
76 + expect(onPickExternal).toHaveBeenCalledTimes(1);
77 + expect(onOpenChange).toHaveBeenCalledWith(false);
78 + expect(onSelect).toHaveBeenCalledWith("/Users/me/Pictures/icon.png");
79 +});
80 +
81 +it("hides the native picker for WSL project paths", () => {
82 + expect(canPickExternalProjectFavicon("/home/me/project", "Win32")).toBe(false);
83 + expect(canPickExternalProjectFavicon("C:\\Users\\me\\project", "Win32")).toBe(true);
84 +});
85 +
86 +it("keeps the dialog open when the native picker fails", async () => {
87 + const { onOpenChange, onSelect } = await renderPicker(
88 + vi.fn().mockRejectedValue(new Error("picker failed")),
89 + );
90 +
91 + await clickOpenInFinder();
92 +
93 + expect(onOpenChange).not.toHaveBeenCalled();
94 + expect(onSelect).not.toHaveBeenCalled();
95 + expect(toast).toHaveBeenCalledWith({
96 + type: "error",
97 + title: "Could not open image picker",
98 + description: "picker failed",
99 + });
100 +});
apps/web/src/components/settings/ProjectFaviconPickerDialog.test.tsx deleted
-125
@@ -1,125 +0,0 @@
1 -import { EnvironmentId } from "@t3tools/contracts";
2 -import type { ReactElement } from "react";
3 -import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
4 -
5 -import { visitElements } from "../../test/reactElementTree";
6 -import { reactHookHarness as hooks } from "../../test/reactHookHarness";
7 -
8 -vi.mock("react", async (importOriginal) => {
9 - const actual = await importOriginal<typeof import("react")>();
10 - const { reactHookHarness } = await import("../../test/reactHookHarness");
11 - return {
12 - ...actual,
13 - useMemo: reactHookHarness.useMemo,
14 - useState: reactHookHarness.useState,
15 - };
16 -});
17 -
18 -vi.mock("react/compiler-runtime", async () => {
19 - const { reactHookHarness } = await import("../../test/reactHookHarness");
20 - return { c: reactHookHarness.useMemoCache };
21 -});
22 -
23 -vi.mock("@effect/atom-react", () => ({
24 - useAtomValue: () => ({}),
25 -}));
26 -
27 -vi.mock("~/state/server", () => ({
28 - primaryServerKeybindingsAtom: Symbol("keybindings"),
29 -}));
30 -
31 -vi.mock("~/hooks/useTheme", () => ({
32 - useTheme: () => ({ resolvedTheme: "dark" }),
33 -}));
34 -
35 -vi.mock("../files/projectFilesQueryState", () => ({
36 - useProjectFilePickerQuery: () => ({
37 - entries: [],
38 - error: null,
39 - isPending: false,
40 - matchedQuery: "",
41 - }),
42 -}));
43 -
44 -vi.mock("../ui/toast", () => ({
45 - toastManager: { add: vi.fn() },
46 -}));
47 -
48 -import { toastManager } from "../ui/toast";
49 -import {
50 - canPickExternalProjectFavicon,
51 - ProjectFaviconPickerDialog,
52 -} from "./ProjectFaviconPickerDialog";
53 -
54 -describe("ProjectFaviconPickerDialog", () => {
55 - beforeEach(() => {
56 - hooks.reset();
57 - vi.stubGlobal("navigator", { platform: "MacIntel" });
58 - });
59 -
60 - it("selects an image from the native file picker", async () => {
61 - const onOpenChange = vi.fn();
62 - const onPickExternal = vi.fn().mockResolvedValue("/Users/me/Pictures/icon.png");
63 - const onSelect = vi.fn();
64 - hooks.beginRender();
65 - const picker = ProjectFaviconPickerDialog({
66 - cwd: "/Users/me/project",
67 - environmentId: EnvironmentId.make("local"),
68 - onOpenChange,
69 - onPickExternal,
70 - onSelect,
71 - open: true,
72 - projectName: "Project",
73 - } as Parameters<typeof ProjectFaviconPickerDialog>[0] & {
74 - readonly onPickExternal: () => Promise<string | null>;
75 - }) as ReactElement<Record<string, unknown>>;
76 -
77 - const button = visitElements(picker, (element) => element.props.children === "Open in Finder");
78 - expect(button).not.toBeNull();
79 -
80 - (button?.props.onClick as (() => void) | undefined)?.();
81 - await Promise.resolve();
82 - await Promise.resolve();
83 -
84 - expect(onPickExternal).toHaveBeenCalledTimes(1);
85 - expect(onOpenChange).toHaveBeenCalledWith(false);
86 - expect(onSelect).toHaveBeenCalledWith("/Users/me/Pictures/icon.png");
87 - });
88 -
89 - it("hides the native picker for WSL project paths", () => {
90 - expect(canPickExternalProjectFavicon("/home/me/project", "Win32")).toBe(false);
91 - expect(canPickExternalProjectFavicon("C:\\Users\\me\\project", "Win32")).toBe(true);
92 - });
93 -
94 - it("keeps the dialog open when the native picker fails", async () => {
95 - const onOpenChange = vi.fn();
96 - const onSelect = vi.fn();
97 - const props = {
98 - cwd: "/Users/me/project",
99 - environmentId: EnvironmentId.make("local"),
100 - onOpenChange,
101 - onPickExternal: vi.fn().mockRejectedValue(new Error("picker failed")),
102 - onSelect,
103 - open: true,
104 - projectName: "Project",
105 - } as Parameters<typeof ProjectFaviconPickerDialog>[0] & {
106 - readonly onPickExternal: () => Promise<string | null>;
107 - };
108 -
109 - hooks.beginRender();
110 - const picker = ProjectFaviconPickerDialog(props) as ReactElement<Record<string, unknown>>;
111 - const button = visitElements(picker, (element) => element.props.children === "Open in Finder");
112 -
113 - (button?.props.onClick as (() => void) | undefined)?.();
114 - await Promise.resolve();
115 - await Promise.resolve();
116 -
117 - expect(onOpenChange).not.toHaveBeenCalled();
118 - expect(onSelect).not.toHaveBeenCalled();
119 - expect(toastManager.add).toHaveBeenCalledWith({
120 - type: "error",
121 - title: "Could not open image picker",
122 - description: "picker failed",
123 - });
124 - });
125 -});
apps/web/src/components/settings/ProviderSetupSection.browser.test.tsx new
+380
@@ -0,0 +1,380 @@
1 +import {
2 + EnvironmentId,
3 + ProviderDriverKind,
4 + ProviderInstanceId,
5 + type ProviderAuthState,
6 + type ProviderInstallState,
7 + type ServerProvider,
8 +} from "@t3tools/contracts";
9 +import { act } from "react";
10 +import { createRoot, type Root } from "react-dom/client";
11 +import { userEvent } from "vite-plus/test/browser";
12 +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
13 +
14 +const setup = vi.hoisted(() => ({
15 + auth: null as ProviderAuthState | null,
16 + installation: null as ProviderInstallState | null,
17 + authState: vi.fn(() => "auth"),
18 + installState: vi.fn(() => "installation"),
19 + startAuth: vi.fn(),
20 + completeAuth: vi.fn(),
21 + respondAuth: vi.fn(),
22 + cancelAuth: vi.fn(),
23 + logoutAuth: vi.fn(),
24 + startInstall: vi.fn(),
25 + cancelInstall: vi.fn(),
26 + removeInstall: vi.fn(),
27 + confirm: vi.fn(),
28 +}));
29 +
30 +vi.mock(import("../../state/server"), async (original) => {
31 + const actual = await original();
32 + return {
33 + ...actual,
34 + serverEnvironment: {
35 + ...actual.serverEnvironment,
36 + providerAuthState: setup.authState as never,
37 + providerInstallState: setup.installState as never,
38 + startProviderAuth: setup.startAuth as never,
39 + completeProviderAuth: setup.completeAuth as never,
40 + respondProviderAuth: setup.respondAuth as never,
41 + cancelProviderAuth: setup.cancelAuth as never,
42 + logoutProviderAuth: setup.logoutAuth as never,
43 + startProviderInstall: setup.startInstall as never,
44 + cancelProviderInstall: setup.cancelInstall as never,
45 + removeProviderInstallation: setup.removeInstall as never,
46 + },
47 + };
48 +});
49 +vi.mock(import("../../state/use-atom-command"), async (original) => ({
50 + ...(await original()),
51 + useAtomCommand: ((command: unknown) => command) as never,
52 +}));
53 +// The queries behave like live subscriptions: changing `setup.auth` and calling
54 +// `publish()` re-renders the sections that read them.
55 +const queryListeners = vi.hoisted(() => new Set<() => void>());
56 +vi.mock(import("../../state/query"), async (original) => {
57 + const { useSyncExternalStore } = await import("react");
58 + const subscribe = (listener: () => void) => {
59 + queryListeners.add(listener);
60 + return () => queryListeners.delete(listener);
61 + };
62 + return {
63 + ...(await original()),
64 + useEnvironmentQuery: ((atom: string) => ({
65 + data: useSyncExternalStore(subscribe, () =>
66 + atom === "auth" ? setup.auth : setup.installation,
67 + ),
68 + error: null,
69 + isPending: false,
70 + refresh: vi.fn(),
71 + })) as never,
72 + };
73 +});
74 +const publish = () =>
75 + act(async () => {
76 + for (const listener of queryListeners) listener();
77 + });
78 +vi.mock(import("../../localApi"), async (original) => ({
79 + ...(await original()),
80 + ensureLocalApi: () => ({ dialogs: { confirm: setup.confirm } }) as never,
81 +}));
82 +
83 +import { ProviderSetupSection } from "./ProviderSetupSection";
84 +
85 +const environmentId = EnvironmentId.make("remote-google");
86 +const instanceId = ProviderInstanceId.make("antigravity_work");
87 +const provider: ServerProvider = {
88 + instanceId,
89 + driver: ProviderDriverKind.make("antigravity"),
90 + installed: true,
91 + enabled: true,
92 + version: "test-version",
93 + status: "error",
94 + auth: { status: "unauthenticated" },
95 + checkedAt: "2026-09-02T00:00:00.000Z",
96 + models: [],
97 + skills: [],
98 + slashCommands: [],
99 + setup: { canAuthenticate: true, canInstall: true },
100 +};
101 +
102 +function authState(patch: Partial<ProviderAuthState> = {}): ProviderAuthState {
103 + return {
104 + instanceId,
105 + phase: "waiting",
106 + flowId: "flow-1",
107 + authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth?state=test-only",
108 + expiresAt: "2026-09-02T00:05:00.000Z",
109 + message: null,
110 + ...patch,
111 + };
112 +}
113 +
114 +function deferred<T>() {
115 + let resolve!: (value: T) => void;
116 + const promise = new Promise<T>((done) => {
117 + resolve = done;
118 + });
119 + return { promise, resolve };
120 +}
121 +
122 +let root: Root;
123 +let container: HTMLDivElement;
124 +
125 +function renderSetup(
126 + options: {
127 + readOnly?: boolean;
128 + provider?: ServerProvider;
129 + enabled?: boolean;
130 + binaryPath?: string;
131 + } = {},
132 +) {
133 + return act(async () =>
134 + root.render(
135 + <ProviderSetupSection
136 + environmentId={environmentId}
137 + environmentLabel="Remote Google device"
138 + instanceId={instanceId}
139 + provider={options.provider ?? provider}
140 + binaryPath={options.binaryPath}
141 + enabled={options.enabled ?? true}
142 + readOnly={options.readOnly ?? false}
143 + onEnable={vi.fn()}
144 + />,
145 + ),
146 + );
147 +}
148 +
149 +function button(label: string) {
150 + return (
151 + [...container.querySelectorAll("button")].find(
152 + (element) => element.textContent === label || element.getAttribute("aria-label") === label,
153 + ) ?? null
154 + );
155 +}
156 +async function click(label: string) {
157 + const target = button(label);
158 + expect(target, `button ${label}`).not.toBeNull();
159 + expect(target!.disabled, `${label} disabled`).toBe(false);
160 + await act(async () => target!.click());
161 +}
162 +function occurrences(text: string) {
163 + return (container.textContent ?? "").split(text).length - 1;
164 +}
165 +const callbackInput = () =>
166 + container.querySelector<HTMLInputElement>(`[id="provider-callback-${instanceId}"]`)!;
167 +
168 +describe("Antigravity setup", () => {
169 + beforeEach(() => {
170 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
171 + vi.clearAllMocks();
172 + setup.auth = authState();
173 + setup.installation = {
174 + driver: ProviderDriverKind.make("antigravity"),
175 + operationId: null,
176 + phase: "idle",
177 + downloadedBytes: 0,
178 + totalBytes: null,
179 + version: null,
180 + installedVersion: null,
181 + canRemove: false,
182 + message: null,
183 + };
184 + for (const command of [
185 + setup.startAuth,
186 + setup.completeAuth,
187 + setup.cancelAuth,
188 + setup.logoutAuth,
189 + setup.startInstall,
190 + setup.cancelInstall,
191 + setup.removeInstall,
192 + ]) {
193 + command.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
194 + }
195 + setup.confirm.mockReset().mockResolvedValue(false);
196 + container = document.createElement("div");
197 + document.body.append(container);
198 + root = createRoot(container);
199 + });
200 +
201 + afterEach(async () => {
202 + await act(async () => root.unmount());
203 + container.remove();
204 + vi.unstubAllGlobals();
205 + });
206 +
207 + it("waits for verified auth after submitting a callback to the selected environment", async () => {
208 + const callbackUrl = "http://127.0.0.1:5555/?state=test-only&code=test-only";
209 + await renderSetup();
210 + await act(async () => userEvent.fill(callbackInput(), callbackUrl));
211 + await click("Continue");
212 +
213 + expect(setup.completeAuth).toHaveBeenCalledWith({
214 + environmentId,
215 + input: { instanceId, flowId: "flow-1", callbackUrl },
216 + });
217 + expect(occurrences("Signed in.")).toBe(0);
218 + expect(callbackInput().value).toBe("");
219 +
220 + setup.auth = authState({ phase: "verifying", authorizationUrl: null });
221 + await publish();
222 + expect(occurrences("Signed in.")).toBe(0);
223 + setup.auth = authState({ phase: "succeeded", authorizationUrl: null });
224 + await renderSetup({
225 + provider: { ...provider, status: "ready", auth: { status: "authenticated" } },
226 + });
227 + expect(occurrences("Signed in.")).toBe(1);
228 + });
229 +
230 + it("offers sign-in again when credentials expire after a completed auth flow", async () => {
231 + setup.auth = authState({
232 + phase: "succeeded",
233 + authorizationUrl: null,
234 + message: "Google sign-in complete.",
235 + });
236 + await renderSetup({
237 + provider: { ...provider, status: "ready", auth: { status: "authenticated" } },
238 + });
239 + await renderSetup();
240 + expect(button("Sign in")).not.toBeNull();
241 + expect(occurrences("Signed in.")).toBe(0);
242 + expect(occurrences("Google sign-in complete.")).toBe(0);
243 + });
244 +
245 + it("does not send a callback left over from a replaced sign-in flow", async () => {
246 + const interaction = {
247 + type: "browser" as const,
248 + id: "same-interaction",
249 + url: "https://example.com/login",
250 + requiresConsent: false,
251 + acceptsCallback: true,
252 + };
253 + setup.auth = authState({ interaction });
254 + await renderSetup();
255 + await act(async () =>
256 + userEvent.fill(callbackInput(), "http://127.0.0.1:5555/?state=old-flow&code=test-only"),
257 + );
258 + setup.auth = authState({ flowId: "flow-2", interaction });
259 + await publish();
260 + expect(callbackInput().value).toBe("");
261 + await act(async () => callbackInput().form!.requestSubmit());
262 +
263 + expect(setup.completeAuth).not.toHaveBeenCalled();
264 + expect(setup.authState).toHaveBeenLastCalledWith({ environmentId, input: { instanceId } });
265 + });
266 +
267 + it("coalesces repeated sign-in clicks while start is pending", async () => {
268 + setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
269 + const pending = deferred<{ _tag: "Success"; value: undefined }>();
270 + setup.startAuth.mockReturnValueOnce(pending.promise);
271 + await renderSetup();
272 + const signIn = button("Sign in")!;
273 + // Both clicks land before React re-renders the button as disabled.
274 + await act(async () => {
275 + signIn.click();
276 + signIn.click();
277 + });
278 +
279 + expect(setup.startAuth).toHaveBeenCalledTimes(1);
280 + expect(setup.startAuth).toHaveBeenCalledWith({ environmentId, input: { instanceId } });
281 + await act(async () => pending.resolve({ _tag: "Success", value: undefined }));
282 + });
283 +
284 + it("shows a repeated runtime status message only once", async () => {
285 + setup.installation = {
286 + ...setup.installation!,
287 + operationId: "install-1",
288 + phase: "verifying",
289 + message: "Checking the downloaded runtime.",
290 + };
291 +
292 + await renderSetup();
293 + expect(occurrences("Checking the downloaded runtime.")).toBe(1);
294 + });
295 +
296 + it("removes an owned damaged runtime only after confirmation", async () => {
297 + setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
298 + setup.installation = {
299 + ...setup.installation!,
300 + phase: "failed",
301 + canRemove: true,
302 + installedVersion: null,
303 + };
304 + await renderSetup();
305 + await click("Remove downloaded runtime");
306 + expect(setup.confirm).toHaveBeenCalledOnce();
307 + expect(setup.removeInstall).not.toHaveBeenCalled();
308 +
309 + setup.confirm.mockResolvedValue(true);
310 + await click("Remove downloaded runtime");
311 + expect(setup.removeInstall).toHaveBeenCalledWith({ environmentId, input: { instanceId } });
312 + });
313 +
314 + it.each([true, false])(
315 + "can sign out a verified account when its instance is enabled=%s",
316 + async (enabled) => {
317 + setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
318 + setup.confirm.mockResolvedValue(true);
319 + await renderSetup({
320 + enabled,
321 + provider: {
322 + ...provider,
323 + enabled,
324 + installed: false,
325 + status: enabled ? "warning" : "disabled",
326 + auth: { status: "authenticated" },
327 + },
328 + });
329 + await click("Sign out");
330 + expect(setup.logoutAuth).toHaveBeenCalledWith({ environmentId, input: { instanceId } });
331 + },
332 + );
333 +
334 + it.each(["unauthenticated", "unknown"] as const)(
335 + "does not offer sign-out for an unverified %s account",
336 + async (status) => {
337 + setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
338 + await renderSetup({
339 + provider: { ...provider, auth: { status, canLogout: true } },
340 + });
341 + expect(button("Sign in")).not.toBeNull();
342 + expect(button("Sign out")).toBeNull();
343 + expect(button("Change account")).toBeNull();
344 + },
345 + );
346 +
347 + it("offers account actions after verified login when discovery cannot identify auth", async () => {
348 + setup.auth = authState({ phase: "succeeded", flowId: null, authorizationUrl: null });
349 + await renderSetup({ provider: { ...provider, auth: { status: "unknown" } } });
350 + expect(button("Change account")).not.toBeNull();
351 + expect(button("Sign out")).not.toBeNull();
352 + expect(button("Sign in")).toBeNull();
353 + });
354 +
355 + it("does not let a shared managed install hide an invalid custom binary path", async () => {
356 + setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
357 + setup.installation = {
358 + ...setup.installation!,
359 + installedVersion: "test-version",
360 + canRemove: true,
361 + };
362 + await renderSetup({
363 + provider: { ...provider, installed: false },
364 + binaryPath: "/missing/antigravity",
365 + });
366 + expect(button("Sign in")?.disabled).toBe(true);
367 + expect(setup.startAuth).not.toHaveBeenCalled();
368 + });
369 +
370 + it.each(["read-only", "older-server"] as const)(
371 + "does not open private setup subscriptions for a %s view",
372 + async (mode) => {
373 + const { setup: _setup, ...olderProvider } = provider;
374 + await renderSetup(mode === "read-only" ? { readOnly: true } : { provider: olderProvider });
375 + expect(setup.authState).not.toHaveBeenCalled();
376 + expect(setup.installState).not.toHaveBeenCalled();
377 + expect(setup.startAuth).not.toHaveBeenCalled();
378 + },
379 + );
380 +});
apps/web/src/components/settings/ProviderSetupSection.test.tsx deleted
-426
@@ -1,426 +0,0 @@
1 -import { cloneElement, isValidElement, type FunctionComponent, type ReactElement } from "react";
2 -import {
3 - EnvironmentId,
4 - ProviderDriverKind,
5 - ProviderInstanceId,
6 - type ProviderAuthState,
7 - type ProviderInstallState,
8 - type ServerProvider,
9 -} from "@t3tools/contracts";
10 -import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
11 -
12 -import { visitElements } from "../../test/reactElementTree";
13 -import { reactHookHarness as hooks } from "../../test/reactHookHarness";
14 -
15 -const setup = vi.hoisted(() => ({
16 - auth: null as ProviderAuthState | null,
17 - installation: null as ProviderInstallState | null,
18 - authState: vi.fn(() => "auth"),
19 - installState: vi.fn(() => "installation"),
20 - startAuth: vi.fn(),
21 - completeAuth: vi.fn(),
22 - respondAuth: vi.fn(),
23 - cancelAuth: vi.fn(),
24 - logoutAuth: vi.fn(),
25 - startInstall: vi.fn(),
26 - cancelInstall: vi.fn(),
27 - removeInstall: vi.fn(),
28 - confirm: vi.fn(),
29 -}));
30 -
31 -vi.mock("react", async (importOriginal) => {
32 - const actual = await importOriginal<typeof import("react")>();
33 - const { reactHookHarness } = await import("../../test/reactHookHarness");
34 - return {
35 - ...actual,
36 - useRef: reactHookHarness.useRef,
37 - useState: reactHookHarness.useState,
38 - };
39 -});
40 -
41 -vi.mock("react/compiler-runtime", async () => {
42 - const { reactHookHarness } = await import("../../test/reactHookHarness");
43 - return { c: reactHookHarness.useMemoCache };
44 -});
45 -
46 -vi.mock("../../state/server", () => ({
47 - serverEnvironment: {
48 - providerAuthState: setup.authState,
49 - providerInstallState: setup.installState,
50 - startProviderAuth: setup.startAuth,
51 - completeProviderAuth: setup.completeAuth,
52 - respondProviderAuth: setup.respondAuth,
53 - cancelProviderAuth: setup.cancelAuth,
54 - logoutProviderAuth: setup.logoutAuth,
55 - startProviderInstall: setup.startInstall,
56 - cancelProviderInstall: setup.cancelInstall,
57 - removeProviderInstallation: setup.removeInstall,
58 - },
59 -}));
60 -
61 -vi.mock("../../state/use-atom-command", () => ({
62 - useAtomCommand: (command: unknown) => command,
63 -}));
64 -
65 -vi.mock("../../state/query", () => ({
66 - useEnvironmentQuery: (atom: string) => ({
67 - data: atom === "auth" ? setup.auth : setup.installation,
68 - error: null,
69 - isPending: false,
70 - refresh: vi.fn(),
71 - }),
72 -}));
73 -
74 -vi.mock("../../localApi", () => ({
75 - ensureLocalApi: () => ({ dialogs: { confirm: setup.confirm } }),
76 -}));
77 -
78 -import { ProviderAuthenticationSection } from "./ProviderAuthenticationSection";
79 -import { ProviderSetupSection } from "./ProviderSetupSection";
80 -
81 -const environmentId = EnvironmentId.make("remote-google");
82 -const instanceId = ProviderInstanceId.make("antigravity_work");
83 -const provider: ServerProvider = {
84 - instanceId,
85 - driver: ProviderDriverKind.make("antigravity"),
86 - installed: true,
87 - enabled: true,
88 - version: "test-version",
89 - status: "error",
90 - auth: { status: "unauthenticated" },
91 - checkedAt: "2026-09-02T00:00:00.000Z",
92 - models: [],
93 - skills: [],
94 - slashCommands: [],
95 - setup: { canAuthenticate: true, canInstall: true },
96 -};
97 -
98 -function authState(patch: Partial<ProviderAuthState> = {}): ProviderAuthState {
99 - return {
100 - instanceId,
101 - phase: "waiting",
102 - flowId: "flow-1",
103 - authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth?state=test-only",
104 - expiresAt: "2026-09-02T00:05:00.000Z",
105 - message: null,
106 - ...patch,
107 - };
108 -}
109 -
110 -function renderSetup(
111 - options: {
112 - readOnly?: boolean;
113 - provider?: ServerProvider;
114 - enabled?: boolean;
115 - binaryPath?: string;
116 - } = {},
117 -) {
118 - hooks.beginRender();
119 - const view = ProviderSetupSection({
120 - environmentId,
121 - environmentLabel: "Remote Google device",
122 - instanceId,
123 - provider: options.provider ?? provider,
124 - binaryPath: options.binaryPath,
125 - enabled: options.enabled ?? true,
126 - readOnly: options.readOnly ?? false,
127 - onEnable: vi.fn(),
128 - });
129 - const actions = visitElements(
130 - view,
131 - (element) =>
132 - typeof element.type === "function" &&
133 - element.props.environmentId === environmentId &&
134 - element.props.instanceId === instanceId,
135 - );
136 - if (!actions) return view;
137 - const Actions = actions.type as FunctionComponent<Record<string, unknown>>;
138 - function expand(node: unknown): unknown {
139 - if (Array.isArray(node)) return node.map(expand);
140 - if (!isValidElement<Record<string, unknown>>(node)) return node;
141 - if (node.type === ProviderAuthenticationSection)
142 - return ProviderAuthenticationSection(
143 - node.props as Parameters<typeof ProviderAuthenticationSection>[0],
144 - );
145 - return cloneElement(
146 - node,
147 - Object.fromEntries(Object.entries(node.props).map(([key, value]) => [key, expand(value)])),
148 - );
149 - }
150 - return expand(Actions(actions.props));
151 -}
152 -
153 -function button(view: unknown, label: string) {
154 - return visitElements(
155 - view,
156 - (element) =>
157 - (element.props.children === label || element.props["aria-label"] === label) &&
158 - typeof element.props.onClick === "function",
159 - );
160 -}
161 -
162 -function countElements(
163 - node: unknown,
164 - predicate: (element: ReactElement<Record<string, unknown>>) => boolean,
165 -): number {
166 - if (Array.isArray(node)) {
167 - return node.reduce((total, child) => total + countElements(child, predicate), 0);
168 - }
169 - if (!isValidElement<Record<string, unknown>>(node)) return 0;
170 - return (
171 - Number(predicate(node)) +
172 - Object.values(node.props).reduce<number>(
173 - (total, value) => total + countElements(value, predicate),
174 - 0,
175 - )
176 - );
177 -}
178 -
179 -function click(view: unknown, label: string) {
180 - const target = button(view, label);
181 - if (!target) throw new Error(`Missing button: ${label}`);
182 - if (target.props.disabled) throw new Error(`Button is disabled: ${label}`);
183 - (target.props.onClick as () => void)();
184 -}
185 -
186 -function setCallback(view: unknown, value: string) {
187 - const input = visitElements(
188 - view,
189 - (element) => element.props.id === `provider-callback-${instanceId}`,
190 - );
191 - if (!input) throw new Error("Missing callback input.");
192 - (input.props.onChange as (event: { target: { value: string } }) => void)({ target: { value } });
193 -}
194 -
195 -function submitCallback(view: unknown) {
196 - const form = visitElements(view, (element) => element.type === "form");
197 - if (!form) throw new Error("Missing callback form.");
198 - (form.props.onSubmit as (event: { preventDefault: () => void }) => void)({
199 - preventDefault: vi.fn(),
200 - });
201 -}
202 -
203 -async function flushPromises() {
204 - await Promise.resolve();
205 - await Promise.resolve();
206 - await Promise.resolve();
207 -}
208 -
209 -describe("Antigravity setup", () => {
210 - beforeEach(() => {
211 - hooks.reset();
212 - vi.clearAllMocks();
213 - setup.auth = authState();
214 - setup.installation = {
215 - driver: ProviderDriverKind.make("antigravity"),
216 - operationId: null,
217 - phase: "idle",
218 - downloadedBytes: 0,
219 - totalBytes: null,
220 - version: null,
221 - installedVersion: null,
222 - canRemove: false,
223 - message: null,
224 - };
225 - for (const command of [
226 - setup.startAuth,
227 - setup.completeAuth,
228 - setup.cancelAuth,
229 - setup.logoutAuth,
230 - setup.startInstall,
231 - setup.cancelInstall,
232 - setup.removeInstall,
233 - ]) {
234 - command.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
235 - }
236 - setup.confirm.mockReset().mockResolvedValue(false);
237 - });
238 -
239 - it("waits for verified auth after submitting a callback to the selected environment", async () => {
240 - const callbackUrl = "http://127.0.0.1:5555/?state=test-only&code=test-only";
241 - setCallback(renderSetup(), callbackUrl);
242 - submitCallback(renderSetup());
243 - await flushPromises();
244 -
245 - expect(setup.completeAuth).toHaveBeenCalledWith({
246 - environmentId,
247 - input: { instanceId, flowId: "flow-1", callbackUrl },
248 - });
249 - let view = renderSetup();
250 - expect(visitElements(view, (element) => element.props.children === "Signed in.")).toBeNull();
251 - expect(
252 - visitElements(view, (element) => element.props.id === `provider-callback-${instanceId}`)
253 - ?.props.value,
254 - ).toBe("");
255 -
256 - setup.auth = authState({ phase: "verifying", authorizationUrl: null });
257 - expect(
258 - visitElements(renderSetup(), (element) => element.props.children === "Signed in."),
259 - ).toBeNull();
260 - setup.auth = authState({ phase: "succeeded", authorizationUrl: null });
261 - view = renderSetup({
262 - provider: { ...provider, status: "ready", auth: { status: "authenticated" } },
263 - });
264 - expect(
265 - visitElements(view, (element) => element.props.children === "Signed in."),
266 - ).not.toBeNull();
267 - });
268 -
269 - it("offers sign-in again when credentials expire after a completed auth flow", () => {
270 - setup.auth = authState({
271 - phase: "succeeded",
272 - authorizationUrl: null,
273 - message: "Google sign-in complete.",
274 - });
275 - renderSetup({
276 - provider: { ...provider, status: "ready", auth: { status: "authenticated" } },
277 - });
278 - const expired = renderSetup();
279 - expect(button(expired, "Sign in")).not.toBeNull();
280 - expect(visitElements(expired, (element) => element.props.children === "Signed in.")).toBeNull();
281 - expect(
282 - visitElements(expired, (element) => element.props.children === "Google sign-in complete."),
283 - ).toBeNull();
284 - });
285 -
286 - it("does not send a callback left over from a replaced sign-in flow", async () => {
287 - const interaction = {
288 - type: "browser" as const,
289 - id: "same-interaction",
290 - url: "https://example.com/login",
291 - requiresConsent: false,
292 - acceptsCallback: true,
293 - };
294 - setup.auth = authState({ interaction });
295 - setCallback(renderSetup(), "http://127.0.0.1:5555/?state=old-flow&code=test-only");
296 - setup.auth = authState({ flowId: "flow-2", interaction });
297 - submitCallback(renderSetup());
298 - await flushPromises();
299 -
300 - expect(setup.completeAuth).not.toHaveBeenCalled();
301 - expect(setup.authState).toHaveBeenLastCalledWith({ environmentId, input: { instanceId } });
302 - });
303 -
304 - it("coalesces repeated sign-in clicks while start is pending", async () => {
305 - setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
306 - let completeStart: (value: { _tag: "Success"; value: undefined }) => void = () => {
307 - throw new Error("Missing start resolver.");
308 - };
309 - const pending = new Promise<{ _tag: "Success"; value: undefined }>((resolve) => {
310 - completeStart = resolve;
311 - });
312 - setup.startAuth.mockReturnValueOnce(pending);
313 - const view = renderSetup();
314 - click(view, "Sign in");
315 - click(view, "Sign in");
316 -
317 - expect(setup.startAuth).toHaveBeenCalledTimes(1);
318 - expect(setup.startAuth).toHaveBeenCalledWith({ environmentId, input: { instanceId } });
319 - completeStart({ _tag: "Success", value: undefined });
320 - await flushPromises();
321 - });
322 -
323 - it("shows a repeated runtime status message only once", () => {
324 - setup.installation = {
325 - ...setup.installation!,
326 - operationId: "install-1",
327 - phase: "verifying",
328 - message: "Checking the downloaded runtime.",
329 - };
330 -
331 - const view = renderSetup();
332 - expect(
333 - countElements(
334 - view,
335 - (element) => element.props.children === "Checking the downloaded runtime.",
336 - ),
337 - ).toBe(1);
338 - });
339 -
340 - it("removes an owned damaged runtime only after confirmation", async () => {
341 - setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
342 - setup.installation = {
343 - ...setup.installation!,
344 - phase: "failed",
345 - canRemove: true,
346 - installedVersion: null,
347 - };
348 - const view = renderSetup();
349 - click(view, "Remove downloaded runtime");
350 - await flushPromises();
351 - expect(setup.removeInstall).not.toHaveBeenCalled();
352 -
353 - setup.confirm.mockResolvedValue(true);
354 - click(view, "Remove downloaded runtime");
355 - await flushPromises();
356 - expect(setup.removeInstall).toHaveBeenCalledWith({ environmentId, input: { instanceId } });
357 - });
358 -
359 - it.each([true, false])(
360 - "can sign out a verified account when its instance is enabled=%s",
361 - async (enabled) => {
362 - setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
363 - setup.confirm.mockResolvedValue(true);
364 - const view = renderSetup({
365 - enabled,
366 - provider: {
367 - ...provider,
368 - enabled,
369 - installed: false,
370 - status: enabled ? "warning" : "disabled",
371 - auth: { status: "authenticated" },
372 - },
373 - });
374 - click(view, "Sign out");
375 - await flushPromises();
376 - expect(setup.logoutAuth).toHaveBeenCalledWith({ environmentId, input: { instanceId } });
377 - },
378 - );
379 -
380 - it.each(["unauthenticated", "unknown"] as const)(
381 - "does not offer sign-out for an unverified %s account",
382 - (status) => {
383 - setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
384 - const view = renderSetup({
385 - provider: { ...provider, auth: { status, canLogout: true } },
386 - });
387 - expect(button(view, "Sign in")).not.toBeNull();
388 - expect(button(view, "Sign out")).toBeNull();
389 - expect(button(view, "Change account")).toBeNull();
390 - },
391 - );
392 -
393 - it("offers account actions after verified login when discovery cannot identify auth", () => {
394 - setup.auth = authState({ phase: "succeeded", flowId: null, authorizationUrl: null });
395 - const view = renderSetup({ provider: { ...provider, auth: { status: "unknown" } } });
396 - expect(button(view, "Change account")).not.toBeNull();
397 - expect(button(view, "Sign out")).not.toBeNull();
398 - expect(button(view, "Sign in")).toBeNull();
399 - });
400 -
401 - it("does not let a shared managed install hide an invalid custom binary path", () => {
402 - setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
403 - setup.installation = {
404 - ...setup.installation!,
405 - installedVersion: "test-version",
406 - canRemove: true,
407 - };
408 - const view = renderSetup({
409 - provider: { ...provider, installed: false },
410 - binaryPath: "/missing/antigravity",
411 - });
412 - expect(button(view, "Sign in")?.props.disabled).toBe(true);
413 - expect(setup.startAuth).not.toHaveBeenCalled();
414 - });
415 -
416 - it.each(["read-only", "older-server"] as const)(
417 - "does not open private setup subscriptions for a %s view",
418 - (mode) => {
419 - const { setup: _setup, ...olderProvider } = provider;
420 - renderSetup(mode === "read-only" ? { readOnly: true } : { provider: olderProvider });
421 - expect(setup.authState).not.toHaveBeenCalled();
422 - expect(setup.installState).not.toHaveBeenCalled();
423 - expect(setup.startAuth).not.toHaveBeenCalled();
424 - },
425 - );
426 -});
apps/web/src/components/settings/SettingsPanels.restore.browser.test.tsx renamed
+45 -44
@@ -1,7 +1,7 @@
1 import { DEFAULT_UNIFIED_SETTINGS, type UnifiedSettings } from "@t3tools/contracts";
2 -import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
3 -
4 -import { reactHookHarness as hooks } from "../../test/reactHookHarness";
2 +import { act, useEffect } from "react";
3 +import { createRoot, type Root } from "react-dom/client";
4 +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
5
6 const state = vi.hoisted(() => ({
7 settings: null as UnifiedSettings | null,
@@ -9,57 +9,59 @@ const state = vi.hoisted(() => ({
9 confirm: vi.fn(),
10 }));
11
12 -vi.mock("react", async (importOriginal) => {
13 - const actual = await importOriginal<typeof import("react")>();
14 - const { reactHookHarness } = await import("../../test/reactHookHarness");
15 - return {
16 - ...actual,
17 - useCallback: reactHookHarness.useCallback,
18 - useMemo: reactHookHarness.useMemo,
19 - };
20 -});
21 -
22 -vi.mock("react/compiler-runtime", async () => {
23 - const { reactHookHarness } = await import("../../test/reactHookHarness");
24 - return { c: reactHookHarness.useMemoCache };
25 -});
26 -
27 -vi.mock("../../hooks/useTheme", async (importOriginal) => ({
28 - ...(await importOriginal<typeof import("../../hooks/useTheme")>()),
29 - useTheme: () => ({
30 - theme: "system",
31 - followSystem: true,
32 - themeHalves: null,
33 - setTheme: vi.fn(),
34 - setFollowSystem: vi.fn(),
35 - setThemeHalf: vi.fn(),
36 - clearThemeHalves: vi.fn(),
37 - }),
12 +vi.mock(import("../../hooks/useTheme"), async (original) => ({
13 + ...(await original()),
14 + useTheme: () =>
15 + ({
16 + theme: "system",
17 + followSystem: true,
18 + themeHalves: null,
19 + setTheme: vi.fn(),
20 + setFollowSystem: vi.fn(),
21 + setThemeHalf: vi.fn(),
22 + clearThemeHalves: vi.fn(),
23 + }) as never,
24 readThemePreference: () => "system",
25 readThemeHalves: () => null,
26 readAppearanceModePreference: () => "system",
27 }));
42 -
43 -vi.mock("./useScopedSettings", async (importOriginal) => ({
44 - ...(await importOriginal<typeof import("./useScopedSettings")>()),
45 - useScopedSettings: () => state.settings,
28 +vi.mock(import("./useScopedSettings"), async (original) => ({
29 + ...(await original()),
30 + useScopedSettings: (() => state.settings!) as never,
31 useUpdateScopedSettings: () => state.update,
32 }));
48 -
49 -vi.mock("../../localApi", async (importOriginal) => ({
50 - ...(await importOriginal<typeof import("../../localApi")>()),
51 - readLocalApi: () => ({ dialogs: { confirm: state.confirm } }),
33 +vi.mock(import("../../localApi"), async (original) => ({
34 + ...(await original()),
35 + readLocalApi: () => ({ dialogs: { confirm: state.confirm } }) as never,
36 }));
37
38 import { useSettingsRestore } from "./SettingsPanels";
39
56 -beforeEach(() => {
57 - hooks.reset();
40 +let root: Root;
41 +let restore: ReturnType<typeof useSettingsRestore>;
42 +
43 +function Probe() {
44 + const result = useSettingsRestore();
45 + useEffect(() => {
46 + restore = result;
47 + });
48 + return null;
49 +}
50 +
51 +beforeEach(async () => {
52 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
53 vi.clearAllMocks();
54 state.settings = { ...DEFAULT_UNIFIED_SETTINGS };
55 state.confirm.mockResolvedValue(true);
56 + root = createRoot(document.createElement("div"));
57 +});
58 +afterEach(async () => {
59 + await act(async () => root.unmount());
60 + vi.unstubAllGlobals();
61 });
62
63 +const render = () => act(async () => root.render(<Probe />));
64 +
65 describe("restoring V2 settings", () => {
66 it.each([
67 ["persistComposerContextStrip", "Composer context"],
@@ -67,11 +69,10 @@ describe("restoring V2 settings", () => {
69 ["snoozeLimitedThreads", "Snooze limited threads"],
70 ] as const)("restores %s when it is the only changed setting", async (key, label) => {
71 state.settings = { ...DEFAULT_UNIFIED_SETTINGS, [key]: true };
70 - hooks.beginRender();
71 - const restore = useSettingsRestore();
72 + await render();
73
74 expect(restore.changedSettingLabels).toEqual([label]);
74 - await restore.restoreDefaults();
75 + await act(() => restore.restoreDefaults());
76
77 expect(state.confirm.mock.calls[0]?.[0]).toContain(label);
78 expect(state.update).toHaveBeenCalledOnce();
@@ -81,9 +82,9 @@ describe("restoring V2 settings", () => {
82 it("does not reset settings after cancellation", async () => {
83 state.settings = { ...DEFAULT_UNIFIED_SETTINGS, autoResumeLimitedThreads: true };
84 state.confirm.mockResolvedValue(false);
84 - hooks.beginRender();
85 + await render();
86
86 - await useSettingsRestore().restoreDefaults();
87 + await act(() => restore.restoreDefaults());
88
89 expect(state.confirm).toHaveBeenCalledOnce();
90 expect(state.update).not.toHaveBeenCalled();
apps/web/src/components/settings/SnapShotSettings.browser.test.tsx new
+368
@@ -0,0 +1,368 @@
1 +import {
2 + DEFAULT_CLIENT_SETTINGS,
3 + type ClientSettingsPatch,
4 + type DesktopSnapShotState,
5 +} from "@t3tools/contracts";
6 +import { act } from "react";
7 +import { createRoot, type Root } from "react-dom/client";
8 +import { userEvent } from "vite-plus/test/browser";
9 +import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
10 +
11 +const bridge = vi.hoisted(() => ({
12 + getSnapShotState: vi.fn<() => Promise<DesktopSnapShotState>>(),
13 + setSnapShotShortcutSuppressed: vi.fn(),
14 + checkSnapShotShortcut: vi.fn(),
15 + previewSnapShotConfig: vi.fn(),
16 + applySnapShotConfig: vi.fn(),
17 + setupSnapShot: vi.fn(),
18 + requestSnapShotPermissions: vi.fn(),
19 + onMenuAction: vi.fn(),
20 + onSnapShotEvent: vi.fn(() => () => undefined),
21 +}));
22 +const toast = vi.hoisted(() => vi.fn());
23 +// Client settings behave like the real store: an update re-renders every reader.
24 +const settingsStore = vi.hoisted(() => ({
25 + current: {} as typeof DEFAULT_CLIENT_SETTINGS,
26 + listeners: new Set<() => void>(),
27 + update: vi.fn<(patch: ClientSettingsPatch) => Promise<void>>(),
28 + set(next: typeof DEFAULT_CLIENT_SETTINGS) {
29 + settingsStore.current = next;
30 + for (const listener of settingsStore.listeners) listener();
31 + },
32 +}));
33 +vi.mock(import("@tanstack/react-router"), async (original) => ({
34 + ...(await original()),
35 + useLocation: ((options?: { select?: (location: unknown) => unknown }) =>
36 + options?.select?.({ hash: "", pathname: "/settings/snapshots", state: {} }) ?? "") as never,
37 + useNavigate: (() => vi.fn()) as never,
38 +}));
39 +vi.mock(import("../../lib/desktopSnapShot"), async (original) => ({
40 + ...(await original()),
41 + getDesktopSnapShotBridge: () => bridge as never,
42 +}));
43 +vi.mock(import("../ui/toast"), async (original) => {
44 + const actual = await original();
45 + return { ...actual, toastManager: { ...actual.toastManager, add: toast } };
46 +});
47 +vi.mock(import("../../hooks/useSettings"), async (original) => {
48 + const { useSyncExternalStore } = await import("react");
49 + const subscribe = (listener: () => void) => {
50 + settingsStore.listeners.add(listener);
51 + return () => settingsStore.listeners.delete(listener);
52 + };
53 + return {
54 + ...(await original()),
55 + useClientSettings: (() =>
56 + useSyncExternalStore(subscribe, () => settingsStore.current)) as never,
57 + useUpdateClientSettings: () => settingsStore.update as never,
58 + };
59 +});
60 +
61 +import { readSnapShotSetupResume } from "../../lib/snapShotSetupResume";
62 +import { SnapShotSettings } from "./SnapShotSettings";
63 +
64 +let state: DesktopSnapShotState;
65 +let root: Root;
66 +let container: HTMLDivElement;
67 +
68 +async function mount() {
69 + root = createRoot(container);
70 + await act(async () => root.render(<SnapShotSettings />));
71 + await vi.waitFor(() => expect(bridge.getSnapShotState).toHaveBeenCalled());
72 + await act(async () => {});
73 +}
74 +const dialog = () => document.querySelector<HTMLElement>('[role="dialog"]');
75 +const scope = () => dialog() ?? container;
76 +function button(label: string, within: ParentNode = scope()) {
77 + return (
78 + [...within.querySelectorAll("button")].find(
79 + (element) => element.textContent?.trim() === label,
80 + ) ?? null
81 + );
82 +}
83 +async function click(label: string) {
84 + const target = button(label);
85 + expect(target, `button ${label}`).not.toBeNull();
86 + await act(async () => target!.click());
87 +}
88 +const recorder = () => scope().querySelector<HTMLButtonElement>("[data-keybinding-capture]")!;
89 +const toggle = (label: string) =>
90 + container.querySelector<HTMLButtonElement>(`[role="switch"][aria-label="${label}"]`)!;
91 +const stepTitle = () => dialog()?.querySelector("h3")?.textContent;
92 +
93 +beforeEach(() => {
94 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
95 + vi.clearAllMocks();
96 + localStorage.clear();
97 + Object.defineProperty(navigator, "platform", { configurable: true, get: () => "Linux" });
98 + settingsStore.current = { ...DEFAULT_CLIENT_SETTINGS, snapShotEnabled: true };
99 + state = {
100 + mode: "portal",
101 + linuxBackend: "hyprland",
102 + shortcut: DEFAULT_CLIENT_SETTINGS.snapShotShortcut,
103 + shortcutRegistered: false,
104 + shortcutActionRegistered: true,
105 + shortcutMessage: null,
106 + message: null,
107 + hyprlandHelper: { status: "ready", message: "Ready" },
108 + };
109 + bridge.getSnapShotState.mockImplementation(async () => state);
110 + bridge.setSnapShotShortcutSuppressed.mockResolvedValue(undefined);
111 + bridge.checkSnapShotShortcut.mockResolvedValue({ available: true, message: null });
112 + bridge.requestSnapShotPermissions.mockResolvedValue(undefined);
113 + bridge.setupSnapShot.mockReset().mockResolvedValue(undefined);
114 + settingsStore.update.mockImplementation(async (patch) => {
115 + state = { ...state, shortcut: patch.snapShotShortcut ?? state.shortcut };
116 + settingsStore.set({ ...settingsStore.current, ...patch });
117 + });
118 + container = document.createElement("div");
119 + document.body.append(container);
120 +});
121 +afterEach(async () => {
122 + await act(async () => root.unmount());
123 + container.remove();
124 + localStorage.clear();
125 + Reflect.deleteProperty(navigator, "platform");
126 + vi.unstubAllGlobals();
127 +});
128 +
129 +it.each(["niri", "hyprland"] as const)(
130 + "reopens %s setup at Shortcut without reading config or expanding Settings",
131 + async (desktop) => {
132 + state = { ...state, linuxBackend: desktop };
133 + await mount();
134 + expect(dialog()).toBeNull();
135 + expect(button("Review changes", container)).toBeNull();
136 + await click("Change shortcut");
137 + expect(stepTitle()).toBe("Choose your shortcut");
138 + expect(button("Review changes")).not.toBeNull();
139 + expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();
140 + expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
141 + await click("Close");
142 + expect(dialog()).toBeNull();
143 + expect(settingsStore.update).not.toHaveBeenCalled();
144 + expect(settingsStore.current.snapShotEnabled).toBe(true);
145 + },
146 +);
147 +
148 +it("returns to Access if the Hyprland helper needs attention before changing keys", async () => {
149 + await mount();
150 + state = { ...state, hyprlandHelper: { status: "not-installed", message: "Install helper" } };
151 + await click("Change shortcut");
152 + expect(stepTitle()).toBe("Allow snapshots");
153 + expect(button("Install helper")).not.toBeNull();
154 + expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();
155 +});
156 +
157 +it.each(["direct", "gnome-extension", "kde"] as const)(
158 + "keeps %s shortcut recording and saving inline",
159 + async (backend) => {
160 + state = {
161 + ...state,
162 + mode: backend === "direct" ? "direct" : "portal",
163 + linuxBackend: backend === "direct" ? undefined : backend,
164 + shortcutRegistered: true,
165 + shortcutLabel: backend === "direct" ? undefined : "Press <Shift><Control>2",
166 + shortcutMessage: backend === "direct" ? null : "Desktop shortcut: Press <Shift><Control>2",
167 + };
168 + await mount();
169 + if (backend !== "direct") {
170 + expect(recorder().getAttribute("aria-label")).toBe(
171 + "Record snapshot shortcut, currently Ctrl+Shift+2",
172 + );
173 + }
174 + await act(async () => userEvent.click(recorder()));
175 + await act(async () => userEvent.keyboard("{Control>}{Alt>}y{/Alt}{/Control}"));
176 + expect(bridge.checkSnapShotShortcut).toHaveBeenCalledOnce();
177 + expect(container.textContent).toContain("Ready to save.");
178 + expect(recorder().getAttribute("aria-label")).toBe(
179 + "Record snapshot shortcut, currently Ctrl+Alt+Y",
180 + );
181 + await click("Save");
182 + expect(settingsStore.update).toHaveBeenCalledWith({
183 + snapShotShortcut: expect.objectContaining({ key: "y", modKey: true, altKey: true }),
184 + });
185 + expect(dialog()).toBeNull();
186 + expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();
187 + },
188 +);
189 +
190 +it("turns capture on directly on Windows without opening setup", async () => {
191 + settingsStore.current = { ...settingsStore.current, snapShotEnabled: false };
192 + state = { ...state, mode: "direct", linuxBackend: undefined, windows: true };
193 + await mount();
194 + await act(async () => toggle("Enable snapshots").click());
195 + expect(settingsStore.update).toHaveBeenCalledWith({ snapShotEnabled: true });
196 + expect(toggle("Enable snapshots").getAttribute("aria-checked")).toBe("true");
197 + expect(dialog()).toBeNull();
198 + expect(button("Manage capture")).toBeNull();
199 +});
200 +
201 +it("keeps the approved desktop shortcut when recording is cancelled in setup", async () => {
202 + state = {
203 + ...state,
204 + linuxBackend: "gnome-extension",
205 + gnomeExtension: { status: "enabled", message: "Ready" },
206 + shortcutRegistered: true,
207 + shortcutLabel: "Press <Control><Alt>8",
208 + };
209 + await mount();
210 + await click("Manage capture");
211 + expect(dialog()).not.toBeNull();
212 + expect(recorder().getAttribute("aria-label")).toBe(
213 + "Record snapshot shortcut, currently Ctrl+Alt+8",
214 + );
215 + await act(async () => userEvent.click(recorder()));
216 + expect(recorder().textContent).toBe("Press shortcut…");
217 + await act(async () => userEvent.keyboard("{Escape}"));
218 + expect(dialog()).not.toBeNull();
219 + expect(recorder().getAttribute("aria-label")).toBe(
220 + "Record snapshot shortcut, currently Ctrl+Alt+8",
221 + );
222 + expect(settingsStore.update).not.toHaveBeenCalled();
223 + expect(bridge.checkSnapShotShortcut).not.toHaveBeenCalled();
224 +});
225 +
226 +function usePortalShortcut(shortcutCanRetry: boolean) {
227 + const shortcut = {
228 + key: "2",
229 + modKey: false,
230 + ctrlKey: true,
231 + altKey: false,
232 + shiftKey: true,
233 + metaKey: false,
234 + };
235 + settingsStore.current = { ...settingsStore.current, snapShotShortcut: shortcut };
236 + state = {
237 + ...state,
238 + linuxBackend: "gnome-extension",
239 + gnomeExtension: { status: "enabled", message: "Ready" },
240 + shortcut,
241 + linuxFeedbackAvailable: true,
242 + shortcutRegistered: true,
243 + shortcutCanRetry,
244 + };
245 +}
246 +
247 +it("keeps older portal shortcuts editable without offering unsupported permissions", async () => {
248 + usePortalShortcut(false);
249 + await mount();
250 + expect(button("Shortcut permissions")).toBeNull();
251 + expect(bridge.setupSnapShot).not.toHaveBeenCalled();
252 + await act(async () => userEvent.click(recorder()));
253 + expect(recorder().textContent).toBe("Press shortcut…");
254 +});
255 +
256 +it("shows permission errors once in a toast and allows retrying", async () => {
257 + usePortalShortcut(true);
258 + bridge.setupSnapShot.mockRejectedValueOnce(new Error("The desktop service disconnected."));
259 + await mount();
260 + await click("Shortcut permissions");
261 + expect(toast).toHaveBeenCalledExactlyOnceWith({
262 + type: "error",
263 + title: "Couldn't open shortcut permissions",
264 + description: "The desktop service disconnected.",
265 + });
266 + expect(container.querySelector('[role="alert"]')).toBeNull();
267 + await click("Shortcut permissions");
268 + expect(bridge.setupSnapShot).toHaveBeenCalledTimes(2);
269 + expect(toast).toHaveBeenCalledTimes(1);
270 +});
271 +
272 +it("keeps a failed preference unchanged and reports the save error in a toast", async () => {
273 + usePortalShortcut(true);
274 + settingsStore.update.mockRejectedValueOnce(new Error("The settings file is read-only."));
275 + await mount();
276 + const flash = () => toggle("Flash captured window");
277 + expect(flash().getAttribute("aria-checked")).toBe("true");
278 + await act(async () => flash().click());
279 + expect(flash().getAttribute("aria-checked")).toBe("true");
280 + expect(toast).toHaveBeenCalledExactlyOnceWith({
281 + type: "error",
282 + title: "Couldn't save capture settings",
283 + description: "The settings file is read-only.",
284 + });
285 + await act(async () => flash().click());
286 + expect(flash().getAttribute("aria-checked")).toBe("false");
287 + expect(toast).toHaveBeenCalledTimes(1);
288 +});
289 +
290 +it("keeps setup errors in the wizard and does not toast them after closing it", async () => {
291 + usePortalShortcut(true);
292 + state = { ...state, shortcutRegistered: false };
293 + await mount();
294 + await click("Manage capture");
295 + expect(stepTitle()).toBe("Choose your shortcut");
296 + bridge.setupSnapShot.mockRejectedValueOnce(new Error("The desktop service disconnected."));
297 + await click("Shortcut permissions");
298 + expect(dialog()!.querySelector('[role="alert"]')?.textContent).toContain(
299 + "Couldn't finish this step",
300 + );
301 + expect(dialog()!.querySelector("details")?.textContent).toContain(
302 + "The desktop service disconnected.",
303 + );
304 + expect(toast).not.toHaveBeenCalled();
305 + await click("Close");
306 + expect(dialog()).toBeNull();
307 + expect(toast).not.toHaveBeenCalled();
308 +});
309 +
310 +function useMacPermissions(granted: boolean) {
311 + settingsStore.current = { ...settingsStore.current, snapShotEnabled: false };
312 + state = {
313 + mode: "direct",
314 + shortcut: DEFAULT_CLIENT_SETTINGS.snapShotShortcut,
315 + shortcutRegistered: granted,
316 + shortcutMessage: null,
317 + message: null,
318 + macPermissions: { screenRecording: granted, accessibility: granted },
319 + };
320 +}
321 +
322 +it.each([false, true])(
323 + "resumes macOS permission setup after restart and clears it on close, completed=%s",
324 + async (completed) => {
325 + useMacPermissions(false);
326 + await mount();
327 + await act(async () => toggle("Enable snapshots").click());
328 + expect(stepTitle()).toBe("Allow snapshots");
329 + bridge.setupSnapShot.mockImplementationOnce(async () => {
330 + expect(readSnapShotSetupResume()).toEqual({ wasEnabled: false });
331 + });
332 + await click("Allow");
333 + expect(bridge.setupSnapShot).toHaveBeenCalledWith("allow-screen-recording");
334 +
335 + // macOS quits the app from its permission prompt; the next launch resumes setup.
336 + await act(async () => root.unmount());
337 + state = { ...state, shortcutRegistered: true };
338 + state = { ...state, macPermissions: { screenRecording: true, accessibility: true } };
339 + await mount();
340 + expect(stepTitle()).toBe("Allow snapshots");
341 + expect(button("Finish later")).not.toBeNull();
342 + if (completed) {
343 + await click("Test capture and continue");
344 + expect(stepTitle()).toBe("Choose your shortcut");
345 + await click("Done");
346 + } else {
347 + await click("Finish later");
348 + }
349 + expect(dialog()).toBeNull();
350 + expect(readSnapShotSetupResume()).toBeNull();
351 + },
352 +);
353 +
354 +it("requires a successful macOS test capture before enabling and allows retry", async () => {
355 + useMacPermissions(true);
356 + await mount();
357 + await act(async () => toggle("Enable snapshots").click());
358 + bridge.setupSnapShot.mockRejectedValueOnce(new Error("Capture was denied"));
359 + await click("Test capture and continue");
360 + expect(dialog()!.querySelector('[role="alert"]')).not.toBeNull();
361 + expect(dialog()!.querySelector("details")?.textContent).toContain("Capture was denied");
362 + expect(stepTitle()).toBe("Allow snapshots");
363 + expect(settingsStore.current.snapShotEnabled).toBe(false);
364 + await click("Test capture and continue");
365 + expect(stepTitle()).toBe("Choose your shortcut");
366 + expect(bridge.setupSnapShot.mock.calls).toEqual([["test-mac-capture"], ["test-mac-capture"]]);
367 + expect(settingsStore.current.snapShotEnabled).toBe(true);
368 +});
apps/web/src/components/settings/SnapShotSettings.test.tsx deleted
-425
@@ -1,425 +0,0 @@
1 -import {
2 - DEFAULT_CLIENT_SETTINGS,
3 - type ClientSettingsPatch,
4 - type DesktopSnapShotState,
5 -} from "@t3tools/contracts";
6 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
7 -import { reactHookHarness as hooks } from "../../test/reactHookHarness";
8 -import { visitElements } from "../../test/reactElementTree";
9 -
10 -const effects = vi.hoisted(() => [] as (() => void)[]);
11 -vi.mock("react", async (original) => {
12 - const actual = await original<typeof import("react")>();
13 - const { reactHookHarness } = await import("../../test/reactHookHarness");
14 - return {
15 - ...actual,
16 - useCallback: reactHookHarness.useCallback,
17 - useMemo: reactHookHarness.useMemo,
18 - useRef: reactHookHarness.useRef,
19 - useState: reactHookHarness.useState,
20 - useEffect: (effect: () => void) => effects.push(effect),
21 - };
22 -});
23 -vi.mock("../../hooks/useStableCallback", () => ({
24 - useStableCallback: <F,>(fn: F) => fn,
25 -}));
26 -vi.mock("react/compiler-runtime", async () => {
27 - const { reactHookHarness } = await import("../../test/reactHookHarness");
28 - return { c: reactHookHarness.useMemoCache };
29 -});
30 -vi.mock("@effect/atom-react", () => ({ useAtomValue: () => [] }));
31 -vi.mock("../../state/environments", () => ({
32 - usePrimaryEnvironmentId: () => null,
33 - useEnvironments: () => [],
34 -}));
35 -vi.mock("../../state/server", () => ({ primaryServerKeybindingsAtom: {} }));
36 -vi.mock("./SettingsScopeContext", () => ({ useOptionalSettingsScope: () => null }));
37 -vi.mock("./SettingsScopeSentence", () => ({ SettingsScopeSentence: () => null }));
38 -const bridge = vi.hoisted(() => ({
39 - getSnapShotState: vi.fn<() => Promise<DesktopSnapShotState>>(),
40 - setSnapShotShortcutSuppressed: vi.fn(),
41 - checkSnapShotShortcut: vi.fn(),
42 - previewSnapShotConfig: vi.fn(),
43 - applySnapShotConfig: vi.fn(),
44 - setupSnapShot: vi.fn(),
45 - requestSnapShotPermissions: vi.fn().mockResolvedValue(undefined),
46 - onMenuAction: vi.fn(),
47 - onSnapShotEvent: vi.fn(() => () => undefined),
48 -}));
49 -const toastManager = vi.hoisted(() => ({ add: vi.fn() }));
50 -vi.mock("../ui/toast", () => ({ toastManager }));
51 -vi.mock("../../lib/desktopSnapShot", () => ({ getDesktopSnapShotBridge: () => bridge }));
52 -const settingsStore = vi.hoisted(() => ({
53 - current: {} as typeof DEFAULT_CLIENT_SETTINGS,
54 - update: vi.fn<(patch: ClientSettingsPatch) => Promise<void>>(),
55 -}));
56 -vi.mock("../../hooks/useSettings", () => ({
57 - useClientSettings: () => settingsStore.current,
58 - useUpdateClientSettings: () => settingsStore.update,
59 -}));
60 -
61 -import { SnapShotSettings } from "./SnapShotSettings";
62 -import { SnapShotSetupDialog } from "./SnapShotSetupDialog";
63 -import { CaptureShortcutConfig } from "./CaptureShortcutConfig";
64 -import { SnapShotShortcutKeys } from "../desktop/SnapShotShortcutKeys";
65 -
66 -let state: DesktopSnapShotState;
67 -function render() {
68 - hooks.beginRender();
69 - return SnapShotSettings();
70 -}
71 -function renderWithEffects() {
72 - effects.length = 0;
73 - const tree = render();
74 - for (const effect of effects.splice(0)) effect();
75 - return tree;
76 -}
77 -function wizard(tree: ReturnType<typeof render>) {
78 - return visitElements(tree, (element) => element.type === SnapShotSetupDialog);
79 -}
80 -function button(tree: ReturnType<typeof render>, label: string) {
81 - const node = visitElements(
82 - tree,
83 - (element) => element.props.children === label && typeof element.props.onClick === "function",
84 - );
85 - if (!node) throw new Error(`Missing button: ${label}`);
86 - return node.props as { onClick: () => void };
87 -}
88 -async function finish(promise: Promise<unknown>) {
89 - await promise;
90 - await Promise.resolve();
91 -}
92 -async function mount() {
93 - render();
94 - for (const effect of effects.splice(0)) effect();
95 - await finish(bridge.getSnapShotState.mock.results[0]!.value);
96 - return render();
97 -}
98 -beforeEach(() => {
99 - hooks.reset();
100 - effects.length = 0;
101 - vi.clearAllMocks();
102 - vi.stubGlobal("navigator", { platform: "Linux" });
103 - vi.stubGlobal("window", { addEventListener: vi.fn(), removeEventListener: vi.fn() });
104 - settingsStore.current = { ...DEFAULT_CLIENT_SETTINGS, snapShotEnabled: true };
105 - state = {
106 - mode: "portal",
107 - linuxBackend: "hyprland",
108 - shortcut: DEFAULT_CLIENT_SETTINGS.snapShotShortcut,
109 - shortcutRegistered: false,
110 - shortcutActionRegistered: true,
111 - shortcutMessage: null,
112 - message: null,
113 - hyprlandHelper: { status: "ready", message: "Ready" },
114 - };
115 - bridge.getSnapShotState.mockImplementation(async () => state);
116 - bridge.setSnapShotShortcutSuppressed.mockResolvedValue(undefined);
117 - bridge.checkSnapShotShortcut.mockResolvedValue({ available: true, message: null });
118 - bridge.setupSnapShot.mockReset().mockResolvedValue(undefined);
119 - settingsStore.update.mockImplementation(async (patch) => {
120 - settingsStore.current = { ...settingsStore.current, ...patch };
121 - state = { ...state, shortcut: settingsStore.current.snapShotShortcut };
122 - });
123 -});
124 -afterEach(() => vi.unstubAllGlobals());
125 -
126 -it.each(["niri", "hyprland"] as const)(
127 - "reopens %s setup at Shortcut without reading config or expanding Settings",
128 - async (desktop) => {
129 - state = { ...state, linuxBackend: desktop };
130 - const tree = await mount();
131 - expect(wizard(tree)).toBeNull();
132 - button(tree, "Change shortcut").onClick();
133 - await finish(bridge.getSnapShotState.mock.results[1]!.value);
134 - const opened = render();
135 - expect(visitElements(opened, (element) => element.type === CaptureShortcutConfig)).toBeNull();
136 - const dialog = wizard(opened);
137 - expect(dialog?.props.initialStep).toBe("shortcut");
138 - expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();
139 - expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();
140 - await (dialog!.props.onClose as (completed: boolean) => Promise<void>)(false);
141 - expect(wizard(render())).toBeNull();
142 - expect(settingsStore.update).not.toHaveBeenCalled();
143 - expect(settingsStore.current.snapShotEnabled).toBe(true);
144 - },
145 -);
146 -it("returns to Access if the Hyprland helper needs attention before changing keys", async () => {
147 - const tree = await mount();
148 - state = { ...state, hyprlandHelper: { status: "not-installed", message: "Install helper" } };
149 - button(tree, "Change shortcut").onClick();
150 - await finish(bridge.getSnapShotState.mock.results[1]!.value);
151 - expect(wizard(render())?.props.initialStep).toBe("access");
152 - expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();
153 -});
154 -it.each(["direct", "gnome-extension", "kde"] as const)(
155 - "keeps %s shortcut recording and saving inline",
156 - async (backend) => {
157 - state = {
158 - ...state,
159 - mode: backend === "direct" ? "direct" : "portal",
160 - linuxBackend: backend === "direct" ? undefined : backend,
161 - shortcutRegistered: true,
162 - shortcutLabel: backend === "direct" ? undefined : "Press <Shift><Control>2",
163 - shortcutMessage: backend === "direct" ? null : "Desktop shortcut: Press <Shift><Control>2",
164 - };
165 - const tree = await mount();
166 - const recorder = (node: ReturnType<typeof render>) => {
167 - const control = visitElements(node, (element) => "data-keybinding-capture" in element.props);
168 - if (!control) throw new Error("Missing inline shortcut recorder");
169 - return control.props;
170 - };
171 - if (backend !== "direct") {
172 - expect(recorder(tree)["aria-label"]).toBe("Record snapshot shortcut, currently Ctrl+Shift+2");
173 - const keycaps = visitElements(tree, (element) => element.type === SnapShotShortcutKeys);
174 - expect(keycaps?.props.shortcut).toMatchObject({ key: "2", ctrlKey: true, shiftKey: true });
175 - expect(
176 - visitElements(tree, (element) => element.props.id === "snap-shot-shortcut")?.props.status,
177 - ).toBeNull();
178 - }
179 - (recorder(tree).onClick as () => void)();
180 - await finish(bridge.setSnapShotShortcutSuppressed.mock.results.at(-1)!.value);
181 - (recorder(render()).onKeyDown as (event: object) => void)({
182 - key: "y",
183 - code: "KeyY",
184 - ctrlKey: true,
185 - altKey: true,
186 - shiftKey: false,
187 - metaKey: false,
188 - repeat: false,
189 - preventDefault: vi.fn(),
190 - stopPropagation: vi.fn(),
191 - });
192 - await finish(bridge.checkSnapShotShortcut.mock.results[0]!.value);
193 - expect(recorder(render()).size).toBe("xs");
194 - expect(recorder(render())["aria-label"]).toBe("Record snapshot shortcut, currently Ctrl+Alt+Y");
195 - button(render(), "Save").onClick();
196 - await finish(settingsStore.update.mock.results[0]!.value);
197 - expect(settingsStore.update).toHaveBeenCalledWith({
198 - snapShotShortcut: expect.objectContaining({ key: "y", modKey: true, altKey: true }),
199 - });
200 - expect(wizard(render())).toBeNull();
201 - expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();
202 - },
203 -);
204 -
205 -it("turns capture on directly on Windows without opening setup", async () => {
206 - settingsStore.current = { ...settingsStore.current, snapShotEnabled: false };
207 - state = { ...state, mode: "direct", linuxBackend: undefined, windows: true };
208 - const tree = await mount();
209 - const toggle = visitElements(
210 - tree,
211 - (element) => element.props["aria-label"] === "Enable snapshots",
212 - );
213 - if (!toggle) throw new Error("Missing capture toggle");
214 - (toggle.props.onCheckedChange as (checked: boolean) => void)(true);
215 - await finish(settingsStore.update.mock.results[0]!.value);
216 - expect(settingsStore.update).toHaveBeenCalledWith({ snapShotEnabled: true });
217 - expect(wizard(renderWithEffects())).toBeNull();
218 - expect(
219 - visitElements(renderWithEffects(), (element) => element.props.children === "Manage capture"),
220 - ).toBeNull();
221 -});
222 -
223 -it("keeps the approved desktop shortcut when recording is cancelled in setup", async () => {
224 - state = {
225 - ...state,
226 - linuxBackend: "gnome-extension",
227 - gnomeExtension: { status: "enabled", message: "Ready" },
228 - shortcutRegistered: true,
229 - shortcutLabel: "Press <Control><Alt>8",
230 - };
231 - const tree = await mount();
232 - button(tree, "Manage capture").onClick();
233 - await finish(bridge.getSnapShotState.mock.results[1]!.value);
234 - const shortcut = () => {
235 - const input = visitElements(
236 - wizard(render()),
237 - (element) => "data-keybinding-capture" in element.props,
238 - );
239 - if (!input) throw new Error("Missing setup shortcut recorder");
240 - return input.props;
241 - };
242 - expect(shortcut()["aria-label"]).toBe("Record snapshot shortcut, currently Ctrl+Alt+8");
243 - (shortcut().onClick as () => void)();
244 - await finish(bridge.setSnapShotShortcutSuppressed.mock.results.at(-1)!.value);
245 - expect(shortcut().children).toBe("Press shortcut…");
246 - (shortcut().onKeyDown as (event: object) => void)({
247 - key: "Escape",
248 - preventDefault: vi.fn(),
249 - stopPropagation: vi.fn(),
250 - });
251 - expect(shortcut()["aria-label"]).toBe("Record snapshot shortcut, currently Ctrl+Alt+8");
252 - expect(settingsStore.update).not.toHaveBeenCalled();
253 - expect(bridge.checkSnapShotShortcut).not.toHaveBeenCalled();
254 -});
255 -
256 -function usePortalShortcut(shortcutCanRetry: boolean) {
257 - const shortcut = {
258 - key: "2",
259 - modKey: false,
260 - ctrlKey: true,
261 - altKey: false,
262 - shiftKey: true,
263 - metaKey: false,
264 - };
265 - settingsStore.current = { ...settingsStore.current, snapShotShortcut: shortcut };
266 - state = {
267 - ...state,
268 - linuxBackend: "gnome-extension",
269 - gnomeExtension: { status: "enabled", message: "Ready" },
270 - shortcut,
271 - linuxFeedbackAvailable: true,
272 - shortcutRegistered: true,
273 - shortcutCanRetry,
274 - };
275 -}
276 -
277 -it("keeps older portal shortcuts editable without offering unsupported permissions", async () => {
278 - usePortalShortcut(false);
279 - const tree = await mount();
280 - expect(() => button(tree, "Shortcut permissions")).toThrow("Missing button");
281 - expect(bridge.setupSnapShot).not.toHaveBeenCalled();
282 - const recorder = visitElements(tree, (element) => "data-keybinding-capture" in element.props);
283 - (recorder!.props.onClick as () => void)();
284 - await finish(bridge.setSnapShotShortcutSuppressed.mock.results.at(-1)!.value);
285 - expect(
286 - visitElements(render(), (element) => "data-keybinding-capture" in element.props)?.props
287 - .children,
288 - ).toBe("Press shortcut…");
289 -});
290 -
291 -it("shows permission errors once in a toast and allows retrying", async () => {
292 - usePortalShortcut(true);
293 - bridge.setupSnapShot.mockRejectedValueOnce(new Error("The desktop service disconnected."));
294 - button(await mount(), "Shortcut permissions").onClick();
295 - await finish(bridge.setupSnapShot.mock.results[0]!.value.catch(() => undefined));
296 - const tree = renderWithEffects();
297 - expect(toastManager.add).toHaveBeenCalledExactlyOnceWith({
298 - type: "error",
299 - title: "Couldn't open shortcut permissions",
300 - description: "The desktop service disconnected.",
301 - });
302 - expect(visitElements(tree, (element) => element.props.role === "alert")).toBeNull();
303 - expect(state.shortcutRegistered).toBe(true);
304 - button(renderWithEffects(), "Shortcut permissions").onClick();
305 - await finish(bridge.setupSnapShot.mock.results[1]!.value);
306 - renderWithEffects();
307 - expect(bridge.setupSnapShot).toHaveBeenCalledTimes(2);
308 - expect(toastManager.add).toHaveBeenCalledTimes(1);
309 -});
310 -
311 -it("keeps a failed preference unchanged and reports the save error in a toast", async () => {
312 - usePortalShortcut(true);
313 - const flash = (tree: ReturnType<typeof render>) => {
314 - const control = visitElements(
315 - tree,
316 - (element) => element.props["aria-label"] === "Flash captured window",
317 - );
318 - if (!control) throw new Error("Missing flash control");
319 - return control.props as { onCheckedChange: (checked: boolean) => void; checked: boolean };
320 - };
321 - settingsStore.update.mockRejectedValueOnce(new Error("The settings file is read-only."));
322 - flash(await mount()).onCheckedChange(false);
323 - await finish(settingsStore.update.mock.results[0]!.value.catch(() => undefined));
324 - expect(flash(renderWithEffects()).checked).toBe(true);
325 - expect(toastManager.add).toHaveBeenCalledExactlyOnceWith({
326 - type: "error",
327 - title: "Couldn't save capture settings",
328 - description: "The settings file is read-only.",
329 - });
330 - flash(renderWithEffects()).onCheckedChange(false);
331 - await finish(settingsStore.update.mock.results[1]!.value);
332 - expect(flash(renderWithEffects()).checked).toBe(false);
333 - expect(toastManager.add).toHaveBeenCalledTimes(1);
334 -});
335 -
336 -it("keeps setup errors in the wizard and does not toast them after closing it", async () => {
337 - usePortalShortcut(true);
338 - button(await mount(), "Manage capture").onClick();
339 - await finish(bridge.getSnapShotState.mock.results[1]!.value);
340 - bridge.setupSnapShot.mockRejectedValueOnce(new Error("The desktop service disconnected."));
341 - const action = wizard(render())!.props.onAction as (action: "retry-shortcut") => Promise<void>;
342 - await action("retry-shortcut");
343 - const dialog = wizard(renderWithEffects())!;
344 - expect(dialog.props.error).toBe("The desktop service disconnected.");
345 - expect(toastManager.add).not.toHaveBeenCalled();
346 - await (dialog.props.onClose as (completed: boolean) => Promise<void>)(false);
347 - expect(wizard(renderWithEffects())).toBeNull();
348 - expect(toastManager.add).not.toHaveBeenCalled();
349 -});
350 -
351 -it.each([false, true])(
352 - "resumes macOS permission setup after restart and clears it on close, completed=%s",
353 - async (completed) => {
354 - const { readSnapShotSetupResume } = await import("../../lib/snapShotSetupResume");
355 - const values = new Map<string, string>();
356 - Object.assign(window, {
357 - localStorage: {
358 - getItem: (key: string) => values.get(key) ?? null,
359 - setItem: (key: string, value: string) => values.set(key, value),
360 - removeItem: (key: string) => values.delete(key),
361 - },
362 - });
363 - settingsStore.current = { ...settingsStore.current, snapShotEnabled: false };
364 - state = {
365 - mode: "direct",
366 - shortcut: DEFAULT_CLIENT_SETTINGS.snapShotShortcut,
367 - shortcutRegistered: false,
368 - shortcutMessage: null,
369 - message: null,
370 - macPermissions: { screenRecording: false, accessibility: false },
371 - };
372 - const tree = await mount();
373 - const toggle = visitElements(
374 - tree,
375 - (element) => element.props["aria-label"] === "Enable snapshots",
376 - );
377 - (toggle!.props.onCheckedChange as (checked: boolean) => void)(true);
378 - await finish(bridge.getSnapShotState.mock.results[1]!.value);
379 - bridge.setupSnapShot.mockImplementationOnce(async () => {
380 - expect(readSnapShotSetupResume()).toEqual({ wasEnabled: false });
381 - });
382 - await (wizard(render())!.props.onAction as (action: string) => Promise<void>)(
383 - "allow-screen-recording",
384 - );
385 -
386 - hooks.reset();
387 - effects.length = 0;
388 - bridge.getSnapShotState.mockClear();
389 - state = { ...state, macPermissions: { screenRecording: true, accessibility: true } };
390 - const resumed = wizard(await mount());
391 - expect(resumed).not.toBeNull();
392 - expect(resumed!.props.initialStep).toBe("access");
393 - expect(resumed!.props.wasEnabled).toBe(false);
394 - await (resumed!.props.onClose as (completed: boolean) => Promise<void>)(completed);
395 - expect(wizard(render())).toBeNull();
396 - expect(readSnapShotSetupResume()).toBeNull();
397 - },
398 -);
399 -
400 -it("requires a successful macOS test capture before enabling and allows retry", async () => {
401 - settingsStore.current = { ...DEFAULT_CLIENT_SETTINGS, snapShotEnabled: false };
402 - state = {
403 - mode: "direct",
404 - shortcut: DEFAULT_CLIENT_SETTINGS.snapShotShortcut,
405 - shortcutRegistered: false,
406 - shortcutMessage: null,
407 - message: null,
408 - macPermissions: { screenRecording: true, accessibility: true },
409 - };
410 - const tree = await mount();
411 - const toggle = visitElements(
412 - tree,
413 - (element) => element.props["aria-label"] === "Enable snapshots",
414 - );
415 - (toggle!.props.onCheckedChange as (checked: boolean) => void)(true);
416 - await finish(bridge.getSnapShotState.mock.results[1]!.value);
417 - bridge.setupSnapShot.mockRejectedValueOnce(new Error("Capture was denied"));
418 - const enable = () => (wizard(render())!.props.onEnable as () => Promise<boolean>)();
419 - expect(await enable()).toBe(false);
420 - expect(wizard(render())!.props.error).toBe("Capture was denied");
421 - expect(settingsStore.current.snapShotEnabled).toBe(false);
422 - expect(await enable()).toBe(true);
423 - expect(bridge.setupSnapShot.mock.calls).toEqual([["test-mac-capture"], ["test-mac-capture"]]);
424 - expect(settingsStore.current.snapShotEnabled).toBe(true);
425 -});
apps/web/src/components/settings/ThemeEditorHost.browser.test.tsx new
+138
@@ -0,0 +1,138 @@
1 +import { act } from "react";
2 +import { createRoot, type Root } from "react-dom/client";
3 +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4 +
5 +import {
6 + installCustomTheme,
7 + invalidateCustomThemes,
8 + parseThemeFile,
9 + removeCustomTheme,
10 + THEME_FILE_VERSION,
11 + themeColorToHex,
12 + updateCustomTheme,
13 + type ThemeDefinition,
14 +} from "../../themePalette";
15 +
16 +vi.mock(import("../../hooks/useTheme"), async (original) => ({
17 + ...(await original()),
18 + useTheme: () =>
19 + ({ theme: "system", themeHalves: null, setTheme: vi.fn(), refreshTheme: vi.fn() }) as never,
20 +}));
21 +// The real panel is a large lazy editor; this stand-in shows which theme the host hands it.
22 +vi.mock(import("./ThemeEditorPanel"), async (original) => ({
23 + ...(await original()),
24 + ThemeEditorPanel: (({
25 + editingTheme,
26 + seedTheme,
27 + }: {
28 + editingTheme: ThemeDefinition | null;
29 + seedTheme: ThemeDefinition | null;
30 + }) => (
31 + <dl>
32 + <dt>editingTheme</dt>
33 + <dd>{editingTheme ? themeColorToHex(editingTheme.colors.accent ?? "") : "none"}</dd>
34 + <dt>seedTheme</dt>
35 + <dd>{seedTheme ? themeColorToHex(seedTheme.colors.accent ?? "") : "none"}</dd>
36 + </dl>
37 + )) as never,
38 +}));
39 +
40 +import { ThemeEditorHost } from "./ThemeEditorHost";
41 +import { useThemeEditorStore } from "./themeEditorStore";
42 +
43 +type Field = "editingTheme" | "seedTheme";
44 +let root: Root;
45 +let container: HTMLDivElement;
46 +
47 +function install(id: string) {
48 + return installCustomTheme(
49 + parseThemeFile({
50 + version: THEME_FILE_VERSION,
51 + id,
52 + name: id,
53 + appearance: "dark",
54 + colors: { accent: "#1f6e4a" },
55 + }),
56 + );
57 +}
58 +function open(field: Field, themeId: string) {
59 + return act(async () =>
60 + useThemeEditorStore.getState().openThemeEditor({
61 + editingThemeId: field === "editingTheme" ? themeId : null,
62 + seedThemeId: field === "seedTheme" ? themeId : null,
63 + seedName: null,
64 + initialAppearance: "dark",
65 + }),
66 + );
67 +}
68 +async function shown(field: Field) {
69 + await vi.waitFor(() => expect(container.querySelector("dl")).not.toBeNull(), {
70 + timeout: 5_000,
71 + });
72 + const terms = [...container.querySelectorAll("dt")];
73 + return terms.find((term) => term.textContent === field)?.nextElementSibling?.textContent;
74 +}
75 +
76 +// The host lazy-loads the panel; load it once so the first test does not race the import.
77 +beforeAll(() => import("./ThemeEditorPanel"));
78 +
79 +beforeEach(async () => {
80 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
81 + localStorage.clear();
82 + invalidateCustomThemes();
83 + useThemeEditorStore.setState({ session: null });
84 + container = document.createElement("div");
85 + document.body.append(container);
86 + root = createRoot(container);
87 + await act(async () => root.render(<ThemeEditorHost />));
88 +});
89 +afterEach(async () => {
90 + await act(async () => root.unmount());
91 + container.remove();
92 + localStorage.clear();
93 + invalidateCustomThemes();
94 + vi.unstubAllGlobals();
95 +});
96 +
97 +describe("ThemeEditorHost", () => {
98 + it.each(["editingTheme", "seedTheme"] as const)(
99 + "reopens the same %s with its saved colors",
100 + async (field) => {
101 + const theme = install("saved-colors");
102 + await open(field, theme.id);
103 + expect(await shown(field)).toBe("#1f6e4a");
104 +
105 + await act(async () => useThemeEditorStore.getState().closeThemeEditor());
106 + expect(container.querySelector("dl")).toBeNull();
107 + updateCustomTheme({ ...theme, colors: { ...theme.colors, accent: "#7241b8" } });
108 + await open(field, theme.id);
109 +
110 + expect(await shown(field)).toBe("#7241b8");
111 + },
112 + );
113 +
114 + it.each(["editingTheme", "seedTheme"] as const)(
115 + "refreshes an open %s when the library changes",
116 + async (field) => {
117 + const theme = install("updated-theme");
118 + await open(field, theme.id);
119 + expect(await shown(field)).toBe("#1f6e4a");
120 +
121 + await act(async () =>
122 + updateCustomTheme({ ...theme, colors: { ...theme.colors, accent: "#7241b8" } }),
123 + );
124 +
125 + expect(await shown(field)).toBe("#7241b8");
126 + },
127 + );
128 +
129 + it("does not keep editing a theme removed from the library", async () => {
130 + const theme = install("removed-theme");
131 + await open("editingTheme", theme.id);
132 + expect(await shown("editingTheme")).toBe("#1f6e4a");
133 +
134 + await act(async () => removeCustomTheme(theme.id));
135 +
136 + expect(await shown("editingTheme")).toBe("none");
137 + });
138 +});
apps/web/src/components/settings/ThemeEditorHost.test.tsx deleted
-191
@@ -1,191 +0,0 @@
1 -import type { ReactElement } from "react";
2 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
3 -
4 -import { reactHookHarness as hooks } from "../../test/reactHookHarness";
5 -import {
6 - getThemeDefinition,
7 - installCustomTheme,
8 - invalidateCustomThemes,
9 - parseThemeFile,
10 - removeCustomTheme,
11 - THEME_FILE_VERSION,
12 - themeColorToHex,
13 - updateCustomTheme,
14 - type ThemeDefinition,
15 -} from "../../themePalette";
16 -import type { ThemeEditorSession } from "./themeEditorStore";
17 -
18 -const state = vi.hoisted(() => ({
19 - session: null as ThemeEditorSession | null,
20 - closeThemeEditor: vi.fn(),
21 - onStoreChange: vi.fn(),
22 - subscriptions: new Set<() => void>(),
23 - theme: {
24 - theme: "system",
25 - themeHalves: null,
26 - setTheme: vi.fn(),
27 - refreshTheme: vi.fn(),
28 - },
29 -}));
30 -
31 -vi.mock("react", async (importOriginal) => {
32 - const actual = await importOriginal<typeof import("react")>();
33 - const { reactHookHarness } = await import("../../test/reactHookHarness");
34 - return {
35 - ...actual,
36 - useCallback: reactHookHarness.useCallback,
37 - useSyncExternalStore: (
38 - subscribe: (listener: () => void) => () => void,
39 - getSnapshot: () => unknown,
40 - ) => {
41 - const subscription = reactHookHarness.useRef<(() => void) | null>(null);
42 - if (!subscription.current) {
43 - subscription.current = subscribe(() => state.onStoreChange());
44 - state.subscriptions.add(subscription.current);
45 - }
46 - return getSnapshot();
47 - },
48 - };
49 -});
50 -
51 -vi.mock("react/compiler-runtime", async () => {
52 - const { reactHookHarness } = await import("../../test/reactHookHarness");
53 - return { c: reactHookHarness.useMemoCache };
54 -});
55 -
56 -vi.mock("../../hooks/useTheme", () => ({ useTheme: () => state.theme }));
57 -vi.mock("./themeEditorStore", () => ({
58 - useThemeEditorStore: (select: (store: typeof state) => unknown) => select(state),
59 -}));
60 -vi.mock("../ui/toast", () => ({
61 - toastManager: { add: vi.fn() },
62 - stackedThreadToast: (value: unknown) => value,
63 -}));
64 -
65 -import { ThemeEditorHost } from "./ThemeEditorHost";
66 -
67 -function renderEditor() {
68 - hooks.beginRender();
69 - const host = ThemeEditorHost() as ReactElement<{
70 - children: ReactElement<{
71 - editingTheme: ThemeDefinition | null;
72 - seedTheme: ThemeDefinition | null;
73 - }>;
74 - }> | null;
75 - return host?.props.children.props ?? null;
76 -}
77 -
78 -describe("ThemeEditorHost", () => {
79 - beforeEach(() => {
80 - hooks.reset();
81 - state.session = null;
82 - state.onStoreChange.mockReset();
83 - const storage = new Map<string, string>();
84 - vi.stubGlobal("window", {
85 - localStorage: {
86 - getItem: (key: string) => storage.get(key) ?? null,
87 - setItem: (key: string, value: string) => storage.set(key, value),
88 - },
89 - addEventListener: vi.fn(),
90 - removeEventListener: vi.fn(),
91 - });
92 - invalidateCustomThemes();
93 - });
94 -
95 - afterEach(() => {
96 - for (const unsubscribe of state.subscriptions) unsubscribe();
97 - state.subscriptions.clear();
98 - vi.unstubAllGlobals();
99 - invalidateCustomThemes();
100 - });
101 -
102 - it.each(["editingTheme", "seedTheme"] as const)(
103 - "reopens the same %s with its saved colors",
104 - (field) => {
105 - const theme = installCustomTheme(
106 - parseThemeFile({
107 - version: THEME_FILE_VERSION,
108 - id: "saved-colors",
109 - name: "Saved colors",
110 - appearance: "dark",
111 - colors: { accent: "#1f6e4a" },
112 - }),
113 - );
114 - const session = {
115 - id: 1,
116 - editingThemeId: field === "editingTheme" ? theme.id : null,
117 - seedThemeId: field === "seedTheme" ? theme.id : null,
118 - seedName: null,
119 - initialAppearance: "dark" as const,
120 - };
121 - state.session = session;
122 - expect(themeColorToHex(renderEditor()?.[field]?.colors.accent ?? "")).toBe("#1f6e4a");
123 -
124 - updateCustomTheme({ ...theme, colors: { ...theme.colors, accent: "#7241b8" } });
125 - expect(themeColorToHex(getThemeDefinition(theme.id)?.colors.accent ?? "")).toBe("#7241b8");
126 - state.session = null;
127 - expect(renderEditor()).toBeNull();
128 - state.session = { ...session, id: 2 };
129 -
130 - expect(themeColorToHex(renderEditor()?.[field]?.colors.accent ?? "")).toBe("#7241b8");
131 - },
132 - );
133 -
134 - it.each(["editingTheme", "seedTheme"] as const)(
135 - "refreshes an open %s when the library changes",
136 - (field) => {
137 - const theme = installCustomTheme(
138 - parseThemeFile({
139 - version: THEME_FILE_VERSION,
140 - id: "updated-theme",
141 - name: "Updated theme",
142 - appearance: "dark",
143 - colors: { accent: "#1f6e4a" },
144 - }),
145 - );
146 - state.session = {
147 - id: 1,
148 - editingThemeId: field === "editingTheme" ? theme.id : null,
149 - seedThemeId: field === "seedTheme" ? theme.id : null,
150 - seedName: null,
151 - initialAppearance: "dark",
152 - };
153 - let editor = renderEditor();
154 - state.onStoreChange.mockImplementation(() => {
155 - editor = renderEditor();
156 - });
157 -
158 - updateCustomTheme({ ...theme, colors: { ...theme.colors, accent: "#7241b8" } });
159 -
160 - expect(themeColorToHex(editor?.[field]?.colors.accent ?? "")).toBe("#7241b8");
161 - },
162 - );
163 -
164 - it("does not keep editing a theme removed from the library", () => {
165 - const theme = installCustomTheme(
166 - parseThemeFile({
167 - version: THEME_FILE_VERSION,
168 - id: "removed-theme",
169 - name: "Removed theme",
170 - appearance: "dark",
171 - colors: { accent: "#1f6e4a" },
172 - }),
173 - );
174 - state.session = {
175 - id: 1,
176 - editingThemeId: theme.id,
177 - seedThemeId: null,
178 - seedName: null,
179 - initialAppearance: "dark",
180 - };
181 - let editor = renderEditor();
182 - expect(editor?.editingTheme?.id).toBe(theme.id);
183 - state.onStoreChange.mockImplementation(() => {
184 - editor = renderEditor();
185 - });
186 -
187 - removeCustomTheme(theme.id);
188 -
189 - expect(editor?.editingTheme).toBeNull();
190 - });
191 -});
apps/web/src/components/settings/useSnapShotShortcutRecorder.browser.test.tsx new
+175
@@ -0,0 +1,175 @@
1 +import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts";
2 +import { act, useEffect } from "react";
3 +import { createRoot, type Root } from "react-dom/client";
4 +import { userEvent } from "vite-plus/test/browser";
5 +import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
6 +
7 +const suppress = vi.hoisted(() => vi.fn<(enabled: boolean) => Promise<void>>());
8 +vi.mock(import("../../lib/desktopSnapShot"), async (original) => ({
9 + ...(await original()),
10 + getDesktopSnapShotBridge: () => ({ setSnapShotShortcutSuppressed: suppress }) as never,
11 +}));
12 +
13 +import { useSnapShotShortcutRecorder } from "./useSnapShotShortcutRecorder";
14 +
15 +function deferred<T>() {
16 + let resolve!: (value: T) => void;
17 + const promise = new Promise<T>((done) => {
18 + resolve = done;
19 + });
20 + return { promise, resolve };
21 +}
22 +
23 +const recorded = vi.fn();
24 +const error = vi.fn();
25 +let root: Root;
26 +let container: HTMLDivElement;
27 +let recording = false;
28 +
29 +function Recorder(props: { allowModifierPairs?: boolean; shortcutLabel?: string }) {
30 + const recorder = useSnapShotShortcutRecorder({
31 + shortcut: DEFAULT_CLIENT_SETTINGS.snapShotShortcut,
32 + shortcutLabel: props.shortcutLabel,
33 + allowModifierPairs: props.allowModifierPairs ?? false,
34 + onRecord: recorded,
35 + onError: error,
36 + });
37 + useEffect(() => {
38 + recording = recorder.recording;
39 + });
40 + return recorder.input;
41 +}
42 +
43 +async function render(props: Parameters<typeof Recorder>[0] = {}) {
44 + await act(async () => root.render(<Recorder {...props} />));
45 +}
46 +const button = () => container.querySelector<HTMLButtonElement>("[data-keybinding-capture]")!;
47 +async function start(props: Parameters<typeof Recorder>[0] = {}) {
48 + await render(props);
49 + await act(async () => userEvent.click(button()));
50 + expect(recording).toBe(true);
51 +}
52 +const press = (keys: string) => act(async () => userEvent.keyboard(keys));
53 +function setPlatform(platform: string) {
54 + Object.defineProperty(navigator, "platform", { configurable: true, get: () => platform });
55 +}
56 +
57 +beforeEach(() => {
58 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
59 + suppress.mockReset().mockResolvedValue(undefined);
60 + recorded.mockReset();
61 + error.mockReset();
62 + setPlatform("Linux x86_64");
63 + container = document.createElement("div");
64 + document.body.append(container);
65 + root = createRoot(container);
66 +});
67 +afterEach(async () => {
68 + await act(async () => root.unmount());
69 + container.remove();
70 + Reflect.deleteProperty(navigator, "platform");
71 + vi.unstubAllGlobals();
72 +});
73 +
74 +it("suppresses capture while recording and uses the physical key for shifted digits", async () => {
75 + await start();
76 + expect(suppress).toHaveBeenCalledExactlyOnceWith(true);
77 + expect(button().textContent).toBe("Press shortcut…");
78 + await press("{Control>}{Shift>}2{/Shift}{/Control}");
79 + expect(recorded).toHaveBeenCalledExactlyOnceWith({
80 + key: "2",
81 + modKey: true,
82 + ctrlKey: false,
83 + metaKey: false,
84 + altKey: false,
85 + shiftKey: true,
86 + });
87 + expect(suppress).toHaveBeenLastCalledWith(false);
88 + expect(recording).toBe(false);
89 +});
90 +
91 +it("lets users replace an unrecognized desktop label without displaying guessed keys", async () => {
92 + const shortcutLabel = "Use the shortcut assigned in desktop settings";
93 + await render({ shortcutLabel });
94 + expect(button().textContent).toBe("Change shortcut");
95 + expect(button().getAttribute("aria-label")).toBe("Change snapshot shortcut");
96 + await act(async () => userEvent.click(button()));
97 + expect(button().textContent).toBe("Press shortcut…");
98 + await press("{Control>}{Shift>}2{/Shift}{/Control}");
99 + expect(recorded).toHaveBeenCalledWith(
100 + expect.objectContaining({ key: "2", modKey: true, shiftKey: true }),
101 + );
102 + expect(suppress).toHaveBeenLastCalledWith(false);
103 +});
104 +
105 +it("records macOS Command without treating it as Control", async () => {
106 + setPlatform("MacIntel");
107 + await start({ allowModifierPairs: true });
108 + await press("{Meta>}k{/Meta}");
109 + expect(recorded).toHaveBeenCalledWith(expect.objectContaining({ key: "k", modKey: true }));
110 +});
111 +
112 +it.each(["Escape", "blur", "unmount"])("cancels on %s without selecting keys", async (cancel) => {
113 + await start();
114 + if (cancel === "Escape") {
115 + const outside = vi.fn();
116 + document.addEventListener("keydown", outside);
117 + await press("{Escape}");
118 + document.removeEventListener("keydown", outside);
119 + expect(outside).not.toHaveBeenCalled();
120 + } else if (cancel === "blur") await act(async () => button().blur());
121 + else await act(async () => root.render(null));
122 + expect(suppress).toHaveBeenLastCalledWith(false);
123 + expect(recorded).not.toHaveBeenCalled();
124 + if (cancel !== "unmount") expect(recording).toBe(false);
125 +});
126 +
127 +it("ignores late suppression acknowledgements after cancellation", async () => {
128 + const pending = deferred<void>();
129 + suppress.mockImplementation((enabled) => (enabled ? pending.promise : Promise.resolve()));
130 + await render();
131 + await act(async () => userEvent.click(button()));
132 + await act(async () => button().blur());
133 + await act(async () => pending.resolve());
134 + expect(recording).toBe(false);
135 + expect(suppress).toHaveBeenLastCalledWith(false);
136 + expect(recorded).not.toHaveBeenCalled();
137 +});
138 +
139 +it("reports suppression failures instead of arming the recorder", async () => {
140 + suppress.mockRejectedValue(new Error("Couldn't pause capture"));
141 + await render();
142 + await act(async () => userEvent.click(button()));
143 + expect(recording).toBe(false);
144 + expect(error).toHaveBeenCalledWith("Couldn't pause capture");
145 +});
146 +
147 +it("does not record Tab, unmodified keys, or modifier keys on their own", async () => {
148 + await start();
149 + await press("y");
150 + await press("{Control>}{/Control}");
151 + expect(recorded).not.toHaveBeenCalled();
152 + expect(recording).toBe(true);
153 + await press("{Tab}");
154 + expect(document.activeElement).not.toBe(button());
155 +});
156 +
157 +it("rejects modifier pairs on Wayland but accepts the next key chord", async () => {
158 + await start();
159 + await press("{ShiftLeft>}{ShiftRight>}{/ShiftRight}{/ShiftLeft}");
160 + expect(recorded).not.toHaveBeenCalled();
161 + expect(error).toHaveBeenCalledWith(expect.stringContaining("Add a letter, number"));
162 + expect(recording).toBe(true);
163 + await press("{Control>}{Alt>}y{/Alt}{/Control}");
164 + expect(recorded).toHaveBeenCalledOnce();
165 +});
166 +
167 +it("preserves native modifier-pair recording and tracks released keys", async () => {
168 + await start({ allowModifierPairs: true });
169 + await press("{ShiftLeft}");
170 + await press("{ShiftRight>}");
171 + expect(recorded).not.toHaveBeenCalled();
172 + await press("{ShiftLeft>}");
173 + expect(recorded).toHaveBeenCalledExactlyOnceWith({ kind: "both-shift-keys" });
174 + await press("{/ShiftLeft}{/ShiftRight}");
175 +});
apps/web/src/components/settings/useSnapShotShortcutRecorder.test.tsx deleted
-166
@@ -1,166 +0,0 @@
1 -import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts";
2 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
3 -import { reactHookHarness as hooks } from "../../test/reactHookHarness";
4 -import { useSnapShotShortcutRecorder } from "./useSnapShotShortcutRecorder";
5 -
6 -const effects = vi.hoisted(() => [] as (() => () => void)[]);
7 -vi.mock("react", async (original) => {
8 - const actual = await original<typeof import("react")>();
9 - const { reactHookHarness } = await import("../../test/reactHookHarness");
10 - return {
11 - ...actual,
12 - useCallback: reactHookHarness.useCallback,
13 - useRef: reactHookHarness.useRef,
14 - useState: reactHookHarness.useState,
15 - useEffect: (effect: () => () => void) => effects.push(effect),
16 - };
17 -});
18 -vi.mock("react/compiler-runtime", async () => {
19 - const { reactHookHarness } = await import("../../test/reactHookHarness");
20 - return { c: reactHookHarness.useMemoCache };
21 -});
22 -const suppress = vi.hoisted(() => vi.fn<(_: boolean) => Promise<void>>());
23 -vi.mock("../../lib/desktopSnapShot", () => ({
24 - getDesktopSnapShotBridge: () => ({ setSnapShotShortcutSuppressed: suppress }),
25 -}));
26 -
27 -const recorded = vi.fn();
28 -const error = vi.fn();
29 -function render(allowModifierPairs = false, shortcutLabel?: string) {
30 - hooks.beginRender();
31 - return useSnapShotShortcutRecorder({
32 - shortcut: DEFAULT_CLIENT_SETTINGS.snapShotShortcut,
33 - shortcutLabel,
34 - allowModifierPairs,
35 - onRecord: recorded,
36 - onError: error,
37 - });
38 -}
39 -function event(key: string, code = key, extra: object = {}) {
40 - return {
41 - key,
42 - code,
43 - ctrlKey: false,
44 - altKey: false,
45 - shiftKey: false,
46 - metaKey: false,
47 - repeat: false,
48 - preventDefault: vi.fn(),
49 - stopPropagation: vi.fn(),
50 - ...extra,
51 - };
52 -}
53 -async function start(allowModifierPairs = false) {
54 - render(allowModifierPairs).input.props.onClick();
55 - await suppress.mock.results.at(-1)!.value;
56 - return render(allowModifierPairs);
57 -}
58 -beforeEach(() => {
59 - hooks.reset();
60 - effects.length = 0;
61 - suppress.mockReset().mockResolvedValue(undefined);
62 - recorded.mockReset();
63 - error.mockReset();
64 - vi.stubGlobal("navigator", { platform: "Linux" });
65 -});
66 -afterEach(() => vi.unstubAllGlobals());
67 -
68 -it("suppresses capture while recording and uses the physical key for shifted digits", async () => {
69 - const recorder = await start();
70 - expect(recorder.recording).toBe(true);
71 - expect(suppress).toHaveBeenCalledExactlyOnceWith(true);
72 - recorder.input.props.onKeyDown(event("@", "Digit2", { ctrlKey: true, shiftKey: true }));
73 - expect(recorded).toHaveBeenCalledExactlyOnceWith({
74 - key: "2",
75 - modKey: true,
76 - ctrlKey: false,
77 - metaKey: false,
78 - altKey: false,
79 - shiftKey: true,
80 - });
81 - expect(suppress).toHaveBeenLastCalledWith(false);
82 - expect(render().recording).toBe(false);
83 -});
84 -it("lets users replace an unrecognized desktop label without displaying guessed keys", async () => {
85 - const label = "Use the shortcut assigned in desktop settings";
86 - let recorder = render(false, label);
87 - expect(recorder.input.props.children).toBe("Change shortcut");
88 - expect(recorder.input.props["aria-label"]).toBe("Change snapshot shortcut");
89 - recorder.input.props.onClick();
90 - await suppress.mock.results.at(-1)!.value;
91 - recorder = render(false, label);
92 - expect(recorder.input.props.children).toBe("Press shortcut…");
93 - recorder.input.props.onKeyDown(event("@", "Digit2", { ctrlKey: true, shiftKey: true }));
94 - expect(recorded).toHaveBeenCalledWith(
95 - expect.objectContaining({ key: "2", modKey: true, shiftKey: true }),
96 - );
97 - expect(suppress).toHaveBeenLastCalledWith(false);
98 -});
99 -it("records macOS Command without treating it as Control", async () => {
100 - vi.stubGlobal("navigator", { platform: "MacIntel" });
101 - (await start(true)).input.props.onKeyDown(event("k", "KeyK", { metaKey: true }));
102 - expect(recorded).toHaveBeenCalledWith(expect.objectContaining({ key: "k", modKey: true }));
103 -});
104 -it.each(["Escape", "blur", "unmount"])("cancels on %s without selecting keys", async (cancel) => {
105 - const recorder = await start();
106 - if (cancel === "Escape") {
107 - const escape = event("Escape");
108 - recorder.input.props.onKeyDown(escape);
109 - expect(escape.preventDefault).toHaveBeenCalled();
110 - expect(escape.stopPropagation).toHaveBeenCalled();
111 - } else if (cancel === "blur") recorder.input.props.onBlur();
112 - else effects[0]!()();
113 - expect(suppress).toHaveBeenLastCalledWith(false);
114 - expect(recorded).not.toHaveBeenCalled();
115 - if (cancel !== "unmount") expect(render().recording).toBe(false);
116 -});
117 -it("ignores late suppression acknowledgements after cancellation", async () => {
118 - let resolve!: () => void;
119 - const pending = new Promise<void>((done) => {
120 - resolve = done;
121 - });
122 - suppress.mockImplementation((enabled) => (enabled ? pending : Promise.resolve()));
123 - render().input.props.onClick();
124 - render().input.props.onBlur();
125 - resolve();
126 - await pending;
127 - expect(render().recording).toBe(false);
128 - expect(suppress).toHaveBeenLastCalledWith(false);
129 - expect(recorded).not.toHaveBeenCalled();
130 -});
131 -it("reports suppression failures instead of arming the recorder", async () => {
132 - suppress.mockRejectedValue(new Error("Couldn't pause capture"));
133 - render().input.props.onClick();
134 - await suppress.mock.results[0]!.value.catch(() => undefined);
135 - expect(render().recording).toBe(false);
136 - expect(error).toHaveBeenCalledWith("Couldn't pause capture");
137 -});
138 -it("does not record Tab, held repeats, or modifier keys on their own", async () => {
139 - const recorder = await start();
140 - const tab = event("Tab");
141 - recorder.input.props.onKeyDown(tab);
142 - recorder.input.props.onKeyDown(event("y", "KeyY", { ctrlKey: true, repeat: true }));
143 - recorder.input.props.onKeyDown(event("Control", "ControlLeft", { ctrlKey: true }));
144 - expect(tab.preventDefault).not.toHaveBeenCalled();
145 - expect(recorded).not.toHaveBeenCalled();
146 - expect(render().recording).toBe(true);
147 -});
148 -it("rejects modifier pairs on Wayland but accepts the next key chord", async () => {
149 - const recorder = await start();
150 - recorder.input.props.onKeyDown(event("Shift", "ShiftLeft", { shiftKey: true }));
151 - recorder.input.props.onKeyDown(event("Shift", "ShiftRight", { shiftKey: true }));
152 - expect(recorded).not.toHaveBeenCalled();
153 - expect(error).toHaveBeenCalledWith(expect.stringContaining("Add a letter, number"));
154 - expect(render().recording).toBe(true);
155 - render().input.props.onKeyDown(event("y", "KeyY", { ctrlKey: true, altKey: true }));
156 - expect(recorded).toHaveBeenCalledOnce();
157 -});
158 -it("preserves native modifier-pair recording and tracks released keys", async () => {
159 - const recorder = await start(true);
160 - recorder.input.props.onKeyDown(event("Shift", "ShiftLeft", { shiftKey: true }));
161 - recorder.input.props.onKeyUp(event("Shift", "ShiftLeft"));
162 - recorder.input.props.onKeyDown(event("Shift", "ShiftRight", { shiftKey: true }));
163 - expect(recorded).not.toHaveBeenCalled();
164 - recorder.input.props.onKeyDown(event("Shift", "ShiftLeft", { shiftKey: true }));
165 - expect(recorded).toHaveBeenCalledExactlyOnceWith({ kind: "both-shift-keys" });
166 -});
apps/web/vite.config.ts
+2
@@ -82,6 +82,8 @@ const unitTestProject = {
82 // in headless Chromium through the same plugins as the app, so it exercises compiled code.
83 const browserTestProject = {
84 extends: true,
85 + // Pre-bundled so the first test importing userEvent does not trigger a mid-run reload.
86 + optimizeDeps: { include: ["vite-plus/test/browser"] },
87 test: {
88 name: "browser",
89 include: ["src/**/*.browser.test.{ts,tsx}"],