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