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

DesktopBackendConfiguration.test.ts

1,002 lines41.6 KB

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