Skip to content

Commit ab3816e

Browse files
test(web): hook-harness tests run in a real browser
Rewrites the settings and permission tests that called components as plain functions through the mocked-React hook harness. They now render the real components in Chromium with the React Compiler, and drive them with clicks and keyboard input. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 489d08a commit ab3816e

24 files changed

Lines changed: 2431 additions & 2813 deletions
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
import { act, useEffect } from "react";
2+
import { createRoot, type Root } from "react-dom/client";
3+
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
4+
5+
import { usePermissionStatus } from "./usePermissionStatus";
6+
7+
type Status = { screen: boolean; accessibility: boolean };
8+
const check = vi.fn<() => Promise<Status>>();
9+
10+
function deferred<T>() {
11+
let resolve!: (value: T) => void;
12+
const promise = new Promise<T>((done) => {
13+
resolve = done;
14+
});
15+
return { promise, resolve };
16+
}
17+
18+
let root: Root | null;
19+
let current: ReturnType<typeof usePermissionStatus<keyof Status>>;
20+
let visibility: DocumentVisibilityState;
21+
22+
function Probe() {
23+
const status = usePermissionStatus(check, { screen: false, accessibility: false });
24+
useEffect(() => {
25+
current = status;
26+
});
27+
return null;
28+
}
29+
30+
beforeEach(() => {
31+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
32+
vi.useFakeTimers();
33+
visibility = "visible";
34+
Object.defineProperty(document, "visibilityState", {
35+
configurable: true,
36+
get: () => visibility,
37+
});
38+
check.mockReset().mockResolvedValue({ screen: false, accessibility: false });
39+
root = null;
40+
});
41+
afterEach(async () => {
42+
await unmount();
43+
vi.useRealTimers();
44+
vi.unstubAllGlobals();
45+
Reflect.deleteProperty(document, "visibilityState");
46+
});
47+
48+
async function start() {
49+
root = createRoot(document.createElement("div"));
50+
await act(async () => root!.render(<Probe />));
51+
}
52+
async function unmount() {
53+
const mounted = root;
54+
root = null;
55+
if (mounted) await act(async () => mounted.unmount());
56+
}
57+
const tick = (ms: number) => act(() => vi.advanceTimersByTimeAsync(ms));
58+
59+
it("unlocks Continue only for required grants and relocks on revocation", async () => {
60+
await start();
61+
expect(current.isReady(["screen"])).toBe(false);
62+
check.mockResolvedValue({ screen: true, accessibility: false });
63+
await tick(1500);
64+
expect(current.isReady(["screen"])).toBe(true);
65+
expect(current.isReady(["screen", "accessibility"])).toBe(false);
66+
check.mockResolvedValue({ screen: true, accessibility: true });
67+
await tick(1500);
68+
expect(current.isReady(["screen", "accessibility"])).toBe(true);
69+
check.mockResolvedValue({ screen: false, accessibility: true });
70+
await act(async () => window.dispatchEvent(new Event("focus")));
71+
expect(current.isReady(["screen"])).toBe(false);
72+
});
73+
74+
it("does not overlap checks and discards completion after closing", async () => {
75+
const pending = deferred<Status>();
76+
check.mockReturnValue(pending.promise);
77+
await start();
78+
await tick(4500);
79+
window.dispatchEvent(new Event("focus"));
80+
expect(check).toHaveBeenCalledTimes(1);
81+
const last = current;
82+
await unmount();
83+
await act(async () => pending.resolve({ screen: true, accessibility: true }));
84+
expect(last.isReady(["screen"])).toBe(false);
85+
expect(vi.getTimerCount()).toBe(0);
86+
});
87+
88+
it("pauses in the background and blocks stale grants after a check failure", async () => {
89+
check.mockResolvedValue({ screen: true, accessibility: true });
90+
await start();
91+
expect(current.isReady(["screen"])).toBe(true);
92+
visibility = "hidden";
93+
await tick(3000);
94+
expect(check).toHaveBeenCalledTimes(1);
95+
check.mockRejectedValue(new Error("IPC unavailable"));
96+
visibility = "visible";
97+
await act(async () => document.dispatchEvent(new Event("visibilitychange")));
98+
expect(current.isReady(["screen"])).toBe(false);
99+
expect(current.error).not.toBeNull();
100+
check.mockResolvedValue({ screen: true, accessibility: true });
101+
await tick(1500);
102+
expect(current.isReady(["screen"])).toBe(true);
103+
});

‎apps/web/src/components/permissions/usePermissionStatus.test.ts‎

Lines changed: 0 additions & 96 deletions
This file was deleted.
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import { act } from "react";
2+
import { createRoot, type Root } from "react-dom/client";
3+
import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
4+
5+
import { AcpRegistryAgentIcon } from "./AcpRegistryIcon";
6+
7+
const url = "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg";
8+
const fetchIcon = vi.fn<typeof fetch>();
9+
let root: Root;
10+
let container: HTMLDivElement;
11+
12+
beforeEach(() => {
13+
vi.stubGlobal("caches", undefined);
14+
vi.stubGlobal("fetch", fetchIcon);
15+
fetchIcon.mockReset();
16+
container = document.createElement("div");
17+
document.body.append(container);
18+
root = createRoot(container);
19+
});
20+
afterEach(async () => {
21+
await act(async () => root.unmount());
22+
container.remove();
23+
vi.unstubAllGlobals();
24+
});
25+
26+
const image = () => container.querySelector("img");
27+
const fallback = () => container.querySelector('[data-slot="acp-icon-fallback"]');
28+
29+
it("falls back to the raw allowlisted CDN URL when the validating fetch is blocked", async () => {
30+
// The official CDN serves no CORS headers, so the fetch can reject even
31+
// though native <img> loading works.
32+
fetchIcon.mockRejectedValue(new TypeError("Failed to fetch"));
33+
await act(async () => root.render(<AcpRegistryAgentIcon icon={url} />));
34+
35+
await vi.waitFor(() => expect(image()?.getAttribute("src")).toBe(url));
36+
expect(image()?.referrerPolicy).toBe("no-referrer");
37+
expect(fallback()).not.toBeNull();
38+
});
39+
40+
function serve(body: string) {
41+
fetchIcon.mockResolvedValue(
42+
new Response(body, { status: 200, headers: { "content-type": "image/svg+xml" } }),
43+
);
44+
}
45+
46+
it("swaps the fallback for the validated blob once the image loads", async () => {
47+
serve('<svg xmlns="http://www.w3.org/2000/svg" width="8" height="8"/>');
48+
await act(async () => root.render(<AcpRegistryAgentIcon icon={url} />));
49+
50+
await vi.waitFor(() => expect(fallback()).toBeNull());
51+
expect(image()?.src).toMatch(/^blob:/);
52+
expect(image()?.checkVisibility()).toBe(true);
53+
});
54+
55+
it("keeps the fallback and drops the image when the validated blob fails to decode", async () => {
56+
serve("not an svg");
57+
await act(async () => root.render(<AcpRegistryAgentIcon icon={url} />));
58+
59+
await vi.waitFor(() => expect(fetchIcon).toHaveBeenCalledOnce());
60+
await vi.waitFor(() => expect(image()).toBeNull());
61+
expect(fallback()).not.toBeNull();
62+
});
63+
64+
it("never renders an icon from outside the official CDN", async () => {
65+
await act(async () =>
66+
root.render(<AcpRegistryAgentIcon icon="https://cdn.agentclientprotocol.com.evil/icon.svg" />),
67+
);
68+
expect(fetchIcon).not.toHaveBeenCalled();
69+
expect(image()).toBeNull();
70+
expect(fallback()).not.toBeNull();
71+
});
Lines changed: 0 additions & 93 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,6 @@
1-
import type { ReactElement } from "react";
21
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
32

4-
import { visitElements } from "../../test/reactElementTree";
5-
import { reactHookHarness as hooks } from "../../test/reactHookHarness";
6-
7-
vi.mock("react", async (importOriginal) => {
8-
const actual = await importOriginal<typeof import("react")>();
9-
const { reactHookHarness } = await import("../../test/reactHookHarness");
10-
return {
11-
...actual,
12-
useEffect: (effect: () => void | (() => void)) => effect(),
13-
useState: reactHookHarness.useState,
14-
useId: () => "acp-icon-test-filter",
15-
};
16-
});
17-
183
import {
19-
AcpRegistryAgentIcon,
204
loadCachedAcpRegistryIcon,
215
officialAcpRegistryIconUrlForAgentId,
226
resolveOfficialAcpRegistryIconUrl,
@@ -31,7 +15,6 @@ describe("ACP Registry icon cache", () => {
3115
const fetchIcon = vi.fn();
3216

3317
beforeEach(() => {
34-
hooks.reset();
3518
stored.clear();
3619
match.mockClear();
3720
put.mockClear();
@@ -125,80 +108,4 @@ describe("ACP Registry icon cache", () => {
125108
);
126109
expect(officialAcpRegistryIconUrlForAgentId("../kilo")).toBeNull();
127110
});
128-
129-
it("falls back to the raw allowlisted CDN URL when the validating fetch is blocked", async () => {
130-
const url = "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg";
131-
// The official CDN serves no CORS headers, so the fetch can reject even
132-
// though native <img> loading works.
133-
fetchIcon.mockRejectedValue(new TypeError("Failed to fetch"));
134-
hooks.beginRender();
135-
AcpRegistryAgentIcon({ icon: url });
136-
137-
await new Promise((resolve) => setTimeout(resolve, 0));
138-
hooks.beginRender();
139-
const tree = AcpRegistryAgentIcon({ icon: url }) as ReactElement<Record<string, unknown>>;
140-
const image = visitElements(tree, (element) => element.type === "img");
141-
expect(image?.props).toMatchObject({ src: url, referrerPolicy: "no-referrer" });
142-
expect(
143-
visitElements(tree, (element) => element.props["data-slot"] === "acp-icon-fallback"),
144-
).not.toBeNull();
145-
});
146-
147-
it("renders only the validated blob object URL and keeps the fallback until load", async () => {
148-
const url = "https://cdn.agentclientprotocol.com/registry/v1/latest/kilo.svg";
149-
const objectUrl = "blob:t3/kilo-icon";
150-
Object.assign(URL, {
151-
createObjectURL: vi.fn(() => objectUrl),
152-
revokeObjectURL: vi.fn(),
153-
});
154-
fetchIcon.mockResolvedValue(
155-
new Response("<svg/>", {
156-
status: 200,
157-
headers: { "content-type": "image/svg+xml" },
158-
}),
159-
);
160-
hooks.beginRender();
161-
const validating = AcpRegistryAgentIcon({ icon: url }) as ReactElement<Record<string, unknown>>;
162-
163-
expect(visitElements(validating, (element) => element.type === "img")).toBeNull();
164-
expect(
165-
visitElements(validating, (element) => element.props["data-slot"] === "acp-icon-fallback"),
166-
).not.toBeNull();
167-
168-
await new Promise((resolve) => setTimeout(resolve, 0));
169-
hooks.beginRender();
170-
const loading = AcpRegistryAgentIcon({ icon: url }) as ReactElement<Record<string, unknown>>;
171-
const loadingImage = visitElements(loading, (element) => element.type === "img");
172-
173-
expect(loadingImage?.props).toMatchObject({
174-
src: objectUrl,
175-
alt: "",
176-
decoding: "async",
177-
referrerPolicy: "no-referrer",
178-
});
179-
expect(loadingImage?.props.className).not.toContain("dark:invert");
180-
expect(loadingImage?.props.className).toContain("invisible");
181-
expect(
182-
visitElements(loading, (element) => element.props["data-slot"] === "acp-icon-fallback"),
183-
).not.toBeNull();
184-
185-
(loadingImage?.props.onLoad as (() => void) | undefined)?.();
186-
hooks.beginRender();
187-
const loaded = AcpRegistryAgentIcon({ icon: url }) as ReactElement<Record<string, unknown>>;
188-
expect(
189-
visitElements(loaded, (element) => element.type === "img")?.props.className,
190-
).not.toContain("invisible");
191-
expect(
192-
visitElements(loaded, (element) => element.props["data-slot"] === "acp-icon-fallback"),
193-
).toBeNull();
194-
195-
const loadedImage = visitElements(loaded, (element) => element.type === "img");
196-
(loadedImage?.props.onError as (() => void) | undefined)?.();
197-
hooks.beginRender();
198-
const failed = AcpRegistryAgentIcon({ icon: url }) as ReactElement<Record<string, unknown>>;
199-
expect(visitElements(failed, (element) => element.type === "img")).toBeNull();
200-
expect(
201-
visitElements(failed, (element) => element.props["data-slot"] === "acp-icon-fallback"),
202-
).not.toBeNull();
203-
});
204111
});

0 commit comments

Comments
 (0)