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

main
ts 1,027 lines 41.9 KB
Raw
1 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import { assert, describe, it } from "@effect/vitest";
4 import { currentDesktopBootstrapToken } from "@t3tools/shared/desktopBootstrapToken";
5 import * as HostProcess from "@t3tools/shared/HostProcess";
6 import * as Clock from "effect/Clock";
7 import * as Effect from "effect/Effect";
8 import * as FileSystem from "effect/FileSystem";
9 import * as Layer from "effect/Layer";
10 import * as ManagedRuntime from "effect/ManagedRuntime";
11 import * as Option from "effect/Option";
12 import * as Path from "effect/Path";
13 import * as Stream from "effect/Stream";
14 import { ChildProcessSpawner } from "effect/process";
15
16 import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
17 import * as DesktopManagedPolicy from "../app/DesktopManagedPolicy.ts";
18 import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
19 import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts";
20 import * as DesktopConfig from "../app/DesktopConfig.ts";
21 import * as DesktopServerExposure from "./DesktopServerExposure.ts";
22 import * as DesktopState from "../app/DesktopState.ts";
23 import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
24 import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
25 import * as DesktopWslServerTree from "../wsl/DesktopWslServerTree.ts";
26
27 const layerShellEnvironment = (prepared = true) =>
28 Layer.succeed(DesktopShellEnvironment.DesktopShellEnvironment, {
29 installIntoProcess: Effect.succeed(prepared),
30 awaitDiscovery: Effect.succeed(prepared),
31 awaitUserShellDiscovery: Effect.succeed(prepared),
32 discoveryFinished: Effect.succeed(true),
33 updates: Stream.empty,
34 });
35
36 const layerBackendConfiguration = (prepared = true) =>
37 DesktopBackendConfiguration.layer.pipe(
38 Layer.provide(layerShellEnvironment(prepared)),
39 Layer.provide(DesktopState.layer),
40 );
41
42 const layerServerExposure = Layer.succeed(DesktopServerExposure.DesktopServerExposure, {
43 getState: Effect.die("unexpected getState"),
44 backendConfig: Effect.succeed({
45 port: 4888,
46 bindHost: "0.0.0.0",
47 httpBaseUrl: new URL("http://127.0.0.1:4888"),
48 tailscaleServeEnabled: true,
49 tailscaleServePort: 8443,
50 }),
51 configureFromSettings: () => Effect.die("unexpected configureFromSettings"),
52 setMode: () => Effect.die("unexpected setMode"),
53 setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
54 getAdvertisedEndpoints: Effect.succeed([]),
55 } satisfies DesktopServerExposure.DesktopServerExposure["Service"]);
56
57 function layerEnvironment(
58 baseDir: string,
59 options?: {
60 readonly appPath?: string;
61 readonly dirname?: string;
62 readonly isPackaged?: boolean;
63 readonly devServerUrl?: string;
64 readonly platform?: NodeJS.Platform;
65 readonly resourcesPath?: string;
66 readonly appVersion?: string;
67 readonly processArch?: NodeJS.Architecture;
68 readonly otlpTracesUrl?: string;
69 readonly otlpMetricsUrl?: string;
70 readonly otlpLogsUrl?: string;
71 },
72 ) {
73 return DesktopEnvironment.layer({
74 dirname: options?.dirname ?? "/repo/apps/desktop/src",
75 homeDirectory: baseDir,
76 platform: options?.platform ?? "darwin",
77 processArch: options?.processArch ?? "x64",
78 appVersion: options?.appVersion ?? "1.2.3",
79 appPath: options?.appPath ?? "/repo",
80 isPackaged: options?.isPackaged ?? true,
81 resourcesPath: options?.resourcesPath ?? "/missing/resources",
82 runningUnderArm64Translation: false,
83 }).pipe(
84 Layer.provide(
85 Layer.mergeAll(
86 NodeServices.layer,
87 NodeCrypto.layer,
88 DesktopConfig.layerTest({
89 T3CODE_HOME: baseDir,
90 T3CODE_PORT: "9999",
91 T3CODE_MODE: "desktop",
92 T3CODE_DESKTOP_LAN_HOST: "192.168.1.50",
93 VITE_DEV_SERVER_URL: options?.devServerUrl,
94 T3CODE_OTLP_TRACES_URL: options?.otlpTracesUrl,
95 T3CODE_OTLP_METRICS_URL: options?.otlpMetricsUrl,
96 T3CODE_OTLP_LOGS_URL: options?.otlpLogsUrl,
97 }),
98 ),
99 ),
100 );
101 }
102
103 const withHarness = <A, E, R>(
104 effect: Effect.Effect<
105 A,
106 E,
107 | R
108 | DesktopEnvironment.DesktopEnvironment
109 | FileSystem.FileSystem
110 | DesktopBackendConfiguration.DesktopBackendConfiguration
111 >,
112 prepared = true,
113 ) =>
114 Effect.gen(function* () {
115 const fileSystem = yield* FileSystem.FileSystem;
116 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
117 prefix: "t3-desktop-backend-config-test-",
118 });
119
120 return yield* effect.pipe(
121 Effect.provide(
122 layerBackendConfiguration(prepared).pipe(
123 Layer.provideMerge(layerServerExposure),
124 Layer.provideMerge(DesktopAppSettings.layerTest()),
125 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
126 Layer.provideMerge(DesktopWslServerTree.layerTest()),
127 Layer.provideMerge(layerEnvironment(baseDir)),
128 ),
129 ),
130 );
131 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)));
132
133 interface PackagedWslHarnessContext {
134 readonly baseDir: string;
135 readonly archivePath: string;
136 readonly hashPath: string;
137 readonly archiveHash: string;
138 readonly mountedAppRoot: string;
139 readonly mountedEntryPath: string;
140 }
141
142 const withPackagedWslHarness = <A, E, R>(
143 input: {
144 readonly archiveHash: string;
145 readonly wsl: (
146 context: PackagedWslHarnessContext,
147 ) => DesktopWslEnvironment.DesktopWslEnvironmentTestStub;
148 readonly forbidFallback?: string;
149 readonly cleanupLegacy?: Effect.Effect<void>;
150 readonly forbidCleanup?: string;
151 },
152 effect: (
153 context: PackagedWslHarnessContext,
154 ) => Effect.Effect<
155 A,
156 E,
157 R | FileSystem.FileSystem | Path.Path | DesktopBackendConfiguration.DesktopBackendConfiguration
158 >,
159 ) =>
160 Effect.gen(function* () {
161 const fileSystem = yield* FileSystem.FileSystem;
162 const path = yield* Path.Path;
163 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
164 prefix: "t3-desktop-backend-config-test-",
165 });
166 const archivePath = path.join(baseDir, "wsl-runtime.tar.gz");
167 const hashPath = `${archivePath}.sha256`;
168 const mountedAppRoot = "/mnt/c/app.asar.unpacked";
169 const mountedEntryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");
170 yield* fileSystem.makeDirectory(path.dirname(mountedEntryPath), { recursive: true });
171 yield* fileSystem.writeFileString(mountedEntryPath, "");
172 yield* fileSystem.writeFileString(archivePath, "archive");
173 yield* fileSystem.writeFileString(hashPath, `${input.archiveHash}\n`);
174
175 const context = {
176 baseDir,
177 archivePath,
178 hashPath,
179 archiveHash: input.archiveHash,
180 mountedAppRoot,
181 mountedEntryPath,
182 } satisfies PackagedWslHarnessContext;
183 const layerServerTree = input.forbidFallback
184 ? Layer.succeed(
185 DesktopWslServerTree.DesktopWslServerTree,
186 DesktopWslServerTree.DesktopWslServerTree.of({
187 ensure: Effect.die(input.forbidFallback),
188 cleanupLegacy: input.forbidCleanup
189 ? Effect.die(input.forbidCleanup)
190 : (input.cleanupLegacy ?? Effect.void),
191 }),
192 )
193 : DesktopWslServerTree.layerTest({
194 result: { ok: true, root: path.join(baseDir, "app.asar.unpacked") },
195 cleanupLegacy: input.cleanupLegacy ?? Effect.void,
196 });
197
198 return yield* effect(context).pipe(
199 Effect.provide(
200 layerBackendConfiguration().pipe(
201 Layer.provideMerge(layerServerExposure),
202 Layer.provideMerge(DesktopAppSettings.layerTest()),
203 Layer.provideMerge(layerServerTree),
204 Layer.provideMerge(
205 DesktopWslEnvironment.layerTest({
206 isAvailable: true,
207 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
208 windowsToWslPath: () => Option.some(mountedAppRoot),
209 getDistroIp: () => Option.some("172.27.0.99"),
210 ...input.wsl(context),
211 }),
212 ),
213 Layer.provideMerge(
214 layerEnvironment(baseDir, {
215 appPath: baseDir,
216 platform: "win32",
217 resourcesPath: baseDir,
218 }),
219 ),
220 ),
221 ),
222 );
223 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)));
224
225 describe("DesktopBackendConfiguration", () => {
226 it.effect("resolvePrimary produces a stable scoped bootstrap token", () =>
227 withHarness(
228 Effect.gen(function* () {
229 const environment = yield* DesktopEnvironment.DesktopEnvironment;
230 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
231
232 const first = yield* configuration.resolvePrimary;
233 const second = yield* configuration.resolvePrimary;
234
235 assert.equal(first.executablePath, process.execPath);
236 assert.deepEqual(first.args.slice(0, 3), [
237 "--require",
238 environment.compileCachePath,
239 environment.backendEntryPath,
240 ]);
241 assert.equal(first.entryPath, environment.backendEntryPath);
242 assert.equal(first.cwd, environment.backendCwd);
243 assert.equal(first.captureOutput, true);
244 assert.equal(first.env.ELECTRON_RUN_AS_NODE, "1");
245 assert.equal(first.env.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING, "1");
246 assert.isUndefined(first.env.T3CODE_PORT);
247 assert.isUndefined(first.env.T3CODE_MODE);
248 assert.isUndefined(first.env.T3CODE_DESKTOP_LAN_HOST);
249
250 assert.equal(first.bootstrap.mode, "desktop");
251 assert.equal(first.bootstrap.noBrowser, true);
252 assert.equal(first.bootstrap.port, 4888);
253 assert.equal(first.bootstrap.host, "0.0.0.0");
254 assert.equal(first.bootstrap.t3Home, environment.baseDir);
255 assert.equal(first.bootstrap.tailscaleServeEnabled, true);
256 assert.equal(first.bootstrap.tailscaleServePort, 8443);
257 assert.match(first.bootstrap.desktopBootstrapSecret ?? "", /^[0-9a-f]{64}$/i);
258 assert.equal(
259 second.bootstrap.desktopBootstrapSecret,
260 first.bootstrap.desktopBootstrapSecret,
261 );
262 assert.equal(
263 first.bootstrap.desktopBootstrapToken,
264 yield* currentDesktopBootstrapToken(
265 first.bootstrap.desktopBootstrapSecret ?? "",
266 yield* Clock.currentTimeMillis,
267 ).pipe(Effect.provide(NodeCrypto.layerMac)),
268 );
269 assert.equal(
270 yield* configuration.currentBootstrapToken,
271 first.bootstrap.desktopBootstrapToken,
272 );
273 }),
274 ),
275 );
276
277 it.effect("resolvePrimary starts from server.asar without materializing the WSL tree", () =>
278 Effect.gen(function* () {
279 const fileSystem = yield* FileSystem.FileSystem;
280 const path = yield* Path.Path;
281 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
282 prefix: "t3-desktop-backend-config-test-",
283 });
284 const resourcesPath = path.join(baseDir, "resources");
285
286 const config = yield* Effect.gen(function* () {
287 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
288 return yield* configuration.resolvePrimary;
289 }).pipe(
290 Effect.provide(
291 layerBackendConfiguration().pipe(
292 Layer.provideMerge(layerServerExposure),
293 Layer.provideMerge(DesktopAppSettings.layerTest()),
294 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
295 Layer.provideMerge(
296 Layer.succeed(
297 DesktopWslServerTree.DesktopWslServerTree,
298 DesktopWslServerTree.DesktopWslServerTree.of({
299 ensure: Effect.die("Windows primary must not extract the WSL server tree"),
300 cleanupLegacy: Effect.die("Windows primary must not clean the WSL server tree"),
301 }),
302 ),
303 ),
304 Layer.provideMerge(
305 layerEnvironment(baseDir, {
306 appPath: `${resourcesPath}/app.asar`,
307 platform: "win32",
308 resourcesPath,
309 }),
310 ),
311 ),
312 ),
313 );
314
315 assert.equal(
316 config.entryPath,
317 path.join(resourcesPath, "server.asar/apps/server/dist/bin.mjs"),
318 );
319 assert.equal(config.env.ELECTRON_RUN_AS_NODE, "1");
320 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
321 );
322
323 it.effect("resolveWsl pins a default-tracking run to the concrete default distro", () =>
324 Effect.gen(function* () {
325 const fileSystem = yield* FileSystem.FileSystem;
326 const path = yield* Path.Path;
327 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
328 prefix: "t3-desktop-backend-config-test-",
329 });
330 const entryPath = path.join(baseDir, "apps/server/dist/bin.mjs");
331 yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
332 yield* fileSystem.writeFileString(entryPath, "");
333
334 const observedDistros: Array<string | null> = [];
335 const config = yield* Effect.gen(function* () {
336 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
337 return yield* configuration.resolveWsl({ port: 5000, distro: null });
338 }).pipe(
339 Effect.provide(
340 layerBackendConfiguration().pipe(
341 Layer.provideMerge(layerServerExposure),
342 Layer.provideMerge(DesktopAppSettings.layerTest()),
343 Layer.provideMerge(DesktopWslServerTree.layerTest()),
344 Layer.provideMerge(
345 DesktopWslEnvironment.layerTest({
346 isAvailable: true,
347 distros: [
348 { name: "Debian", isDefault: false, version: 2 },
349 { name: "Ubuntu", isDefault: true, version: 2 },
350 ],
351 windowsToWslPath: (distro) => {
352 observedDistros.push(distro);
353 return Option.some("/repo");
354 },
355 ensureNodePty: (distro) => {
356 observedDistros.push(distro);
357 return {
358 ok: true,
359 nodePath: "/usr/bin/node",
360 resolvedPath: "/usr/bin:/bin",
361 t3Home: null,
362 };
363 },
364 getDistroIp: (distro) => {
365 observedDistros.push(distro);
366 return Option.some("172.27.0.99");
367 },
368 }),
369 ),
370 Layer.provideMerge(
371 layerEnvironment(baseDir, {
372 appPath: baseDir,
373 platform: "win32",
374 resourcesPath: baseDir,
375 }),
376 ),
377 ),
378 ),
379 );
380
381 assert.equal(config.runningDistro, "Ubuntu");
382 assert.deepEqual(config.args.slice(0, 5), ["-d", "Ubuntu", "--cd", "~", "--exec"]);
383 assert.deepEqual(observedDistros, ["Ubuntu", "Ubuntu", "Ubuntu"]);
384 assert.isTrue(Option.isNone(config.preflightFailure));
385 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
386 );
387
388 it.effect("resolveWsl launches a packaged backend from the WSL-local runtime cache", () => {
389 const observedArchives: Array<{
390 windowsArchivePath: string;
391 runtimeId: string;
392 sha256: string;
393 t3Home: string | null;
394 }> = [];
395 let probeCount = 0;
396 let legacyCleanupCount = 0;
397 const t3Home = "/home/test/.config/t3";
398 const linuxAppRoot = `${t3Home}/wsl-runtime/1.2.3-x64`;
399 const resolvedPath = "/home/test/.local/bin:/usr/bin:/bin";
400
401 return withPackagedWslHarness(
402 {
403 archiveHash: "a".repeat(64),
404 forbidFallback: "A valid WSL archive must not extract the Windows fallback",
405 cleanupLegacy: Effect.sync(() => {
406 legacyCleanupCount += 1;
407 }),
408 wsl: () => ({
409 prepareRuntime: (_distro, archive, archiveT3Home) => {
410 observedArchives.push({
411 windowsArchivePath: archive.windowsPath,
412 runtimeId: archive.runtimeId,
413 sha256: archive.sha256,
414 t3Home: archiveT3Home,
415 });
416 return { ok: true, linuxAppRoot };
417 },
418 probeRuntime: () => {
419 probeCount += 1;
420 return { ok: true, resolvedPath, t3Home };
421 },
422 ensureNodePty: () => {
423 throw new Error("the staged runtime must not probe for node-pty");
424 },
425 }),
426 },
427 ({ archiveHash, archivePath, baseDir }) =>
428 Effect.gen(function* () {
429 const path = yield* Path.Path;
430 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
431 const config = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
432
433 assert.deepEqual(observedArchives, [
434 {
435 windowsArchivePath: archivePath,
436 runtimeId: `sha256-${archiveHash}`,
437 sha256: archiveHash,
438 t3Home,
439 },
440 ]);
441 assert.equal(probeCount, 1);
442 assert.equal(
443 config.entryPath,
444 path.join(baseDir, "server.asar/apps/server/dist/bin.mjs"),
445 );
446 assert.deepEqual(config.args, [
447 "-d",
448 "Ubuntu",
449 "--cd",
450 "~",
451 "--exec",
452 "env",
453 `PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${resolvedPath}`,
454 `T3CODE_HOME=${t3Home}`,
455 `${linuxAppRoot}/t3`,
456 "--bootstrap-fd",
457 "0",
458 ]);
459 assert.notInclude(config.args, "/usr/bin/node");
460 assert.equal(config.wslRuntimeId, `sha256-${archiveHash}`);
461 assert.equal(config.wslT3Home, t3Home);
462 assert.equal(legacyCleanupCount, 1);
463 assert.isTrue(Option.isNone(config.preflightFailure));
464 }),
465 );
466 });
467
468 it.effect("resolveWsl changes the cache id when the packaged archive changes", () => {
469 const firstHash = "a".repeat(64);
470 const secondHash = "b".repeat(64);
471 const observedRuntimeIds: string[] = [];
472 return withPackagedWslHarness(
473 {
474 archiveHash: firstHash,
475 wsl: () => ({
476 prepareRuntime: (_distro, archive) => {
477 observedRuntimeIds.push(archive.runtimeId);
478 return { ok: true, linuxAppRoot: `/runtime/${archive.runtimeId}` };
479 },
480 ensureNodePty: () => ({
481 ok: true,
482 nodePath: "/usr/bin/node",
483 resolvedPath: "/usr/bin:/bin",
484 t3Home: null,
485 }),
486 }),
487 },
488 ({ hashPath, mountedAppRoot }) =>
489 Effect.gen(function* () {
490 const fileSystem = yield* FileSystem.FileSystem;
491 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
492 const first = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
493 yield* fileSystem.writeFileString(hashPath, secondHash);
494 const second = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
495 yield* fileSystem.writeFileString(hashPath, "not-a-sha256");
496 const invalidIdentity = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
497
498 assert.deepEqual(observedRuntimeIds, [`sha256-${firstHash}`, `sha256-${secondHash}`]);
499 assert.equal(first.wslRuntimeId, observedRuntimeIds[0]);
500 assert.include(first.args, `/runtime/sha256-${firstHash}/t3`);
501 assert.equal(second.wslRuntimeId, observedRuntimeIds[1]);
502 assert.include(second.args, `/runtime/sha256-${secondHash}/t3`);
503 assert.isUndefined(invalidIdentity.wslRuntimeId);
504 assert.include(invalidIdentity.args, "/usr/bin/node");
505 assert.include(invalidIdentity.args, `${mountedAppRoot}/apps/server/dist/bin.mjs`);
506 }),
507 );
508 });
509
510 it.effect("resolveWsl falls back to the mounted runtime when archive staging fails", () => {
511 const observedNodePtyRoots: string[] = [];
512 return withPackagedWslHarness(
513 {
514 archiveHash: "b".repeat(64),
515 wsl: () => ({
516 prepareRuntime: () => ({ ok: false, reason: "archive is corrupt" }),
517 ensureNodePty: (_distro, root) => {
518 observedNodePtyRoots.push(root);
519 return {
520 ok: true,
521 nodePath: "/usr/bin/node",
522 resolvedPath: "/usr/bin:/bin",
523 t3Home: null,
524 };
525 },
526 }),
527 },
528 ({ mountedAppRoot, mountedEntryPath }) =>
529 Effect.gen(function* () {
530 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
531 const config = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
532
533 assert.deepEqual(observedNodePtyRoots, [mountedAppRoot]);
534 assert.equal(config.entryPath, mountedEntryPath);
535 assert.include(config.args, "/usr/bin/node");
536 assert.include(config.args, `${mountedAppRoot}/apps/server/dist/bin.mjs`);
537 assert.isUndefined(config.wslRuntimeId);
538 assert.isTrue(Option.isNone(config.preflightFailure));
539 }),
540 );
541 });
542
543 it.effect("resolveWsl does not stage a runtime when the login-shell probe fails", () => {
544 const archiveHash = "c".repeat(64);
545 const stagedAppRoot = `/home/test/.t3/wsl-runtime/sha256-${archiveHash}`;
546 let probeCount = 0;
547 const observedNodePtyRoots: string[] = [];
548 return withPackagedWslHarness(
549 {
550 archiveHash,
551 wsl: () => ({
552 prepareRuntime: () => {
553 throw new Error("a failed probe must not stage the runtime");
554 },
555 probeRuntime: () => {
556 probeCount += 1;
557 return { ok: false, reason: "WSL login-shell PATH could not be resolved" };
558 },
559 ensureNodePty: (_distro, root) => {
560 observedNodePtyRoots.push(root);
561 return {
562 ok: true,
563 nodePath: "/usr/bin/node",
564 resolvedPath: "/usr/bin:/bin",
565 t3Home: null,
566 };
567 },
568 }),
569 },
570 ({ mountedAppRoot, mountedEntryPath }) =>
571 Effect.gen(function* () {
572 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
573 const config = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
574
575 assert.equal(probeCount, 1);
576 assert.deepEqual(observedNodePtyRoots, [mountedAppRoot]);
577 assert.include(config.args, "/usr/bin/node");
578 assert.include(config.args, `${mountedAppRoot}/apps/server/dist/bin.mjs`);
579 assert.notInclude(config.args, `${stagedAppRoot}/t3`);
580 assert.equal(config.entryPath, mountedEntryPath);
581 assert.isUndefined(config.wslRuntimeId);
582 assert.isTrue(Option.isNone(config.preflightFailure));
583 }),
584 );
585 });
586
587 it.effect("resolveWsl keeps WSL retryable when the mounted fallback fails transiently", () => {
588 const stagedAppRoot = "/home/test/.t3/wsl-runtime/cache";
589 return withPackagedWslHarness(
590 {
591 archiveHash: "f".repeat(64),
592 wsl: () => ({
593 prepareRuntime: () => ({ ok: true, linuxAppRoot: stagedAppRoot }),
594 probeRuntime: () => ({ ok: false, reason: "WSL login-shell PATH could not be resolved" }),
595 ensureNodePty: () => ({
596 ok: false,
597 reason: "WSL backend preflight timed out while probing for Node.js.",
598 fatal: false,
599 }),
600 }),
601 },
602 () =>
603 Effect.gen(function* () {
604 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
605 const config = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
606 const failure = Option.getOrThrow(config.preflightFailure);
607
608 assert.isFalse(failure.fatal);
609 assert.equal(failure.retryLimit, 12);
610 assert.include(failure.reason, "timed out");
611 }),
612 );
613 });
614
615 it.effect(
616 "resolveWsl preserves inherited PATH with quote-sensitive values as separate args",
617 () =>
618 Effect.gen(function* () {
619 const fileSystem = yield* FileSystem.FileSystem;
620 const path = yield* Path.Path;
621 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
622 prefix: "t3-desktop-backend-config-test-",
623 });
624 const entryPath = path.join(baseDir, "apps/server/dist/bin.mjs");
625 yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
626 yield* fileSystem.writeFileString(entryPath, "");
627
628 const nodePath = "/home/test user's/.nvm/versions/node/v22.0.0/bin/node";
629 const linuxAppRoot = "/tmp/t3 code's launch";
630 const linuxEntryPath = `${linuxAppRoot}/apps/server/dist/bin.mjs`;
631 const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
632 const devServerUrl = "http://127.0.0.1:5733/dev%20assets/?label=hello%20world";
633 const config = yield* Effect.gen(function* () {
634 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
635 return yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
636 }).pipe(
637 Effect.provide(
638 layerBackendConfiguration().pipe(
639 Layer.provideMerge(layerServerExposure),
640 Layer.provideMerge(DesktopAppSettings.layerTest()),
641 Layer.provideMerge(DesktopWslServerTree.layerTest()),
642 Layer.provideMerge(
643 DesktopWslEnvironment.layerTest({
644 isAvailable: true,
645 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
646 windowsToWslPath: () => Option.some(linuxAppRoot),
647 ensureNodePty: () => ({ ok: true, nodePath, resolvedPath, t3Home: null }),
648 getDistroIp: () => Option.some("172.27.0.99"),
649 }),
650 ),
651 Layer.provideMerge(
652 layerEnvironment(baseDir, {
653 appPath: baseDir,
654 devServerUrl,
655 isPackaged: true,
656 platform: "win32",
657 resourcesPath: baseDir,
658 }),
659 ),
660 ),
661 ),
662 );
663
664 assert.equal(config.bootstrapDelivery, "stdin");
665 assert.deepEqual(config.args, [
666 "-d",
667 "Ubuntu",
668 "--cd",
669 "~",
670 "--exec",
671 "env",
672 "PATH=/home/test user's/.nvm/versions/node/v22.0.0/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin",
673 nodePath,
674 linuxEntryPath,
675 "--bootstrap-fd",
676 "0",
677 "--dev-url",
678 devServerUrl,
679 ]);
680 assert.notInclude(config.args, "bash");
681 assert.notInclude(config.args, "/bin/sh");
682 assert.notInclude(config.args, "-c");
683 assert.isTrue(Option.isNone(config.preflightFailure));
684 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
685 );
686
687 it.effect("resolvePrimary and resolveWsl share one token under concurrent resolution", () =>
688 withHarness(
689 Effect.gen(function* () {
690 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
691
692 const [primary, wsl] = yield* Effect.all(
693 [configuration.resolvePrimary, configuration.resolveWsl({ port: 5000, distro: null })],
694 { concurrency: "unbounded" },
695 );
696
697 assert.equal(wsl.bootstrap.desktopBootstrapToken, primary.bootstrap.desktopBootstrapToken);
698 }),
699 ),
700 );
701
702 it.effect("gives the Windows and WSL backends one host scope that survives a restart", () =>
703 Effect.gen(function* () {
704 const fileSystem = yield* FileSystem.FileSystem;
705 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
706 prefix: "t3-desktop-backend-config-test-",
707 });
708 const launch = Effect.gen(function* () {
709 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
710 const primary = yield* configuration.resolvePrimary;
711 const wsl = yield* configuration.resolveWsl({ port: 5050, distro: null });
712 assert.equal(wsl.env.T3CODE_DESKTOP_HOST_SCOPE, primary.env.T3CODE_DESKTOP_HOST_SCOPE);
713 assert.include((wsl.env.WSLENV ?? "").split(":"), "T3CODE_DESKTOP_HOST_SCOPE");
714 return primary.env.T3CODE_DESKTOP_HOST_SCOPE;
715 }).pipe(
716 Effect.provide(
717 layerBackendConfiguration().pipe(
718 Layer.provideMerge(layerServerExposure),
719 Layer.provideMerge(DesktopAppSettings.layerTest()),
720 Layer.provideMerge(DesktopWslServerTree.layerTest()),
721 Layer.provideMerge(
722 DesktopWslEnvironment.layerTest({
723 isAvailable: true,
724 windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"),
725 getDistroIp: () => Option.some("172.27.0.99"),
726 }),
727 ),
728 Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })),
729 ),
730 ),
731 );
732
733 const first = yield* launch;
734 assert.match(first ?? "", /^[0-9a-f]{32}$/);
735 assert.equal(yield* launch, first);
736 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
737 );
738
739 it.effect("resolveWsl carries the kill switch and resource attributes into the distro", () =>
740 Effect.gen(function* () {
741 const fileSystem = yield* FileSystem.FileSystem;
742 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
743 prefix: "t3-desktop-backend-config-test-",
744 });
745
746 yield* Effect.gen(function* () {
747 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
748 const config = yield* configuration.resolveWsl({ port: 5050, distro: null });
749
750 assert.equal(config.env.OTEL_SDK_DISABLED, "true");
751 assert.include((config.env.WSLENV ?? "").split(":"), "OTEL_SDK_DISABLED");
752 assert.equal(config.env.T3CODE_TELEMETRY_ENABLED, "false");
753 assert.include((config.env.WSLENV ?? "").split(":"), "T3CODE_TELEMETRY_ENABLED");
754 assert.equal(config.env.OTEL_RESOURCE_ATTRIBUTES, "deployment.environment.name=staging");
755 assert.include((config.env.WSLENV ?? "").split(":"), "OTEL_RESOURCE_ATTRIBUTES");
756 }).pipe(
757 Effect.provide(
758 layerBackendConfiguration().pipe(
759 Layer.provideMerge(layerServerExposure),
760 Layer.provideMerge(DesktopAppSettings.layerTest()),
761 Layer.provideMerge(DesktopWslServerTree.layerTest()),
762 Layer.provideMerge(
763 DesktopWslEnvironment.layerTest({
764 isAvailable: true,
765 windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"),
766 getDistroIp: () => Option.some("172.27.0.99"),
767 }),
768 ),
769 Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })),
770 ),
771 ),
772 Effect.provideService(HostProcess.Environment, {
773 OTEL_SDK_DISABLED: "true",
774 T3CODE_TELEMETRY_ENABLED: "false",
775 OTEL_RESOURCE_ATTRIBUTES: "deployment.environment.name=staging",
776 }),
777 );
778 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
779 );
780
781 it.effect("resolveWsl preserves existing WSLENV entries when forwarding backend secrets", () =>
782 Effect.gen(function* () {
783 const fileSystem = yield* FileSystem.FileSystem;
784 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
785 prefix: "t3-desktop-backend-config-test-",
786 });
787
788 yield* Effect.gen(function* () {
789 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
790 const config = yield* configuration.resolveWsl({ port: 5050, distro: null });
791
792 assert.equal(config.executablePath, "wsl.exe");
793 assert.equal(config.bootstrap.port, 5050);
794 assert.equal(config.bootstrap.host, "0.0.0.0");
795 assert.equal(config.bootstrap.tailscaleServeEnabled, false);
796 assert.notProperty(config.bootstrap, "desktopTelemetryFd");
797 assert.notProperty(config.bootstrap, "resourceMonitorPath");
798 assert.equal(config.httpBaseUrl.href, "http://172.27.0.99:5050/");
799 assert.equal(config.env.OPENAI_API_KEY, "openai-key");
800 assert.equal(config.env.ANTHROPIC_API_KEY, "anthropic-key");
801 assert.equal(config.env.T3CODE_OTLP_PROTOCOL, "http/protobuf");
802 assert.equal(
803 config.env.WSLENV,
804 "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:T3CODE_DESKTOP_HOST_SCOPE:ANTHROPIC_API_KEY:T3CODE_OTLP_HEADERS:T3CODE_OTLP_PROTOCOL",
805 );
806 }).pipe(
807 Effect.provide(
808 layerBackendConfiguration().pipe(
809 Layer.provideMerge(layerServerExposure),
810 Layer.provideMerge(DesktopAppSettings.layerTest()),
811 Layer.provideMerge(DesktopWslServerTree.layerTest()),
812 Layer.provideMerge(
813 DesktopWslEnvironment.layerTest({
814 isAvailable: true,
815 windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"),
816 getDistroIp: () => Option.some("172.27.0.99"),
817 }),
818 ),
819 Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })),
820 ),
821 ),
822 Effect.provideService(HostProcess.Environment, {
823 WSLENV: "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u",
824 OPENAI_API_KEY: "openai-key",
825 ANTHROPIC_API_KEY: "anthropic-key",
826 T3CODE_OTLP_HEADERS: 'authorization="Bearer%20my-token"',
827 T3CODE_OTLP_PROTOCOL: "http/protobuf",
828 }),
829 );
830 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
831 );
832
833 it.effect(
834 "resolvePrimary falls back to the Windows primary when wsl-only but WSL is unavailable",
835 () =>
836 Effect.gen(function* () {
837 const fileSystem = yield* FileSystem.FileSystem;
838 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
839 prefix: "t3-desktop-backend-config-test-",
840 });
841
842 yield* Effect.gen(function* () {
843 const environment = yield* DesktopEnvironment.DesktopEnvironment;
844 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
845 const config = yield* configuration.resolvePrimary;
846
847 assert.equal(config.executablePath, process.execPath);
848 assert.equal(config.bootstrap.t3Home, environment.baseDir);
849 assert.isTrue(Option.isNone(config.preflightFailure));
850 }).pipe(
851 Effect.provide(
852 layerBackendConfiguration().pipe(
853 Layer.provideMerge(layerServerExposure),
854 Layer.provideMerge(
855 DesktopAppSettings.layerTest({
856 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
857 wslBackendEnabled: true,
858 wslOnly: true,
859 }),
860 ),
861 Layer.provideMerge(DesktopWslServerTree.layerTest()),
862 Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
863 Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })),
864 ),
865 ),
866 );
867 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
868 );
869
870 it.effect(
871 "resolvePrimary marks a removed persisted WSL distro as a fatal preflight failure",
872 () =>
873 Effect.gen(function* () {
874 const fileSystem = yield* FileSystem.FileSystem;
875 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
876 prefix: "t3-desktop-backend-config-test-",
877 });
878
879 yield* Effect.gen(function* () {
880 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
881 const config = yield* configuration.resolvePrimary;
882 const failure = Option.getOrThrow(config.preflightFailure);
883
884 assert.equal(config.executablePath, "wsl.exe");
885 assert.isTrue(failure.fatal);
886 assert.include(failure.reason, "Removed-Distro");
887 }).pipe(
888 Effect.provide(
889 layerBackendConfiguration().pipe(
890 Layer.provideMerge(layerServerExposure),
891 Layer.provideMerge(
892 DesktopAppSettings.layerTest({
893 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
894 wslBackendEnabled: true,
895 wslOnly: true,
896 wslDistro: "Removed-Distro",
897 }),
898 ),
899 Layer.provideMerge(DesktopWslServerTree.layerTest()),
900 Layer.provideMerge(
901 DesktopWslEnvironment.layerTest({
902 isAvailable: true,
903 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
904 }),
905 ),
906 Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })),
907 ),
908 ),
909 );
910 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
911 );
912
913 it.effect("resolveWsl marks a missing packaged server entry as fatal", () =>
914 Effect.gen(function* () {
915 const fileSystem = yield* FileSystem.FileSystem;
916 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
917 prefix: "t3-desktop-backend-config-test-",
918 });
919
920 yield* Effect.gen(function* () {
921 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
922 const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
923 const failure = Option.getOrThrow(config.preflightFailure);
924
925 assert.isTrue(failure.fatal);
926 assert.include(failure.reason, "missing server entry");
927 }).pipe(
928 Effect.provide(
929 layerBackendConfiguration().pipe(
930 Layer.provideMerge(layerServerExposure),
931 Layer.provideMerge(DesktopAppSettings.layerTest()),
932 Layer.provideMerge(DesktopWslServerTree.layerTest()),
933 Layer.provideMerge(
934 DesktopWslEnvironment.layerTest({
935 isAvailable: true,
936 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
937 }),
938 ),
939 Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })),
940 ),
941 ),
942 );
943 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
944 );
945
946 it.effect("prefers the external packaged resource monitor over the copy inside the asar", () =>
947 Effect.gen(function* () {
948 const fileSystem = yield* FileSystem.FileSystem;
949 const path = yield* Path.Path;
950 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
951 prefix: "t3-desktop-backend-config-test-",
952 });
953 const resourcesPath = path.join(baseDir, "resources");
954 const dirname = `${resourcesPath}/app.asar/apps/desktop/dist-electron`;
955 const embeddedMonitorPath = `${resourcesPath}/app.asar/apps/desktop/prod-resources/resource-monitor/t3-resource-monitor`;
956 const monitorPath = path.join(resourcesPath, "resource-monitor/t3-resource-monitor");
957 yield* fileSystem.makeDirectory(
958 `${resourcesPath}/app.asar/apps/desktop/prod-resources/resource-monitor`,
959 { recursive: true },
960 );
961 yield* fileSystem.makeDirectory(`${resourcesPath}/resource-monitor`, {
962 recursive: true,
963 });
964 yield* fileSystem.writeFileString(embeddedMonitorPath, "embedded");
965 yield* fileSystem.writeFileString(monitorPath, "binary");
966 yield* fileSystem.chmod(monitorPath, 0o755);
967
968 yield* Effect.gen(function* () {
969 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
970 const config = yield* configuration.resolvePrimary;
971 assert.equal(config.bootstrap.resourceMonitorPath, monitorPath);
972 assert.equal(config.bootstrap.desktopTelemetryFd, 4);
973 assert.equal(config.bootstrap.desktopTelemetryControlFd, 5);
974 }).pipe(
975 Effect.provide(
976 layerBackendConfiguration().pipe(
977 Layer.provideMerge(layerServerExposure),
978 Layer.provideMerge(DesktopAppSettings.layerTest()),
979 Layer.provideMerge(DesktopWslServerTree.layerTest()),
980 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
981 Layer.provideMerge(
982 layerEnvironment(baseDir, {
983 appPath: `${resourcesPath}/app.asar`,
984 dirname,
985 isPackaged: true,
986 resourcesPath,
987 }),
988 ),
989 ),
990 ),
991 );
992 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
993 );
994
995 it("resolvePrimaryLabel is runSync-safe against the real WSL availability probe", async () => {
996 // oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- This test intentionally replicates the sync IPC handler's runSync path to catch a regression to async-only resolution; it.effect would mask it.
997 const runtime = ManagedRuntime.make(
998 layerBackendConfiguration().pipe(
999 Layer.provideMerge(layerServerExposure),
1000 Layer.provideMerge(DesktopAppSettings.layerTest()),
1001 Layer.provideMerge(DesktopWslServerTree.layerTest()),
1002 Layer.provideMerge(DesktopWslEnvironment.layer),
1003 Layer.provideMerge(DesktopManagedPolicy.layerTest()),
1004 Layer.provideMerge(
1005 Layer.succeed(
1006 ChildProcessSpawner.ChildProcessSpawner,
1007 ChildProcessSpawner.make(() =>
1008 Effect.die("spawner should not be used while probing WSL availability"),
1009 ),
1010 ),
1011 ),
1012 Layer.provideMerge(layerEnvironment("/tmp/t3-wsl-isavailable", { platform: "win32" })),
1013 Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
1014 ),
1015 );
1016 try {
1017 const configuration = await runtime.runPromise(
1018 DesktopBackendConfiguration.DesktopBackendConfiguration,
1019 );
1020 // oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- Same reason: this is the synchronous resolution the IPC handler performs.
1021 const label = Effect.runSync(configuration.resolvePrimaryLabel);
1022 assert.equal(typeof label, "string");
1023 } finally {
1024 await runtime.dispose();
1025 }
1026 });
1027 });