Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProviderSetupSection.test.tsx

389 lines12.3 KB

1import { isValidElement, type FunctionComponent, type ReactElement } from "react";
2import {
3 EnvironmentId,
4 ProviderDriverKind,
5 ProviderInstanceId,
6 type ProviderAuthState,
7 type ProviderInstallState,
8 type ServerProvider,
9} from "@t3tools/contracts";
10import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
11​
12import { visitElements } from "../../test/reactElementTree";
13import { reactHookHarness as hooks } from "../../test/reactHookHarness";
14​
15const setup = vi.hoisted(() => ({
16 auth: null as ProviderAuthState | null,
17 installation: null as ProviderInstallState | null,
18 authState: vi.fn(() => "auth"),
19 installState: vi.fn(() => "installation"),
20 startAuth: vi.fn(),
21 completeAuth: vi.fn(),
22 cancelAuth: vi.fn(),
23 logoutAuth: vi.fn(),
24 startInstall: vi.fn(),
25 cancelInstall: vi.fn(),
26 removeInstall: vi.fn(),
27 confirm: vi.fn(),
28}));
29​
30vi.mock("react", async (importOriginal) => {
31 const actual = await importOriginal<typeof import("react")>();
32 const { reactHookHarness } = await import("../../test/reactHookHarness");
33 return {
34 ...actual,
35 useRef: reactHookHarness.useRef,
36 useState: reactHookHarness.useState,
37 };
38});
39​
40vi.mock("react/compiler-runtime", async () => {
41 const { reactHookHarness } = await import("../../test/reactHookHarness");
42 return { c: reactHookHarness.useMemoCache };
43});
44​
45vi.mock("../../state/server", () => ({
46 serverEnvironment: {
47 providerAuthState: setup.authState,
48 providerInstallState: setup.installState,
49 startProviderAuth: setup.startAuth,
50 completeProviderAuth: setup.completeAuth,
51 cancelProviderAuth: setup.cancelAuth,
52 logoutProviderAuth: setup.logoutAuth,
53 startProviderInstall: setup.startInstall,
54 cancelProviderInstall: setup.cancelInstall,
55 removeProviderInstallation: setup.removeInstall,
56 },
57}));
58​
59vi.mock("../../state/use-atom-command", () => ({
60 useAtomCommand: (command: unknown) => command,
61}));
62​
63vi.mock("../../state/query", () => ({
64 useEnvironmentQuery: (atom: string) => ({
65 data: atom === "auth" ? setup.auth : setup.installation,
66 error: null,
67 isPending: false,
68 refresh: vi.fn(),
69 }),
70}));
71​
72vi.mock("../../localApi", () => ({
73 ensureLocalApi: () => ({ dialogs: { confirm: setup.confirm } }),
74}));
75​
76import { ProviderSetupSection } from "./ProviderSetupSection";
77​
78const environmentId = EnvironmentId.make("remote-google");
79const instanceId = ProviderInstanceId.make("antigravity_work");
80const provider: ServerProvider = {
81 instanceId,
82 driver: ProviderDriverKind.make("antigravity"),
83 installed: true,
84 enabled: true,
85 version: "test-version",
86 status: "error",
87 auth: { status: "unauthenticated" },
88 checkedAt: "2026-09-02T00:00:00.000Z",
89 models: [],
90 skills: [],
91 slashCommands: [],
92 setup: { canAuthenticate: true, canInstall: true },
93};
94​
95function authState(patch: Partial<ProviderAuthState> = {}): ProviderAuthState {
96 return {
97 instanceId,
98 phase: "waiting",
99 flowId: "flow-1",
100 authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth?state=test-only",
101 expiresAt: "2026-09-02T00:05:00.000Z",
102 message: null,
103 ...patch,
104 };
106​
107function renderSetup(
108 options: {
109 readOnly?: boolean;
110 provider?: ServerProvider;
111 enabled?: boolean;
112 binaryPath?: string;
113 } = {},
114) {
115 hooks.beginRender();
116 const view = ProviderSetupSection({
117 environmentId,
118 environmentLabel: "Remote Google device",
119 instanceId,
120 provider: options.provider ?? provider,
121 binaryPath: options.binaryPath,
122 enabled: options.enabled ?? true,
123 readOnly: options.readOnly ?? false,
124 onEnable: vi.fn(),
125 });
126 const actions = visitElements(
127 view,
128 (element) =>
129 typeof element.type === "function" &&
130 element.props.environmentId === environmentId &&
131 element.props.instanceId === instanceId,
132 );
133 if (!actions) return view;
134 const Actions = actions.type as FunctionComponent<Record<string, unknown>>;
135 return Actions(actions.props) as ReactElement<Record<string, unknown>>;
137​
138function button(view: unknown, label: string) {
139 return visitElements(
140 view,
141 (element) =>
142 (element.props.children === label || element.props["aria-label"] === label) &&
143 typeof element.props.onClick === "function",
144 );
146​
147function countElements(
148 node: unknown,
149 predicate: (element: ReactElement<Record<string, unknown>>) => boolean,
150): number {
151 if (Array.isArray(node)) {
152 return node.reduce((total, child) => total + countElements(child, predicate), 0);
153 }
154 if (!isValidElement<Record<string, unknown>>(node)) return 0;
155 return (
156 Number(predicate(node)) +
157 Object.values(node.props).reduce<number>(
158 (total, value) => total + countElements(value, predicate),
159 0,
160 )
161 );
163​
164function click(view: unknown, label: string) {
165 const target = button(view, label);
166 if (!target) throw new Error(`Missing button: ${label}`);
167 if (target.props.disabled) throw new Error(`Button is disabled: ${label}`);
168 (target.props.onClick as () => void)();
170​
171function setCallback(view: unknown, value: string) {
172 const input = visitElements(
173 view,
174 (element) => element.props.id === `provider-callback-${instanceId}`,
175 );
176 if (!input) throw new Error("Missing callback input.");
177 (input.props.onChange as (event: { target: { value: string } }) => void)({ target: { value } });
179​
180function submitCallback(view: unknown) {
181 const form = visitElements(view, (element) => element.type === "form");
182 if (!form) throw new Error("Missing callback form.");
183 (form.props.onSubmit as (event: { preventDefault: () => void }) => void)({
184 preventDefault: vi.fn(),
185 });
187​
188async function flushPromises() {
189 await Promise.resolve();
190 await Promise.resolve();
191 await Promise.resolve();
193​
194describe("Antigravity setup", () => {
195 beforeEach(() => {
196 hooks.reset();
197 vi.clearAllMocks();
198 setup.auth = authState();
199 setup.installation = {
200 driver: ProviderDriverKind.make("antigravity"),
201 operationId: null,
202 phase: "idle",
203 downloadedBytes: 0,
204 totalBytes: null,
205 version: null,
206 installedVersion: null,
207 canRemove: false,
208 message: null,
209 };
210 for (const command of [
211 setup.startAuth,
212 setup.completeAuth,
213 setup.cancelAuth,
214 setup.logoutAuth,
215 setup.startInstall,
216 setup.cancelInstall,
217 setup.removeInstall,
218 ]) {
219 command.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
220 }
221 setup.confirm.mockReset().mockResolvedValue(false);
222 });
223​
224 it("waits for verified auth after submitting a callback to the selected environment", async () => {
225 const callbackUrl = "http://127.0.0.1:5555/?state=test-only&code=test-only";
226 setCallback(renderSetup(), callbackUrl);
227 submitCallback(renderSetup());
228 await flushPromises();
229​
230 expect(setup.completeAuth).toHaveBeenCalledWith({
231 environmentId,
232 input: { instanceId, flowId: "flow-1", callbackUrl },
233 });
234 let view = renderSetup();
235 expect(
236 visitElements(view, (element) => element.props.children === "Signed in with Google."),
237 ).toBeNull();
238 expect(
239 visitElements(view, (element) => element.props.id === `provider-callback-${instanceId}`)
240 ?.props.value,
241 ).toBe("");
242​
243 setup.auth = authState({ phase: "verifying", authorizationUrl: null });
244 expect(
245 visitElements(
246 renderSetup(),
247 (element) => element.props.children === "Signed in with Google.",
248 ),
249 ).toBeNull();
250 setup.auth = authState({ phase: "succeeded", authorizationUrl: null });
251 view = renderSetup({
252 provider: { ...provider, status: "ready", auth: { status: "authenticated" } },
253 });
254 expect(
255 visitElements(view, (element) => element.props.children === "Signed in with Google."),
256 ).not.toBeNull();
257 });
258​
259 it("offers sign-in again when credentials expire after a completed auth flow", () => {
260 setup.auth = authState({
261 phase: "succeeded",
262 authorizationUrl: null,
263 message: "Google sign-in complete.",
264 });
265 renderSetup({
266 provider: { ...provider, status: "ready", auth: { status: "authenticated" } },
267 });
268 const expired = renderSetup();
269 expect(button(expired, "Sign in with Google")).not.toBeNull();
270 expect(
271 visitElements(expired, (element) => element.props.children === "Signed in with Google."),
272 ).toBeNull();
273 expect(
274 visitElements(expired, (element) => element.props.children === "Google sign-in complete."),
275 ).toBeNull();
276 });
277​
278 it("does not send a callback left over from a replaced sign-in flow", async () => {
279 setCallback(renderSetup(), "http://127.0.0.1:5555/?state=old-flow&code=test-only");
280 setup.auth = authState({ flowId: "flow-2" });
281 submitCallback(renderSetup());
282 await flushPromises();
283​
284 expect(setup.completeAuth).not.toHaveBeenCalled();
285 expect(setup.authState).toHaveBeenLastCalledWith({ environmentId, input: { instanceId } });
286 });
287​
288 it("coalesces repeated sign-in clicks while start is pending", async () => {
289 setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
290 let completeStart: (value: { _tag: "Success"; value: undefined }) => void = () => {
291 throw new Error("Missing start resolver.");
292 };
293 const pending = new Promise<{ _tag: "Success"; value: undefined }>((resolve) => {
294 completeStart = resolve;
295 });
296 setup.startAuth.mockReturnValueOnce(pending);
297 const view = renderSetup();
298 click(view, "Sign in with Google");
299 click(view, "Sign in with Google");
300​
301 expect(setup.startAuth).toHaveBeenCalledTimes(1);
302 expect(setup.startAuth).toHaveBeenCalledWith({ environmentId, input: { instanceId } });
303 completeStart({ _tag: "Success", value: undefined });
304 await flushPromises();
305 });
306​
307 it("shows a repeated runtime status message only once", () => {
308 setup.installation = {
309 ...setup.installation!,
310 operationId: "install-1",
311 phase: "verifying",
312 message: "Checking the downloaded runtime.",
313 };
314​
315 const view = renderSetup();
316 expect(
317 countElements(
318 view,
319 (element) => element.props.children === "Checking the downloaded runtime.",
320 ),
321 ).toBe(1);
322 });
323​
324 it("removes an owned damaged runtime only after confirmation", async () => {
325 setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
326 setup.installation = {
327 ...setup.installation!,
328 phase: "failed",
329 canRemove: true,
330 installedVersion: null,
331 };
332 const view = renderSetup();
333 click(view, "Remove downloaded runtime");
334 await flushPromises();
335 expect(setup.removeInstall).not.toHaveBeenCalled();
336​
337 setup.confirm.mockResolvedValue(true);
338 click(view, "Remove downloaded runtime");
339 await flushPromises();
340 expect(setup.removeInstall).toHaveBeenCalledWith({ environmentId, input: { instanceId } });
341 });
342​
343 it.each([true, false])(
344 "can sign out an unchecked account when its instance is enabled=%s",
345 async (enabled) => {
346 setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
347 setup.confirm.mockResolvedValue(true);
348 const view = renderSetup({
349 enabled,
350 provider: {
351 ...provider,
352 enabled,
353 installed: false,
354 status: enabled ? "warning" : "disabled",
355 auth: { status: "unknown" },
356 },
357 });
358 click(view, "Sign out of Google");
359 await flushPromises();
360 expect(setup.logoutAuth).toHaveBeenCalledWith({ environmentId, input: { instanceId } });
361 },
362 );
363​
364 it("does not let a shared managed install hide an invalid custom binary path", () => {
365 setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
366 setup.installation = {
367 ...setup.installation!,
368 installedVersion: "test-version",
369 canRemove: true,
370 };
371 const view = renderSetup({
372 provider: { ...provider, installed: false },
373 binaryPath: "/missing/antigravity",
374 });
375 expect(button(view, "Sign in with Google")?.props.disabled).toBe(true);
376 expect(setup.startAuth).not.toHaveBeenCalled();
377 });
378​
379 it.each(["read-only", "older-server"] as const)(
380 "does not open private setup subscriptions for a %s view",
381 (mode) => {
382 const { setup: _setup, ...olderProvider } = provider;
383 renderSetup(mode === "read-only" ? { readOnly: true } : { provider: olderProvider });
384 expect(setup.authState).not.toHaveBeenCalled();
385 expect(setup.installState).not.toHaveBeenCalled();
386 expect(setup.startAuth).not.toHaveBeenCalled();
387 },
388 );
389});