Open History to see the last commit
1import {
2 EnvironmentId,
3 ProviderDriverKind,
4 ProviderInstanceId,
5 type ProviderAuthState,
6 type ProviderInstallState,
7 type ServerProvider,
8} from "@t3tools/contracts";
9import { act } from "react";
10import { createRoot, type Root } from "react-dom/client";
11import { userEvent } from "vite-plus/test/browser";
12import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
13
14const setup = vi.hoisted(() => ({
15 auth: null as ProviderAuthState | null,
16 installation: null as ProviderInstallState | null,
17 authState: vi.fn(() => "auth"),
18 installState: vi.fn(() => "installation"),
19 startAuth: vi.fn(),
20 completeAuth: vi.fn(),
21 respondAuth: 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(import("../../state/server"), async (original) => {
31 const actual = await original();
32 return {
33 ...actual,
34 serverEnvironment: {
35 ...actual.serverEnvironment,
36 providerAuthState: setup.authState as never,
37 providerInstallState: setup.installState as never,
38 startProviderAuth: setup.startAuth as never,
39 completeProviderAuth: setup.completeAuth as never,
40 respondProviderAuth: setup.respondAuth as never,
41 cancelProviderAuth: setup.cancelAuth as never,
42 logoutProviderAuth: setup.logoutAuth as never,
43 startProviderInstall: setup.startInstall as never,
44 cancelProviderInstall: setup.cancelInstall as never,
45 removeProviderInstallation: setup.removeInstall as never,
46 },
47 };
48});
49vi.mock(import("../../state/use-atom-command"), async (original) => ({
50 ...(await original()),
51 useAtomCommand: ((command: unknown) => command) as never,
52}));
53// The queries behave like live subscriptions: changing `setup.auth` and calling
54// `publish()` re-renders the sections that read them.
55const queryListeners = vi.hoisted(() => new Set<() => void>());
56vi.mock(import("../../state/query"), async (original) => {
57 const { useSyncExternalStore } = await import("react");
58 const subscribe = (listener: () => void) => {
59 queryListeners.add(listener);
60 return () => queryListeners.delete(listener);
61 };
62 return {
63 ...(await original()),
64 useEnvironmentQuery: ((atom: string) => ({
65 data: useSyncExternalStore(subscribe, () =>
66 atom === "auth" ? setup.auth : setup.installation,
67 ),
68 error: null,
69 isPending: false,
70 refresh: vi.fn(),
71 })) as never,
72 };
73});
74const publish = () =>
75 act(async () => {
76 for (const listener of queryListeners) listener();
77 });
78vi.mock(import("../../localApi"), async (original) => ({
79 ...(await original()),
80 ensureLocalApi: () => ({ dialogs: { confirm: setup.confirm } }) as never,
81}));
82
83import { ProviderSetupSection } from "./ProviderSetupSection";
84
85const environmentId = EnvironmentId.make("remote-google");
86const instanceId = ProviderInstanceId.make("antigravity_work");
87const provider: ServerProvider = {
88 instanceId,
89 driver: ProviderDriverKind.make("antigravity"),
90 installed: true,
91 enabled: true,
92 version: "test-version",
93 status: "error",
94 auth: { status: "unauthenticated" },
95 checkedAt: "2026-09-02T00:00:00.000Z",
96 models: [],
97 skills: [],
98 slashCommands: [],
99 setup: { canAuthenticate: true, canInstall: true },
100};
101
102function authState(patch: Partial<ProviderAuthState> = {}): ProviderAuthState {
103 return {
104 instanceId,
105 phase: "waiting",
106 flowId: "flow-1",
107 authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth?state=test-only",
108 expiresAt: "2026-09-02T00:05:00.000Z",
109 message: null,
110 ...patch,
111 };
112}
113
114function deferred<T>() {
115 let resolve!: (value: T) => void;
116 const promise = new Promise<T>((done) => {
117 resolve = done;
118 });
119 return { promise, resolve };
120}
121
122let root: Root;
123let container: HTMLDivElement;
124
125function renderSetup(
126 options: {
127 readOnly?: boolean;
128 provider?: ServerProvider;
129 enabled?: boolean;
130 binaryPath?: string;
131 } = {},
132) {
133 return act(async () =>
134 root.render(
135 <ProviderSetupSection
136 environmentId={environmentId}
137 environmentLabel="Remote Google device"
138 instanceId={instanceId}
139 provider={options.provider ?? provider}
140 binaryPath={options.binaryPath}
141 enabled={options.enabled ?? true}
142 readOnly={options.readOnly ?? false}
143 onEnable={vi.fn()}
144 />,
145 ),
146 );
147}
148
149function button(label: string) {
150 return (
151 [...container.querySelectorAll("button")].find(
152 (element) => element.textContent === label || element.getAttribute("aria-label") === label,
153 ) ?? null
154 );
155}
156async function click(label: string) {
157 const target = button(label);
158 expect(target, `button ${label}`).not.toBeNull();
159 expect(target!.disabled, `${label} disabled`).toBe(false);
160 await act(async () => target!.click());
161}
162function occurrences(text: string) {
163 return (container.textContent ?? "").split(text).length - 1;
164}
165const callbackInput = () =>
166 container.querySelector<HTMLInputElement>(`[id="provider-callback-${instanceId}"]`)!;
167
168describe("Antigravity setup", () => {
169 beforeEach(() => {
170 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
171 vi.clearAllMocks();
172 setup.auth = authState();
173 setup.installation = {
174 driver: ProviderDriverKind.make("antigravity"),
175 operationId: null,
176 phase: "idle",
177 downloadedBytes: 0,
178 totalBytes: null,
179 version: null,
180 installedVersion: null,
181 canRemove: false,
182 message: null,
183 };
184 for (const command of [
185 setup.startAuth,
186 setup.completeAuth,
187 setup.cancelAuth,
188 setup.logoutAuth,
189 setup.startInstall,
190 setup.cancelInstall,
191 setup.removeInstall,
192 ]) {
193 command.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
194 }
195 setup.confirm.mockReset().mockResolvedValue(false);
196 container = document.createElement("div");
197 document.body.append(container);
198 root = createRoot(container);
199 });
200
201 afterEach(async () => {
202 await act(async () => root.unmount());
203 container.remove();
204 vi.unstubAllGlobals();
205 });
206
207 it("waits for verified auth after submitting a callback to the selected environment", async () => {
208 const callbackUrl = "http://127.0.0.1:5555/?state=test-only&code=test-only";
209 await renderSetup();
210 await act(async () => userEvent.fill(callbackInput(), callbackUrl));
211 await click("Continue");
212
213 expect(setup.completeAuth).toHaveBeenCalledWith({
214 environmentId,
215 input: { instanceId, flowId: "flow-1", callbackUrl },
216 });
217 expect(occurrences("Signed in.")).toBe(0);
218 expect(callbackInput().value).toBe("");
219
220 setup.auth = authState({ phase: "verifying", authorizationUrl: null });
221 await publish();
222 expect(occurrences("Signed in.")).toBe(0);
223 setup.auth = authState({ phase: "succeeded", authorizationUrl: null });
224 await renderSetup({
225 provider: { ...provider, status: "ready", auth: { status: "authenticated" } },
226 });
227 expect(occurrences("Signed in.")).toBe(1);
228 });
229
230 it("offers sign-in again when credentials expire after a completed auth flow", async () => {
231 setup.auth = authState({
232 phase: "succeeded",
233 authorizationUrl: null,
234 message: "Google sign-in complete.",
235 });
236 await renderSetup({
237 provider: { ...provider, status: "ready", auth: { status: "authenticated" } },
238 });
239 await renderSetup();
240 expect(button("Sign in")).not.toBeNull();
241 expect(occurrences("Signed in.")).toBe(0);
242 expect(occurrences("Google sign-in complete.")).toBe(0);
243 });
244
245 it("does not send a callback left over from a replaced sign-in flow", async () => {
246 const interaction = {
247 type: "browser" as const,
248 id: "same-interaction",
249 url: "https://example.com/login",
250 requiresConsent: false,
251 acceptsCallback: true,
252 };
253 setup.auth = authState({ interaction });
254 await renderSetup();
255 await act(async () =>
256 userEvent.fill(callbackInput(), "http://127.0.0.1:5555/?state=old-flow&code=test-only"),
257 );
258 setup.auth = authState({ flowId: "flow-2", interaction });
259 await publish();
260 expect(callbackInput().value).toBe("");
261 await act(async () => callbackInput().form!.requestSubmit());
262
263 expect(setup.completeAuth).not.toHaveBeenCalled();
264 expect(setup.authState).toHaveBeenLastCalledWith({ environmentId, input: { instanceId } });
265 });
266
267 it("coalesces repeated sign-in clicks while start is pending", async () => {
268 setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
269 const pending = deferred<{ _tag: "Success"; value: undefined }>();
270 setup.startAuth.mockReturnValueOnce(pending.promise);
271 await renderSetup();
272 const signIn = button("Sign in")!;
273 // Both clicks land before React re-renders the button as disabled.
274 await act(async () => {
275 signIn.click();
276 signIn.click();
277 });
278
279 expect(setup.startAuth).toHaveBeenCalledTimes(1);
280 expect(setup.startAuth).toHaveBeenCalledWith({ environmentId, input: { instanceId } });
281 await act(async () => pending.resolve({ _tag: "Success", value: undefined }));
282 });
283
284 it("shows a repeated runtime status message only once", async () => {
285 setup.installation = {
286 ...setup.installation!,
287 operationId: "install-1",
288 phase: "verifying",
289 message: "Checking the downloaded runtime.",
290 };
291
292 await renderSetup();
293 expect(occurrences("Checking the downloaded runtime.")).toBe(1);
294 });
295
296 it("removes an owned damaged runtime only after confirmation", async () => {
297 setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
298 setup.installation = {
299 ...setup.installation!,
300 phase: "failed",
301 canRemove: true,
302 installedVersion: null,
303 };
304 await renderSetup();
305 await click("Remove downloaded runtime");
306 expect(setup.confirm).toHaveBeenCalledOnce();
307 expect(setup.removeInstall).not.toHaveBeenCalled();
308
309 setup.confirm.mockResolvedValue(true);
310 await click("Remove downloaded runtime");
311 expect(setup.removeInstall).toHaveBeenCalledWith({ environmentId, input: { instanceId } });
312 });
313
314 it.each([true, false])(
315 "can sign out a verified account when its instance is enabled=%s",
316 async (enabled) => {
317 setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
318 setup.confirm.mockResolvedValue(true);
319 await renderSetup({
320 enabled,
321 provider: {
322 ...provider,
323 enabled,
324 installed: false,
325 status: enabled ? "warning" : "disabled",
326 auth: { status: "authenticated" },
327 },
328 });
329 await click("Sign out");
330 expect(setup.logoutAuth).toHaveBeenCalledWith({ environmentId, input: { instanceId } });
331 },
332 );
333
334 it.each(["unauthenticated", "unknown"] as const)(
335 "does not offer sign-out for an unverified %s account",
336 async (status) => {
337 setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
338 await renderSetup({
339 provider: { ...provider, auth: { status, canLogout: true } },
340 });
341 expect(button("Sign in")).not.toBeNull();
342 expect(button("Sign out")).toBeNull();
343 expect(button("Change account")).toBeNull();
344 },
345 );
346
347 it("offers account actions after verified login when discovery cannot identify auth", async () => {
348 setup.auth = authState({ phase: "succeeded", flowId: null, authorizationUrl: null });
349 await renderSetup({ provider: { ...provider, auth: { status: "unknown" } } });
350 expect(button("Change account")).not.toBeNull();
351 expect(button("Sign out")).not.toBeNull();
352 expect(button("Sign in")).toBeNull();
353 });
354
355 it("does not let a shared managed install hide an invalid custom binary path", async () => {
356 setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
357 setup.installation = {
358 ...setup.installation!,
359 installedVersion: "test-version",
360 canRemove: true,
361 };
362 await renderSetup({
363 provider: { ...provider, installed: false },
364 binaryPath: "/missing/antigravity",
365 });
366 expect(button("Sign in")?.disabled).toBe(true);
367 expect(setup.startAuth).not.toHaveBeenCalled();
368 });
369
370 it.each(["read-only", "older-server"] as const)(
371 "does not open private setup subscriptions for a %s view",
372 async (mode) => {
373 const { setup: _setup, ...olderProvider } = provider;
374 await renderSetup(mode === "read-only" ? { readOnly: true } : { provider: olderProvider });
375 expect(setup.authState).not.toHaveBeenCalled();
376 expect(setup.installState).not.toHaveBeenCalled();
377 expect(setup.startAuth).not.toHaveBeenCalled();
378 },
379 );
380});