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

DesktopBackendConfiguration.test.ts

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