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

DesktopBackendConfiguration.test.ts

1,350 lines55.0 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, so the preflight must not
403 // go looking for one in the distro.
404 ensureNodePty: () => {
405 throw new Error("the staged runtime must not probe for Node");
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 try {
857 process.env.WSLENV = "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u";
858 process.env.OPENAI_API_KEY = "openai-key";
859 process.env.ANTHROPIC_API_KEY = "anthropic-key";
860​
861 yield* Effect.gen(function* () {
862 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
863 const config = yield* configuration.resolveWsl({ port: 5050, distro: null });
864​
865 assert.equal(config.executablePath, "wsl.exe");
866 assert.equal(config.bootstrap.port, 5050);
867 // Binds to 0.0.0.0 inside WSL so the backend is reachable via
868 // both wslhost-forwarded localhost and the distro's eth0 IP.
869 assert.equal(config.bootstrap.host, "0.0.0.0");
870 assert.equal(config.bootstrap.tailscaleServeEnabled, false);
871 assert.notProperty(config.bootstrap, "desktopTelemetryFd");
872 assert.notProperty(config.bootstrap, "resourceMonitorPath");
873 // httpBaseUrl uses the resolved distro IP from the test stub,
874 // not localhost — the renderer reaches the backend directly to
875 // avoid relying on wslhost forwarding.
876 assert.equal(config.httpBaseUrl.href, "http://172.27.0.99:5050/");
877 assert.equal(config.env.OPENAI_API_KEY, "openai-key");
878 assert.equal(config.env.ANTHROPIC_API_KEY, "anthropic-key");
879 // The existing WSLENV is preserved byte-for-byte (note the empty
880 // "::" segment survives — WSL ignores it, so we don't normalize
881 // it away) and ANTHROPIC_API_KEY is appended. OPENAI_API_KEY is
882 // already declared, so it isn't forwarded twice.
883 assert.equal(
884 config.env.WSLENV,
885 "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:ANTHROPIC_API_KEY",
886 );
887 }).pipe(
888 Effect.provide(
889 DesktopBackendConfiguration.layer.pipe(
890 Layer.provideMerge(serverExposureLayer),
891 Layer.provideMerge(DesktopAppSettings.layerTest()),
892 Layer.provideMerge(DesktopWslServerTree.layerTest()),
893 Layer.provideMerge(
894 DesktopWslEnvironment.layerTest({
895 isAvailable: true,
896 windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"),
897 getDistroIp: () => Option.some("172.27.0.99"),
898 }),
899 ),
900 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
901 ),
902 ),
903 );
904 } finally {
905 restoreEnv("WSLENV", previousWslEnv);
906 restoreEnv("OPENAI_API_KEY", previousOpenAiKey);
907 restoreEnv("ANTHROPIC_API_KEY", previousAnthropicKey);
908 }
909 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
910 );
911​
912 it.effect(
913 "resolvePrimary falls back to the Windows primary when wsl-only but WSL is unavailable",
914 () =>
915 Effect.gen(function* () {
916 const fileSystem = yield* FileSystem.FileSystem;
917 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
918 prefix: "t3-desktop-backend-config-test-",
919 });
920​
921 yield* Effect.gen(function* () {
922 const environment = yield* DesktopEnvironment.DesktopEnvironment;
923 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
924 const config = yield* configuration.resolvePrimary;
925​
926 // wsl-only is persisted but WSL is unavailable, so the primary must
927 // not spawn wsl.exe (which would loop on preflight failures while the
928 // Connections backend control is hidden). Resolve the Windows primary.
929 assert.equal(config.executablePath, process.execPath);
930 assert.equal(config.bootstrap.t3Home, environment.baseDir);
931 assert.isTrue(Option.isNone(config.preflightFailure));
932 }).pipe(
933 Effect.provide(
934 DesktopBackendConfiguration.layer.pipe(
935 Layer.provideMerge(serverExposureLayer),
936 Layer.provideMerge(
937 DesktopAppSettings.layerTest({
938 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
939 wslBackendEnabled: true,
940 wslOnly: true,
941 }),
942 ),
943 Layer.provideMerge(DesktopWslServerTree.layerTest()),
944 Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
945 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
946 ),
947 ),
948 );
949 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
950 );
951​
952 it.effect(
953 "resolvePrimary marks a removed persisted WSL distro as a fatal preflight failure",
954 () =>
955 Effect.gen(function* () {
956 const fileSystem = yield* FileSystem.FileSystem;
957 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
958 prefix: "t3-desktop-backend-config-test-",
959 });
960​
961 yield* Effect.gen(function* () {
962 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
963 const config = yield* configuration.resolvePrimary;
964 const failure = Option.getOrThrow(config.preflightFailure);
965​
966 assert.equal(config.executablePath, "wsl.exe");
967 assert.isTrue(failure.fatal);
968 assert.include(failure.reason, "Removed-Distro");
969 }).pipe(
970 Effect.provide(
971 DesktopBackendConfiguration.layer.pipe(
972 Layer.provideMerge(serverExposureLayer),
973 Layer.provideMerge(
974 DesktopAppSettings.layerTest({
975 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
976 wslBackendEnabled: true,
977 wslOnly: true,
978 wslDistro: "Removed-Distro",
979 }),
980 ),
981 Layer.provideMerge(DesktopWslServerTree.layerTest()),
982 Layer.provideMerge(
983 DesktopWslEnvironment.layerTest({
984 isAvailable: true,
985 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
986 }),
987 ),
988 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
989 ),
990 ),
991 );
992 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
993 );
994​
995 it.effect("resolveWsl keeps a transient distro-list failure retryable", () =>
996 Effect.gen(function* () {
997 const fileSystem = yield* FileSystem.FileSystem;
998 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
999 prefix: "t3-desktop-backend-config-test-",
1000 });
1001​
1002 yield* Effect.gen(function* () {
1003 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
1004 const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
1005 const failure = Option.getOrThrow(config.preflightFailure);
1006​
1007 assert.isFalse(failure.fatal);
1008 assert.equal(failure.retryLimit, 12);
1009 assert.include(failure.reason, "timed out");
1010 }).pipe(
1011 Effect.provide(
1012 DesktopBackendConfiguration.layer.pipe(
1013 Layer.provideMerge(serverExposureLayer),
1014 Layer.provideMerge(DesktopAppSettings.layerTest()),
1015 Layer.provideMerge(DesktopWslServerTree.layerTest()),
1016 Layer.provideMerge(
1017 DesktopWslEnvironment.layerTest({
1018 isAvailable: true,
1019 distroListError: new DesktopWslEnvironment.DesktopWslDistroListError({
1020 reason: "wsl.exe --list --verbose timed out",
1021 }),
1022 }),
1023 ),
1024 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
1025 ),
1026 ),
1027 );
1028 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1029 );
1030​
1031 it.effect("resolveWsl marks a missing packaged server entry as fatal", () =>
1032 Effect.gen(function* () {
1033 const fileSystem = yield* FileSystem.FileSystem;
1034 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
1035 prefix: "t3-desktop-backend-config-test-",
1036 });
1037​
1038 yield* Effect.gen(function* () {
1039 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
1040 const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
1041 const failure = Option.getOrThrow(config.preflightFailure);
1042​
1043 assert.isTrue(failure.fatal);
1044 assert.include(failure.reason, "missing server entry");
1045 }).pipe(
1046 Effect.provide(
1047 DesktopBackendConfiguration.layer.pipe(
1048 Layer.provideMerge(serverExposureLayer),
1049 Layer.provideMerge(DesktopAppSettings.layerTest()),
1050 Layer.provideMerge(DesktopWslServerTree.layerTest()),
1051 Layer.provideMerge(
1052 DesktopWslEnvironment.layerTest({
1053 isAvailable: true,
1054 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
1055 }),
1056 ),
1057 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
1058 ),
1059 ),
1060 );
1061 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1062 );
1063​
1064 it.effect("resolveWsl surfaces sidecar extraction failures through typed preflight", () =>
1065 Effect.gen(function* () {
1066 const fileSystem = yield* FileSystem.FileSystem;
1067 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
1068 prefix: "t3-desktop-backend-config-test-",
1069 });
1070​
1071 yield* Effect.gen(function* () {
1072 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
1073 const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
1074 const failure = Option.getOrThrow(config.preflightFailure);
1075​
1076 assert.isFalse(failure.fatal);
1077 assert.equal(failure.retryLimit, 12);
1078 assert.include(failure.reason, "could not be extracted");
1079 }).pipe(
1080 Effect.provide(
1081 DesktopBackendConfiguration.layer.pipe(
1082 Layer.provideMerge(serverExposureLayer),
1083 Layer.provideMerge(DesktopAppSettings.layerTest()),
1084 Layer.provideMerge(
1085 DesktopWslServerTree.layerTest({
1086 result: {
1087 ok: false,
1088 reason: "WSL server files could not be extracted",
1089 fatal: false,
1090 },
1091 }),
1092 ),
1093 Layer.provideMerge(
1094 DesktopWslEnvironment.layerTest({
1095 isAvailable: true,
1096 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
1097 }),
1098 ),
1099 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
1100 ),
1101 ),
1102 );
1103 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1104 );
1105​
1106 it.effect("resolveWsl marks a missing selected distro as a fatal preflight failure", () =>
1107 Effect.gen(function* () {
1108 const fileSystem = yield* FileSystem.FileSystem;
1109 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
1110 prefix: "t3-desktop-backend-config-test-",
1111 });
1112​
1113 yield* Effect.gen(function* () {
1114 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
1115 const config = yield* configuration.resolveWsl({ port: 5050, distro: "Removed-Distro" });
1116 const failure = Option.getOrThrow(config.preflightFailure);
1117​
1118 assert.isTrue(failure.fatal);
1119 assert.include(failure.reason, "Removed-Distro");
1120 }).pipe(
1121 Effect.provide(
1122 DesktopBackendConfiguration.layer.pipe(
1123 Layer.provideMerge(serverExposureLayer),
1124 Layer.provideMerge(DesktopAppSettings.layerTest()),
1125 Layer.provideMerge(DesktopWslServerTree.layerTest()),
1126 Layer.provideMerge(
1127 DesktopWslEnvironment.layerTest({
1128 isAvailable: true,
1129 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
1130 }),
1131 ),
1132 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
1133 ),
1134 ),
1135 );
1136 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1137 );
1138​
1139 it.effect("resolvePrimaryLabel reports the WSL distro when wsl-only and WSL is available", () =>
1140 Effect.gen(function* () {
1141 const fileSystem = yield* FileSystem.FileSystem;
1142 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
1143 prefix: "t3-desktop-backend-config-test-",
1144 });
1145​
1146 yield* Effect.gen(function* () {
1147 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
1148 const label = yield* configuration.resolvePrimaryLabel;
1149 assert.equal(label, "WSL (Ubuntu)");
1150 }).pipe(
1151 Effect.provide(
1152 DesktopBackendConfiguration.layer.pipe(
1153 Layer.provideMerge(serverExposureLayer),
1154 Layer.provideMerge(
1155 DesktopAppSettings.layerTest({
1156 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
1157 wslBackendEnabled: true,
1158 wslOnly: true,
1159 wslDistro: "Ubuntu",
1160 }),
1161 ),
1162 Layer.provideMerge(DesktopWslServerTree.layerTest()),
1163 Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
1164 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
1165 ),
1166 ),
1167 );
1168 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1169 );
1170​
1171 it.effect("prefers the external packaged resource monitor over the copy inside the asar", () =>
1172 Effect.gen(function* () {
1173 const fileSystem = yield* FileSystem.FileSystem;
1174 const path = yield* Path.Path;
1175 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
1176 prefix: "t3-desktop-backend-config-test-",
1177 });
1178 const resourcesPath = path.join(baseDir, "resources");
1179 const dirname = `${resourcesPath}/app.asar/apps/desktop/dist-electron`;
1180 const embeddedMonitorPath = `${resourcesPath}/app.asar/apps/desktop/prod-resources/resource-monitor/t3-resource-monitor`;
1181 const monitorPath = path.join(resourcesPath, "resource-monitor/t3-resource-monitor");
1182 yield* fileSystem.makeDirectory(
1183 `${resourcesPath}/app.asar/apps/desktop/prod-resources/resource-monitor`,
1184 { recursive: true },
1185 );
1186 yield* fileSystem.makeDirectory(`${resourcesPath}/resource-monitor`, {
1187 recursive: true,
1188 });
1189 yield* fileSystem.writeFileString(embeddedMonitorPath, "embedded");
1190 yield* fileSystem.writeFileString(monitorPath, "binary");
1191 yield* fileSystem.chmod(monitorPath, 0o755);
1192​
1193 yield* Effect.gen(function* () {
1194 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
1195 const config = yield* configuration.resolvePrimary;
1196 assert.equal(config.bootstrap.resourceMonitorPath, monitorPath);
1197 assert.equal(config.bootstrap.desktopTelemetryFd, 4);
1198 assert.equal(config.bootstrap.desktopTelemetryControlFd, 5);
1199 }).pipe(
1200 Effect.provide(
1201 DesktopBackendConfiguration.layer.pipe(
1202 Layer.provideMerge(serverExposureLayer),
1203 Layer.provideMerge(DesktopAppSettings.layerTest()),
1204 Layer.provideMerge(DesktopWslServerTree.layerTest()),
1205 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
1206 Layer.provideMerge(
1207 makeEnvironmentLayer(baseDir, {
1208 appPath: `${resourcesPath}/app.asar`,
1209 dirname,
1210 isPackaged: true,
1211 resourcesPath,
1212 }),
1213 ),
1214 ),
1215 ),
1216 );
1217 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1218 );
1219​
1220 it.effect("prefers the release resource monitor when both development builds exist", () =>
1221 Effect.gen(function* () {
1222 const fileSystem = yield* FileSystem.FileSystem;
1223 const path = yield* Path.Path;
1224 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
1225 prefix: "t3-desktop-backend-config-test-",
1226 });
1227 const dirname = path.join(baseDir, "apps/desktop/src");
1228 const releaseMonitorPath = path.join(
1229 baseDir,
1230 "native/resource-monitor/target/release/t3-resource-monitor",
1231 );
1232 const debugMonitorPath = path.join(
1233 baseDir,
1234 "native/resource-monitor/target/debug/t3-resource-monitor",
1235 );
1236 yield* fileSystem.makeDirectory(path.dirname(releaseMonitorPath), { recursive: true });
1237 yield* fileSystem.makeDirectory(path.dirname(debugMonitorPath), { recursive: true });
1238 yield* fileSystem.writeFileString(releaseMonitorPath, "release");
1239 yield* fileSystem.writeFileString(debugMonitorPath, "debug");
1240​
1241 yield* Effect.gen(function* () {
1242 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
1243 const config = yield* configuration.resolvePrimary;
1244 assert.equal(config.bootstrap.resourceMonitorPath, releaseMonitorPath);
1245 }).pipe(
1246 Effect.provide(
1247 DesktopBackendConfiguration.layer.pipe(
1248 Layer.provideMerge(serverExposureLayer),
1249 Layer.provideMerge(DesktopAppSettings.layerTest()),
1250 Layer.provideMerge(DesktopWslServerTree.layerTest()),
1251 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
1252 Layer.provideMerge(
1253 makeEnvironmentLayer(baseDir, {
1254 dirname,
1255 devServerUrl: "http://127.0.0.1:5733",
1256 isPackaged: false,
1257 }),
1258 ),
1259 ),
1260 ),
1261 );
1262 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1263 );
1264​
1265 it.effect("resolvePrimaryLabel reports the local environment on non-Windows platforms", () =>
1266 withHarness(
1267 Effect.gen(function* () {
1268 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
1269 const label = yield* configuration.resolvePrimaryLabel;
1270 assert.equal(label, "Local environment");
1271 }),
1272 ),
1273 );
1274​
1275 it.effect("resolvePrimaryLabel reports Windows when wsl-only but WSL is unavailable", () =>
1276 Effect.gen(function* () {
1277 const fileSystem = yield* FileSystem.FileSystem;
1278 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
1279 prefix: "t3-desktop-backend-config-test-",
1280 });
1281​
1282 yield* Effect.gen(function* () {
1283 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
1284 // Mirrors the resolvePrimary fall-back: the label must follow the
1285 // backend that actually resolves, not the persisted preference, so the
1286 // env switcher can't show "WSL" for a Windows backend.
1287 const label = yield* configuration.resolvePrimaryLabel;
1288 assert.equal(label, "Windows");
1289 }).pipe(
1290 Effect.provide(
1291 DesktopBackendConfiguration.layer.pipe(
1292 Layer.provideMerge(serverExposureLayer),
1293 Layer.provideMerge(
1294 DesktopAppSettings.layerTest({
1295 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
1296 wslBackendEnabled: true,
1297 wslOnly: true,
1298 wslDistro: "Ubuntu",
1299 }),
1300 ),
1301 Layer.provideMerge(DesktopWslServerTree.layerTest()),
1302 Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
1303 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
1304 ),
1305 ),
1306 );
1307 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
1308 );
1309​
1310 it("resolvePrimaryLabel is runSync-safe against the real WSL availability probe", async () => {
1311 // getLocalEnvironmentBootstraps is a sync IPC method: it resolves the
1312 // primary instance's lazy label through Effect.runSync. The label chains
1313 // to wslEnvironment.isAvailable, whose real layer probes the filesystem.
1314 // That probe must run once at layer build and expose a resolved value, not
1315 // a live async effect — otherwise runSync throws in the handler. Build the
1316 // real WSL layer (not the sync test stub) and resolve the label with a
1317 // top-level runSync, exactly as the handler does.
1318 // 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.
1319 const runtime = ManagedRuntime.make(
1320 DesktopBackendConfiguration.layer.pipe(
1321 Layer.provideMerge(serverExposureLayer),
1322 Layer.provideMerge(DesktopAppSettings.layerTest()),
1323 Layer.provideMerge(DesktopWslServerTree.layerTest()),
1324 Layer.provideMerge(DesktopWslEnvironment.layer),
1325 // isAvailable on win32 only touches the filesystem, never the spawner,
1326 // so a die-stub is enough to satisfy the layer's deps.
1327 Layer.provideMerge(
1328 Layer.succeed(
1329 ChildProcessSpawner.ChildProcessSpawner,
1330 ChildProcessSpawner.make(() =>
1331 Effect.die("spawner should not be used while probing WSL availability"),
1332 ),
1333 ),
1334 ),
1335 Layer.provideMerge(makeEnvironmentLayer("/tmp/t3-wsl-isavailable", { platform: "win32" })),
1336 Layer.provide(NodeServices.layer),
1337 ),
1338 );
1339 try {
1340 const configuration = await runtime.runPromise(
1341 DesktopBackendConfiguration.DesktopBackendConfiguration,
1342 );
1343 // oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- Same reason: this is the synchronous resolution the IPC handler performs.
1344 const label = Effect.runSync(configuration.resolvePrimaryLabel);
1345 assert.equal(typeof label, "string");
1346 } finally {
1347 await runtime.dispose();
1349 });
1350});