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

DesktopBackendConfiguration.test.ts

893 lines36.7 KB

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