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

DesktopBackendConfiguration.test.ts

799 lines32.6 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";
20​
21const PersistedServerObservabilitySettingsDocument = Schema.Struct({
22 observability: Schema.Struct({
23 otlpTracesUrl: Schema.String,
24 otlpMetricsUrl: Schema.String,
25 }),
26});
27​
28const encodePersistedServerObservabilitySettingsDocument = Schema.encodeEffect(
29 Schema.fromJsonString(PersistedServerObservabilitySettingsDocument),
30);
31​
32const isDesktopBackendObservabilitySettingsReadError = Schema.is(
33 DesktopBackendConfiguration.DesktopBackendObservabilitySettingsReadError,
34);
35​
36const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExposure, {
37 getState: Effect.die("unexpected getState"),
38 backendConfig: Effect.succeed({
39 port: 4888,
40 bindHost: "0.0.0.0",
41 httpBaseUrl: new URL("http://127.0.0.1:4888"),
42 tailscaleServeEnabled: true,
43 tailscaleServePort: 8443,
44 }),
45 configureFromSettings: () => Effect.die("unexpected configureFromSettings"),
46 setMode: () => Effect.die("unexpected setMode"),
47 setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
48 getAdvertisedEndpoints: Effect.succeed([]),
49} satisfies DesktopServerExposure.DesktopServerExposure["Service"]);
50​
51function makeEnvironmentLayer(
52 baseDir: string,
53 options?: {
54 readonly appPath?: string;
55 readonly isPackaged?: boolean;
56 readonly devServerUrl?: string;
57 readonly platform?: NodeJS.Platform;
58 readonly resourcesPath?: string;
59 },
60) {
61 return DesktopEnvironment.layer({
62 dirname: "/repo/apps/desktop/src",
63 homeDirectory: baseDir,
64 platform: options?.platform ?? "darwin",
65 processArch: "x64",
66 appVersion: "1.2.3",
67 appPath: options?.appPath ?? "/repo",
68 isPackaged: options?.isPackaged ?? true,
69 resourcesPath: options?.resourcesPath ?? "/missing/resources",
70 runningUnderArm64Translation: false,
71 }).pipe(
72 Layer.provide(
73 Layer.mergeAll(
74 NodeServices.layer,
75 DesktopConfig.layerTest({
76 T3CODE_HOME: baseDir,
77 T3CODE_PORT: "9999",
78 T3CODE_MODE: "desktop",
79 T3CODE_DESKTOP_LAN_HOST: "192.168.1.50",
80 VITE_DEV_SERVER_URL: options?.devServerUrl,
81 }),
82 ),
83 ),
84 );
86​
87const restoreEnv = (name: string, value: string | undefined) => {
88 if (value === undefined) {
89 delete process.env[name];
90 } else {
91 process.env[name] = value;
92 }
93};
94​
95const withHarness = <A, E, R>(
96 effect: Effect.Effect<
97 A,
98 E,
99 | R
100 | DesktopEnvironment.DesktopEnvironment
101 | FileSystem.FileSystem
102 | DesktopBackendConfiguration.DesktopBackendConfiguration
103 >,
104) =>
105 Effect.gen(function* () {
106 const fileSystem = yield* FileSystem.FileSystem;
107 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
108 prefix: "t3-desktop-backend-config-test-",
109 });
110​
111 return yield* effect.pipe(
112 Effect.provide(
113 DesktopBackendConfiguration.layer.pipe(
114 Layer.provideMerge(serverExposureLayer),
115 Layer.provideMerge(DesktopAppSettings.layerTest()),
116 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
117 Layer.provideMerge(makeEnvironmentLayer(baseDir)),
118 ),
119 ),
120 );
121 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
122​
123describe("DesktopBackendConfiguration", () => {
124 it.effect("resolvePrimary produces a stable scoped bootstrap token", () =>
125 withHarness(
126 Effect.gen(function* () {
127 const environment = yield* DesktopEnvironment.DesktopEnvironment;
128 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
129​
130 const first = yield* configuration.resolvePrimary;
131 const second = yield* configuration.resolvePrimary;
132​
133 assert.equal(first.executablePath, process.execPath);
134 assert.equal(first.entryPath, environment.backendEntryPath);
135 assert.equal(first.cwd, environment.backendCwd);
136 assert.equal(first.captureOutput, true);
137 assert.equal(first.env.ELECTRON_RUN_AS_NODE, "1");
138 assert.isUndefined(first.env.T3CODE_PORT);
139 assert.isUndefined(first.env.T3CODE_MODE);
140 assert.isUndefined(first.env.T3CODE_DESKTOP_LAN_HOST);
141​
142 assert.equal(first.bootstrap.mode, "desktop");
143 assert.equal(first.bootstrap.noBrowser, true);
144 assert.equal(first.bootstrap.port, 4888);
145 assert.equal(first.bootstrap.host, "0.0.0.0");
146 assert.equal(first.bootstrap.t3Home, environment.baseDir);
147 assert.equal(first.bootstrap.tailscaleServeEnabled, true);
148 assert.equal(first.bootstrap.tailscaleServePort, 8443);
149 assert.match(first.bootstrap.desktopBootstrapToken, /^[0-9a-f]{48}$/i);
150 assert.equal(second.bootstrap.desktopBootstrapToken, first.bootstrap.desktopBootstrapToken);
151 }),
152 ),
153 );
154​
155 it.effect("resolveWsl reuses the primary's bootstrap token", () =>
156 withHarness(
157 Effect.gen(function* () {
158 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
159​
160 const primary = yield* configuration.resolvePrimary;
161 const wsl = yield* configuration.resolveWsl({ port: 5000, distro: null });
162​
163 assert.equal(wsl.bootstrap.desktopBootstrapToken, primary.bootstrap.desktopBootstrapToken);
164 }),
165 ),
166 );
167​
168 it.effect("resolveWsl pins a default-tracking run to the concrete default distro", () =>
169 Effect.gen(function* () {
170 const fileSystem = yield* FileSystem.FileSystem;
171 const path = yield* Path.Path;
172 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
173 prefix: "t3-desktop-backend-config-test-",
174 });
175 const entryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");
176 yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
177 yield* fileSystem.writeFileString(entryPath, "");
178​
179 const observedDistros: Array<string | null> = [];
180 const config = yield* Effect.gen(function* () {
181 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
182 return yield* configuration.resolveWsl({ port: 5000, distro: null });
183 }).pipe(
184 Effect.provide(
185 DesktopBackendConfiguration.layer.pipe(
186 Layer.provideMerge(serverExposureLayer),
187 Layer.provideMerge(DesktopAppSettings.layerTest()),
188 Layer.provideMerge(
189 DesktopWslEnvironment.layerTest({
190 isAvailable: true,
191 distros: [
192 { name: "Debian", isDefault: false, version: 2 },
193 { name: "Ubuntu", isDefault: true, version: 2 },
194 ],
195 windowsToWslPath: (distro) => {
196 observedDistros.push(distro);
197 return Option.some("/repo/apps/server/dist/bin.mjs");
198 },
199 ensureNodePty: (distro) => {
200 observedDistros.push(distro);
201 return { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" };
202 },
203 getDistroIp: (distro) => {
204 observedDistros.push(distro);
205 return Option.some("172.27.0.99");
206 },
207 }),
208 ),
209 Layer.provideMerge(
210 makeEnvironmentLayer(baseDir, {
211 appPath: baseDir,
212 platform: "win32",
213 resourcesPath: baseDir,
214 }),
215 ),
216 ),
217 ),
218 );
219​
220 assert.equal(config.runningDistro, "Ubuntu");
221 assert.deepEqual(config.args.slice(0, 2), ["-d", "Ubuntu"]);
222 assert.deepEqual(observedDistros, ["Ubuntu", "Ubuntu", "Ubuntu"]);
223 assert.isTrue(Option.isNone(config.preflightFailure));
224 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
225 );
226​
227 it.effect(
228 "resolveWsl preserves inherited PATH with quote-sensitive values as separate args",
229 () =>
230 Effect.gen(function* () {
231 const fileSystem = yield* FileSystem.FileSystem;
232 const path = yield* Path.Path;
233 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
234 prefix: "t3-desktop-backend-config-test-",
235 });
236 const entryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");
237 yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
238 yield* fileSystem.writeFileString(entryPath, "");
239​
240 const nodePath = "/home/test user's/.nvm/versions/node/v22.0.0/bin/node";
241 const linuxEntryPath = "/tmp/t3 code's launch/entry file.mjs";
242 const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
243 const devServerUrl = "http://127.0.0.1:5733/dev%20assets/?label=hello%20world";
244 const config = yield* Effect.gen(function* () {
245 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
246 return yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
247 }).pipe(
248 Effect.provide(
249 DesktopBackendConfiguration.layer.pipe(
250 Layer.provideMerge(serverExposureLayer),
251 Layer.provideMerge(DesktopAppSettings.layerTest()),
252 Layer.provideMerge(
253 DesktopWslEnvironment.layerTest({
254 isAvailable: true,
255 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
256 windowsToWslPath: () => Option.some(linuxEntryPath),
257 ensureNodePty: () => ({ ok: true, nodePath, resolvedPath }),
258 getDistroIp: () => Option.some("172.27.0.99"),
259 }),
260 ),
261 Layer.provideMerge(
262 makeEnvironmentLayer(baseDir, {
263 appPath: baseDir,
264 devServerUrl,
265 isPackaged: true,
266 platform: "win32",
267 resourcesPath: baseDir,
268 }),
269 ),
270 ),
271 ),
272 );
273​
274 assert.equal(config.bootstrapDelivery, "stdin");
275 assert.deepEqual(config.args, [
276 "-d",
277 "Ubuntu",
278 "--exec",
279 "env",
280 "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",
281 nodePath,
282 linuxEntryPath,
283 "--bootstrap-fd",
284 "0",
285 "--dev-url",
286 devServerUrl,
287 ]);
288 assert.notInclude(config.args, "bash");
289 assert.notInclude(config.args, "/bin/sh");
290 assert.notInclude(config.args, "-c");
291 assert.isTrue(Option.isNone(config.preflightFailure));
292 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
293 );
294​
295 it.effect("resolvePrimary and resolveWsl share one token under concurrent resolution", () =>
296 withHarness(
297 Effect.gen(function* () {
298 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
299​
300 // Resolve both before any token is cached, concurrently, so the
301 // generate step (a yield point) can interleave. The atomic
302 // get-or-create must still hand both the same token; a non-atomic
303 // Ref would let each generate its own and break the shared-token
304 // invariant.
305 const [primary, wsl] = yield* Effect.all(
306 [configuration.resolvePrimary, configuration.resolveWsl({ port: 5000, distro: null })],
307 { concurrency: "unbounded" },
308 );
309​
310 assert.equal(wsl.bootstrap.desktopBootstrapToken, primary.bootstrap.desktopBootstrapToken);
311 }),
312 ),
313 );
314​
315 it.effect("resolvePrimary surfaces persisted backend observability endpoints", () =>
316 withHarness(
317 Effect.gen(function* () {
318 const fileSystem = yield* FileSystem.FileSystem;
319 const environment = yield* DesktopEnvironment.DesktopEnvironment;
320 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
321​
322 yield* fileSystem.makeDirectory(environment.path.dirname(environment.serverSettingsPath), {
323 recursive: true,
324 });
325 yield* fileSystem.writeFileString(
326 environment.serverSettingsPath,
327 yield* encodePersistedServerObservabilitySettingsDocument({
328 observability: {
329 otlpTracesUrl: " http://127.0.0.1:4318/v1/traces ",
330 otlpMetricsUrl: " http://127.0.0.1:4318/v1/metrics ",
331 },
332 }),
333 );
334​
335 const config = yield* configuration.resolvePrimary;
336 assert.equal(config.bootstrap.otlpTracesUrl, "http://127.0.0.1:4318/v1/traces");
337 assert.equal(config.bootstrap.otlpMetricsUrl, "http://127.0.0.1:4318/v1/metrics");
338 }),
339 ),
340 );
341​
342 it.effect("resolvePrimary omits backend observability endpoints when settings are missing", () =>
343 withHarness(
344 Effect.gen(function* () {
345 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
346 const config = yield* configuration.resolvePrimary;
347​
348 assert.isUndefined(config.bootstrap.otlpTracesUrl);
349 assert.isUndefined(config.bootstrap.otlpMetricsUrl);
350 }),
351 ),
352 );
353​
354 it.effect("logs structured context when persisted observability settings cannot be read", () =>
355 Effect.gen(function* () {
356 const fileSystem = yield* FileSystem.FileSystem;
357 const path = yield* Path.Path;
358 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
359 prefix: "t3-desktop-backend-config-test-",
360 });
361 const settingsPath = path.join(baseDir, "userdata", "settings.json");
362 const cause = PlatformError.systemError({
363 _tag: "PermissionDenied",
364 module: "FileSystem",
365 method: "readFileString",
366 pathOrDescriptor: settingsPath,
367 });
368 const messages: Array<unknown> = [];
369 const logger = Logger.make(({ message }) => {
370 messages.push(message);
371 });
372 const failingFileSystemLayer = Layer.succeed(
373 FileSystem.FileSystem,
374 FileSystem.makeNoop({
375 readFileString: () => Effect.fail(cause),
376 }),
377 );
378​
379 const config = yield* Effect.gen(function* () {
380 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
381 return yield* configuration.resolvePrimary;
382 }).pipe(
383 Effect.provide(
384 Layer.mergeAll(
385 DesktopBackendConfiguration.layer.pipe(
386 Layer.provideMerge(serverExposureLayer),
387 Layer.provideMerge(DesktopAppSettings.layerTest()),
388 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
389 Layer.provideMerge(makeEnvironmentLayer(baseDir)),
390 Layer.provideMerge(failingFileSystemLayer),
391 ),
392 Logger.layer([logger], { mergeWithExisting: false }),
393 ),
394 ),
395 );
396​
397 assert.isUndefined(config.bootstrap.otlpTracesUrl);
398 assert.isUndefined(config.bootstrap.otlpMetricsUrl);
399​
400 const error = messages
401 .flatMap((message) => (Array.isArray(message) ? message : [message]))
402 .find(isDesktopBackendObservabilitySettingsReadError);
403 assert.isDefined(error);
404 assert.equal(error.settingsPath, settingsPath);
405 assert.equal(error.cause, cause);
406 assert.equal(
407 error.message,
408 `Failed to read persisted backend observability settings at ${settingsPath}.`,
409 );
410 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
411 );
412​
413 it.effect("resolvePrimary captures backend output in dev so child logs can be persisted", () =>
414 Effect.gen(function* () {
415 const fileSystem = yield* FileSystem.FileSystem;
416 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
417 prefix: "t3-desktop-backend-config-test-",
418 });
419​
420 yield* Effect.gen(function* () {
421 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
422 const config = yield* configuration.resolvePrimary;
423 assert.equal(config.captureOutput, true);
424 }).pipe(
425 Effect.provide(
426 DesktopBackendConfiguration.layer.pipe(
427 Layer.provideMerge(serverExposureLayer),
428 Layer.provideMerge(DesktopAppSettings.layerTest()),
429 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
430 Layer.provideMerge(
431 makeEnvironmentLayer(baseDir, {
432 isPackaged: false,
433 devServerUrl: "http://127.0.0.1:5733",
434 }),
435 ),
436 ),
437 ),
438 );
439 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
440 );
441​
442 it.effect("resolveWsl preserves existing WSLENV entries when forwarding backend secrets", () =>
443 Effect.gen(function* () {
444 const fileSystem = yield* FileSystem.FileSystem;
445 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
446 prefix: "t3-desktop-backend-config-test-",
447 });
448​
449 const previousWslEnv = process.env.WSLENV;
450 const previousOpenAiKey = process.env.OPENAI_API_KEY;
451 const previousAnthropicKey = process.env.ANTHROPIC_API_KEY;
452 try {
453 process.env.WSLENV = "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u";
454 process.env.OPENAI_API_KEY = "openai-key";
455 process.env.ANTHROPIC_API_KEY = "anthropic-key";
456​
457 yield* Effect.gen(function* () {
458 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
459 const config = yield* configuration.resolveWsl({ port: 5050, distro: null });
460​
461 assert.equal(config.executablePath, "wsl.exe");
462 assert.equal(config.bootstrap.port, 5050);
463 // Binds to 0.0.0.0 inside WSL so the backend is reachable via
464 // both wslhost-forwarded localhost and the distro's eth0 IP.
465 assert.equal(config.bootstrap.host, "0.0.0.0");
466 assert.equal(config.bootstrap.tailscaleServeEnabled, false);
467 // httpBaseUrl uses the resolved distro IP from the test stub,
468 // not localhost — the renderer reaches the backend directly to
469 // avoid relying on wslhost forwarding.
470 assert.equal(config.httpBaseUrl.href, "http://172.27.0.99:5050/");
471 assert.equal(config.env.OPENAI_API_KEY, "openai-key");
472 assert.equal(config.env.ANTHROPIC_API_KEY, "anthropic-key");
473 // The existing WSLENV is preserved byte-for-byte (note the empty
474 // "::" segment survives — WSL ignores it, so we don't normalize
475 // it away) and ANTHROPIC_API_KEY is appended. OPENAI_API_KEY is
476 // already declared, so it isn't forwarded twice.
477 assert.equal(
478 config.env.WSLENV,
479 "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:ANTHROPIC_API_KEY",
480 );
481 }).pipe(
482 Effect.provide(
483 DesktopBackendConfiguration.layer.pipe(
484 Layer.provideMerge(serverExposureLayer),
485 Layer.provideMerge(DesktopAppSettings.layerTest()),
486 Layer.provideMerge(
487 DesktopWslEnvironment.layerTest({
488 isAvailable: true,
489 windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"),
490 getDistroIp: () => Option.some("172.27.0.99"),
491 }),
492 ),
493 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
494 ),
495 ),
496 );
497 } finally {
498 restoreEnv("WSLENV", previousWslEnv);
499 restoreEnv("OPENAI_API_KEY", previousOpenAiKey);
500 restoreEnv("ANTHROPIC_API_KEY", previousAnthropicKey);
501 }
502 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
503 );
504​
505 it.effect(
506 "resolvePrimary falls back to the Windows primary when wsl-only but WSL is unavailable",
507 () =>
508 Effect.gen(function* () {
509 const fileSystem = yield* FileSystem.FileSystem;
510 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
511 prefix: "t3-desktop-backend-config-test-",
512 });
513​
514 yield* Effect.gen(function* () {
515 const environment = yield* DesktopEnvironment.DesktopEnvironment;
516 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
517 const config = yield* configuration.resolvePrimary;
518​
519 // wsl-only is persisted but WSL is unavailable, so the primary must
520 // not spawn wsl.exe (which would loop on preflight failures while the
521 // Connections backend control is hidden). Resolve the Windows primary.
522 assert.equal(config.executablePath, process.execPath);
523 assert.equal(config.bootstrap.t3Home, environment.baseDir);
524 assert.isTrue(Option.isNone(config.preflightFailure));
525 }).pipe(
526 Effect.provide(
527 DesktopBackendConfiguration.layer.pipe(
528 Layer.provideMerge(serverExposureLayer),
529 Layer.provideMerge(
530 DesktopAppSettings.layerTest({
531 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
532 wslBackendEnabled: true,
533 wslOnly: true,
534 }),
535 ),
536 Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
537 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
538 ),
539 ),
540 );
541 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
542 );
543​
544 it.effect(
545 "resolvePrimary marks a removed persisted WSL distro as a fatal preflight failure",
546 () =>
547 Effect.gen(function* () {
548 const fileSystem = yield* FileSystem.FileSystem;
549 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
550 prefix: "t3-desktop-backend-config-test-",
551 });
552​
553 yield* Effect.gen(function* () {
554 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
555 const config = yield* configuration.resolvePrimary;
556 const failure = Option.getOrThrow(config.preflightFailure);
557​
558 assert.equal(config.executablePath, "wsl.exe");
559 assert.isTrue(failure.fatal);
560 assert.include(failure.reason, "Removed-Distro");
561 }).pipe(
562 Effect.provide(
563 DesktopBackendConfiguration.layer.pipe(
564 Layer.provideMerge(serverExposureLayer),
565 Layer.provideMerge(
566 DesktopAppSettings.layerTest({
567 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
568 wslBackendEnabled: true,
569 wslOnly: true,
570 wslDistro: "Removed-Distro",
571 }),
572 ),
573 Layer.provideMerge(
574 DesktopWslEnvironment.layerTest({
575 isAvailable: true,
576 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
577 }),
578 ),
579 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
580 ),
581 ),
582 );
583 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
584 );
585​
586 it.effect("resolveWsl keeps a transient distro-list failure retryable", () =>
587 Effect.gen(function* () {
588 const fileSystem = yield* FileSystem.FileSystem;
589 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
590 prefix: "t3-desktop-backend-config-test-",
591 });
592​
593 yield* Effect.gen(function* () {
594 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
595 const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
596 const failure = Option.getOrThrow(config.preflightFailure);
597​
598 assert.isFalse(failure.fatal);
599 assert.equal(failure.retryLimit, 12);
600 assert.include(failure.reason, "timed out");
601 }).pipe(
602 Effect.provide(
603 DesktopBackendConfiguration.layer.pipe(
604 Layer.provideMerge(serverExposureLayer),
605 Layer.provideMerge(DesktopAppSettings.layerTest()),
606 Layer.provideMerge(
607 DesktopWslEnvironment.layerTest({
608 isAvailable: true,
609 distroListError: new DesktopWslEnvironment.DesktopWslDistroListError({
610 reason: "wsl.exe --list --verbose timed out",
611 }),
612 }),
613 ),
614 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
615 ),
616 ),
617 );
618 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
619 );
620​
621 it.effect("resolveWsl marks a missing packaged server entry as fatal", () =>
622 Effect.gen(function* () {
623 const fileSystem = yield* FileSystem.FileSystem;
624 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
625 prefix: "t3-desktop-backend-config-test-",
626 });
627​
628 yield* Effect.gen(function* () {
629 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
630 const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
631 const failure = Option.getOrThrow(config.preflightFailure);
632​
633 assert.isTrue(failure.fatal);
634 assert.include(failure.reason, "missing server entry");
635 }).pipe(
636 Effect.provide(
637 DesktopBackendConfiguration.layer.pipe(
638 Layer.provideMerge(serverExposureLayer),
639 Layer.provideMerge(DesktopAppSettings.layerTest()),
640 Layer.provideMerge(
641 DesktopWslEnvironment.layerTest({
642 isAvailable: true,
643 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
644 }),
645 ),
646 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
647 ),
648 ),
649 );
650 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
651 );
652​
653 it.effect("resolveWsl marks a missing selected distro as a fatal preflight failure", () =>
654 Effect.gen(function* () {
655 const fileSystem = yield* FileSystem.FileSystem;
656 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
657 prefix: "t3-desktop-backend-config-test-",
658 });
659​
660 yield* Effect.gen(function* () {
661 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
662 const config = yield* configuration.resolveWsl({ port: 5050, distro: "Removed-Distro" });
663 const failure = Option.getOrThrow(config.preflightFailure);
664​
665 assert.isTrue(failure.fatal);
666 assert.include(failure.reason, "Removed-Distro");
667 }).pipe(
668 Effect.provide(
669 DesktopBackendConfiguration.layer.pipe(
670 Layer.provideMerge(serverExposureLayer),
671 Layer.provideMerge(DesktopAppSettings.layerTest()),
672 Layer.provideMerge(
673 DesktopWslEnvironment.layerTest({
674 isAvailable: true,
675 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
676 }),
677 ),
678 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
679 ),
680 ),
681 );
682 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
683 );
684​
685 it.effect("resolvePrimaryLabel reports the WSL distro when wsl-only and WSL is available", () =>
686 Effect.gen(function* () {
687 const fileSystem = yield* FileSystem.FileSystem;
688 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
689 prefix: "t3-desktop-backend-config-test-",
690 });
691​
692 yield* Effect.gen(function* () {
693 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
694 const label = yield* configuration.resolvePrimaryLabel;
695 assert.equal(label, "WSL (Ubuntu)");
696 }).pipe(
697 Effect.provide(
698 DesktopBackendConfiguration.layer.pipe(
699 Layer.provideMerge(serverExposureLayer),
700 Layer.provideMerge(
701 DesktopAppSettings.layerTest({
702 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
703 wslBackendEnabled: true,
704 wslOnly: true,
705 wslDistro: "Ubuntu",
706 }),
707 ),
708 Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
709 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
710 ),
711 ),
712 );
713 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
714 );
715​
716 it.effect("resolvePrimaryLabel reports the local environment on non-Windows platforms", () =>
717 withHarness(
718 Effect.gen(function* () {
719 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
720 const label = yield* configuration.resolvePrimaryLabel;
721 assert.equal(label, "Local environment");
722 }),
723 ),
724 );
725​
726 it.effect("resolvePrimaryLabel reports Windows when wsl-only but WSL is unavailable", () =>
727 Effect.gen(function* () {
728 const fileSystem = yield* FileSystem.FileSystem;
729 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
730 prefix: "t3-desktop-backend-config-test-",
731 });
732​
733 yield* Effect.gen(function* () {
734 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
735 // Mirrors the resolvePrimary fall-back: the label must follow the
736 // backend that actually resolves, not the persisted preference, so the
737 // env switcher can't show "WSL" for a Windows backend.
738 const label = yield* configuration.resolvePrimaryLabel;
739 assert.equal(label, "Windows");
740 }).pipe(
741 Effect.provide(
742 DesktopBackendConfiguration.layer.pipe(
743 Layer.provideMerge(serverExposureLayer),
744 Layer.provideMerge(
745 DesktopAppSettings.layerTest({
746 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
747 wslBackendEnabled: true,
748 wslOnly: true,
749 wslDistro: "Ubuntu",
750 }),
751 ),
752 Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
753 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
754 ),
755 ),
756 );
757 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
758 );
759​
760 it("resolvePrimaryLabel is runSync-safe against the real WSL availability probe", async () => {
761 // getLocalEnvironmentBootstraps is a sync IPC method: it resolves the
762 // primary instance's lazy label through Effect.runSync. The label chains
763 // to wslEnvironment.isAvailable, whose real layer probes the filesystem.
764 // That probe must run once at layer build and expose a resolved value, not
765 // a live async effect — otherwise runSync throws in the handler. Build the
766 // real WSL layer (not the sync test stub) and resolve the label with a
767 // top-level runSync, exactly as the handler does.
768 // 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.
769 const runtime = ManagedRuntime.make(
770 DesktopBackendConfiguration.layer.pipe(
771 Layer.provideMerge(serverExposureLayer),
772 Layer.provideMerge(DesktopAppSettings.layerTest()),
773 Layer.provideMerge(DesktopWslEnvironment.layer),
774 // isAvailable on win32 only touches the filesystem, never the spawner,
775 // so a die-stub is enough to satisfy the layer's deps.
776 Layer.provideMerge(
777 Layer.succeed(
778 ChildProcessSpawner.ChildProcessSpawner,
779 ChildProcessSpawner.make(() =>
780 Effect.die("spawner should not be used while probing WSL availability"),
781 ),
782 ),
783 ),
784 Layer.provideMerge(makeEnvironmentLayer("/tmp/t3-wsl-isavailable", { platform: "win32" })),
785 Layer.provide(NodeServices.layer),
786 ),
787 );
788 try {
789 const configuration = await runtime.runPromise(
790 DesktopBackendConfiguration.DesktopBackendConfiguration,
791 );
792 // oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- Same reason: this is the synchronous resolution the IPC handler performs.
793 const label = Effect.runSync(configuration.resolvePrimaryLabel);
794 assert.equal(typeof label, "string");
795 } finally {
796 await runtime.dispose();
797 }
798 });
799});