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

DesktopBackendConfiguration.test.ts

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