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

ProviderSetupSection.browser.test.tsx

284 lines9.2 KB

1import {
2 EnvironmentId,
3 ProviderDriverKind,
4 ProviderInstanceId,
5 type ProviderAuthState,
6 type ProviderInstallState,
7 type ServerProvider,
8} from "@t3tools/contracts";
9import { userEvent } from "vite-plus/test/browser";
10import { describe, expect, it, vi } from "vite-plus/test";
11​
12import { act, render } from "../../../test/render";
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}));
53const queryListeners = vi.hoisted(() => new Set<() => void>());
54vi.mock(import("../../state/query"), async (original) => {
55 const { useSyncExternalStore } = await import("react");
56 const subscribe = (listener: () => void) => {
57 queryListeners.add(listener);
58 return () => queryListeners.delete(listener);
59 };
60 return {
61 ...(await original()),
62 useEnvironmentQuery: ((atom: string) => ({
63 data: useSyncExternalStore(subscribe, () =>
64 atom === "auth" ? setup.auth : setup.installation,
65 ),
66 error: null,
67 isPending: false,
68 refresh: vi.fn(),
69 })) as never,
70 };
71});
72const publish = () =>
73 act(async () => {
74 for (const listener of queryListeners) listener();
75 });
76vi.mock(import("../../localApi"), async (original) => ({
77 ...(await original()),
78 ensureLocalApi: () => ({ dialogs: { confirm: setup.confirm } }) as never,
79}));
80​
81import { ProviderSetupSection } from "./ProviderSetupSection";
82​
83const environmentId = EnvironmentId.make("remote-google");
84const instanceId = ProviderInstanceId.make("antigravity_work");
85const provider: ServerProvider = {
86 instanceId,
87 driver: ProviderDriverKind.make("antigravity"),
88 installed: true,
89 enabled: true,
90 version: "test-version",
91 status: "error",
92 auth: { status: "unauthenticated" },
93 checkedAt: "2026-09-02T00:00:00.000Z",
94 models: [],
95 skills: [],
96 slashCommands: [],
97 setup: { canAuthenticate: true, canInstall: true },
98};
99​
100function authState(patch: Partial<ProviderAuthState> = {}): ProviderAuthState {
101 return {
102 instanceId,
103 phase: "waiting",
104 flowId: "flow-1",
105 authorizationUrl: "https://accounts.google.com/o/oauth2/v2/auth?state=test-only",
106 expiresAt: "2026-09-02T00:05:00.000Z",
107 message: null,
108 ...patch,
109 };
111​
112interface SectionOptions {
113 readOnly?: boolean;
114 provider?: ServerProvider;
115 enabled?: boolean;
116 binaryPath?: string;
118​
119function section(options: SectionOptions = {}) {
120 return (
121 <ProviderSetupSection
122 environmentId={environmentId}
123 environmentLabel="Remote Google device"
124 instanceId={instanceId}
125 provider={options.provider ?? provider}
126 binaryPath={options.binaryPath}
127 enabled={options.enabled ?? true}
128 readOnly={options.readOnly ?? false}
129 onEnable={vi.fn()}
130 />
131 );
133​
134async function renderSetup(options: SectionOptions = {}) {
135 const screen = await render(section(options));
136 const { container } = screen;
137 const button = (label: string) =>
138 [...container.querySelectorAll("button")].find(
139 (element) => element.textContent === label || element.getAttribute("aria-label") === label,
140 ) ?? null;
141 return Object.assign(screen, {
142 button,
143 async click(label: string) {
144 const target = button(label);
145 expect(target, `button ${label}`).not.toBeNull();
146 expect(target!.disabled, `${label} disabled`).toBe(false);
147 await act(async () => target!.click());
148 },
149 occurrences: (text: string) => (container.textContent ?? "").split(text).length - 1,
150 callbackInput: () =>
151 container.querySelector<HTMLInputElement>(`[id="provider-callback-${instanceId}"]`)!,
152 });
154​
155function resetSetup() {
156 vi.clearAllMocks();
157 setup.auth = authState();
158 setup.installation = {
159 driver: ProviderDriverKind.make("antigravity"),
160 operationId: null,
161 phase: "idle",
162 downloadedBytes: 0,
163 totalBytes: null,
164 version: null,
165 installedVersion: null,
166 canRemove: false,
167 message: null,
168 };
169 for (const command of [
170 setup.startAuth,
171 setup.completeAuth,
172 setup.cancelAuth,
173 setup.logoutAuth,
174 setup.startInstall,
175 setup.cancelInstall,
176 setup.removeInstall,
177 ]) {
178 command.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
179 }
180 setup.confirm.mockReset().mockResolvedValue(false);
182​
183describe("Antigravity setup", () => {
184 it("can start installation before the first install snapshot arrives", async () => {
185 resetSetup();
186 setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
187 const idleInstallation = setup.installation!;
188 setup.installation = null;
189 let resolveStart!: () => void;
190 const command = new Promise<{ _tag: "Success"; value: undefined }>((resolve) => {
191 resolveStart = () => resolve({ _tag: "Success", value: undefined });
192 });
193 setup.startInstall.mockReturnValueOnce(command);
194 await using screen = await renderSetup({ provider: { ...provider, installed: false } });
195​
196 await screen.click("Install Antigravity");
197 await expect
198 .element(screen.getByRole("status").filter({ hasText: "Starting installation." }))
199 .toBeVisible();
200​
201 setup.installation = {
202 ...idleInstallation,
203 operationId: "install-1",
204 phase: "downloading",
205 downloadedBytes: 1_000_000,
206 totalBytes: 2_000_000,
207 };
208 await publish();
209 await expect
210 .element(screen.getByRole("button", { name: "Cancel installation" }))
211 .toBeDisabled();
212 await act(async () => resolveStart());
213 await expect.element(screen.getByRole("button", { name: "Cancel installation" })).toBeEnabled();
214 await expect
215 .element(screen.getByRole("status").filter({ hasText: "Downloading 1.0 MB of 2.0 MB." }))
216 .toBeVisible();
217 });
218​
219 it("waits for verified auth after submitting a callback to the selected environment", async () => {
220 resetSetup();
221 const callbackUrl = "http://127.0.0.1:5555/?state=test-only&code=test-only";
222 await using screen = await renderSetup();
223 await userEvent.fill(screen.callbackInput(), callbackUrl);
224 await screen.click("Continue");
225​
226 expect(setup.completeAuth).toHaveBeenCalledWith({
227 environmentId,
228 input: { instanceId, flowId: "flow-1", callbackUrl },
229 });
230 expect(screen.occurrences("Signed in.")).toBe(0);
231 expect(screen.callbackInput().value).toBe("");
232​
233 setup.auth = authState({ phase: "verifying", authorizationUrl: null });
234 await publish();
235 expect(screen.occurrences("Signed in.")).toBe(0);
236 setup.auth = authState({ phase: "succeeded", authorizationUrl: null });
237 await screen.rerender(
238 section({
239 provider: { ...provider, status: "ready", auth: { status: "authenticated" } },
240 }),
241 );
242 expect(screen.occurrences("Signed in.")).toBe(1);
243 });
244​
245 it("does not send a callback left over from a replaced sign-in flow", async () => {
246 resetSetup();
247 const interaction = {
248 type: "browser" as const,
249 id: "same-interaction",
250 url: "https://example.com/login",
251 requiresConsent: false,
252 acceptsCallback: true,
253 };
254 setup.auth = authState({ interaction });
255 await using screen = await renderSetup();
256 await userEvent.fill(
257 screen.callbackInput(),
258 "http://127.0.0.1:5555/?state=old-flow&code=test-only",
259 );
260 setup.auth = authState({ flowId: "flow-2", interaction });
261 await publish();
262 expect(screen.callbackInput().value).toBe("");
263 await act(async () => screen.callbackInput().form!.requestSubmit());
264​
265 expect(setup.completeAuth).not.toHaveBeenCalled();
266 expect(setup.authState).toHaveBeenLastCalledWith({ environmentId, input: { instanceId } });
267 });
268​
269 it("does not let a shared managed install hide an invalid custom binary path", async () => {
270 resetSetup();
271 setup.auth = authState({ phase: "idle", flowId: null, authorizationUrl: null });
272 setup.installation = {
273 ...setup.installation!,
274 installedVersion: "test-version",
275 canRemove: true,
276 };
277 await using screen = await renderSetup({
278 provider: { ...provider, installed: false },
279 binaryPath: "/missing/antigravity",
280 });
281 expect(screen.button("Sign in")?.disabled).toBe(true);
282 expect(setup.startAuth).not.toHaveBeenCalled();
283 });
284});