The best way to control Claude Code, Codex and more from any computer or phone

main
ts 559 lines 22.1 KB
Raw
1 import { assert, describe, it } from "@effect/vitest";
2 import { DESKTOP_UPDATE_IN_PROGRESS_TTL_MS } from "@t3tools/contracts";
3 import * as Deferred from "effect/Deferred";
4 import * as Duration from "effect/Duration";
5 import * as Effect from "effect/Effect";
6 import * as Fiber from "effect/Fiber";
7 import * as Queue from "effect/Queue";
8 import * as TestClock from "effect/testing/TestClock";
9 import * as FileSystem from "effect/FileSystem";
10 import * as Layer from "effect/Layer";
11 import * as Option from "effect/Option";
12 import * as Path from "effect/Path";
13 import * as Ref from "effect/Ref";
14 import * as Sink from "effect/Sink";
15 import * as Stream from "effect/Stream";
16 import { HttpClient, HttpClientResponse } from "effect/http";
17 import { ChildProcessSpawner } from "effect/process";
18
19 import * as DesktopConfig from "../app/DesktopConfig.ts";
20 import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
21 import * as DesktopObservability from "../app/DesktopObservability.ts";
22 import * as DesktopState from "../app/DesktopState.ts";
23 import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
24 import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
25 import * as DesktopBrowserHost from "../preview/DesktopBrowserHost.ts";
26 import * as ElectronDialog from "../electron/ElectronDialog.ts";
27 import * as ElectronApp from "../electron/ElectronApp.ts";
28 import * as DesktopWindow from "../window/DesktopWindow.ts";
29 import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
30 import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
31 import * as DesktopBackendPool from "./DesktopBackendPool.ts";
32 import type { DesktopBackendStartConfig } from "./DesktopBackendManager.ts";
33
34 // Models the spawner's release for a backend that ignores SIGTERM, without OS signals.
35 const makeFakeBackendProcess = Effect.fn("test.makeFakeBackendProcess")(function* () {
36 const started = yield* Deferred.make<void>();
37 const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
38 const signals = yield* Queue.unbounded<"SIGTERM" | "SIGKILL">();
39 let running = false;
40 const killWait = Duration.seconds(1);
41 const exit = Effect.sync(() => {
42 running = false;
43 }).pipe(Effect.andThen(Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0))), Effect.asVoid);
44 const layer = Layer.succeed(
45 ChildProcessSpawner.ChildProcessSpawner,
46 ChildProcessSpawner.make((command) =>
47 Effect.gen(function* () {
48 if (command._tag !== "StandardCommand") {
49 return yield* Effect.die("Expected a standard backend command");
50 }
51 const terminateGrace = Duration.fromInputUnsafe(command.options.forceKillAfter ?? 0);
52 running = true;
53 yield* Effect.addFinalizer(() =>
54 Effect.gen(function* () {
55 yield* Queue.offer(signals, "SIGTERM");
56 yield* Effect.sleep(terminateGrace);
57 yield* Queue.offer(signals, "SIGKILL");
58 yield* Effect.sleep(killWait);
59 yield* exit;
60 }),
61 );
62 yield* Deferred.succeed(started, undefined);
63 return ChildProcessSpawner.makeHandle({
64 pid: ChildProcessSpawner.ProcessId(123),
65 stdout: Stream.empty,
66 stderr: Stream.empty,
67 all: Stream.empty,
68 stdin: Sink.drain,
69 getInputFd: () => Sink.drain,
70 getOutputFd: () => Stream.empty,
71 exitCode: Deferred.await(exited),
72 isRunning: Effect.sync(() => running),
73 kill: () => exit,
74 unref: Effect.succeed(Effect.void),
75 });
76 }),
77 ),
78 );
79 return {
80 layer,
81 started: Deferred.await(started),
82 signals,
83 isRunning: Effect.sync(() => running),
84 killWait,
85 };
86 });
87
88 const runningConfig = {
89 executablePath: "/electron",
90 args: [],
91 entryPath: "/server/bin.mjs",
92 cwd: "/server",
93 env: {},
94 bootstrap: {
95 mode: "desktop",
96 noBrowser: true,
97 port: 3774,
98 t3Home: "/tmp/t3",
99 host: "127.0.0.1",
100 desktopBootstrapToken: "token",
101 tailscaleServeEnabled: false,
102 tailscaleServePort: 443,
103 },
104 bootstrapDelivery: "fd3",
105 extendEnv: true,
106 httpBaseUrl: new URL("http://127.0.0.1:3774"),
107 captureOutput: false,
108 preflightFailure: Option.none(),
109 } satisfies DesktopBackendStartConfig;
110
111 function layerPool(
112 labelRef: Ref.Ref<string>,
113 options: {
114 readonly config?: DesktopBackendStartConfig;
115 readonly resolvePrimary?: Effect.Effect<DesktopBackendStartConfig>;
116 readonly onMainContentsCommand?: (
117 command: DesktopWindow.MainWindowContentsCommand,
118 ) => Effect.Effect<void>;
119 readonly fileSystem?: Partial<FileSystem.FileSystem>;
120 readonly spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"];
121 readonly httpClient?: HttpClient.HttpClient;
122 readonly onReady?: Effect.Effect<void>;
123 readonly backend?: Effect.Success<ReturnType<typeof makeFakeBackendProcess>>;
124 } = {},
125 ): Layer.Layer<DesktopBackendPool.DesktopBackendPool> {
126 return DesktopBackendPool.layer.pipe(
127 Layer.provideMerge(
128 Layer.mergeAll(
129 DesktopEnvironment.layer({
130 dirname: "/repo/apps/desktop/src",
131 homeDirectory: "/test-home",
132 platform: "linux",
133 processArch: "x64",
134 appVersion: "1.2.3",
135 appPath: "/repo",
136 isPackaged: true,
137 resourcesPath: "/missing/resources",
138 runningUnderArm64Translation: false,
139 }).pipe(
140 Layer.provide(
141 Layer.mergeAll(Path.layer, DesktopConfig.layerTest({ T3CODE_HOME: "/test-home" })),
142 ),
143 Layer.orDie,
144 ),
145 FileSystem.layerNoop(options.fileSystem ?? { exists: () => Effect.succeed(true) }),
146 Path.layer,
147 options.backend?.layer ??
148 Layer.succeed(
149 ChildProcessSpawner.ChildProcessSpawner,
150 options.spawner ??
151 ChildProcessSpawner.make(() => Effect.die("unexpected child process spawn")),
152 ),
153 Layer.succeed(
154 HttpClient.HttpClient,
155 options.httpClient ??
156 HttpClient.make((request) =>
157 options.backend === undefined
158 ? Effect.die("unexpected HTTP request")
159 : Effect.succeed(
160 HttpClientResponse.fromWeb(request, new Response(null, { status: 200 })),
161 ),
162 ),
163 ),
164 Layer.succeed(DesktopObservability.DesktopBackendOutputLogFactory, {
165 forInstance: () =>
166 Effect.succeed({
167 beginSession: () => Effect.void,
168 writeOutputChunk: () => Effect.void,
169 persistFailureSnapshot: () => Effect.void,
170 persistFailure: () => Effect.void,
171 discardSession: Effect.void,
172 } satisfies DesktopObservability.DesktopBackendOutputLogShape),
173 } satisfies DesktopObservability.DesktopBackendOutputLogFactory["Service"]),
174 Layer.succeed(DesktopTelemetryPublisher.DesktopTelemetryPublisher, {
175 latest: Effect.succeedNone,
176 changes: Stream.empty,
177 encoded: Stream.empty,
178 handleControlForSource: () => Effect.void,
179 removeControlSource: () => Effect.void,
180 publishUpdateReport: () => Effect.void,
181 updateRequests: Stream.empty,
182 updateCommits: Stream.empty,
183 updateCancellations: Stream.empty,
184 }),
185 DesktopBrowserHost.layer,
186 Layer.succeed(DesktopBackendConfiguration.DesktopBackendConfiguration, {
187 resolvePrimary:
188 options.resolvePrimary ??
189 (options.config
190 ? Effect.succeed(options.config)
191 : Effect.die("unexpected primary config resolve")),
192 resolvePrimaryLabel: Ref.get(labelRef),
193 resolveWsl: () => Effect.die("unexpected WSL config resolve"),
194 currentBootstrapToken: Effect.die("unexpected bootstrap token read"),
195 } satisfies DesktopBackendConfiguration.DesktopBackendConfiguration["Service"]),
196 DesktopAppSettings.layerTest(),
197 DesktopState.layer,
198 DesktopWslEnvironment.layerTest(),
199 Layer.succeed(ElectronDialog.ElectronDialog, {
200 pickFolder: () => Effect.die("unexpected folder picker"),
201 pickFiles: () => Effect.die("unexpected file picker"),
202 showMessageBox: () => Effect.die("unexpected message box"),
203 showErrorBox: () => Effect.void,
204 } satisfies ElectronDialog.ElectronDialog["Service"]),
205 ElectronApp.layer,
206 Layer.succeed(DesktopWindow.DesktopWindow, {
207 createMain: Effect.die("unexpected window create"),
208 ensureMain: Effect.die("unexpected window ensure"),
209 revealOrCreateMain: Effect.die("unexpected window reveal"),
210 activate: Effect.die("unexpected window activate"),
211 createMainIfBackendReady: Effect.die("unexpected window create"),
212 showConnectingSplash: Effect.void,
213 handleBackendReady: () => options.onReady ?? Effect.void,
214 handleBackendNotReady: Effect.void,
215 flushMainWindowBounds: Effect.void,
216 prepareCaptureReveal: Effect.void,
217 dispatchMenuAction: () => Effect.die("unexpected menu action"),
218 dispatchSnapShotEvent: () => Effect.void,
219 zoomMain: () => Effect.die("unexpected zoom"),
220 runMainContentsCommand:
221 options.onMainContentsCommand ?? (() => Effect.die("unexpected main contents command")),
222 syncAppearance: Effect.void,
223 } satisfies DesktopWindow.DesktopWindow["Service"]),
224 ),
225 ),
226 );
227 }
228
229 const markerPath = "/test-home/runtime/desktop-update-in-progress";
230 const runtimePath = "/test-home/userdata/server-runtime.json";
231
232 const makeUpdateMarkerFixture = () =>
233 Effect.gen(function* () {
234 const allowReady = yield* Deferred.make<void>();
235 const runtimeChecked = yield* Deferred.make<void>();
236 const markerRemoved = yield* Deferred.make<void>();
237 const readyRuns = yield* Queue.unbounded<void>();
238 let nextPid = 123;
239 const files = new Map([[markerPath, JSON.stringify({ startedAt: 0, expiresAt: 60_000 })]]);
240 const removed: string[] = [];
241 const config: DesktopBackendStartConfig = {
242 executablePath: "/electron",
243 args: [],
244 entryPath: "/server/bin.mjs",
245 cwd: "/server",
246 env: {},
247 bootstrap: {
248 mode: "desktop",
249 noBrowser: true,
250 port: 3774,
251 t3Home: "/test-home",
252 host: "127.0.0.1",
253 desktopBootstrapToken: "token",
254 tailscaleServeEnabled: false,
255 tailscaleServePort: 443,
256 },
257 bootstrapDelivery: "fd3",
258 extendEnv: true,
259 httpBaseUrl: new URL("http://127.0.0.1:3774"),
260 captureOutput: false,
261 preflightFailure: Option.none(),
262 };
263 const layer = layerPool(Ref.makeUnsafe("Local"), {
264 config,
265 fileSystem: {
266 exists: (path) => Effect.succeed(files.has(path) || path === config.entryPath),
267 readFileString: (path) =>
268 (path === runtimePath ? Deferred.succeed(runtimeChecked, undefined) : Effect.void).pipe(
269 Effect.andThen(Effect.sync(() => files.get(path) ?? "")),
270 ),
271 remove: (path) =>
272 Effect.sync(() => {
273 removed.push(path);
274 files.delete(path);
275 }).pipe(
276 Effect.andThen(
277 path === markerPath ? Deferred.succeed(markerRemoved, undefined) : Effect.void,
278 ),
279 Effect.asVoid,
280 ),
281 },
282 spawner: ChildProcessSpawner.make(() =>
283 Effect.gen(function* () {
284 const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
285 const exit = Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0)).pipe(
286 Effect.asVoid,
287 );
288 // Like the real spawner, closing the run's scope ends the process.
289 yield* Effect.addFinalizer(() => exit);
290 return ChildProcessSpawner.makeHandle({
291 pid: ChildProcessSpawner.ProcessId(nextPid++),
292 stdout: Stream.empty,
293 stderr: Stream.empty,
294 all: Stream.empty,
295 exitCode: Deferred.await(exited),
296 isRunning: Effect.succeed(true),
297 kill: () => exit,
298 stdin: Sink.drain,
299 getInputFd: () => Sink.drain,
300 getOutputFd: () => Stream.empty,
301 unref: Effect.succeed(Effect.void),
302 });
303 }),
304 ),
305 httpClient: HttpClient.make((request) =>
306 Deferred.await(allowReady).pipe(
307 Effect.as(HttpClientResponse.fromWeb(request, new Response(null, { status: 200 }))),
308 ),
309 ),
310 onReady: Queue.offer(readyRuns, undefined).pipe(Effect.asVoid),
311 });
312 const publishRuntime = (pid: number) =>
313 files.set(
314 runtimePath,
315 JSON.stringify({
316 version: 1,
317 pid,
318 port: 3774,
319 origin: "http://127.0.0.1:3774",
320 startedAt: "2026-10-27T00:00:00.000Z",
321 }),
322 );
323 return {
324 layer,
325 files,
326 removed,
327 allowReady,
328 readyRuns,
329 runtimeChecked,
330 markerRemoved,
331 publishRuntime,
332 };
333 });
334
335 describe("DesktopBackendPool", () => {
336 it.effect(
337 "keeps the update marker after HTTP readiness until the backend publishes its runtime",
338 () =>
339 Effect.gen(function* () {
340 const fixture = yield* makeUpdateMarkerFixture();
341 yield* Effect.gen(function* () {
342 const pool = yield* DesktopBackendPool.DesktopBackendPool;
343 const primary = yield* pool.primary;
344 yield* primary.start;
345 yield* Deferred.succeed(fixture.allowReady, undefined);
346 yield* Queue.take(fixture.readyRuns);
347 assert.isTrue(
348 fixture.files.has(markerPath),
349 "a launcher could neither wait nor adopt between readiness and publication",
350 );
351 yield* Deferred.await(fixture.runtimeChecked);
352 yield* TestClock.adjust(Duration.seconds(5));
353 assert.isTrue(fixture.files.has(markerPath));
354 fixture.publishRuntime(456);
355 yield* TestClock.adjust(Duration.seconds(1));
356 assert.isTrue(
357 fixture.files.has(markerPath),
358 "another process's runtime is not the replacement",
359 );
360 fixture.publishRuntime(123);
361 yield* TestClock.adjust(Duration.seconds(1));
362 yield* Deferred.await(fixture.markerRemoved);
363 assert.deepEqual(fixture.removed, [markerPath]);
364 }).pipe(Effect.provide(fixture.layer));
365 }),
366 );
367
368 it.effect("leaves a replacement update marker written while an earlier wait is pending", () =>
369 Effect.gen(function* () {
370 const fixture = yield* makeUpdateMarkerFixture();
371 yield* Effect.gen(function* () {
372 const pool = yield* DesktopBackendPool.DesktopBackendPool;
373 const primary = yield* pool.primary;
374 yield* primary.start;
375 yield* Deferred.succeed(fixture.allowReady, undefined);
376 yield* Queue.take(fixture.readyRuns);
377 yield* Deferred.await(fixture.runtimeChecked);
378 yield* TestClock.adjust(Duration.millis(DESKTOP_UPDATE_IN_PROGRESS_TTL_MS - 1_000));
379 const replacement = JSON.stringify({ startedAt: 59_000, expiresAt: 119_000 });
380 fixture.files.set(markerPath, replacement);
381 yield* TestClock.adjust(Duration.millis(DESKTOP_UPDATE_IN_PROGRESS_TTL_MS));
382 assert.equal(fixture.files.get(markerPath), replacement);
383 assert.deepEqual(fixture.removed, []);
384 }).pipe(Effect.provide(fixture.layer));
385 }),
386 );
387
388 it.effect("a later backend run's readiness supersedes the earlier run's marker wait", () =>
389 Effect.gen(function* () {
390 const fixture = yield* makeUpdateMarkerFixture();
391 yield* Effect.gen(function* () {
392 const pool = yield* DesktopBackendPool.DesktopBackendPool;
393 const primary = yield* pool.primary;
394 yield* primary.start;
395 yield* Deferred.succeed(fixture.allowReady, undefined);
396 yield* Queue.take(fixture.readyRuns);
397 yield* Deferred.await(fixture.runtimeChecked);
398 yield* TestClock.adjust(Duration.seconds(30));
399 yield* primary.stop();
400 yield* primary.start;
401 yield* Queue.take(fixture.readyRuns);
402 yield* TestClock.adjust(Duration.seconds(31));
403 assert.isTrue(
404 fixture.files.has(markerPath),
405 "the earlier run's wait must not end the later run's handoff",
406 );
407 assert.deepEqual(fixture.removed, []);
408 fixture.publishRuntime(124);
409 yield* TestClock.adjust(Duration.millis(100));
410 yield* Deferred.await(fixture.markerRemoved);
411 assert.deepEqual(fixture.removed, [markerPath]);
412 }).pipe(Effect.provide(fixture.layer));
413 }),
414 );
415
416 it.effect("unregister during pool quit does not interrupt sibling stops", () =>
417 Effect.gen(function* () {
418 const backend = yield* makeFakeBackendProcess();
419 yield* Effect.gen(function* () {
420 const pool = yield* DesktopBackendPool.DesktopBackendPool;
421 const id = DesktopBackendPool.BackendInstanceId("wsl:Ubuntu");
422 const ready = yield* Deferred.make<void>();
423 const siblingStarted = yield* Deferred.make<void>();
424 const finishSibling = yield* Deferred.make<void>();
425 let siblingCompleted = false;
426 const instance = yield* pool.register({
427 id,
428 label: Effect.succeed("WSL (Ubuntu)"),
429 configResolve: Effect.succeed(runningConfig),
430 onReady: () => Deferred.succeed(ready, undefined).pipe(Effect.asVoid),
431 });
432 yield* instance.start;
433 yield* backend.started;
434 yield* Deferred.await(ready);
435 const quitFiber = yield* Effect.all(
436 [
437 instance.stop({ timeout: Duration.seconds(5) }),
438 Deferred.succeed(siblingStarted, undefined).pipe(
439 Effect.andThen(Deferred.await(finishSibling)),
440 Effect.andThen(
441 Effect.sync(() => {
442 siblingCompleted = true;
443 }),
444 ),
445 ),
446 ],
447 { concurrency: "unbounded" },
448 ).pipe(Effect.forkChild);
449 yield* Deferred.await(siblingStarted);
450 assert.equal(yield* Queue.take(backend.signals), "SIGTERM");
451 const unregisterFiber = yield* pool.unregister(id).pipe(Effect.forkChild);
452 yield* TestClock.adjust(Duration.seconds(5));
453 assert.equal(yield* Queue.take(backend.signals), "SIGKILL");
454 assert.isUndefined(quitFiber.pollUnsafe());
455 assert.isUndefined(unregisterFiber.pollUnsafe());
456 assert.isTrue(yield* backend.isRunning);
457 yield* TestClock.adjust(backend.killWait);
458 yield* Fiber.join(unregisterFiber);
459 yield* Deferred.succeed(finishSibling, undefined);
460 yield* Fiber.join(quitFiber);
461
462 assert.isTrue(siblingCompleted);
463 assert.isFalse(yield* backend.isRunning);
464 assert.isTrue(Option.isNone((yield* instance.snapshot).activePid));
465 assert.isTrue(Option.isNone(yield* pool.get(id)));
466 }).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows"), { backend })));
467 }),
468 );
469
470 it.effect("unregister stops the registered instance", () =>
471 Effect.gen(function* () {
472 const id = DesktopBackendPool.BackendInstanceId("wsl:Ubuntu");
473 const pool = yield* DesktopBackendPool.DesktopBackendPool;
474 const instance = yield* pool.register({
475 id,
476 label: Effect.succeed("WSL (Ubuntu)"),
477 configResolve: Effect.succeed({
478 ...runningConfig,
479 preflightFailure: Option.some({ reason: "WSL starting", fatal: false }),
480 }),
481 });
482 yield* instance.start;
483 assert.equal((yield* instance.snapshot).restartScheduled, true);
484
485 yield* pool.unregister(id);
486
487 const stopped = yield* instance.snapshot;
488 assert.equal(stopped.desiredRunning, false);
489 assert.equal(stopped.restartScheduled, false);
490 assert.equal(Option.isNone(yield* pool.get(id)), true);
491 }).pipe(Effect.provide(layerPool(Ref.makeUnsafe("Windows")))),
492 );
493
494 it.effect("reloads a main window that read the WSL endpoint before the Windows fallback", () =>
495 Effect.gen(function* () {
496 const events: string[] = [];
497 let resolves = 0;
498 const resolvePrimary = Effect.sync(() =>
499 resolves++ === 0
500 ? {
501 ...runningConfig,
502 preflightFailure: Option.some({
503 reason: "WSL still unavailable",
504 fatal: false,
505 retryLimit: 1,
506 }),
507 }
508 : runningConfig,
509 );
510 const ready = yield* Deferred.make<void>();
511 yield* Effect.gen(function* () {
512 const primary = yield* (yield* DesktopBackendPool.DesktopBackendPool).primary;
513 yield* primary.start;
514 yield* TestClock.adjust(Duration.seconds(1));
515 yield* Deferred.await(ready);
516
517 assert.deepEqual(events, ["reload", "ready"]);
518 }).pipe(
519 Effect.provide(
520 layerPool(Ref.makeUnsafe("WSL"), {
521 resolvePrimary,
522 spawner: ChildProcessSpawner.make(() =>
523 Effect.gen(function* () {
524 const exited = yield* Deferred.make<ChildProcessSpawner.ExitCode>();
525 const exit = Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0)).pipe(
526 Effect.asVoid,
527 );
528 yield* Effect.addFinalizer(() => exit);
529 return ChildProcessSpawner.makeHandle({
530 pid: ChildProcessSpawner.ProcessId(123),
531 stdout: Stream.empty,
532 stderr: Stream.empty,
533 all: Stream.empty,
534 exitCode: Deferred.await(exited),
535 isRunning: Effect.succeed(true),
536 kill: () => exit,
537 stdin: Sink.drain,
538 getInputFd: () => Sink.drain,
539 getOutputFd: () => Stream.empty,
540 unref: Effect.succeed(Effect.void),
541 });
542 }),
543 ),
544 httpClient: HttpClient.make((request) =>
545 Effect.succeed(
546 HttpClientResponse.fromWeb(request, new Response(null, { status: 200 })),
547 ),
548 ),
549 onMainContentsCommand: (command) => Effect.sync(() => void events.push(command)),
550 onReady: Effect.sync(() => void events.push("ready")).pipe(
551 Effect.andThen(Deferred.succeed(ready, undefined)),
552 Effect.asVoid,
553 ),
554 }),
555 ),
556 );
557 }),
558 );
559 });