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

DesktopBackendConfiguration.test.ts

1,357 lines55.5 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Logger from "effect/Logger";
7import * as ManagedRuntime from "effect/ManagedRuntime";
8import * as Option from "effect/Option";
9import * as Path from "effect/Path";
10import * as PlatformError from "effect/PlatformError";
11import * as Schema from "effect/Schema";
12import { ChildProcessSpawner } from "effect/unstable/process";
13​
14import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
15import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
16import * as DesktopConfig from "../app/DesktopConfig.ts";
17import * as DesktopServerExposure from "./DesktopServerExposure.ts";
18import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
19import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
20import * as DesktopWslServerTree from "../wsl/DesktopWslServerTree.ts";
21​
22const PersistedServerObservabilitySettingsDocument = Schema.Struct({
23 observability: Schema.Struct({
24 otlpTracesUrl: Schema.String,
25 otlpMetricsUrl: Schema.String,
26 }),
27});
28​
29const encodePersistedServerObservabilitySettingsDocument = Schema.encodeEffect(
30 Schema.fromJsonString(PersistedServerObservabilitySettingsDocument),
31);
32​
33const isDesktopBackendObservabilitySettingsReadError = Schema.is(
34 DesktopBackendConfiguration.DesktopBackendObservabilitySettingsReadError,
35);
36​
37const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExposure, {
38 getState: Effect.die("unexpected getState"),
39 backendConfig: Effect.succeed({
40 port: 4888,
41 bindHost: "0.0.0.0",
42 httpBaseUrl: new URL("http://127.0.0.1:4888"),
43 tailscaleServeEnabled: true,
44 tailscaleServePort: 8443,
45 }),
46 configureFromSettings: () => Effect.die("unexpected configureFromSettings"),
47 setMode: () => Effect.die("unexpected setMode"),
48 setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
49 getAdvertisedEndpoints: Effect.succeed([]),
50} satisfies DesktopServerExposure.DesktopServerExposure["Service"]);
51​
52function makeEnvironmentLayer(
53 baseDir: string,
54 options?: {
55 readonly appPath?: string;
56 readonly dirname?: string;
57 readonly isPackaged?: boolean;
58 readonly devServerUrl?: string;
59 readonly platform?: NodeJS.Platform;
60 readonly resourcesPath?: string;
61 readonly appVersion?: string;
62 readonly processArch?: NodeJS.Architecture;
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 }),
86 ),
87 ),
88 );
90​
91const restoreEnv = (name: string, value: string | undefined) => {
92 if (value === undefined) {
93 delete process.env[name];
94 } else {
95 process.env[name] = value;
96 }
97};
98​
99const withHarness = <A, E, R>(
100 effect: Effect.Effect<
101 A,
102 E,
103 | R
104 | DesktopEnvironment.DesktopEnvironment
105 | FileSystem.FileSystem
106 | DesktopBackendConfiguration.DesktopBackendConfiguration
107 >,
108) =>
109 Effect.gen(function* () {
110 const fileSystem = yield* FileSystem.FileSystem;
111 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
112 prefix: "t3-desktop-backend-config-test-",
113 });
114​
115 return yield* effect.pipe(
116 Effect.provide(
117 DesktopBackendConfiguration.layer.pipe(
118 Layer.provideMerge(serverExposureLayer),
119 Layer.provideMerge(DesktopAppSettings.layerTest()),
120 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
121 Layer.provideMerge(DesktopWslServerTree.layerTest()),
122 Layer.provideMerge(makeEnvironmentLayer(baseDir)),
123 ),
124 ),
125 );
126 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
127​
128interface PackagedWslHarnessContext {
129 readonly baseDir: string;
130 readonly archivePath: string;
131 readonly hashPath: string;
132 readonly archiveHash: string;
133 readonly mountedAppRoot: string;
134 readonly mountedEntryPath: string;
136​
137const withPackagedWslHarness = <A, E, R>(
138 input: {
139 readonly archiveHash: string;
140 readonly wsl: (
141 context: PackagedWslHarnessContext,
142 ) => DesktopWslEnvironment.DesktopWslEnvironmentTestStub;
143 readonly forbidFallback?: string;
144 readonly cleanupLegacy?: Effect.Effect<void>;
145 readonly forbidCleanup?: string;
146 },
147 effect: (
148 context: PackagedWslHarnessContext,
149 ) => Effect.Effect<
150 A,
151 E,
152 R | FileSystem.FileSystem | Path.Path | DesktopBackendConfiguration.DesktopBackendConfiguration
153 >,
154) =>
155 Effect.gen(function* () {
156 const fileSystem = yield* FileSystem.FileSystem;
157 const path = yield* Path.Path;
158 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
159 prefix: "t3-desktop-backend-config-test-",
160 });
161 const archivePath = path.join(baseDir, "wsl-runtime.tar.gz");
162 const hashPath = `${archivePath}.sha256`;
163 const mountedAppRoot = "/mnt/c/app.asar.unpacked";
164 const mountedEntryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");
165 yield* fileSystem.makeDirectory(path.dirname(mountedEntryPath), { recursive: true });
166 yield* fileSystem.writeFileString(mountedEntryPath, "");
167 yield* fileSystem.writeFileString(archivePath, "archive");
168 yield* fileSystem.writeFileString(hashPath, `${input.archiveHash}\n`);
169​
170 const context = {
171 baseDir,
172 archivePath,
173 hashPath,
174 archiveHash: input.archiveHash,
175 mountedAppRoot,
176 mountedEntryPath,
177 } satisfies PackagedWslHarnessContext;
178 const serverTreeLayer = input.forbidFallback
179 ? Layer.succeed(
180 DesktopWslServerTree.DesktopWslServerTree,
181 DesktopWslServerTree.DesktopWslServerTree.of({
182 ensure: Effect.die(input.forbidFallback),
183 cleanupLegacy: input.forbidCleanup
184 ? Effect.die(input.forbidCleanup)
185 : (input.cleanupLegacy ?? Effect.void),
186 }),
187 )
188 : DesktopWslServerTree.layerTest({
189 result: { ok: true, root: path.join(baseDir, "app.asar.unpacked") },
190 cleanupLegacy: input.cleanupLegacy ?? Effect.void,
191 });
192​
193 return yield* effect(context).pipe(
194 Effect.provide(
195 DesktopBackendConfiguration.layer.pipe(
196 Layer.provideMerge(serverExposureLayer),
197 Layer.provideMerge(DesktopAppSettings.layerTest()),
198 Layer.provideMerge(serverTreeLayer),
199 Layer.provideMerge(
200 DesktopWslEnvironment.layerTest({
201 isAvailable: true,
202 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
203 windowsToWslPath: () => Option.some(mountedAppRoot),
204 getDistroIp: () => Option.some("172.27.0.99"),
205 ...input.wsl(context),
206 }),
207 ),
208 Layer.provideMerge(
209 makeEnvironmentLayer(baseDir, {
210 appPath: baseDir,
211 platform: "win32",
212 resourcesPath: baseDir,
213 }),
214 ),
215 ),
216 ),
217 );
218 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
219​
220describe("DesktopBackendConfiguration", () => {
221 it.effect("resolvePrimary produces a stable scoped bootstrap token", () =>
222 withHarness(
223 Effect.gen(function* () {
224 const environment = yield* DesktopEnvironment.DesktopEnvironment;
225 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
226​
227 const first = yield* configuration.resolvePrimary;
228 const second = yield* configuration.resolvePrimary;
229​
230 assert.equal(first.executablePath, process.execPath);
231 assert.equal(first.entryPath, environment.backendEntryPath);
232 assert.equal(first.cwd, environment.backendCwd);
233 assert.equal(first.captureOutput, true);
234 assert.equal(first.env.ELECTRON_RUN_AS_NODE, "1");
235 assert.isUndefined(first.env.T3CODE_PORT);
236 assert.isUndefined(first.env.T3CODE_MODE);
237 assert.isUndefined(first.env.T3CODE_DESKTOP_LAN_HOST);
238​
239 assert.equal(first.bootstrap.mode, "desktop");
240 assert.equal(first.bootstrap.noBrowser, true);
241 assert.equal(first.bootstrap.port, 4888);
242 assert.equal(first.bootstrap.host, "0.0.0.0");
243 assert.equal(first.bootstrap.t3Home, environment.baseDir);
244 assert.equal(first.bootstrap.tailscaleServeEnabled, true);
245 assert.equal(first.bootstrap.tailscaleServePort, 8443);
246 assert.match(first.bootstrap.desktopBootstrapToken, /^[0-9a-f]{48}$/i);
247 assert.equal(second.bootstrap.desktopBootstrapToken, first.bootstrap.desktopBootstrapToken);
248 }),
249 ),
250 );
251​
252 it.effect("resolvePrimary starts from server.asar without materializing the WSL tree", () =>
253 Effect.gen(function* () {
254 const fileSystem = yield* FileSystem.FileSystem;
255 const path = yield* Path.Path;
256 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
257 prefix: "t3-desktop-backend-config-test-",
258 });
259 const resourcesPath = path.join(baseDir, "resources");
260​
261 const config = yield* Effect.gen(function* () {
262 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
263 return yield* configuration.resolvePrimary;
264 }).pipe(
265 Effect.provide(
266 DesktopBackendConfiguration.layer.pipe(
267 Layer.provideMerge(serverExposureLayer),
268 Layer.provideMerge(DesktopAppSettings.layerTest()),
269 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
270 Layer.provideMerge(
271 Layer.succeed(
272 DesktopWslServerTree.DesktopWslServerTree,
273 DesktopWslServerTree.DesktopWslServerTree.of({
274 ensure: Effect.die("Windows primary must not extract the WSL server tree"),
275 cleanupLegacy: Effect.die("Windows primary must not clean the WSL server tree"),
276 }),
277 ),
278 ),
279 Layer.provideMerge(
280 makeEnvironmentLayer(baseDir, {
281 appPath: `${resourcesPath}/app.asar`,
282 platform: "win32",
283 resourcesPath,
284 }),
285 ),
286 ),
287 ),
288 );
289​
290 assert.equal(
291 config.entryPath,
292 path.join(resourcesPath, "server.asar/apps/server/dist/bin.mjs"),
293 );
294 assert.equal(config.env.ELECTRON_RUN_AS_NODE, "1");
295 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
296 );
297​
298 it.effect("resolveWsl reuses the primary's bootstrap token", () =>
299 withHarness(
300 Effect.gen(function* () {
301 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
302​
303 const primary = yield* configuration.resolvePrimary;
304 const wsl = yield* configuration.resolveWsl({ port: 5000, distro: null });
305​
306 assert.equal(wsl.bootstrap.desktopBootstrapToken, primary.bootstrap.desktopBootstrapToken);
307 }),
308 ),
309 );
310​
311 it.effect("resolveWsl pins a default-tracking run to the concrete default distro", () =>
312 Effect.gen(function* () {
313 const fileSystem = yield* FileSystem.FileSystem;
314 const path = yield* Path.Path;
315 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
316 prefix: "t3-desktop-backend-config-test-",
317 });
318 const entryPath = path.join(baseDir, "apps/server/dist/bin.mjs");
319 yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
320 yield* fileSystem.writeFileString(entryPath, "");
321​
322 const observedDistros: Array<string | null> = [];
323 const config = yield* Effect.gen(function* () {
324 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
325 return yield* configuration.resolveWsl({ port: 5000, distro: null });
326 }).pipe(
327 Effect.provide(
328 DesktopBackendConfiguration.layer.pipe(
329 Layer.provideMerge(serverExposureLayer),
330 Layer.provideMerge(DesktopAppSettings.layerTest()),
331 Layer.provideMerge(DesktopWslServerTree.layerTest()),
332 Layer.provideMerge(
333 DesktopWslEnvironment.layerTest({
334 isAvailable: true,
335 distros: [
336 { name: "Debian", isDefault: false, version: 2 },
337 { name: "Ubuntu", isDefault: true, version: 2 },
338 ],
339 windowsToWslPath: (distro) => {
340 observedDistros.push(distro);
341 return Option.some("/repo");
342 },
343 ensureNodePty: (distro) => {
344 observedDistros.push(distro);
345 return { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" };
346 },
347 getDistroIp: (distro) => {
348 observedDistros.push(distro);
349 return Option.some("172.27.0.99");
350 },
351 }),
352 ),
353 Layer.provideMerge(
354 makeEnvironmentLayer(baseDir, {
355 appPath: baseDir,
356 platform: "win32",
357 resourcesPath: baseDir,
358 }),
359 ),
360 ),
361 ),
362 );
363​
364 assert.equal(config.runningDistro, "Ubuntu");
365 assert.deepEqual(config.args.slice(0, 2), ["-d", "Ubuntu"]);
366 assert.deepEqual(observedDistros, ["Ubuntu", "Ubuntu", "Ubuntu"]);
367 assert.isTrue(Option.isNone(config.preflightFailure));
368 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
369 );
370​
371 it.effect("resolveWsl launches a packaged backend from the WSL-local runtime cache", () => {
372 const observedArchives: Array<{
373 windowsArchivePath: string;
374 runtimeId: string;
375 sha256: string;
376 }> = [];
377 const observedProbeRoots: string[] = [];
378 let legacyCleanupCount = 0;
379 const linuxAppRoot = "/home/test/.t3/wsl-runtime/1.2.3-x64";
380 const resolvedPath = "/home/test/.local/bin:/usr/bin:/bin";
381​
382 return withPackagedWslHarness(
383 {
384 archiveHash: "a".repeat(64),
385 forbidFallback: "A valid WSL archive must not extract the Windows fallback",
386 cleanupLegacy: Effect.sync(() => {
387 legacyCleanupCount += 1;
388 }),
389 wsl: () => ({
390 prepareRuntime: (_distro, archive) => {
391 observedArchives.push({
392 windowsArchivePath: archive.windowsPath,
393 runtimeId: archive.runtimeId,
394 sha256: archive.sha256,
395 });
396 return { ok: true, linuxAppRoot };
397 },
398 probeRuntime: (_distro, root) => {
399 observedProbeRoots.push(root);
400 return { ok: true, resolvedPath };
401 },
402 // The staged runtime carries its own Node and node-pty, so it must
403 // not require the mounted server tree's native dependency check.
404 ensureNodePty: () => {
405 throw new Error("the staged runtime must not probe for node-pty");
406 },
407 }),
408 },
409 ({ archiveHash, archivePath, baseDir }) =>
410 Effect.gen(function* () {
411 const path = yield* Path.Path;
412 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
413 const config = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
414​
415 assert.deepEqual(observedArchives, [
416 {
417 windowsArchivePath: archivePath,
418 runtimeId: `sha256-${archiveHash}`,
419 sha256: archiveHash,
420 },
421 ]);
422 assert.deepEqual(observedProbeRoots, [linuxAppRoot]);
423 assert.equal(
424 config.entryPath,
425 path.join(baseDir, "server.asar/apps/server/dist/bin.mjs"),
426 );
427 assert.deepEqual(config.args, [
428 "-d",
429 "Ubuntu",
430 "--exec",
431 "env",
432 `PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${resolvedPath}`,
433 `${linuxAppRoot}/t3`,
434 "--bootstrap-fd",
435 "0",
436 ]);
437 assert.notInclude(config.args, "/usr/bin/node");
438 assert.equal(config.wslRuntimeId, `sha256-${archiveHash}`);
439 assert.equal(legacyCleanupCount, 1);
440 assert.isTrue(Option.isNone(config.preflightFailure));
441 }),
442 );
443 });
444​
445 it.effect("resolveWsl changes the cache id when the packaged archive changes", () => {
446 const firstHash = "a".repeat(64);
447 const secondHash = "b".repeat(64);
448 const observedRuntimeIds: string[] = [];
449 return withPackagedWslHarness(
450 {
451 archiveHash: firstHash,
452 wsl: () => ({
453 prepareRuntime: (_distro, archive) => {
454 observedRuntimeIds.push(archive.runtimeId);
455 return { ok: true, linuxAppRoot: `/runtime/${archive.runtimeId}` };
456 },
457 ensureNodePty: () => ({
458 ok: true,
459 nodePath: "/usr/bin/node",
460 resolvedPath: "/usr/bin:/bin",
461 }),
462 }),
463 },
464 ({ hashPath, mountedAppRoot }) =>
465 Effect.gen(function* () {
466 const fileSystem = yield* FileSystem.FileSystem;
467 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
468 const first = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
469 yield* fileSystem.writeFileString(hashPath, secondHash);
470 const second = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
471 yield* fileSystem.writeFileString(hashPath, "not-a-sha256");
472 const invalidIdentity = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
473​
474 assert.deepEqual(observedRuntimeIds, [`sha256-${firstHash}`, `sha256-${secondHash}`]);
475 assert.equal(first.wslRuntimeId, observedRuntimeIds[0]);
476 assert.include(first.args, `/runtime/sha256-${firstHash}/t3`);
477 assert.equal(second.wslRuntimeId, observedRuntimeIds[1]);
478 assert.include(second.args, `/runtime/sha256-${secondHash}/t3`);
479 assert.isUndefined(invalidIdentity.wslRuntimeId);
480 assert.include(invalidIdentity.args, "/usr/bin/node");
481 assert.include(invalidIdentity.args, `${mountedAppRoot}/apps/server/dist/bin.mjs`);
482 }),
483 );
484 });
485​
486 it.effect("resolveWsl falls back to the mounted runtime when archive staging fails", () => {
487 const observedNodePtyRoots: string[] = [];
488 return withPackagedWslHarness(
489 {
490 archiveHash: "b".repeat(64),
491 wsl: () => ({
492 prepareRuntime: () => ({ ok: false, reason: "archive is corrupt" }),
493 ensureNodePty: (_distro, root) => {
494 observedNodePtyRoots.push(root);
495 return { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" };
496 },
497 }),
498 },
499 ({ mountedAppRoot, mountedEntryPath }) =>
500 Effect.gen(function* () {
501 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
502 const config = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
503​
504 assert.deepEqual(observedNodePtyRoots, [mountedAppRoot]);
505 assert.equal(config.entryPath, mountedEntryPath);
506 assert.include(config.args, "/usr/bin/node");
507 assert.include(config.args, `${mountedAppRoot}/apps/server/dist/bin.mjs`);
508 assert.isUndefined(config.wslRuntimeId);
509 assert.isTrue(Option.isNone(config.preflightFailure));
510 }),
511 );
512 });
513​
514 it.effect("resolveWsl retires a staged runtime whose executable does not start", () => {
515 const archiveHash = "c".repeat(64);
516 const stagedAppRoot = `/home/test/.t3/wsl-runtime/sha256-${archiveHash}`;
517 const observedProbeRoots: string[] = [];
518 const observedNodePtyRoots: string[] = [];
519 const invalidatedRuntimeIds: string[] = [];
520 return withPackagedWslHarness(
521 {
522 archiveHash,
523 wsl: () => ({
524 prepareRuntime: () => ({ ok: true, linuxAppRoot: stagedAppRoot }),
525 invalidateRuntime: (_distro, runtimeId) =>
526 Effect.sync(() => {
527 invalidatedRuntimeIds.push(runtimeId);
528 }),
529 probeRuntime: (_distro, root) => {
530 observedProbeRoots.push(root);
531 return { ok: false, reason: `${root}/t3 --version failed (exit 127)` };
532 },
533 ensureNodePty: (_distro, root) => {
534 observedNodePtyRoots.push(root);
535 return { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" };
536 },
537 }),
538 },
539 ({ mountedAppRoot, mountedEntryPath }) =>
540 Effect.gen(function* () {
541 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
542 const config = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
543​
544 assert.deepEqual(observedProbeRoots, [stagedAppRoot]);
545 assert.deepEqual(observedNodePtyRoots, [mountedAppRoot]);
546 assert.include(config.args, "/usr/bin/node");
547 assert.include(config.args, `${mountedAppRoot}/apps/server/dist/bin.mjs`);
548 assert.notInclude(config.args, `${stagedAppRoot}/t3`);
549 assert.equal(config.entryPath, mountedEntryPath);
550 assert.isUndefined(config.wslRuntimeId);
551 assert.isTrue(Option.isNone(config.preflightFailure));
552 assert.deepEqual(invalidatedRuntimeIds, [`sha256-${archiveHash}`]);
553 }),
554 );
555 });
556​
557 it.effect("resolveWsl keeps the staged runtime when the mounted tree fails too", () => {
558 const stagedAppRoot = "/home/test/.t3/wsl-runtime/cache";
559 const invalidatedRuntimeIds: string[] = [];
560 return withPackagedWslHarness(
561 {
562 archiveHash: "d".repeat(64),
563 wsl: () => ({
564 prepareRuntime: () => ({ ok: true, linuxAppRoot: stagedAppRoot }),
565 invalidateRuntime: (_distro, runtimeId) =>
566 Effect.sync(() => {
567 invalidatedRuntimeIds.push(runtimeId);
568 }),
569 probeRuntime: () => ({
570 ok: false,
571 reason: "unsupported CPU architecture or incompatible system libraries",
572 }),
573 ensureNodePty: () => ({
574 ok: false,
575 reason: "mounted tree is broken in some other way",
576 fatal: true,
577 }),
578 }),
579 },
580 () =>
581 Effect.gen(function* () {
582 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
583 const config = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
584 const failure = Option.getOrThrow(config.preflightFailure);
585​
586 assert.isTrue(failure.fatal);
587 assert.include(failure.reason, "unsupported CPU architecture");
588 assert.deepEqual(invalidatedRuntimeIds, []);
589 }),
590 );
591 });
592​
593 it.effect("resolveWsl keeps WSL retryable when the mounted fallback fails transiently", () => {
594 const stagedAppRoot = "/home/test/.t3/wsl-runtime/cache";
595 const invalidatedRuntimeIds: string[] = [];
596 return withPackagedWslHarness(
597 {
598 archiveHash: "f".repeat(64),
599 wsl: () => ({
600 prepareRuntime: () => ({ ok: true, linuxAppRoot: stagedAppRoot }),
601 invalidateRuntime: (_distro, runtimeId) =>
602 Effect.sync(() => {
603 invalidatedRuntimeIds.push(runtimeId);
604 }),
605 probeRuntime: () => ({ ok: false, reason: "t3 --version failed (exit 1)" }),
606 ensureNodePty: () => ({
607 ok: false,
608 reason: "WSL backend preflight timed out while probing for Node.js.",
609 fatal: false,
610 }),
611 }),
612 },
613 () =>
614 Effect.gen(function* () {
615 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
616 const config = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
617 const failure = Option.getOrThrow(config.preflightFailure);
618​
619 assert.isFalse(failure.fatal);
620 assert.equal(failure.retryLimit, 12);
621 assert.include(failure.reason, "timed out");
622 assert.deepEqual(invalidatedRuntimeIds, []);
623 }),
624 );
625 });
626​
627 it.effect(
628 "resolveWsl preserves inherited PATH with quote-sensitive values as separate args",
629 () =>
630 Effect.gen(function* () {
631 const fileSystem = yield* FileSystem.FileSystem;
632 const path = yield* Path.Path;
633 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
634 prefix: "t3-desktop-backend-config-test-",
635 });
636 const entryPath = path.join(baseDir, "apps/server/dist/bin.mjs");
637 yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
638 yield* fileSystem.writeFileString(entryPath, "");
639​
640 const nodePath = "/home/test user's/.nvm/versions/node/v22.0.0/bin/node";
641 const linuxAppRoot = "/tmp/t3 code's launch";
642 const linuxEntryPath = `${linuxAppRoot}/apps/server/dist/bin.mjs`;
643 const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
644 const devServerUrl = "http://127.0.0.1:5733/dev%20assets/?label=hello%20world";
645 const config = yield* Effect.gen(function* () {
646 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
647 return yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
648 }).pipe(
649 Effect.provide(
650 DesktopBackendConfiguration.layer.pipe(
651 Layer.provideMerge(serverExposureLayer),
652 Layer.provideMerge(DesktopAppSettings.layerTest()),
653 Layer.provideMerge(DesktopWslServerTree.layerTest()),
654 Layer.provideMerge(
655 DesktopWslEnvironment.layerTest({
656 isAvailable: true,
657 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
658 windowsToWslPath: () => Option.some(linuxAppRoot),
659 ensureNodePty: () => ({ ok: true, nodePath, resolvedPath }),
660 getDistroIp: () => Option.some("172.27.0.99"),
661 }),
662 ),
663 Layer.provideMerge(
664 makeEnvironmentLayer(baseDir, {
665 appPath: baseDir,
666 devServerUrl,
667 isPackaged: true,
668 platform: "win32",
669 resourcesPath: baseDir,
670 }),
671 ),
672 ),
673 ),
674 );
675​
676 assert.equal(config.bootstrapDelivery, "stdin");
677 assert.deepEqual(config.args, [
678 "-d",
679 "Ubuntu",
680 "--exec",
681 "env",
682 "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",
683 nodePath,
684 linuxEntryPath,
685 "--bootstrap-fd",
686 "0",
687 "--dev-url",
688 devServerUrl,
689 ]);
690 assert.notInclude(config.args, "bash");
691 assert.notInclude(config.args, "/bin/sh");
692 assert.notInclude(config.args, "-c");
693 assert.isTrue(Option.isNone(config.preflightFailure));
694 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
695 );
696​
697 it.effect("resolvePrimary and resolveWsl share one token under concurrent resolution", () =>
698 withHarness(
699 Effect.gen(function* () {
700 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
701​
702 // Resolve both before any token is cached, concurrently, so the
703 // generate step (a yield point) can interleave. The atomic
704 // get-or-create must still hand both the same token; a non-atomic
705 // Ref would let each generate its own and break the shared-token
706 // invariant.
707 const [primary, wsl] = yield* Effect.all(
708 [configuration.resolvePrimary, configuration.resolveWsl({ port: 5000, distro: null })],
709 { concurrency: "unbounded" },
710 );
711​
712 assert.equal(wsl.bootstrap.desktopBootstrapToken, primary.bootstrap.desktopBootstrapToken);
713 }),
714 ),
715 );
716​
717 it.effect("resolvePrimary surfaces persisted backend observability endpoints", () =>
718 withHarness(
719 Effect.gen(function* () {
720 const fileSystem = yield* FileSystem.FileSystem;
721 const environment = yield* DesktopEnvironment.DesktopEnvironment;
722 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
723​
724 yield* fileSystem.makeDirectory(environment.path.dirname(environment.serverSettingsPath), {
725 recursive: true,
726 });
727 yield* fileSystem.writeFileString(
728 environment.serverSettingsPath,
729 yield* encodePersistedServerObservabilitySettingsDocument({
730 observability: {
731 otlpTracesUrl: " http://127.0.0.1:4318/v1/traces ",
732 otlpMetricsUrl: " http://127.0.0.1:4318/v1/metrics ",
733 },
734 }),
735 );
736​
737 const config = yield* configuration.resolvePrimary;
738 assert.equal(config.bootstrap.otlpTracesUrl, "http://127.0.0.1:4318/v1/traces");
739 assert.equal(config.bootstrap.otlpMetricsUrl, "http://127.0.0.1:4318/v1/metrics");
740 }),
741 ),
742 );
743​
744 it.effect("resolvePrimary omits backend observability endpoints when settings are missing", () =>
745 withHarness(
746 Effect.gen(function* () {
747 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
748 const config = yield* configuration.resolvePrimary;
749​
750 assert.isUndefined(config.bootstrap.otlpTracesUrl);
751 assert.isUndefined(config.bootstrap.otlpMetricsUrl);
752 }),
753 ),
754 );
755​
756 it.effect("logs structured context when persisted observability settings cannot be read", () =>
757 Effect.gen(function* () {
758 const fileSystem = yield* FileSystem.FileSystem;
759 const path = yield* Path.Path;
760 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
761 prefix: "t3-desktop-backend-config-test-",
762 });
763 const settingsPath = path.join(baseDir, "userdata", "settings.json");
764 const cause = PlatformError.systemError({
765 _tag: "PermissionDenied",
766 module: "FileSystem",
767 method: "readFileString",
768 pathOrDescriptor: settingsPath,
769 });
770 const messages: Array<unknown> = [];
771 const logger = Logger.make(({ message }) => {
772 messages.push(message);
773 });
774 const failingFileSystemLayer = Layer.succeed(
775 FileSystem.FileSystem,
776 FileSystem.makeNoop({
777 readFileString: () => Effect.fail(cause),
778 }),
779 );
780​
781 const config = yield* Effect.gen(function* () {
782 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
783 return yield* configuration.resolvePrimary;
784 }).pipe(
785 Effect.provide(
786 Layer.mergeAll(
787 DesktopBackendConfiguration.layer.pipe(
788 Layer.provideMerge(serverExposureLayer),
789 Layer.provideMerge(DesktopAppSettings.layerTest()),
790 Layer.provideMerge(DesktopWslServerTree.layerTest()),
791 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
792 Layer.provideMerge(makeEnvironmentLayer(baseDir)),
793 Layer.provideMerge(failingFileSystemLayer),
794 ),
795 Logger.layer([logger], { mergeWithExisting: false }),
796 ),
797 ),
798 );
799​
800 assert.isUndefined(config.bootstrap.otlpTracesUrl);
801 assert.isUndefined(config.bootstrap.otlpMetricsUrl);
802​
803 const error = messages
804 .flatMap((message) => (Array.isArray(message) ? message : [message]))
805 .find(isDesktopBackendObservabilitySettingsReadError);
806 assert.isDefined(error);
807 assert.equal(error.settingsPath, settingsPath);
808 assert.equal(error.cause, cause);
809 assert.equal(
810 error.message,
811 `Failed to read persisted backend observability settings at ${settingsPath}.`,
812 );
813 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
814 );
815​
816 it.effect("resolvePrimary captures backend output in dev so child logs can be persisted", () =>
817 Effect.gen(function* () {
818 const fileSystem = yield* FileSystem.FileSystem;
819 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
820 prefix: "t3-desktop-backend-config-test-",
821 });
822​
823 yield* Effect.gen(function* () {
824 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
825 const config = yield* configuration.resolvePrimary;
826 assert.equal(config.captureOutput, true);
827 }).pipe(
828 Effect.provide(
829 DesktopBackendConfiguration.layer.pipe(
830 Layer.provideMerge(serverExposureLayer),
831 Layer.provideMerge(DesktopAppSettings.layerTest()),
832 Layer.provideMerge(DesktopWslServerTree.layerTest()),
833 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
834 Layer.provideMerge(
835 makeEnvironmentLayer(baseDir, {
836 isPackaged: false,
837 devServerUrl: "http://127.0.0.1:5733",
838 }),
839 ),
840 ),
841 ),
842 );
843 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
844 );
845​
846 it.effect("resolveWsl preserves existing WSLENV entries when forwarding backend secrets", () =>
847 Effect.gen(function* () {
848 const fileSystem = yield* FileSystem.FileSystem;
849 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
850 prefix: "t3-desktop-backend-config-test-",
851 });
852​
853 const previousWslEnv = process.env.WSLENV;
854 const previousOpenAiKey = process.env.OPENAI_API_KEY;
855 const previousAnthropicKey = process.env.ANTHROPIC_API_KEY;
856 const previousOtlpHeaders = process.env.T3CODE_OTLP_HEADERS;
857 const previousOtlpProtocol = process.env.T3CODE_OTLP_PROTOCOL;
858 try {
859 process.env.WSLENV = "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u";
860 process.env.OPENAI_API_KEY = "openai-key";
861 process.env.ANTHROPIC_API_KEY = "anthropic-key";
862 process.env.T3CODE_OTLP_HEADERS = 'authorization="Bearer%20my-token"';
863 process.env.T3CODE_OTLP_PROTOCOL = "http/protobuf";
864​
865 yield* Effect.gen(function* () {
866 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
867 const config = yield* configuration.resolveWsl({ port: 5050, distro: null });
868​
869 assert.equal(config.executablePath, "wsl.exe");
870 assert.equal(config.bootstrap.port, 5050);
871 // Binds to 0.0.0.0 inside WSL so the backend is reachable via
872 // both wslhost-forwarded localhost and the distro's eth0 IP.
873 assert.equal(config.bootstrap.host, "0.0.0.0");
874 assert.equal(config.bootstrap.tailscaleServeEnabled, false);
875 assert.notProperty(config.bootstrap, "desktopTelemetryFd");
876 assert.notProperty(config.bootstrap, "resourceMonitorPath");
877 // httpBaseUrl uses the resolved distro IP from the test stub,
878 // not localhost — the renderer reaches the backend directly to
879 // avoid relying on wslhost forwarding.
880 assert.equal(config.httpBaseUrl.href, "http://172.27.0.99:5050/");
881 assert.equal(config.env.OPENAI_API_KEY, "openai-key");
882 assert.equal(config.env.ANTHROPIC_API_KEY, "anthropic-key");
883 assert.equal(config.env.T3CODE_OTLP_PROTOCOL, "http/protobuf");
884 // The existing WSLENV is preserved byte-for-byte (note the empty
885 // "::" segment survives — WSL ignores it, so we don't normalize
886 // it away) and ANTHROPIC_API_KEY is appended. OPENAI_API_KEY is
887 // already declared, so it isn't forwarded twice.
888 assert.equal(
889 config.env.WSLENV,
890 "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:ANTHROPIC_API_KEY:T3CODE_OTLP_HEADERS:T3CODE_OTLP_PROTOCOL",
891 );
892 }).pipe(
893 Effect.provide(
894 DesktopBackendConfiguration.layer.pipe(
895 Layer.provideMerge(serverExposureLayer),
896 Layer.provideMerge(DesktopAppSettings.layerTest()),
897 Layer.provideMerge(DesktopWslServerTree.layerTest()),
898 Layer.provideMerge(
899 DesktopWslEnvironment.layerTest({
900 isAvailable: true,
901 windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"),
902 getDistroIp: () => Option.some("172.27.0.99"),
903 }),
904 ),
905 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
906 ),
907 ),
908 );
909 } finally {
910 restoreEnv("WSLENV", previousWslEnv);
911 restoreEnv("OPENAI_API_KEY", previousOpenAiKey);
912 restoreEnv("ANTHROPIC_API_KEY", previousAnthropicKey);
913 restoreEnv("T3CODE_OTLP_HEADERS", previousOtlpHeaders);
914 restoreEnv("T3CODE_OTLP_PROTOCOL", previousOtlpProtocol);
915 }
916 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
917 );
918​
919 it.effect(
920 "resolvePrimary falls back to the Windows primary when wsl-only but WSL is unavailable",
921 () =>
922 Effect.gen(function* () {
923 const fileSystem = yield* FileSystem.FileSystem;
924 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
925 prefix: "t3-desktop-backend-config-test-",
926 });
927​
928 yield* Effect.gen(function* () {
929 const environment = yield* DesktopEnvironment.DesktopEnvironment;
930 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
931 const config = yield* configuration.resolvePrimary;
932​
933 // wsl-only is persisted but WSL is unavailable, so the primary must
934 // not spawn wsl.exe (which would loop on preflight failures while the
935 // Connections backend control is hidden). Resolve the Windows primary.
936 assert.equal(config.executablePath, process.execPath);
937 assert.equal(config.bootstrap.t3Home, environment.baseDir);
938 assert.isTrue(Option.isNone(config.preflightFailure));
939 }).pipe(
940 Effect.provide(
941 DesktopBackendConfiguration.layer.pipe(
942 Layer.provideMerge(serverExposureLayer),
943 Layer.provideMerge(
944 DesktopAppSettings.layerTest({
945 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
946 wslBackendEnabled: true,
947 wslOnly: true,
948 }),
949 ),
950 Layer.provideMerge(DesktopWslServerTree.layerTest()),
951 Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
952 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
953 ),
954 ),
955 );
956 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
957 );
958​
959 it.effect(
960 "resolvePrimary marks a removed persisted WSL distro as a fatal preflight failure",
961 () =>
962 Effect.gen(function* () {
963 const fileSystem = yield* FileSystem.FileSystem;
964 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
965 prefix: "t3-desktop-backend-config-test-",
966 });
967​
968 yield* Effect.gen(function* () {
969 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
970 const config = yield* configuration.resolvePrimary;
971 const failure = Option.getOrThrow(config.preflightFailure);
972​
973 assert.equal(config.executablePath, "wsl.exe");
974 assert.isTrue(failure.fatal);
975 assert.include(failure.reason, "Removed-Distro");
976 }).pipe(
977 Effect.provide(
978 DesktopBackendConfiguration.layer.pipe(
979 Layer.provideMerge(serverExposureLayer),
980 Layer.provideMerge(
981 DesktopAppSettings.layerTest({
982 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
983 wslBackendEnabled: true,
984 wslOnly: true,
985 wslDistro: "Removed-Distro",
986 }),
987 ),
988 Layer.provideMerge(DesktopWslServerTree.layerTest()),
989 Layer.provideMerge(
990 DesktopWslEnvironment.layerTest({
991 isAvailable: true,
992 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
993 }),
994 ),
995 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
996 ),
997 ),
998 );
999 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1000 );
1001​
1002 it.effect("resolveWsl keeps a transient distro-list failure retryable", () =>
1003 Effect.gen(function* () {
1004 const fileSystem = yield* FileSystem.FileSystem;
1005 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
1006 prefix: "t3-desktop-backend-config-test-",
1007 });
1008​
1009 yield* Effect.gen(function* () {
1010 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
1011 const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
1012 const failure = Option.getOrThrow(config.preflightFailure);
1013​
1014 assert.isFalse(failure.fatal);
1015 assert.equal(failure.retryLimit, 12);
1016 assert.include(failure.reason, "timed out");
1017 }).pipe(
1018 Effect.provide(
1019 DesktopBackendConfiguration.layer.pipe(
1020 Layer.provideMerge(serverExposureLayer),
1021 Layer.provideMerge(DesktopAppSettings.layerTest()),
1022 Layer.provideMerge(DesktopWslServerTree.layerTest()),
1023 Layer.provideMerge(
1024 DesktopWslEnvironment.layerTest({
1025 isAvailable: true,
1026 distroListError: new DesktopWslEnvironment.DesktopWslDistroListError({
1027 reason: "wsl.exe --list --verbose timed out",
1028 }),
1029 }),
1030 ),
1031 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
1032 ),
1033 ),
1034 );
1035 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1036 );
1037​
1038 it.effect("resolveWsl marks a missing packaged server entry as fatal", () =>
1039 Effect.gen(function* () {
1040 const fileSystem = yield* FileSystem.FileSystem;
1041 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
1042 prefix: "t3-desktop-backend-config-test-",
1043 });
1044​
1045 yield* Effect.gen(function* () {
1046 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
1047 const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
1048 const failure = Option.getOrThrow(config.preflightFailure);
1049​
1050 assert.isTrue(failure.fatal);
1051 assert.include(failure.reason, "missing server entry");
1052 }).pipe(
1053 Effect.provide(
1054 DesktopBackendConfiguration.layer.pipe(
1055 Layer.provideMerge(serverExposureLayer),
1056 Layer.provideMerge(DesktopAppSettings.layerTest()),
1057 Layer.provideMerge(DesktopWslServerTree.layerTest()),
1058 Layer.provideMerge(
1059 DesktopWslEnvironment.layerTest({
1060 isAvailable: true,
1061 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
1062 }),
1063 ),
1064 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
1065 ),
1066 ),
1067 );
1068 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1069 );
1070​
1071 it.effect("resolveWsl surfaces sidecar extraction failures through typed preflight", () =>
1072 Effect.gen(function* () {
1073 const fileSystem = yield* FileSystem.FileSystem;
1074 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
1075 prefix: "t3-desktop-backend-config-test-",
1076 });
1077​
1078 yield* Effect.gen(function* () {
1079 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
1080 const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
1081 const failure = Option.getOrThrow(config.preflightFailure);
1082​
1083 assert.isFalse(failure.fatal);
1084 assert.equal(failure.retryLimit, 12);
1085 assert.include(failure.reason, "could not be extracted");
1086 }).pipe(
1087 Effect.provide(
1088 DesktopBackendConfiguration.layer.pipe(
1089 Layer.provideMerge(serverExposureLayer),
1090 Layer.provideMerge(DesktopAppSettings.layerTest()),
1091 Layer.provideMerge(
1092 DesktopWslServerTree.layerTest({
1093 result: {
1094 ok: false,
1095 reason: "WSL server files could not be extracted",
1096 fatal: false,
1097 },
1098 }),
1099 ),
1100 Layer.provideMerge(
1101 DesktopWslEnvironment.layerTest({
1102 isAvailable: true,
1103 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
1104 }),
1105 ),
1106 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
1107 ),
1108 ),
1109 );
1110 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1111 );
1112​
1113 it.effect("resolveWsl marks a missing selected distro as a fatal preflight failure", () =>
1114 Effect.gen(function* () {
1115 const fileSystem = yield* FileSystem.FileSystem;
1116 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
1117 prefix: "t3-desktop-backend-config-test-",
1118 });
1119​
1120 yield* Effect.gen(function* () {
1121 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
1122 const config = yield* configuration.resolveWsl({ port: 5050, distro: "Removed-Distro" });
1123 const failure = Option.getOrThrow(config.preflightFailure);
1124​
1125 assert.isTrue(failure.fatal);
1126 assert.include(failure.reason, "Removed-Distro");
1127 }).pipe(
1128 Effect.provide(
1129 DesktopBackendConfiguration.layer.pipe(
1130 Layer.provideMerge(serverExposureLayer),
1131 Layer.provideMerge(DesktopAppSettings.layerTest()),
1132 Layer.provideMerge(DesktopWslServerTree.layerTest()),
1133 Layer.provideMerge(
1134 DesktopWslEnvironment.layerTest({
1135 isAvailable: true,
1136 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
1137 }),
1138 ),
1139 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
1140 ),
1141 ),
1142 );
1143 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1144 );
1145​
1146 it.effect("resolvePrimaryLabel reports the WSL distro when wsl-only and WSL is available", () =>
1147 Effect.gen(function* () {
1148 const fileSystem = yield* FileSystem.FileSystem;
1149 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
1150 prefix: "t3-desktop-backend-config-test-",
1151 });
1152​
1153 yield* Effect.gen(function* () {
1154 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
1155 const label = yield* configuration.resolvePrimaryLabel;
1156 assert.equal(label, "WSL (Ubuntu)");
1157 }).pipe(
1158 Effect.provide(
1159 DesktopBackendConfiguration.layer.pipe(
1160 Layer.provideMerge(serverExposureLayer),
1161 Layer.provideMerge(
1162 DesktopAppSettings.layerTest({
1163 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
1164 wslBackendEnabled: true,
1165 wslOnly: true,
1166 wslDistro: "Ubuntu",
1167 }),
1168 ),
1169 Layer.provideMerge(DesktopWslServerTree.layerTest()),
1170 Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
1171 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
1172 ),
1173 ),
1174 );
1175 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1176 );
1177​
1178 it.effect("prefers the external packaged resource monitor over the copy inside the asar", () =>
1179 Effect.gen(function* () {
1180 const fileSystem = yield* FileSystem.FileSystem;
1181 const path = yield* Path.Path;
1182 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
1183 prefix: "t3-desktop-backend-config-test-",
1184 });
1185 const resourcesPath = path.join(baseDir, "resources");
1186 const dirname = `${resourcesPath}/app.asar/apps/desktop/dist-electron`;
1187 const embeddedMonitorPath = `${resourcesPath}/app.asar/apps/desktop/prod-resources/resource-monitor/t3-resource-monitor`;
1188 const monitorPath = path.join(resourcesPath, "resource-monitor/t3-resource-monitor");
1189 yield* fileSystem.makeDirectory(
1190 `${resourcesPath}/app.asar/apps/desktop/prod-resources/resource-monitor`,
1191 { recursive: true },
1192 );
1193 yield* fileSystem.makeDirectory(`${resourcesPath}/resource-monitor`, {
1194 recursive: true,
1195 });
1196 yield* fileSystem.writeFileString(embeddedMonitorPath, "embedded");
1197 yield* fileSystem.writeFileString(monitorPath, "binary");
1198 yield* fileSystem.chmod(monitorPath, 0o755);
1199​
1200 yield* Effect.gen(function* () {
1201 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
1202 const config = yield* configuration.resolvePrimary;
1203 assert.equal(config.bootstrap.resourceMonitorPath, monitorPath);
1204 assert.equal(config.bootstrap.desktopTelemetryFd, 4);
1205 assert.equal(config.bootstrap.desktopTelemetryControlFd, 5);
1206 }).pipe(
1207 Effect.provide(
1208 DesktopBackendConfiguration.layer.pipe(
1209 Layer.provideMerge(serverExposureLayer),
1210 Layer.provideMerge(DesktopAppSettings.layerTest()),
1211 Layer.provideMerge(DesktopWslServerTree.layerTest()),
1212 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
1213 Layer.provideMerge(
1214 makeEnvironmentLayer(baseDir, {
1215 appPath: `${resourcesPath}/app.asar`,
1216 dirname,
1217 isPackaged: true,
1218 resourcesPath,
1219 }),
1220 ),
1221 ),
1222 ),
1223 );
1224 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1225 );
1226​
1227 it.effect("prefers the release resource monitor when both development builds exist", () =>
1228 Effect.gen(function* () {
1229 const fileSystem = yield* FileSystem.FileSystem;
1230 const path = yield* Path.Path;
1231 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
1232 prefix: "t3-desktop-backend-config-test-",
1233 });
1234 const dirname = path.join(baseDir, "apps/desktop/src");
1235 const releaseMonitorPath = path.join(
1236 baseDir,
1237 "native/resource-monitor/target/release/t3-resource-monitor",
1238 );
1239 const debugMonitorPath = path.join(
1240 baseDir,
1241 "native/resource-monitor/target/debug/t3-resource-monitor",
1242 );
1243 yield* fileSystem.makeDirectory(path.dirname(releaseMonitorPath), { recursive: true });
1244 yield* fileSystem.makeDirectory(path.dirname(debugMonitorPath), { recursive: true });
1245 yield* fileSystem.writeFileString(releaseMonitorPath, "release");
1246 yield* fileSystem.writeFileString(debugMonitorPath, "debug");
1247​
1248 yield* Effect.gen(function* () {
1249 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
1250 const config = yield* configuration.resolvePrimary;
1251 assert.equal(config.bootstrap.resourceMonitorPath, releaseMonitorPath);
1252 }).pipe(
1253 Effect.provide(
1254 DesktopBackendConfiguration.layer.pipe(
1255 Layer.provideMerge(serverExposureLayer),
1256 Layer.provideMerge(DesktopAppSettings.layerTest()),
1257 Layer.provideMerge(DesktopWslServerTree.layerTest()),
1258 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
1259 Layer.provideMerge(
1260 makeEnvironmentLayer(baseDir, {
1261 dirname,
1262 devServerUrl: "http://127.0.0.1:5733",
1263 isPackaged: false,
1264 }),
1265 ),
1266 ),
1267 ),
1268 );
1269 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1270 );
1271​
1272 it.effect("resolvePrimaryLabel reports the local environment on non-Windows platforms", () =>
1273 withHarness(
1274 Effect.gen(function* () {
1275 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
1276 const label = yield* configuration.resolvePrimaryLabel;
1277 assert.equal(label, "Local environment");
1278 }),
1279 ),
1280 );
1281​
1282 it.effect("resolvePrimaryLabel reports Windows when wsl-only but WSL is unavailable", () =>
1283 Effect.gen(function* () {
1284 const fileSystem = yield* FileSystem.FileSystem;
1285 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
1286 prefix: "t3-desktop-backend-config-test-",
1287 });
1288​
1289 yield* Effect.gen(function* () {
1290 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
1291 // Mirrors the resolvePrimary fall-back: the label must follow the
1292 // backend that actually resolves, not the persisted preference, so the
1293 // env switcher can't show "WSL" for a Windows backend.
1294 const label = yield* configuration.resolvePrimaryLabel;
1295 assert.equal(label, "Windows");
1296 }).pipe(
1297 Effect.provide(
1298 DesktopBackendConfiguration.layer.pipe(
1299 Layer.provideMerge(serverExposureLayer),
1300 Layer.provideMerge(
1301 DesktopAppSettings.layerTest({
1302 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
1303 wslBackendEnabled: true,
1304 wslOnly: true,
1305 wslDistro: "Ubuntu",
1306 }),
1307 ),
1308 Layer.provideMerge(DesktopWslServerTree.layerTest()),
1309 Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
1310 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
1311 ),
1312 ),
1313 );
1314 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1315 );
1316​
1317 it("resolvePrimaryLabel is runSync-safe against the real WSL availability probe", async () => {
1318 // getLocalEnvironmentBootstraps is a sync IPC method: it resolves the
1319 // primary instance's lazy label through Effect.runSync. The label chains
1320 // to wslEnvironment.isAvailable, whose real layer probes the filesystem.
1321 // That probe must run once at layer build and expose a resolved value, not
1322 // a live async effect — otherwise runSync throws in the handler. Build the
1323 // real WSL layer (not the sync test stub) and resolve the label with a
1324 // top-level runSync, exactly as the handler does.
1325 // 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.
1326 const runtime = ManagedRuntime.make(
1327 DesktopBackendConfiguration.layer.pipe(
1328 Layer.provideMerge(serverExposureLayer),
1329 Layer.provideMerge(DesktopAppSettings.layerTest()),
1330 Layer.provideMerge(DesktopWslServerTree.layerTest()),
1331 Layer.provideMerge(DesktopWslEnvironment.layer),
1332 // isAvailable on win32 only touches the filesystem, never the spawner,
1333 // so a die-stub is enough to satisfy the layer's deps.
1334 Layer.provideMerge(
1335 Layer.succeed(
1336 ChildProcessSpawner.ChildProcessSpawner,
1337 ChildProcessSpawner.make(() =>
1338 Effect.die("spawner should not be used while probing WSL availability"),
1339 ),
1340 ),
1341 ),
1342 Layer.provideMerge(makeEnvironmentLayer("/tmp/t3-wsl-isavailable", { platform: "win32" })),
1343 Layer.provide(NodeServices.layer),
1344 ),
1345 );
1346 try {
1347 const configuration = await runtime.runPromise(
1348 DesktopBackendConfiguration.DesktopBackendConfiguration,
1349 );
1350 // oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- Same reason: this is the synchronous resolution the IPC handler performs.
1351 const label = Effect.runSync(configuration.resolvePrimaryLabel);
1352 assert.equal(typeof label, "string");
1353 } finally {
1354 await runtime.dispose();
1356 });
1357});