TypeScript
test(web): hook-harness tests run in a real browser (#20866)
Julius Marmingee4fb9f2ccfbb
diff --git a/apps/web/src/components/permissions/usePermissionStatus.browser.test.tsx b/apps/web/src/components/permissions/usePermissionStatus.browser.test.tsxnew file mode 100644index 00000000000..a15e63337c5--- /dev/null+++ b/apps/web/src/components/permissions/usePermissionStatus.browser.test.tsx@@ -0,0 +1,103 @@+import { act, useEffect } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";++import { usePermissionStatus } from "./usePermissionStatus";++type Status = { screen: boolean; accessibility: boolean };+const check = vi.fn<() => Promise<Status>>();++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => {+ resolve = done;+ });+ return { promise, resolve };+}++let root: Root | null;+let current: ReturnType<typeof usePermissionStatus<keyof Status>>;+let visibility: DocumentVisibilityState;++function Probe() {+ const status = usePermissionStatus(check, { screen: false, accessibility: false });+ useEffect(() => {+ current = status;+ });+ return null;+}++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ vi.useFakeTimers();+ visibility = "visible";+ Object.defineProperty(document, "visibilityState", {+ configurable: true,+ get: () => visibility,+ });+ check.mockReset().mockResolvedValue({ screen: false, accessibility: false });+ root = null;+});+afterEach(async () => {+ await unmount();+ vi.useRealTimers();+ vi.unstubAllGlobals();+ Reflect.deleteProperty(document, "visibilityState");+});++async function start() {+ root = createRoot(document.createElement("div"));+ await act(async () => root!.render(<Probe />));+}+async function unmount() {+ const mounted = root;+ root = null;+ if (mounted) await act(async () => mounted.unmount());+}+const tick = (ms: number) => act(() => vi.advanceTimersByTimeAsync(ms));++it("unlocks Continue only for required grants and relocks on revocation", async () => {+ await start();+ expect(current.isReady(["screen"])).toBe(false);+ check.mockResolvedValue({ screen: true, accessibility: false });+ await tick(1500);+ expect(current.isReady(["screen"])).toBe(true);+ expect(current.isReady(["screen", "accessibility"])).toBe(false);+ check.mockResolvedValue({ screen: true, accessibility: true });+ await tick(1500);+ expect(current.isReady(["screen", "accessibility"])).toBe(true);+ check.mockResolvedValue({ screen: false, accessibility: true });+ await act(async () => window.dispatchEvent(new Event("focus")));+ expect(current.isReady(["screen"])).toBe(false);+});++it("does not overlap checks and discards completion after closing", async () => {+ const pending = deferred<Status>();+ check.mockReturnValue(pending.promise);+ await start();+ await tick(4500);+ window.dispatchEvent(new Event("focus"));+ expect(check).toHaveBeenCalledTimes(1);+ const last = current;+ await unmount();+ await act(async () => pending.resolve({ screen: true, accessibility: true }));+ expect(last.isReady(["screen"])).toBe(false);+ expect(vi.getTimerCount()).toBe(0);+});++it("pauses in the background and blocks stale grants after a check failure", async () => {+ check.mockResolvedValue({ screen: true, accessibility: true });+ await start();+ expect(current.isReady(["screen"])).toBe(true);+ visibility = "hidden";+ await tick(3000);+ expect(check).toHaveBeenCalledTimes(1);+ check.mockRejectedValue(new Error("IPC unavailable"));+ visibility = "visible";+ await act(async () => document.dispatchEvent(new Event("visibilitychange")));+ expect(current.isReady(["screen"])).toBe(false);+ expect(current.error).not.toBeNull();+ check.mockResolvedValue({ screen: true, accessibility: true });+ await tick(1500);+ expect(current.isReady(["screen"])).toBe(true);+});diff --git a/apps/web/src/components/permissions/usePermissionStatus.test.ts b/apps/web/src/components/permissions/usePermissionStatus.test.tsdeleted file mode 100644index 8b882f9df67..00000000000--- a/apps/web/src/components/permissions/usePermissionStatus.test.ts+++ /dev/null@@ -1,96 +0,0 @@-import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";-import { reactHookHarness as hooks } from "../../test/reactHookHarness";-import { usePermissionStatus } from "./usePermissionStatus";--const effects = vi.hoisted(() => [] as Array<() => (() => void) | undefined>);-vi.mock("react", async (original) => {- const actual = await original<typeof import("react")>();- const { reactHookHarness } = await import("../../test/reactHookHarness");- return {- ...actual,- useState: reactHookHarness.useState,- useEffect: (effect: () => (() => void) | undefined) => effects.push(effect),- useEffectEvent: <T>(callback: T) => callback,- };-});-vi.mock("react/compiler-runtime", async () => {- const { reactHookHarness } = await import("../../test/reactHookHarness");- return { c: reactHookHarness.useMemoCache };-});-const check = vi.fn<() => Promise<{ screen: boolean; accessibility: boolean }>>();-let cleanup: (() => void) | undefined;-let page: EventTarget & { visibilityState: string };-const render = () => {- hooks.beginRender();- return usePermissionStatus(check, { screen: false, accessibility: false });-};-beforeEach(() => {- hooks.reset();- effects.length = 0;- vi.useFakeTimers();- page = Object.assign(new EventTarget(), { visibilityState: "visible" });- vi.stubGlobal("document", page);- vi.stubGlobal("window", Object.assign(new EventTarget(), { setInterval, clearInterval }));- check.mockReset().mockResolvedValue({ screen: false, accessibility: false });-});-afterEach(() => {- cleanup?.();- vi.useRealTimers();- vi.unstubAllGlobals();-});-const start = async () => {- render();- cleanup = effects[0]!();- await Promise.resolve();-};--it("unlocks Continue only for required grants and relocks on revocation", async () => {- await start();- expect(render().isReady(["screen"])).toBe(false);- check.mockResolvedValue({ screen: true, accessibility: false });- await vi.advanceTimersByTimeAsync(1500);- expect(render().isReady(["screen"])).toBe(true);- expect(render().isReady(["screen", "accessibility"])).toBe(false);- check.mockResolvedValue({ screen: true, accessibility: true });- await vi.advanceTimersByTimeAsync(1500);- expect(render().isReady(["screen", "accessibility"])).toBe(true);- check.mockResolvedValue({ screen: false, accessibility: true });- window.dispatchEvent(new Event("focus"));- await Promise.resolve();- expect(render().isReady(["screen"])).toBe(false);-});--it("does not overlap checks and discards completion after closing", async () => {- let resolve!: (status: { screen: boolean; accessibility: boolean }) => void;- const promise = new Promise<{ screen: boolean; accessibility: boolean }>((done) => {- resolve = done;- });- const pending = { promise, resolve };- check.mockReturnValue(pending.promise);- await start();- await vi.advanceTimersByTimeAsync(4500);- window.dispatchEvent(new Event("focus"));- expect(check).toHaveBeenCalledTimes(1);- cleanup?.();- pending.resolve({ screen: true, accessibility: true });- await pending.promise;- expect(render().isReady(["screen"])).toBe(false);- expect(vi.getTimerCount()).toBe(0);-});--it("pauses in the background and blocks stale grants after a check failure", async () => {- check.mockResolvedValue({ screen: true, accessibility: true });- await start();- expect(render().isReady(["screen"])).toBe(true);- page.visibilityState = "hidden";- await vi.advanceTimersByTimeAsync(3000);- expect(check).toHaveBeenCalledTimes(1);- check.mockRejectedValue(new Error("IPC unavailable"));- page.visibilityState = "visible";- page.dispatchEvent(new Event("visibilitychange"));- await Promise.resolve();- expect(render().isReady(["screen"])).toBe(false);- check.mockResolvedValue({ screen: true, accessibility: true });- await vi.advanceTimersByTimeAsync(1500);- expect(render().isReady(["screen"])).toBe(true);-});diff --git a/apps/web/src/components/settings/AcpRegistryIcon.browser.test.tsx b/apps/web/src/components/settings/AcpRegistryIcon.browser.test.tsxnew file mode 100644index 00000000000..51844a28236--- /dev/null+++ b/apps/web/src/components/settings/AcpRegistryIcon.browser.test.tsx@@ -0,0 +1,71 @@+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";++import { AcpRegistryAgentIcon } from "./AcpRegistryIcon";++const url = "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg";+const fetchIcon = vi.fn<typeof fetch>();+let root: Root;+let container: HTMLDivElement;++beforeEach(() => {+ vi.stubGlobal("caches", undefined);+ vi.stubGlobal("fetch", fetchIcon);+ fetchIcon.mockReset();+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});+afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+ vi.unstubAllGlobals();+});++const image = () => container.querySelector("img");+const fallback = () => container.querySelector('[data-slot="acp-icon-fallback"]');++it("falls back to the raw allowlisted CDN URL when the validating fetch is blocked", async () => {+ // The official CDN serves no CORS headers, so the fetch can reject even+ // though native <img> loading works.+ fetchIcon.mockRejectedValue(new TypeError("Failed to fetch"));+ await act(async () => root.render(<AcpRegistryAgentIcon icon={url} />));++ await vi.waitFor(() => expect(image()?.getAttribute("src")).toBe(url));+ expect(image()?.referrerPolicy).toBe("no-referrer");+ expect(fallback()).not.toBeNull();+});++function serve(body: string) {+ fetchIcon.mockResolvedValue(+ new Response(body, { status: 200, headers: { "content-type": "image/svg+xml" } }),+ );+}++it("swaps the fallback for the validated blob once the image loads", async () => {+ serve('<svg xmlns="http://www.w3.org/2000/svg" width="8" height="8"/>');+ await act(async () => root.render(<AcpRegistryAgentIcon icon={url} />));++ await vi.waitFor(() => expect(fallback()).toBeNull());+ expect(image()?.src).toMatch(/^blob:/);+ expect(image()?.checkVisibility()).toBe(true);+});++it("keeps the fallback and drops the image when the validated blob fails to decode", async () => {+ serve("not an svg");+ await act(async () => root.render(<AcpRegistryAgentIcon icon={url} />));++ await vi.waitFor(() => expect(fetchIcon).toHaveBeenCalledOnce());+ await vi.waitFor(() => expect(image()).toBeNull());+ expect(fallback()).not.toBeNull();+});++it("never renders an icon from outside the official CDN", async () => {+ await act(async () =>+ root.render(<AcpRegistryAgentIcon icon="https://cdn.agentclientprotocol.com.evil/icon.svg" />),+ );+ expect(fetchIcon).not.toHaveBeenCalled();+ expect(image()).toBeNull();+ expect(fallback()).not.toBeNull();+});diff --git a/apps/web/src/components/settings/AcpRegistryIcon.test.ts b/apps/web/src/components/settings/AcpRegistryIcon.test.tsindex 90658b4ad6f..ccac3bcc37b 100644--- a/apps/web/src/components/settings/AcpRegistryIcon.test.ts+++ b/apps/web/src/components/settings/AcpRegistryIcon.test.ts@@ -1,22 +1,6 @@-import type { ReactElement } from "react";import { beforeEach, describe, expect, it, vi } from "vite-plus/test";-import { visitElements } from "../../test/reactElementTree";-import { reactHookHarness as hooks } from "../../test/reactHookHarness";--vi.mock("react", async (importOriginal) => {- const actual = await importOriginal<typeof import("react")>();- const { reactHookHarness } = await import("../../test/reactHookHarness");- return {- ...actual,- useEffect: (effect: () => void | (() => void)) => effect(),- useState: reactHookHarness.useState,- useId: () => "acp-icon-test-filter",- };-});-import {- AcpRegistryAgentIcon,loadCachedAcpRegistryIcon,officialAcpRegistryIconUrlForAgentId,resolveOfficialAcpRegistryIconUrl,@@ -31,7 +15,6 @@ describe("ACP Registry icon cache", () => {const fetchIcon = vi.fn();beforeEach(() => {- hooks.reset();stored.clear();match.mockClear();put.mockClear();@@ -125,80 +108,4 @@ describe("ACP Registry icon cache", () => {);expect(officialAcpRegistryIconUrlForAgentId("../kilo")).toBeNull();});-- it("falls back to the raw allowlisted CDN URL when the validating fetch is blocked", async () => {- const url = "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg";- // The official CDN serves no CORS headers, so the fetch can reject even- // though native <img> loading works.- fetchIcon.mockRejectedValue(new TypeError("Failed to fetch"));- hooks.beginRender();- AcpRegistryAgentIcon({ icon: url });-- await new Promise((resolve) => setTimeout(resolve, 0));- hooks.beginRender();- const tree = AcpRegistryAgentIcon({ icon: url }) as ReactElement<Record<string, unknown>>;- const image = visitElements(tree, (element) => element.type === "img");- expect(image?.props).toMatchObject({ src: url, referrerPolicy: "no-referrer" });- expect(- visitElements(tree, (element) => element.props["data-slot"] === "acp-icon-fallback"),- ).not.toBeNull();- });-- it("renders only the validated blob object URL and keeps the fallback until load", async () => {- const url = "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg";- const objectUrl = "blob:t3/kilo-icon";- Object.assign(URL, {- createObjectURL: vi.fn(() => objectUrl),- revokeObjectURL: vi.fn(),- });- fetchIcon.mockResolvedValue(- new Response("<svg/>", {- status: 200,- headers: { "content-type": "image/svg+xml" },- }),- );- hooks.beginRender();- const validating = AcpRegistryAgentIcon({ icon: url }) as ReactElement<Record<string, unknown>>;-- expect(visitElements(validating, (element) => element.type === "img")).toBeNull();- expect(- visitElements(validating, (element) => element.props["data-slot"] === "acp-icon-fallback"),- ).not.toBeNull();-- await new Promise((resolve) => setTimeout(resolve, 0));- hooks.beginRender();- const loading = AcpRegistryAgentIcon({ icon: url }) as ReactElement<Record<string, unknown>>;- const loadingImage = visitElements(loading, (element) => element.type === "img");-- expect(loadingImage?.props).toMatchObject({- src: objectUrl,- alt: "",- decoding: "async",- referrerPolicy: "no-referrer",- });- expect(loadingImage?.props.className).not.toContain("dark:invert");- expect(loadingImage?.props.className).toContain("invisible");- expect(- visitElements(loading, (element) => element.props["data-slot"] === "acp-icon-fallback"),- ).not.toBeNull();-- (loadingImage?.props.onLoad as (() => void) | undefined)?.();- hooks.beginRender();- const loaded = AcpRegistryAgentIcon({ icon: url }) as ReactElement<Record<string, unknown>>;- expect(- visitElements(loaded, (element) => element.type === "img")?.props.className,- ).not.toContain("invisible");- expect(- visitElements(loaded, (element) => element.props["data-slot"] === "acp-icon-fallback"),- ).toBeNull();-- const loadedImage = visitElements(loaded, (element) => element.type === "img");- (loadedImage?.props.onError as (() => void) | undefined)?.();- hooks.beginRender();- const failed = AcpRegistryAgentIcon({ icon: url }) as ReactElement<Record<string, unknown>>;- expect(visitElements(failed, (element) => element.type === "img")).toBeNull();- expect(- visitElements(failed, (element) => element.props["data-slot"] === "acp-icon-fallback"),- ).not.toBeNull();- });});diff --git a/apps/web/src/components/settings/AcpSessionManagementSection.browser.test.tsx b/apps/web/src/components/settings/AcpSessionManagementSection.browser.test.tsxnew file mode 100644index 00000000000..9d4995be732--- /dev/null+++ b/apps/web/src/components/settings/AcpSessionManagementSection.browser.test.tsx@@ -0,0 +1,294 @@+import {+ EnvironmentId,+ ProjectId,+ ProviderDriverKind,+ ProviderInstanceId,+ ThreadId,+ type ServerProvider,+} from "@t3tools/contracts";+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";++const commands = vi.hoisted(() => ({+ list: vi.fn(),+ import: vi.fn(),+ delete: vi.fn(),+ listProviders: vi.fn(),+ setProvider: vi.fn(),+ disableProvider: vi.fn(),+ logout: vi.fn(),+}));+const grants = vi.hoisted(() => ({ scopes: new Set<string>() }));+const dialogs = vi.hoisted(() => ({ confirm: vi.fn() }));++vi.mock(import("~/state/session"), async (original) => ({+ ...(await original()),+ useEnvironmentScope: ((_id: unknown, scope: string) => grants.scopes.has(scope)) as never,+ readEnvironmentScope: ((_id: unknown, scope: string) => grants.scopes.has(scope)) as never,+}));+vi.mock(import("../../state/use-atom-command"), async (original) => {+ const { serverEnvironment } = await import("../../state/server");+ const byAtom = new Map<unknown, unknown>([+ [serverEnvironment.listAcpRegistrySessions, commands.list],+ [serverEnvironment.importAcpRegistrySession, commands.import],+ [serverEnvironment.deleteAcpRegistrySession, commands.delete],+ [serverEnvironment.listAcpRegistryProviders, commands.listProviders],+ [serverEnvironment.setAcpRegistryProvider, commands.setProvider],+ [serverEnvironment.disableAcpRegistryProvider, commands.disableProvider],+ [serverEnvironment.logoutAcpRegistry, commands.logout],+ ]);+ return {+ ...(await original()),+ useAtomCommand: ((atom: unknown) => byAtom.get(atom)) as never,+ };+});+vi.mock(import("../../localApi"), async (original) => ({+ ...(await original()),+ ensureLocalApi: () => ({ dialogs }) as never,+}));++import { AcpSessionManagementSection } from "./AcpSessionManagementSection";++const environmentId = EnvironmentId.make("remote-device");+const instanceId = ProviderInstanceId.make("acpRegistry_antigravity");+const projectId = ProjectId.make("project-antigravity");+const session = {+ sessionId: "native-session-1",+ cwd: "/workspace/antigravity",+ additionalDirectories: [],+ title: "Native Antigravity session",+ updatedAt: "2026-08-23T00:00:00Z",+ importedThreadId: null,+} as const;+const provider = {+ instanceId,+ driver: ProviderDriverKind.make("acpRegistry"),+ enabled: true,+ installed: true,+ version: "1.0.0",+ status: "ready",+ auth: { status: "authenticated", canLogout: true },+ nativeSessions: { canList: true, canLoad: true, canResume: true, canDelete: true },+ configurableProviders: true,+ checkedAt: "2026-08-23T00:00:00.000Z",+ models: [],+ slashCommands: [],+ skills: [],+} satisfies ServerProvider;++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => {+ resolve = done;+ });+ return { promise, resolve };+}++let root: Root;+let container: HTMLDivElement;++function render(readOnly = false) {+ return act(async () =>+ root.render(+ <AcpSessionManagementSection+ environmentId={environmentId}+ instanceId={instanceId}+ provider={provider}+ projects={[{ id: projectId, title: "Antigravity", workspaceRoot: session.cwd }]}+ readOnly={readOnly}+ />,+ ),+ );+}+function button(label: string) {+ const found = [...container.querySelectorAll("button")].find(+ (element) => element.textContent === label,+ );+ expect(found, `button ${label}`).toBeDefined();+ return found!;+}+const click = (label: string) => act(async () => button(label).click());++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ grants.scopes = new Set(["orchestration:read", "orchestration:operate", "providers:manage"]);+ commands.list.mockReset().mockResolvedValue({+ _tag: "Success",+ value: {+ sessions: [session],+ nextCursor: null,+ canLoad: true,+ canResume: true,+ canDelete: true,+ },+ });+ commands.import.mockReset().mockResolvedValue({+ _tag: "Success",+ value: { threadId: ThreadId.make("thread-imported"), imported: true },+ });+ commands.delete.mockReset().mockResolvedValue({+ _tag: "Success",+ value: { deleted: true },+ });+ commands.listProviders.mockReset().mockResolvedValue({+ _tag: "Success",+ value: {+ providers: [+ {+ providerId: "google",+ supported: ["openai"],+ required: false,+ current: { apiType: "openai", baseUrl: "https://api.example.test/v1" },+ },+ ],+ },+ });+ commands.setProvider.mockReset().mockResolvedValue({+ _tag: "Success",+ value: { configured: true },+ });+ commands.disableProvider.mockReset().mockResolvedValue({+ _tag: "Success",+ value: { disabled: true },+ });+ commands.logout.mockReset().mockResolvedValue({+ _tag: "Success",+ value: { loggedOut: true },+ });+ dialogs.confirm.mockReset().mockResolvedValue(true);+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});++afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+ vi.unstubAllGlobals();+});++describe("AcpSessionManagementSection", () => {+ it("lists and imports native sessions through the owning environment", async () => {+ await render();+ await click("List sessions");++ expect(commands.list).toHaveBeenCalledWith({+ environmentId,+ input: { instanceId, projectId },+ });+ expect(container.textContent).toContain(session.title);++ await click("Import");++ expect(commands.import).toHaveBeenCalledWith({+ environmentId,+ input: {+ instanceId,+ projectId,+ sessionId: session.sessionId,+ title: session.title,+ updatedAt: session.updatedAt,+ },+ });+ expect(button("Imported").disabled).toBe(true);+ });++ it("logs out the provider instance through the owning environment", async () => {+ await render();+ await click("Log out");++ expect(commands.logout).toHaveBeenCalledWith({+ environmentId,+ input: { instanceId },+ });+ });++ it("deletes unimported native sessions after destructive confirmation", async () => {+ await render();+ await click("List sessions");+ await click("Delete");++ expect(dialogs.confirm).toHaveBeenCalledOnce();+ expect(commands.delete).toHaveBeenCalledWith({+ environmentId,+ input: { instanceId, projectId, sessionId: session.sessionId },+ });+ });++ it("locks the project picker while a project-scoped request is pending", async () => {+ const pending = deferred<{+ readonly _tag: "Success";+ readonly value: { readonly providers: [] };+ }>();+ commands.listProviders.mockReturnValueOnce(pending.promise);+ await render();+ const picker = () =>+ container.querySelector<HTMLElement>('[aria-label="Project for ACP sessions"]')!;+ expect(picker().hasAttribute("data-disabled")).toBe(false);++ await click("List providers");++ expect(picker().hasAttribute("data-disabled")).toBe(true);+ await act(async () => pending.resolve({ _tag: "Success", value: { providers: [] } }));+ expect(picker().hasAttribute("data-disabled")).toBe(false);+ });++ it("lists, saves, and disables configurable ACP providers", async () => {+ await render();+ await click("List providers");++ expect(commands.listProviders).toHaveBeenCalledWith({+ environmentId,+ input: { instanceId, projectId },+ });+ expect(+ container.querySelector<HTMLInputElement>('input[aria-label="google base URL"]')?.value,+ ).toBe("https://api.example.test/v1");+ await click("Save");+ expect(commands.setProvider).toHaveBeenCalledWith({+ environmentId,+ input: {+ instanceId,+ projectId,+ providerId: "google",+ apiType: "openai",+ baseUrl: "https://api.example.test/v1",+ },+ });++ await click("Disable");+ expect(commands.disableProvider).toHaveBeenCalledWith({+ environmentId,+ input: { instanceId, projectId, providerId: "google" },+ });+ });+});++it("imports with task access even when provider configuration is read-only", async () => {+ grants.scopes.delete("providers:manage");+ await render(true);+ await click("List sessions");+ await click("Import");+ expect(commands.import).toHaveBeenCalledOnce();+});++it("does not import with provider management alone", async () => {+ grants.scopes.delete("orchestration:operate");+ await render();+ await click("List sessions");+ expect(button("Import").disabled).toBe(true);+ await click("Import");+ expect(commands.import).not.toHaveBeenCalled();+});++it("rechecks task access after confirming deletion", async () => {+ await render();+ await click("List sessions");+ dialogs.confirm.mockImplementationOnce(async () => {+ grants.scopes.delete("orchestration:operate");+ return true;+ });+ await click("Delete");+ expect(commands.delete).not.toHaveBeenCalled();+});diff --git a/apps/web/src/components/settings/AcpSessionManagementSection.test.tsx b/apps/web/src/components/settings/AcpSessionManagementSection.test.tsxdeleted file mode 100644index e9dd834bd45..00000000000--- a/apps/web/src/components/settings/AcpSessionManagementSection.test.tsx+++ /dev/null@@ -1,331 +0,0 @@-import type { ReactElement } from "react";-import {- EnvironmentId,- ProjectId,- ProviderDriverKind,- ProviderInstanceId,- ThreadId,- type ServerProvider,-} from "@t3tools/contracts";-import { beforeEach, describe, expect, it, vi } from "vite-plus/test";--import { visitElements } from "../../test/reactElementTree";-import { reactHookHarness as hooks } from "../../test/reactHookHarness";--const atoms = vi.hoisted(() => ({- list: Symbol("list-acp-sessions"),- import: Symbol("import-acp-session"),- delete: Symbol("delete-acp-session"),- listProviders: Symbol("list-acp-providers"),- setProvider: Symbol("set-acp-provider"),- disableProvider: Symbol("disable-acp-provider"),- logout: Symbol("logout-acp"),-}));--const commands = vi.hoisted(() => ({- list: vi.fn(),- import: vi.fn(),- delete: vi.fn(),- listProviders: vi.fn(),- setProvider: vi.fn(),- disableProvider: vi.fn(),- logout: vi.fn(),-}));--const grants = vi.hoisted(() => ({ scopes: new Set<string>() }));-vi.mock("~/state/session", async (original) => ({- ...(await original<typeof import("~/state/session")>()),- useEnvironmentScope: (_id: unknown, scope: string) => grants.scopes.has(scope),- readEnvironmentScope: (_id: unknown, scope: string) => grants.scopes.has(scope),-}));-const dialogs = vi.hoisted(() => ({ confirm: vi.fn() }));--vi.mock("react", async (importOriginal) => {- const actual = await importOriginal<typeof import("react")>();- const { reactHookHarness } = await import("../../test/reactHookHarness");- return {- ...actual,- useState: reactHookHarness.useState,- };-});--vi.mock("react/compiler-runtime", async () => {- const { reactHookHarness } = await import("../../test/reactHookHarness");- return { c: reactHookHarness.useMemoCache };-});--vi.mock("../../state/server", () => ({- serverEnvironment: {- listAcpRegistrySessions: atoms.list,- importAcpRegistrySession: atoms.import,- deleteAcpRegistrySession: atoms.delete,- listAcpRegistryProviders: atoms.listProviders,- setAcpRegistryProvider: atoms.setProvider,- disableAcpRegistryProvider: atoms.disableProvider,- logoutAcpRegistry: atoms.logout,- },-}));--vi.mock("../../state/use-atom-command", () => ({- useAtomCommand: (atom: symbol) => {- if (atom === atoms.list) return commands.list;- if (atom === atoms.import) return commands.import;- if (atom === atoms.delete) return commands.delete;- if (atom === atoms.listProviders) return commands.listProviders;- if (atom === atoms.setProvider) return commands.setProvider;- if (atom === atoms.disableProvider) return commands.disableProvider;- return commands.logout;- },-}));--vi.mock("../../localApi", () => ({- ensureLocalApi: () => ({ dialogs }),-}));--import { AcpSessionManagementSection } from "./AcpSessionManagementSection";--const environmentId = EnvironmentId.make("remote-device");-const instanceId = ProviderInstanceId.make("acpRegistry_antigravity");-const projectId = ProjectId.make("project-antigravity");-const session = {- sessionId: "native-session-1",- cwd: "/workspace/antigravity",- additionalDirectories: [],- title: "Native Antigravity session",- updatedAt: "2026-08-23T00:00:00Z",- importedThreadId: null,-} as const;-const provider = {- instanceId,- driver: ProviderDriverKind.make("acpRegistry"),- enabled: true,- installed: true,- version: "1.0.0",- status: "ready",- auth: { status: "authenticated", canLogout: true },- nativeSessions: { canList: true, canLoad: true, canResume: true, canDelete: true },- configurableProviders: true,- checkedAt: "2026-08-23T00:00:00.000Z",- models: [],- slashCommands: [],- skills: [],-} satisfies ServerProvider;--function render(readOnly = false): ReactElement<Record<string, unknown>> {- hooks.beginRender();- return AcpSessionManagementSection({- environmentId,- instanceId,- provider,- projects: [{ id: projectId, title: "Antigravity", workspaceRoot: session.cwd }],- readOnly,- }) as ReactElement<Record<string, unknown>>;-}--function findByLabel(- tree: ReactElement<Record<string, unknown>>,- label: string,-): ReactElement<Record<string, unknown>> {- const found = visitElements(tree, (element) => element.props.children === label);- expect(found).not.toBeNull();- return found!;-}--function findByAriaLabel(- tree: ReactElement<Record<string, unknown>>,- label: string,-): ReactElement<Record<string, unknown>> {- const found = visitElements(tree, (element) => element.props["aria-label"] === label);- expect(found).not.toBeNull();- return found!;-}--async function flushPromises(): Promise<void> {- await Promise.resolve();- await Promise.resolve();-}--beforeEach(() => {- hooks.reset();- grants.scopes = new Set(["orchestration:read", "orchestration:operate", "providers:manage"]);- commands.list.mockReset().mockResolvedValue({- _tag: "Success",- value: {- sessions: [session],- nextCursor: null,- canLoad: true,- canResume: true,- canDelete: true,- },- });- commands.import.mockReset().mockResolvedValue({- _tag: "Success",- value: { threadId: ThreadId.make("thread-imported"), imported: true },- });- commands.delete.mockReset().mockResolvedValue({- _tag: "Success",- value: { deleted: true },- });- commands.listProviders.mockReset().mockResolvedValue({- _tag: "Success",- value: {- providers: [- {- providerId: "google",- supported: ["openai"],- required: false,- current: { apiType: "openai", baseUrl: "https://api.example.test/v1" },- },- ],- },- });- commands.setProvider.mockReset().mockResolvedValue({- _tag: "Success",- value: { configured: true },- });- commands.disableProvider.mockReset().mockResolvedValue({- _tag: "Success",- value: { disabled: true },- });- commands.logout.mockReset().mockResolvedValue({- _tag: "Success",- value: { loggedOut: true },- });- dialogs.confirm.mockReset().mockResolvedValue(true);-});--describe("AcpSessionManagementSection", () => {- it("lists and imports native sessions through the owning environment", async () => {- const initial = render();- (findByLabel(initial, "List sessions").props.onClick as (() => void) | undefined)?.();- await flushPromises();-- expect(commands.list).toHaveBeenCalledWith({- environmentId,- input: { instanceId, projectId },- });-- const listed = render();- (findByLabel(listed, "Import").props.onClick as (() => void) | undefined)?.();- await flushPromises();-- expect(commands.import).toHaveBeenCalledWith({- environmentId,- input: {- instanceId,- projectId,- sessionId: session.sessionId,- title: session.title,- updatedAt: session.updatedAt,- },- });- expect(findByLabel(render(), "Imported")).not.toBeNull();- });-- it("logs out the provider instance through the owning environment", async () => {- const tree = render();- (findByLabel(tree, "Log out").props.onClick as (() => void) | undefined)?.();- await flushPromises();-- expect(commands.logout).toHaveBeenCalledWith({- environmentId,- input: { instanceId },- });- });-- it("deletes unimported native sessions after destructive confirmation", async () => {- (findByLabel(render(), "List sessions").props.onClick as (() => void) | undefined)?.();- await flushPromises();- (findByLabel(render(), "Delete").props.onClick as (() => void) | undefined)?.();- await flushPromises();-- expect(dialogs.confirm).toHaveBeenCalledOnce();- expect(commands.delete).toHaveBeenCalledWith({- environmentId,- input: { instanceId, projectId, sessionId: session.sessionId },- });- });-- it("locks the project picker while a project-scoped request is pending", async () => {- let resolveProviders!: (result: {- readonly _tag: "Success";- readonly value: { readonly providers: [] };- }) => void;- commands.listProviders.mockReturnValueOnce(- new Promise((resolve) => {- resolveProviders = resolve;- }),- );- (findByLabel(render(), "List providers").props.onClick as (() => void) | undefined)?.();-- const projectSelect = visitElements(- render(),- (element) =>- element.props.value === projectId && typeof element.props.onValueChange === "function",- );- expect(projectSelect?.props.disabled).toBe(true);- resolveProviders({ _tag: "Success", value: { providers: [] } });- await flushPromises();- });-- it("lists, saves, and disables configurable ACP providers", async () => {- (findByLabel(render(), "List providers").props.onClick as (() => void) | undefined)?.();- await flushPromises();-- expect(commands.listProviders).toHaveBeenCalledWith({- environmentId,- input: { instanceId, projectId },- });- const providers = render();- expect(findByAriaLabel(providers, "google protocol").props.size).toBe("sm");- (findByLabel(providers, "Save").props.onClick as (() => void) | undefined)?.();- await flushPromises();- expect(commands.setProvider).toHaveBeenCalledWith({- environmentId,- input: {- instanceId,- projectId,- providerId: "google",- apiType: "openai",- baseUrl: "https://api.example.test/v1",- },- });-- (findByLabel(render(), "Disable").props.onClick as (() => void) | undefined)?.();- await flushPromises();- expect(commands.disableProvider).toHaveBeenCalledWith({- environmentId,- input: { instanceId, projectId, providerId: "google" },- });- });-});--it("imports with task access even when provider configuration is read-only", async () => {- grants.scopes.delete("providers:manage");- (findByLabel(render(true), "List sessions").props.onClick as () => void)();- await flushPromises();- (findByLabel(render(true), "Import").props.onClick as () => void)();- await flushPromises();- expect(commands.import).toHaveBeenCalledOnce();-});--it("does not import with provider management alone", async () => {- grants.scopes.delete("orchestration:operate");- (findByLabel(render(), "List sessions").props.onClick as () => void)();- await flushPromises();- (findByLabel(render(), "Import").props.onClick as () => void)();- await flushPromises();- expect(commands.import).not.toHaveBeenCalled();-});--it("rechecks task access after confirming deletion", async () => {- (findByLabel(render(), "List sessions").props.onClick as () => void)();- await flushPromises();- dialogs.confirm.mockImplementationOnce(async () => {- grants.scopes.delete("orchestration:operate");- return true;- });- (findByLabel(render(), "Delete").props.onClick as () => void)();- await flushPromises();- expect(commands.delete).not.toHaveBeenCalled();-});diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.environment.browser.test.tsx b/apps/web/src/components/settings/AddProviderInstanceDialog.environment.browser.test.tsxnew file mode 100644index 00000000000..f4d5179da2d--- /dev/null+++ b/apps/web/src/components/settings/AddProviderInstanceDialog.environment.browser.test.tsx@@ -0,0 +1,357 @@+import { EnvironmentId, ProviderDriverKind, type AcpRegistrySearchAgent } from "@t3tools/contracts";+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { userEvent } from "vite-plus/test/browser";+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";++const actions = vi.hoisted(() => ({+ toast: vi.fn(),+ onOpenChange: vi.fn(),+ canManageProviders: true,+}));+const settingsHooks = vi.hoisted(() => ({+ read: vi.fn(() => ({ providerInstances: {} })),+ mutate: vi.fn(),+ useMutation: vi.fn(),+}));+const preparedAgent = vi.hoisted((): AcpRegistrySearchAgent => ({+ id: "kilo",+ name: "Kilo Code",+ version: "4.2.0",+ description: "Kilo ACP agent",+ authors: ["Kilo"],+ license: "Apache-2.0",+ website: null,+ repository: null,+ icon: "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg",+ distribution: "binary",+ integrity: "sha256",+}));++vi.mock(import("@t3tools/client-runtime/state/runtime"), async (original) => ({+ ...(await original()),+ squashAtomCommandFailure: () => new Error("The settings update failed."),+}));+vi.mock(import("../../hooks/useSettings"), async (original) => ({+ ...(await original()),+ useEnvironmentSettings: settingsHooks.read as never,+ usePersistEnvironmentProviderInstanceMutation: settingsHooks.useMutation as never,+}));+vi.mock(import("../../state/session"), async (original) => {+ const hasScope = (environmentId: EnvironmentId, scope: string) =>+ environmentId === "remote-device" && scope === "providers:manage" && actions.canManageProviders;+ return {+ ...(await original()),+ useEnvironmentScope: hasScope as never,+ readEnvironmentScope: hasScope as never,+ };+});+vi.mock(import("../ui/toast"), async (original) => {+ const actual = await original();+ return { ...actual, toastManager: { ...actual.toastManager, add: actions.toast } };+});+// The registry search and the sign-in step talk to the environment over RPC; these+// stand-ins expose the choices a user makes there.+vi.mock(import("./AcpRegistrySearchStep"), async (original) => ({+ ...(await original()),+ AcpRegistrySearchStep: ((props: {+ onPrepared: (agent: AcpRegistrySearchAgent) => void;+ onManualConfiguration: () => void;+ onLocalConfiguration: () => void;+ }) => (+ <div>+ <button type="button" onClick={() => props.onPrepared(preparedAgent)}>+ Use Kilo Code+ </button>+ <button type="button" onClick={props.onManualConfiguration}>+ Enter registry agent+ </button>+ <button type="button" onClick={props.onLocalConfiguration}>+ Use local command+ </button>+ </div>+ )) as never,+}));+vi.mock(import("./ProviderWizardAuthenticationStep"), async (original) => ({+ ...(await original()),+ ProviderWizardAuthenticationStep: (props: {+ environmentId: string;+ instanceId: string;+ onFinish: () => void;+ }) => (+ <section aria-label="Sign-in step">+ {props.environmentId}/{props.instanceId}+ <button type="button" onClick={props.onFinish}>+ Finish sign-in+ </button>+ </section>+ ),+}));++import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog";++const remoteEnvironmentId = EnvironmentId.make("remote-device");++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => {+ resolve = done;+ });+ return { promise, resolve };+}++let root: Root;++function render(onOpenChange = actions.onOpenChange) {+ return act(async () =>+ root.render(+ <AddProviderInstanceDialog+ open+ environmentId={remoteEnvironmentId}+ environmentLabel="Remote device"+ onOpenChange={onOpenChange}+ />,+ ),+ );+}+function button(label: string) {+ const found = [...document.querySelectorAll("button")].find(+ (element) => element.textContent?.trim() === label,+ );+ expect(found, `button ${label}`).toBeDefined();+ return found!;+}+const click = (label: string) => act(async () => button(label).click());+const input = (selector: string) => {+ const found = document.querySelector<HTMLInputElement>(selector);+ expect(found, selector).not.toBeNull();+ return found!;+};+async function type(selector: string, value: string) {+ await act(async () => userEvent.fill(input(selector), value));+ await act(async () => input(selector).blur());+}+const signInStep = () => document.querySelector('[aria-label="Sign-in step"]');++async function prepareCodexInstance() {+ await render();+ await click("Configure manually");+ await type("#add-provider-label", "Work");+ await click("Next");+}++describe("AddProviderInstanceDialog environment routing", () => {+ beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ actions.canManageProviders = true;+ actions.toast.mockReset();+ actions.onOpenChange.mockReset();+ settingsHooks.read.mockReset().mockReturnValue({ providerInstances: {} });+ settingsHooks.mutate.mockReset().mockResolvedValue({ _tag: "Success", value: {} });+ settingsHooks.useMutation.mockReset().mockReturnValue(settingsHooks.mutate);+ root = createRoot(document.createElement("div"));+ });+ afterEach(async () => {+ await act(async () => root.unmount());+ vi.unstubAllGlobals();+ });++ it("creates a provider with its default identity without typing", async () => {+ await render();+ const grok = [...document.querySelectorAll('[role="radio"]')].find((radio) =>+ radio.textContent?.includes("Grok"),+ ) as HTMLElement;+ await act(async () => grok.click());+ await click("Next");+ await click("Next");+ await click("Add instance");+ expect(settingsHooks.mutate).toHaveBeenCalledWith({+ operation: "create",+ instanceId: "grok",+ instance: { driver: "grok", enabled: true, displayName: "Grok" },+ });+ });++ it("chooses an unused identity for another account without replacing configured instances", async () => {+ settingsHooks.read.mockReturnValue({+ providerInstances: { codex_2: { driver: "codex", enabled: false } },+ });+ await render();+ await click("Configure manually");+ await click("Next");+ await click("Add instance");+ expect(settingsHooks.mutate).toHaveBeenCalledWith({+ operation: "create",+ instanceId: "codex_3",+ instance: {+ driver: "codex",+ enabled: true,+ displayName: "Codex",+ config: { setupMode: "existing" },+ },+ });+ });++ it("reads and writes settings through the supplied environment", async () => {+ await render();++ expect(settingsHooks.read).toHaveBeenCalledWith(remoteEnvironmentId);+ expect(settingsHooks.useMutation).toHaveBeenCalledWith(remoteEnvironmentId);+ });++ it("awaits an atomic create before closing and retains prepared ACP metadata", async () => {+ const mutation = deferred<{ readonly _tag: "Success"; readonly value: unknown }>();+ settingsHooks.mutate.mockReturnValueOnce(mutation.promise);+ await render();+ await click("Use Kilo Code");++ expect(document.body.textContent).toContain("v4.2.0 · binary");+ await click("Continue to sign-in");+ expect(settingsHooks.mutate).toHaveBeenCalledWith({+ operation: "create",+ instanceId: "acpRegistry_kilo_code",+ instance: {+ driver: ProviderDriverKind.make("acpRegistry"),+ enabled: true,+ displayName: "Kilo Code",+ config: {+ agentId: "kilo",+ distribution: "auto",+ registryIconUrl: "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg",+ },+ },+ });+ expect(signInStep()).toBeNull();++ await act(async () => mutation.resolve({ _tag: "Success", value: {} }));+ expect(actions.onOpenChange).not.toHaveBeenCalled();+ expect(signInStep()?.textContent).toContain("remote-device/acpRegistry_kilo_code");+ expect(settingsHooks.mutate).toHaveBeenCalledTimes(1);+ await click("Finish sign-in");+ expect(actions.onOpenChange).toHaveBeenCalledWith(false);+ });++ it("configures a manually entered registry agent from the first provider screen", async () => {+ await render();+ await click("Enter registry agent");+ await type("#add-provider-acpRegistry-manual-agentId", "devin");+ await click("Next");+ await click("Continue to sign-in");+ expect(settingsHooks.mutate).toHaveBeenCalledWith({+ operation: "create",+ instanceId: "acpRegistry_custom",+ instance: {+ driver: "acpRegistry",+ enabled: true,+ config: { agentId: "devin" },+ },+ });+ expect(signInStep()).not.toBeNull();+ });++ it("creates a local command in the selected environment without a sign-in step", async () => {+ await render();+ await click("Use local command");+ await click("Next");+ expect(document.body.textContent).toContain("Executable is required.");+ expect(settingsHooks.mutate).not.toHaveBeenCalled();++ await type("#add-provider-acpRegistry-manual-commandPath", "dsh");+ const commandArgs = ["--profile", "acp", " literal $(value) ; ", ""];+ for (const [index, argument] of commandArgs.entries()) {+ await click("Add argument");+ if (argument) await type(`input[aria-label="Argument ${index + 1}"]`, argument);+ }+ await click("Add variable");+ await type('input[aria-label="Environment variable name 1"]', "DSH_PROFILE");+ await act(async () =>+ document+ .querySelector<HTMLButtonElement>(+ 'button[aria-label="Mark environment variable DSH_PROFILE as sensitive"]',+ )!+ .click(),+ );+ await type('input[aria-label="Environment variable value 1"]', "work");+ await click("Next");+ await type("#add-provider-label", "Deepseek Harness");+ await click("Add instance");++ expect(settingsHooks.useMutation).toHaveBeenCalledWith(remoteEnvironmentId);+ expect(settingsHooks.mutate).toHaveBeenCalledWith({+ operation: "create",+ instanceId: "acpRegistry_deepseek_harness",+ instance: {+ driver: "acpRegistry",+ enabled: true,+ displayName: "Deepseek Harness",+ config: { source: "local", commandPath: "dsh", commandArgs },+ environment: [+ expect.objectContaining({ name: "DSH_PROFILE", value: "work", sensitive: false }),+ ],+ },+ });+ expect(actions.onOpenChange).toHaveBeenCalledWith(false);+ expect(signInStep()).toBeNull();+ });++ it("keeps the dialog open when the atomic upsert fails", async () => {+ settingsHooks.mutate.mockResolvedValueOnce({ _tag: "Failure", cause: new Error("Conflict") });+ await render();+ await click("Use Kilo Code");+ await click("Continue to sign-in");++ expect(actions.onOpenChange).not.toHaveBeenCalled();+ expect(actions.toast).toHaveBeenCalledWith(+ expect.objectContaining({ type: "error", title: "Could not add provider instance" }),+ );+ expect(button("Continue to sign-in").disabled).toBe(false);+ });++ it("adds an instance with the selected environment's provider grant alone", async () => {+ await prepareCodexInstance();+ await click("Add instance");++ expect(settingsHooks.mutate).toHaveBeenCalledWith({+ operation: "create",+ instanceId: "codex_work",+ instance: {+ driver: "codex",+ enabled: true,+ displayName: "Work",+ config: { setupMode: "existing" },+ },+ });+ expect(actions.toast).toHaveBeenCalledWith(+ expect.objectContaining({ type: "success", title: "Provider instance added" }),+ );+ expect(actions.onOpenChange).toHaveBeenCalledWith(false);+ });++ it("rejects a queued save after the provider grant is revoked", async () => {+ await prepareCodexInstance();+ const save = button("Add instance");+ actions.canManageProviders = false;+ // The rendered button is still enabled; the click must recheck the live grant.+ await act(async () => save.click());++ expect(settingsHooks.mutate).not.toHaveBeenCalled();+ expect(actions.toast).not.toHaveBeenCalled();+ expect(actions.onOpenChange).not.toHaveBeenCalled();+ await render();+ expect(button("Add instance").disabled).toBe(true);+ });++ it("keeps a denied draft available when the provider grant arrives", async () => {+ actions.canManageProviders = false;+ await prepareCodexInstance();+ expect(button("Add instance").disabled).toBe(true);+ expect(settingsHooks.mutate).not.toHaveBeenCalled();++ actions.canManageProviders = true;+ await render();+ expect(button("Add instance").disabled).toBe(false);+ await click("Add instance");+ expect(settingsHooks.mutate).toHaveBeenCalledOnce();+ expect(actions.onOpenChange).toHaveBeenCalledWith(false);+ });+});diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.environment.test.tsx b/apps/web/src/components/settings/AddProviderInstanceDialog.environment.test.tsxdeleted file mode 100644index e4aba048bb6..00000000000--- a/apps/web/src/components/settings/AddProviderInstanceDialog.environment.test.tsx+++ /dev/null@@ -1,424 +0,0 @@-import { EnvironmentId, ProviderDriverKind, type AcpRegistrySearchAgent } from "@t3tools/contracts";-import { beforeEach, describe, expect, it, vi } from "vite-plus/test";--import { visitElements } from "../../test/reactElementTree";-import { reactHookHarness as hooks } from "../../test/reactHookHarness";--const actions = vi.hoisted(() => ({- update: vi.fn(),- toast: vi.fn(),- onOpenChange: vi.fn(),- canManageProviders: true,-}));--const settingsHooks = vi.hoisted(() => ({- read: vi.fn(() => ({ providerInstances: {} })),- mutate: vi.fn(),- useMutation: vi.fn(),-}));--vi.mock("react", async (importOriginal) => {- const actual = await importOriginal<typeof import("react")>();- const { reactHookHarness } = await import("../../test/reactHookHarness");- return {- ...actual,- useMemo: reactHookHarness.useMemo,- useState: reactHookHarness.useState,- };-});--vi.mock("react/compiler-runtime", async () => {- const { reactHookHarness } = await import("../../test/reactHookHarness");- return { c: reactHookHarness.useMemoCache };-});--vi.mock("@t3tools/client-runtime/state/runtime", async (importOriginal) => ({- ...(await importOriginal<typeof import("@t3tools/client-runtime/state/runtime")>()),- squashAtomCommandFailure: () => new Error("The settings update failed."),-}));--vi.mock("../../hooks/useSettings", () => ({- useEnvironmentSettings: settingsHooks.read,- usePersistEnvironmentProviderInstanceMutation: settingsHooks.useMutation,-}));--vi.mock("../../state/session", async (importOriginal) => {- const actual = await importOriginal<typeof import("../../state/session")>();- const hasScope = (environmentId: EnvironmentId, scope: string) =>- environmentId === "remote-device" && scope === "providers:manage" && actions.canManageProviders;- return { ...actual, useEnvironmentScope: hasScope, readEnvironmentScope: hasScope };-});--vi.mock("../ui/toast", () => ({ toastManager: { add: actions.toast } }));--import { AddProviderInstanceDialog } from "./AddProviderInstanceDialog";--const remoteEnvironmentId = EnvironmentId.make("remote-device");-const preparedAgent: AcpRegistrySearchAgent = {- id: "kilo",- name: "Kilo Code",- version: "4.2.0",- description: "Kilo ACP agent",- authors: ["Kilo"],- license: "Apache-2.0",- website: null,- repository: null,- icon: "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg",- distribution: "binary",- integrity: "sha256",-};--function render(onOpenChange = vi.fn()) {- hooks.beginRender();- return AddProviderInstanceDialog({- open: true,- environmentId: remoteEnvironmentId,- environmentLabel: "Remote device",- onOpenChange,- });-}--function findByChildren(tree: ReturnType<typeof render>, children: string) {- const result = visitElements(tree, (element) => element.props.children === children);- expect(result).not.toBeNull();- return result!;-}--async function selectPreparedAcp() {- const searchStep = render();- const search = visitElements(- searchStep,- (element) =>- typeof element.type === "function" && element.type.name === "AcpRegistrySearchStep",- );- expect(search).not.toBeNull();- (search?.props.onPrepared as ((agent: AcpRegistrySearchAgent) => void) | undefined)?.(- preparedAgent,- );-}--function renderDialog() {- hooks.beginRender();- return AddProviderInstanceDialog({- open: true,- environmentId: remoteEnvironmentId,- environmentLabel: "Remote device",- onOpenChange: actions.onOpenChange,- });-}--function button(dialog: unknown, label: string) {- const element = visitElements(- dialog,- (entry) => entry.props.children === label && typeof entry.props.onClick === "function",- );- if (!element) throw new Error(`Missing button: ${label}`);- return element;-}--function prepareInstance() {- let dialog = renderDialog();- (button(dialog, "Configure manually").props.onClick as () => void)();- dialog = renderDialog();- const label = visitElements(dialog, (entry) => entry.props.placeholder === "e.g. Work");- if (!label) throw new Error("Missing instance label input.");- (label.props.onChange as (event: { target: { value: string } }) => void)({- target: { value: "Work" },- });- dialog = renderDialog();- (button(dialog, "Next").props.onClick as () => void)();- return renderDialog();-}--describe("AddProviderInstanceDialog environment routing", () => {- beforeEach(() => {- hooks.reset();- actions.canManageProviders = true;- actions.toast.mockReset();- actions.onOpenChange.mockReset();- settingsHooks.read.mockReset().mockReturnValue({ providerInstances: {} });- settingsHooks.mutate.mockReset().mockResolvedValue({ _tag: "Success", value: {} });- settingsHooks.useMutation.mockReset().mockReturnValue(settingsHooks.mutate);- });-- it("creates a provider with its default identity without typing", async () => {- let tree = render();- const group = visitElements(- tree,- (element) => element.props["aria-labelledby"] === "add-instance-driver-label",- );- (group!.props.onValueChange as (value: string) => void)("grok");- tree = render();- (findByChildren(tree, "Next").props.onClick as () => void)();- tree = render();- (findByChildren(tree, "Next").props.onClick as () => void)();- tree = render();- (findByChildren(tree, "Add instance").props.onClick as () => void)();- await Promise.resolve();- expect(settingsHooks.mutate).toHaveBeenCalledWith({- operation: "create",- instanceId: "grok",- instance: { driver: "grok", enabled: true, displayName: "Grok" },- });- });-- it("chooses an unused identity for another account without replacing configured instances", async () => {- settingsHooks.read.mockReturnValue({- providerInstances: {- codex_2: { driver: "codex", enabled: false },- },- });- let tree = render();- (findByChildren(tree, "Configure manually").props.onClick as () => void)();- tree = render();- (findByChildren(tree, "Next").props.onClick as () => void)();- tree = render();- (findByChildren(tree, "Add instance").props.onClick as () => void)();- await Promise.resolve();- expect(settingsHooks.mutate).toHaveBeenCalledWith({- operation: "create",- instanceId: "codex_3",- instance: {- driver: "codex",- enabled: true,- displayName: "Codex",- config: { setupMode: "existing" },- },- });- });-- it("reads and writes settings through the supplied environment", () => {- render();-- expect(settingsHooks.read).toHaveBeenCalledWith(remoteEnvironmentId);- expect(settingsHooks.useMutation).toHaveBeenCalledWith(remoteEnvironmentId);- });-- it("awaits an atomic create before closing and retains prepared ACP metadata", async () => {- const onOpenChange = vi.fn();- let resolveMutation!: (value: { readonly _tag: "Success"; readonly value: unknown }) => void;- settingsHooks.mutate.mockReturnValueOnce(- new Promise((resolve) => {- resolveMutation = resolve;- }),- );- await selectPreparedAcp();-- const identityStep = render(onOpenChange);- expect(- visitElements(identityStep, (element) => {- const content = JSON.stringify(element.props.children);- return content?.includes("4.2.0") === true && content.includes("binary");- }),- ).not.toBeNull();- (- findByChildren(identityStep, "Continue to sign-in").props.onClick as (() => void) | undefined- )?.();- expect(settingsHooks.mutate).toHaveBeenCalledWith({- operation: "create",- instanceId: "acpRegistry_kilo_code",- instance: {- driver: ProviderDriverKind.make("acpRegistry"),- enabled: true,- displayName: "Kilo Code",- config: {- agentId: "kilo",- distribution: "auto",- registryIconUrl: "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg",- },- },- });- expect(onOpenChange).not.toHaveBeenCalled();-- resolveMutation({ _tag: "Success", value: {} });- await Promise.resolve();- await Promise.resolve();- expect(onOpenChange).not.toHaveBeenCalled();- const signInStep = render(onOpenChange);- const authentication = visitElements(- signInStep,- (element) =>- typeof element.type === "function" &&- element.type.name === "ProviderWizardAuthenticationStep",- );- expect(authentication?.props.instanceId).toBe("acpRegistry_kilo_code");- expect(authentication?.props.environmentId).toBe(remoteEnvironmentId);- expect(settingsHooks.mutate).toHaveBeenCalledTimes(1);- (authentication!.props.onFinish as () => void)();- expect(onOpenChange).toHaveBeenCalledWith(false);- });-- it("configures a manually entered registry agent from the first provider screen", async () => {- let tree = render();- const search = visitElements(- tree,- (element) =>- typeof element.type === "function" && element.type.name === "AcpRegistrySearchStep",- );- (search!.props.onManualConfiguration as () => void)();- tree = render();- const configuration = visitElements(- tree,- (element) => element.props.idPrefix === "add-provider-acpRegistry-manual",- );- (configuration!.props.onChange as (value: Record<string, unknown>) => void)({- agentId: "devin",- });- tree = render();- (findByChildren(tree, "Next").props.onClick as () => void)();- tree = render();- (findByChildren(tree, "Continue to sign-in").props.onClick as () => void)();- await Promise.resolve();- await Promise.resolve();- expect(settingsHooks.mutate).toHaveBeenCalledWith({- operation: "create",- instanceId: "acpRegistry_custom",- instance: {- driver: "acpRegistry",- enabled: true,- config: { agentId: "devin" },- },- });- tree = render();- expect(- visitElements(- tree,- (element) =>- typeof element.type === "function" &&- element.type.name === "ProviderWizardAuthenticationStep",- ),- ).not.toBeNull();- });-- it("creates a local command in the selected environment without a sign-in step", async () => {- const onOpenChange = vi.fn();- let tree = render(onOpenChange);- const search = visitElements(- tree,- (element) =>- typeof element.type === "function" && element.type.name === "AcpRegistrySearchStep",- );- (search!.props.onLocalConfiguration as () => void)();- tree = render(onOpenChange);- (findByChildren(tree, "Next").props.onClick as () => void)();- tree = render(onOpenChange);- expect(findByChildren(tree, "Executable is required.")).not.toBeNull();- expect(settingsHooks.mutate).not.toHaveBeenCalled();-- const configuration = visitElements(- tree,- (element) => element.props.idPrefix === "add-provider-acpRegistry-manual",- );- const commandArgs = ["--profile", "acp", " literal $(value) ; ", ""];- (configuration!.props.onChange as (value: Record<string, unknown>) => void)({- source: "local",- commandPath: "dsh",- commandArgs,- });- const environmentEditor = visitElements(- tree,- (element) =>- typeof element.type === "function" && element.type.name === "ProviderEnvironmentSection",- );- const environment = [{ name: "DSH_PROFILE", value: "work", sensitive: false }];- (environmentEditor!.props.onChange as (value: typeof environment) => void)(environment);- tree = render(onOpenChange);- (findByChildren(tree, "Next").props.onClick as () => void)();- tree = render(onOpenChange);- const label = visitElements(tree, (element) => element.props.id === "add-provider-label");- (label!.props.onChange as (event: { target: { value: string } }) => void)({- target: { value: "Deepseek Harness" },- });- tree = render(onOpenChange);- (findByChildren(tree, "Add instance").props.onClick as () => void)();- await Promise.resolve();- await Promise.resolve();-- expect(settingsHooks.useMutation).toHaveBeenCalledWith(remoteEnvironmentId);- expect(settingsHooks.mutate).toHaveBeenCalledWith({- operation: "create",- instanceId: "acpRegistry_deepseek_harness",- instance: {- driver: "acpRegistry",- enabled: true,- displayName: "Deepseek Harness",- config: { source: "local", commandPath: "dsh", commandArgs },- environment,- },- });- expect(onOpenChange).toHaveBeenCalledWith(false);- tree = render(onOpenChange);- expect(- visitElements(- tree,- (element) =>- typeof element.type === "function" &&- element.type.name === "ProviderWizardAuthenticationStep",- ),- ).toBeNull();- });-- it("keeps the dialog open when the atomic upsert fails", async () => {- settingsHooks.mutate.mockResolvedValueOnce({ _tag: "Failure", cause: new Error("Conflict") });- const onOpenChange = vi.fn();- await selectPreparedAcp();-- const identityStep = render(onOpenChange);- (- findByChildren(identityStep, "Continue to sign-in").props.onClick as (() => void) | undefined- )?.();- await Promise.resolve();- await Promise.resolve();-- expect(onOpenChange).not.toHaveBeenCalled();- });-- it("adds an instance with the selected environment's provider grant alone", async () => {- const dialog = prepareInstance();- (button(dialog, "Add instance").props.onClick as () => void)();-- await Promise.resolve();- expect(settingsHooks.mutate).toHaveBeenCalledWith({- operation: "create",- instanceId: "codex_work",- instance: {- driver: "codex",- enabled: true,- displayName: "Work",- config: { setupMode: "existing" },- },- });- expect(actions.toast).toHaveBeenCalledWith(- expect.objectContaining({ type: "success", title: "Provider instance added" }),- );- expect(actions.onOpenChange).toHaveBeenCalledWith(false);- });-- it("rejects a queued save after the provider grant is revoked", () => {- const dialog = prepareInstance();- const save = button(dialog, "Add instance").props.onClick as () => void;- actions.canManageProviders = false;- save();-- expect(settingsHooks.mutate).not.toHaveBeenCalled();- expect(actions.toast).not.toHaveBeenCalled();- expect(actions.onOpenChange).not.toHaveBeenCalled();- expect(button(renderDialog(), "Add instance").props.disabled).toBe(true);- });-- it("keeps a denied draft available when the provider grant arrives", async () => {- actions.canManageProviders = false;- let dialog = prepareInstance();- (button(dialog, "Add instance").props.onClick as () => void)();- expect(settingsHooks.mutate).not.toHaveBeenCalled();- expect(actions.toast).not.toHaveBeenCalled();-- actions.canManageProviders = true;- dialog = renderDialog();- expect(button(dialog, "Add instance").props.disabled).toBe(false);- (button(dialog, "Add instance").props.onClick as () => void)();- await Promise.resolve();- expect(settingsHooks.mutate).toHaveBeenCalledOnce();- expect(actions.onOpenChange).toHaveBeenCalledWith(false);- });-});diff --git a/apps/web/src/components/settings/CaptureShortcutConfig.browser.test.tsx b/apps/web/src/components/settings/CaptureShortcutConfig.browser.test.tsxnew file mode 100644index 00000000000..3af26ae02a4--- /dev/null+++ b/apps/web/src/components/settings/CaptureShortcutConfig.browser.test.tsx@@ -0,0 +1,263 @@+import {+ DEFAULT_CLIENT_SETTINGS,+ type DesktopCaptureConfigPreview,+ type DesktopSnapShotState,+} from "@t3tools/contracts";+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { userEvent } from "vite-plus/test/browser";+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";++const bridge = vi.hoisted(() => ({+ previewSnapShotConfig: vi.fn(),+ applySnapShotConfig: vi.fn(),+ setSnapShotShortcutSuppressed: vi.fn(),+}));+const toast = vi.hoisted(() => vi.fn());+vi.mock(import("../../lib/desktopSnapShot"), async (original) => ({+ ...(await original()),+ getDesktopSnapShotBridge: () => bridge as never,+}));+vi.mock(import("../ui/toast"), async (original) => {+ const actual = await original();+ return { ...actual, toastManager: { ...actual.toastManager, add: toast } };+});++import { CaptureShortcutConfig } from "./CaptureShortcutConfig";++const preview: DesktopCaptureConfigPreview = {+ id: "approved-snapshot",+ path: "/config/niri/config.kdl",+ resolvedPath: "/config/niri/config.kdl",+ before: "binds {\n}\n",+ after: 'binds {\n Ctrl+Shift+2 { spawn "gdbus"; }\n}\n',+ shortcut: "Ctrl+Shift+2",+ operation: "install",+};+const complete = vi.fn<() => Promise<void>>();++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => {+ resolve = done;+ });+ return { promise, resolve };+}++let root: Root;+let container: HTMLDivElement;++async function render(desktop: "niri" | "hyprland" = "niri") {+ const state: DesktopSnapShotState = {+ mode: "portal",+ linuxBackend: desktop,+ shortcut: DEFAULT_CLIENT_SETTINGS.snapShotShortcut,+ shortcutRegistered: false,+ shortcutActionRegistered: true,+ shortcutMessage: null,+ message: null,+ shortcutConfigPath: preview.path,+ shortcutBinding: "manual binding",+ };+ await act(async () => root.render(<CaptureShortcutConfig state={state} onComplete={complete} />));+}+function button(label: string) {+ return [...container.querySelectorAll("button")].find((element) => element.textContent === label);+}+async function click(label: string) {+ const target = button(label);+ expect(target, `button ${label}`).toBeDefined();+ await act(async () => target!.click());+}+const recorder = () => container.querySelector<HTMLButtonElement>("[data-keybinding-capture]")!;+const diff = () => container.querySelector('[aria-label="Shortcut changes"]');+const alert = () => container.querySelector('[role="alert"]');+const advanced = () => container.querySelector("details")!;+async function recordKeys(keys: string) {+ await act(async () => userEvent.click(recorder()));+ await act(async () => userEvent.keyboard(keys));+}++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ Object.defineProperty(navigator, "platform", { configurable: true, get: () => "Linux" });+ bridge.setSnapShotShortcutSuppressed.mockReset().mockResolvedValue(undefined);+ bridge.previewSnapShotConfig.mockReset().mockResolvedValue(preview);+ bridge.applySnapShotConfig+ .mockReset()+ .mockResolvedValue({ backupPath: "/config/backup", warning: null });+ complete.mockReset().mockResolvedValue(undefined);+ toast.mockClear();+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});+afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+ Reflect.deleteProperty(navigator, "platform");+ vi.unstubAllGlobals();+});++it.each(["niri", "hyprland"] as const)(+ "shows the fallback before review and requires separate read and write approval on %s",+ async (desktop) => {+ await render(desktop);+ expect(recorder().getAttribute("aria-label")).toBe(+ "Record snapshot shortcut, currently Ctrl+Shift+2",+ );+ expect(advanced().textContent).toContain("manual binding");+ expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();+ await click("Review changes");+ expect(recorder().getAttribute("aria-label")).toBe(+ "Record snapshot shortcut, currently Ctrl+Shift+2",+ );+ expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();+ expect(diff()).not.toBeNull();+ await click("Save shortcut");+ expect(bridge.applySnapShotConfig).toHaveBeenCalledExactlyOnceWith(preview.id);+ expect(complete).toHaveBeenCalledOnce();+ expect(toast).toHaveBeenCalledWith(expect.objectContaining({ type: "success" }));+ },+);++it.each(["niri", "hyprland"] as const)(+ "lets users choose %s keys without opening Advanced, then approve the matching diff",+ async (desktop) => {+ await render(desktop);+ expect(advanced().contains(recorder())).toBe(false);+ await recordKeys("{Control>}{Alt>}y{/Alt}{/Control}");+ expect(bridge.setSnapShotShortcutSuppressed).toHaveBeenNthCalledWith(1, true);+ expect(bridge.setSnapShotShortcutSuppressed).toHaveBeenLastCalledWith(false);+ expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();+ const custom = {+ ...preview,+ id: "custom-keys",+ shortcut: "Ctrl+Alt+Y",+ after: preview.after.replace("Ctrl+Shift+2", "Ctrl+Alt+Y"),+ };+ bridge.previewSnapShotConfig.mockResolvedValue(custom);+ await click("Review changes");+ expect(bridge.previewSnapShotConfig).toHaveBeenCalledExactlyOnceWith({+ operation: "install",+ chooseFile: false,+ shortcut: "ctrl+alt+y",+ });+ expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();+ await click("Save shortcut");+ expect(bridge.applySnapShotConfig).toHaveBeenCalledExactlyOnceWith(custom.id);+ expect(toast).toHaveBeenCalledWith(+ expect.objectContaining({ description: "Use Ctrl+Alt+Y from another app." }),+ );+ },+);++it("uses the existing config keys when no replacement was chosen", async () => {+ bridge.previewSnapShotConfig.mockResolvedValue({ ...preview, shortcut: "Super+F8" });+ await render();+ await click("Review changes");+ expect(bridge.previewSnapShotConfig).toHaveBeenCalledExactlyOnceWith({+ operation: "install",+ chooseFile: false,+ });+ expect(recorder().getAttribute("aria-label")).toContain("F8");+});++it("requires a new diff after changing keys during review", async () => {+ await render();+ await click("Review changes");+ expect(diff()).not.toBeNull();+ await recordKeys("{Meta>}{F8}{/Meta}");+ expect(diff()).toBeNull();+ expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();+ const replacement = { ...preview, id: "replacement", shortcut: "Super+F8" };+ bridge.previewSnapShotConfig.mockResolvedValue(replacement);+ await click("Review changes");+ expect(bridge.previewSnapShotConfig).toHaveBeenLastCalledWith({+ operation: "install",+ chooseFile: false,+ shortcut: "meta+f8",+ });+ await click("Save shortcut");+ expect(bridge.applySnapShotConfig).toHaveBeenCalledExactlyOnceWith(replacement.id);+});++it.each(["Escape", "blur"])(+ "keeps the reviewed diff when recording is cancelled with %s",+ async (cancel) => {+ await render();+ await click("Review changes");+ await act(async () => userEvent.click(recorder()));+ expect(button("Save shortcut")?.disabled).toBe(true);+ if (cancel === "Escape") await act(async () => userEvent.keyboard("{Escape}"));+ else await act(async () => recorder().blur());+ expect(button("Save shortcut")?.disabled).toBe(false);+ expect(bridge.previewSnapShotConfig).toHaveBeenCalledOnce();+ await click("Save shortcut");+ expect(bridge.applySnapShotConfig).toHaveBeenCalledExactlyOnceWith(preview.id);+ },+);++it("cancelling a reviewed diff does not write or finish setup", async () => {+ await render();+ await click("Review changes");+ await click("Cancel");+ expect(recorder().getAttribute("aria-label")).toBe(+ "Record snapshot shortcut, currently Ctrl+Shift+2",+ );+ expect(button("Review changes")).toBeDefined();+ expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();+ expect(complete).not.toHaveBeenCalled();+});++it("shows reading feedback until a proposal arrives", async () => {+ const pending = deferred<DesktopCaptureConfigPreview>();+ bridge.previewSnapShotConfig.mockReturnValue(pending.promise);+ await render();+ await click("Review changes");+ expect(button("Preparing changes…")?.disabled).toBe(true);+ await act(async () => pending.resolve(preview));+ expect(button("Save shortcut")?.disabled).toBe(false);+});++it("keeps read failures actionable with technical details in Advanced, then permits retry", async () => {+ bridge.previewSnapShotConfig.mockRejectedValueOnce(new Error("EACCES: /config/niri/config.kdl"));+ await render();+ await click("Review changes");+ expect(alert()?.textContent).toBe("Couldn't prepare the changes. Check Advanced for help.");+ expect(advanced().textContent).toContain("EACCES: /config/niri/config.kdl");+ await click("Review changes");+ expect(alert()).toBeNull();+ expect(button("Save shortcut")?.disabled).toBe(false);+ expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();+});++it("withdraws a stale diff and requires another read instead of retrying its write", async () => {+ await render();+ await click("Review changes");+ bridge.applySnapShotConfig.mockRejectedValue(+ new Error("Your config changed since this preview."),+ );+ await click("Save shortcut");+ expect(alert()?.textContent).toContain("Review the changes and try again");+ expect(advanced().textContent).toContain("Your config changed since this preview.");+ expect(button("Review changes")).toBeDefined();+ expect(diff()).toBeNull();+ expect(complete).not.toHaveBeenCalled();+});++it("does not finish or claim success when the desktop could not reload", async () => {+ await render();+ await click("Review changes");+ bridge.applySnapShotConfig.mockResolvedValue({+ backupPath: "/config/backup",+ warning: "Config saved, but reload failed.",+ });+ await click("Save shortcut");+ expect(container.querySelector('[role="status"]')?.textContent).toBe(+ "Saved, but the shortcut needs attention. Check Advanced for help.",+ );+ expect(advanced().textContent).toContain("Config saved, but reload failed.");+ expect(complete).not.toHaveBeenCalled();+ expect(toast).not.toHaveBeenCalled();+});diff --git a/apps/web/src/components/settings/CaptureShortcutConfig.test.tsx b/apps/web/src/components/settings/CaptureShortcutConfig.test.tsxdeleted file mode 100644index a913885ca4d..00000000000--- a/apps/web/src/components/settings/CaptureShortcutConfig.test.tsx+++ /dev/null@@ -1,320 +0,0 @@-import {- DEFAULT_CLIENT_SETTINGS,- type DesktopCaptureConfigPreview,- type DesktopSnapShotState,-} from "@t3tools/contracts";-import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";-import { reactHookHarness as hooks } from "../../test/reactHookHarness";-import { visitElements } from "../../test/reactElementTree";--vi.mock("react", async (original) => {- const actual = await original<typeof import("react")>();- const { reactHookHarness } = await import("../../test/reactHookHarness");- return {- ...actual,- useCallback: reactHookHarness.useCallback,- useRef: reactHookHarness.useRef,- useEffect: () => undefined,- useMemo: reactHookHarness.useMemo,- useState: reactHookHarness.useState,- };-});-vi.mock("react/compiler-runtime", async () => {- const { reactHookHarness } = await import("../../test/reactHookHarness");- return { c: reactHookHarness.useMemoCache };-});-const bridge = vi.hoisted(() => ({- previewSnapShotConfig: vi.fn(),- applySnapShotConfig: vi.fn(),- setSnapShotShortcutSuppressed: vi.fn(),-}));-vi.mock("../../lib/desktopSnapShot", () => ({ getDesktopSnapShotBridge: () => bridge }));-vi.mock("../../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "light" }) }));-vi.mock("../../hooks/useCopyToClipboard", () => ({- useCopyToClipboard: () => ({ copyToClipboard: vi.fn(), isCopied: false }),-}));-vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn() } }));-import { CaptureShortcutConfig } from "./CaptureShortcutConfig";-import { toastManager } from "../ui/toast";--const preview: DesktopCaptureConfigPreview = {- id: "approved-snapshot",- path: "/config/niri/config.kdl",- resolvedPath: "/config/niri/config.kdl",- before: "binds {\n}\n",- after: 'binds {\n Ctrl+Shift+2 { spawn "gdbus"; }\n}\n',- shortcut: "Ctrl+Shift+2",- operation: "install",-};-const complete = vi.fn<() => Promise<void>>();-function render(desktop: "niri" | "hyprland" = "niri") {- const state: DesktopSnapShotState = {- mode: "portal",- linuxBackend: desktop,- shortcut: DEFAULT_CLIENT_SETTINGS.snapShotShortcut,- shortcutRegistered: false,- shortcutActionRegistered: true,- shortcutMessage: null,- message: null,- shortcutConfigPath: preview.path,- shortcutBinding: "manual binding",- };- hooks.beginRender();- return CaptureShortcutConfig({ state, onComplete: complete });-}-function button(tree: ReturnType<typeof render>, label: string) {- const node = visitElements(- tree,- (element) => element.props.children === label && typeof element.props.onClick === "function",- );- if (!node) throw new Error(`Missing button: ${label}`);- return node.props as { onClick: () => void; disabled: boolean };-}-function shortcutInput(tree: ReturnType<typeof render>) {- const node = visitElements(tree, (element) => "data-keybinding-capture" in element.props);- if (!node) throw new Error("Missing shortcut recorder");- return node.props as {- "aria-label": string;- onClick: () => void;- onKeyDown: (event: object) => void;- onBlur: () => void;- };-}-async function recordKeys(desktop: "niri" | "hyprland", modifiers: object = {}) {- shortcutInput(render(desktop)).onClick();- await finish(bridge.setSnapShotShortcutSuppressed.mock.results.at(-1)!.value);- shortcutInput(render(desktop)).onKeyDown({- key: "y",- code: "KeyY",- ctrlKey: true,- altKey: true,- shiftKey: false,- metaKey: false,- repeat: false,- preventDefault: vi.fn(),- stopPropagation: vi.fn(),- ...modifiers,- });-}-async function finish(promise: Promise<unknown>) {- await promise.catch(() => undefined);- await Promise.resolve();-}-beforeEach(() => {- hooks.reset();- vi.stubGlobal("navigator", { platform: "Linux" });- bridge.setSnapShotShortcutSuppressed.mockReset().mockResolvedValue(undefined);- bridge.previewSnapShotConfig.mockReset().mockResolvedValue(preview);- bridge.applySnapShotConfig- .mockReset()- .mockResolvedValue({ backupPath: "/config/backup", warning: null });- complete.mockReset().mockResolvedValue(undefined);- vi.mocked(toastManager.add).mockClear();-});-afterEach(() => vi.unstubAllGlobals());--it.each(["niri", "hyprland"] as const)(- "shows the fallback before review and requires separate read and write approval on %s",- async (desktop) => {- let tree = render(desktop);- expect(shortcutInput(tree)["aria-label"]).toBe(- "Record snapshot shortcut, currently Ctrl+Shift+2",- );- expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();- expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();- expect(visitElements(tree, (element) => element.type === "details")).not.toBeNull();- button(tree, "Review changes").onClick();- await finish(bridge.previewSnapShotConfig.mock.results[0]!.value);- tree = render(desktop);- expect(shortcutInput(tree)["aria-label"]).toBe(- "Record snapshot shortcut, currently Ctrl+Shift+2",- );- expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();- const diff = visitElements(tree, (element) => "fileDiff" in element.props);- expect(diff).not.toBeNull();- expect(diff?.props.fileDiff).toMatchObject({ name: preview.path });- button(tree, "Save shortcut").onClick();- await finish(bridge.applySnapShotConfig.mock.results[0]!.value);- expect(bridge.applySnapShotConfig).toHaveBeenCalledExactlyOnceWith(preview.id);- expect(complete).toHaveBeenCalledOnce();- expect(toastManager.add).toHaveBeenCalledWith(expect.objectContaining({ type: "success" }));- },-);-it.each(["niri", "hyprland"] as const)(- "lets users choose %s keys without opening Advanced, then approve the matching diff",- async (desktop) => {- const tree = render(desktop);- const advanced = visitElements(tree, (element) => element.type === "details");- expect(- visitElements(advanced, (element) => "data-keybinding-capture" in element.props),- ).toBeNull();- await recordKeys(desktop);- expect(bridge.setSnapShotShortcutSuppressed).toHaveBeenNthCalledWith(1, true);- expect(bridge.setSnapShotShortcutSuppressed).toHaveBeenLastCalledWith(false);- expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();- const custom = {- ...preview,- id: "custom-keys",- shortcut: "Ctrl+Alt+Y",- after: preview.after.replace("Ctrl+Shift+2", "Ctrl+Alt+Y"),- };- bridge.previewSnapShotConfig.mockResolvedValue(custom);- button(render(desktop), "Review changes").onClick();- await finish(bridge.previewSnapShotConfig.mock.results[0]!.value);- expect(bridge.previewSnapShotConfig).toHaveBeenCalledExactlyOnceWith({- operation: "install",- chooseFile: false,- shortcut: "ctrl+alt+y",- });- expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();- button(render(desktop), "Save shortcut").onClick();- await finish(bridge.applySnapShotConfig.mock.results[0]!.value);- expect(bridge.applySnapShotConfig).toHaveBeenCalledExactlyOnceWith(custom.id);- expect(toastManager.add).toHaveBeenCalledWith(- expect.objectContaining({ description: "Use Ctrl+Alt+Y from another app." }),- );- },-);-it("uses the existing config keys when no replacement was chosen", async () => {- bridge.previewSnapShotConfig.mockResolvedValue({ ...preview, shortcut: "Super+F8" });- button(render(), "Review changes").onClick();- await finish(bridge.previewSnapShotConfig.mock.results[0]!.value);- expect(bridge.previewSnapShotConfig).toHaveBeenCalledExactlyOnceWith({- operation: "install",- chooseFile: false,- });- expect(shortcutInput(render())["aria-label"]).toContain("F8");-});-it("requires a new diff after changing keys during review", async () => {- button(render(), "Review changes").onClick();- await finish(bridge.previewSnapShotConfig.mock.results[0]!.value);- await recordKeys("niri", { key: "F8", code: "F8", ctrlKey: false, altKey: false, metaKey: true });- expect(visitElements(render(), (element) => "fileDiff" in element.props)).toBeNull();- expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();- const replacement = { ...preview, id: "replacement", shortcut: "Super+F8" };- bridge.previewSnapShotConfig.mockResolvedValue(replacement);- button(render(), "Review changes").onClick();- await finish(bridge.previewSnapShotConfig.mock.results[1]!.value);- expect(bridge.previewSnapShotConfig).toHaveBeenLastCalledWith({- operation: "install",- chooseFile: false,- shortcut: "meta+f8",- });- button(render(), "Save shortcut").onClick();- await finish(bridge.applySnapShotConfig.mock.results[0]!.value);- expect(bridge.applySnapShotConfig).toHaveBeenCalledExactlyOnceWith(replacement.id);-});-it.each(["Escape", "blur"])(- "keeps the reviewed diff when recording is cancelled with %s",- async (cancel) => {- button(render(), "Review changes").onClick();- await finish(bridge.previewSnapShotConfig.mock.results[0]!.value);- shortcutInput(render()).onClick();- await finish(bridge.setSnapShotShortcutSuppressed.mock.results.at(-1)!.value);- expect(button(render(), "Save shortcut").disabled).toBe(true);- if (cancel === "Escape")- shortcutInput(render()).onKeyDown({- key: "Escape",- preventDefault: vi.fn(),- stopPropagation: vi.fn(),- });- else shortcutInput(render()).onBlur();- expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();- expect(button(render(), "Save shortcut").disabled).toBe(false);- expect(bridge.previewSnapShotConfig).toHaveBeenCalledOnce();- button(render(), "Save shortcut").onClick();- await finish(bridge.applySnapShotConfig.mock.results[0]!.value);- expect(bridge.applySnapShotConfig).toHaveBeenCalledExactlyOnceWith(preview.id);- },-);-it("cancelling a reviewed diff does not write or finish setup", async () => {- button(render(), "Review changes").onClick();- await finish(bridge.previewSnapShotConfig.mock.results[0]!.value);- button(render(), "Cancel").onClick();- expect(shortcutInput(render())["aria-label"]).toBe(- "Record snapshot shortcut, currently Ctrl+Shift+2",- );- expect(button(render(), "Review changes")).toBeDefined();- expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();- expect(complete).not.toHaveBeenCalled();-});-it("shows reading feedback until a proposal arrives", async () => {- let resolvePreview!: (value: DesktopCaptureConfigPreview) => void;- const pending = new Promise<DesktopCaptureConfigPreview>((resolve) => {- resolvePreview = resolve;- });- bridge.previewSnapShotConfig.mockReturnValue(pending);- button(render(), "Review changes").onClick();- expect(button(render(), "Preparing changes…").disabled).toBe(true);- expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();- resolvePreview(preview);- await finish(pending);- expect(button(render(), "Save shortcut").disabled).toBe(false);-});-it("keeps read failures actionable with technical details in Advanced, then permits retry", async () => {- bridge.previewSnapShotConfig.mockRejectedValueOnce(new Error("EACCES: /config/niri/config.kdl"));- button(render(), "Review changes").onClick();- await finish(bridge.previewSnapShotConfig.mock.results[0]!.value);- const failed = render();- expect(visitElements(failed, (element) => element.props.role === "alert")?.props.children).toBe(- "Couldn't prepare the changes. Check Advanced for help.",- );- const advanced = visitElements(failed, (element) => element.type === "details");- expect(- visitElements(- advanced,- (element) => element.props.children === "EACCES: /config/niri/config.kdl",- ),- ).not.toBeNull();- expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();- button(failed, "Review changes").onClick();- await finish(bridge.previewSnapShotConfig.mock.results[1]!.value);- expect(visitElements(render(), (element) => element.props.role === "alert")).toBeNull();- expect(button(render(), "Save shortcut").disabled).toBe(false);- expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();-});-it("withdraws a stale diff and requires another read instead of retrying its write", async () => {- button(render(), "Review changes").onClick();- await finish(bridge.previewSnapShotConfig.mock.results[0]!.value);- bridge.applySnapShotConfig.mockRejectedValue(- new Error("Your config changed since this preview."),- );- button(render(), "Save shortcut").onClick();- await finish(bridge.applySnapShotConfig.mock.results[0]!.value);- const tree = render();- expect(- visitElements(tree, (element) => element.props.role === "alert")?.props.children,- ).toContain("Review the changes and try again");- const advanced = visitElements(tree, (element) => element.type === "details");- expect(- visitElements(- advanced,- (element) => element.props.children === "Your config changed since this preview.",- ),- ).not.toBeNull();- expect(button(tree, "Review changes")).toBeDefined();- expect(visitElements(tree, (element) => "fileDiff" in element.props)).toBeNull();- expect(complete).not.toHaveBeenCalled();-});-it("does not finish or claim success when the desktop could not reload", async () => {- button(render(), "Review changes").onClick();- await finish(bridge.previewSnapShotConfig.mock.results[0]!.value);- bridge.applySnapShotConfig.mockResolvedValue({- backupPath: "/config/backup",- warning: "Config saved, but reload failed.",- });- button(render(), "Save shortcut").onClick();- await finish(bridge.applySnapShotConfig.mock.results[0]!.value);- expect(- visitElements(render(), (element) => element.props.role === "status")?.props.children,- ).toBe("Saved, but the shortcut needs attention. Check Advanced for help.");- const advanced = visitElements(render(), (element) => element.type === "details");- expect(- visitElements(- advanced,- (element) => element.props.children === "Config saved, but reload failed.",- ),- ).not.toBeNull();- expect(complete).not.toHaveBeenCalled();- expect(toastManager.add).not.toHaveBeenCalled();-});diff --git a/apps/web/src/components/settings/KeybindingsSettings.environment.browser.test.tsx b/apps/web/src/components/settings/KeybindingsSettings.environment.browser.test.tsxnew file mode 100644index 00000000000..2f438dfc439--- /dev/null+++ b/apps/web/src/components/settings/KeybindingsSettings.environment.browser.test.tsx@@ -0,0 +1,135 @@+import type { EnvironmentId } from "@t3tools/contracts";+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";++const state = vi.hoisted(() => ({+ canOperate: false,+ canWriteSettings: true,+ connected: true,+ openEditor: vi.fn(),+}));++vi.mock(import("@tanstack/react-router"), async (original) => ({+ ...(await original()),+ useLocation: (() => "") as never,+}));+vi.mock(import("./SettingsScopeContext"), async (original) => ({+ ...(await original()),+ useSettingsScope: () => {+ const environment = {+ environmentId: "primary-settings",+ serverConfig: {+ keybindings: [],+ keybindingsConfigPath: "/fixture/keybindings.json",+ availableEditors: [],+ },+ };+ return (+ state.connected+ ? { environment, connectedEnvironments: [environment] }+ : { environment: null, connectedEnvironments: [] }+ ) as never;+ },+}));+vi.mock(import("../../state/session"), async (original) => {+ const hasScope = (environmentId: EnvironmentId | null, scope: string) =>+ environmentId === "primary-settings" &&+ (scope === "orchestration:operate"+ ? state.canOperate+ : scope === "settings:write" && state.canWriteSettings);+ return {+ ...(await original()),+ useEnvironmentScope: hasScope as never,+ readEnvironmentScope: hasScope as never,+ useEnvironmentsWithScope: (() =>+ new Set(state.canWriteSettings ? ["primary-settings"] : [])) as never,+ };+});+vi.mock(import("../../editorPreferences"), async (original) => ({+ ...(await original()),+ useOpenInPreferredEditor: ((environmentId: EnvironmentId) => (path: string) =>+ state.openEditor({ environmentId, path })) as never,+}));++import { KeybindingsSettingsPanel } from "./KeybindingsSettings";++let root: Root;+let container: HTMLDivElement;++const render = () => act(async () => root.render(<KeybindingsSettingsPanel />));+const openButton = () => {+ const button = container.querySelector<HTMLButtonElement>(+ 'button[aria-label="Open keybindings.json"]',+ );+ expect(button).not.toBeNull();+ return button!;+};++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ state.canOperate = false;+ state.canWriteSettings = true;+ state.connected = true;+ state.openEditor.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});+afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+ vi.unstubAllGlobals();+});++describe("KeybindingsSettings editor permission", () => {+ it("rejects editor launches when settings writes are the only write grant", async () => {+ await render();+ expect(openButton().disabled).toBe(true);+ await act(async () => openButton().click());+ expect(state.openEditor).not.toHaveBeenCalled();+ });++ it("opens the primary environment's file after operate is granted without settings writes", async () => {+ state.canWriteSettings = false;+ await render();+ state.canOperate = true;+ await render();+ expect(openButton().disabled).toBe(false);+ await act(async () => openButton().click());++ expect(state.openEditor).toHaveBeenCalledWith({+ environmentId: "primary-settings",+ path: "/fixture/keybindings.json",+ });+ });++ it("rejects a queued editor launch after operate is revoked", async () => {+ state.canOperate = true;+ await render();+ const button = openButton();+ state.canOperate = false;+ // The rendered button is still enabled; the click must recheck the live grant.+ await act(async () => button.click());++ expect(state.openEditor).not.toHaveBeenCalled();+ await render();+ expect(openButton().disabled).toBe(true);+ });+});++describe("KeybindingsSettings write notice", () => {+ it("asks for a connected environment when none is connected", async () => {+ state.connected = false;+ await render();+ expect(container.textContent).toContain("Connect an environment to change keybindings.");+ });++ it("names the permission when the connection cannot write settings", async () => {+ state.canWriteSettings = false;+ await render();+ expect(container.textContent).toContain(+ "This connection can view keybindings but cannot change them.",+ );+ });+});diff --git a/apps/web/src/components/settings/KeybindingsSettings.environment.test.tsx b/apps/web/src/components/settings/KeybindingsSettings.environment.test.tsxdeleted file mode 100644index 8196b951252..00000000000--- a/apps/web/src/components/settings/KeybindingsSettings.environment.test.tsx+++ /dev/null@@ -1,172 +0,0 @@-import type { EnvironmentId } from "@t3tools/contracts";-import { beforeEach, describe, expect, it, vi } from "vite-plus/test";--import { visitElements } from "../../test/reactElementTree";-import { reactHookHarness as hooks } from "../../test/reactHookHarness";--const state = vi.hoisted(() => ({- canOperate: false,- canWriteSettings: true,- connected: true,- openEditor: vi.fn(),- upsert: vi.fn(),- remove: vi.fn(),-}));--vi.mock("react", async (importOriginal) => {- const actual = await importOriginal<typeof import("react")>();- const { reactHookHarness } = await import("../../test/reactHookHarness");- return {- ...actual,- useCallback: reactHookHarness.useCallback,- useEffect: () => undefined,- useMemo: reactHookHarness.useMemo,- useRef: reactHookHarness.useRef,- useState: reactHookHarness.useState,- };-});--vi.mock("react/compiler-runtime", async () => {- const { reactHookHarness } = await import("../../test/reactHookHarness");- return { c: reactHookHarness.useMemoCache };-});--vi.mock("@effect/atom-react", () => ({- useAtomValue: (atom: string) => (atom === "config-path" ? "/fixture/keybindings.json" : []),-}));--vi.mock("@tanstack/react-router", () => ({ useLocation: () => "" }));-vi.mock("../ProjectFavicon", () => ({ ProjectFavicon: () => null }));-vi.mock("../../state/server", () => ({- primaryServerKeybindingsAtom: "keybindings",- primaryServerKeybindingsConfigPathAtom: "config-path",- primaryServerAvailableEditorsAtom: "editors",- serverEnvironment: { upsertKeybinding: state.upsert, removeKeybinding: state.remove },-}));--vi.mock("../../state/environments", () => ({- usePrimaryEnvironment: () => ({ environmentId: "primary-settings" }),-}));--vi.mock("./SettingsScopeContext", () => ({- useSettingsScope: () => {- const environment = {- environmentId: "primary-settings",- serverConfig: {- keybindings: [],- keybindingsConfigPath: "/fixture/keybindings.json",- availableEditors: [],- },- };- return state.connected- ? { environment, connectedEnvironments: [environment] }- : { environment: null, connectedEnvironments: [] };- },-}));--vi.mock("../../state/session", () => {- const hasScope = (environmentId: EnvironmentId | null, scope: string) =>- environmentId === "primary-settings" &&- (scope === "orchestration:operate"- ? state.canOperate- : scope === "settings:write" && state.canWriteSettings);- return {- useEnvironmentScope: hasScope,- readEnvironmentScope: hasScope,- useEnvironmentsWithScope: () => new Set(state.canWriteSettings ? ["primary-settings"] : []),- };-});--vi.mock("../../state/use-atom-command", () => ({- useAtomCommand: (command: unknown) => command,-}));--vi.mock("../../editorPreferences", () => ({- useOpenInPreferredEditor: (environmentId: EnvironmentId) => (path: string) =>- state.openEditor({ environmentId, path }),-}));--import { KeybindingsSettingsPanel } from "./KeybindingsSettings";--function renderPanel() {- hooks.beginRender();- return KeybindingsSettingsPanel();-}--function openButton(panel: unknown) {- const button = visitElements(- panel,- (element) => element.props["aria-label"] === "Open keybindings.json",- );- if (!button) throw new Error("Missing Open keybindings.json action.");- return button;-}--describe("KeybindingsSettings editor permission", () => {- beforeEach(() => {- hooks.reset();- state.canOperate = false;- state.canWriteSettings = true;- state.connected = true;- state.openEditor.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });- state.upsert.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });- state.remove.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });- });-- it("rejects editor launches when settings writes are the only write grant", () => {- const button = openButton(renderPanel());- (button.props.onClick as () => void)();-- expect(state.openEditor).not.toHaveBeenCalled();- expect(button.props.disabled).toBe(true);- });-- it("opens the primary environment's file after operate is granted without settings writes", () => {- state.canWriteSettings = false;- renderPanel();- state.canOperate = true;- const button = openButton(renderPanel());- expect(button.props.disabled).toBe(false);- (button.props.onClick as () => void)();-- expect(state.openEditor).toHaveBeenCalledWith({- environmentId: "primary-settings",- path: "/fixture/keybindings.json",- });- });-- it("rejects a queued editor launch after operate is revoked", () => {- state.canOperate = true;- const open = openButton(renderPanel()).props.onClick as () => void;- state.canOperate = false;- open();-- expect(state.openEditor).not.toHaveBeenCalled();- expect(openButton(renderPanel()).props.disabled).toBe(true);- });-});--function noticeText(panel: unknown) {- const notice = visitElements(panel, (element) => element.type === "p");- return notice?.props.children;-}--describe("KeybindingsSettings write notice", () => {- beforeEach(() => {- hooks.reset();- state.canWriteSettings = true;- state.connected = true;- });-- it("asks for a connected environment when none is connected", () => {- state.connected = false;- expect(noticeText(renderPanel())).toBe("Connect an environment to change keybindings.");- });-- it("names the permission when the connection cannot write settings", () => {- state.canWriteSettings = false;- expect(noticeText(renderPanel())).toBe(- "This connection can view keybindings but cannot change them.",- );- });-});diff --git a/apps/web/src/components/settings/ProjectFaviconPickerDialog.browser.test.tsx b/apps/web/src/components/settings/ProjectFaviconPickerDialog.browser.test.tsxnew file mode 100644index 00000000000..010effe3076--- /dev/null+++ b/apps/web/src/components/settings/ProjectFaviconPickerDialog.browser.test.tsx@@ -0,0 +1,100 @@+import { EnvironmentId } from "@t3tools/contracts";+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";++const toast = vi.hoisted(() => vi.fn());+vi.mock(import("../files/projectFilesQueryState"), async (original) => ({+ ...(await original()),+ useProjectFilePickerQuery: () => ({+ entries: [],+ error: null,+ isPending: false,+ matchedQuery: "",+ }),+}));+vi.mock(import("../ui/toast"), async (original) => {+ const actual = await original();+ return { ...actual, toastManager: { ...actual.toastManager, add: toast } };+});++import {+ canPickExternalProjectFavicon,+ ProjectFaviconPickerDialog,+} from "./ProjectFaviconPickerDialog";++let root: Root;+let container: HTMLDivElement;++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ Object.defineProperty(navigator, "platform", { configurable: true, get: () => "MacIntel" });+ toast.mockClear();+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});+afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+ Reflect.deleteProperty(navigator, "platform");+ vi.unstubAllGlobals();+});++async function renderPicker(onPickExternal: () => Promise<string | null>) {+ const onOpenChange = vi.fn();+ const onSelect = vi.fn();+ await act(async () =>+ root.render(+ <ProjectFaviconPickerDialog+ cwd="/Users/me/project"+ environmentId={EnvironmentId.make("local")}+ onOpenChange={onOpenChange}+ onPickExternal={onPickExternal}+ onSelect={onSelect}+ open+ projectName="Project"+ />,+ ),+ );+ return { onOpenChange, onSelect };+}+async function clickOpenInFinder() {+ const button = [...document.querySelectorAll("button")].find((element) =>+ element.textContent?.includes("Open in Finder"),+ );+ expect(button, "Open in Finder").toBeDefined();+ await act(async () => button!.click());+}++it("selects an image from the native file picker", async () => {+ const onPickExternal = vi.fn().mockResolvedValue("/Users/me/Pictures/icon.png");+ const { onOpenChange, onSelect } = await renderPicker(onPickExternal);++ await clickOpenInFinder();++ expect(onPickExternal).toHaveBeenCalledTimes(1);+ expect(onOpenChange).toHaveBeenCalledWith(false);+ expect(onSelect).toHaveBeenCalledWith("/Users/me/Pictures/icon.png");+});++it("hides the native picker for WSL project paths", () => {+ expect(canPickExternalProjectFavicon("/home/me/project", "Win32")).toBe(false);+ expect(canPickExternalProjectFavicon("C:\\Users\\me\\project", "Win32")).toBe(true);+});++it("keeps the dialog open when the native picker fails", async () => {+ const { onOpenChange, onSelect } = await renderPicker(+ vi.fn().mockRejectedValue(new Error("picker failed")),+ );++ await clickOpenInFinder();++ expect(onOpenChange).not.toHaveBeenCalled();+ expect(onSelect).not.toHaveBeenCalled();+ expect(toast).toHaveBeenCalledWith({+ type: "error",+ title: "Could not open image picker",+ description: "picker failed",+ });+});diff --git a/apps/web/src/components/settings/ProjectFaviconPickerDialog.test.tsx b/apps/web/src/components/settings/ProjectFaviconPickerDialog.test.tsxdeleted file mode 100644index 1cb090d9dc5..00000000000--- a/apps/web/src/components/settings/ProjectFaviconPickerDialog.test.tsx+++ /dev/null@@ -1,125 +0,0 @@-import { EnvironmentId } from "@t3tools/contracts";-import type { ReactElement } from "react";-import { beforeEach, describe, expect, it, vi } from "vite-plus/test";--import { visitElements } from "../../test/reactElementTree";-import { reactHookHarness as hooks } from "../../test/reactHookHarness";--vi.mock("react", async (importOriginal) => {- const actual = await importOriginal<typeof import("react")>();- const { reactHookHarness } = await import("../../test/reactHookHarness");- return {- ...actual,- useMemo: reactHookHarness.useMemo,- useState: reactHookHarness.useState,- };-});--vi.mock("react/compiler-runtime", async () => {- const { reactHookHarness } = await import("../../test/reactHookHarness");- return { c: reactHookHarness.useMemoCache };-});--vi.mock("@effect/atom-react", () => ({- useAtomValue: () => ({}),-}));--vi.mock("~/state/server", () => ({- primaryServerKeybindingsAtom: Symbol("keybindings"),-}));--vi.mock("~/hooks/useTheme", () => ({- useTheme: () => ({ resolvedTheme: "dark" }),-}));--vi.mock("../files/projectFilesQueryState", () => ({- useProjectFilePickerQuery: () => ({- entries: [],- error: null,- isPending: false,- matchedQuery: "",- }),-}));--vi.mock("../ui/toast", () => ({- toastManager: { add: vi.fn() },-}));--import { toastManager } from "../ui/toast";-import {- canPickExternalProjectFavicon,- ProjectFaviconPickerDialog,-} from "./ProjectFaviconPickerDialog";--describe("ProjectFaviconPickerDialog", () => {- beforeEach(() => {- hooks.reset();- vi.stubGlobal("navigator", { platform: "MacIntel" });- });-- it("selects an image from the native file picker", async () => {- const onOpenChange = vi.fn();- const onPickExternal = vi.fn().mockResolvedValue("/Users/me/Pictures/icon.png");- const onSelect = vi.fn();- hooks.beginRender();- const picker = ProjectFaviconPickerDialog({- cwd: "/Users/me/project",- environmentId: EnvironmentId.make("local"),- onOpenChange,- onPickExternal,- onSelect,- open: true,- projectName: "Project",- } as Parameters<typeof ProjectFaviconPickerDialog>[0] & {- readonly onPickExternal: () => Promise<string | null>;- }) as ReactElement<Record<string, unknown>>;-- const button = visitElements(picker, (element) => element.props.children === "Open in Finder");- expect(button).not.toBeNull();-- (button?.props.onClick as (() => void) | undefined)?.();- await Promise.resolve();- await Promise.resolve();-- expect(onPickExternal).toHaveBeenCalledTimes(1);- expect(onOpenChange).toHaveBeenCalledWith(false);- expect(onSelect).toHaveBeenCalledWith("/Users/me/Pictures/icon.png");- });-- it("hides the native picker for WSL project paths", () => {- expect(canPickExternalProjectFavicon("/home/me/project", "Win32")).toBe(false);- expect(canPickExternalProjectFavicon("C:\\Users\\me\\project", "Win32")).toBe(true);- });-- it("keeps the dialog open when the native picker fails", async () => {- const onOpenChange = vi.fn();- const onSelect = vi.fn();- const props = {- cwd: "/Users/me/project",- environmentId: EnvironmentId.make("local"),- onOpenChange,- onPickExternal: vi.fn().mockRejectedValue(new Error("picker failed")),- onSelect,- open: true,- projectName: "Project",- } as Parameters<typeof ProjectFaviconPickerDialog>[0] & {- readonly onPickExternal: () => Promise<string | null>;- };-- hooks.beginRender();- const picker = ProjectFaviconPickerDialog(props) as ReactElement<Record<string, unknown>>;- const button = visitElements(picker, (element) => element.props.children === "Open in Finder");-- (button?.props.onClick as (() => void) | undefined)?.();- await Promise.resolve();- await Promise.resolve();-- expect(onOpenChange).not.toHaveBeenCalled();- expect(onSelect).not.toHaveBeenCalled();- expect(toastManager.add).toHaveBeenCalledWith({- type: "error",- title: "Could not open image picker",- description: "picker failed",- });- });-});diff --git a/apps/web/src/components/settings/ProviderSetupSection.browser.test.tsx b/apps/web/src/components/settings/ProviderSetupSection.browser.test.tsxnew file mode 100644index 00000000000..d65046fd2b9--- /dev/null+++ b/apps/web/src/components/settings/ProviderSetupSection.browser.test.tsx@@ -0,0 +1,380 @@+import {+ EnvironmentId,+ ProviderDriverKind,+ ProviderInstanceId,+ type ProviderAuthState,+ type ProviderInstallState,+ type ServerProvider,+} from "@t3tools/contracts";+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { userEvent } from "vite-plus/test/browser";+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";++const setup = vi.hoisted(() => ({+ auth: null as ProviderAuthState | null,+ installation: null as ProviderInstallState | null,+ authState: vi.fn(() => "auth"),+ installState: vi.fn(() => "installation"),+ startAuth: vi.fn(),+ completeAuth: vi.fn(),+ respondAuth: vi.fn(),+ cancelAuth: vi.fn(),+ logoutAuth: vi.fn(),+ startInstall: vi.fn(),+ cancelInstall: vi.fn(),+ removeInstall: vi.fn(),+ confirm: vi.fn(),+}));++vi.mock(import("../../state/server"), async (original) => {+ const actual = await original();+ return {+ ...actual,+ serverEnvironment: {+ ...actual.serverEnvironment,+ providerAuthState: setup.authState as never,+ providerInstallState: setup.installState as never,+ startProviderAuth: setup.startAuth as never,+ completeProviderAuth: setup.completeAuth as never,+ respondProviderAuth: setup.respondAuth as never,+ cancelProviderAuth: setup.cancelAuth as never,+ logoutProviderAuth: setup.logoutAuth as never,+ startProviderInstall: setup.startInstall as never,+ cancelProviderInstall: setup.cancelInstall as never,+ removeProviderInstallation: setup.removeInstall as never,+ },+ };+});+vi.mock(import("../../state/use-atom-command"), async (original) => ({+ ...(await original()),+ useAtomCommand: ((command: unknown) => command) as never,+}));+// The queries behave like live subscriptions: changing `setup.auth` and calling+// `publish()` re-renders the sections that read them.+const queryListeners = vi.hoisted(() => new Set<() => void>());+vi.mock(import("../../state/query"), async (original) => {+ const { useSyncExternalStore } = await import("react");+ const subscribe = (listener: () => void) => {+ queryListeners.add(listener);+ return () => queryListeners.delete(listener);+ };+ return {+ ...(await original()),+ useEnvironmentQuery: ((atom: string) => ({+ data: useSyncExternalStore(subscribe, () =>+ atom === "auth" ? setup.auth : setup.installation,+ ),+ error: null,+ isPending: false,+ refresh: vi.fn(),+ })) as never,+ };+});+const publish = () =>+ act(async () => {+ for (const listener of queryListeners) listener();+ });+vi.mock(import("../../localApi"), async (original) => ({+ ...(await original()),+ ensureLocalApi: () => ({ dialogs: { confirm: setup.confirm } }) as never,+}));++import { ProviderSetupSection } from "./ProviderSetupSection";++const environmentId = EnvironmentId.make("remote-google");+const instanceId = ProviderInstanceId.make("antigravity_work");+const provider: ServerProvider = {+ instanceId,+ driver: ProviderDriverKind.make("antigravity"),+ installed: true,+ enabled: true,+ version: "test-version",+ status: "error",+ auth: { status: "unauthenticated" },+ checkedAt: "2026-09-02T00:00:00.000Z",+ models: [],+ skills: [],+ slashCommands: [],+ setup: { canAuthenticate: true, canInstall: true },+};++function authState(patch: Partial<ProviderAuthState> = {}): ProviderAuthState {+ return {+ instanceId,+ phase: "waiting",+ flowId: "flow-1",+ authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth?state=test-only",+ expiresAt: "2026-09-02T00:05:00.000Z",+ message: null,+ ...patch,+ };+}++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => {+ resolve = done;+ });+ return { promise, resolve };+}++let root: Root;+let container: HTMLDivElement;++function renderSetup(+ options: {+ readOnly?: boolean;+ provider?: ServerProvider;+ enabled?: boolean;+ binaryPath?: string;+ } = {},+) {+ return act(async () =>+ root.render(+ <ProviderSetupSection+ environmentId={environmentId}+ environmentLabel="Remote Google device"+ instanceId={instanceId}+ provider={options.provider ?? provider}+ binaryPath={options.binaryPath}+ enabled={options.enabled ?? true}+ readOnly={options.readOnly ?? false}+ onEnable={vi.fn()}+ />,+ ),+ );+}++function button(label: string) {+ return (+ [...container.querySelectorAll("button")].find(+ (element) => element.textContent === label || element.getAttribute("aria-label") === label,+ ) ?? null+ );+}+async function click(label: string) {+ const target = button(label);+ expect(target, `button ${label}`).not.toBeNull();+ expect(target!.disabled, `${label} disabled`).toBe(false);+ await act(async () => target!.click());+}+function occurrences(text: string) {+ return (container.textContent ?? "").split(text).length - 1;+}+const callbackInput = () =>+ container.querySelector<HTMLInputElement>(`[id="provider-callback-${instanceId}"]`)!;++describe("Antigravity setup", () => {+ beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ vi.clearAllMocks();+ setup.auth = authState();+ setup.installation = {+ driver: ProviderDriverKind.make("antigravity"),+ operationId: null,+ phase: "idle",+ downloadedBytes: 0,+ totalBytes: null,+ version: null,+ installedVersion: null,+ canRemove: false,+ message: null,+ };+ for (const command of [+ setup.startAuth,+ setup.completeAuth,+ setup.cancelAuth,+ setup.logoutAuth,+ setup.startInstall,+ setup.cancelInstall,+ setup.removeInstall,+ ]) {+ command.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });+ }+ setup.confirm.mockReset().mockResolvedValue(false);+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ });++ afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+ vi.unstubAllGlobals();+ });++ it("waits for verified auth after submitting a callback to the selected environment", async () => {+ const callbackUrl = "http://127.0.0.1:5555/?state=test-only&code=test-only";+ await renderSetup();+ await act(async () => userEvent.fill(callbackInput(), callbackUrl));+ await click("Continue");++ expect(setup.completeAuth).toHaveBeenCalledWith({+ environmentId,+ input: { instanceId, flowId: "flow-1", callbackUrl },+ });+ expect(occurrences("Signed in.")).toBe(0);+ expect(callbackInput().value).toBe("");++ setup.auth = authState({ phase: "verifying", authorizationUrl: null });+ await publish();+ expect(occurrences("Signed in.")).toBe(0);+ setup.auth = authState({ phase: "succeeded", authorizationUrl: null });+ await renderSetup({+ provider: { ...provider, status: "ready", auth: { status: "authenticated" } },+ });+ expect(occurrences("Signed in.")).toBe(1);+ });++ it("offers sign-in again when credentials expire after a completed auth flow", async () => {+ setup.auth = authState({+ phase: "succeeded",+ authorizationUrl: null,+ message: "Google sign-in complete.",+ });+ await renderSetup({+ provider: { ...provider, status: "ready", auth: { status: "authenticated" } },+ });+ await renderSetup();+ expect(button("Sign in")).not.toBeNull();+ expect(occurrences("Signed in.")).toBe(0);+ expect(occurrences("Google sign-in complete.")).toBe(0);+ });++ it("does not send a callback left over from a replaced sign-in flow", async () => {+ const interaction = {+ type: "browser" as const,+ id: "same-interaction",+ url: "https://example.com/login",+ requiresConsent: false,+ acceptsCallback: true,+ };+ setup.auth = authState({ interaction });+ await renderSetup();+ await act(async () =>+ userEvent.fill(callbackInput(), "http://127.0.0.1:5555/?state=old-flow&code=test-only"),+ );+ setup.auth = authState({ flowId: "flow-2", interaction });+ await publish();+ expect(callbackInput().value).toBe("");+ await act(async () => callbackInput().form!.requestSubmit());++ expect(setup.completeAuth).not.toHaveBeenCalled();+ expect(setup.authState).toHaveBeenLastCalledWith({ environmentId, input: { instanceId } });+ });++ it("coalesces repeated sign-in clicks while start is pending", async () => {+ setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });+ const pending = deferred<{ _tag: "Success"; value: undefined }>();+ setup.startAuth.mockReturnValueOnce(pending.promise);+ await renderSetup();+ const signIn = button("Sign in")!;+ // Both clicks land before React re-renders the button as disabled.+ await act(async () => {+ signIn.click();+ signIn.click();+ });++ expect(setup.startAuth).toHaveBeenCalledTimes(1);+ expect(setup.startAuth).toHaveBeenCalledWith({ environmentId, input: { instanceId } });+ await act(async () => pending.resolve({ _tag: "Success", value: undefined }));+ });++ it("shows a repeated runtime status message only once", async () => {+ setup.installation = {+ ...setup.installation!,+ operationId: "install-1",+ phase: "verifying",+ message: "Checking the downloaded runtime.",+ };++ await renderSetup();+ expect(occurrences("Checking the downloaded runtime.")).toBe(1);+ });++ it("removes an owned damaged runtime only after confirmation", async () => {+ setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });+ setup.installation = {+ ...setup.installation!,+ phase: "failed",+ canRemove: true,+ installedVersion: null,+ };+ await renderSetup();+ await click("Remove downloaded runtime");+ expect(setup.confirm).toHaveBeenCalledOnce();+ expect(setup.removeInstall).not.toHaveBeenCalled();++ setup.confirm.mockResolvedValue(true);+ await click("Remove downloaded runtime");+ expect(setup.removeInstall).toHaveBeenCalledWith({ environmentId, input: { instanceId } });+ });++ it.each([true, false])(+ "can sign out a verified account when its instance is enabled=%s",+ async (enabled) => {+ setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });+ setup.confirm.mockResolvedValue(true);+ await renderSetup({+ enabled,+ provider: {+ ...provider,+ enabled,+ installed: false,+ status: enabled ? "warning" : "disabled",+ auth: { status: "authenticated" },+ },+ });+ await click("Sign out");+ expect(setup.logoutAuth).toHaveBeenCalledWith({ environmentId, input: { instanceId } });+ },+ );++ it.each(["unauthenticated", "unknown"] as const)(+ "does not offer sign-out for an unverified %s account",+ async (status) => {+ setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });+ await renderSetup({+ provider: { ...provider, auth: { status, canLogout: true } },+ });+ expect(button("Sign in")).not.toBeNull();+ expect(button("Sign out")).toBeNull();+ expect(button("Change account")).toBeNull();+ },+ );++ it("offers account actions after verified login when discovery cannot identify auth", async () => {+ setup.auth = authState({ phase: "succeeded", flowId: null, authorizationUrl: null });+ await renderSetup({ provider: { ...provider, auth: { status: "unknown" } } });+ expect(button("Change account")).not.toBeNull();+ expect(button("Sign out")).not.toBeNull();+ expect(button("Sign in")).toBeNull();+ });++ it("does not let a shared managed install hide an invalid custom binary path", async () => {+ setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });+ setup.installation = {+ ...setup.installation!,+ installedVersion: "test-version",+ canRemove: true,+ };+ await renderSetup({+ provider: { ...provider, installed: false },+ binaryPath: "/missing/antigravity",+ });+ expect(button("Sign in")?.disabled).toBe(true);+ expect(setup.startAuth).not.toHaveBeenCalled();+ });++ it.each(["read-only", "older-server"] as const)(+ "does not open private setup subscriptions for a %s view",+ async (mode) => {+ const { setup: _setup, ...olderProvider } = provider;+ await renderSetup(mode === "read-only" ? { readOnly: true } : { provider: olderProvider });+ expect(setup.authState).not.toHaveBeenCalled();+ expect(setup.installState).not.toHaveBeenCalled();+ expect(setup.startAuth).not.toHaveBeenCalled();+ },+ );+});diff --git a/apps/web/src/components/settings/ProviderSetupSection.test.tsx b/apps/web/src/components/settings/ProviderSetupSection.test.tsxdeleted file mode 100644index 214546c48f7..00000000000--- a/apps/web/src/components/settings/ProviderSetupSection.test.tsx+++ /dev/null@@ -1,426 +0,0 @@-import { cloneElement, isValidElement, type FunctionComponent, type ReactElement } from "react";-import {- EnvironmentId,- ProviderDriverKind,- ProviderInstanceId,- type ProviderAuthState,- type ProviderInstallState,- type ServerProvider,-} from "@t3tools/contracts";-import { beforeEach, describe, expect, it, vi } from "vite-plus/test";--import { visitElements } from "../../test/reactElementTree";-import { reactHookHarness as hooks } from "../../test/reactHookHarness";--const setup = vi.hoisted(() => ({- auth: null as ProviderAuthState | null,- installation: null as ProviderInstallState | null,- authState: vi.fn(() => "auth"),- installState: vi.fn(() => "installation"),- startAuth: vi.fn(),- completeAuth: vi.fn(),- respondAuth: vi.fn(),- cancelAuth: vi.fn(),- logoutAuth: vi.fn(),- startInstall: vi.fn(),- cancelInstall: vi.fn(),- removeInstall: vi.fn(),- confirm: vi.fn(),-}));--vi.mock("react", async (importOriginal) => {- const actual = await importOriginal<typeof import("react")>();- const { reactHookHarness } = await import("../../test/reactHookHarness");- return {- ...actual,- useRef: reactHookHarness.useRef,- useState: reactHookHarness.useState,- };-});--vi.mock("react/compiler-runtime", async () => {- const { reactHookHarness } = await import("../../test/reactHookHarness");- return { c: reactHookHarness.useMemoCache };-});--vi.mock("../../state/server", () => ({- serverEnvironment: {- providerAuthState: setup.authState,- providerInstallState: setup.installState,- startProviderAuth: setup.startAuth,- completeProviderAuth: setup.completeAuth,- respondProviderAuth: setup.respondAuth,- cancelProviderAuth: setup.cancelAuth,- logoutProviderAuth: setup.logoutAuth,- startProviderInstall: setup.startInstall,- cancelProviderInstall: setup.cancelInstall,- removeProviderInstallation: setup.removeInstall,- },-}));--vi.mock("../../state/use-atom-command", () => ({- useAtomCommand: (command: unknown) => command,-}));--vi.mock("../../state/query", () => ({- useEnvironmentQuery: (atom: string) => ({- data: atom === "auth" ? setup.auth : setup.installation,- error: null,- isPending: false,- refresh: vi.fn(),- }),-}));--vi.mock("../../localApi", () => ({- ensureLocalApi: () => ({ dialogs: { confirm: setup.confirm } }),-}));--import { ProviderAuthenticationSection } from "./ProviderAuthenticationSection";-import { ProviderSetupSection } from "./ProviderSetupSection";--const environmentId = EnvironmentId.make("remote-google");-const instanceId = ProviderInstanceId.make("antigravity_work");-const provider: ServerProvider = {- instanceId,- driver: ProviderDriverKind.make("antigravity"),- installed: true,- enabled: true,- version: "test-version",- status: "error",- auth: { status: "unauthenticated" },- checkedAt: "2026-09-02T00:00:00.000Z",- models: [],- skills: [],- slashCommands: [],- setup: { canAuthenticate: true, canInstall: true },-};--function authState(patch: Partial<ProviderAuthState> = {}): ProviderAuthState {- return {- instanceId,- phase: "waiting",- flowId: "flow-1",- authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth?state=test-only",- expiresAt: "2026-09-02T00:05:00.000Z",- message: null,- ...patch,- };-}--function renderSetup(- options: {- readOnly?: boolean;- provider?: ServerProvider;- enabled?: boolean;- binaryPath?: string;- } = {},-) {- hooks.beginRender();- const view = ProviderSetupSection({- environmentId,- environmentLabel: "Remote Google device",- instanceId,- provider: options.provider ?? provider,- binaryPath: options.binaryPath,- enabled: options.enabled ?? true,- readOnly: options.readOnly ?? false,- onEnable: vi.fn(),- });- const actions = visitElements(- view,- (element) =>- typeof element.type === "function" &&- element.props.environmentId === environmentId &&- element.props.instanceId === instanceId,- );- if (!actions) return view;- const Actions = actions.type as FunctionComponent<Record<string, unknown>>;- function expand(node: unknown): unknown {- if (Array.isArray(node)) return node.map(expand);- if (!isValidElement<Record<string, unknown>>(node)) return node;- if (node.type === ProviderAuthenticationSection)- return ProviderAuthenticationSection(- node.props as Parameters<typeof ProviderAuthenticationSection>[0],- );- return cloneElement(- node,- Object.fromEntries(Object.entries(node.props).map(([key, value]) => [key, expand(value)])),- );- }- return expand(Actions(actions.props));-}--function button(view: unknown, label: string) {- return visitElements(- view,- (element) =>- (element.props.children === label || element.props["aria-label"] === label) &&- typeof element.props.onClick === "function",- );-}--function countElements(- node: unknown,- predicate: (element: ReactElement<Record<string, unknown>>) => boolean,-): number {- if (Array.isArray(node)) {- return node.reduce((total, child) => total + countElements(child, predicate), 0);- }- if (!isValidElement<Record<string, unknown>>(node)) return 0;- return (- Number(predicate(node)) +- Object.values(node.props).reduce<number>(- (total, value) => total + countElements(value, predicate),- 0,- )- );-}--function click(view: unknown, label: string) {- const target = button(view, label);- if (!target) throw new Error(`Missing button: ${label}`);- if (target.props.disabled) throw new Error(`Button is disabled: ${label}`);- (target.props.onClick as () => void)();-}--function setCallback(view: unknown, value: string) {- const input = visitElements(- view,- (element) => element.props.id === `provider-callback-${instanceId}`,- );- if (!input) throw new Error("Missing callback input.");- (input.props.onChange as (event: { target: { value: string } }) => void)({ target: { value } });-}--function submitCallback(view: unknown) {- const form = visitElements(view, (element) => element.type === "form");- if (!form) throw new Error("Missing callback form.");- (form.props.onSubmit as (event: { preventDefault: () => void }) => void)({- preventDefault: vi.fn(),- });-}--async function flushPromises() {- await Promise.resolve();- await Promise.resolve();- await Promise.resolve();-}--describe("Antigravity setup", () => {- beforeEach(() => {- hooks.reset();- vi.clearAllMocks();- setup.auth = authState();- setup.installation = {- driver: ProviderDriverKind.make("antigravity"),- operationId: null,- phase: "idle",- downloadedBytes: 0,- totalBytes: null,- version: null,- installedVersion: null,- canRemove: false,- message: null,- };- for (const command of [- setup.startAuth,- setup.completeAuth,- setup.cancelAuth,- setup.logoutAuth,- setup.startInstall,- setup.cancelInstall,- setup.removeInstall,- ]) {- command.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });- }- setup.confirm.mockReset().mockResolvedValue(false);- });-- it("waits for verified auth after submitting a callback to the selected environment", async () => {- const callbackUrl = "http://127.0.0.1:5555/?state=test-only&code=test-only";- setCallback(renderSetup(), callbackUrl);- submitCallback(renderSetup());- await flushPromises();-- expect(setup.completeAuth).toHaveBeenCalledWith({- environmentId,- input: { instanceId, flowId: "flow-1", callbackUrl },- });- let view = renderSetup();- expect(visitElements(view, (element) => element.props.children === "Signed in.")).toBeNull();- expect(- visitElements(view, (element) => element.props.id === `provider-callback-${instanceId}`)- ?.props.value,- ).toBe("");-- setup.auth = authState({ phase: "verifying", authorizationUrl: null });- expect(- visitElements(renderSetup(), (element) => element.props.children === "Signed in."),- ).toBeNull();- setup.auth = authState({ phase: "succeeded", authorizationUrl: null });- view = renderSetup({- provider: { ...provider, status: "ready", auth: { status: "authenticated" } },- });- expect(- visitElements(view, (element) => element.props.children === "Signed in."),- ).not.toBeNull();- });-- it("offers sign-in again when credentials expire after a completed auth flow", () => {- setup.auth = authState({- phase: "succeeded",- authorizationUrl: null,- message: "Google sign-in complete.",- });- renderSetup({- provider: { ...provider, status: "ready", auth: { status: "authenticated" } },- });- const expired = renderSetup();- expect(button(expired, "Sign in")).not.toBeNull();- expect(visitElements(expired, (element) => element.props.children === "Signed in.")).toBeNull();- expect(- visitElements(expired, (element) => element.props.children === "Google sign-in complete."),- ).toBeNull();- });-- it("does not send a callback left over from a replaced sign-in flow", async () => {- const interaction = {- type: "browser" as const,- id: "same-interaction",- url: "https://example.com/login",- requiresConsent: false,- acceptsCallback: true,- };- setup.auth = authState({ interaction });- setCallback(renderSetup(), "http://127.0.0.1:5555/?state=old-flow&code=test-only");- setup.auth = authState({ flowId: "flow-2", interaction });- submitCallback(renderSetup());- await flushPromises();-- expect(setup.completeAuth).not.toHaveBeenCalled();- expect(setup.authState).toHaveBeenLastCalledWith({ environmentId, input: { instanceId } });- });-- it("coalesces repeated sign-in clicks while start is pending", async () => {- setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });- let completeStart: (value: { _tag: "Success"; value: undefined }) => void = () => {- throw new Error("Missing start resolver.");- };- const pending = new Promise<{ _tag: "Success"; value: undefined }>((resolve) => {- completeStart = resolve;- });- setup.startAuth.mockReturnValueOnce(pending);- const view = renderSetup();- click(view, "Sign in");- click(view, "Sign in");-- expect(setup.startAuth).toHaveBeenCalledTimes(1);- expect(setup.startAuth).toHaveBeenCalledWith({ environmentId, input: { instanceId } });- completeStart({ _tag: "Success", value: undefined });- await flushPromises();- });-- it("shows a repeated runtime status message only once", () => {- setup.installation = {- ...setup.installation!,- operationId: "install-1",- phase: "verifying",- message: "Checking the downloaded runtime.",- };-- const view = renderSetup();- expect(- countElements(- view,- (element) => element.props.children === "Checking the downloaded runtime.",- ),- ).toBe(1);- });-- it("removes an owned damaged runtime only after confirmation", async () => {- setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });- setup.installation = {- ...setup.installation!,- phase: "failed",- canRemove: true,- installedVersion: null,- };- const view = renderSetup();- click(view, "Remove downloaded runtime");- await flushPromises();- expect(setup.removeInstall).not.toHaveBeenCalled();-- setup.confirm.mockResolvedValue(true);- click(view, "Remove downloaded runtime");- await flushPromises();- expect(setup.removeInstall).toHaveBeenCalledWith({ environmentId, input: { instanceId } });- });-- it.each([true, false])(- "can sign out a verified account when its instance is enabled=%s",- async (enabled) => {- setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });- setup.confirm.mockResolvedValue(true);- const view = renderSetup({- enabled,- provider: {- ...provider,- enabled,- installed: false,- status: enabled ? "warning" : "disabled",- auth: { status: "authenticated" },- },- });- click(view, "Sign out");- await flushPromises();- expect(setup.logoutAuth).toHaveBeenCalledWith({ environmentId, input: { instanceId } });- },- );-- it.each(["unauthenticated", "unknown"] as const)(- "does not offer sign-out for an unverified %s account",- (status) => {- setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });- const view = renderSetup({- provider: { ...provider, auth: { status, canLogout: true } },- });- expect(button(view, "Sign in")).not.toBeNull();- expect(button(view, "Sign out")).toBeNull();- expect(button(view, "Change account")).toBeNull();- },- );-- it("offers account actions after verified login when discovery cannot identify auth", () => {- setup.auth = authState({ phase: "succeeded", flowId: null, authorizationUrl: null });- const view = renderSetup({ provider: { ...provider, auth: { status: "unknown" } } });- expect(button(view, "Change account")).not.toBeNull();- expect(button(view, "Sign out")).not.toBeNull();- expect(button(view, "Sign in")).toBeNull();- });-- it("does not let a shared managed install hide an invalid custom binary path", () => {- setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });- setup.installation = {- ...setup.installation!,- installedVersion: "test-version",- canRemove: true,- };- const view = renderSetup({- provider: { ...provider, installed: false },- binaryPath: "/missing/antigravity",- });- expect(button(view, "Sign in")?.props.disabled).toBe(true);- expect(setup.startAuth).not.toHaveBeenCalled();- });-- it.each(["read-only", "older-server"] as const)(- "does not open private setup subscriptions for a %s view",- (mode) => {- const { setup: _setup, ...olderProvider } = provider;- renderSetup(mode === "read-only" ? { readOnly: true } : { provider: olderProvider });- expect(setup.authState).not.toHaveBeenCalled();- expect(setup.installState).not.toHaveBeenCalled();- expect(setup.startAuth).not.toHaveBeenCalled();- },- );-});diff --git a/apps/web/src/components/settings/SettingsPanels.restore.test.tsx b/apps/web/src/components/settings/SettingsPanels.restore.browser.test.tsxsimilarity index 50%rename from apps/web/src/components/settings/SettingsPanels.restore.test.tsxrename to apps/web/src/components/settings/SettingsPanels.restore.browser.test.tsxindex 88c9cb1776e..594a623c438 100644--- a/apps/web/src/components/settings/SettingsPanels.restore.test.tsx+++ b/apps/web/src/components/settings/SettingsPanels.restore.browser.test.tsx@@ -1,7 +1,7 @@import { DEFAULT_UNIFIED_SETTINGS, type UnifiedSettings } from "@t3tools/contracts";-import { beforeEach, describe, expect, it, vi } from "vite-plus/test";--import { reactHookHarness as hooks } from "../../test/reactHookHarness";+import { act, useEffect } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";const state = vi.hoisted(() => ({settings: null as UnifiedSettings | null,@@ -9,57 +9,59 @@ const state = vi.hoisted(() => ({confirm: vi.fn(),}));-vi.mock("react", async (importOriginal) => {- const actual = await importOriginal<typeof import("react")>();- const { reactHookHarness } = await import("../../test/reactHookHarness");- return {- ...actual,- useCallback: reactHookHarness.useCallback,- useMemo: reactHookHarness.useMemo,- };-});--vi.mock("react/compiler-runtime", async () => {- const { reactHookHarness } = await import("../../test/reactHookHarness");- return { c: reactHookHarness.useMemoCache };-});--vi.mock("../../hooks/useTheme", async (importOriginal) => ({- ...(await importOriginal<typeof import("../../hooks/useTheme")>()),- useTheme: () => ({- theme: "system",- followSystem: true,- themeHalves: null,- setTheme: vi.fn(),- setFollowSystem: vi.fn(),- setThemeHalf: vi.fn(),- clearThemeHalves: vi.fn(),- }),+vi.mock(import("../../hooks/useTheme"), async (original) => ({+ ...(await original()),+ useTheme: () =>+ ({+ theme: "system",+ followSystem: true,+ themeHalves: null,+ setTheme: vi.fn(),+ setFollowSystem: vi.fn(),+ setThemeHalf: vi.fn(),+ clearThemeHalves: vi.fn(),+ }) as never,readThemePreference: () => "system",readThemeHalves: () => null,readAppearanceModePreference: () => "system",}));--vi.mock("./useScopedSettings", async (importOriginal) => ({- ...(await importOriginal<typeof import("./useScopedSettings")>()),- useScopedSettings: () => state.settings,+vi.mock(import("./useScopedSettings"), async (original) => ({+ ...(await original()),+ useScopedSettings: (() => state.settings!) as never,useUpdateScopedSettings: () => state.update,}));--vi.mock("../../localApi", async (importOriginal) => ({- ...(await importOriginal<typeof import("../../localApi")>()),- readLocalApi: () => ({ dialogs: { confirm: state.confirm } }),+vi.mock(import("../../localApi"), async (original) => ({+ ...(await original()),+ readLocalApi: () => ({ dialogs: { confirm: state.confirm } }) as never,}));import { useSettingsRestore } from "./SettingsPanels";-beforeEach(() => {- hooks.reset();+let root: Root;+let restore: ReturnType<typeof useSettingsRestore>;++function Probe() {+ const result = useSettingsRestore();+ useEffect(() => {+ restore = result;+ });+ return null;+}++beforeEach(async () => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);vi.clearAllMocks();state.settings = { ...DEFAULT_UNIFIED_SETTINGS };state.confirm.mockResolvedValue(true);+ root = createRoot(document.createElement("div"));+});+afterEach(async () => {+ await act(async () => root.unmount());+ vi.unstubAllGlobals();});+const render = () => act(async () => root.render(<Probe />));+describe("restoring V2 settings", () => {it.each([["persistComposerContextStrip", "Composer context"],@@ -67,11 +69,10 @@ describe("restoring V2 settings", () => {["snoozeLimitedThreads", "Snooze limited threads"],] as const)("restores %s when it is the only changed setting", async (key, label) => {state.settings = { ...DEFAULT_UNIFIED_SETTINGS, [key]: true };- hooks.beginRender();- const restore = useSettingsRestore();+ await render();expect(restore.changedSettingLabels).toEqual([label]);- await restore.restoreDefaults();+ await act(() => restore.restoreDefaults());expect(state.confirm.mock.calls[0]?.[0]).toContain(label);expect(state.update).toHaveBeenCalledOnce();@@ -81,9 +82,9 @@ describe("restoring V2 settings", () => {it("does not reset settings after cancellation", async () => {state.settings = { ...DEFAULT_UNIFIED_SETTINGS, autoResumeLimitedThreads: true };state.confirm.mockResolvedValue(false);- hooks.beginRender();+ await render();- await useSettingsRestore().restoreDefaults();+ await act(() => restore.restoreDefaults());expect(state.confirm).toHaveBeenCalledOnce();expect(state.update).not.toHaveBeenCalled();diff --git a/apps/web/src/components/settings/SnapShotSettings.browser.test.tsx b/apps/web/src/components/settings/SnapShotSettings.browser.test.tsxnew file mode 100644index 00000000000..ada82678c49--- /dev/null+++ b/apps/web/src/components/settings/SnapShotSettings.browser.test.tsx@@ -0,0 +1,368 @@+import {+ DEFAULT_CLIENT_SETTINGS,+ type ClientSettingsPatch,+ type DesktopSnapShotState,+} from "@t3tools/contracts";+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { userEvent } from "vite-plus/test/browser";+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";++const bridge = vi.hoisted(() => ({+ getSnapShotState: vi.fn<() => Promise<DesktopSnapShotState>>(),+ setSnapShotShortcutSuppressed: vi.fn(),+ checkSnapShotShortcut: vi.fn(),+ previewSnapShotConfig: vi.fn(),+ applySnapShotConfig: vi.fn(),+ setupSnapShot: vi.fn(),+ requestSnapShotPermissions: vi.fn(),+ onMenuAction: vi.fn(),+ onSnapShotEvent: vi.fn(() => () => undefined),+}));+const toast = vi.hoisted(() => vi.fn());+// Client settings behave like the real store: an update re-renders every reader.+const settingsStore = vi.hoisted(() => ({+ current: {} as typeof DEFAULT_CLIENT_SETTINGS,+ listeners: new Set<() => void>(),+ update: vi.fn<(patch: ClientSettingsPatch) => Promise<void>>(),+ set(next: typeof DEFAULT_CLIENT_SETTINGS) {+ settingsStore.current = next;+ for (const listener of settingsStore.listeners) listener();+ },+}));+vi.mock(import("@tanstack/react-router"), async (original) => ({+ ...(await original()),+ useLocation: ((options?: { select?: (location: unknown) => unknown }) =>+ options?.select?.({ hash: "", pathname: "/settings/snapshots", state: {} }) ?? "") as never,+ useNavigate: (() => vi.fn()) as never,+}));+vi.mock(import("../../lib/desktopSnapShot"), async (original) => ({+ ...(await original()),+ getDesktopSnapShotBridge: () => bridge as never,+}));+vi.mock(import("../ui/toast"), async (original) => {+ const actual = await original();+ return { ...actual, toastManager: { ...actual.toastManager, add: toast } };+});+vi.mock(import("../../hooks/useSettings"), async (original) => {+ const { useSyncExternalStore } = await import("react");+ const subscribe = (listener: () => void) => {+ settingsStore.listeners.add(listener);+ return () => settingsStore.listeners.delete(listener);+ };+ return {+ ...(await original()),+ useClientSettings: (() =>+ useSyncExternalStore(subscribe, () => settingsStore.current)) as never,+ useUpdateClientSettings: () => settingsStore.update as never,+ };+});++import { readSnapShotSetupResume } from "../../lib/snapShotSetupResume";+import { SnapShotSettings } from "./SnapShotSettings";++let state: DesktopSnapShotState;+let root: Root;+let container: HTMLDivElement;++async function mount() {+ root = createRoot(container);+ await act(async () => root.render(<SnapShotSettings />));+ await vi.waitFor(() => expect(bridge.getSnapShotState).toHaveBeenCalled());+ await act(async () => {});+}+const dialog = () => document.querySelector<HTMLElement>('[role="dialog"]');+const scope = () => dialog() ?? container;+function button(label: string, within: ParentNode = scope()) {+ return (+ [...within.querySelectorAll("button")].find(+ (element) => element.textContent?.trim() === label,+ ) ?? null+ );+}+async function click(label: string) {+ const target = button(label);+ expect(target, `button ${label}`).not.toBeNull();+ await act(async () => target!.click());+}+const recorder = () => scope().querySelector<HTMLButtonElement>("[data-keybinding-capture]")!;+const toggle = (label: string) =>+ container.querySelector<HTMLButtonElement>(`[role="switch"][aria-label="${label}"]`)!;+const stepTitle = () => dialog()?.querySelector("h3")?.textContent;++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ vi.clearAllMocks();+ localStorage.clear();+ Object.defineProperty(navigator, "platform", { configurable: true, get: () => "Linux" });+ settingsStore.current = { ...DEFAULT_CLIENT_SETTINGS, snapShotEnabled: true };+ state = {+ mode: "portal",+ linuxBackend: "hyprland",+ shortcut: DEFAULT_CLIENT_SETTINGS.snapShotShortcut,+ shortcutRegistered: false,+ shortcutActionRegistered: true,+ shortcutMessage: null,+ message: null,+ hyprlandHelper: { status: "ready", message: "Ready" },+ };+ bridge.getSnapShotState.mockImplementation(async () => state);+ bridge.setSnapShotShortcutSuppressed.mockResolvedValue(undefined);+ bridge.checkSnapShotShortcut.mockResolvedValue({ available: true, message: null });+ bridge.requestSnapShotPermissions.mockResolvedValue(undefined);+ bridge.setupSnapShot.mockReset().mockResolvedValue(undefined);+ settingsStore.update.mockImplementation(async (patch) => {+ state = { ...state, shortcut: patch.snapShotShortcut ?? state.shortcut };+ settingsStore.set({ ...settingsStore.current, ...patch });+ });+ container = document.createElement("div");+ document.body.append(container);+});+afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+ localStorage.clear();+ Reflect.deleteProperty(navigator, "platform");+ vi.unstubAllGlobals();+});++it.each(["niri", "hyprland"] as const)(+ "reopens %s setup at Shortcut without reading config or expanding Settings",+ async (desktop) => {+ state = { ...state, linuxBackend: desktop };+ await mount();+ expect(dialog()).toBeNull();+ expect(button("Review changes", container)).toBeNull();+ await click("Change shortcut");+ expect(stepTitle()).toBe("Choose your shortcut");+ expect(button("Review changes")).not.toBeNull();+ expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();+ expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();+ await click("Close");+ expect(dialog()).toBeNull();+ expect(settingsStore.update).not.toHaveBeenCalled();+ expect(settingsStore.current.snapShotEnabled).toBe(true);+ },+);++it("returns to Access if the Hyprland helper needs attention before changing keys", async () => {+ await mount();+ state = { ...state, hyprlandHelper: { status: "not-installed", message: "Install helper" } };+ await click("Change shortcut");+ expect(stepTitle()).toBe("Allow snapshots");+ expect(button("Install helper")).not.toBeNull();+ expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();+});++it.each(["direct", "gnome-extension", "kde"] as const)(+ "keeps %s shortcut recording and saving inline",+ async (backend) => {+ state = {+ ...state,+ mode: backend === "direct" ? "direct" : "portal",+ linuxBackend: backend === "direct" ? undefined : backend,+ shortcutRegistered: true,+ shortcutLabel: backend === "direct" ? undefined : "Press <Shift><Control>2",+ shortcutMessage: backend === "direct" ? null : "Desktop shortcut: Press <Shift><Control>2",+ };+ await mount();+ if (backend !== "direct") {+ expect(recorder().getAttribute("aria-label")).toBe(+ "Record snapshot shortcut, currently Ctrl+Shift+2",+ );+ }+ await act(async () => userEvent.click(recorder()));+ await act(async () => userEvent.keyboard("{Control>}{Alt>}y{/Alt}{/Control}"));+ expect(bridge.checkSnapShotShortcut).toHaveBeenCalledOnce();+ expect(container.textContent).toContain("Ready to save.");+ expect(recorder().getAttribute("aria-label")).toBe(+ "Record snapshot shortcut, currently Ctrl+Alt+Y",+ );+ await click("Save");+ expect(settingsStore.update).toHaveBeenCalledWith({+ snapShotShortcut: expect.objectContaining({ key: "y", modKey: true, altKey: true }),+ });+ expect(dialog()).toBeNull();+ expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();+ },+);++it("turns capture on directly on Windows without opening setup", async () => {+ settingsStore.current = { ...settingsStore.current, snapShotEnabled: false };+ state = { ...state, mode: "direct", linuxBackend: undefined, windows: true };+ await mount();+ await act(async () => toggle("Enable snapshots").click());+ expect(settingsStore.update).toHaveBeenCalledWith({ snapShotEnabled: true });+ expect(toggle("Enable snapshots").getAttribute("aria-checked")).toBe("true");+ expect(dialog()).toBeNull();+ expect(button("Manage capture")).toBeNull();+});++it("keeps the approved desktop shortcut when recording is cancelled in setup", async () => {+ state = {+ ...state,+ linuxBackend: "gnome-extension",+ gnomeExtension: { status: "enabled", message: "Ready" },+ shortcutRegistered: true,+ shortcutLabel: "Press <Control><Alt>8",+ };+ await mount();+ await click("Manage capture");+ expect(dialog()).not.toBeNull();+ expect(recorder().getAttribute("aria-label")).toBe(+ "Record snapshot shortcut, currently Ctrl+Alt+8",+ );+ await act(async () => userEvent.click(recorder()));+ expect(recorder().textContent).toBe("Press shortcut…");+ await act(async () => userEvent.keyboard("{Escape}"));+ expect(dialog()).not.toBeNull();+ expect(recorder().getAttribute("aria-label")).toBe(+ "Record snapshot shortcut, currently Ctrl+Alt+8",+ );+ expect(settingsStore.update).not.toHaveBeenCalled();+ expect(bridge.checkSnapShotShortcut).not.toHaveBeenCalled();+});++function usePortalShortcut(shortcutCanRetry: boolean) {+ const shortcut = {+ key: "2",+ modKey: false,+ ctrlKey: true,+ altKey: false,+ shiftKey: true,+ metaKey: false,+ };+ settingsStore.current = { ...settingsStore.current, snapShotShortcut: shortcut };+ state = {+ ...state,+ linuxBackend: "gnome-extension",+ gnomeExtension: { status: "enabled", message: "Ready" },+ shortcut,+ linuxFeedbackAvailable: true,+ shortcutRegistered: true,+ shortcutCanRetry,+ };+}++it("keeps older portal shortcuts editable without offering unsupported permissions", async () => {+ usePortalShortcut(false);+ await mount();+ expect(button("Shortcut permissions")).toBeNull();+ expect(bridge.setupSnapShot).not.toHaveBeenCalled();+ await act(async () => userEvent.click(recorder()));+ expect(recorder().textContent).toBe("Press shortcut…");+});++it("shows permission errors once in a toast and allows retrying", async () => {+ usePortalShortcut(true);+ bridge.setupSnapShot.mockRejectedValueOnce(new Error("The desktop service disconnected."));+ await mount();+ await click("Shortcut permissions");+ expect(toast).toHaveBeenCalledExactlyOnceWith({+ type: "error",+ title: "Couldn't open shortcut permissions",+ description: "The desktop service disconnected.",+ });+ expect(container.querySelector('[role="alert"]')).toBeNull();+ await click("Shortcut permissions");+ expect(bridge.setupSnapShot).toHaveBeenCalledTimes(2);+ expect(toast).toHaveBeenCalledTimes(1);+});++it("keeps a failed preference unchanged and reports the save error in a toast", async () => {+ usePortalShortcut(true);+ settingsStore.update.mockRejectedValueOnce(new Error("The settings file is read-only."));+ await mount();+ const flash = () => toggle("Flash captured window");+ expect(flash().getAttribute("aria-checked")).toBe("true");+ await act(async () => flash().click());+ expect(flash().getAttribute("aria-checked")).toBe("true");+ expect(toast).toHaveBeenCalledExactlyOnceWith({+ type: "error",+ title: "Couldn't save capture settings",+ description: "The settings file is read-only.",+ });+ await act(async () => flash().click());+ expect(flash().getAttribute("aria-checked")).toBe("false");+ expect(toast).toHaveBeenCalledTimes(1);+});++it("keeps setup errors in the wizard and does not toast them after closing it", async () => {+ usePortalShortcut(true);+ state = { ...state, shortcutRegistered: false };+ await mount();+ await click("Manage capture");+ expect(stepTitle()).toBe("Choose your shortcut");+ bridge.setupSnapShot.mockRejectedValueOnce(new Error("The desktop service disconnected."));+ await click("Shortcut permissions");+ expect(dialog()!.querySelector('[role="alert"]')?.textContent).toContain(+ "Couldn't finish this step",+ );+ expect(dialog()!.querySelector("details")?.textContent).toContain(+ "The desktop service disconnected.",+ );+ expect(toast).not.toHaveBeenCalled();+ await click("Close");+ expect(dialog()).toBeNull();+ expect(toast).not.toHaveBeenCalled();+});++function useMacPermissions(granted: boolean) {+ settingsStore.current = { ...settingsStore.current, snapShotEnabled: false };+ state = {+ mode: "direct",+ shortcut: DEFAULT_CLIENT_SETTINGS.snapShotShortcut,+ shortcutRegistered: granted,+ shortcutMessage: null,+ message: null,+ macPermissions: { screenRecording: granted, accessibility: granted },+ };+}++it.each([false, true])(+ "resumes macOS permission setup after restart and clears it on close, completed=%s",+ async (completed) => {+ useMacPermissions(false);+ await mount();+ await act(async () => toggle("Enable snapshots").click());+ expect(stepTitle()).toBe("Allow snapshots");+ bridge.setupSnapShot.mockImplementationOnce(async () => {+ expect(readSnapShotSetupResume()).toEqual({ wasEnabled: false });+ });+ await click("Allow");+ expect(bridge.setupSnapShot).toHaveBeenCalledWith("allow-screen-recording");++ // macOS quits the app from its permission prompt; the next launch resumes setup.+ await act(async () => root.unmount());+ state = { ...state, shortcutRegistered: true };+ state = { ...state, macPermissions: { screenRecording: true, accessibility: true } };+ await mount();+ expect(stepTitle()).toBe("Allow snapshots");+ expect(button("Finish later")).not.toBeNull();+ if (completed) {+ await click("Test capture and continue");+ expect(stepTitle()).toBe("Choose your shortcut");+ await click("Done");+ } else {+ await click("Finish later");+ }+ expect(dialog()).toBeNull();+ expect(readSnapShotSetupResume()).toBeNull();+ },+);++it("requires a successful macOS test capture before enabling and allows retry", async () => {+ useMacPermissions(true);+ await mount();+ await act(async () => toggle("Enable snapshots").click());+ bridge.setupSnapShot.mockRejectedValueOnce(new Error("Capture was denied"));+ await click("Test capture and continue");+ expect(dialog()!.querySelector('[role="alert"]')).not.toBeNull();+ expect(dialog()!.querySelector("details")?.textContent).toContain("Capture was denied");+ expect(stepTitle()).toBe("Allow snapshots");+ expect(settingsStore.current.snapShotEnabled).toBe(false);+ await click("Test capture and continue");+ expect(stepTitle()).toBe("Choose your shortcut");+ expect(bridge.setupSnapShot.mock.calls).toEqual([["test-mac-capture"], ["test-mac-capture"]]);+ expect(settingsStore.current.snapShotEnabled).toBe(true);+});diff --git a/apps/web/src/components/settings/SnapShotSettings.test.tsx b/apps/web/src/components/settings/SnapShotSettings.test.tsxdeleted file mode 100644index 781155a20e2..00000000000--- a/apps/web/src/components/settings/SnapShotSettings.test.tsx+++ /dev/null@@ -1,425 +0,0 @@-import {- DEFAULT_CLIENT_SETTINGS,- type ClientSettingsPatch,- type DesktopSnapShotState,-} from "@t3tools/contracts";-import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";-import { reactHookHarness as hooks } from "../../test/reactHookHarness";-import { visitElements } from "../../test/reactElementTree";--const effects = vi.hoisted(() => [] as (() => void)[]);-vi.mock("react", async (original) => {- const actual = await original<typeof import("react")>();- const { reactHookHarness } = await import("../../test/reactHookHarness");- return {- ...actual,- useCallback: reactHookHarness.useCallback,- useMemo: reactHookHarness.useMemo,- useRef: reactHookHarness.useRef,- useState: reactHookHarness.useState,- useEffect: (effect: () => void) => effects.push(effect),- };-});-vi.mock("../../hooks/useStableCallback", () => ({- useStableCallback: <F,>(fn: F) => fn,-}));-vi.mock("react/compiler-runtime", async () => {- const { reactHookHarness } = await import("../../test/reactHookHarness");- return { c: reactHookHarness.useMemoCache };-});-vi.mock("@effect/atom-react", () => ({ useAtomValue: () => [] }));-vi.mock("../../state/environments", () => ({- usePrimaryEnvironmentId: () => null,- useEnvironments: () => [],-}));-vi.mock("../../state/server", () => ({ primaryServerKeybindingsAtom: {} }));-vi.mock("./SettingsScopeContext", () => ({ useOptionalSettingsScope: () => null }));-vi.mock("./SettingsScopeSentence", () => ({ SettingsScopeSentence: () => null }));-const bridge = vi.hoisted(() => ({- getSnapShotState: vi.fn<() => Promise<DesktopSnapShotState>>(),- setSnapShotShortcutSuppressed: vi.fn(),- checkSnapShotShortcut: vi.fn(),- previewSnapShotConfig: vi.fn(),- applySnapShotConfig: vi.fn(),- setupSnapShot: vi.fn(),- requestSnapShotPermissions: vi.fn().mockResolvedValue(undefined),- onMenuAction: vi.fn(),- onSnapShotEvent: vi.fn(() => () => undefined),-}));-const toastManager = vi.hoisted(() => ({ add: vi.fn() }));-vi.mock("../ui/toast", () => ({ toastManager }));-vi.mock("../../lib/desktopSnapShot", () => ({ getDesktopSnapShotBridge: () => bridge }));-const settingsStore = vi.hoisted(() => ({- current: {} as typeof DEFAULT_CLIENT_SETTINGS,- update: vi.fn<(patch: ClientSettingsPatch) => Promise<void>>(),-}));-vi.mock("../../hooks/useSettings", () => ({- useClientSettings: () => settingsStore.current,- useUpdateClientSettings: () => settingsStore.update,-}));--import { SnapShotSettings } from "./SnapShotSettings";-import { SnapShotSetupDialog } from "./SnapShotSetupDialog";-import { CaptureShortcutConfig } from "./CaptureShortcutConfig";-import { SnapShotShortcutKeys } from "../desktop/SnapShotShortcutKeys";--let state: DesktopSnapShotState;-function render() {- hooks.beginRender();- return SnapShotSettings();-}-function renderWithEffects() {- effects.length = 0;- const tree = render();- for (const effect of effects.splice(0)) effect();- return tree;-}-function wizard(tree: ReturnType<typeof render>) {- return visitElements(tree, (element) => element.type === SnapShotSetupDialog);-}-function button(tree: ReturnType<typeof render>, label: string) {- const node = visitElements(- tree,- (element) => element.props.children === label && typeof element.props.onClick === "function",- );- if (!node) throw new Error(`Missing button: ${label}`);- return node.props as { onClick: () => void };-}-async function finish(promise: Promise<unknown>) {- await promise;- await Promise.resolve();-}-async function mount() {- render();- for (const effect of effects.splice(0)) effect();- await finish(bridge.getSnapShotState.mock.results[0]!.value);- return render();-}-beforeEach(() => {- hooks.reset();- effects.length = 0;- vi.clearAllMocks();- vi.stubGlobal("navigator", { platform: "Linux" });- vi.stubGlobal("window", { addEventListener: vi.fn(), removeEventListener: vi.fn() });- settingsStore.current = { ...DEFAULT_CLIENT_SETTINGS, snapShotEnabled: true };- state = {- mode: "portal",- linuxBackend: "hyprland",- shortcut: DEFAULT_CLIENT_SETTINGS.snapShotShortcut,- shortcutRegistered: false,- shortcutActionRegistered: true,- shortcutMessage: null,- message: null,- hyprlandHelper: { status: "ready", message: "Ready" },- };- bridge.getSnapShotState.mockImplementation(async () => state);- bridge.setSnapShotShortcutSuppressed.mockResolvedValue(undefined);- bridge.checkSnapShotShortcut.mockResolvedValue({ available: true, message: null });- bridge.setupSnapShot.mockReset().mockResolvedValue(undefined);- settingsStore.update.mockImplementation(async (patch) => {- settingsStore.current = { ...settingsStore.current, ...patch };- state = { ...state, shortcut: settingsStore.current.snapShotShortcut };- });-});-afterEach(() => vi.unstubAllGlobals());--it.each(["niri", "hyprland"] as const)(- "reopens %s setup at Shortcut without reading config or expanding Settings",- async (desktop) => {- state = { ...state, linuxBackend: desktop };- const tree = await mount();- expect(wizard(tree)).toBeNull();- button(tree, "Change shortcut").onClick();- await finish(bridge.getSnapShotState.mock.results[1]!.value);- const opened = render();- expect(visitElements(opened, (element) => element.type === CaptureShortcutConfig)).toBeNull();- const dialog = wizard(opened);- expect(dialog?.props.initialStep).toBe("shortcut");- expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();- expect(bridge.applySnapShotConfig).not.toHaveBeenCalled();- await (dialog!.props.onClose as (completed: boolean) => Promise<void>)(false);- expect(wizard(render())).toBeNull();- expect(settingsStore.update).not.toHaveBeenCalled();- expect(settingsStore.current.snapShotEnabled).toBe(true);- },-);-it("returns to Access if the Hyprland helper needs attention before changing keys", async () => {- const tree = await mount();- state = { ...state, hyprlandHelper: { status: "not-installed", message: "Install helper" } };- button(tree, "Change shortcut").onClick();- await finish(bridge.getSnapShotState.mock.results[1]!.value);- expect(wizard(render())?.props.initialStep).toBe("access");- expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();-});-it.each(["direct", "gnome-extension", "kde"] as const)(- "keeps %s shortcut recording and saving inline",- async (backend) => {- state = {- ...state,- mode: backend === "direct" ? "direct" : "portal",- linuxBackend: backend === "direct" ? undefined : backend,- shortcutRegistered: true,- shortcutLabel: backend === "direct" ? undefined : "Press <Shift><Control>2",- shortcutMessage: backend === "direct" ? null : "Desktop shortcut: Press <Shift><Control>2",- };- const tree = await mount();- const recorder = (node: ReturnType<typeof render>) => {- const control = visitElements(node, (element) => "data-keybinding-capture" in element.props);- if (!control) throw new Error("Missing inline shortcut recorder");- return control.props;- };- if (backend !== "direct") {- expect(recorder(tree)["aria-label"]).toBe("Record snapshot shortcut, currently Ctrl+Shift+2");- const keycaps = visitElements(tree, (element) => element.type === SnapShotShortcutKeys);- expect(keycaps?.props.shortcut).toMatchObject({ key: "2", ctrlKey: true, shiftKey: true });- expect(- visitElements(tree, (element) => element.props.id === "snap-shot-shortcut")?.props.status,- ).toBeNull();- }- (recorder(tree).onClick as () => void)();- await finish(bridge.setSnapShotShortcutSuppressed.mock.results.at(-1)!.value);- (recorder(render()).onKeyDown as (event: object) => void)({- key: "y",- code: "KeyY",- ctrlKey: true,- altKey: true,- shiftKey: false,- metaKey: false,- repeat: false,- preventDefault: vi.fn(),- stopPropagation: vi.fn(),- });- await finish(bridge.checkSnapShotShortcut.mock.results[0]!.value);- expect(recorder(render()).size).toBe("xs");- expect(recorder(render())["aria-label"]).toBe("Record snapshot shortcut, currently Ctrl+Alt+Y");- button(render(), "Save").onClick();- await finish(settingsStore.update.mock.results[0]!.value);- expect(settingsStore.update).toHaveBeenCalledWith({- snapShotShortcut: expect.objectContaining({ key: "y", modKey: true, altKey: true }),- });- expect(wizard(render())).toBeNull();- expect(bridge.previewSnapShotConfig).not.toHaveBeenCalled();- },-);--it("turns capture on directly on Windows without opening setup", async () => {- settingsStore.current = { ...settingsStore.current, snapShotEnabled: false };- state = { ...state, mode: "direct", linuxBackend: undefined, windows: true };- const tree = await mount();- const toggle = visitElements(- tree,- (element) => element.props["aria-label"] === "Enable snapshots",- );- if (!toggle) throw new Error("Missing capture toggle");- (toggle.props.onCheckedChange as (checked: boolean) => void)(true);- await finish(settingsStore.update.mock.results[0]!.value);- expect(settingsStore.update).toHaveBeenCalledWith({ snapShotEnabled: true });- expect(wizard(renderWithEffects())).toBeNull();- expect(- visitElements(renderWithEffects(), (element) => element.props.children === "Manage capture"),- ).toBeNull();-});--it("keeps the approved desktop shortcut when recording is cancelled in setup", async () => {- state = {- ...state,- linuxBackend: "gnome-extension",- gnomeExtension: { status: "enabled", message: "Ready" },- shortcutRegistered: true,- shortcutLabel: "Press <Control><Alt>8",- };- const tree = await mount();- button(tree, "Manage capture").onClick();- await finish(bridge.getSnapShotState.mock.results[1]!.value);- const shortcut = () => {- const input = visitElements(- wizard(render()),- (element) => "data-keybinding-capture" in element.props,- );- if (!input) throw new Error("Missing setup shortcut recorder");- return input.props;- };- expect(shortcut()["aria-label"]).toBe("Record snapshot shortcut, currently Ctrl+Alt+8");- (shortcut().onClick as () => void)();- await finish(bridge.setSnapShotShortcutSuppressed.mock.results.at(-1)!.value);- expect(shortcut().children).toBe("Press shortcut…");- (shortcut().onKeyDown as (event: object) => void)({- key: "Escape",- preventDefault: vi.fn(),- stopPropagation: vi.fn(),- });- expect(shortcut()["aria-label"]).toBe("Record snapshot shortcut, currently Ctrl+Alt+8");- expect(settingsStore.update).not.toHaveBeenCalled();- expect(bridge.checkSnapShotShortcut).not.toHaveBeenCalled();-});--function usePortalShortcut(shortcutCanRetry: boolean) {- const shortcut = {- key: "2",- modKey: false,- ctrlKey: true,- altKey: false,- shiftKey: true,- metaKey: false,- };- settingsStore.current = { ...settingsStore.current, snapShotShortcut: shortcut };- state = {- ...state,- linuxBackend: "gnome-extension",- gnomeExtension: { status: "enabled", message: "Ready" },- shortcut,- linuxFeedbackAvailable: true,- shortcutRegistered: true,- shortcutCanRetry,- };-}--it("keeps older portal shortcuts editable without offering unsupported permissions", async () => {- usePortalShortcut(false);- const tree = await mount();- expect(() => button(tree, "Shortcut permissions")).toThrow("Missing button");- expect(bridge.setupSnapShot).not.toHaveBeenCalled();- const recorder = visitElements(tree, (element) => "data-keybinding-capture" in element.props);- (recorder!.props.onClick as () => void)();- await finish(bridge.setSnapShotShortcutSuppressed.mock.results.at(-1)!.value);- expect(- visitElements(render(), (element) => "data-keybinding-capture" in element.props)?.props- .children,- ).toBe("Press shortcut…");-});--it("shows permission errors once in a toast and allows retrying", async () => {- usePortalShortcut(true);- bridge.setupSnapShot.mockRejectedValueOnce(new Error("The desktop service disconnected."));- button(await mount(), "Shortcut permissions").onClick();- await finish(bridge.setupSnapShot.mock.results[0]!.value.catch(() => undefined));- const tree = renderWithEffects();- expect(toastManager.add).toHaveBeenCalledExactlyOnceWith({- type: "error",- title: "Couldn't open shortcut permissions",- description: "The desktop service disconnected.",- });- expect(visitElements(tree, (element) => element.props.role === "alert")).toBeNull();- expect(state.shortcutRegistered).toBe(true);- button(renderWithEffects(), "Shortcut permissions").onClick();- await finish(bridge.setupSnapShot.mock.results[1]!.value);- renderWithEffects();- expect(bridge.setupSnapShot).toHaveBeenCalledTimes(2);- expect(toastManager.add).toHaveBeenCalledTimes(1);-});--it("keeps a failed preference unchanged and reports the save error in a toast", async () => {- usePortalShortcut(true);- const flash = (tree: ReturnType<typeof render>) => {- const control = visitElements(- tree,- (element) => element.props["aria-label"] === "Flash captured window",- );- if (!control) throw new Error("Missing flash control");- return control.props as { onCheckedChange: (checked: boolean) => void; checked: boolean };- };- settingsStore.update.mockRejectedValueOnce(new Error("The settings file is read-only."));- flash(await mount()).onCheckedChange(false);- await finish(settingsStore.update.mock.results[0]!.value.catch(() => undefined));- expect(flash(renderWithEffects()).checked).toBe(true);- expect(toastManager.add).toHaveBeenCalledExactlyOnceWith({- type: "error",- title: "Couldn't save capture settings",- description: "The settings file is read-only.",- });- flash(renderWithEffects()).onCheckedChange(false);- await finish(settingsStore.update.mock.results[1]!.value);- expect(flash(renderWithEffects()).checked).toBe(false);- expect(toastManager.add).toHaveBeenCalledTimes(1);-});--it("keeps setup errors in the wizard and does not toast them after closing it", async () => {- usePortalShortcut(true);- button(await mount(), "Manage capture").onClick();- await finish(bridge.getSnapShotState.mock.results[1]!.value);- bridge.setupSnapShot.mockRejectedValueOnce(new Error("The desktop service disconnected."));- const action = wizard(render())!.props.onAction as (action: "retry-shortcut") => Promise<void>;- await action("retry-shortcut");- const dialog = wizard(renderWithEffects())!;- expect(dialog.props.error).toBe("The desktop service disconnected.");- expect(toastManager.add).not.toHaveBeenCalled();- await (dialog.props.onClose as (completed: boolean) => Promise<void>)(false);- expect(wizard(renderWithEffects())).toBeNull();- expect(toastManager.add).not.toHaveBeenCalled();-});--it.each([false, true])(- "resumes macOS permission setup after restart and clears it on close, completed=%s",- async (completed) => {- const { readSnapShotSetupResume } = await import("../../lib/snapShotSetupResume");- const values = new Map<string, string>();- Object.assign(window, {- localStorage: {- getItem: (key: string) => values.get(key) ?? null,- setItem: (key: string, value: string) => values.set(key, value),- removeItem: (key: string) => values.delete(key),- },- });- settingsStore.current = { ...settingsStore.current, snapShotEnabled: false };- state = {- mode: "direct",- shortcut: DEFAULT_CLIENT_SETTINGS.snapShotShortcut,- shortcutRegistered: false,- shortcutMessage: null,- message: null,- macPermissions: { screenRecording: false, accessibility: false },- };- const tree = await mount();- const toggle = visitElements(- tree,- (element) => element.props["aria-label"] === "Enable snapshots",- );- (toggle!.props.onCheckedChange as (checked: boolean) => void)(true);- await finish(bridge.getSnapShotState.mock.results[1]!.value);- bridge.setupSnapShot.mockImplementationOnce(async () => {- expect(readSnapShotSetupResume()).toEqual({ wasEnabled: false });- });- await (wizard(render())!.props.onAction as (action: string) => Promise<void>)(- "allow-screen-recording",- );-- hooks.reset();- effects.length = 0;- bridge.getSnapShotState.mockClear();- state = { ...state, macPermissions: { screenRecording: true, accessibility: true } };- const resumed = wizard(await mount());- expect(resumed).not.toBeNull();- expect(resumed!.props.initialStep).toBe("access");- expect(resumed!.props.wasEnabled).toBe(false);- await (resumed!.props.onClose as (completed: boolean) => Promise<void>)(completed);- expect(wizard(render())).toBeNull();- expect(readSnapShotSetupResume()).toBeNull();- },-);--it("requires a successful macOS test capture before enabling and allows retry", async () => {- settingsStore.current = { ...DEFAULT_CLIENT_SETTINGS, snapShotEnabled: false };- state = {- mode: "direct",- shortcut: DEFAULT_CLIENT_SETTINGS.snapShotShortcut,- shortcutRegistered: false,- shortcutMessage: null,- message: null,- macPermissions: { screenRecording: true, accessibility: true },- };- const tree = await mount();- const toggle = visitElements(- tree,- (element) => element.props["aria-label"] === "Enable snapshots",- );- (toggle!.props.onCheckedChange as (checked: boolean) => void)(true);- await finish(bridge.getSnapShotState.mock.results[1]!.value);- bridge.setupSnapShot.mockRejectedValueOnce(new Error("Capture was denied"));- const enable = () => (wizard(render())!.props.onEnable as () => Promise<boolean>)();- expect(await enable()).toBe(false);- expect(wizard(render())!.props.error).toBe("Capture was denied");- expect(settingsStore.current.snapShotEnabled).toBe(false);- expect(await enable()).toBe(true);- expect(bridge.setupSnapShot.mock.calls).toEqual([["test-mac-capture"], ["test-mac-capture"]]);- expect(settingsStore.current.snapShotEnabled).toBe(true);-});diff --git a/apps/web/src/components/settings/ThemeEditorHost.browser.test.tsx b/apps/web/src/components/settings/ThemeEditorHost.browser.test.tsxnew file mode 100644index 00000000000..f625a4471e9--- /dev/null+++ b/apps/web/src/components/settings/ThemeEditorHost.browser.test.tsx@@ -0,0 +1,138 @@+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vite-plus/test";++import {+ installCustomTheme,+ invalidateCustomThemes,+ parseThemeFile,+ removeCustomTheme,+ THEME_FILE_VERSION,+ themeColorToHex,+ updateCustomTheme,+ type ThemeDefinition,+} from "../../themePalette";++vi.mock(import("../../hooks/useTheme"), async (original) => ({+ ...(await original()),+ useTheme: () =>+ ({ theme: "system", themeHalves: null, setTheme: vi.fn(), refreshTheme: vi.fn() }) as never,+}));+// The real panel is a large lazy editor; this stand-in shows which theme the host hands it.+vi.mock(import("./ThemeEditorPanel"), async (original) => ({+ ...(await original()),+ ThemeEditorPanel: (({+ editingTheme,+ seedTheme,+ }: {+ editingTheme: ThemeDefinition | null;+ seedTheme: ThemeDefinition | null;+ }) => (+ <dl>+ <dt>editingTheme</dt>+ <dd>{editingTheme ? themeColorToHex(editingTheme.colors.accent ?? "") : "none"}</dd>+ <dt>seedTheme</dt>+ <dd>{seedTheme ? themeColorToHex(seedTheme.colors.accent ?? "") : "none"}</dd>+ </dl>+ )) as never,+}));++import { ThemeEditorHost } from "./ThemeEditorHost";+import { useThemeEditorStore } from "./themeEditorStore";++type Field = "editingTheme" | "seedTheme";+let root: Root;+let container: HTMLDivElement;++function install(id: string) {+ return installCustomTheme(+ parseThemeFile({+ version: THEME_FILE_VERSION,+ id,+ name: id,+ appearance: "dark",+ colors: { accent: "#1f6e4a" },+ }),+ );+}+function open(field: Field, themeId: string) {+ return act(async () =>+ useThemeEditorStore.getState().openThemeEditor({+ editingThemeId: field === "editingTheme" ? themeId : null,+ seedThemeId: field === "seedTheme" ? themeId : null,+ seedName: null,+ initialAppearance: "dark",+ }),+ );+}+async function shown(field: Field) {+ await vi.waitFor(() => expect(container.querySelector("dl")).not.toBeNull(), {+ timeout: 5_000,+ });+ const terms = [...container.querySelectorAll("dt")];+ return terms.find((term) => term.textContent === field)?.nextElementSibling?.textContent;+}++// The host lazy-loads the panel; load it once so the first test does not race the import.+beforeAll(() => import("./ThemeEditorPanel"));++beforeEach(async () => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ localStorage.clear();+ invalidateCustomThemes();+ useThemeEditorStore.setState({ session: null });+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+ await act(async () => root.render(<ThemeEditorHost />));+});+afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+ localStorage.clear();+ invalidateCustomThemes();+ vi.unstubAllGlobals();+});++describe("ThemeEditorHost", () => {+ it.each(["editingTheme", "seedTheme"] as const)(+ "reopens the same %s with its saved colors",+ async (field) => {+ const theme = install("saved-colors");+ await open(field, theme.id);+ expect(await shown(field)).toBe("#1f6e4a");++ await act(async () => useThemeEditorStore.getState().closeThemeEditor());+ expect(container.querySelector("dl")).toBeNull();+ updateCustomTheme({ ...theme, colors: { ...theme.colors, accent: "#7241b8" } });+ await open(field, theme.id);++ expect(await shown(field)).toBe("#7241b8");+ },+ );++ it.each(["editingTheme", "seedTheme"] as const)(+ "refreshes an open %s when the library changes",+ async (field) => {+ const theme = install("updated-theme");+ await open(field, theme.id);+ expect(await shown(field)).toBe("#1f6e4a");++ await act(async () =>+ updateCustomTheme({ ...theme, colors: { ...theme.colors, accent: "#7241b8" } }),+ );++ expect(await shown(field)).toBe("#7241b8");+ },+ );++ it("does not keep editing a theme removed from the library", async () => {+ const theme = install("removed-theme");+ await open("editingTheme", theme.id);+ expect(await shown("editingTheme")).toBe("#1f6e4a");++ await act(async () => removeCustomTheme(theme.id));++ expect(await shown("editingTheme")).toBe("none");+ });+});diff --git a/apps/web/src/components/settings/ThemeEditorHost.test.tsx b/apps/web/src/components/settings/ThemeEditorHost.test.tsxdeleted file mode 100644index eaf0c1b06b2..00000000000--- a/apps/web/src/components/settings/ThemeEditorHost.test.tsx+++ /dev/null@@ -1,191 +0,0 @@-import type { ReactElement } from "react";-import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";--import { reactHookHarness as hooks } from "../../test/reactHookHarness";-import {- getThemeDefinition,- installCustomTheme,- invalidateCustomThemes,- parseThemeFile,- removeCustomTheme,- THEME_FILE_VERSION,- themeColorToHex,- updateCustomTheme,- type ThemeDefinition,-} from "../../themePalette";-import type { ThemeEditorSession } from "./themeEditorStore";--const state = vi.hoisted(() => ({- session: null as ThemeEditorSession | null,- closeThemeEditor: vi.fn(),- onStoreChange: vi.fn(),- subscriptions: new Set<() => void>(),- theme: {- theme: "system",- themeHalves: null,- setTheme: vi.fn(),- refreshTheme: vi.fn(),- },-}));--vi.mock("react", async (importOriginal) => {- const actual = await importOriginal<typeof import("react")>();- const { reactHookHarness } = await import("../../test/reactHookHarness");- return {- ...actual,- useCallback: reactHookHarness.useCallback,- useSyncExternalStore: (- subscribe: (listener: () => void) => () => void,- getSnapshot: () => unknown,- ) => {- const subscription = reactHookHarness.useRef<(() => void) | null>(null);- if (!subscription.current) {- subscription.current = subscribe(() => state.onStoreChange());- state.subscriptions.add(subscription.current);- }- return getSnapshot();- },- };-});--vi.mock("react/compiler-runtime", async () => {- const { reactHookHarness } = await import("../../test/reactHookHarness");- return { c: reactHookHarness.useMemoCache };-});--vi.mock("../../hooks/useTheme", () => ({ useTheme: () => state.theme }));-vi.mock("./themeEditorStore", () => ({- useThemeEditorStore: (select: (store: typeof state) => unknown) => select(state),-}));-vi.mock("../ui/toast", () => ({- toastManager: { add: vi.fn() },- stackedThreadToast: (value: unknown) => value,-}));--import { ThemeEditorHost } from "./ThemeEditorHost";--function renderEditor() {- hooks.beginRender();- const host = ThemeEditorHost() as ReactElement<{- children: ReactElement<{- editingTheme: ThemeDefinition | null;- seedTheme: ThemeDefinition | null;- }>;- }> | null;- return host?.props.children.props ?? null;-}--describe("ThemeEditorHost", () => {- beforeEach(() => {- hooks.reset();- state.session = null;- state.onStoreChange.mockReset();- const storage = new Map<string, string>();- vi.stubGlobal("window", {- localStorage: {- getItem: (key: string) => storage.get(key) ?? null,- setItem: (key: string, value: string) => storage.set(key, value),- },- addEventListener: vi.fn(),- removeEventListener: vi.fn(),- });- invalidateCustomThemes();- });-- afterEach(() => {- for (const unsubscribe of state.subscriptions) unsubscribe();- state.subscriptions.clear();- vi.unstubAllGlobals();- invalidateCustomThemes();- });-- it.each(["editingTheme", "seedTheme"] as const)(- "reopens the same %s with its saved colors",- (field) => {- const theme = installCustomTheme(- parseThemeFile({- version: THEME_FILE_VERSION,- id: "saved-colors",- name: "Saved colors",- appearance: "dark",- colors: { accent: "#1f6e4a" },- }),- );- const session = {- id: 1,- editingThemeId: field === "editingTheme" ? theme.id : null,- seedThemeId: field === "seedTheme" ? theme.id : null,- seedName: null,- initialAppearance: "dark" as const,- };- state.session = session;- expect(themeColorToHex(renderEditor()?.[field]?.colors.accent ?? "")).toBe("#1f6e4a");-- updateCustomTheme({ ...theme, colors: { ...theme.colors, accent: "#7241b8" } });- expect(themeColorToHex(getThemeDefinition(theme.id)?.colors.accent ?? "")).toBe("#7241b8");- state.session = null;- expect(renderEditor()).toBeNull();- state.session = { ...session, id: 2 };-- expect(themeColorToHex(renderEditor()?.[field]?.colors.accent ?? "")).toBe("#7241b8");- },- );-- it.each(["editingTheme", "seedTheme"] as const)(- "refreshes an open %s when the library changes",- (field) => {- const theme = installCustomTheme(- parseThemeFile({- version: THEME_FILE_VERSION,- id: "updated-theme",- name: "Updated theme",- appearance: "dark",- colors: { accent: "#1f6e4a" },- }),- );- state.session = {- id: 1,- editingThemeId: field === "editingTheme" ? theme.id : null,- seedThemeId: field === "seedTheme" ? theme.id : null,- seedName: null,- initialAppearance: "dark",- };- let editor = renderEditor();- state.onStoreChange.mockImplementation(() => {- editor = renderEditor();- });-- updateCustomTheme({ ...theme, colors: { ...theme.colors, accent: "#7241b8" } });-- expect(themeColorToHex(editor?.[field]?.colors.accent ?? "")).toBe("#7241b8");- },- );-- it("does not keep editing a theme removed from the library", () => {- const theme = installCustomTheme(- parseThemeFile({- version: THEME_FILE_VERSION,- id: "removed-theme",- name: "Removed theme",- appearance: "dark",- colors: { accent: "#1f6e4a" },- }),- );- state.session = {- id: 1,- editingThemeId: theme.id,- seedThemeId: null,- seedName: null,- initialAppearance: "dark",- };- let editor = renderEditor();- expect(editor?.editingTheme?.id).toBe(theme.id);- state.onStoreChange.mockImplementation(() => {- editor = renderEditor();- });-- removeCustomTheme(theme.id);-- expect(editor?.editingTheme).toBeNull();- });-});diff --git a/apps/web/src/components/settings/useSnapShotShortcutRecorder.browser.test.tsx b/apps/web/src/components/settings/useSnapShotShortcutRecorder.browser.test.tsxnew file mode 100644index 00000000000..c81720038dd--- /dev/null+++ b/apps/web/src/components/settings/useSnapShotShortcutRecorder.browser.test.tsx@@ -0,0 +1,175 @@+import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts";+import { act, useEffect } from "react";+import { createRoot, type Root } from "react-dom/client";+import { userEvent } from "vite-plus/test/browser";+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";++const suppress = vi.hoisted(() => vi.fn<(enabled: boolean) => Promise<void>>());+vi.mock(import("../../lib/desktopSnapShot"), async (original) => ({+ ...(await original()),+ getDesktopSnapShotBridge: () => ({ setSnapShotShortcutSuppressed: suppress }) as never,+}));++import { useSnapShotShortcutRecorder } from "./useSnapShotShortcutRecorder";++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((done) => {+ resolve = done;+ });+ return { promise, resolve };+}++const recorded = vi.fn();+const error = vi.fn();+let root: Root;+let container: HTMLDivElement;+let recording = false;++function Recorder(props: { allowModifierPairs?: boolean; shortcutLabel?: string }) {+ const recorder = useSnapShotShortcutRecorder({+ shortcut: DEFAULT_CLIENT_SETTINGS.snapShotShortcut,+ shortcutLabel: props.shortcutLabel,+ allowModifierPairs: props.allowModifierPairs ?? false,+ onRecord: recorded,+ onError: error,+ });+ useEffect(() => {+ recording = recorder.recording;+ });+ return recorder.input;+}++async function render(props: Parameters<typeof Recorder>[0] = {}) {+ await act(async () => root.render(<Recorder {...props} />));+}+const button = () => container.querySelector<HTMLButtonElement>("[data-keybinding-capture]")!;+async function start(props: Parameters<typeof Recorder>[0] = {}) {+ await render(props);+ await act(async () => userEvent.click(button()));+ expect(recording).toBe(true);+}+const press = (keys: string) => act(async () => userEvent.keyboard(keys));+function setPlatform(platform: string) {+ Object.defineProperty(navigator, "platform", { configurable: true, get: () => platform });+}++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ suppress.mockReset().mockResolvedValue(undefined);+ recorded.mockReset();+ error.mockReset();+ setPlatform("Linux x86_64");+ container = document.createElement("div");+ document.body.append(container);+ root = createRoot(container);+});+afterEach(async () => {+ await act(async () => root.unmount());+ container.remove();+ Reflect.deleteProperty(navigator, "platform");+ vi.unstubAllGlobals();+});++it("suppresses capture while recording and uses the physical key for shifted digits", async () => {+ await start();+ expect(suppress).toHaveBeenCalledExactlyOnceWith(true);+ expect(button().textContent).toBe("Press shortcut…");+ await press("{Control>}{Shift>}2{/Shift}{/Control}");+ expect(recorded).toHaveBeenCalledExactlyOnceWith({+ key: "2",+ modKey: true,+ ctrlKey: false,+ metaKey: false,+ altKey: false,+ shiftKey: true,+ });+ expect(suppress).toHaveBeenLastCalledWith(false);+ expect(recording).toBe(false);+});++it("lets users replace an unrecognized desktop label without displaying guessed keys", async () => {+ const shortcutLabel = "Use the shortcut assigned in desktop settings";+ await render({ shortcutLabel });+ expect(button().textContent).toBe("Change shortcut");+ expect(button().getAttribute("aria-label")).toBe("Change snapshot shortcut");+ await act(async () => userEvent.click(button()));+ expect(button().textContent).toBe("Press shortcut…");+ await press("{Control>}{Shift>}2{/Shift}{/Control}");+ expect(recorded).toHaveBeenCalledWith(+ expect.objectContaining({ key: "2", modKey: true, shiftKey: true }),+ );+ expect(suppress).toHaveBeenLastCalledWith(false);+});++it("records macOS Command without treating it as Control", async () => {+ setPlatform("MacIntel");+ await start({ allowModifierPairs: true });+ await press("{Meta>}k{/Meta}");+ expect(recorded).toHaveBeenCalledWith(expect.objectContaining({ key: "k", modKey: true }));+});++it.each(["Escape", "blur", "unmount"])("cancels on %s without selecting keys", async (cancel) => {+ await start();+ if (cancel === "Escape") {+ const outside = vi.fn();+ document.addEventListener("keydown", outside);+ await press("{Escape}");+ document.removeEventListener("keydown", outside);+ expect(outside).not.toHaveBeenCalled();+ } else if (cancel === "blur") await act(async () => button().blur());+ else await act(async () => root.render(null));+ expect(suppress).toHaveBeenLastCalledWith(false);+ expect(recorded).not.toHaveBeenCalled();+ if (cancel !== "unmount") expect(recording).toBe(false);+});++it("ignores late suppression acknowledgements after cancellation", async () => {+ const pending = deferred<void>();+ suppress.mockImplementation((enabled) => (enabled ? pending.promise : Promise.resolve()));+ await render();+ await act(async () => userEvent.click(button()));+ await act(async () => button().blur());+ await act(async () => pending.resolve());+ expect(recording).toBe(false);+ expect(suppress).toHaveBeenLastCalledWith(false);+ expect(recorded).not.toHaveBeenCalled();+});++it("reports suppression failures instead of arming the recorder", async () => {+ suppress.mockRejectedValue(new Error("Couldn't pause capture"));+ await render();+ await act(async () => userEvent.click(button()));+ expect(recording).toBe(false);+ expect(error).toHaveBeenCalledWith("Couldn't pause capture");+});++it("does not record Tab, unmodified keys, or modifier keys on their own", async () => {+ await start();+ await press("y");+ await press("{Control>}{/Control}");+ expect(recorded).not.toHaveBeenCalled();+ expect(recording).toBe(true);+ await press("{Tab}");+ expect(document.activeElement).not.toBe(button());+});++it("rejects modifier pairs on Wayland but accepts the next key chord", async () => {+ await start();+ await press("{ShiftLeft>}{ShiftRight>}{/ShiftRight}{/ShiftLeft}");+ expect(recorded).not.toHaveBeenCalled();+ expect(error).toHaveBeenCalledWith(expect.stringContaining("Add a letter, number"));+ expect(recording).toBe(true);+ await press("{Control>}{Alt>}y{/Alt}{/Control}");+ expect(recorded).toHaveBeenCalledOnce();+});++it("preserves native modifier-pair recording and tracks released keys", async () => {+ await start({ allowModifierPairs: true });+ await press("{ShiftLeft}");+ await press("{ShiftRight>}");+ expect(recorded).not.toHaveBeenCalled();+ await press("{ShiftLeft>}");+ expect(recorded).toHaveBeenCalledExactlyOnceWith({ kind: "both-shift-keys" });+ await press("{/ShiftLeft}{/ShiftRight}");+});diff --git a/apps/web/src/components/settings/useSnapShotShortcutRecorder.test.tsx b/apps/web/src/components/settings/useSnapShotShortcutRecorder.test.tsxdeleted file mode 100644index b41113c5cf0..00000000000--- a/apps/web/src/components/settings/useSnapShotShortcutRecorder.test.tsx+++ /dev/null@@ -1,166 +0,0 @@-import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts";-import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";-import { reactHookHarness as hooks } from "../../test/reactHookHarness";-import { useSnapShotShortcutRecorder } from "./useSnapShotShortcutRecorder";--const effects = vi.hoisted(() => [] as (() => () => void)[]);-vi.mock("react", async (original) => {- const actual = await original<typeof import("react")>();- const { reactHookHarness } = await import("../../test/reactHookHarness");- return {- ...actual,- useCallback: reactHookHarness.useCallback,- useRef: reactHookHarness.useRef,- useState: reactHookHarness.useState,- useEffect: (effect: () => () => void) => effects.push(effect),- };-});-vi.mock("react/compiler-runtime", async () => {- const { reactHookHarness } = await import("../../test/reactHookHarness");- return { c: reactHookHarness.useMemoCache };-});-const suppress = vi.hoisted(() => vi.fn<(_: boolean) => Promise<void>>());-vi.mock("../../lib/desktopSnapShot", () => ({- getDesktopSnapShotBridge: () => ({ setSnapShotShortcutSuppressed: suppress }),-}));--const recorded = vi.fn();-const error = vi.fn();-function render(allowModifierPairs = false, shortcutLabel?: string) {- hooks.beginRender();- return useSnapShotShortcutRecorder({- shortcut: DEFAULT_CLIENT_SETTINGS.snapShotShortcut,- shortcutLabel,- allowModifierPairs,- onRecord: recorded,- onError: error,- });-}-function event(key: string, code = key, extra: object = {}) {- return {- key,- code,- ctrlKey: false,- altKey: false,- shiftKey: false,- metaKey: false,- repeat: false,- preventDefault: vi.fn(),- stopPropagation: vi.fn(),- ...extra,- };-}-async function start(allowModifierPairs = false) {- render(allowModifierPairs).input.props.onClick();- await suppress.mock.results.at(-1)!.value;- return render(allowModifierPairs);-}-beforeEach(() => {- hooks.reset();- effects.length = 0;- suppress.mockReset().mockResolvedValue(undefined);- recorded.mockReset();- error.mockReset();- vi.stubGlobal("navigator", { platform: "Linux" });-});-afterEach(() => vi.unstubAllGlobals());--it("suppresses capture while recording and uses the physical key for shifted digits", async () => {- const recorder = await start();- expect(recorder.recording).toBe(true);- expect(suppress).toHaveBeenCalledExactlyOnceWith(true);- recorder.input.props.onKeyDown(event("@", "Digit2", { ctrlKey: true, shiftKey: true }));- expect(recorded).toHaveBeenCalledExactlyOnceWith({- key: "2",- modKey: true,- ctrlKey: false,- metaKey: false,- altKey: false,- shiftKey: true,- });- expect(suppress).toHaveBeenLastCalledWith(false);- expect(render().recording).toBe(false);-});-it("lets users replace an unrecognized desktop label without displaying guessed keys", async () => {- const label = "Use the shortcut assigned in desktop settings";- let recorder = render(false, label);- expect(recorder.input.props.children).toBe("Change shortcut");- expect(recorder.input.props["aria-label"]).toBe("Change snapshot shortcut");- recorder.input.props.onClick();- await suppress.mock.results.at(-1)!.value;- recorder = render(false, label);- expect(recorder.input.props.children).toBe("Press shortcut…");- recorder.input.props.onKeyDown(event("@", "Digit2", { ctrlKey: true, shiftKey: true }));- expect(recorded).toHaveBeenCalledWith(- expect.objectContaining({ key: "2", modKey: true, shiftKey: true }),- );- expect(suppress).toHaveBeenLastCalledWith(false);-});-it("records macOS Command without treating it as Control", async () => {- vi.stubGlobal("navigator", { platform: "MacIntel" });- (await start(true)).input.props.onKeyDown(event("k", "KeyK", { metaKey: true }));- expect(recorded).toHaveBeenCalledWith(expect.objectContaining({ key: "k", modKey: true }));-});-it.each(["Escape", "blur", "unmount"])("cancels on %s without selecting keys", async (cancel) => {- const recorder = await start();- if (cancel === "Escape") {- const escape = event("Escape");- recorder.input.props.onKeyDown(escape);- expect(escape.preventDefault).toHaveBeenCalled();- expect(escape.stopPropagation).toHaveBeenCalled();- } else if (cancel === "blur") recorder.input.props.onBlur();- else effects[0]!()();- expect(suppress).toHaveBeenLastCalledWith(false);- expect(recorded).not.toHaveBeenCalled();- if (cancel !== "unmount") expect(render().recording).toBe(false);-});-it("ignores late suppression acknowledgements after cancellation", async () => {- let resolve!: () => void;- const pending = new Promise<void>((done) => {- resolve = done;- });- suppress.mockImplementation((enabled) => (enabled ? pending : Promise.resolve()));- render().input.props.onClick();- render().input.props.onBlur();- resolve();- await pending;- expect(render().recording).toBe(false);- expect(suppress).toHaveBeenLastCalledWith(false);- expect(recorded).not.toHaveBeenCalled();-});-it("reports suppression failures instead of arming the recorder", async () => {- suppress.mockRejectedValue(new Error("Couldn't pause capture"));- render().input.props.onClick();- await suppress.mock.results[0]!.value.catch(() => undefined);- expect(render().recording).toBe(false);- expect(error).toHaveBeenCalledWith("Couldn't pause capture");-});-it("does not record Tab, held repeats, or modifier keys on their own", async () => {- const recorder = await start();- const tab = event("Tab");- recorder.input.props.onKeyDown(tab);- recorder.input.props.onKeyDown(event("y", "KeyY", { ctrlKey: true, repeat: true }));- recorder.input.props.onKeyDown(event("Control", "ControlLeft", { ctrlKey: true }));- expect(tab.preventDefault).not.toHaveBeenCalled();- expect(recorded).not.toHaveBeenCalled();- expect(render().recording).toBe(true);-});-it("rejects modifier pairs on Wayland but accepts the next key chord", async () => {- const recorder = await start();- recorder.input.props.onKeyDown(event("Shift", "ShiftLeft", { shiftKey: true }));- recorder.input.props.onKeyDown(event("Shift", "ShiftRight", { shiftKey: true }));- expect(recorded).not.toHaveBeenCalled();- expect(error).toHaveBeenCalledWith(expect.stringContaining("Add a letter, number"));- expect(render().recording).toBe(true);- render().input.props.onKeyDown(event("y", "KeyY", { ctrlKey: true, altKey: true }));- expect(recorded).toHaveBeenCalledOnce();-});-it("preserves native modifier-pair recording and tracks released keys", async () => {- const recorder = await start(true);- recorder.input.props.onKeyDown(event("Shift", "ShiftLeft", { shiftKey: true }));- recorder.input.props.onKeyUp(event("Shift", "ShiftLeft"));- recorder.input.props.onKeyDown(event("Shift", "ShiftRight", { shiftKey: true }));- expect(recorded).not.toHaveBeenCalled();- recorder.input.props.onKeyDown(event("Shift", "ShiftLeft", { shiftKey: true }));- expect(recorded).toHaveBeenCalledExactlyOnceWith({ kind: "both-shift-keys" });-});diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.tsindex e83e0201fd3..31968b3bb7e 100644--- a/apps/web/vite.config.ts+++ b/apps/web/vite.config.ts@@ -82,6 +82,8 @@ const unitTestProject = {// in headless Chromium through the same plugins as the app, so it exercises compiled code.const browserTestProject = {extends: true,+ // Pre-bundled so the first test importing userEvent does not trigger a mid-run reload.+ optimizeDeps: { include: ["vite-plus/test/browser"] },test: {name: "browser",include: ["src/**/*.browser.test.{ts,tsx}"],