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

DesktopBackendConfiguration.test.ts

1,000 lines41.1 KB

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