Open History to see the last commit
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 };
105}
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>>;
136}
137
138function button(view: unknown, label: string) {
139 return visitElements(
140 view,
141 (element) => element.props.children === label && typeof element.props.onClick === "function",
142 );
143}
144
145function countElements(
146 node: unknown,
147 predicate: (element: ReactElement<Record<string, unknown>>) => boolean,
148): number {
149 if (Array.isArray(node)) {
150 return node.reduce((total, child) => total + countElements(child, predicate), 0);
151 }
152 if (!isValidElement<Record<string, unknown>>(node)) return 0;
153 return (
154 Number(predicate(node)) +
155 Object.values(node.props).reduce<number>(
156 (total, value) => total + countElements(value, predicate),
157 0,
158 )
159 );
160}
161
162function click(view: unknown, label: string) {
163 const target = button(view, label);
164 if (!target) throw new Error(`Missing button: ${label}`);
165 if (target.props.disabled) throw new Error(`Button is disabled: ${label}`);
166 (target.props.onClick as () => void)();
167}
168
169function setCallback(view: unknown, value: string) {
170 const input = visitElements(
171 view,
172 (element) => element.props.id === `provider-callback-${instanceId}`,
173 );
174 if (!input) throw new Error("Missing callback input.");
175 (input.props.onChange as (event: { target: { value: string } }) => void)({ target: { value } });
176}
177
178function submitCallback(view: unknown) {
179 const form = visitElements(view, (element) => element.type === "form");
180 if (!form) throw new Error("Missing callback form.");
181 (form.props.onSubmit as (event: { preventDefault: () => void }) => void)({
182 preventDefault: vi.fn(),
183 });
184}
185
186async function flushPromises() {
187 await Promise.resolve();
188 await Promise.resolve();
189 await Promise.resolve();
190}
191
192describe("Antigravity setup", () => {
193 beforeEach(() => {
194 hooks.reset();
195 vi.clearAllMocks();
196 setup.auth = authState();
197 setup.installation = {
198 driver: ProviderDriverKind.make("antigravity"),
199 operationId: null,
200 phase: "idle",
201 downloadedBytes: 0,
202 totalBytes: null,
203 version: null,
204 installedVersion: null,
205 canRemove: false,
206 message: null,
207 };
208 for (const command of [
209 setup.startAuth,
210 setup.completeAuth,
211 setup.cancelAuth,
212 setup.logoutAuth,
213 setup.startInstall,
214 setup.cancelInstall,
215 setup.removeInstall,
216 ]) {
217 command.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
218 }
219 setup.confirm.mockReset().mockResolvedValue(false);
220 });
221
222 it("waits for verified auth after submitting a callback to the selected environment", async () => {
223 const callbackUrl = "http://127.0.0.1:5555/?state=test-only&code=test-only";
224 setCallback(renderSetup(), callbackUrl);
225 submitCallback(renderSetup());
226 await flushPromises();
227
228 expect(setup.completeAuth).toHaveBeenCalledWith({
229 environmentId,
230 input: { instanceId, flowId: "flow-1", callbackUrl },
231 });
232 let view = renderSetup();
233 expect(
234 visitElements(view, (element) => element.props.children === "Signed in with Google."),
235 ).toBeNull();
236 expect(
237 visitElements(view, (element) => element.props.id === `provider-callback-${instanceId}`)
238 ?.props.value,
239 ).toBe("");
240
241 setup.auth = authState({ phase: "verifying", authorizationUrl: null });
242 expect(
243 visitElements(
244 renderSetup(),
245 (element) => element.props.children === "Signed in with Google.",
246 ),
247 ).toBeNull();
248 setup.auth = authState({ phase: "succeeded", authorizationUrl: null });
249 view = renderSetup({
250 provider: { ...provider, status: "ready", auth: { status: "authenticated" } },
251 });
252 expect(
253 visitElements(view, (element) => element.props.children === "Signed in with Google."),
254 ).not.toBeNull();
255 });
256
257 it("offers sign-in again when credentials expire after a completed auth flow", () => {
258 setup.auth = authState({
259 phase: "succeeded",
260 authorizationUrl: null,
261 message: "Google sign-in complete.",
262 });
263 renderSetup({
264 provider: { ...provider, status: "ready", auth: { status: "authenticated" } },
265 });
266 const expired = renderSetup();
267 expect(button(expired, "Sign in with Google")).not.toBeNull();
268 expect(
269 visitElements(expired, (element) => element.props.children === "Signed in with Google."),
270 ).toBeNull();
271 expect(
272 visitElements(expired, (element) => element.props.children === "Google sign-in complete."),
273 ).toBeNull();
274 });
275
276 it("does not send a callback left over from a replaced sign-in flow", async () => {
277 setCallback(renderSetup(), "http://127.0.0.1:5555/?state=old-flow&code=test-only");
278 setup.auth = authState({ flowId: "flow-2" });
279 submitCallback(renderSetup());
280 await flushPromises();
281
282 expect(setup.completeAuth).not.toHaveBeenCalled();
283 expect(setup.authState).toHaveBeenLastCalledWith({ environmentId, input: { instanceId } });
284 });
285
286 it("coalesces repeated sign-in clicks while start is pending", async () => {
287 setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
288 let completeStart: (value: { _tag: "Success"; value: undefined }) => void = () => {
289 throw new Error("Missing start resolver.");
290 };
291 const pending = new Promise<{ _tag: "Success"; value: undefined }>((resolve) => {
292 completeStart = resolve;
293 });
294 setup.startAuth.mockReturnValueOnce(pending);
295 const view = renderSetup();
296 click(view, "Sign in with Google");
297 click(view, "Sign in with Google");
298
299 expect(setup.startAuth).toHaveBeenCalledTimes(1);
300 expect(setup.startAuth).toHaveBeenCalledWith({ environmentId, input: { instanceId } });
301 completeStart({ _tag: "Success", value: undefined });
302 await flushPromises();
303 });
304
305 it("shows a repeated runtime status message only once", () => {
306 setup.installation = {
307 ...setup.installation!,
308 operationId: "install-1",
309 phase: "verifying",
310 message: "Checking the downloaded runtime.",
311 };
312
313 const view = renderSetup();
314 expect(
315 countElements(
316 view,
317 (element) => element.props.children === "Checking the downloaded runtime.",
318 ),
319 ).toBe(1);
320 });
321
322 it("removes an owned damaged runtime only after confirmation", async () => {
323 setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
324 setup.installation = {
325 ...setup.installation!,
326 phase: "failed",
327 canRemove: true,
328 installedVersion: null,
329 };
330 const view = renderSetup();
331 click(view, "Remove downloaded runtime");
332 await flushPromises();
333 expect(setup.removeInstall).not.toHaveBeenCalled();
334
335 setup.confirm.mockResolvedValue(true);
336 click(view, "Remove downloaded runtime");
337 await flushPromises();
338 expect(setup.removeInstall).toHaveBeenCalledWith({ environmentId, input: { instanceId } });
339 });
340
341 it.each([true, false])(
342 "can sign out an unchecked account when its instance is enabled=%s",
343 async (enabled) => {
344 setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
345 setup.confirm.mockResolvedValue(true);
346 const view = renderSetup({
347 enabled,
348 provider: {
349 ...provider,
350 enabled,
351 installed: false,
352 status: enabled ? "warning" : "disabled",
353 auth: { status: "unknown" },
354 },
355 });
356 click(view, "Sign out of Google");
357 await flushPromises();
358 expect(setup.logoutAuth).toHaveBeenCalledWith({ environmentId, input: { instanceId } });
359 },
360 );
361
362 it("does not let a shared managed install hide an invalid custom binary path", () => {
363 setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
364 setup.installation = {
365 ...setup.installation!,
366 installedVersion: "test-version",
367 canRemove: true,
368 };
369 const view = renderSetup({
370 provider: { ...provider, installed: false },
371 binaryPath: "/missing/antigravity",
372 });
373 expect(button(view, "Sign in with Google")?.props.disabled).toBe(true);
374 expect(setup.startAuth).not.toHaveBeenCalled();
375 });
376
377 it.each(["read-only", "older-server"] as const)(
378 "does not open private setup subscriptions for a %s view",
379 (mode) => {
380 const { setup: _setup, ...olderProvider } = provider;
381 renderSetup(mode === "read-only" ? { readOnly: true } : { provider: olderProvider });
382 expect(setup.authState).not.toHaveBeenCalled();
383 expect(setup.installState).not.toHaveBeenCalled();
384 expect(setup.startAuth).not.toHaveBeenCalled();
385 },
386 );
387});