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