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

DesktopClerk.test.ts

386 lines15.0 KB

1// @effect-diagnostics nodeBuiltinImport:off globalFetchInEffect:off - Hosted handoff test uses a real localhost listener without an OpenAI account.
2import * as NodeHttp from "node:http";
3import * as NodePath from "@effect/platform-node/NodePath";
4import { codexAuthHandoffUrl, readCodexAuthDelivery } from "@t3tools/shared/codexAuthHandoff";
5import { EnvironmentId, ProviderInstanceId } from "@t3tools/contracts";
6import { HostProcessArguments } from "@t3tools/shared/hostProcess";
7import { assert, describe, it } from "@effect/vitest";
8import * as Cause from "effect/Cause";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import { beforeEach, vi } from "vite-plus/test";
12​
13const { createClerkBridgeMock, storageAdapter, storageMock } = vi.hoisted(() => ({
14 createClerkBridgeMock: vi.fn(),
15 storageAdapter: {
16 getItem: vi.fn(),
17 setItem: vi.fn(),
18 removeItem: vi.fn(),
19 },
20 storageMock: vi.fn(),
21}));
22​
23vi.mock("@clerk/electron", () => ({
24 createClerkBridge: createClerkBridgeMock,
25}));
26​
27vi.mock("@clerk/electron/storage", () => ({
28 storage: storageMock,
29}));
30​
31import * as Option from "effect/Option";
32import * as Exit from "effect/Exit";
33import * as FileSystem from "effect/FileSystem";
34import * as ElectronApp from "../electron/ElectronApp.ts";
35import * as ElectronShell from "../electron/ElectronShell.ts";
36import * as ElectronWindow from "../electron/ElectronWindow.ts";
37import * as DesktopClerk from "./DesktopClerk.ts";
38import * as DesktopEnvironment from "./DesktopEnvironment.ts";
39import * as DesktopPreReadyFileSystem from "./DesktopPreReadyFileSystem.ts";
40​
41const makeDesktopClerkLayer = (
42 isDevelopment = true,
43 events: string[] = [],
44 platform: NodeJS.Platform = "darwin",
45 fileSystemLayer: Layer.Layer<FileSystem.FileSystem> = FileSystem.layerNoop({
46 exists: () => Effect.succeed(false),
47 }),
48 shell: ElectronShell.ElectronShell["Service"] = {
49 openExternal: () => Effect.succeed(true),
50 openSystemSettings: () => Effect.succeed(false),
51 copyText: () => Effect.void,
52 },
53) => {
54 const environment = DesktopEnvironment.DesktopEnvironment.of({
55 stateDir: "/tmp/t3-state",
56 isDevelopment,
57 appDataDirectory: "/tmp/app-data",
58 platform,
59 } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
60​
61 const electronApp = {
62 setPath: (name: string, value: string) =>
63 Effect.sync(() => {
64 events.push(`setPath:${name}:${value}`);
65 }),
66 } as unknown as ElectronApp.ElectronApp["Service"];
67​
68 return DesktopClerk.layer.pipe(
69 Layer.provide(
70 Layer.mergeAll(
71 NodePath.layerPosix,
72 Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment),
73 Layer.succeed(ElectronApp.ElectronApp, electronApp),
74 Layer.succeed(ElectronShell.ElectronShell, shell),
75 fileSystemLayer,
76 ),
77 ),
78 );
79};
80​
81describe("DesktopClerk", () => {
82 beforeEach(() => {
83 createClerkBridgeMock.mockReset();
84 storageMock.mockReset();
85 });
86​
87 it.effect("acquires and releases the SDK bridge with the layer", () => {
88 const cleanup = vi.fn();
89 const events: string[] = [];
90 storageMock.mockReturnValue(storageAdapter);
91 createClerkBridgeMock.mockImplementation(() => {
92 events.push("createClerkBridge");
93 return { cleanup, isPrimaryInstance: true };
94 });
95​
96 return Effect.gen(function* () {
97 yield* Effect.scoped(Layer.build(makeDesktopClerkLayer(true, events)));
98​
99 assert.deepEqual(createClerkBridgeMock.mock.calls, [
100 [
101 {
102 storage: storageAdapter,
103 passkeys: true,
104 renderer: { scheme: "t3code-dev", host: "app" },
105 },
106 ],
107 ]);
108 assert.equal(cleanup.mock.calls.length, 1);
109 // The bridge acquires Electron's single-instance lock at creation, and
110 // the lock both lives in and creates the userData directory — so the
111 // real path must be set before the bridge exists.
112 assert.deepEqual(events, ["setPath:userData:/tmp/app-data/t3code-dev", "createClerkBridge"]);
113 storageMock.mockClear();
114 createClerkBridgeMock.mockClear();
115 });
116 });
117​
118 it.each([
119 {
120 name: "packaged Windows",
121 isDevelopment: false,
122 platform: "win32" as const,
123 userData: "/tmp/app-data/t3code-v2",
124 },
125 {
126 name: "development",
127 isDevelopment: true,
128 platform: "win32" as const,
129 userData: "/tmp/app-data/t3code-dev",
130 },
131 ])(
132 "creates the bridge before startup can yield to the event loop ($name)",
133 ({ isDevelopment, platform, userData }) => {
134 const events: string[] = [];
135 storageMock.mockReturnValue(storageAdapter);
136 createClerkBridgeMock.mockImplementation(() => {
137 events.push("createClerkBridge");
138 return { cleanup: vi.fn(), isPrimaryInstance: true };
139 });
140 // runSync throws if the layer ever suspends, which would let Electron emit
141 // ready before the bridge exists. main.ts provides the same FileSystem.
142 // oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- The assertion IS that the layer builds synchronously; it.effect would mask a regression to async.
143 Effect.runSync(
144 Effect.scoped(
145 Layer.build(
146 makeDesktopClerkLayer(isDevelopment, events, platform, DesktopPreReadyFileSystem.layer),
147 ),
148 ),
149 );
150​
151 assert.deepEqual(events, [`setPath:userData:${userData}`, "createClerkBridge"]);
152 },
153 );
154​
155 it.effect("preserves bridge initialization failures", () => {
156 const cause = new Error("bridge initialization failed");
157 storageMock.mockReturnValue(storageAdapter);
158 createClerkBridgeMock.mockImplementationOnce(() => {
159 throw cause;
160 });
161​
162 return Effect.gen(function* () {
163 const error = yield* Effect.scoped(Layer.build(makeDesktopClerkLayer())).pipe(Effect.flip);
164​
165 assert.instanceOf(error, DesktopClerk.DesktopClerkBridgeInitializationError);
166 assert.equal(error.stateDir, "/tmp/t3-state");
167 assert.equal(error.isDevelopment, true);
168 assert.strictEqual(error.cause, cause);
169 assert.equal(
170 error.message,
171 'Failed to initialize the desktop Clerk bridge for state directory "/tmp/t3-state" (development: true).',
172 );
173 });
174 });
175​
176 it.effect("preserves bridge cleanup failures", () => {
177 const cause = new Error("bridge cleanup failed");
178 storageMock.mockReturnValue(storageAdapter);
179 createClerkBridgeMock.mockReturnValue({
180 cleanup: () => {
181 throw cause;
182 },
183 });
184​
185 return Effect.gen(function* () {
186 const exit = yield* Effect.exit(Effect.scoped(Layer.build(makeDesktopClerkLayer(false))));
187​
188 assert.equal(exit._tag, "Failure");
189 if (exit._tag === "Failure") {
190 const error = Cause.squash(exit.cause);
191 assert.instanceOf(error, DesktopClerk.DesktopClerkBridgeCleanupError);
192 assert.equal(error.stateDir, "/tmp/t3-state");
193 assert.equal(error.isDevelopment, false);
194 assert.strictEqual(error.cause, cause);
195 assert.equal(
196 error.message,
197 'Failed to clean up the desktop Clerk bridge for state directory "/tmp/t3-state" (development: false).',
198 );
199 }
200 });
201 });
202​
203 it.effect("registers the second-instance handler in the primary instance", () => {
204 storageMock.mockReturnValue(storageAdapter);
205 createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: true });
206 const quit = vi.fn();
207 const registeredEvents: string[] = [];
208 const electronApp = {
209 quit: Effect.sync(quit),
210 on: (eventName: string) =>
211 Effect.sync(() => {
212 registeredEvents.push(eventName);
213 }),
214 } as unknown as ElectronApp.ElectronApp["Service"];
215 const electronWindow = {} as ElectronWindow.ElectronWindow["Service"];
216​
217 return Effect.gen(function* () {
218 const clerk = yield* DesktopClerk.DesktopClerk;
219 const exit = yield* Effect.exit(Effect.scoped(clerk.configure));
220​
221 assert.isTrue(Exit.isSuccess(exit));
222 assert.equal(quit.mock.calls.length, 0);
223 assert.deepEqual(registeredEvents, ["open-url", "second-instance"]);
224 }).pipe(
225 Effect.provide(makeDesktopClerkLayer()),
226 Effect.provideService(ElectronApp.ElectronApp, electronApp),
227 Effect.provideService(ElectronWindow.ElectronWindow, electronWindow),
228 );
229 });
230​
231 it.effect("quits and interrupts startup in a secondary instance", () => {
232 storageMock.mockReturnValue(storageAdapter);
233 createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: false });
234 const quit = vi.fn();
235 const registeredEvents: string[] = [];
236 const electronApp = {
237 quit: Effect.sync(quit),
238 on: (eventName: string) =>
239 Effect.sync(() => {
240 registeredEvents.push(eventName);
241 }),
242 } as unknown as ElectronApp.ElectronApp["Service"];
243 const electronWindow = {} as ElectronWindow.ElectronWindow["Service"];
244​
245 return Effect.gen(function* () {
246 const clerk = yield* DesktopClerk.DesktopClerk;
247 const exit = yield* Effect.exit(Effect.scoped(clerk.configure));
248​
249 assert.isTrue(Exit.hasInterrupts(exit));
250 assert.equal(quit.mock.calls.length, 1);
251 assert.deepEqual(registeredEvents, []);
252 }).pipe(
253 Effect.provide(makeDesktopClerkLayer()),
254 Effect.provideService(ElectronApp.ElectronApp, electronApp),
255 Effect.provideService(ElectronWindow.ElectronWindow, electronWindow),
256 );
257 });
258});
259​
260it.effect(
261 "provider auth deep links navigate and reveal the running desktop without handling Clerk URLs",
262 () => {
263 storageMock.mockReturnValue(storageAdapter);
264 createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: true });
265 const listeners = new Map<string, (...args: unknown[]) => void>();
266 const revealed = Promise.withResolvers<void>();
267 const loadURL = vi.fn(async (_url: string) => undefined);
268 const window = { loadURL };
269 const electronApp = {
270 on: (name: string, listener: (...args: unknown[]) => void) =>
271 Effect.sync(() => {
272 listeners.set(name, listener);
273 }),
274 } as unknown as ElectronApp.ElectronApp["Service"];
275 const electronWindow = {
276 currentMainOrFirst: Effect.succeed(Option.some(window)),
277 reveal: () => Effect.sync(() => revealed.resolve()),
278 } as unknown as ElectronWindow.ElectronWindow["Service"];
279 return Effect.gen(function* () {
280 const clerk = yield* DesktopClerk.DesktopClerk;
281 yield* clerk.configure;
282 const event = { preventDefault: vi.fn() };
283 listeners.get("open-url")!(event, "t3code-dev://app/auth/callback?code=clerk-code");
284 listeners.get("open-url")!(event, "t3code://app/welcome");
285 assert.equal(loadURL.mock.calls.length, 0);
286 assert.equal(event.preventDefault.mock.calls.length, 0);
287 listeners.get("second-instance")!({}, [
288 "t3",
289 "t3code-dev://app/settings/providers?instanceId=work&code=never-forward",
290 ]);
291 yield* Effect.promise(() => revealed.promise);
292 assert.deepEqual(loadURL.mock.calls, [
293 ["t3code-dev://app/settings/providers?instanceId=work"],
294 ]);
295 listeners.get("open-url")!(event, "t3code-dev://app/welcome#agents:machine-id");
296 assert.equal(event.preventDefault.mock.calls.length, 1);
297 }).pipe(
298 Effect.scoped,
299 Effect.provide(makeDesktopClerkLayer()),
300 Effect.provideService(ElectronApp.ElectronApp, electronApp),
301 Effect.provideService(ElectronWindow.ElectronWindow, electronWindow),
302 );
303 },
304);
305​
306for (const entry of ["startup", "open-url"] as const) {
307 it.effect(`receives hosted web sign-in through the desktop ${entry} handler`, () =>
308 Effect.gen(function* () {
309 storageMock.mockReturnValue(storageAdapter);
310 createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: true });
311 const port = yield* Effect.promise(async () => {
312 const server = NodeHttp.createServer();
313 await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
314 const address = server.address();
315 if (!address || typeof address === "string") throw new Error("address");
316 await new Promise<void>((resolve) => server.close(() => resolve()));
317 return address.port;
318 });
319 const authorize = new URL("https://auth.openai.com/api/accounts/authorize");
320 authorize.search = new URLSearchParams({
321 client_id: "dynamic_agent_client",
322 response_type: "code",
323 redirect_uri: `http://127.0.0.1:${port}/auth/callback`,
324 state: "a".repeat(43),
325 code_challenge_method: "S256",
326 code_challenge: "b".repeat(43),
327 }).toString();
328 const request = {
329 authorizationUrl: authorize.toString(),
330 returnUrl: "https://app.t3.codes/welcome#agents:remote-one",
331 environmentId: EnvironmentId.make("remote-one"),
332 instanceId: ProviderInstanceId.make("work"),
333 flowId: "flow-one",
334 };
335 const link = codexAuthHandoffUrl(request, true);
336 const delivered = Promise.withResolvers<string>();
337 const shell = ElectronShell.ElectronShell.of({
338 openExternal: (value) =>
339 Effect.promise(async () => {
340 const url = new URL(String(value));
341 const callback = new URL(url.searchParams.get("redirect_uri")!);
342 callback.search = new URLSearchParams({
343 state: url.searchParams.get("state")!,
344 code: "test-code",
345 client_id: "oaiapp_test",
346 }).toString();
347 const response = await fetch(callback, { redirect: "manual" });
348 delivered.resolve(response.headers.get("location")!);
349 return true;
350 }),
351 openSystemSettings: () => Effect.succeed(false),
352 copyText: () => Effect.void,
353 });
354 const listeners = new Map<string, (...args: unknown[]) => void>();
355 const electronApp = {
356 whenReady: Effect.void,
357 on: (name: string, listener: (...args: unknown[]) => void) =>
358 Effect.sync(() => {
359 listeners.set(name, listener);
360 }),
361 } as unknown as ElectronApp.ElectronApp["Service"];
362 yield* Effect.gen(function* () {
363 const clerk = yield* DesktopClerk.DesktopClerk;
364 yield* clerk.configure;
365 if (entry === "open-url") {
366 const event = { preventDefault: vi.fn() };
367 listeners.get("open-url")!(event, link);
368 assert.strictEqual(event.preventDefault.mock.calls.length, 1);
369 }
370 const delivery = readCodexAuthDelivery(yield* Effect.promise(() => delivered.promise));
371 assert.strictEqual(delivery?.environmentId, request.environmentId);
372 assert.strictEqual(delivery?.instanceId, request.instanceId);
373 assert.strictEqual(delivery?.flowId, request.flowId);
374 assert.strictEqual(delivery?.returnUrl, request.returnUrl);
375 }).pipe(
376 Effect.provide(makeDesktopClerkLayer(true, [], "darwin", undefined, shell)),
377 Effect.provideService(HostProcessArguments, entry === "startup" ? ["t3", link] : ["t3"]),
378 Effect.provideService(ElectronApp.ElectronApp, electronApp),
379 Effect.provideService(
380 ElectronWindow.ElectronWindow,
381 {} as ElectronWindow.ElectronWindow["Service"],
382 ),
383 );
384 }).pipe(Effect.scoped),
385 );