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

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

test(web): misc-a tests run in a real browser (#20868)

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

Julius Marminge committed Oct 17, 2026 at 02:53 UTC ecd95d5eb5c0b897b9d55819756c3dc2e789b29e
27 files changed +1515 -1752
apps/web/src/browser/HostedBrowserWebview.browser.test.tsx renamed
+49 -46
@@ -7,7 +7,7 @@ import {
7 type DesktopPreviewBridge,
8 } from "@t3tools/contracts";
9 import { act } from "react";
10 -import { create, type ReactTestRenderer } from "react-test-renderer";
10 +import { createRoot, type Root } from "react-dom/client";
11 import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
12
13 const mocks = vi.hoisted(() => ({
@@ -20,28 +20,32 @@ const mocks = vi.hoisted(() => ({
20 activeRecordings: new Set<string>(),
21 }));
22
23 -vi.mock("~/localApi", () => ({
24 - ensureLocalApi: () => ({ persistence: mocks }),
25 -}));
23 +vi.mock(import("~/localApi"), async (original) => {
24 + const actual = await original();
25 + return {
26 + ...actual,
27 + ensureLocalApi: () => ({ ...actual.ensureLocalApi(), persistence: mocks as never }),
28 + };
29 +});
30 +
31 +vi.mock(import("./desktopTabLifetime"), { spy: true });
32
27 -vi.mock("~/components/preview/previewBridge", () => ({
33 +// The Electron desktop bridge; a browser has none.
34 +vi.mock(import("~/components/preview/previewBridge"), async (original) => ({
35 + ...(await original()),
36 previewBridge: {
37 createTab: mocks.createTab,
38 closeTab: mocks.closeTab,
39 registerWebview: mocks.registerWebview,
40 getPreviewConfig: mocks.getPreviewConfig,
33 - },
41 + } as unknown as DesktopPreviewBridge,
42 }));
43
36 -vi.mock("~/components/preview/usePreviewBridge", () => ({
44 +vi.mock(import("~/components/preview/usePreviewBridge"), async (original) => ({
45 + ...(await original()),
46 usePreviewBridge: () => undefined,
47 }));
48
40 -vi.mock("./browserRecording", () => ({
41 - useActiveBrowserRecordingTabIds: () => mocks.activeRecordings,
42 - stopBrowserRecording: async () => null,
43 -}));
44 -
49 import {
50 __resetClientSettingsPersistenceForTests,
51 ensureClientSettingsHydrated,
@@ -50,7 +54,8 @@ import { useBrowserSurfaceStore } from "./browserSurfaceStore";
54 import * as desktopTabLifetime from "./desktopTabLifetime";
55 import { HostedBrowserWebview } from "./HostedBrowserWebview";
56
53 -let renderer: ReactTestRenderer | undefined;
57 +let root: Root | undefined;
58 +let container: HTMLDivElement;
59
60 function deferred<A>() {
61 let resolve!: (value: A) => void;
@@ -76,20 +81,16 @@ beforeEach(() => {
81 preloadUrl: null,
82 });
83 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
79 - vi.stubGlobal("window", globalThis);
80 - vi.stubGlobal("navigator", { platform: "Linux" });
81 - vi.stubGlobal(
82 - "requestAnimationFrame",
83 - vi.fn(() => 0),
84 - );
85 - vi.stubGlobal("cancelAnimationFrame", vi.fn());
84 vi.spyOn(console, "error").mockImplementation(() => undefined);
85 + container = document.createElement("div");
86 + document.body.append(container);
87 });
88
89 afterEach(async () => {
90 vi.useFakeTimers();
91 - await act(() => renderer?.unmount());
92 - renderer = undefined;
91 + await act(async () => root?.unmount());
92 + root = undefined;
93 + container.remove();
94 await vi.advanceTimersByTimeAsync(0);
95 vi.useRealTimers();
96 __resetClientSettingsPersistenceForTests();
@@ -107,10 +108,21 @@ describe("HostedBrowserWebview settings hydration", () => {
108 .mockReturnValueOnce(firstRead.promise)
109 .mockReturnValueOnce(retryRead.promise);
110 mocks.createTab.mockReturnValueOnce(tabCreation.promise);
110 - const acquire = vi.spyOn(desktopTabLifetime, "acquireDesktopTab");
111 - const createGuest = vi.fn((_attributes: unknown) =>
112 - Object.assign(new EventTarget(), { getWebContentsId: () => 41 }),
113 - );
111 + const acquire = vi.mocked(desktopTabLifetime.acquireDesktopTab);
112 + // Chromium treats <webview> as an unknown element; give it the one Electron method the
113 + // host calls once the guest attaches.
114 + const createElement = document.createElement.bind(document);
115 + const createGuest = vi.spyOn(document, "createElement").mockImplementation(((
116 + tagName: string,
117 + options?: ElementCreationOptions,
118 + ) => {
119 + const element = createElement(tagName, options);
120 + return tagName === "webview"
121 + ? Object.assign(element, { getWebContentsId: () => 41 })
122 + : element;
123 + }) as typeof document.createElement);
124 + const guests = () => createGuest.mock.calls.filter(([tagName]) => tagName === "webview");
125 + const guest = () => container.querySelector("webview");
126 const threadRef = {
127 environmentId: EnvironmentId.make("host-settings-retry"),
128 threadId: ThreadId.make("thread-settings-retry"),
@@ -118,8 +130,9 @@ describe("HostedBrowserWebview settings hydration", () => {
130 const runtimeTabId = "retained-background-tab";
131 useBrowserSurfaceStore.getState().acquireActivity(runtimeTabId);
132
121 - await act(() => {
122 - renderer = create(
133 + root = createRoot(container);
134 + await act(async () =>
135 + root!.render(
136 <HostedBrowserWebview
137 threadRef={threadRef}
138 tabId="server-tab"
@@ -130,18 +143,12 @@ describe("HostedBrowserWebview settings hydration", () => {
143 profileId="work"
144 zoomFactor={1.25}
145 />,
133 - {
134 - createNodeMock: (element) =>
135 - element.type === "webview"
136 - ? createGuest(element.props)
137 - : { scrollLeft: 0, scrollTop: 0, scrollTo: () => undefined },
138 - },
139 - );
140 - });
146 + ),
147 + );
148
149 expect(mocks.getClientSettings).toHaveBeenCalledOnce();
150 expect(acquire).not.toHaveBeenCalled();
144 - expect(createGuest).not.toHaveBeenCalled();
151 + expect(guest()).toBeNull();
152 expect(mocks.createTab).not.toHaveBeenCalled();
153
154 const failure = new Error("Saved settings are unavailable");
@@ -151,7 +158,7 @@ describe("HostedBrowserWebview settings hydration", () => {
158 await expect(hydration).rejects.toBe(failure);
159 });
160 expect(acquire).not.toHaveBeenCalled();
154 - expect(createGuest).not.toHaveBeenCalled();
161 + expect(guest()).toBeNull();
162 expect(mocks.createTab).not.toHaveBeenCalled();
163
164 let retry!: Promise<void>;
@@ -160,7 +167,7 @@ describe("HostedBrowserWebview settings hydration", () => {
167 });
168 expect(mocks.getClientSettings).toHaveBeenCalledTimes(2);
169 expect(acquire).not.toHaveBeenCalled();
163 - expect(createGuest).not.toHaveBeenCalled();
170 + expect(guest()).toBeNull();
171 expect(mocks.createTab).not.toHaveBeenCalled();
172
173 await act(async () => {
@@ -176,13 +183,9 @@ describe("HostedBrowserWebview settings hydration", () => {
183
184 expect(acquire).toHaveBeenCalledExactlyOnceWith(runtimeTabId, undefined);
185 expect(mocks.getPreviewConfig).toHaveBeenCalledExactlyOnceWith(threadRef.environmentId, "work");
179 - expect(createGuest).toHaveBeenCalledOnce();
180 - expect(createGuest).toHaveBeenCalledWith(
181 - expect.objectContaining({
182 - partition: "persist:t3-preview-work",
183 - src: "https://example.com",
184 - }),
185 - );
186 + expect(guests()).toHaveLength(1);
187 + expect(guest()?.getAttribute("partition")).toBe("persist:t3-preview-work");
188 + expect(guest()?.getAttribute("src")).toBe("https://example.com");
189 expect(mocks.createTab).toHaveBeenCalledExactlyOnceWith(runtimeTabId, {
190 zoomFactor: 1.25,
191 colorScheme: "dark",
apps/web/src/cloud/useCloudLinkController.browser.test.tsx renamed
+47 -26
@@ -7,7 +7,7 @@ import {
7 import type { RelayManagedEndpointProviderKind } from "@t3tools/contracts/relay";
8 import { AsyncResult } from "effect/reactivity";
9 import { act, useLayoutEffect } from "react";
10 -import { create, type ReactTestRenderer } from "react-test-renderer";
10 +import { createRoot, type Root } from "react-dom/client";
11 import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
12
13 const testState = vi.hoisted(() => ({
@@ -24,8 +24,9 @@ const testState = vi.hoisted(() => ({
24 toast: vi.fn(),
25 }));
26
27 -vi.mock("@effect/atom-react", () => ({
28 - useAtomValue: () => ({
27 +vi.mock(import("@effect/atom-react"), async (original) => ({
28 + ...(await original()),
29 + useAtomValue: (() => ({
30 environments: new Map(
31 testState.relayProviderKind === null
32 ? []
@@ -36,35 +37,56 @@ vi.mock("@effect/atom-react", () => ({
37 ],
38 ],
39 ),
39 - }),
40 + })) as never,
41 }));
41 -vi.mock("@clerk/react", () => ({
42 - useAuth: () => ({ getToken: testState.getToken, isSignedIn: true }),
42 +vi.mock(import("@clerk/react"), async (original) => ({
43 + ...(await original()),
44 + useAuth: (() => ({ getToken: testState.getToken, isSignedIn: true })) as never,
45 }));
44 -vi.mock("../components/ui/toast", () => ({ toastManager: { add: testState.toast } }));
45 -vi.mock("../state/relay", () => ({
46 - relayEnvironmentDiscovery: { refresh: testState.refreshDiscovery, stateValueAtom: {} },
46 +vi.mock(import("../components/ui/toast"), async (original) => {
47 + const actual = await original();
48 + return { ...actual, toastManager: { ...actual.toastManager, add: testState.toast } as never };
49 +});
50 +vi.mock(import("../state/relay"), async (original) => {
51 + const actual = await original();
52 + return {
53 + ...actual,
54 + relayEnvironmentDiscovery: {
55 + ...actual.relayEnvironmentDiscovery,
56 + refresh: testState.refreshDiscovery,
57 + } as never,
58 + };
59 +});
60 +vi.mock(import("../state/session"), async (original) => ({
61 + ...(await original()),
62 + readEnvironmentScope: (_environmentId, scope) => testState.scopes.has(scope),
63 }));
48 -vi.mock("../state/session", () => ({
49 - readEnvironmentScope: (_environmentId: string, scope: string) => testState.scopes.has(scope),
64 +vi.mock(import("../state/use-atom-command"), async (original) => ({
65 + ...(await original()),
66 + useAtomCommand: ((command: unknown) => command) as never,
67 }));
51 -vi.mock("../state/use-atom-command", () => ({ useAtomCommand: (command: unknown) => command }));
52 -vi.mock("./linkEnvironmentAtoms", () => ({
53 - linkPrimaryEnvironment: testState.link,
54 - unlinkPrimaryEnvironment: testState.unlink,
55 - updatePrimaryEnvironmentPreferences: testState.preferences,
68 +vi.mock(import("./linkEnvironmentAtoms"), async (original) => ({
69 + ...(await original()),
70 + linkPrimaryEnvironment: testState.link as never,
71 + unlinkPrimaryEnvironment: testState.unlink as never,
72 + updatePrimaryEnvironmentPreferences: testState.preferences as never,
73 }));
57 -vi.mock("./primaryCloudLinkState", () => ({
74 +vi.mock(import("./primaryCloudLinkState"), async (original) => ({
75 + ...(await original()),
76 readCachedPrimaryCloudLinkState: () => testState.snapshot,
59 - usePrimaryCloudLinkState: () => ({
77 + usePrimaryCloudLinkState: (() => ({
78 target,
79 data: testState.renderedSnapshot,
80 error: null,
81 isPending: false,
82 refresh: testState.refreshLink,
65 - }),
83 + })) as never,
84 +}));
85 +// The Clerk JWT template is build-time config the test environment does not set.
86 +vi.mock(import("./publicConfig"), async (original) => ({
87 + ...(await original()),
88 + resolveRelayClerkTokenOptions: () => ({}) as never,
89 }));
67 -vi.mock("./publicConfig", () => ({ resolveRelayClerkTokenOptions: () => ({}) }));
90
91 import { useCloudLinkController, type CloudLinkDesiredState } from "./useCloudLinkController";
92
@@ -83,7 +105,7 @@ const linkedState: EnvironmentCloudLinkStateResult = {
105 publishAgentActivity: false,
106 };
107
86 -let renderer: ReactTestRenderer | null = null;
108 +let root: Root | null = null;
109 let controller: ReturnType<typeof useCloudLinkController> | null = null;
110
111 function ControllerProbe() {
@@ -95,9 +117,8 @@ function ControllerProbe() {
117 }
118
119 async function mountController() {
98 - await act(() => {
99 - renderer = create(<ControllerProbe />);
100 - });
120 + root = createRoot(document.createElement("div"));
121 + await act(async () => root!.render(<ControllerProbe />));
122 }
123
124 async function reconcile(desired: CloudLinkDesiredState) {
@@ -136,8 +157,8 @@ beforeEach(() => {
157 });
158
159 afterEach(async () => {
139 - await act(() => renderer?.unmount());
140 - renderer = null;
160 + await act(async () => root?.unmount());
161 + root = null;
162 controller = null;
163 vi.restoreAllMocks();
164 vi.unstubAllGlobals();
apps/web/src/components/KeybindingsConfigWarning.browser.test.tsx new
+117
@@ -0,0 +1,117 @@
1 +import { RegistryContext } from "@effect/atom-react";
2 +import {
3 + AuthOrchestrationOperateScope,
4 + EnvironmentId,
5 + type AuthEnvironmentScope,
6 + type AuthSessionState,
7 +} from "@t3tools/contracts";
8 +import { AsyncResult, Atom } from "effect/reactivity";
9 +import { act } from "react";
10 +import { createRoot, type Root } from "react-dom/client";
11 +import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
12 +
13 +type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;
14 +const state = vi.hoisted(() => ({
15 + sessions: new Map<EnvironmentId, Atom.Writable<SessionResult>>(),
16 + run: vi.fn(),
17 + toast: vi.fn(),
18 +}));
19 +
20 +vi.mock(import("@t3tools/client-runtime/state/session"), async (original) => {
21 + const actual = await original();
22 + return {
23 + ...actual,
24 + createEnvironmentSessionAtoms: ((runtime: never) => ({
25 + ...actual.createEnvironmentSessionAtoms(runtime),
26 + sessionStateAtom: (id: EnvironmentId) => state.sessions.get(id)!,
27 + })) as never,
28 + };
29 +});
30 +vi.mock(import("../state/use-atom-command"), async (original) => ({
31 + ...(await original()),
32 + useAtomCommand: (() => state.run) as never,
33 +}));
34 +vi.mock(import("./ui/toast"), async (original) => {
35 + const actual = await original();
36 + return { ...actual, toastManager: { ...actual.toastManager, add: state.toast } as never };
37 +});
38 +
39 +import { appAtomRegistry } from "../rpc/atomRegistry";
40 +import { KeybindingsConfigWarning } from "./KeybindingsConfigWarning";
41 +
42 +const environmentId = EnvironmentId.make("warning-environment");
43 +let root: Root;
44 +let container: HTMLDivElement;
45 +const session = (scopes: readonly AuthEnvironmentScope[]): AuthSessionState => ({
46 + authenticated: true,
47 + scopes,
48 + auth: {
49 + policy: "remote-reachable",
50 + bootstrapMethods: ["one-time-token"],
51 + sessionMethods: ["bearer-access-token"],
52 + sessionCookieName: "t3_session",
53 + },
54 +});
55 +const setScopes = (scopes: readonly AuthEnvironmentScope[]) =>
56 + appAtomRegistry.set(state.sessions.get(environmentId)!, AsyncResult.success(session(scopes)));
57 +const button = () => container.querySelector("button")!;
58 +
59 +beforeEach(() => {
60 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
61 + localStorage.setItem("t3code:last-editor", JSON.stringify("vscode"));
62 + state.sessions.set(
63 + environmentId,
64 + Atom.make<SessionResult>(AsyncResult.success(session([AuthOrchestrationOperateScope]))).pipe(
65 + Atom.keepAlive,
66 + ),
67 + );
68 + state.run.mockReset().mockResolvedValue(AsyncResult.success(undefined));
69 + state.toast.mockReset();
70 + container = document.createElement("div");
71 + document.body.append(container);
72 + root = createRoot(container);
73 +});
74 +
75 +afterEach(async () => {
76 + await act(async () => root.unmount());
77 + container.remove();
78 + localStorage.clear();
79 + state.sessions.clear();
80 + vi.unstubAllGlobals();
81 +});
82 +
83 +it("updates a visible warning on revocation and blocks a click that raced it until regrant", async () => {
84 + await act(async () =>
85 + root.render(
86 + <RegistryContext.Provider value={appAtomRegistry}>
87 + <KeybindingsConfigWarning
88 + environmentId={environmentId}
89 + configPath="/t3/keybindings.json"
90 + availableEditors={["vscode"]}
91 + message="Invalid shortcut"
92 + />
93 + </RegistryContext.Provider>,
94 + ),
95 + );
96 + expect(container.textContent).toContain("Invalid shortcut");
97 + expect(button().disabled).toBe(false);
98 +
99 + // The click lands before React re-renders the revoked grant.
100 + await act(async () => {
101 + setScopes([]);
102 + button().click();
103 + });
104 + expect(button().disabled).toBe(true);
105 + expect(state.run).not.toHaveBeenCalled();
106 + expect(state.toast).toHaveBeenCalledWith(
107 + expect.objectContaining({ title: "Unable to open keybindings file" }),
108 + );
109 +
110 + await act(async () => setScopes([AuthOrchestrationOperateScope]));
111 + expect(button().disabled).toBe(false);
112 + await act(async () => button().click());
113 + expect(state.run).toHaveBeenCalledExactlyOnceWith({
114 + environmentId,
115 + input: { cwd: "/t3/keybindings.json", editor: "vscode" },
116 + });
117 +});
apps/web/src/components/KeybindingsConfigWarning.test.tsx deleted
-119
@@ -1,119 +0,0 @@
1 -import { RegistryContext } from "@effect/atom-react";
2 -import {
3 - AuthOrchestrationOperateScope,
4 - EnvironmentId,
5 - type AuthEnvironmentScope,
6 - type AuthSessionState,
7 -} from "@t3tools/contracts";
8 -import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
9 -import { act, create, type ReactTestRenderer } from "react-test-renderer";
10 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
11 -
12 -type SessionResult = AsyncResult.AsyncResult<AuthSessionState, Error>;
13 -const state = vi.hoisted(() => ({
14 - registry: null as AtomRegistry.AtomRegistry | null,
15 - sessions: new Map<EnvironmentId, Atom.Writable<SessionResult>>(),
16 - run: vi.fn(),
17 - toast: vi.fn(),
18 -}));
19 -
20 -vi.mock("../connection/runtime", () => ({ connectionAtomRuntime: undefined }));
21 -vi.mock("@t3tools/client-runtime/state/session", () => ({
22 - createEnvironmentSessionAtoms: () => ({
23 - sessionStateAtom: (id: EnvironmentId) => state.sessions.get(id)!,
24 - }),
25 -}));
26 -vi.mock("../rpc/atomRegistry", () => ({
27 - get appAtomRegistry() {
28 - return state.registry;
29 - },
30 -}));
31 -vi.mock("../state/shell", () => ({ shellEnvironment: { openInEditor: "openInEditor" } }));
32 -vi.mock("../state/use-atom-command", () => ({ useAtomCommand: () => state.run }));
33 -vi.mock("../hooks/useLocalStorage", () => ({
34 - getLocalStorageItem: () => "vscode",
35 - setLocalStorageItem: vi.fn(),
36 - useLocalStorage: vi.fn(),
37 -}));
38 -vi.mock("./ui/button", () => ({ Button: "button" }));
39 -vi.mock("./ui/toast", () => ({
40 - toastManager: { add: state.toast },
41 - stackedThreadToast: (value: unknown) => value,
42 -}));
43 -
44 -import { KeybindingsConfigWarning } from "./KeybindingsConfigWarning";
45 -
46 -const environmentId = EnvironmentId.make("warning-environment");
47 -let renderer: ReactTestRenderer | undefined;
48 -const session = (scopes: readonly AuthEnvironmentScope[]): AuthSessionState => ({
49 - authenticated: true,
50 - scopes,
51 - auth: {
52 - policy: "remote-reachable",
53 - bootstrapMethods: ["one-time-token"],
54 - sessionMethods: ["bearer-access-token"],
55 - sessionCookieName: "t3_session",
56 - },
57 -});
58 -
59 -beforeEach(() => {
60 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
61 - state.registry = AtomRegistry.make();
62 - state.sessions.set(
63 - environmentId,
64 - Atom.make<SessionResult>(AsyncResult.success(session([AuthOrchestrationOperateScope]))).pipe(
65 - Atom.keepAlive,
66 - ),
67 - );
68 - state.run.mockReset().mockResolvedValue(AsyncResult.success(undefined));
69 - state.toast.mockReset();
70 -});
71 -
72 -afterEach(async () => {
73 - await act(async () => renderer?.unmount());
74 - renderer = undefined;
75 - state.registry?.dispose();
76 - state.sessions.clear();
77 - vi.unstubAllGlobals();
78 -});
79 -
80 -it("updates a visible warning on revocation and blocks its retained action until regrant", async () => {
81 - await act(async () => {
82 - renderer = create(
83 - <RegistryContext.Provider value={state.registry!}>
84 - <KeybindingsConfigWarning
85 - environmentId={environmentId}
86 - configPath="/t3/keybindings.json"
87 - availableEditors={["vscode"]}
88 - message="Invalid shortcut"
89 - />
90 - </RegistryContext.Provider>,
91 - );
92 - });
93 - const open = renderer!.root.findByType("button").props.onClick;
94 - expect(renderer!.root.findByType("button").props.disabled).toBe(false);
95 - await act(async () => {
96 - state.registry!.set(state.sessions.get(environmentId)!, AsyncResult.success(session([])));
97 - await open();
98 - });
99 - expect(renderer!.root.findByType("button").props.disabled).toBe(true);
100 - expect(state.run).not.toHaveBeenCalled();
101 - expect(state.toast).toHaveBeenCalledWith(
102 - expect.objectContaining({
103 - title: "Unable to open keybindings file",
104 - }),
105 - );
106 -
107 - await act(async () => {
108 - state.registry!.set(
109 - state.sessions.get(environmentId)!,
110 - AsyncResult.success(session([AuthOrchestrationOperateScope])),
111 - );
112 - });
113 - expect(renderer!.root.findByType("button").props.disabled).toBe(false);
114 - await act(async () => open());
115 - expect(state.run).toHaveBeenCalledExactlyOnceWith({
116 - environmentId,
117 - input: { cwd: "/t3/keybindings.json", editor: "vscode" },
118 - });
119 -});
apps/web/src/components/PermissionUpdateNotice.browser.test.tsx new
+113
@@ -0,0 +1,113 @@
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 +type Session = {
6 + _tag: "Success" | "Failure";
7 + waiting: boolean;
8 + value: { authenticated: boolean; permissions: string[] };
9 +};
10 +const state = vi.hoisted(() => ({
11 + id: 0,
12 + session: null as unknown as Session,
13 + add: vi.fn((_notice: unknown) => "notice"),
14 + close: vi.fn(),
15 + navigate: vi.fn(),
16 +}));
17 +vi.mock(import("@effect/atom-react"), async (original) => ({
18 + ...(await original()),
19 + useAtomValue: (() => state.session) as never,
20 +}));
21 +vi.mock(import("@tanstack/react-router"), async (original) => ({
22 + ...(await original()),
23 + useNavigate: (() => state.navigate) as never,
24 +}));
25 +vi.mock(import("../state/environments"), async (original) => ({
26 + ...(await original()),
27 + useEnvironments: (() => ({
28 + environments: [{ environmentId: `env-${state.id}`, label: "Work laptop" }],
29 + })) as never,
30 +}));
31 +vi.mock(import("./ui/toast"), async (original) => {
32 + const actual = await original();
33 + return {
34 + ...actual,
35 + toastManager: { ...actual.toastManager, add: state.add, close: state.close } as never,
36 + };
37 +});
38 +import { PermissionUpdateNotice } from "./PermissionUpdateNotice";
39 +
40 +let root: Root;
41 +let container: HTMLDivElement;
42 +const storageKey = () => `t3code:permission-update:v1:env-${state.id}`;
43 +
44 +beforeEach(() => {
45 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
46 + state.id++;
47 + state.session = {
48 + _tag: "Success",
49 + waiting: false,
50 + value: { authenticated: true, permissions: ["orchestration:operate"] },
51 + };
52 + vi.clearAllMocks();
53 + container = document.createElement("div");
54 + root = createRoot(container);
55 +});
56 +afterEach(async () => {
57 + await act(async () => root.unmount());
58 + localStorage.clear();
59 + vi.unstubAllGlobals();
60 +});
61 +const render = () => act(async () => root.render(<PermissionUpdateNotice />));
62 +type Notice = {
63 + timeout: number;
64 + actionProps: { onClick: () => void };
65 + data: { secondaryActionProps: { onClick: () => void } };
66 +};
67 +const notice = () => state.add.mock.calls[0]![0] as Notice;
68 +
69 +it("keeps the notice visible and persists dismissal, with a route to pairing settings", async () => {
70 + await render();
71 + expect(notice().timeout).toBe(0);
72 + expect(localStorage.getItem(storageKey())).toBeNull();
73 + notice().actionProps.onClick();
74 + expect(state.navigate).toHaveBeenCalledWith({ to: "/settings/connections" });
75 + expect(state.close).toHaveBeenCalledWith("notice");
76 + expect(localStorage.getItem(storageKey())).toBe("true");
77 +});
78 +it("does not repeat on session refresh or remount", async () => {
79 + await render();
80 + await act(async () => root.unmount());
81 + root = createRoot(container);
82 + state.session = { ...state.session };
83 + await render();
84 + expect(state.add).toHaveBeenCalledTimes(1);
85 +});
86 +it("skips a notice dismissed on an earlier launch", async () => {
87 + localStorage.setItem(storageKey(), "true");
88 + await render();
89 + expect(state.add).not.toHaveBeenCalled();
90 +});
91 +it("waits for a successful, settled session check", async () => {
92 + state.session._tag = "Failure";
93 + await render();
94 + expect(state.add).not.toHaveBeenCalled();
95 + state.session = { ...state.session, _tag: "Success", waiting: true };
96 + await render();
97 + expect(state.add).not.toHaveBeenCalled();
98 + state.session = { ...state.session, waiting: false };
99 + await render();
100 + expect(state.add).toHaveBeenCalledTimes(1);
101 +});
102 +it("does not warn for a granular grant", async () => {
103 + state.session.value.permissions.push("filesystem:read");
104 + await render();
105 + expect(state.add).not.toHaveBeenCalled();
106 +});
107 +
108 +it("persists the secondary dismissal without relying on the toast close callback", async () => {
109 + await render();
110 + notice().data.secondaryActionProps.onClick();
111 + expect(localStorage.getItem(storageKey())).toBe("true");
112 + expect(state.close).toHaveBeenCalledWith("notice");
113 +});
apps/web/src/components/PermissionUpdateNotice.test.tsx deleted
-111
@@ -1,111 +0,0 @@
1 -import { act, create, type ReactTestRenderer } from "react-test-renderer";
2 -import { beforeEach, afterEach, expect, it, vi } from "vite-plus/test";
3 -
4 -const state = vi.hoisted(() => ({
5 - id: 0,
6 - saved: false,
7 - session: {
8 - _tag: "Success",
9 - waiting: false,
10 - value: { authenticated: true, permissions: ["orchestration:operate"] },
11 - },
12 - add: vi.fn((_notice: unknown) => "notice"),
13 - close: vi.fn(),
14 - save: vi.fn(),
15 - navigate: vi.fn(),
16 -}));
17 -vi.mock("@effect/atom-react", () => ({ useAtomValue: () => state.session }));
18 -vi.mock("@tanstack/react-router", () => ({ useNavigate: () => state.navigate }));
19 -vi.mock("../state/environments", () => ({
20 - useEnvironments: () => ({
21 - environments: [{ environmentId: `env-${state.id}`, label: "Work laptop" }],
22 - }),
23 -}));
24 -vi.mock("../state/session", () => ({ environmentSession: { sessionStateAtom: () => null } }));
25 -vi.mock("../hooks/useLocalStorage", () => ({
26 - getLocalStorageItem: () => state.saved,
27 - setLocalStorageItem: (...args: unknown[]) => state.save(...args),
28 -}));
29 -vi.mock("./ui/toast", () => ({ toastManager: { add: state.add, close: state.close } }));
30 -import { PermissionUpdateNotice } from "./PermissionUpdateNotice";
31 -
32 -let renderer: ReactTestRenderer;
33 -beforeEach(() => {
34 - state.id++;
35 - state.saved = false;
36 - state.session = {
37 - _tag: "Success",
38 - waiting: false,
39 - value: { authenticated: true, permissions: ["orchestration:operate"] },
40 - };
41 - vi.clearAllMocks();
42 -});
43 -afterEach(async () => {
44 - if (renderer) await act(async () => renderer.unmount());
45 -});
46 -async function render() {
47 - await act(async () => {
48 - renderer = create(<PermissionUpdateNotice />);
49 - });
50 -}
51 -
52 -it("keeps the notice visible and persists dismissal, with a route to pairing settings", async () => {
53 - await render();
54 - const notice = state.add.mock.calls[0]![0] as unknown as {
55 - timeout: number;
56 - onClose: () => void;
57 - actionProps: { onClick: () => void };
58 - };
59 - expect(notice.timeout).toBe(0);
60 - expect(state.save).not.toHaveBeenCalled();
61 - notice.actionProps.onClick();
62 - expect(state.navigate).toHaveBeenCalledWith({ to: "/settings/connections" });
63 - expect(state.close).toHaveBeenCalledWith("notice");
64 - expect(state.save).toHaveBeenCalledWith(
65 - `t3code:permission-update:v1:env-${state.id}`,
66 - true,
67 - expect.anything(),
68 - );
69 -});
70 -it("does not repeat on session refresh or remount", async () => {
71 - await render();
72 - await act(async () => renderer.unmount());
73 - state.session = { ...state.session };
74 - await render();
75 - expect(state.add).toHaveBeenCalledTimes(1);
76 -});
77 -it("skips a notice dismissed on an earlier launch", async () => {
78 - state.saved = true;
79 - await render();
80 - expect(state.add).not.toHaveBeenCalled();
81 -});
82 -it("waits for a successful, settled session check", async () => {
83 - state.session._tag = "Failure";
84 - await render();
85 - expect(state.add).not.toHaveBeenCalled();
86 - state.session = { ...state.session, _tag: "Success", waiting: true };
87 - await act(async () => renderer.update(<PermissionUpdateNotice />));
88 - expect(state.add).not.toHaveBeenCalled();
89 - state.session = { ...state.session, waiting: false };
90 - await act(async () => renderer.update(<PermissionUpdateNotice />));
91 - expect(state.add).toHaveBeenCalledTimes(1);
92 -});
93 -it("does not warn for a granular grant", async () => {
94 - state.session.value.permissions.push("filesystem:read");
95 - await render();
96 - expect(state.add).not.toHaveBeenCalled();
97 -});
98 -
99 -it("persists the secondary dismissal without relying on the toast close callback", async () => {
100 - await render();
101 - const notice = state.add.mock.calls[0]![0] as {
102 - data: { secondaryActionProps: { onClick: () => void } };
103 - };
104 - notice.data.secondaryActionProps.onClick();
105 - expect(state.save).toHaveBeenCalledWith(
106 - `t3code:permission-update:v1:env-${state.id}`,
107 - true,
108 - expect.anything(),
109 - );
110 - expect(state.close).toHaveBeenCalledWith("notice");
111 -});
apps/web/src/components/clerk/T3ConnectUserProfilePage.test.tsx deleted
-63
@@ -1,63 +0,0 @@
1 -import type { EnvironmentId } from "@t3tools/contracts";
2 -import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";
3 -import { renderToStaticMarkup } from "react-dom/server";
4 -import { describe, expect, it, vi } from "vite-plus/test";
5 -
6 -import { T3ConnectEnvironmentRow } from "./T3ConnectUserProfilePage";
7 -
8 -const environment: RelayClientEnvironmentRecord = {
9 - environmentId: "environment-1" as EnvironmentId,
10 - label: "Studio Mac",
11 - endpoint: {
12 - httpBaseUrl: "https://studio.example.com",
13 - wsBaseUrl: "wss://studio.example.com",
14 - providerKind: "cloudflare_tunnel",
15 - },
16 - linkedAt: "2026-08-12T12:00:00.000Z",
17 -};
18 -
19 -function renderRow({
20 - confirmationOpen = false,
21 - mutationPending = false,
22 -}: {
23 - readonly confirmationOpen?: boolean;
24 - readonly mutationPending?: boolean;
25 -} = {}) {
26 - return renderToStaticMarkup(
27 - <T3ConnectEnvironmentRow
28 - environment={environment}
29 - confirmationOpen={confirmationOpen}
30 - mutationPending={mutationPending}
31 - onConfirmationChange={vi.fn()}
32 - onDeregister={vi.fn()}
33 - />,
34 - );
35 -}
36 -
37 -describe("T3 Connect environment row", () => {
38 - it("keeps deregistration confirmation inline and collapsed by default", () => {
39 - const markup = renderRow();
40 -
41 - expect(markup).toContain("Studio Mac");
42 - expect(markup).toContain("Deregister");
43 - expect(markup).not.toContain("Deregister server");
44 - expect(markup).not.toContain("Confirm deregistration of Studio Mac");
45 - });
46 -
47 - it("expands Clerk-style confirmation content beneath the environment row", () => {
48 - const markup = renderRow({ confirmationOpen: true });
49 -
50 - expect(markup).toContain("Deregister server");
51 - expect(markup).toContain("“Studio Mac” will be removed from this account.");
52 - expect(markup).toContain("Confirm deregistration of Studio Mac");
53 - expect(markup).toContain("Local connections on your devices are not changed.");
54 - expect(markup).toContain("Cancel");
55 - });
56 -
57 - it("locks the confirmation actions while deregistration is pending", () => {
58 - const markup = renderRow({ confirmationOpen: true, mutationPending: true });
59 -
60 - expect(markup).toContain("Deregistering…");
61 - expect(markup.match(/ disabled=""/g)).toHaveLength(3);
62 - });
63 -});
apps/web/src/components/clerk/T3ConnectUserProfilePage.tsx
+1 -1
@@ -38,7 +38,7 @@ function endpointLabel(environment: RelayClientEnvironmentRecord): string {
38 : "Activity publishing only";
39 }
40
41 -export function T3ConnectEnvironmentRow(props: {
41 +function T3ConnectEnvironmentRow(props: {
42 readonly environment: RelayClientEnvironmentRecord;
43 readonly confirmationOpen: boolean;
44 readonly mutationPending: boolean;
apps/web/src/components/cloud/CloudEnvironmentConnectList.browser.test.tsx renamed
+104 -143
@@ -3,8 +3,8 @@ import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
3 import { EnvironmentId, ORCHESTRATION_PROTOCOL_VERSION } from "@t3tools/contracts";
4 import * as Option from "effect/Option";
5 import { AsyncResult } from "effect/reactivity";
6 -import { act, useState, type ButtonHTMLAttributes, type ReactNode } from "react";
7 -import { create, type ReactTestRenderer } from "react-test-renderer";
6 +import { act, useState } from "react";
7 +import { createRoot, type Root } from "react-dom/client";
8 import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
9
10 type DiscoveredEnvironments = Discovery.RelayEnvironmentDiscoveryState["environments"];
@@ -12,24 +12,22 @@ type DiscoveredEnvironments = Discovery.RelayEnvironmentDiscoveryState["environm
12 const discovery = vi.hoisted(() => ({
13 state: null as Discovery.RelayEnvironmentDiscoveryState | null,
14 listeners: new Set<() => void>(),
15 - refreshCommand: Symbol("refresh"),
16 - registerCommand: Symbol("register"),
15 refresh: vi.fn<() => Promise<AtomCommandResult<void, never>>>(),
16 register: vi.fn(),
17 listEnvironments: vi.fn<() => Promise<DiscoveredEnvironments>>(),
18 }));
19
22 -vi.mock("~/state/relay", () => ({
23 - relayEnvironmentDiscovery: { refresh: discovery.refreshCommand },
24 -}));
25 -vi.mock("~/connection/catalog", () => ({
26 - environmentCatalog: { register: discovery.registerCommand },
27 -}));
28 -vi.mock("~/state/use-atom-command", () => ({
29 - useAtomCommand: (command: unknown) =>
30 - command === discovery.refreshCommand ? discovery.refresh : discovery.register,
31 -}));
32 -vi.mock("~/state/environments", async () => {
20 +vi.mock(import("~/state/use-atom-command"), async (original) => {
21 + const { relayEnvironmentDiscovery } = await import("~/state/relay");
22 + return {
23 + ...(await original()),
24 + useAtomCommand: ((command: unknown) =>
25 + command === relayEnvironmentDiscovery.refresh
26 + ? discovery.refresh
27 + : discovery.register) as never,
28 + };
29 +});
30 +vi.mock(import("~/state/environments"), async (original) => {
31 const { useSyncExternalStore } = await import("react");
32 const subscribe = (listener: () => void) => {
33 discovery.listeners.add(listener);
@@ -39,34 +37,11 @@ vi.mock("~/state/environments", async () => {
37 if (discovery.state === null) throw new Error("Discovery fixture is not initialized");
38 return discovery.state;
39 };
42 - return { useRelayEnvironmentDiscovery: () => useSyncExternalStore(subscribe, read, read) };
40 + return {
41 + ...(await original()),
42 + useRelayEnvironmentDiscovery: () => useSyncExternalStore(subscribe, read, read),
43 + };
44 });
44 -vi.mock("../ConnectionStatusDot", () => ({ ConnectionStatusDot: () => null }));
45 -vi.mock("../ui/tooltip", () => ({
46 - Tooltip: ({ children }: { children: ReactNode }) => children,
47 - TooltipTrigger: ({ children }: { children: ReactNode }) => <span>{children}</span>,
48 - TooltipPopup: () => null,
49 -}));
50 -vi.mock("../ui/checkbox", () => ({
51 - Checkbox: (props: {
52 - checked: boolean;
53 - disabled: boolean;
54 - onCheckedChange: (checked: boolean) => void;
55 - }) => (
56 - <input
57 - type="checkbox"
58 - checked={props.checked}
59 - disabled={props.disabled}
60 - onChange={(event) => props.onCheckedChange(event.target.checked)}
61 - />
62 - ),
63 -}));
64 -vi.mock("../ui/button", () => ({
65 - Button: ({ children, ...props }: ButtonHTMLAttributes<HTMLButtonElement>) => (
66 - <button {...props}>{children}</button>
67 - ),
68 -}));
69 -vi.mock("../ui/toast", () => ({ toastManager: { add: vi.fn() } }));
45
46 import { CloudEnvironmentConnectRows } from "./CloudEnvironmentConnectList";
47
@@ -92,27 +67,41 @@ const linkedMachines: DiscoveredEnvironments = new Map([
67 ],
68 ]);
69
95 -let renderer: ReactTestRenderer | null;
96 -let page: EventTarget & { visibilityState: DocumentVisibilityState };
97 -let browserWindow: EventTarget;
70 +let root: Root | null;
71 +let container: HTMLDivElement;
72 +let visibility: DocumentVisibilityState;
73
74 function publish(state: Discovery.RelayEnvironmentDiscoveryState) {
75 discovery.state = state;
76 for (const listener of discovery.listeners) listener();
77 }
78
79 +async function render(element: React.ReactElement) {
80 + root ??= createRoot(container);
81 + await act(async () => root!.render(element));
82 +}
83 +
84 async function mount(refreshWhileEmpty = true) {
105 - await act(async () => {
106 - renderer = create(
107 - <CloudEnvironmentConnectRows
108 - primaryEnvironmentId={null}
109 - savedEnvironments={[]}
110 - showSavedEnvironments
111 - refreshWhileEmpty={refreshWhileEmpty}
112 - empty={<p>Waiting for your computer to connect.</p>}
113 - />,
114 - );
115 - });
85 + await render(
86 + <CloudEnvironmentConnectRows
87 + primaryEnvironmentId={null}
88 + savedEnvironments={[]}
89 + showSavedEnvironments
90 + refreshWhileEmpty={refreshWhileEmpty}
91 + empty={<p>Waiting for your computer to connect.</p>}
92 + />,
93 + );
94 +}
95 +
96 +const text = () => container.textContent ?? "";
97 +const button = () =>
98 + [...container.querySelectorAll("button")].find((element) => element.textContent !== "");
99 +const checkbox = () => container.querySelector<HTMLElement>('[role="checkbox"]')!;
100 +const checked = () => checkbox().getAttribute("aria-checked") === "true";
101 +const toggle = () => act(async () => checkbox().click());
102 +function setVisibility(next: DocumentVisibilityState) {
103 + visibility = next;
104 + document.dispatchEvent(new Event("visibilitychange"));
105 }
106
107 async function advance(milliseconds: number) {
@@ -124,11 +113,11 @@ async function advance(milliseconds: number) {
113 beforeEach(() => {
114 vi.useFakeTimers();
115 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
127 - page = Object.assign(new EventTarget(), { visibilityState: "visible" as const });
128 - browserWindow = new EventTarget();
129 - vi.stubGlobal("document", page);
130 - vi.stubGlobal("window", browserWindow);
131 - renderer = null;
116 + visibility = "visible";
117 + vi.spyOn(document, "visibilityState", "get").mockImplementation(() => visibility);
118 + container = document.createElement("div");
119 + document.body.append(container);
120 + root = null;
121 discovery.listeners.clear();
122 discovery.state = {
123 environments: new Map(),
@@ -147,8 +136,10 @@ beforeEach(() => {
136 });
137
138 afterEach(async () => {
150 - await act(async () => renderer?.unmount());
139 + await act(async () => root?.unmount());
140 + container.remove();
141 vi.useRealTimers();
142 + vi.restoreAllMocks();
143 vi.unstubAllGlobals();
144 });
145
@@ -167,12 +158,10 @@ describe("cloud environment offline reasons", () => {
158 ...(offlineReason ? { offlineReason } : {}),
159 }),
160 });
170 - const rowText = () =>
171 - renderer!.root.findAllByType("p").flatMap((paragraph) => paragraph.children);
161
162 discovery.listEnvironments.mockResolvedValue(new Map([[newMachineId, offlineEntry()]]));
163 await mount();
175 - expect(rowText()).toContain("T3 Connect · Not added · Relay offline");
164 + expect(text()).toContain("T3 Connect · Not added · Relay offline");
165
166 await act(async () => {
167 publish({
@@ -182,7 +171,7 @@ describe("cloud environment offline reasons", () => {
171 error: Option.none(),
172 });
173 });
185 - expect(rowText()).toContain(RELAY_TUNNEL_RELEASED_MESSAGE);
174 + expect(text()).toContain(RELAY_TUNNEL_RELEASED_MESSAGE);
175 });
176 });
177
@@ -195,21 +184,19 @@ describe("cloud onboarding discovery", () => {
184 }),
185 );
186 const onDiscoveryReady = vi.fn();
198 - await act(async () => {
199 - renderer = create(
200 - <CloudEnvironmentConnectRows
201 - primaryEnvironmentId={null}
202 - savedEnvironments={[]}
203 - onDiscoveryReady={onDiscoveryReady}
204 - />,
205 - );
206 - });
187 + await render(
188 + <CloudEnvironmentConnectRows
189 + primaryEnvironmentId={null}
190 + savedEnvironments={[]}
191 + onDiscoveryReady={onDiscoveryReady}
192 + />,
193 + );
194 expect(onDiscoveryReady).not.toHaveBeenCalled();
195 await act(async () => {
196 finishDiscovery(linkedMachines);
197 });
198 expect(onDiscoveryReady).toHaveBeenCalledTimes(1);
212 - expect(renderer!.root.findByType("button").children).toEqual(["Add"]);
199 + expect(button()?.textContent).toBe("Add");
200 });
201
202 it("keeps incompatible discoveries unselected until the user enables a compatible server", async () => {
@@ -261,19 +248,13 @@ describe("cloud onboarding discovery", () => {
248 />
249 );
250 }
264 - await act(async () => {
265 - renderer = create(<Setup />);
266 - });
251 + await render(<Setup />);
252 expect(discovery.register).not.toHaveBeenCalled();
253 expect(onSelectionChange).toHaveBeenCalledWith(newMachineId, false);
269 - expect(renderer!.root.findByType("input").props.checked).toBe(false);
270 - expect(renderer!.root.findByType("input").props.disabled).toBe(true);
271 - expect(renderer!.root.findAllByType("span").flatMap((span) => span.children)).toContain(
272 - "Client not supported",
273 - );
274 - await act(async () => {
275 - await renderer!.root.findByType("input").props.onChange({ target: { checked: true } });
276 - });
254 + expect(checked()).toBe(false);
255 + expect(checkbox().hasAttribute("data-disabled")).toBe(true);
256 + expect(text()).toContain("Client not supported");
257 + await toggle();
258 expect(discovery.register).not.toHaveBeenCalled();
259 await act(async () =>
260 publish({
@@ -282,11 +263,9 @@ describe("cloud onboarding discovery", () => {
263 }),
264 );
265 expect(discovery.register).not.toHaveBeenCalled();
285 - expect(renderer!.root.findByType("input").props.checked).toBe(false);
286 - expect(renderer!.root.findByType("input").props.disabled).toBe(false);
287 - await act(async () => {
288 - await renderer!.root.findByType("input").props.onChange({ target: { checked: true } });
289 - });
266 + expect(checked()).toBe(false);
267 + expect(checkbox().hasAttribute("data-disabled")).toBe(false);
268 + await toggle();
269 expect(discovery.register).toHaveBeenCalledTimes(1);
270 });
271
@@ -314,19 +293,15 @@ describe("cloud onboarding discovery", () => {
293 />
294 );
295 }
317 - await act(async () => {
318 - renderer = create(<Setup />);
319 - });
296 + await render(<Setup />);
297
298 expect(discovery.register).toHaveBeenCalledTimes(1);
322 - expect(renderer!.root.findByType("input").props.checked).toBe(true);
323 - await act(async () => {
324 - await renderer!.root.findByType("input").props.onChange({ target: { checked: false } });
325 - });
299 + expect(checked()).toBe(true);
300 + await toggle();
301 await act(async () => {
302 publish({ ...discovery.state!, environments: new Map(linkedMachines) });
303 });
329 - expect(renderer!.root.findByType("input").props.checked).toBe(false);
304 + expect(checked()).toBe(false);
305 expect(discovery.register).toHaveBeenCalledTimes(1);
306 });
307
@@ -335,16 +310,12 @@ describe("cloud onboarding discovery", () => {
310 .mockResolvedValueOnce(new Map())
311 .mockResolvedValueOnce(linkedMachines);
312 await mount();
338 - expect(renderer!.root.findByType("p").children).toEqual([
339 - "Waiting for your computer to connect.",
340 - ]);
313 + expect(text()).toBe("Waiting for your computer to connect.");
314
315 await advance(5_000);
316
344 - expect(renderer!.root.findAllByType("p").map((node) => node.children)).toContainEqual([
345 - "Work laptop",
346 - ]);
347 - expect(renderer!.root.findByType("button").children).toEqual(["Add"]);
317 + expect(text()).toContain("Work laptop");
318 + expect(button()?.textContent).toBe("Add");
319 await advance(30_000);
320 expect(discovery.listEnvironments).toHaveBeenCalledTimes(2);
321 });
@@ -352,44 +323,36 @@ describe("cloud onboarding discovery", () => {
323 it("keeps a discovered computer visible when it is added to the browser", async () => {
324 discovery.listEnvironments.mockResolvedValue(linkedMachines);
325 await mount();
355 - expect(renderer!.root.findByType("button").children).toEqual(["Add"]);
356 - await act(async () => {
357 - renderer!.update(
358 - <CloudEnvironmentConnectRows
359 - primaryEnvironmentId={null}
360 - savedEnvironments={[
361 - {
362 - environmentId: newMachineId,
363 - connection: { phase: "connected", error: null, traceId: null },
364 - relayManaged: true,
365 - },
366 - ]}
367 - showSavedEnvironments
368 - refreshWhileEmpty
369 - />,
370 - );
371 - });
372 - expect(renderer!.root.findAllByType("p").map((node) => node.children)).toContainEqual([
373 - "Work laptop",
374 - ]);
375 - expect(renderer!.root.findByType("button").children).toEqual(["Connected"]);
326 + expect(button()?.textContent).toBe("Add");
327 + await render(
328 + <CloudEnvironmentConnectRows
329 + primaryEnvironmentId={null}
330 + savedEnvironments={[
331 + {
332 + environmentId: newMachineId,
333 + connection: { phase: "connected", error: null, traceId: null },
334 + relayManaged: true,
335 + },
336 + ]}
337 + showSavedEnvironments
338 + refreshWhileEmpty
339 + />,
340 + );
341 + expect(text()).toContain("Work laptop");
342 + expect(button()?.textContent).toBe("Connected");
343 });
344
345 it("waits while hidden and refreshes immediately when visible again", async () => {
379 - page.visibilityState = "hidden";
346 + visibility = "hidden";
347 await mount();
348 await advance(30_000);
349 expect(discovery.listEnvironments).not.toHaveBeenCalled();
350
384 - await act(async () => {
385 - page.visibilityState = "visible";
386 - page.dispatchEvent(new Event("visibilitychange"));
387 - });
351 + await act(async () => setVisibility("visible"));
352 expect(discovery.listEnvironments).toHaveBeenCalledTimes(1);
353
390 - page.visibilityState = "hidden";
391 - page.dispatchEvent(new Event("visibilitychange"));
392 - browserWindow.dispatchEvent(new Event("focus"));
354 + setVisibility("hidden");
355 + window.dispatchEvent(new Event("focus"));
356 await advance(30_000);
357 expect(discovery.listEnvironments).toHaveBeenCalledTimes(1);
358 });
@@ -402,17 +365,15 @@ describe("cloud onboarding discovery", () => {
365 discovery.listEnvironments.mockResolvedValueOnce(new Map()).mockReturnValueOnce(pending);
366 await mount();
367 await advance(5_000);
405 - expect(renderer!.root.findByType("p").children).toEqual([
406 - "Waiting for your computer to connect.",
407 - ]);
368 + expect(text()).toBe("Waiting for your computer to connect.");
369
409 - browserWindow.dispatchEvent(new Event("focus"));
410 - page.dispatchEvent(new Event("visibilitychange"));
370 + window.dispatchEvent(new Event("focus"));
371 + document.dispatchEvent(new Event("visibilitychange"));
372 await advance(30_000);
373 expect(discovery.listEnvironments).toHaveBeenCalledTimes(2);
374
414 - await act(async () => renderer!.unmount());
415 - renderer = null;
375 + await act(async () => root!.unmount());
376 + root = null;
377 await act(async () => resolveRefresh(new Map()));
378 await advance(30_000);
379 expect(discovery.listEnvironments).toHaveBeenCalledTimes(2);
apps/web/src/components/device/DeviceStreamView.browser.test.tsx renamed
+100 -58
@@ -1,7 +1,7 @@
1 import { act, useEffect, useSyncExternalStore } from "react";
2 -import { create, type ReactTestRenderer } from "react-test-renderer";
2 +import { createRoot, type Root } from "react-dom/client";
3 import { EnvironmentId } from "@t3tools/contracts";
4 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
4 +import { afterEach, beforeEach, expect, it, onTestFinished, vi } from "vite-plus/test";
5
6 const accessStore = {
7 value: { httpBase: "http://test", wsBase: "ws://test", query: {}, credentials: true },
@@ -15,50 +15,102 @@ const accessStore = {
15 return () => accessStore.listeners.delete(listener);
16 },
17 };
18 -vi.mock("~/state/device", () => ({
18 +vi.mock(import("~/state/device"), async (original) => ({
19 + ...(await original()),
20 useDeviceHubAccess: () => useSyncExternalStore(accessStore.subscribe, () => accessStore.value),
21 refreshDeviceHubAccess: () => accessStore.refresh(),
22 }));
23 let viewerMounts = 0;
24 let viewerUnmounts = 0;
24 -vi.mock("./DevicePhoneViewport", () => ({
25 - DevicePhoneViewport: function Viewer() {
25 +// The 3D phone frame needs WebGL; the test only cares whether it stays mounted.
26 +vi.mock(import("./DevicePhoneViewport"), async (original) => ({
27 + ...(await original()),
28 + DevicePhoneViewport: function Viewer(): React.ReactElement {
29 useEffect(() => {
30 viewerMounts++;
31 return () => {
32 viewerUnmounts++;
33 };
34 }, []);
32 - return null;
35 + return <></>;
36 },
37 }));
38 import { DeviceStreamView } from "./DeviceStreamView";
39
37 -class Image extends EventTarget {
38 - src = "";
39 - naturalWidth = 0;
40 - naturalHeight = 0;
41 - removeAttribute(name: string) {
42 - if (name === "src") this.src = "";
40 +// MJPEG frames come from the device hub, so images keep their src without loading it and a
41 +// test publishes a frame by setting the natural size and firing "load".
42 +const imageSources = new WeakMap<HTMLImageElement, string>();
43 +const framedImages = new WeakSet<HTMLImageElement>();
44 +let images: HTMLImageElement[] = [];
45 +const srcDescriptor = Object.getOwnPropertyDescriptor(HTMLImageElement.prototype, "src")!;
46 +const naturalWidthDescriptor = Object.getOwnPropertyDescriptor(
47 + HTMLImageElement.prototype,
48 + "naturalWidth",
49 +)!;
50 +const naturalHeightDescriptor = Object.getOwnPropertyDescriptor(
51 + HTMLImageElement.prototype,
52 + "naturalHeight",
53 +)!;
54 +const removeAttribute = Element.prototype.removeAttribute;
55 +function stubImages() {
56 + Object.defineProperty(HTMLImageElement.prototype, "src", {
57 + configurable: true,
58 + get(this: HTMLImageElement) {
59 + return imageSources.get(this) ?? "";
60 + },
61 + set(this: HTMLImageElement, value: string) {
62 + if (!images.includes(this)) images.push(this);
63 + imageSources.set(this, value);
64 + },
65 + });
66 + for (const name of ["naturalWidth", "naturalHeight"]) {
67 + Object.defineProperty(HTMLImageElement.prototype, name, {
68 + configurable: true,
69 + get(this: HTMLImageElement) {
70 + if (!framedImages.has(this)) return 0;
71 + return name === "naturalWidth" ? 400 : 800;
72 + },
73 + });
74 }
75 + Element.prototype.removeAttribute = function (this: Element, name: string) {
76 + if (this instanceof HTMLImageElement && name === "src") imageSources.delete(this);
77 + return removeAttribute.call(this, name);
78 + };
79 }
45 -let renderer: ReactTestRenderer | undefined;
80 +function restoreImages() {
81 + Object.defineProperty(HTMLImageElement.prototype, "src", srcDescriptor);
82 + Object.defineProperty(HTMLImageElement.prototype, "naturalWidth", naturalWidthDescriptor);
83 + Object.defineProperty(HTMLImageElement.prototype, "naturalHeight", naturalHeightDescriptor);
84 + Element.prototype.removeAttribute = removeAttribute;
85 +}
86 +async function publishFrame(image: HTMLImageElement) {
87 + framedImages.add(image);
88 + await act(async () => image.dispatchEvent(new Event("load")));
89 +}
90 +let root: Root;
91 +let container: HTMLDivElement;
92 let primes = 0;
93 beforeEach(() => {
94 primes = 0;
95 viewerMounts = 0;
96 viewerUnmounts = 0;
97 + images = [];
98 + stubImages();
99 + container = document.createElement("div");
100 + container.style.cssText = "width: 400px; height: 800px; display: flex";
101 + document.body.append(container);
102 + root = createRoot(container);
103 });
104 afterEach(async () => {
53 - await act(async () => renderer?.unmount());
54 - renderer = undefined;
105 + await act(async () => root.unmount());
106 + container.remove();
107 + restoreImages();
108 vi.useRealTimers();
109 vi.unstubAllGlobals();
110 });
111
112 async function setup(h264 = false) {
113 vi.useFakeTimers();
61 - vi.stubGlobal("window", globalThis);
114 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
115 let videoBody: ReadableStreamDefaultController<Uint8Array> | undefined;
116 let output: VideoFrameOutputCallback | undefined;
@@ -80,6 +132,15 @@ async function setup(h264 = false) {
132 },
133 );
134 vi.stubGlobal("EncodedVideoChunk", vi.fn());
135 + } else {
136 + // Without WebCodecs the iOS client streams MJPEG.
137 + const videoDecoder = Object.getOwnPropertyDescriptor(globalThis, "VideoDecoder");
138 + if (videoDecoder) {
139 + Reflect.deleteProperty(globalThis, "VideoDecoder");
140 + onTestFinished(() => {
141 + Object.defineProperty(globalThis, "VideoDecoder", videoDecoder);
142 + });
143 + }
144 }
145 vi.stubGlobal("fetch", (url: string, init: RequestInit) => {
146 if (url.endsWith("stream.avcc")) {
@@ -111,14 +172,6 @@ async function setup(h264 = false) {
172 close() {}
173 },
174 );
114 - vi.stubGlobal(
115 - "ResizeObserver",
116 - class {
117 - observe() {}
118 - disconnect() {}
119 - },
120 - );
121 - const images: Image[] = [];
175 const view = (visible: boolean) => (
176 <DeviceStreamView
177 hostId="local"
@@ -129,22 +182,7 @@ async function setup(h264 = false) {
182 allowPhoneView={h264}
183 />
184 );
132 - await act(async () => {
133 - renderer = create(view(true), {
134 - createNodeMock: (node) => {
135 - if (node.type === "img") {
136 - const image = new Image();
137 - images.push(image);
138 - return image;
139 - }
140 - return {
141 - getContext: () => ({ drawImage() {} }),
142 - style: { setProperty() {} },
143 - getBoundingClientRect: () => ({ width: 400, height: 800 }),
144 - };
145 - },
146 - });
147 - });
185 + await act(async () => root.render(view(true)));
186 return {
187 images,
188 view,
@@ -160,19 +198,29 @@ async function setup(h264 = false) {
198 videoBody?.enqueue(new Uint8Array([0, 0, 0, 5, 1, 1, 0x64, 0, 0x1f]));
199 },
200 frame() {
163 - output?.({ displayWidth: 400, displayHeight: 800, close() {} } as VideoFrame);
201 + const source = new OffscreenCanvas(400, 800);
202 + source.getContext("2d")!.fillRect(0, 0, 400, 800);
203 + output?.(new VideoFrame(source, { timestamp: 0 }));
204 },
205 };
206 }
207
208 +const alert = () => container.querySelector('[role="alert"]');
209 +const reconnect = () =>
210 + act(async () =>
211 + [...container.querySelectorAll("button")]
212 + .find((button) => button.textContent?.includes("Reconnect"))!
213 + .click(),
214 + );
215 +
216 it("removes MJPEG requests while hidden and reconnects when shown", async () => {
217 const { images, view } = await setup();
218 expect(images[0]!.src).toContain("stream.mjpeg");
171 - await act(async () => renderer!.update(view(false)));
172 - expect(renderer!.root.findAllByType("img")).toHaveLength(0);
219 + await act(async () => root.render(view(false)));
220 + expect(container.querySelectorAll("img")).toHaveLength(0);
221 expect(images[0]!.src).toBe("");
222 expect(vi.getTimerCount()).toBe(0);
175 - await act(async () => renderer!.update(view(true)));
223 + await act(async () => root.render(view(true)));
224 expect(images.at(-1)!.src).toContain("stream.mjpeg");
225 });
226
@@ -181,20 +229,14 @@ it("offers Reconnect after the shared timeout and receives a frame after retry w
229 await act(async () => {
230 await vi.advanceTimersByTimeAsync(15_000);
231 });
184 - expect(
185 - renderer!.root.findByProps({ role: "alert" }).findByType("span").children.join(""),
186 - ).toContain("No video");
232 + expect(alert()?.textContent).toContain("No video");
233 expect(images[0]!.src).toBe("");
188 - await act(async () => renderer!.root.findByType("button").props.onClick());
189 - expect(renderer!.root.findAllByProps({ role: "alert" })).toHaveLength(0);
234 + await reconnect();
235 + expect(alert()).toBeNull();
236 expect(images[1]!.src).toContain("stream.mjpeg");
191 - await act(async () => {
192 - images[1]!.naturalWidth = 400;
193 - images[1]!.naturalHeight = 800;
194 - images[1]!.dispatchEvent(new Event("load"));
195 - });
196 - expect(renderer!.root.findAllByProps({ role: "status" })).toHaveLength(0);
197 - expect(renderer!.root.findAllByType("button")).toHaveLength(0);
237 + await publishFrame(images[1]!);
238 + expect(container.querySelector('[role="status"]')).toBeNull();
239 + expect(container.querySelectorAll("button")).toHaveLength(0);
240 expect(vi.getTimerCount()).toBe(0);
241 });
242
@@ -204,7 +246,7 @@ it("starts exactly one new stream per Reconnect press", async () => {
246 await vi.advanceTimersByTimeAsync(15_000);
247 });
248 expect(primes).toBe(1);
207 - await act(async () => renderer!.root.findByType("button").props.onClick());
249 + await reconnect();
250 expect(primes).toBe(2);
251 });
252
@@ -225,7 +267,7 @@ it("keeps the 3D viewer mounted across iOS video recovery and releases it when h
267 });
268 await act(async () => frame());
269 expect(viewerMounts).toBe(1);
228 - await act(async () => renderer!.update(view(false)));
270 + await act(async () => root.render(view(false)));
271 expect(viewerUnmounts).toBe(1);
272 expect(vi.getTimerCount()).toBe(0);
273 });
apps/web/src/components/device/useDeviceControls.browser.test.tsx renamed
+42 -32
@@ -1,9 +1,9 @@
1 import { EnvironmentId, type DeviceDetail, type DeviceSummary } from "@t3tools/contracts";
2 import type { DeviceHubAccess } from "@t3tools/client-runtime/device/hub-access";
3 +import * as Cause from "effect/Cause";
4 import { act, useEffect } from "react";
4 -import { create, type ReactTestRenderer } from "react-test-renderer";
5 +import { createRoot, type Root } from "react-dom/client";
6 import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
6 -import { useDeviceControls, type DeviceControls } from "./useDeviceControls";
7
8 type Result = { _tag: "Success"; value: DeviceDetail } | { _tag: "Failure"; cause: unknown };
9 const { read, action, subscribe } = vi.hoisted(() => ({
@@ -12,13 +12,22 @@ const { read, action, subscribe } = vi.hoisted(() => ({
12 subscribe:
13 vi.fn<(_target: unknown, onChange: (app: { id: string } | null) => void) => () => void>(),
14 }));
15 -vi.mock("~/state/device", () => ({ deviceEnvironment: { detail: "detail", action: "action" } }));
16 -vi.mock("~/state/use-atom-command", () => ({
17 - useAtomCommand: (command: string) => (command === "detail" ? read : action),
15 +vi.mock(import("~/state/use-atom-command"), async (original) => {
16 + const { deviceEnvironment } = await import("~/state/device");
17 + return {
18 + ...(await original()),
19 + useAtomCommand: ((command: unknown) =>
20 + command === deviceEnvironment.detail ? read : action) as never,
21 + };
22 +});
23 +vi.mock(import("./deviceHubApi"), async (original) => ({
24 + ...(await original()),
25 + subscribeDeviceForeground: subscribe as never,
26 }));
19 -vi.mock("~/state/query", () => ({ formatEnvironmentQueryError: () => "Device action failed" }));
20 -vi.mock("./deviceHubApi", () => ({ subscribeDeviceForeground: subscribe }));
27
28 +import { useDeviceControls, type DeviceControls } from "./useDeviceControls";
29 +
30 +const offline = Cause.fail(new Error("Device offline"));
31 const device: DeviceSummary = {
32 hostId: "remote",
33 id: "phone",
@@ -45,7 +54,7 @@ function deferred() {
54 });
55 return { promise, resolve };
56 }
48 -let renderer: ReactTestRenderer | undefined;
57 +let root: Root;
58 let controls: DeviceControls;
59 function Probe({ visible, access = null }: { visible: boolean; access?: DeviceHubAccess | null }) {
60 const next = useDeviceControls({
@@ -66,14 +75,15 @@ beforeEach(() => {
75 subscribe.mockReset();
76 subscribe.mockReturnValue(() => {});
77 read.mockResolvedValue(snapshot("light"));
78 + root = createRoot(document.createElement("div"));
79 });
80 afterEach(async () => {
71 - await act(async () => renderer?.unmount());
81 + await act(async () => root.unmount());
82 vi.unstubAllGlobals();
83 });
84 async function mount() {
85 await act(async () => {
76 - renderer = create(<Probe visible />);
86 + root.render(<Probe visible />);
87 });
88 }
89
@@ -94,10 +104,10 @@ it("serializes rapid actions and retains confirmed settings while pending or aft
104 await pending;
105 });
106 expect(controls.detail?.settings.appearance).toBe("dark");
97 - action.mockResolvedValueOnce({ _tag: "Failure", cause: "offline" });
107 + action.mockResolvedValueOnce({ _tag: "Failure", cause: offline });
108 await act(async () => controls.act({ type: "setAppearance", value: "light" }));
109 expect(controls.detail?.settings.appearance).toBe("dark");
100 - expect(controls.error).toBe("Device action failed");
110 + expect(controls.error).toBe("Device offline");
111 expect(controls.disabled).toBe(false);
112 });
113
@@ -109,9 +119,9 @@ it("serializes host actions across hide/reopen and discards detached results", a
119 await act(async () => {
120 pending = controls.act({ type: "setAppearance", value: "dark" });
121 });
112 - await act(async () => renderer!.update(<Probe visible={false} />));
122 + await act(async () => root.render(<Probe visible={false} />));
123 expect(controls.disabled).toBe(true);
114 - await act(async () => renderer!.update(<Probe visible />));
124 + await act(async () => root.render(<Probe visible />));
125 await act(async () => controls.act({ type: "setAppearance", value: "light" }));
126 expect(action).toHaveBeenCalledOnce();
127 expect(controls.disabled).toBe(true);
@@ -143,36 +153,36 @@ it("keeps actions disabled when settings cannot be confirmed after a detached co
153 await act(async () => {
154 pending = controls.act({ type: "setAppearance", value: "dark" });
155 });
146 - await act(async () => renderer!.update(<Probe visible={false} />));
147 - await act(async () => renderer!.update(<Probe visible />));
148 - read.mockResolvedValueOnce({ _tag: "Failure", cause: "offline" });
156 + await act(async () => root.render(<Probe visible={false} />));
157 + await act(async () => root.render(<Probe visible />));
158 + read.mockResolvedValueOnce({ _tag: "Failure", cause: offline });
159 await act(async () => {
160 response.resolve(snapshot("dark"));
161 await pending;
162 });
163 expect(controls.detail).toBeNull();
164 expect(controls.disabled).toBe(true);
155 - expect(controls.error).toBe("Device action failed");
165 + expect(controls.error).toBe("Device offline");
166 await act(async () => controls.act({ type: "setAppearance", value: "light" }));
167 expect(action).toHaveBeenCalledOnce();
158 - await act(async () => renderer!.update(<Probe visible={false} />));
159 - await act(async () => renderer!.update(<Probe visible />));
168 + await act(async () => root.render(<Probe visible={false} />));
169 + await act(async () => root.render(<Probe visible />));
170 expect(controls.disabled).toBe(false);
171 expect(controls.error).toBeNull();
172 });
173
174 it("disables stale settings after a failed reopen read and recovers on a successful read", async () => {
175 await mount();
166 - await act(async () => renderer!.update(<Probe visible={false} />));
167 - read.mockResolvedValueOnce({ _tag: "Failure", cause: "offline" });
168 - await act(async () => renderer!.update(<Probe visible />));
176 + await act(async () => root.render(<Probe visible={false} />));
177 + read.mockResolvedValueOnce({ _tag: "Failure", cause: offline });
178 + await act(async () => root.render(<Probe visible />));
179 expect(controls.detail).toBeNull();
180 expect(controls.disabled).toBe(true);
171 - expect(controls.error).toBe("Device action failed");
181 + expect(controls.error).toBe("Device offline");
182 await act(async () => controls.act({ type: "setAppearance", value: "dark" }));
183 expect(action).not.toHaveBeenCalled();
174 - await act(async () => renderer!.update(<Probe visible={false} />));
175 - await act(async () => renderer!.update(<Probe visible />));
184 + await act(async () => root.render(<Probe visible={false} />));
185 + await act(async () => root.render(<Probe visible />));
186 expect(controls.detail?.settings.appearance).toBe("light");
187 expect(controls.disabled).toBe(false);
188 expect(controls.error).toBeNull();
@@ -180,10 +190,10 @@ it("disables stale settings after a failed reopen read and recovers on a success
190
191 it("does not let an older refresh overwrite a newer confirmed action", async () => {
192 await mount();
183 - await act(async () => renderer!.update(<Probe visible={false} />));
193 + await act(async () => root.render(<Probe visible={false} />));
194 const refresh = deferred();
195 read.mockReturnValueOnce(refresh.promise);
186 - await act(async () => renderer!.update(<Probe visible />));
196 + await act(async () => root.render(<Probe visible />));
197 action.mockResolvedValueOnce(snapshot("dark"));
198 await act(async () => controls.act({ type: "setAppearance", value: "dark" }));
199 await act(async () => {
@@ -209,17 +219,17 @@ it.each(["hidden", "access renewed"] as const)(
219 value: { ...detail.value, foregroundApp: { id: "snapshot.app" } },
220 });
221 await act(async () => {
212 - renderer = create(<Probe visible access={access} />);
222 + root.render(<Probe visible access={access} />);
223 });
224 const oldEvent = subscribe.mock.calls[0]![1];
225 await act(async () => oldEvent({ id: "previous.live.app" }));
226 expect(controls.foregroundApp?.id).toBe("previous.live.app");
227 if (restart === "hidden") {
218 - await act(async () => renderer!.update(<Probe visible={false} access={access} />));
219 - await act(async () => renderer!.update(<Probe visible access={access} />));
228 + await act(async () => root.render(<Probe visible={false} access={access} />));
229 + await act(async () => root.render(<Probe visible access={access} />));
230 } else {
231 await act(async () =>
222 - renderer!.update(<Probe visible access={{ ...access, query: { ticket: "renewed" } }} />),
232 + root.render(<Probe visible access={{ ...access, query: { ticket: "renewed" } }} />),
233 );
234 }
235 expect(controls.foregroundApp?.id).toBe("snapshot.app");
apps/web/src/components/diffs/DiffCommentAnnotation.test.tsx deleted
-84
@@ -1,84 +0,0 @@
1 -import { renderToStaticMarkup } from "react-dom/server";
2 -import { describe, expect, it, vi } from "vite-plus/test";
3 -
4 -import { DiffCommentAnnotation } from "./DiffCommentAnnotation";
5 -
6 -const callbacks = {
7 - onTextChange: vi.fn(),
8 - onCancel: vi.fn(),
9 - onComment: vi.fn(),
10 - onDelete: vi.fn(),
11 -};
12 -
13 -describe("DiffCommentAnnotation", () => {
14 - it("renders the shared draft composer directly in the selected diff", () => {
15 - const markup = renderToStaticMarkup(
16 - <DiffCommentAnnotation kind="draft" rangeLabel="+78" text="" {...callbacks} />,
17 - );
18 -
19 - expect(markup).toContain("font-sans");
20 - expect(markup).not.toContain("chat-composer-glass");
21 - expect(markup).not.toContain("font-mono");
22 - expect(markup).not.toContain("Local comment");
23 - expect(markup).not.toContain("on +78");
24 - expect(markup).toContain("⌘/Ctrl Enter to send");
25 - expect(markup).toContain("Add a comment…");
26 - expect(markup).toContain(">Comment</button>");
27 - expect(markup).toContain("autofocus");
28 - expect(markup).toMatch(/<span[^>]*data-size="sm"[^>]*data-slot="textarea-control"/);
29 - });
30 -
31 - it("lets a pull-request diff configure actions without replacing the composer", () => {
32 - const markup = renderToStaticMarkup(
33 - <DiffCommentAnnotation
34 - kind="draft"
35 - rangeLabel="src/app.ts:4"
36 - text=""
37 - {...callbacks}
38 - submitLabel="Add to review"
39 - secondaryAction={{
40 - label: "Add to agent",
41 - onAction: vi.fn(),
42 - }}
43 - />,
44 - );
45 -
46 - expect(markup).toContain("Add a comment…");
47 - expect(markup).toContain(">Add to review</button>");
48 - expect(markup.match(/<button[^>]*disabled[^>]*>Add to review<\/button>/)).not.toBeNull();
49 - expect(markup.match(/<button[^>]*disabled[^>]*>Add to agent<\/button>/)).not.toBeNull();
50 - });
51 -
52 - it("renders a saved comment without a nested card or redundant range label", () => {
53 - const markup = renderToStaticMarkup(
54 - <DiffCommentAnnotation
55 - kind="comment"
56 - rangeLabel="+78"
57 - text="Please keep this branch explicit."
58 - {...callbacks}
59 - />,
60 - );
61 -
62 - expect(markup).toContain("font-sans");
63 - expect(markup).not.toContain("chat-composer-glass");
64 - expect(markup).not.toContain("on +78");
65 - expect(markup).toContain("Please keep this branch explicit.");
66 - expect(markup).toContain('aria-label="Delete comment"');
67 - expect(markup).toContain("border-s-2");
68 - expect(markup).toContain("bg-primary/[0.045]");
69 - expect(markup).toContain("lucide-message-circle");
70 - });
71 -
72 - it("renders draft text owned by the annotation wrapper", () => {
73 - const markup = renderToStaticMarkup(
74 - <DiffCommentAnnotation
75 - kind="draft"
76 - rangeLabel="+78"
77 - text="Keep this unsaved draft"
78 - {...callbacks}
79 - />,
80 - );
81 -
82 - expect(markup).toContain("Keep this unsaved draft");
83 - });
84 -});
apps/web/src/components/diffs/DiffFileTree.browser.test.tsx renamed
+47 -56
@@ -1,8 +1,7 @@
1 import type { CodeViewScrollTarget } from "@pierre/diffs";
2 import type { FileTree as FileTreeModel } from "@pierre/trees";
3 -import { FileTree } from "@pierre/trees/react";
4 -import { act, type MouseEvent, type ReactNode } from "react";
5 -import { create, type ReactTestRenderer } from "react-test-renderer";
3 +import { act, type ComponentProps } from "react";
4 +import { createRoot, type Root } from "react-dom/client";
5 import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
6
7 import type { FileDiffMetadata } from "@pierre/diffs";
@@ -11,12 +10,19 @@ import { DiffFileTree, type DiffFileTreeEntry } from "./DiffFileTree";
10 import { diffFileTreeEntries } from "./diffFileTree.logic";
11 import { useCodeViewFileReveal } from "./useCodeViewFileReveal";
12
14 -vi.mock("../../hooks/useTheme", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
15 -vi.mock("../ui/tooltip", () => ({
16 - Tooltip: ({ children }: { children: ReactNode }) => children,
17 - TooltipTrigger: ({ render }: { render: ReactNode }) => render,
18 - TooltipPopup: () => null,
19 -}));
13 +const captured = vi.hoisted(() => ({ model: null as unknown }));
14 +// Read the tree model the component builds, so tests can assert its selection and expansion.
15 +vi.mock(import("@pierre/trees/react"), async (original) => {
16 + const actual = await original();
17 + const RealFileTree = actual.FileTree;
18 + return {
19 + ...actual,
20 + FileTree: ((props: ComponentProps<typeof RealFileTree>) => {
21 + captured.model = props.model;
22 + return <RealFileTree {...props} />;
23 + }) as typeof RealFileTree,
24 + };
25 +});
26
27 const entries: DiffFileTreeEntry[] = [
28 { path: "01-tall.ts", status: "modified" },
@@ -24,16 +30,9 @@ const entries: DiffFileTreeEntry[] = [
30 { path: "03-medium.ts", status: "modified" },
31 ];
32
27 -class TreeRow {
28 - constructor(readonly path: string) {}
29 -
30 - getAttribute(name: string) {
31 - return name === "data-item-path" ? this.path : null;
32 - }
33 -}
34 -
33 describe("diff tree file activation", () => {
36 - let renderer: ReactTestRenderer | undefined;
34 + let root: Root | undefined;
35 + let container: HTMLDivElement;
36 const targets: CodeViewScrollTarget[] = [];
37 const viewer = {
38 getInstance: () => viewer,
@@ -58,56 +57,48 @@ describe("diff tree file activation", () => {
57 );
58 }
59
61 - const model = (): FileTreeModel => renderer!.root.findByType(FileTree).props.model;
60 + const model = (): FileTreeModel => captured.model as FileTreeModel;
61
62 async function mount(props: Parameters<typeof Panel>[0] = {}) {
64 - await act(async () => {
65 - renderer = create(<Panel {...props} />);
66 - });
63 + root ??= createRoot(container);
64 + await act(async () => root!.render(<Panel {...props} />));
65 + }
66 +
67 + function row(path: string): HTMLElement {
68 + const host = container.querySelector("file-tree-container");
69 + const element = (host?.shadowRoot ?? container).querySelector<HTMLElement>(
70 + `[data-item-path="${CSS.escape(path)}"]`,
71 + );
72 + expect(element, `row ${path}`).not.toBeNull();
73 + return element!;
74 }
75
69 - async function activate(path: string, modifiers: Partial<MouseEvent<HTMLElement>> = {}) {
70 - const event = {
71 - button: 0,
72 - ctrlKey: false,
73 - metaKey: false,
74 - shiftKey: false,
75 - altKey: false,
76 - defaultPrevented: false,
77 - nativeEvent: { composedPath: () => [{}, new TreeRow(path), {}] },
78 - ...modifiers,
79 - } as MouseEvent<HTMLElement>;
76 + async function activate(path: string, modifiers: MouseEventInit = {}) {
77 await act(async () => {
81 - renderer!.root
82 - .find((node) => String(node.type) === "file-tree-container")
83 - .props.onClickCapture?.(event);
84 - const tree = model();
85 - const item = tree.getItem(path)!;
86 - if (event.ctrlKey || event.metaKey) {
87 - item.toggleSelect();
88 - } else {
89 - for (const selected of tree.getSelectedPaths()) {
90 - if (selected !== path) tree.getItem(selected)?.deselect();
91 - }
92 - item.select();
93 - }
94 - item.focus();
95 - if ("toggle" in item && !event.ctrlKey && !event.metaKey && !event.shiftKey) item.toggle();
78 + row(path).dispatchEvent(
79 + new MouseEvent("click", {
80 + bubbles: true,
81 + composed: true,
82 + button: 0,
83 + detail: 1,
84 + ...modifiers,
85 + }),
86 + );
87 });
88 }
89
90 beforeEach(() => {
91 targets.length = 0;
101 - vi.useFakeTimers();
92 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
103 - vi.stubGlobal("HTMLElement", TreeRow);
93 + container = document.createElement("div");
94 + container.style.cssText = "display: flex; flex-direction: column; width: 320px; height: 480px";
95 + document.body.append(container);
96 });
97
98 afterEach(async () => {
107 - await act(async () => renderer?.unmount());
108 - renderer = undefined;
109 - vi.runOnlyPendingTimers();
110 - vi.useRealTimers();
99 + await act(async () => root?.unmount());
100 + root = undefined;
101 + container.remove();
102 vi.unstubAllGlobals();
103 });
104
@@ -202,7 +193,7 @@ describe("diff tree file activation", () => {
193 if (!("collapse" in initialFolder)) throw new Error("Expected the directory handle");
194 await act(async () => initialFolder.collapse());
195 await act(async () => {
205 - renderer!.update(<Panel files={[files[1]!, files[0]!]} />);
196 + root!.render(<Panel files={[files[1]!, files[0]!]} />);
197 });
198 const folder = model().getItem("src/features/")!;
199 if (!("isExpanded" in folder)) throw new Error("Expected the directory handle");
@@ -216,7 +207,7 @@ describe("diff tree file activation", () => {
207 await activate("02-short.ts");
208 expect(targets).toHaveLength(1);
209 await act(async () => {
219 - renderer!.update(<Panel selectedPath="03-medium.ts" />);
210 + root!.render(<Panel selectedPath="03-medium.ts" />);
211 });
212 expect(model().getSelectedPaths()).toEqual(["03-medium.ts"]);
213 expect(targets).toHaveLength(1);
apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx new
+117
@@ -0,0 +1,117 @@
1 +import { EnvironmentId } from "@t3tools/contracts";
2 +import { act } from "react";
3 +import { createRoot, type Root } from "react-dom/client";
4 +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
5 +
6 +const { refresh } = vi.hoisted(() => ({ refresh: vi.fn<() => Promise<string | null>>() }));
7 +
8 +vi.mock(import("~/assets/assetUrls"), async (original) => ({
9 + ...(await original()),
10 + useAssetUrlRefresh: () => refresh,
11 +}));
12 +// The real source view highlights through a worker pool; the text it receives is what matters here.
13 +vi.mock(import("./ReadOnlySourcePreview"), async (original) => ({
14 + ...(await original()),
15 + default: ({ text }: { text: string }) => <pre>{text}</pre>,
16 +}));
17 +
18 +import { AttachmentFilePreview } from "./AttachmentFilePreview";
19 +
20 +describe("attachment HTML preview recovery", () => {
21 + const originalUrl = "data:text/html,original";
22 + const renewedUrl = "data:text/html,renewed";
23 + let now = 0;
24 + let root: Root;
25 + let container: HTMLDivElement;
26 +
27 + beforeEach(() => {
28 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
29 + now = 0;
30 + vi.spyOn(Date, "now").mockImplementation(() => now);
31 + refresh.mockReset().mockResolvedValueOnce(originalUrl).mockResolvedValue(renewedUrl);
32 + vi.stubGlobal(
33 + "fetch",
34 + vi.fn(async () => new Response("<p>Captured HTML</p>")),
35 + );
36 + container = document.createElement("div");
37 + document.body.append(container);
38 + root = createRoot(container);
39 + });
40 +
41 + afterEach(async () => {
42 + await act(async () => root.unmount());
43 + container.remove();
44 + vi.restoreAllMocks();
45 + vi.unstubAllGlobals();
46 + });
47 +
48 + const openRemote = () =>
49 + act(async () =>
50 + root.render(
51 + <AttachmentFilePreview
52 + name="document.html"
53 + mimeType="text/html"
54 + sizeBytes={100}
55 + asset={{ environmentId: EnvironmentId.make("test-environment"), attachmentId: "html" }}
56 + />,
57 + ),
58 + );
59 +
60 + const toggleMode = async (label: string) => {
61 + const button = container.querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`);
62 + expect(button, label).not.toBeNull();
63 + await act(async () => button!.click());
64 + };
65 + const alert = () => container.querySelector('[role="alert"]');
66 +
67 + it("keeps a renewed URL for subsequent rendered and source views", async () => {
68 + await openRemote();
69 + expect(container.querySelector("iframe")?.getAttribute("src")).toBe(originalUrl);
70 + now = 61 * 60_000;
71 + await toggleMode("Show HTML source");
72 + expect(fetch).toHaveBeenCalledExactlyOnceWith(renewedUrl, expect.any(Object));
73 + await vi.waitFor(() =>
74 + expect(container.querySelector("pre")?.textContent).toBe("<p>Captured HTML</p>"),
75 + );
76 +
77 + await toggleMode("Show rendered page");
78 + expect(container.querySelector("iframe")?.getAttribute("src")).toBe(renewedUrl);
79 + await toggleMode("Show HTML source");
80 + expect(refresh).toHaveBeenCalledTimes(2);
81 + expect(vi.mocked(fetch).mock.calls.map(([url]) => url)).toEqual([renewedUrl, renewedUrl]);
82 + });
83 +
84 + it("does not fetch or mark an expired URL fresh when reauthorization is unavailable", async () => {
85 + await openRemote();
86 + now = 61 * 60_000;
87 + refresh.mockResolvedValue(null);
88 + await toggleMode("Show HTML source");
89 + expect(fetch).not.toHaveBeenCalled();
90 + expect(alert()?.textContent).toContain("Reconnect to the environment and try again.");
91 +
92 + await toggleMode("Show rendered page");
93 + await toggleMode("Show HTML source");
94 + expect(refresh).toHaveBeenCalledTimes(3);
95 + expect(fetch).not.toHaveBeenCalled();
96 + });
97 +
98 + it("can return to rendered HTML after local source decoding fails", async () => {
99 + const file = new Blob([new Uint8Array([0x3c, 0x70, 0x3e, 0xe9])], { type: "text/html" });
100 + await act(async () =>
101 + root.render(
102 + <AttachmentFilePreview
103 + name="document.html"
104 + mimeType="text/html"
105 + sizeBytes={file.size}
106 + file={file}
107 + />,
108 + ),
109 + );
110 + await toggleMode("Show HTML source");
111 + await vi.waitFor(() => expect(alert()?.textContent).toContain("not UTF-8"));
112 +
113 + await toggleMode("Show rendered page");
114 + expect(alert()).toBeNull();
115 + expect(container.querySelector("iframe")?.title).toBe("document.html");
116 + });
117 +});
apps/web/src/components/files/AttachmentFilePreview.test.tsx deleted
-133
@@ -1,133 +0,0 @@
1 -import { EnvironmentId } from "@t3tools/contracts";
2 -import { act, type ReactNode } from "react";
3 -import { create, type ReactTestRenderer } from "react-test-renderer";
4 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
5 -
6 -import { AttachmentFilePreview } from "./AttachmentFilePreview";
7 -
8 -const { refresh } = vi.hoisted(() => ({ refresh: vi.fn<() => Promise<string | null>>() }));
9 -
10 -vi.mock("~/assets/assetUrls", () => ({ useAssetUrlRefresh: () => refresh }));
11 -vi.mock("~/hooks/useCopyToClipboard", () => ({
12 - useCopyToClipboard: () => ({ copyToClipboard: vi.fn(), isCopied: false }),
13 -}));
14 -vi.mock("~/components/ui/toast", () => ({ toastManager: { add: vi.fn() } }));
15 -vi.mock("~/components/ChatMarkdown", () => ({ default: () => null }));
16 -vi.mock("~/components/ui/scroll-area", () => ({
17 - ScrollArea: ({ children }: { children: ReactNode }) => children,
18 -}));
19 -vi.mock("./ReadOnlySourcePreview", () => ({
20 - default: ({ text }: { text: string }) => <pre>{text}</pre>,
21 -}));
22 -vi.mock("./fileSurfaceChrome", () => ({
23 - FILE_SURFACE_SUBHEADER_CLASS: "",
24 - FileSurfaceAction: ({ label, onPress }: { label: string; onPress: () => void }) => (
25 - <button aria-label={label} onClick={onPress} />
26 - ),
27 - FileSurfaceFailure: ({ message }: { message: string }) => <div role="alert">{message}</div>,
28 - FileSurfaceLoading: () => <div role="status">Loading</div>,
29 - FileSurfaceNotice: ({ children }: { children: ReactNode }) => <div>{children}</div>,
30 -}));
31 -
32 -describe("attachment HTML preview recovery", () => {
33 - const originalUrl = "https://environment.test/original.html";
34 - const renewedUrl = "https://environment.test/renewed.html";
35 - let now = 0;
36 - let renderer: ReactTestRenderer;
37 -
38 - beforeEach(() => {
39 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
40 - now = 0;
41 - vi.spyOn(Date, "now").mockImplementation(() => now);
42 - refresh.mockReset().mockResolvedValueOnce(originalUrl).mockResolvedValue(renewedUrl);
43 - vi.stubGlobal(
44 - "fetch",
45 - vi.fn(async () => new Response("<p>Captured HTML</p>")),
46 - );
47 - });
48 -
49 - afterEach(async () => {
50 - if (renderer) await act(() => renderer.unmount());
51 - vi.restoreAllMocks();
52 - vi.unstubAllGlobals();
53 - });
54 -
55 - const openRemote = async () => {
56 - await act(async () => {
57 - renderer = create(
58 - <AttachmentFilePreview
59 - name="document.html"
60 - mimeType="text/html"
61 - sizeBytes={100}
62 - asset={{ environmentId: EnvironmentId.make("test-environment"), attachmentId: "html" }}
63 - />,
64 - );
65 - });
66 - };
67 -
68 - const toggleMode = async (label: string) => {
69 - await act(async () => {
70 - renderer.root.findByProps({ "aria-label": label }).props.onClick();
71 - });
72 - };
73 -
74 - it("keeps a renewed URL for subsequent rendered and source views", async () => {
75 - await openRemote();
76 - now = 61 * 60_000;
77 - await toggleMode("Show HTML source");
78 - expect(fetch).toHaveBeenCalledExactlyOnceWith(renewedUrl, expect.any(Object));
79 -
80 - await toggleMode("Show rendered page");
81 - expect(renderer.root.findByType("iframe").props.src).toBe(renewedUrl);
82 - await toggleMode("Show HTML source");
83 - expect(refresh).toHaveBeenCalledTimes(2);
84 - expect(fetch).toHaveBeenCalledTimes(2);
85 - expect(vi.mocked(fetch).mock.calls.map(([url]) => url)).toEqual([renewedUrl, renewedUrl]);
86 - });
87 -
88 - it("does not fetch or mark an expired URL fresh when reauthorization is unavailable", async () => {
89 - await openRemote();
90 - now = 61 * 60_000;
91 - refresh.mockResolvedValue(null);
92 - await toggleMode("Show HTML source");
93 - expect(fetch).not.toHaveBeenCalled();
94 - expect(renderer.root.findByProps({ role: "alert" }).children).toEqual([
95 - "Reconnect to the environment and try again.",
96 - ]);
97 -
98 - await toggleMode("Show rendered page");
99 - await toggleMode("Show HTML source");
100 - expect(refresh).toHaveBeenCalledTimes(3);
101 - expect(fetch).not.toHaveBeenCalled();
102 - });
103 -
104 - it("can return to rendered HTML after local source decoding fails", async () => {
105 - const bytes = new Uint8Array([0x3c, 0x70, 0x3e, 0xe9]);
106 - const file = new Blob([bytes], { type: "text/html" });
107 - vi.spyOn(file, "stream").mockImplementation(
108 - () =>
109 - new ReadableStream({
110 - start: (controller) => {
111 - controller.enqueue(bytes);
112 - controller.close();
113 - },
114 - }),
115 - );
116 - await act(async () => {
117 - renderer = create(
118 - <AttachmentFilePreview
119 - name="document.html"
120 - mimeType="text/html"
121 - sizeBytes={file.size}
122 - file={file}
123 - />,
124 - );
125 - });
126 - await toggleMode("Show HTML source");
127 - expect(renderer.root.findByProps({ role: "alert" }).children.join("")).toContain("not UTF-8");
128 -
129 - await toggleMode("Show rendered page");
130 - expect(renderer.root.findAllByProps({ role: "alert" })).toHaveLength(0);
131 - expect(renderer.root.findByType("iframe").props.title).toBe("document.html");
132 - });
133 -});
apps/web/src/components/files/useFileSaveCoordinator.browser.test.tsx renamed
+48 -58
@@ -1,7 +1,7 @@
1 import { EnvironmentId } from "@t3tools/contracts";
2 import { AsyncResult } from "effect/reactivity";
3 -import { act, StrictMode } from "react";
4 -import { create, type ReactTestRenderer } from "react-test-renderer";
3 +import { act, StrictMode, useEffect } from "react";
4 +import { createRoot, type Root } from "react-dom/client";
5 import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
6
7 const { writeFile, confirmFile, readScope, getUnsavedFile } = vi.hoisted(() => ({
@@ -10,13 +10,17 @@ const { writeFile, confirmFile, readScope, getUnsavedFile } = vi.hoisted(() => (
10 readScope: vi.fn(),
11 getUnsavedFile: vi.fn(),
12 }));
13 -vi.mock("~/state/projects", () => ({ projectEnvironment: { writeFile: {} } }));
14 -vi.mock("~/state/session", () => ({
13 +vi.mock(import("~/state/session"), async (original) => ({
14 + ...(await original()),
15 readEnvironmentScope: readScope,
16 useEnvironmentScope: readScope,
17 }));
18 -vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => writeFile }));
19 -vi.mock("./projectFilesQueryState", () => ({
18 +vi.mock(import("~/state/use-atom-command"), async (original) => ({
19 + ...(await original()),
20 + useAtomCommand: (() => writeFile) as never,
21 +}));
22 +vi.mock(import("./projectFilesQueryState"), async (original) => ({
23 + ...(await original()),
24 confirmProjectFileQueryData: confirmFile,
25 getUnsavedProjectFileQueryData: getUnsavedFile,
26 }));
@@ -32,33 +36,40 @@ const defaultProps = {
36 relativePath: "file.txt",
37 onPendingChange,
38 };
35 -let renderer: ReactTestRenderer | null;
36 -
37 -function ChangeSource(_props: { onChange: (contents: string) => void }) {
38 - return null;
39 -}
39 +let root: Root | null;
40 +// The editor's change callback from the latest commit, as an editor would hold it.
41 +let latestChange: (contents: string) => void;
42
43 function FileSurface(props: Parameters<typeof useFileSaveCoordinator>[0]) {
44 const coordinator = useFileSaveCoordinator(props);
43 - return <ChangeSource onChange={(contents) => coordinator.change(contents)} />;
45 + const onChange = (contents: string) => coordinator.change(contents);
46 + useEffect(() => {
47 + latestChange = onChange;
48 + });
49 + return null;
50 }
51
46 -function mount(props = defaultProps) {
47 - act(() => {
48 - renderer = create(
52 +async function render(props = defaultProps) {
53 + root ??= createRoot(document.createElement("div"));
54 + await act(async () =>
55 + root!.render(
56 <StrictMode>
57 <FileSurface {...props} />
58 </StrictMode>,
52 - );
53 - });
59 + ),
60 + );
61 }
62 +const mount = render;
63
56 -function changeHandler(): (contents: string) => void {
57 - return renderer!.root.findByType(ChangeSource).props.onChange;
64 +async function unmountSurface() {
65 + await act(async () => root!.unmount());
66 + root = null;
67 }
68
69 +const changeHandler = () => latestChange;
70 +
71 beforeEach(() => {
61 - renderer = null;
72 + root = null;
73 vi.useFakeTimers();
74 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
75 writeFile.mockReset().mockResolvedValue(AsyncResult.success(undefined));
@@ -69,14 +80,14 @@ beforeEach(() => {
80 });
81
82 afterEach(async () => {
72 - await act(async () => renderer?.unmount());
83 + if (root) await unmountSurface();
84 vi.useRealTimers();
85 vi.unstubAllGlobals();
86 });
87
88 describe("file-save React lifecycle", () => {
89 it("persists editor model changes after StrictMode setup replay", async () => {
79 - mount();
90 + await mount();
91 changeHandler()("AUDIT7907NATIVE\n");
92 expect(onPendingChange).toHaveBeenCalledWith("file.txt", true);
93 await vi.advanceTimersByTimeAsync(500);
@@ -94,7 +105,7 @@ describe("file-save React lifecycle", () => {
105 });
106
107 it("persists rendered Markdown task changes after StrictMode setup replay", async () => {
97 - mount({ ...defaultProps, relativePath: "README.md" });
108 + await mount({ ...defaultProps, relativePath: "README.md" });
109 const nextContents = setMarkdownTaskChecked("- [ ] task\n", 2, true);
110 changeHandler()(nextContents);
111 await vi.advanceTimersByTimeAsync(500);
@@ -105,16 +116,10 @@ describe("file-save React lifecycle", () => {
116 });
117
118 it("keeps the debounce across rerenders of the same file", async () => {
108 - mount();
119 + await mount();
120 changeHandler()("first");
121 await vi.advanceTimersByTimeAsync(300);
111 - act(() =>
112 - renderer!.update(
113 - <StrictMode>
114 - <FileSurface {...defaultProps} />
115 - </StrictMode>,
116 - ),
117 - );
122 + await render(defaultProps);
123 changeHandler()("latest");
124 await vi.advanceTimersByTimeAsync(499);
125 expect(writeFile).not.toHaveBeenCalled();
@@ -124,11 +129,10 @@ describe("file-save React lifecycle", () => {
129 });
130
131 it("flushes on unmount and ignores a retired editor callback", async () => {
127 - mount();
132 + await mount();
133 const retiredChange = changeHandler();
134 retiredChange("pending edit");
130 - await act(async () => renderer!.unmount());
131 - renderer = null;
135 + await unmountSurface();
136 retiredChange("stale editor contents");
137 await vi.runAllTimersAsync();
138 expect(writeFile).toHaveBeenCalledTimes(1);
@@ -138,12 +142,11 @@ describe("file-save React lifecycle", () => {
142 it.each([false, true])(
143 "keeps edits pending after permission is revoked before a React update (unmount: %s)",
144 async (unmount) => {
141 - mount();
145 + await mount();
146 changeHandler()("pending edit");
147 readScope.mockReturnValue(false);
148 if (unmount) {
145 - await act(async () => renderer!.unmount());
146 - renderer = null;
149 + await unmountSurface();
150 }
151 await vi.runAllTimersAsync();
152 expect(writeFile).not.toHaveBeenCalled();
@@ -155,18 +158,12 @@ describe("file-save React lifecycle", () => {
158 it("resumes an unsaved draft when write permission returns after effect replay", async () => {
159 readScope.mockReturnValue(false);
160 getUnsavedFile.mockReturnValue({ contents: "pending draft" });
158 - mount();
161 + await mount();
162 await vi.runAllTimersAsync();
163 expect(writeFile).not.toHaveBeenCalled();
164
165 readScope.mockReturnValue(true);
163 - act(() =>
164 - renderer!.update(
165 - <StrictMode>
166 - <FileSurface {...defaultProps} />
167 - </StrictMode>,
168 - ),
169 - );
166 + await render(defaultProps);
167 await vi.advanceTimersByTimeAsync(500);
168 expect(writeFile).toHaveBeenCalledExactlyOnceWith({
169 environmentId,
@@ -177,7 +174,7 @@ describe("file-save React lifecycle", () => {
174
175 it("recovers an existing draft once after StrictMode setup replay", async () => {
176 getUnsavedFile.mockReturnValue({ contents: "reopened draft" });
180 - mount();
177 + await mount();
178 await vi.runAllTimersAsync();
179 expect(writeFile).toHaveBeenCalledExactlyOnceWith({
180 environmentId,
@@ -191,17 +188,11 @@ describe("file-save React lifecycle", () => {
188 { cwd: "/other-workspace" },
189 { environmentId: EnvironmentId.make("other-environment") },
190 ])("retires callbacks when the file identity changes: %j", async (change) => {
194 - mount();
191 + await mount();
192 const retiredChange = changeHandler();
193 retiredChange("old file edit");
194 const nextProps = { ...defaultProps, ...change };
198 - act(() =>
199 - renderer!.update(
200 - <StrictMode>
201 - <FileSurface {...nextProps} />
202 - </StrictMode>,
203 - ),
204 - );
195 + await render(nextProps);
196 retiredChange("stale editor contents");
197 changeHandler()("new file edit");
198 await vi.runAllTimersAsync();
@@ -222,11 +213,10 @@ describe("file-save React lifecycle", () => {
213 });
214
215 it("does not reactivate a retired callback when the same file mounts again", async () => {
225 - mount();
216 + await mount();
217 const retiredChange = changeHandler();
227 - await act(async () => renderer!.unmount());
228 - renderer = null;
229 - mount();
218 + await unmountSurface();
219 + await mount();
220 retiredChange("stale contents");
221 changeHandler()("current contents");
222 await vi.runAllTimersAsync();
apps/web/src/components/preview/PreviewEmptyState.browser.test.tsx new
+113
@@ -0,0 +1,113 @@
1 +import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2 +import { act } from "react";
3 +import { createRoot, type Root } from "react-dom/client";
4 +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
5 +
6 +import type { PreviewableServer } from "./useDiscoveredLocalServers";
7 +
8 +const mocks = vi.hoisted(() => ({ servers: [] as PreviewableServer[] }));
9 +
10 +vi.mock(import("./useDiscoveredLocalServers"), async (original) => ({
11 + ...(await original()),
12 + useDiscoveredLocalServers: () => mocks.servers,
13 +}));
14 +
15 +import { PreviewEmptyState } from "./PreviewEmptyState";
16 +
17 +const environmentId = EnvironmentId.make("env-1");
18 +const threadRef = { environmentId, threadId: ThreadId.make("thread-1") };
19 +const onOpenUrl = vi.fn();
20 +const onRemoveRecent = vi.fn();
21 +
22 +let root: Root;
23 +let container: HTMLDivElement;
24 +
25 +function server(port: number): PreviewableServer {
26 + return {
27 + host: "localhost",
28 + port,
29 + url: `http://localhost:${port}`,
30 + requestedUrl: `http://localhost:${port}`,
31 + processName: "node",
32 + pid: 1,
33 + terminal: null,
34 + source: "scanner",
35 + } as PreviewableServer;
36 +}
37 +
38 +beforeEach(() => {
39 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
40 + vi.clearAllMocks();
41 + mocks.servers = [];
42 + container = document.createElement("div");
43 + document.body.append(container);
44 + root = createRoot(container);
45 +});
46 +
47 +afterEach(async () => {
48 + await act(async () => root.unmount());
49 + container.remove();
50 + vi.unstubAllGlobals();
51 +});
52 +
53 +async function render(
54 + recentEntries: Array<{ url: string; lastVisitedAt: number; title?: string }>,
55 +) {
56 + await act(async () =>
57 + root.render(
58 + <PreviewEmptyState
59 + threadRef={threadRef}
60 + environmentId={environmentId}
61 + recentEntries={recentEntries}
62 + onRemoveRecent={onRemoveRecent}
63 + onOpenUrl={onOpenUrl}
64 + />,
65 + ),
66 + );
67 +}
68 +
69 +function button(name: string) {
70 + const match = [...container.querySelectorAll("button")].find(
71 + (element) => element.getAttribute("aria-label") === name || element.textContent?.includes(name),
72 + );
73 + expect(match, `button ${name}`).toBeDefined();
74 + return match!;
75 +}
76 +
77 +describe("PreviewEmptyState", () => {
78 + it("lists a recent entry and a live server matching its host:port, and opens or forgets entries", async () => {
79 + mocks.servers = [server(5173)];
80 + await render([
81 + { url: "https://myapp.test/admin#users", lastVisitedAt: Date.now(), title: "Admin" },
82 + { url: "http://localhost:5173/", lastVisitedAt: Date.now(), title: "Recent Local" },
83 + ]);
84 + const text = container.textContent;
85 + expect(text).toContain("Recently used");
86 + expect(text).toContain("Local servers");
87 + expect(text).toContain("Recent Local");
88 + expect(text).toContain("node");
89 +
90 + await act(async () => button("Admin").click());
91 + expect(onOpenUrl).toHaveBeenCalledExactlyOnceWith("https://myapp.test/admin#users");
92 +
93 + await act(async () => button("Remove myapp.test/admin#users from history").click());
94 + expect(onRemoveRecent).toHaveBeenCalledExactlyOnceWith("https://myapp.test/admin#users");
95 + });
96 +
97 + it("shows only the recents group when no servers are found", async () => {
98 + await render([{ url: "https://myapp.test/", lastVisitedAt: 0 }]);
99 + expect(container.textContent).toContain("Recently used");
100 + expect(container.textContent).not.toContain("Local servers");
101 + });
102 +
103 + it("keeps the original empty state when both groups are empty", async () => {
104 + await render([]);
105 + expect(container.textContent).toContain("No preview yet");
106 + });
107 +
108 + it("shows an entry with an out-of-range lastVisitedAt instead of crashing", async () => {
109 + await render([{ url: "https://myapp.test/", lastVisitedAt: 1e20 }]);
110 + expect(container.textContent).toContain("myapp.test");
111 + button("Remove myapp.test from history");
112 + });
113 +});
apps/web/src/components/preview/PreviewEmptyState.test.tsx deleted
-92
@@ -1,92 +0,0 @@
1 -import { EnvironmentId, ThreadId } from "@t3tools/contracts";
2 -import { renderToStaticMarkup } from "react-dom/server";
3 -import { describe, expect, it, vi } from "vite-plus/test";
4 -
5 -const mocks = vi.hoisted(() => ({
6 - servers: [] as Array<{
7 - host: string;
8 - port: number;
9 - url: string;
10 - requestedUrl: string;
11 - processName: string | null;
12 - pid: number | null;
13 - terminal: null;
14 - source: "scanner";
15 - }>,
16 -}));
17 -
18 -vi.mock("./useDiscoveredLocalServers", () => ({
19 - useDiscoveredLocalServers: () => mocks.servers,
20 -}));
21 -vi.mock("./PreviewFaviconIcon", () => ({
22 - PreviewFaviconIcon: () => <span data-favicon-icon />,
23 -}));
24 -
25 -import { PreviewEmptyState } from "./PreviewEmptyState";
26 -
27 -const environmentId = EnvironmentId.make("env-1");
28 -const threadRef = { environmentId, threadId: ThreadId.make("thread-1") };
29 -
30 -function server(port: number) {
31 - return {
32 - host: "localhost",
33 - port,
34 - url: `http://localhost:${port}`,
35 - requestedUrl: `http://localhost:${port}`,
36 - processName: "node",
37 - pid: 1,
38 - terminal: null,
39 - source: "scanner" as const,
40 - };
41 -}
42 -
43 -function render(recentEntries: Array<{ url: string; lastVisitedAt: number; title?: string }>) {
44 - return renderToStaticMarkup(
45 - <PreviewEmptyState
46 - threadRef={threadRef}
47 - environmentId={environmentId}
48 - recentEntries={recentEntries}
49 - onRemoveRecent={() => undefined}
50 - onOpenUrl={() => undefined}
51 - />,
52 - );
53 -}
54 -
55 -describe("PreviewEmptyState", () => {
56 - it("renders a history entry in both groups when its host:port matches a live server", () => {
57 - mocks.servers = [server(5173)];
58 - const html = render([
59 - { url: "https://myapp.test/admin#users", lastVisitedAt: Date.now(), title: "Admin" },
60 - { url: "http://localhost:5173/", lastVisitedAt: Date.now(), title: "Recent Local" },
61 - ]);
62 - expect(html).toContain("Recently used");
63 - expect(html).toContain("Local servers");
64 - expect(html).toContain("myapp.test/admin#users");
65 - expect(html).toContain("Admin");
66 - expect(html).toContain("Recent Local");
67 - expect(html).toContain("node");
68 - });
69 -
70 - it("renders only the recents group when no servers are found", () => {
71 - mocks.servers = [];
72 - const html = render([{ url: "https://myapp.test/", lastVisitedAt: 0 }]);
73 - expect(html).toContain("Recently used");
74 - expect(html).not.toContain("Local servers");
75 - });
76 -
77 - it("keeps the original empty state when both groups are empty", () => {
78 - mocks.servers = [];
79 - const html = render([]);
80 - expect(html).toContain("No preview yet");
81 - });
82 -
83 - it("renders an out-of-range lastVisitedAt entry without throwing", () => {
84 - mocks.servers = [];
85 - let html = "";
86 - expect(() => {
87 - html = render([{ url: "https://myapp.test/", lastVisitedAt: 1e20 }]);
88 - }).not.toThrow();
89 - expect(html).toContain("myapp.test");
90 - expect(html).toContain("Remove");
91 - });
92 -});
apps/web/src/components/preview/PreviewFaviconIcon.browser.test.tsx new
+49
@@ -0,0 +1,49 @@
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 { FaviconImage } from "./PreviewFaviconIcon";
6 +
7 +const GIF = "data:image/gif;base64,R0lGODlhAQABAAAAACw=";
8 +const captured = `${GIF}#captured`;
9 +const remote = `${GIF}#remote`;
10 +
11 +let root: Root;
12 +let container: HTMLDivElement;
13 +
14 +beforeEach(() => {
15 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
16 + container = document.createElement("div");
17 + document.body.append(container);
18 + root = createRoot(container);
19 +});
20 +
21 +afterEach(async () => {
22 + await act(async () => root.unmount());
23 + container.remove();
24 + vi.unstubAllGlobals();
25 +});
26 +
27 +const image = () => container.querySelector("img");
28 +const failImage = () => act(async () => image()!.dispatchEvent(new Event("error")));
29 +
30 +it("falls through failed favicon sources and retries when the source list changes", async () => {
31 + await act(async () =>
32 + root.render(<FaviconImage sources={[captured, remote]} fallback={<span>fallback</span>} />),
33 + );
34 + expect(image()?.getAttribute("src")).toBe(captured);
35 +
36 + await failImage();
37 + expect(image()?.getAttribute("src")).toBe(remote);
38 +
39 + await failImage();
40 + expect(image()).toBeNull();
41 + expect(container.textContent).toBe("fallback");
42 +
43 + await act(async () =>
44 + root.render(
45 + <FaviconImage sources={[captured, `${GIF}#new-icon`]} fallback={<span>fallback</span>} />,
46 + ),
47 + );
48 + expect(image()?.getAttribute("src")).toBe(captured);
49 +});
apps/web/src/components/preview/PreviewFaviconIcon.test.tsx deleted
-43
@@ -1,43 +0,0 @@
1 -import { act } from "react";
2 -import { create, type ReactTestRenderer } from "react-test-renderer";
3 -import { afterEach, expect, it, vi } from "vite-plus/test";
4 -
5 -vi.mock("~/browserFaviconStore", () => ({ useFaviconForThreadUrl: () => null }));
6 -
7 -import { FaviconImage } from "./PreviewFaviconIcon";
8 -
9 -let renderer: ReactTestRenderer | undefined;
10 -
11 -afterEach(async () => {
12 - await act(async () => renderer?.unmount());
13 - vi.unstubAllGlobals();
14 -});
15 -
16 -it("falls through failed favicon sources and retries when the source list changes", async () => {
17 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
18 - const captured = "data:image/png;base64,AAAA";
19 - const remote = "https://public.example/icon";
20 - await act(async () => {
21 - renderer = create(
22 - <FaviconImage sources={[captured, remote]} fallback={<span>fallback</span>} />,
23 - );
24 - });
25 - expect(renderer!.root.findByType("img").props.src).toBe(captured);
26 -
27 - await act(async () => renderer!.root.findByType("img").props.onError());
28 - expect(renderer!.root.findByType("img").props.src).toBe(remote);
29 -
30 - await act(async () => renderer!.root.findByType("img").props.onError());
31 - expect(renderer!.root.findAllByType("img")).toHaveLength(0);
32 - expect(renderer!.root.findByType("span").children).toEqual(["fallback"]);
33 -
34 - await act(async () => {
35 - renderer!.update(
36 - <FaviconImage
37 - sources={[captured, "https://public.example/new-icon"]}
38 - fallback={<span>fallback</span>}
39 - />,
40 - );
41 - });
42 - expect(renderer!.root.findByType("img").props.src).toBe(captured);
43 -});
apps/web/src/components/projectScriptEditor.browser.test.tsx new
+179
@@ -0,0 +1,179 @@
1 +import { EnvironmentId } from "@t3tools/contracts";
2 +import * as Cause from "effect/Cause";
3 +import { AsyncResult } from "effect/reactivity";
4 +import { act, StrictMode } from "react";
5 +import { createRoot, type Root } from "react-dom/client";
6 +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
7 +
8 +vi.mock(import("~/state/session"), async (original) => ({
9 + ...(await original()),
10 + readEnvironmentScope: () => true,
11 + useEnvironmentScope: () => true,
12 +}));
13 +
14 +import {
15 + EMPTY_PROJECT_SCRIPT_INPUT,
16 + ProjectScriptEditorDialog,
17 + type ProjectScriptActionResult,
18 + type ProjectScriptEditorRequest,
19 +} from "./projectScriptEditor";
20 +
21 +const onSubmit = vi.fn<Parameters<typeof ProjectScriptEditorDialog>[0]["onSubmit"]>();
22 +const onClose = vi.fn();
23 +const onDelete = vi.fn();
24 +let root: Root;
25 +let mounted: boolean;
26 +
27 +function request(name: string, error?: string): ProjectScriptEditorRequest {
28 + return {
29 + scriptId: name,
30 + initial: { ...EMPTY_PROJECT_SCRIPT_INPUT, name, command: `run-${name}` },
31 + ...(error === undefined ? {} : { error }),
32 + };
33 +}
34 +
35 +const open = (nextRequest: ProjectScriptEditorRequest) =>
36 + act(async () =>
37 + root.render(
38 + <StrictMode>
39 + <ProjectScriptEditorDialog
40 + environmentId={EnvironmentId.make("test")}
41 + request={nextRequest}
42 + scripts={[]}
43 + onSubmit={onSubmit}
44 + onClose={onClose}
45 + onDelete={onDelete}
46 + />
47 + </StrictMode>,
48 + ),
49 + );
50 +
51 +const submit = () => document.querySelector("form")!.requestSubmit();
52 +const button = (label: string) =>
53 + [...document.querySelectorAll("button")].find((element) => element.textContent === label)!;
54 +const saveButton = () => document.querySelector<HTMLButtonElement>('button[type="submit"]')!;
55 +const fieldset = () => document.querySelector("fieldset")!;
56 +const messages = () => [...document.querySelectorAll("form p")].map((p) => p.textContent);
57 +
58 +function deferredSave() {
59 + let resolve!: (result: ProjectScriptActionResult) => void;
60 + let reject!: (error: Error) => void;
61 + const promise = new Promise<ProjectScriptActionResult>((resolveResult, rejectResult) => {
62 + resolve = resolveResult;
63 + reject = rejectResult;
64 + });
65 + return { promise, resolve, reject };
66 +}
67 +
68 +beforeEach(() => {
69 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
70 + onSubmit.mockReset();
71 + onClose.mockReset();
72 + onDelete.mockReset();
73 + root = createRoot(document.createElement("div"));
74 + mounted = true;
75 +});
76 +
77 +afterEach(async () => {
78 + if (mounted) await act(async () => root.unmount());
79 + vi.unstubAllGlobals();
80 +});
81 +
82 +describe("project action editor save lifecycle", () => {
83 + it("blocks repeated submits and edits until the current save completes", async () => {
84 + const save = deferredSave();
85 + onSubmit.mockReturnValue(save.promise);
86 + await open(request("build"));
87 +
88 + await act(async () => {
89 + submit();
90 + submit();
91 + });
92 +
93 + expect(onSubmit).toHaveBeenCalledTimes(1);
94 + expect(saveButton().disabled).toBe(true);
95 + expect(saveButton().textContent).toBe("Saving…");
96 + expect(fieldset().disabled).toBe(true);
97 + expect(button("Cancel").disabled).toBe(false);
98 +
99 + await act(async () => save.resolve(AsyncResult.success(undefined)));
100 + expect(onClose).toHaveBeenCalledTimes(1);
101 + });
102 +
103 + it("does not close a replacement request or release its in-flight save", async () => {
104 + const first = deferredSave();
105 + const second = deferredSave();
106 + onSubmit.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);
107 + await open(request("build"));
108 + await act(async () => submit());
109 +
110 + await open(request("test"));
111 + expect(saveButton().disabled).toBe(false);
112 + expect(document.querySelector<HTMLInputElement>("#script-name")!.value).toBe("test");
113 + await act(async () => submit());
114 +
115 + await act(async () => first.resolve(AsyncResult.success(undefined)));
116 + expect(onClose).not.toHaveBeenCalled();
117 + expect(saveButton().disabled).toBe(true);
118 +
119 + await act(async () => second.resolve(AsyncResult.success(undefined)));
120 + expect(onClose).toHaveBeenCalledTimes(1);
121 + expect(onSubmit.mock.calls.map(([scriptId]) => scriptId)).toEqual(["build", "test"]);
122 + });
123 +
124 + it.each(["failure", "rejection"] as const)(
125 + "ignores a stale %s after the request changes",
126 + async (outcome) => {
127 + const save = deferredSave();
128 + onSubmit.mockReturnValue(save.promise);
129 + await open(request("build"));
130 + await act(async () => submit());
131 +
132 + await open(request("test", "New request error"));
133 + await act(async () => {
134 + if (outcome === "failure")
135 + save.resolve(AsyncResult.failure(Cause.fail(new Error("Old save error"))));
136 + else save.reject(new Error("Old save error"));
137 + });
138 +
139 + expect(messages()).toContain("New request error");
140 + expect(messages()).not.toContain("Old save error");
141 + expect(saveButton().disabled).toBe(false);
142 + expect(onClose).not.toHaveBeenCalled();
143 + },
144 + );
145 +
146 + it("shows a current save error and allows retry", async () => {
147 + onSubmit.mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("Save failed"))));
148 + onSubmit.mockResolvedValueOnce(AsyncResult.success(undefined));
149 + await open(request("build"));
150 +
151 + await act(async () => saveButton().click());
152 + expect(messages()).toContain("Save failed");
153 + expect(saveButton().disabled).toBe(false);
154 + expect(fieldset().disabled).toBe(false);
155 + expect(onClose).not.toHaveBeenCalled();
156 +
157 + await act(async () => saveButton().click());
158 + expect(onSubmit).toHaveBeenCalledTimes(2);
159 + expect(onClose).toHaveBeenCalledTimes(1);
160 + });
161 +
162 + it.each(["cancel", "unmount"] as const)("ignores save completion after %s", async (exit) => {
163 + const save = deferredSave();
164 + onSubmit.mockReturnValue(save.promise);
165 + await open(request("build"));
166 + await act(async () => submit());
167 +
168 + await act(async () => {
169 + if (exit === "cancel") button("Cancel").click();
170 + else {
171 + root.unmount();
172 + mounted = false;
173 + }
174 + });
175 + onClose.mockClear();
176 + await act(async () => save.resolve(AsyncResult.success(undefined)));
177 + expect(onClose).not.toHaveBeenCalled();
178 + });
179 +});
apps/web/src/components/projectScriptEditor.permissions.browser.test.tsx renamed
+86 -118
@@ -6,50 +6,39 @@ import {
6 } from "@t3tools/contracts";
7 import * as Cause from "effect/Cause";
8 import { AsyncResult } from "effect/reactivity";
9 -import { act, create, type ReactTestRenderer } from "react-test-renderer";
9 +import { act } from "react";
10 +import { createRoot, type Root } from "react-dom/client";
11 import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
12 +import { userEvent } from "vite-plus/test/browser";
13
12 -const permissions = vi.hoisted(() => ({ canWriteSettings: false, canEditProject: true }));
14 +const permissions = vi.hoisted(() => ({
15 + canWriteSettings: false,
16 + canEditProject: true,
17 + listeners: new Set<() => void>(),
18 +}));
19
14 -vi.mock("~/state/session", () => ({
15 - readEnvironmentScope: (_id: EnvironmentId, scope: AuthEnvironmentScope) =>
16 - scope === AuthOrchestrationOperateScope
17 - ? permissions.canEditProject
18 - : permissions.canWriteSettings,
19 - useEnvironmentScope: (_id: EnvironmentId, scope: AuthEnvironmentScope) =>
20 +vi.mock(import("~/state/session"), async (original) => {
21 + const { useSyncExternalStore } = await import("react");
22 + const read = (scope: AuthEnvironmentScope) =>
23 scope === AuthOrchestrationOperateScope
24 ? permissions.canEditProject
22 - : permissions.canWriteSettings,
23 -}));
24 -vi.mock("./ui/dialog", () => ({
25 - Dialog: "div",
26 - DialogDescription: "div",
27 - DialogFooter: "div",
28 - DialogHeader: "div",
29 - DialogPanel: "div",
30 - DialogPopup: "div",
31 - DialogTitle: "div",
32 -}));
33 -vi.mock("./ui/alert-dialog", () => ({
34 - AlertDialog: "div",
35 - AlertDialogClose: "button",
36 - AlertDialogDescription: "div",
37 - AlertDialogFooter: "div",
38 - AlertDialogHeader: "div",
39 - AlertDialogPopup: "div",
40 - AlertDialogTitle: "div",
41 -}));
42 -vi.mock("./ui/popover", () => ({
43 - Popover: "div",
44 - PopoverPopup: "div",
45 - PopoverTrigger: "button",
46 -}));
47 -vi.mock("./ui/button", () => ({ Button: "button" }));
48 -vi.mock("./ui/input", () => ({ Input: "input" }));
49 -vi.mock("./ui/label", () => ({ Label: "label" }));
50 -vi.mock("./ui/switch", () => ({ Switch: "input" }));
51 -vi.mock("./ui/textarea", () => ({ Textarea: "textarea" }));
25 + : permissions.canWriteSettings;
26 + return {
27 + ...(await original()),
28 + readEnvironmentScope: (_id: EnvironmentId, scope: AuthEnvironmentScope) => read(scope),
29 + useEnvironmentScope: (_id: EnvironmentId | null, scope: AuthEnvironmentScope) =>
30 + useSyncExternalStore(
31 + (listener) => {
32 + permissions.listeners.add(listener);
33 + return () => permissions.listeners.delete(listener);
34 + },
35 + () => read(scope),
36 + ),
37 + };
38 +});
39
40 +/** A grant change that React has already rendered, unlike a bare assignment. */
41 +const publish = () => act(async () => permissions.listeners.forEach((listener) => listener()));
42 import {
43 ProjectScriptEditorDialog,
44 type NewProjectScriptInput,
@@ -72,16 +61,18 @@ const request: ProjectScriptEditorRequest = {
61 };
62
63 describe("ProjectScriptEditorDialog", () => {
75 - let renderer: ReactTestRenderer | undefined;
64 + let root: Root;
65
66 beforeEach(() => {
67 + root = createRoot(document.createElement("div"));
68 permissions.canWriteSettings = false;
69 permissions.canEditProject = true;
70 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
71 });
72
73 afterEach(async () => {
84 - await act(() => renderer?.unmount());
74 + await act(async () => root.unmount());
75 + vi.restoreAllMocks();
76 vi.unstubAllGlobals();
77 });
78
@@ -93,8 +84,8 @@ describe("ProjectScriptEditorDialog", () => {
84 | typeof AuthOrchestrationOperateScope
85 | typeof AuthSettingsWriteScope = AuthOrchestrationOperateScope,
86 ) {
96 - await act(() => {
97 - renderer = create(
87 + await act(async () =>
88 + root.render(
89 <ProjectScriptEditorDialog
90 environmentId={EnvironmentId.make("script-editor-test")}
91 editScope={editScope}
@@ -104,9 +95,25 @@ describe("ProjectScriptEditorDialog", () => {
95 onDelete={actions.onDelete}
96 onClose={actions.onClose}
97 />,
98 + ),
99 + );
100 + }
101 +
102 + const submit = () => act(async () => document.querySelector("form")!.requestSubmit());
103 + async function click(label: string) {
104 + const button = await vi.waitFor(() => {
105 + const match = [...document.querySelectorAll("button")].find(
106 + (element) => element.textContent === label,
107 );
108 + expect(match, label).toBeDefined();
109 + return match!;
110 });
109 - return renderer!.root;
111 + await act(async () => button.click());
112 + }
113 + const confirmation = () => document.querySelector('[role="alertdialog"]');
114 + async function pressInShortcutField(keys: string) {
115 + document.querySelector<HTMLInputElement>("#script-keybinding")!.focus();
116 + await userEvent.keyboard(keys);
117 }
118
119 it.each([null, "test"])(
@@ -115,22 +122,12 @@ describe("ProjectScriptEditorDialog", () => {
122 permissions.canEditProject = false;
123 permissions.canWriteSettings = true;
124 const onSubmit = vi.fn().mockResolvedValue(AsyncResult.success(undefined));
118 - const root = await openEditor(
119 - onSubmit,
120 - { ...request, scriptId },
121 - undefined,
122 - AuthSettingsWriteScope,
123 - );
124 - const submit = root.findByType("form").props.onSubmit;
125 + await openEditor(onSubmit, { ...request, scriptId }, undefined, AuthSettingsWriteScope);
126 permissions.canWriteSettings = false;
126 - await act(async () => {
127 - await submit({ preventDefault() {} });
128 - });
127 + await submit();
128 expect(onSubmit).not.toHaveBeenCalled();
129 permissions.canWriteSettings = true;
131 - await act(async () => {
132 - await submit({ preventDefault() {} });
133 - });
130 + await submit();
131 expect(onSubmit).toHaveBeenCalledExactlyOnceWith(
132 scriptId,
133 expect.objectContaining({ command: "vp test" }),
@@ -142,16 +139,16 @@ describe("ProjectScriptEditorDialog", () => {
139 permissions.canEditProject = false;
140 permissions.canWriteSettings = true;
141 const actions = { onDelete: vi.fn(), onClose: vi.fn() };
145 - const root = await openEditor(undefined, request, actions, AuthSettingsWriteScope);
146 - await act(() => {
147 - root.findByProps({ variant: "destructive-outline" }).props.onClick();
148 - });
149 - const confirmDelete = root.findByProps({ variant: "destructive" }).props.onClick;
142 + await openEditor(undefined, request, actions, AuthSettingsWriteScope);
143 + await click("Delete");
144 permissions.canWriteSettings = false;
151 - await act(() => confirmDelete());
145 + await click("Delete action");
146 expect(actions.onDelete).not.toHaveBeenCalled();
147 + await vi.waitFor(() => expect(confirmation()).toBeNull());
148 permissions.canWriteSettings = true;
154 - await act(() => confirmDelete());
149 + await publish();
150 + await click("Delete");
151 + await click("Delete action");
152 expect(actions.onDelete).toHaveBeenCalledExactlyOnceWith(request.scriptId);
153 });
154
@@ -162,14 +159,12 @@ describe("ProjectScriptEditorDialog", () => {
159 if (input.keybinding !== undefined) persistedKeybinding = input.keybinding;
160 return AsyncResult.success(undefined);
161 });
165 - const root = await openEditor(onSubmit, {
162 + await openEditor(onSubmit, {
163 scriptId: null,
164 initial: { ...request.initial, keybinding: null },
165 });
166
170 - await act(async () => {
171 - await root.findByType("form").props.onSubmit({ preventDefault() {} });
172 - });
167 + await submit();
168
169 expect(persistedKeybinding).toBeNull();
170 expect(onSubmit).toHaveBeenCalledWith(null, expect.objectContaining({ keybinding: null }));
@@ -190,15 +185,13 @@ describe("ProjectScriptEditorDialog", () => {
185 if (input.keybinding !== undefined) persisted.keybinding = input.keybinding;
186 return AsyncResult.success(undefined);
187 });
193 - const root = await openEditor(onSubmit, {
188 + await openEditor(onSubmit, {
189 scriptId: null,
190 initial: { ...request.initial, keybinding: null },
191 });
192
193 permissions.canWriteSettings = false;
199 - await act(async () => {
200 - await root.findByType("form").props.onSubmit({ preventDefault() {} });
201 - });
194 + await submit();
195
196 expect(persisted).toEqual({ name: "Test", keybinding: "mod+k" });
197 expect(onSubmit).toHaveBeenCalledOnce();
@@ -209,31 +202,20 @@ describe("ProjectScriptEditorDialog", () => {
202 "requires settings access to override a retained shortcut when re-adding an action (revoked: %s)",
203 async (revokeBeforeSubmit) => {
204 permissions.canWriteSettings = true;
212 - vi.stubGlobal("navigator", { platform: "Linux" });
205 + vi.spyOn(navigator, "platform", "get").mockReturnValue("Linux");
206 const persisted = { name: null as string | null, keybinding: "mod+k" as string | null };
207 const onSubmit = vi.fn(async (_id: string | null, input: NewProjectScriptInput) => {
208 persisted.name = input.name;
209 if (input.keybinding !== undefined) persisted.keybinding = input.keybinding;
210 return AsyncResult.success(undefined);
211 });
219 - const root = await openEditor(onSubmit, {
212 + await openEditor(onSubmit, {
213 scriptId: null,
214 initial: { ...request.initial, keybinding: null },
215 });
223 - await act(() => {
224 - root.findByProps({ id: "script-keybinding" }).props.onKeyDown({
225 - key: "j",
226 - ctrlKey: true,
227 - metaKey: false,
228 - altKey: false,
229 - shiftKey: false,
230 - preventDefault() {},
231 - });
232 - });
216 + await pressInShortcutField("{Control>}j{/Control}");
217 if (revokeBeforeSubmit) permissions.canWriteSettings = false;
234 - await act(async () => {
235 - await root.findByType("form").props.onSubmit({ preventDefault() {} });
236 - });
218 + await submit();
219
220 expect(persisted).toEqual(
221 revokeBeforeSubmit
@@ -253,15 +235,13 @@ describe("ProjectScriptEditorDialog", () => {
235 if (input.keybinding !== undefined) persisted.keybinding = input.keybinding;
236 return AsyncResult.success(undefined);
237 });
256 - const root = await openEditor(onSubmit);
238 + await openEditor(onSubmit);
239
240 persisted.keybinding = "mod+j";
259 - await act(() => {
260 - root.findByProps({ id: "script-name" }).props.onChange({ target: { value: "Renamed" } });
261 - });
262 - await act(async () => {
263 - await root.findByType("form").props.onSubmit({ preventDefault() {} });
264 - });
241 + const name = document.querySelector<HTMLInputElement>("#script-name")!;
242 + await userEvent.clear(name);
243 + await userEvent.type(name, "Renamed");
244 + await submit();
245
246 expect(persisted).toEqual({ name: "Renamed", keybinding: "mod+j" });
247 expect(onSubmit).toHaveBeenCalledOnce();
@@ -273,17 +253,10 @@ describe("ProjectScriptEditorDialog", () => {
253 async (revokeBeforeSubmit) => {
254 permissions.canWriteSettings = true;
255 const onSubmit = vi.fn().mockResolvedValue(AsyncResult.success(undefined));
276 - const root = await openEditor(onSubmit);
277 - await act(() => {
278 - root.findByProps({ id: "script-keybinding" }).props.onKeyDown({
279 - key: "Backspace",
280 - preventDefault() {},
281 - });
282 - });
256 + await openEditor(onSubmit);
257 + await pressInShortcutField("{Backspace}");
258 if (revokeBeforeSubmit) permissions.canWriteSettings = false;
284 - await act(async () => {
285 - await root.findByType("form").props.onSubmit({ preventDefault() {} });
286 - });
259 + await submit();
260
261 if (revokeBeforeSubmit) {
262 expect(onSubmit).not.toHaveBeenCalled();
@@ -302,38 +275,33 @@ describe("ProjectScriptEditorDialog", () => {
275 permissions.canEditProject = revokeBeforeSubmit;
276 permissions.canWriteSettings = true;
277 const onSubmit = vi.fn().mockResolvedValue(AsyncResult.success(undefined));
305 - const root = await openEditor(onSubmit);
306 - const submit = root.findByType("form").props.onSubmit;
278 + await openEditor(onSubmit);
279
280 permissions.canEditProject = false;
309 - await act(async () => {
310 - await submit({ preventDefault() {} });
311 - });
281 + await submit();
282 expect(onSubmit).not.toHaveBeenCalled();
283
284 permissions.canEditProject = true;
315 - await act(async () => {
316 - await submit({ preventDefault() {} });
317 - });
285 + await submit();
286 expect(onSubmit).toHaveBeenCalledOnce();
287 },
288 );
289
290 it("rechecks project access before deleting from an already open confirmation", async () => {
291 const actions = { onDelete: vi.fn(), onClose: vi.fn() };
324 - const root = await openEditor(undefined, request, actions);
325 - await act(() => {
326 - root.findByProps({ variant: "destructive-outline" }).props.onClick();
327 - });
328 - const confirmDelete = root.findByProps({ variant: "destructive" }).props.onClick;
292 + await openEditor(undefined, request, actions);
293 + await click("Delete");
294
295 permissions.canEditProject = false;
331 - await act(() => confirmDelete());
296 + await click("Delete action");
297 expect(actions.onDelete).not.toHaveBeenCalled();
298 expect(actions.onClose).not.toHaveBeenCalled();
299 + await vi.waitFor(() => expect(confirmation()).toBeNull());
300
301 permissions.canEditProject = true;
336 - await act(() => confirmDelete());
302 + await publish();
303 + await click("Delete");
304 + await click("Delete action");
305 expect(actions.onDelete).toHaveBeenCalledExactlyOnceWith(request.scriptId);
306 expect(actions.onClose).toHaveBeenCalledOnce();
307 });
apps/web/src/components/projectScriptEditor.test.tsx deleted
-251
@@ -1,251 +0,0 @@
1 -import { EnvironmentId } from "@t3tools/contracts";
2 -import * as Cause from "effect/Cause";
3 -import { AsyncResult } from "effect/reactivity";
4 -import { act, StrictMode, type ReactNode } from "react";
5 -import { create, type ReactTestRenderer } from "react-test-renderer";
6 -import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
7 -
8 -vi.mock("~/state/session", () => ({
9 - readEnvironmentScope: () => true,
10 - useEnvironmentScope: () => true,
11 -}));
12 -vi.mock("./ui/dialog", () => ({
13 - Dialog: ({ open, children }: { open: boolean; children: ReactNode }) => (open ? children : null),
14 - DialogDescription: "p",
15 - DialogFooter: "footer",
16 - DialogHeader: "header",
17 - DialogPanel: "section",
18 - DialogPopup: "section",
19 - DialogTitle: "h2",
20 -}));
21 -vi.mock("./ui/alert-dialog", () => ({
22 - AlertDialog: ({ open, children }: { open: boolean; children: ReactNode }) =>
23 - open ? children : null,
24 - AlertDialogClose: "button",
25 - AlertDialogDescription: "p",
26 - AlertDialogFooter: "footer",
27 - AlertDialogHeader: "header",
28 - AlertDialogPopup: "section",
29 - AlertDialogTitle: "h2",
30 -}));
31 -vi.mock("./ui/button", () => ({ Button: "button" }));
32 -vi.mock("./ui/input", () => ({ Input: "input" }));
33 -vi.mock("./ui/label", () => ({ Label: "label" }));
34 -vi.mock("./ui/popover", () => ({
35 - Popover: ({ children }: { children: ReactNode }) => children,
36 - PopoverPopup: () => null,
37 - PopoverTrigger: "button",
38 -}));
39 -vi.mock("./ui/switch", () => ({ Switch: "input" }));
40 -vi.mock("./ui/textarea", () => ({ Textarea: "textarea" }));
41 -
42 -import {
43 - EMPTY_PROJECT_SCRIPT_INPUT,
44 - ProjectScriptEditorDialog,
45 - type ProjectScriptActionResult,
46 - type ProjectScriptEditorRequest,
47 -} from "./projectScriptEditor";
48 -
49 -const onSubmit = vi.fn<Parameters<typeof ProjectScriptEditorDialog>[0]["onSubmit"]>();
50 -const onClose = vi.fn();
51 -const onDelete = vi.fn();
52 -let renderer: ReactTestRenderer | null;
53 -
54 -function request(name: string, error?: string): ProjectScriptEditorRequest {
55 - return {
56 - scriptId: name,
57 - initial: { ...EMPTY_PROJECT_SCRIPT_INPUT, name, command: `run-${name}` },
58 - ...(error === undefined ? {} : { error }),
59 - };
60 -}
61 -
62 -function editor(nextRequest: ProjectScriptEditorRequest) {
63 - return (
64 - <StrictMode>
65 - <ProjectScriptEditorDialog
66 - environmentId={EnvironmentId.make("test")}
67 - request={nextRequest}
68 - scripts={[]}
69 - onSubmit={onSubmit}
70 - onClose={onClose}
71 - onDelete={onDelete}
72 - />
73 - </StrictMode>
74 - );
75 -}
76 -
77 -function open(nextRequest: ProjectScriptEditorRequest) {
78 - act(() => {
79 - if (renderer) renderer.update(editor(nextRequest));
80 - else renderer = create(editor(nextRequest));
81 - });
82 -}
83 -
84 -function submit(): Promise<void> {
85 - return renderer!.root.findByType("form").props.onSubmit({ preventDefault() {} });
86 -}
87 -
88 -function saveButton() {
89 - return renderer!.root.findAllByType("button").find((button) => button.props.type === "submit")!;
90 -}
91 -
92 -function deferredSave() {
93 - let resolve!: (result: ProjectScriptActionResult) => void;
94 - let reject!: (error: Error) => void;
95 - const promise = new Promise<ProjectScriptActionResult>((resolveResult, rejectResult) => {
96 - resolve = resolveResult;
97 - reject = rejectResult;
98 - });
99 - return { promise, resolve, reject };
100 -}
101 -
102 -beforeEach(() => {
103 - renderer = null;
104 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
105 - onSubmit.mockReset();
106 - onClose.mockReset();
107 - onDelete.mockReset();
108 -});
109 -
110 -afterEach(async () => {
111 - await act(async () => renderer?.unmount());
112 - vi.unstubAllGlobals();
113 -});
114 -
115 -describe("project action editor save lifecycle", () => {
116 - it("blocks repeated submits and edits until the current save completes", async () => {
117 - const save = deferredSave();
118 - onSubmit.mockReturnValue(save.promise);
119 - open(request("build"));
120 -
121 - let completion!: Promise<void>;
122 - act(() => {
123 - completion = submit();
124 - void submit();
125 - });
126 -
127 - expect(onSubmit).toHaveBeenCalledTimes(1);
128 - expect(saveButton().props.disabled).toBe(true);
129 - expect(renderer!.root.findByType("fieldset").props.disabled).toBe(true);
130 - const cancel = renderer!.root
131 - .findAllByType("button")
132 - .find((button) => button.children.includes("Cancel"))!;
133 - expect(cancel.props.disabled).not.toBe(true);
134 -
135 - await act(async () => {
136 - save.resolve(AsyncResult.success(undefined));
137 - await completion;
138 - });
139 - expect(onClose).toHaveBeenCalledTimes(1);
140 - });
141 -
142 - it("does not close a replacement request or release its in-flight save", async () => {
143 - const first = deferredSave();
144 - const second = deferredSave();
145 - onSubmit.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);
146 - open(request("build"));
147 - let firstCompletion!: Promise<void>;
148 - act(() => {
149 - firstCompletion = submit();
150 - });
151 -
152 - open(request("test"));
153 - expect(saveButton().props.disabled).toBe(false);
154 - expect(renderer!.root.findByProps({ id: "script-name" }).props.value).toBe("test");
155 - let secondCompletion!: Promise<void>;
156 - act(() => {
157 - secondCompletion = submit();
158 - });
159 -
160 - await act(async () => {
161 - first.resolve(AsyncResult.success(undefined));
162 - await firstCompletion;
163 - });
164 - expect(onClose).not.toHaveBeenCalled();
165 - expect(saveButton().props.disabled).toBe(true);
166 -
167 - await act(async () => {
168 - second.resolve(AsyncResult.success(undefined));
169 - await secondCompletion;
170 - });
171 - expect(onClose).toHaveBeenCalledTimes(1);
172 - expect(onSubmit.mock.calls.map(([scriptId]) => scriptId)).toEqual(["build", "test"]);
173 - });
174 -
175 - it.each(["failure", "rejection"] as const)(
176 - "ignores a stale %s after the request changes",
177 - async (outcome) => {
178 - const save = deferredSave();
179 - onSubmit.mockReturnValue(save.promise);
180 - open(request("build"));
181 - let completion!: Promise<void>;
182 - act(() => {
183 - completion = submit();
184 - });
185 -
186 - open(request("test", "New request error"));
187 - await act(async () => {
188 - if (outcome === "failure")
189 - save.resolve(AsyncResult.failure(Cause.fail(new Error("Old save error"))));
190 - else save.reject(new Error("Old save error"));
191 - await completion;
192 - });
193 -
194 - const messages = renderer!.root.findAllByType("p").flatMap((paragraph) => paragraph.children);
195 - expect(messages).toContain("New request error");
196 - expect(messages).not.toContain("Old save error");
197 - expect(saveButton().props.disabled).toBe(false);
198 - expect(onClose).not.toHaveBeenCalled();
199 - },
200 - );
201 -
202 - it("shows a current save error and allows retry", async () => {
203 - onSubmit.mockResolvedValueOnce(AsyncResult.failure(Cause.fail(new Error("Save failed"))));
204 - onSubmit.mockResolvedValueOnce(AsyncResult.success(undefined));
205 - open(request("build"));
206 -
207 - await act(async () => {
208 - await submit();
209 - });
210 - expect(renderer!.root.findAllByType("p").flatMap((paragraph) => paragraph.children)).toContain(
211 - "Save failed",
212 - );
213 - expect(saveButton().props.disabled).toBe(false);
214 - expect(renderer!.root.findByType("fieldset").props.disabled).toBe(false);
215 - expect(onClose).not.toHaveBeenCalled();
216 -
217 - await act(async () => {
218 - await submit();
219 - });
220 - expect(onSubmit).toHaveBeenCalledTimes(2);
221 - expect(onClose).toHaveBeenCalledTimes(1);
222 - });
223 -
224 - it.each(["cancel", "unmount"] as const)("ignores save completion after %s", async (exit) => {
225 - const save = deferredSave();
226 - onSubmit.mockReturnValue(save.promise);
227 - open(request("build"));
228 - let completion!: Promise<void>;
229 - act(() => {
230 - completion = submit();
231 - });
232 -
233 - act(() => {
234 - if (exit === "cancel") {
235 - renderer!.root
236 - .findAllByType("button")
237 - .find((button) => button.children.includes("Cancel"))!
238 - .props.onClick();
239 - } else {
240 - renderer!.unmount();
241 - renderer = null;
242 - }
243 - });
244 - onClose.mockClear();
245 - await act(async () => {
246 - save.resolve(AsyncResult.success(undefined));
247 - await completion;
248 - });
249 - expect(onClose).not.toHaveBeenCalled();
250 - });
251 -});
apps/web/src/components/pullRequest/PullRequestMarkdownEditor.browser.test.tsx renamed
+51 -40
@@ -1,20 +1,22 @@
1 import { AuthSourceControlWriteScope, EnvironmentId } from "@t3tools/contracts";
2 import { act } from "react";
3 -import { create, type ReactTestRenderer } from "react-test-renderer";
3 +import { createRoot, type Root } from "react-dom/client";
4 import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
5 +import { userEvent } from "vite-plus/test/browser";
6
7 const permissions = vi.hoisted(() => ({
8 allowed: new Set<string>(),
9 listeners: new Set<() => void>(),
10 }));
11
11 -vi.mock("~/state/session", async () => {
12 +vi.mock(import("~/state/session"), async (original) => {
13 const { useSyncExternalStore } = await import("react");
13 - const canWrite = (environmentId: string, scope: string) =>
14 - scope === AuthSourceControlWriteScope && permissions.allowed.has(environmentId);
14 + const canWrite = (environmentId: string | null, scope: string) =>
15 + scope === AuthSourceControlWriteScope && permissions.allowed.has(environmentId ?? "");
16 return {
17 + ...(await original()),
18 readEnvironmentScope: canWrite,
17 - useEnvironmentScope: (environmentId: string, scope: string) =>
19 + useEnvironmentScope: (environmentId, scope) =>
20 useSyncExternalStore(
21 (listener) => {
22 permissions.listeners.add(listener);
@@ -24,37 +26,36 @@ vi.mock("~/state/session", async () => {
26 ),
27 };
28 });
27 -vi.mock("~/lib/utils", () => ({ cn: () => "" }));
28 -vi.mock("../ui/button", () => ({ Button: "button" }));
29 -vi.mock("../ui/textarea", () => ({ Textarea: "textarea" }));
30 -vi.mock("../ui/toggle-group", () => ({ Toggle: "button", ToggleGroup: "div" }));
31 -vi.mock("./PullRequestMarkdown", () => ({ PullRequestMarkdown: "article" }));
29
30 import { PullRequestMarkdownEditor } from "./PullRequestMarkdownEditor";
31
32 const primary = EnvironmentId.make("primary");
33 const secondary = EnvironmentId.make("secondary");
37 -let renderer: ReactTestRenderer | undefined;
34 const onSave = vi.fn<(next: string) => void>();
35 const onCancel = vi.fn<() => void>();
36 +let root: Root;
37 +let container: HTMLDivElement;
38
39 beforeEach(() => {
40 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
41 permissions.allowed.clear();
42 permissions.listeners.clear();
44 - renderer = undefined;
43 onSave.mockReset();
44 onCancel.mockReset();
47 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
45 + container = document.createElement("div");
46 + document.body.append(container);
47 + root = createRoot(container);
48 });
49
50 afterEach(async () => {
51 - await act(() => renderer?.unmount());
51 + await act(async () => root.unmount());
52 + container.remove();
53 vi.unstubAllGlobals();
54 });
55
56 async function openEditor(options?: { value?: string; allowEmpty?: boolean }) {
56 - await act(() => {
57 - renderer = create(
57 + await act(async () =>
58 + root.render(
59 <PullRequestMarkdownEditor
60 value={options?.value ?? "Original description"}
61 cwd="/repo"
@@ -65,16 +66,22 @@ async function openEditor(options?: { value?: string; allowEmpty?: boolean }) {
66 onSave={onSave}
67 onCancel={onCancel}
68 />,
68 - );
69 - });
69 + ),
70 + );
71 }
72
72 -function saveHandler(): () => void {
73 - return renderer!.root.findByProps({ children: "Save" }).props.onClick;
73 +function button(label: string) {
74 + const match = [...container.querySelectorAll("button")].find(
75 + (element) => element.textContent === label,
76 + );
77 + expect(match, `button ${label}`).toBeDefined();
78 + return match!;
79 }
80
81 +const clickSave = () => act(async () => button("Save").click());
82 +
83 async function grant(allowed: boolean) {
77 - await act(() => {
84 + await act(async () => {
85 if (allowed) permissions.allowed.add(secondary);
86 else permissions.allowed.delete(secondary);
87 permissions.listeners.forEach((listener) => listener());
@@ -85,18 +92,19 @@ it("does not save a secondary environment's description using the primary grant"
92 permissions.allowed.add(primary);
93 await openEditor();
94
88 - await act(() => saveHandler()());
95 + expect(button("Save").disabled).toBe(true);
96 + await clickSave();
97
98 expect(onSave).not.toHaveBeenCalled();
99 });
100
93 -it("rejects a retained Save callback when the grant changes before React updates", async () => {
101 +it("rejects a Save click when the grant changes before React updates", async () => {
102 permissions.allowed.add(secondary);
103 await openEditor();
96 - const save = saveHandler();
104 permissions.allowed.delete(secondary);
105
99 - await act(() => save());
106 + expect(button("Save").disabled).toBe(false);
107 + await clickSave();
108
109 expect(onSave).not.toHaveBeenCalled();
110 });
@@ -104,45 +112,48 @@ it("rejects a retained Save callback when the grant changes before React updates
112 it("keeps an edited draft through revocation and saves it after access returns without remounting", async () => {
113 permissions.allowed.add(secondary);
114 await openEditor();
107 - await act(() => {
108 - renderer!.root.findByType("textarea").props.onChange({
109 - target: { value: "Keep these unsaved edits" },
110 - });
111 - });
115 + const textarea = container.querySelector("textarea")!;
116 + await userEvent.clear(textarea);
117 + await userEvent.type(textarea, "Keep these unsaved edits");
118
119 await grant(false);
114 - await act(() => saveHandler()());
115 - expect(onSave).not.toHaveBeenCalled();
120 + expect(button("Save").disabled).toBe(true);
121 + expect(container.querySelector("textarea")).toBe(textarea);
122
123 await grant(true);
118 - await act(() => saveHandler()());
124 + await clickSave();
125 expect(onSave).toHaveBeenCalledExactlyOnceWith("Keep these unsaved edits");
126 });
127
122 -it("saves with source-control permission alone", async () => {
128 +it("saves with source-control permission alone, from the button or Cmd/Ctrl+Enter", async () => {
129 permissions.allowed.add(secondary);
130 await openEditor();
131
126 - await act(() => saveHandler()());
127 -
132 + await clickSave();
133 expect(onSave).toHaveBeenCalledExactlyOnceWith("Original description");
134 +
135 + container.querySelector("textarea")!.focus();
136 + await userEvent.keyboard("{Control>}{Enter}{/Control}");
137 + expect(onSave).toHaveBeenCalledTimes(2);
138 });
139
140 it("allows clearing a description only after a pending grant becomes available", async () => {
141 await openEditor({ value: "", allowEmpty: true });
133 - await act(() => saveHandler()());
142 + await clickSave();
143 expect(onSave).not.toHaveBeenCalled();
144
145 await grant(true);
137 - await act(() => saveHandler()());
146 + await clickSave();
147 expect(onSave).toHaveBeenCalledExactlyOnceWith("");
148 });
149
150 it("keeps cancelling a local edit available without a write grant", async () => {
151 await openEditor();
152
144 - await act(() => renderer!.root.findByProps({ children: "Cancel" }).props.onClick());
153 + await act(async () => button("Cancel").click());
154 + container.querySelector("textarea")!.focus();
155 + await userEvent.keyboard("{Escape}");
156
146 - expect(onCancel).toHaveBeenCalledOnce();
157 + expect(onCancel).toHaveBeenCalledTimes(2);
158 expect(onSave).not.toHaveBeenCalled();
159 });
apps/web/src/components/pullRequest/PullRequestSummaryTab.browser.test.tsx new
+221
@@ -0,0 +1,221 @@
1 +import { SourceControlProviderKind } from "@t3tools/contracts";
2 +import { EnvironmentId, ProjectId, type PullRequestDetailView } from "@t3tools/contracts";
3 +import { act } from "react";
4 +import { createRoot, type Root } from "react-dom/client";
5 +import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
6 +import { userEvent } from "vite-plus/test/browser";
7 +
8 +vi.mock(import("~/state/use-atom-command"), async (original) => ({
9 + ...(await original()),
10 + useAtomCommand: (() => vi.fn()) as never,
11 +}));
12 +
13 +import { PullRequestSummaryTab } from "./PullRequestSummaryTab";
14 +
15 +const detail: PullRequestDetailView = {
16 + provider: SourceControlProviderKind.make("github"),
17 + projectId: ProjectId.make("project"),
18 + projectTitle: "Project",
19 + workspaceRoot: "/workspace",
20 + repository: "owner/repo",
21 + number: 1,
22 + title: "Test pull request",
23 + body: "Original description",
24 + url: "https://github.com/owner/repo/pull/1",
25 + author: { login: "author", name: null, avatarUrl: null },
26 + viewer: "author",
27 + state: "open",
28 + isDraft: false,
29 + mergeability: "mergeable",
30 + additions: 1,
31 + deletions: 0,
32 + changedFiles: 1,
33 + headBranch: "feature",
34 + baseBranch: "main",
35 + createdAt: "2026-09-01T00:00:00Z",
36 + updatedAt: "2026-09-01T00:00:00Z",
37 + mergedAt: null,
38 + closedAt: null,
39 + reviewers: [],
40 + labels: [],
41 + checks: [{ name: "Unit tests", status: "success", description: null, url: null }],
42 + comments: [],
43 + commentCount: 0,
44 + commentsTruncated: false,
45 + reviewThreads: [],
46 + commits: [],
47 + mergeCapabilities: { merge: false, squash: false, rebase: false },
48 + capabilities: {
49 + diff: true,
50 + comment: true,
51 + search: true,
52 + actions: [],
53 + mergeMethods: [],
54 + review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
55 + reviewers: { request: false, listCandidates: false },
56 + edit: { changeRequest: true, comment: true },
57 + },
58 + viewerPermissions: {
59 + actions: [],
60 + comment: true,
61 + resolve: false,
62 + verdicts: [],
63 + requestReviewers: false,
64 + },
65 +};
66 +
67 +let root: Root;
68 +let container: HTMLDivElement;
69 +beforeEach(() => {
70 + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
71 + container = document.createElement("div");
72 + document.body.append(container);
73 + root = createRoot(container);
74 +});
75 +afterEach(async () => {
76 + await act(async () => root.unmount());
77 + container.remove();
78 + localStorage.clear();
79 + vi.unstubAllGlobals();
80 +});
81 +
82 +const render = (value = detail) =>
83 + act(async () =>
84 + root.render(
85 + <PullRequestSummaryTab
86 + scrollerRef={() => {}}
87 + environmentId={EnvironmentId.make("environment")}
88 + threadRef={null}
89 + reference={value}
90 + detail={value}
91 + activityPending={false}
92 + activityError={null}
93 + onRefresh={() => {}}
94 + />,
95 + ),
96 + );
97 +
98 +function heading(title: string) {
99 + const section = container.querySelector(`section[aria-label="${title}"]`);
100 + expect(section, `section ${title}`).not.toBeNull();
101 + return [...section!.querySelectorAll("button")].find(
102 + (button) => button.querySelector("span")?.textContent === title,
103 + )!;
104 +}
105 +
106 +const click = (title: string) => act(async () => heading(title).click());
107 +const expanded = (title: string) => heading(title).getAttribute("aria-expanded");
108 +const visibleText = () => container.innerText;
109 +
110 +it("toggles checks from their heading and resets sections for another pull request", async () => {
111 + await render();
112 + expect(visibleText()).not.toContain("Unit tests");
113 + await click("Checks");
114 + expect(visibleText()).toContain("Unit tests");
115 + await click("Checks");
116 + expect(expanded("Checks")).toBe("false");
117 + await click("Checks");
118 + await click("Description");
119 + await render({ ...detail, url: "https://github.com/owner/repo/pull/2", number: 2 });
120 + expect(expanded("Checks")).toBe("false");
121 + expect(expanded("Description")).toBe("true");
122 +});
123 +
124 +it("keeps an unsaved description when collapsed and reopened", async () => {
125 + await render();
126 + await act(async () =>
127 + container.querySelector<HTMLButtonElement>('[aria-label="Edit description"]')!.click(),
128 + );
129 + const textarea = container.querySelector("textarea")!;
130 + await userEvent.clear(textarea);
131 + await userEvent.type(textarea, "Unsaved description");
132 + await click("Description");
133 + expect(expanded("Description")).toBe("false");
134 + await click("Description");
135 + expect(container.querySelector("textarea")!.value).toBe("Unsaved description");
136 +});
137 +
138 +function commentTexts() {
139 + const section = [...container.querySelectorAll("section")].find((element) =>
140 + element.getAttribute("aria-label")?.startsWith("Comments"),
141 + )!;
142 + return [...section.querySelectorAll("p")]
143 + .filter((p) => p.checkVisibility())
144 + .map((p) => p.textContent ?? "");
145 +}
146 +
147 +const filterButton = () =>
148 + container.querySelector<HTMLButtonElement>('[aria-label="Filter comments"]')!;
149 +
150 +function filterItem(label: string) {
151 + const item = [...document.querySelectorAll('[role="menuitemcheckbox"]')].find((element) =>
152 + element.textContent?.includes(label),
153 + ) as HTMLElement | undefined;
154 + expect(item, `filter ${label}`).toBeDefined();
155 + return item!;
156 +}
157 +
158 +async function toggleFilter(label: string) {
159 + if (!document.querySelector('[role="menuitemcheckbox"]')) await userEvent.click(filterButton());
160 + await userEvent.click(filterItem(label));
161 +}
162 +
163 +it("hides bot and resolved comments until the filter shows them, and remembers the choice", async () => {
164 + const comment = (index: number, login: string, body: string, isBot = false) => ({
165 + id: `comment-${index}`,
166 + kind: "issue-comment" as const,
167 + author: { login, name: null, avatarUrl: null, isBot },
168 + body,
169 + createdAt: `2026-09-01T00:00:${String(index).padStart(2, "0")}Z`,
170 + url: null,
171 + path: null,
172 + reviewState: null,
173 + });
174 + const resolved = {
175 + ...comment(13, "reviewer", "Resolved remark"),
176 + kind: "review-comment" as const,
177 + };
178 + const value: PullRequestDetailView = {
179 + ...detail,
180 + commentCount: 14,
181 + comments: [
182 + ...Array.from({ length: 12 }, (_, index) =>
183 + comment(index, "review-app", `Bot report ${index}`, true),
184 + ),
185 + comment(12, "human", "Human comment"),
186 + resolved,
187 + ],
188 + reviewThreads: [
189 + {
190 + id: "thread",
191 + path: "src/index.ts",
192 + line: 1,
193 + side: "right",
194 + isResolved: true,
195 + isOutdated: false,
196 + comments: [resolved],
197 + },
198 + ],
199 + };
200 + await render(value);
201 + expect(commentTexts()).toEqual(["Human comment"]);
202 + expect(filterButton().textContent).toContain("13 hidden");
203 +
204 + await toggleFilter("Bot comments");
205 + expect(commentTexts().filter((text) => text.startsWith("Bot report"))).toHaveLength(9);
206 + expect(commentTexts()).toContain("Human comment");
207 + expect(commentTexts()).not.toContain("Bot report 0");
208 +
209 + await toggleFilter("Resolved or dismissed");
210 + await userEvent.keyboard("{Escape}");
211 + expect(
212 + [...container.querySelectorAll("button")].some((button) => button.textContent === "Resolved"),
213 + ).toBe(true);
214 +
215 + await act(async () => root.unmount());
216 + root = createRoot(container);
217 + await render({ ...value, url: `${value.url}0`, number: 10 });
218 + expect(commentTexts()).toContain("Bot report 11");
219 + await userEvent.click(filterButton());
220 + expect(filterItem("Bot comments").getAttribute("aria-checked")).toBe("true");
221 +});
apps/web/src/components/pullRequest/PullRequestSummaryTab.test.tsx deleted
-245
@@ -1,245 +0,0 @@
1 -import { SourceControlProviderKind } from "@t3tools/contracts";
2 -import { EnvironmentId, ProjectId, type PullRequestDetailView } from "@t3tools/contracts";
3 -import { act, type ReactNode } from "react";
4 -import { create, type ReactTestRenderer } from "react-test-renderer";
5 -import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
6 -
7 -vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() }));
8 -vi.mock("~/state/pullRequests", () => ({ pullRequestEnvironment: {} }));
9 -vi.mock("~/browser/useOpenLink", () => ({ useOpenLink: () => vi.fn() }));
10 -vi.mock("./PullRequestMarkdown", () => ({
11 - PullRequestMarkdown: ({ text }: { text: string }) => <p>{text}</p>,
12 -}));
13 -vi.mock("../ui/menu", () => ({
14 - Menu: "div",
15 - MenuCheckboxItem: "div",
16 - MenuGroup: "div",
17 - MenuGroupLabel: "div",
18 - MenuPopup: "div",
19 - MenuTrigger: "div",
20 -}));
21 -vi.mock("../ui/tooltip", () => ({
22 - Tooltip: ({ children }: { children: ReactNode }) => children,
23 - TooltipTrigger: ({ children }: { children: ReactNode }) => children,
24 - TooltipPopup: () => null,
25 -}));
26 -
27 -import { PullRequestSummaryTab } from "./PullRequestSummaryTab";
28 -
29 -const detail: PullRequestDetailView = {
30 - provider: SourceControlProviderKind.make("github"),
31 - projectId: ProjectId.make("project"),
32 - projectTitle: "Project",
33 - workspaceRoot: "/workspace",
34 - repository: "owner/repo",
35 - number: 1,
36 - title: "Test pull request",
37 - body: "Original description",
38 - url: "https://github.com/owner/repo/pull/1",
39 - author: { login: "author", name: null, avatarUrl: null },
40 - viewer: "author",
41 - state: "open",
42 - isDraft: false,
43 - mergeability: "mergeable",
44 - additions: 1,
45 - deletions: 0,
46 - changedFiles: 1,
47 - headBranch: "feature",
48 - baseBranch: "main",
49 - createdAt: "2026-09-01T00:00:00Z",
50 - updatedAt: "2026-09-01T00:00:00Z",
51 - mergedAt: null,
52 - closedAt: null,
53 - reviewers: [],
54 - labels: [],
55 - checks: [{ name: "Unit tests", status: "success", description: null, url: null }],
56 - comments: [],
57 - commentCount: 0,
58 - commentsTruncated: false,
59 - reviewThreads: [],
60 - commits: [],
61 - mergeCapabilities: { merge: false, squash: false, rebase: false },
62 - capabilities: {
63 - diff: true,
64 - comment: true,
65 - search: true,
66 - actions: [],
67 - mergeMethods: [],
68 - review: { inlineComment: false, reply: false, resolve: false, verdicts: [] },
69 - reviewers: { request: false, listCandidates: false },
70 - edit: { changeRequest: true, comment: true },
71 - },
72 - viewerPermissions: {
73 - actions: [],
74 - comment: true,
75 - resolve: false,
76 - verdicts: [],
77 - requestReviewers: false,
78 - },
79 -};
80 -
81 -let renderer: ReactTestRenderer;
82 -beforeEach(() => {
83 - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
84 - const store = new Map<string, string>();
85 - vi.stubGlobal(
86 - "window",
87 - Object.assign(new EventTarget(), {
88 - localStorage: {
89 - getItem: (key: string) => store.get(key) ?? null,
90 - setItem: (key: string, value: string) => store.set(key, value),
91 - removeItem: (key: string) => store.delete(key),
92 - },
93 - }),
94 - );
95 -});
96 -afterEach(() => {
97 - act(() => renderer?.unmount());
98 - vi.unstubAllGlobals();
99 -});
100 -
101 -function render(value = detail) {
102 - return (
103 - <PullRequestSummaryTab
104 - scrollerRef={() => {}}
105 - environmentId={EnvironmentId.make("environment")}
106 - threadRef={null}
107 - reference={value}
108 - detail={value}
109 - activityPending={false}
110 - activityError={null}
111 - onRefresh={() => {}}
112 - />
113 - );
114 -}
115 -
116 -function heading(title: string) {
117 - const section = renderer.root
118 - .findAllByType("section")
119 - .find((section) => section.props["aria-label"] === title)!;
120 - return section
121 - .findAllByType("button")
122 - .find((button) => button.findAllByType("span").some((span) => span.children.includes(title)))!;
123 -}
124 -
125 -function click(title: string) {
126 - act(() =>
127 - heading(title).props.onClick({ nativeEvent: {}, preventDefault() {}, stopPropagation() {} }),
128 - );
129 -}
130 -
131 -it("toggles checks from their heading and resets sections for another pull request", () => {
132 - act(() => {
133 - renderer = create(render());
134 - });
135 - expect(
136 - renderer.root.findAllByType("span").some((span) => span.children.includes("Unit tests")),
137 - ).toBe(false);
138 - click("Checks");
139 - expect(
140 - renderer.root.findAllByType("span").some((span) => span.children.includes("Unit tests")),
141 - ).toBe(true);
142 - click("Checks");
143 - expect(heading("Checks").props["aria-expanded"]).toBe(false);
144 - click("Checks");
145 - click("Description");
146 - act(() =>
147 - renderer.update(render({ ...detail, url: "https://github.com/owner/repo/pull/2", number: 2 })),
148 - );
149 - expect(heading("Checks").props["aria-expanded"]).toBe(false);
150 - expect(heading("Description").props["aria-expanded"]).toBe(true);
151 -});
152 -
153 -it("keeps an unsaved description when collapsed and reopened", () => {
154 - act(() => {
155 - renderer = create(render());
156 - });
157 - act(() => renderer.root.findByProps({ "aria-label": "Edit description" }).props.onClick());
158 - act(() =>
159 - renderer.root.findByType("textarea").props.onChange({
160 - target: { value: "Unsaved description" },
161 - currentTarget: { value: "Unsaved description" },
162 - nativeEvent: {},
163 - }),
164 - );
165 - click("Description");
166 - expect(heading("Description").props["aria-expanded"]).toBe(false);
167 - click("Description");
168 - expect(renderer.root.findByType("textarea").props.value).toBe("Unsaved description");
169 -});
170 -
171 -function texts() {
172 - return renderer.root
173 - .findAllByType("p")
174 - .map((p) => p.children.join(""))
175 - .filter((text) => text !== detail.body);
176 -}
177 -
178 -function filterItem(label: string) {
179 - return renderer.root.find(
180 - (node) => typeof node.props.onCheckedChange === "function" && node.children.includes(label),
181 - );
182 -}
183 -
184 -it("hides bot and resolved comments until the filter shows them, and remembers the choice", () => {
185 - const comment = (index: number, login: string, body: string, isBot = false) => ({
186 - id: `comment-${index}`,
187 - kind: "issue-comment" as const,
188 - author: { login, name: null, avatarUrl: null, isBot },
189 - body,
190 - createdAt: `2026-09-01T00:00:${String(index).padStart(2, "0")}Z`,
191 - url: null,
192 - path: null,
193 - reviewState: null,
194 - });
195 - const resolved = {
196 - ...comment(13, "reviewer", "Resolved remark"),
197 - kind: "review-comment" as const,
198 - };
199 - const value: PullRequestDetailView = {
200 - ...detail,
201 - commentCount: 14,
202 - comments: [
203 - ...Array.from({ length: 12 }, (_, index) =>
204 - comment(index, "review-app", `Bot report ${index}`, true),
205 - ),
206 - comment(12, "human", "Human comment"),
207 - resolved,
208 - ],
209 - reviewThreads: [
210 - {
211 - id: "thread",
212 - path: "src/index.ts",
213 - line: 1,
214 - side: "right",
215 - isResolved: true,
216 - isOutdated: false,
217 - comments: [resolved],
218 - },
219 - ],
220 - };
221 - act(() => {
222 - renderer = create(render(value));
223 - });
224 - expect(texts()).toEqual(["Human comment"]);
225 - expect(
226 - renderer.root.findByProps({ "aria-label": "Filter comments" }).children.join(""),
227 - ).toContain("13 hidden");
228 -
229 - act(() => filterItem("Bot comments").props.onCheckedChange(true));
230 - expect(texts().filter((text) => text.startsWith("Bot report"))).toHaveLength(9);
231 - expect(texts()).toContain("Human comment");
232 - expect(texts()).not.toContain("Bot report 0");
233 -
234 - act(() => filterItem("Resolved or dismissed").props.onCheckedChange(true));
235 - expect(
236 - renderer.root.findAllByType("button").some((button) => button.children.includes("Resolved")),
237 - ).toBe(true);
238 -
239 - act(() => renderer.unmount());
240 - act(() => {
241 - renderer = create(render({ ...value, url: `${value.url}0`, number: 10 }));
242 - });
243 - expect(filterItem("Bot comments").props.checked).toBe(true);
244 - expect(texts()).toContain("Bot report 11");
245 -});
apps/web/src/components/pullRequest/usePullRequestFilesViewed.browser.test.tsx renamed
+31 -33
@@ -5,8 +5,8 @@ import {
5 type PullRequestRef,
6 } from "@t3tools/contracts";
7 import { AsyncResult } from "effect/reactivity";
8 -import { act, StrictMode } from "react";
9 -import { create, type ReactTestRenderer } from "react-test-renderer";
8 +import { act, StrictMode, useEffect } from "react";
9 +import { createRoot, type Root } from "react-dom/client";
10 import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
11
12 const { host, setFilesViewed, toastAdd } = vi.hoisted(() => ({
@@ -15,20 +15,24 @@ const { host, setFilesViewed, toastAdd } = vi.hoisted(() => ({
15 toastAdd: vi.fn(),
16 }));
17
18 -vi.mock("~/state/pullRequests", () => ({
19 - pullRequestEnvironment: { filesViewed: () => null, setFilesViewed: {} },
20 -}));
21 -vi.mock("~/state/query", () => ({
22 - useEnvironmentQuery: () => ({
18 +vi.mock(import("~/state/query"), async (original) => ({
19 + ...(await original()),
20 + useEnvironmentQuery: (() => ({
21 data: host.data,
22 error: null,
23 isPending: false,
24 isSuccess: true,
25 refresh: host.refresh,
28 - }),
26 + })) as never,
27 +}));
28 +vi.mock(import("~/state/use-atom-command"), async (original) => ({
29 + ...(await original()),
30 + useAtomCommand: (() => setFilesViewed) as never,
31 }));
30 -vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: () => setFilesViewed }));
31 -vi.mock("../ui/toast", () => ({ toastManager: { add: toastAdd } }));
32 +vi.mock(import("../ui/toast"), async (original) => {
33 + const actual = await original();
34 + return { ...actual, toastManager: { ...actual.toastManager, add: toastAdd } as never };
35 +});
36
37 import {
38 usePullRequestFilesViewed,
@@ -46,30 +50,30 @@ function answer(state: "unviewed" | "viewed" | "dismissed"): PullRequestFilesVie
50 return { files: [{ path: "a.ts", state }], truncated: false };
51 }
52
49 -let renderer: ReactTestRenderer | null = null;
50 -
51 -function Probe(_props: { readonly view: PullRequestFilesViewedView }) {
52 - return null;
53 -}
53 +let root: Root;
54 +let current: PullRequestFilesViewedView;
55
56 function Surface() {
57 const view = usePullRequestFilesViewed({ environmentId, reference, enabled: true });
57 - return <Probe view={view} />;
58 -}
59 -
60 -function view(): PullRequestFilesViewedView {
61 - return renderer!.root.findByType(Probe).props.view;
58 + useEffect(() => {
59 + current = view;
60 + });
61 + return null;
62 }
63
64 -async function reads(state: "unviewed" | "viewed" | "dismissed") {
65 - host.data = answer(state);
66 - await act(async () =>
67 - renderer!.update(
64 +const view = () => current;
65 +const render = () =>
66 + act(async () =>
67 + root.render(
68 <StrictMode>
69 <Surface />
70 </StrictMode>,
71 ),
72 );
73 +
74 +async function reads(state: "unviewed" | "viewed" | "dismissed") {
75 + host.data = answer(state);
76 + await render();
77 }
78
79 beforeEach(async () => {
@@ -79,18 +83,12 @@ beforeEach(async () => {
83 host.refresh.mockReset();
84 toastAdd.mockReset();
85 setFilesViewed.mockReset().mockResolvedValue(AsyncResult.success(undefined));
82 - act(() => {
83 - renderer = create(
84 - <StrictMode>
85 - <Surface />
86 - </StrictMode>,
87 - );
88 - });
86 + root = createRoot(document.createElement("div"));
87 + await render();
88 });
89
90 afterEach(async () => {
92 - await act(async () => renderer?.unmount());
93 - renderer = null;
91 + await act(async () => root.unmount());
92 vi.useRealTimers();
93 vi.unstubAllGlobals();
94 });