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

ProviderSetupSection.test.tsx

353 lines11.4 KB

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