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";
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 );
86}
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 const archiveHash = "a".repeat(64);
180 yield* fileSystem.writeFileString(
181 path.join(baseDir, "wsl-runtime.tar.gz.sha256"),
182 archiveHash,
183 );
184
185 const observedDistros: Array<string | null> = [];
186 const observedWindowsConversions: string[] = [];
187 const observedRuntimePreparations: Array<{
188 readonly distro: string | null;
189 readonly windowsArchivePath: string;
190 readonly archiveHash: string;
191 }> = [];
192 const observedNodePtyRoots: string[] = [];
193 const linuxRepoRoot = `/home/test/.cache/t3code/desktop-wsl-runtime/sha256-${archiveHash}`;
194 const config = yield* Effect.gen(function* () {
195 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
196 return yield* configuration.resolveWsl({ port: 5000, distro: null });
197 }).pipe(
198 Effect.provide(
199 DesktopBackendConfiguration.layer.pipe(
200 Layer.provideMerge(serverExposureLayer),
201 Layer.provideMerge(DesktopAppSettings.layerTest()),
202 Layer.provideMerge(
203 DesktopWslEnvironment.layerTest({
204 isAvailable: true,
205 distros: [
206 { name: "Debian", isDefault: false, version: 2 },
207 { name: "Ubuntu", isDefault: true, version: 2 },
208 ],
209 windowsToWslPath: (_distro, windowsPath) => {
210 observedWindowsConversions.push(windowsPath);
211 return Option.some("/mnt/c/t3code");
212 },
213 preparePackagedRuntime: (distro, windowsArchivePath, preparedArchiveHash) => {
214 observedDistros.push(distro);
215 observedRuntimePreparations.push({
216 distro,
217 windowsArchivePath,
218 archiveHash: preparedArchiveHash,
219 });
220 return { ok: true, linuxRepoRoot };
221 },
222 ensureNodePty: (distro, root) => {
223 observedDistros.push(distro);
224 observedNodePtyRoots.push(root);
225 return { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" };
226 },
227 getDistroIp: (distro) => {
228 observedDistros.push(distro);
229 return Option.some("172.27.0.99");
230 },
231 }),
232 ),
233 Layer.provideMerge(
234 makeEnvironmentLayer(baseDir, {
235 appPath: baseDir,
236 platform: "win32",
237 resourcesPath: baseDir,
238 }),
239 ),
240 ),
241 ),
242 );
243
244 assert.equal(config.runningDistro, "Ubuntu");
245 assert.deepEqual(config.args.slice(0, 2), ["-d", "Ubuntu"]);
246 assert.deepEqual(observedDistros, ["Ubuntu", "Ubuntu", "Ubuntu"]);
247 assert.deepEqual(observedWindowsConversions, []);
248 assert.deepEqual(observedRuntimePreparations, [
249 {
250 distro: "Ubuntu",
251 windowsArchivePath: path.join(baseDir, "wsl-runtime.tar.gz"),
252 archiveHash,
253 },
254 ]);
255 assert.deepEqual(observedNodePtyRoots, [linuxRepoRoot]);
256 assert.include(config.args, `${linuxRepoRoot}/apps/server/dist/bin.mjs`);
257 assert.isTrue(Option.isNone(config.preflightFailure));
258 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
259 );
260
261 it.effect("resolveWsl falls back to the mounted runtime when native staging fails", () =>
262 Effect.gen(function* () {
263 const fileSystem = yield* FileSystem.FileSystem;
264 const path = yield* Path.Path;
265 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
266 prefix: "t3-desktop-backend-config-test-",
267 });
268 const entryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");
269 yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
270 yield* fileSystem.writeFileString(entryPath, "");
271 yield* fileSystem.writeFileString(
272 path.join(baseDir, "wsl-runtime.tar.gz.sha256"),
273 `${"b".repeat(64)}\n`,
274 );
275
276 const observedNodePtyRoots: string[] = [];
277 const config = yield* Effect.gen(function* () {
278 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
279 return yield* configuration.resolveWsl({ port: 5001, distro: "Ubuntu" });
280 }).pipe(
281 Effect.provide(
282 DesktopBackendConfiguration.layer.pipe(
283 Layer.provideMerge(serverExposureLayer),
284 Layer.provideMerge(DesktopAppSettings.layerTest()),
285 Layer.provideMerge(
286 DesktopWslEnvironment.layerTest({
287 isAvailable: true,
288 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
289 preparePackagedRuntime: () => ({
290 ok: false,
291 reason: "archive extraction failed",
292 }),
293 windowsToWslPath: () => Option.some("/mnt/c/t3code"),
294 ensureNodePty: (_distro, root) => {
295 observedNodePtyRoots.push(root);
296 return { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" };
297 },
298 getDistroIp: () => Option.none(),
299 }),
300 ),
301 Layer.provideMerge(
302 makeEnvironmentLayer(baseDir, {
303 appPath: baseDir,
304 platform: "win32",
305 resourcesPath: baseDir,
306 }),
307 ),
308 ),
309 ),
310 );
311
312 assert.deepEqual(observedNodePtyRoots, ["/mnt/c/t3code"]);
313 assert.include(config.args, "/mnt/c/t3code/apps/server/dist/bin.mjs");
314 assert.isTrue(Option.isNone(config.preflightFailure));
315 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
316 );
317
318 it.effect(
319 "resolveWsl preserves inherited PATH with quote-sensitive values as separate args",
320 () =>
321 Effect.gen(function* () {
322 const fileSystem = yield* FileSystem.FileSystem;
323 const path = yield* Path.Path;
324 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
325 prefix: "t3-desktop-backend-config-test-",
326 });
327 const dirname = path.join(baseDir, "apps/desktop/src");
328 const entryPath = path.join(baseDir, "apps/server/dist/bin.mjs");
329 yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
330 yield* fileSystem.writeFileString(entryPath, "");
331
332 const nodePath = "/home/test user's/.nvm/versions/node/v22.0.0/bin/node";
333 const linuxRepoRoot = "/tmp/t3 code's launch";
334 const linuxEntryPath = `${linuxRepoRoot}/apps/server/dist/bin.mjs`;
335 const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
336 const devServerUrl = "http://127.0.0.1:5733/dev%20assets/?label=hello%20world";
337 const config = yield* Effect.gen(function* () {
338 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
339 return yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
340 }).pipe(
341 Effect.provide(
342 DesktopBackendConfiguration.layer.pipe(
343 Layer.provideMerge(serverExposureLayer),
344 Layer.provideMerge(DesktopAppSettings.layerTest()),
345 Layer.provideMerge(
346 DesktopWslEnvironment.layerTest({
347 isAvailable: true,
348 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
349 windowsToWslPath: () => Option.some(linuxRepoRoot),
350 ensureNodePty: () => ({ ok: true, nodePath, resolvedPath }),
351 getDistroIp: () => Option.some("172.27.0.99"),
352 }),
353 ),
354 Layer.provideMerge(
355 makeEnvironmentLayer(baseDir, {
356 dirname,
357 devServerUrl,
358 isPackaged: false,
359 platform: "win32",
360 }),
361 ),
362 ),
363 ),
364 );
365
366 assert.equal(config.bootstrapDelivery, "stdin");
367 assert.deepEqual(config.args, [
368 "-d",
369 "Ubuntu",
370 "--exec",
371 "env",
372 "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",
373 nodePath,
374 linuxEntryPath,
375 "--bootstrap-fd",
376 "0",
377 "--dev-url",
378 devServerUrl,
379 ]);
380 assert.notInclude(config.args, "bash");
381 assert.notInclude(config.args, "/bin/sh");
382 assert.notInclude(config.args, "-c");
383 assert.isTrue(Option.isNone(config.preflightFailure));
384 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
385 );
386
387 it.effect("resolvePrimary and resolveWsl share one token under concurrent resolution", () =>
388 withHarness(
389 Effect.gen(function* () {
390 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
391
392 // Resolve both before any token is cached, concurrently, so the
393 // generate step (a yield point) can interleave. The atomic
394 // get-or-create must still hand both the same token; a non-atomic
395 // Ref would let each generate its own and break the shared-token
396 // invariant.
397 const [primary, wsl] = yield* Effect.all(
398 [configuration.resolvePrimary, configuration.resolveWsl({ port: 5000, distro: null })],
399 { concurrency: "unbounded" },
400 );
401
402 assert.equal(wsl.bootstrap.desktopBootstrapToken, primary.bootstrap.desktopBootstrapToken);
403 }),
404 ),
405 );
406
407 it.effect("resolvePrimary surfaces persisted backend observability endpoints", () =>
408 withHarness(
409 Effect.gen(function* () {
410 const fileSystem = yield* FileSystem.FileSystem;
411 const environment = yield* DesktopEnvironment.DesktopEnvironment;
412 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
413
414 yield* fileSystem.makeDirectory(environment.path.dirname(environment.serverSettingsPath), {
415 recursive: true,
416 });
417 yield* fileSystem.writeFileString(
418 environment.serverSettingsPath,
419 yield* encodePersistedServerObservabilitySettingsDocument({
420 observability: {
421 otlpTracesUrl: " http://127.0.0.1:4318/v1/traces ",
422 otlpMetricsUrl: " http://127.0.0.1:4318/v1/metrics ",
423 },
424 }),
425 );
426
427 const config = yield* configuration.resolvePrimary;
428 assert.equal(config.bootstrap.otlpTracesUrl, "http://127.0.0.1:4318/v1/traces");
429 assert.equal(config.bootstrap.otlpMetricsUrl, "http://127.0.0.1:4318/v1/metrics");
430 }),
431 ),
432 );
433
434 it.effect("resolvePrimary omits backend observability endpoints when settings are missing", () =>
435 withHarness(
436 Effect.gen(function* () {
437 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
438 const config = yield* configuration.resolvePrimary;
439
440 assert.isUndefined(config.bootstrap.otlpTracesUrl);
441 assert.isUndefined(config.bootstrap.otlpMetricsUrl);
442 }),
443 ),
444 );
445
446 it.effect("logs structured context when persisted observability settings cannot be read", () =>
447 Effect.gen(function* () {
448 const fileSystem = yield* FileSystem.FileSystem;
449 const path = yield* Path.Path;
450 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
451 prefix: "t3-desktop-backend-config-test-",
452 });
453 const settingsPath = path.join(baseDir, "userdata", "settings.json");
454 const cause = PlatformError.systemError({
455 _tag: "PermissionDenied",
456 module: "FileSystem",
457 method: "readFileString",
458 pathOrDescriptor: settingsPath,
459 });
460 const messages: Array<unknown> = [];
461 const logger = Logger.make(({ message }) => {
462 messages.push(message);
463 });
464 const failingFileSystemLayer = Layer.succeed(
465 FileSystem.FileSystem,
466 FileSystem.makeNoop({
467 readFileString: () => Effect.fail(cause),
468 }),
469 );
470
471 const config = yield* Effect.gen(function* () {
472 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
473 return yield* configuration.resolvePrimary;
474 }).pipe(
475 Effect.provide(
476 Layer.mergeAll(
477 DesktopBackendConfiguration.layer.pipe(
478 Layer.provideMerge(serverExposureLayer),
479 Layer.provideMerge(DesktopAppSettings.layerTest()),
480 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
481 Layer.provideMerge(makeEnvironmentLayer(baseDir)),
482 Layer.provideMerge(failingFileSystemLayer),
483 ),
484 Logger.layer([logger], { mergeWithExisting: false }),
485 ),
486 ),
487 );
488
489 assert.isUndefined(config.bootstrap.otlpTracesUrl);
490 assert.isUndefined(config.bootstrap.otlpMetricsUrl);
491
492 const error = messages
493 .flatMap((message) => (Array.isArray(message) ? message : [message]))
494 .find(isDesktopBackendObservabilitySettingsReadError);
495 assert.isDefined(error);
496 assert.equal(error.settingsPath, settingsPath);
497 assert.equal(error.cause, cause);
498 assert.equal(
499 error.message,
500 `Failed to read persisted backend observability settings at ${settingsPath}.`,
501 );
502 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
503 );
504
505 it.effect("resolvePrimary captures backend output in dev so child logs can be persisted", () =>
506 Effect.gen(function* () {
507 const fileSystem = yield* FileSystem.FileSystem;
508 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
509 prefix: "t3-desktop-backend-config-test-",
510 });
511
512 yield* Effect.gen(function* () {
513 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
514 const config = yield* configuration.resolvePrimary;
515 assert.equal(config.captureOutput, true);
516 }).pipe(
517 Effect.provide(
518 DesktopBackendConfiguration.layer.pipe(
519 Layer.provideMerge(serverExposureLayer),
520 Layer.provideMerge(DesktopAppSettings.layerTest()),
521 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
522 Layer.provideMerge(
523 makeEnvironmentLayer(baseDir, {
524 isPackaged: false,
525 devServerUrl: "http://127.0.0.1:5733",
526 }),
527 ),
528 ),
529 ),
530 );
531 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
532 );
533
534 it.effect("resolveWsl preserves existing WSLENV entries when forwarding backend secrets", () =>
535 Effect.gen(function* () {
536 const fileSystem = yield* FileSystem.FileSystem;
537 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
538 prefix: "t3-desktop-backend-config-test-",
539 });
540
541 const previousWslEnv = process.env.WSLENV;
542 const previousOpenAiKey = process.env.OPENAI_API_KEY;
543 const previousAnthropicKey = process.env.ANTHROPIC_API_KEY;
544 try {
545 process.env.WSLENV = "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u";
546 process.env.OPENAI_API_KEY = "openai-key";
547 process.env.ANTHROPIC_API_KEY = "anthropic-key";
548
549 yield* Effect.gen(function* () {
550 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
551 const config = yield* configuration.resolveWsl({ port: 5050, distro: null });
552
553 assert.equal(config.executablePath, "wsl.exe");
554 assert.equal(config.bootstrap.port, 5050);
555 // Binds to 0.0.0.0 inside WSL so the backend is reachable via
556 // both wslhost-forwarded localhost and the distro's eth0 IP.
557 assert.equal(config.bootstrap.host, "0.0.0.0");
558 assert.equal(config.bootstrap.tailscaleServeEnabled, false);
559 assert.notProperty(config.bootstrap, "desktopTelemetryFd");
560 assert.notProperty(config.bootstrap, "resourceMonitorPath");
561 // httpBaseUrl uses the resolved distro IP from the test stub,
562 // not localhost — the renderer reaches the backend directly to
563 // avoid relying on wslhost forwarding.
564 assert.equal(config.httpBaseUrl.href, "http://172.27.0.99:5050/");
565 assert.equal(config.env.OPENAI_API_KEY, "openai-key");
566 assert.equal(config.env.ANTHROPIC_API_KEY, "anthropic-key");
567 // The existing WSLENV is preserved byte-for-byte (note the empty
568 // "::" segment survives — WSL ignores it, so we don't normalize
569 // it away) and ANTHROPIC_API_KEY is appended. OPENAI_API_KEY is
570 // already declared, so it isn't forwarded twice.
571 assert.equal(
572 config.env.WSLENV,
573 "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:ANTHROPIC_API_KEY",
574 );
575 }).pipe(
576 Effect.provide(
577 DesktopBackendConfiguration.layer.pipe(
578 Layer.provideMerge(serverExposureLayer),
579 Layer.provideMerge(DesktopAppSettings.layerTest()),
580 Layer.provideMerge(
581 DesktopWslEnvironment.layerTest({
582 isAvailable: true,
583 windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"),
584 getDistroIp: () => Option.some("172.27.0.99"),
585 }),
586 ),
587 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
588 ),
589 ),
590 );
591 } finally {
592 restoreEnv("WSLENV", previousWslEnv);
593 restoreEnv("OPENAI_API_KEY", previousOpenAiKey);
594 restoreEnv("ANTHROPIC_API_KEY", previousAnthropicKey);
595 }
596 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
597 );
598
599 it.effect(
600 "resolvePrimary falls back to the Windows primary when wsl-only but WSL is unavailable",
601 () =>
602 Effect.gen(function* () {
603 const fileSystem = yield* FileSystem.FileSystem;
604 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
605 prefix: "t3-desktop-backend-config-test-",
606 });
607
608 yield* Effect.gen(function* () {
609 const environment = yield* DesktopEnvironment.DesktopEnvironment;
610 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
611 const config = yield* configuration.resolvePrimary;
612
613 // wsl-only is persisted but WSL is unavailable, so the primary must
614 // not spawn wsl.exe (which would loop on preflight failures while the
615 // Connections backend control is hidden). Resolve the Windows primary.
616 assert.equal(config.executablePath, process.execPath);
617 assert.equal(config.bootstrap.t3Home, environment.baseDir);
618 assert.isTrue(Option.isNone(config.preflightFailure));
619 }).pipe(
620 Effect.provide(
621 DesktopBackendConfiguration.layer.pipe(
622 Layer.provideMerge(serverExposureLayer),
623 Layer.provideMerge(
624 DesktopAppSettings.layerTest({
625 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
626 wslBackendEnabled: true,
627 wslOnly: true,
628 }),
629 ),
630 Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
631 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
632 ),
633 ),
634 );
635 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
636 );
637
638 it.effect(
639 "resolvePrimary marks a removed persisted WSL distro as a fatal preflight failure",
640 () =>
641 Effect.gen(function* () {
642 const fileSystem = yield* FileSystem.FileSystem;
643 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
644 prefix: "t3-desktop-backend-config-test-",
645 });
646
647 yield* Effect.gen(function* () {
648 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
649 const config = yield* configuration.resolvePrimary;
650 const failure = Option.getOrThrow(config.preflightFailure);
651
652 assert.equal(config.executablePath, "wsl.exe");
653 assert.isTrue(failure.fatal);
654 assert.include(failure.reason, "Removed-Distro");
655 }).pipe(
656 Effect.provide(
657 DesktopBackendConfiguration.layer.pipe(
658 Layer.provideMerge(serverExposureLayer),
659 Layer.provideMerge(
660 DesktopAppSettings.layerTest({
661 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
662 wslBackendEnabled: true,
663 wslOnly: true,
664 wslDistro: "Removed-Distro",
665 }),
666 ),
667 Layer.provideMerge(
668 DesktopWslEnvironment.layerTest({
669 isAvailable: true,
670 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
671 }),
672 ),
673 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
674 ),
675 ),
676 );
677 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
678 );
679
680 it.effect("resolveWsl keeps a transient distro-list failure retryable", () =>
681 Effect.gen(function* () {
682 const fileSystem = yield* FileSystem.FileSystem;
683 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
684 prefix: "t3-desktop-backend-config-test-",
685 });
686
687 yield* Effect.gen(function* () {
688 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
689 const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
690 const failure = Option.getOrThrow(config.preflightFailure);
691
692 assert.isFalse(failure.fatal);
693 assert.equal(failure.retryLimit, 12);
694 assert.include(failure.reason, "timed out");
695 }).pipe(
696 Effect.provide(
697 DesktopBackendConfiguration.layer.pipe(
698 Layer.provideMerge(serverExposureLayer),
699 Layer.provideMerge(DesktopAppSettings.layerTest()),
700 Layer.provideMerge(
701 DesktopWslEnvironment.layerTest({
702 isAvailable: true,
703 distroListError: new DesktopWslEnvironment.DesktopWslDistroListError({
704 reason: "wsl.exe --list --verbose timed out",
705 }),
706 }),
707 ),
708 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
709 ),
710 ),
711 );
712 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
713 );
714
715 it.effect("resolveWsl marks a missing packaged server entry as fatal", () =>
716 Effect.gen(function* () {
717 const fileSystem = yield* FileSystem.FileSystem;
718 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
719 prefix: "t3-desktop-backend-config-test-",
720 });
721
722 yield* Effect.gen(function* () {
723 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
724 const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
725 const failure = Option.getOrThrow(config.preflightFailure);
726
727 assert.isTrue(failure.fatal);
728 assert.include(failure.reason, "missing server entry");
729 }).pipe(
730 Effect.provide(
731 DesktopBackendConfiguration.layer.pipe(
732 Layer.provideMerge(serverExposureLayer),
733 Layer.provideMerge(DesktopAppSettings.layerTest()),
734 Layer.provideMerge(
735 DesktopWslEnvironment.layerTest({
736 isAvailable: true,
737 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
738 }),
739 ),
740 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
741 ),
742 ),
743 );
744 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
745 );
746
747 it.effect("resolveWsl marks a missing selected distro as a fatal preflight failure", () =>
748 Effect.gen(function* () {
749 const fileSystem = yield* FileSystem.FileSystem;
750 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
751 prefix: "t3-desktop-backend-config-test-",
752 });
753
754 yield* Effect.gen(function* () {
755 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
756 const config = yield* configuration.resolveWsl({ port: 5050, distro: "Removed-Distro" });
757 const failure = Option.getOrThrow(config.preflightFailure);
758
759 assert.isTrue(failure.fatal);
760 assert.include(failure.reason, "Removed-Distro");
761 }).pipe(
762 Effect.provide(
763 DesktopBackendConfiguration.layer.pipe(
764 Layer.provideMerge(serverExposureLayer),
765 Layer.provideMerge(DesktopAppSettings.layerTest()),
766 Layer.provideMerge(
767 DesktopWslEnvironment.layerTest({
768 isAvailable: true,
769 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
770 }),
771 ),
772 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
773 ),
774 ),
775 );
776 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
777 );
778
779 it.effect("resolvePrimaryLabel reports the WSL distro when wsl-only and WSL is available", () =>
780 Effect.gen(function* () {
781 const fileSystem = yield* FileSystem.FileSystem;
782 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
783 prefix: "t3-desktop-backend-config-test-",
784 });
785
786 yield* Effect.gen(function* () {
787 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
788 const label = yield* configuration.resolvePrimaryLabel;
789 assert.equal(label, "WSL (Ubuntu)");
790 }).pipe(
791 Effect.provide(
792 DesktopBackendConfiguration.layer.pipe(
793 Layer.provideMerge(serverExposureLayer),
794 Layer.provideMerge(
795 DesktopAppSettings.layerTest({
796 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
797 wslBackendEnabled: true,
798 wslOnly: true,
799 wslDistro: "Ubuntu",
800 }),
801 ),
802 Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
803 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
804 ),
805 ),
806 );
807 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
808 );
809
810 it.effect("prefers the external packaged resource monitor over the copy inside the asar", () =>
811 Effect.gen(function* () {
812 const fileSystem = yield* FileSystem.FileSystem;
813 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
814 prefix: "t3-desktop-backend-config-test-",
815 });
816 const resourcesPath = `${baseDir}/resources`;
817 const dirname = `${resourcesPath}/app.asar/apps/desktop/dist-electron`;
818 const embeddedMonitorPath = `${resourcesPath}/app.asar/apps/desktop/prod-resources/resource-monitor/t3-resource-monitor`;
819 const monitorPath = `${resourcesPath}/resource-monitor/t3-resource-monitor`;
820 yield* fileSystem.makeDirectory(
821 `${resourcesPath}/app.asar/apps/desktop/prod-resources/resource-monitor`,
822 { recursive: true },
823 );
824 yield* fileSystem.makeDirectory(`${resourcesPath}/resource-monitor`, {
825 recursive: true,
826 });
827 yield* fileSystem.writeFileString(embeddedMonitorPath, "embedded");
828 yield* fileSystem.writeFileString(monitorPath, "binary");
829 yield* fileSystem.chmod(monitorPath, 0o755);
830
831 yield* Effect.gen(function* () {
832 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
833 const config = yield* configuration.resolvePrimary;
834 assert.equal(config.bootstrap.resourceMonitorPath, monitorPath);
835 assert.equal(config.bootstrap.desktopTelemetryFd, 4);
836 assert.equal(config.bootstrap.desktopTelemetryControlFd, 5);
837 }).pipe(
838 Effect.provide(
839 DesktopBackendConfiguration.layer.pipe(
840 Layer.provideMerge(serverExposureLayer),
841 Layer.provideMerge(DesktopAppSettings.layerTest()),
842 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
843 Layer.provideMerge(
844 makeEnvironmentLayer(baseDir, {
845 appPath: `${resourcesPath}/app.asar`,
846 dirname,
847 isPackaged: true,
848 resourcesPath,
849 }),
850 ),
851 ),
852 ),
853 );
854 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
855 );
856
857 it.effect("prefers the release resource monitor when both development builds exist", () =>
858 Effect.gen(function* () {
859 const fileSystem = yield* FileSystem.FileSystem;
860 const path = yield* Path.Path;
861 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
862 prefix: "t3-desktop-backend-config-test-",
863 });
864 const dirname = path.join(baseDir, "apps/desktop/src");
865 const releaseMonitorPath = path.join(
866 baseDir,
867 "native/resource-monitor/target/release/t3-resource-monitor",
868 );
869 const debugMonitorPath = path.join(
870 baseDir,
871 "native/resource-monitor/target/debug/t3-resource-monitor",
872 );
873 yield* fileSystem.makeDirectory(path.dirname(releaseMonitorPath), { recursive: true });
874 yield* fileSystem.makeDirectory(path.dirname(debugMonitorPath), { recursive: true });
875 yield* fileSystem.writeFileString(releaseMonitorPath, "release");
876 yield* fileSystem.writeFileString(debugMonitorPath, "debug");
877
878 yield* Effect.gen(function* () {
879 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
880 const config = yield* configuration.resolvePrimary;
881 assert.equal(config.bootstrap.resourceMonitorPath, releaseMonitorPath);
882 }).pipe(
883 Effect.provide(
884 DesktopBackendConfiguration.layer.pipe(
885 Layer.provideMerge(serverExposureLayer),
886 Layer.provideMerge(DesktopAppSettings.layerTest()),
887 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
888 Layer.provideMerge(
889 makeEnvironmentLayer(baseDir, {
890 dirname,
891 devServerUrl: "http://127.0.0.1:5733",
892 isPackaged: false,
893 }),
894 ),
895 ),
896 ),
897 );
898 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
899 );
900
901 it.effect("resolvePrimaryLabel reports the local environment on non-Windows platforms", () =>
902 withHarness(
903 Effect.gen(function* () {
904 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
905 const label = yield* configuration.resolvePrimaryLabel;
906 assert.equal(label, "Local environment");
907 }),
908 ),
909 );
910
911 it.effect("resolvePrimaryLabel reports Windows when wsl-only but WSL is unavailable", () =>
912 Effect.gen(function* () {
913 const fileSystem = yield* FileSystem.FileSystem;
914 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
915 prefix: "t3-desktop-backend-config-test-",
916 });
917
918 yield* Effect.gen(function* () {
919 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
920 // Mirrors the resolvePrimary fall-back: the label must follow the
921 // backend that actually resolves, not the persisted preference, so the
922 // env switcher can't show "WSL" for a Windows backend.
923 const label = yield* configuration.resolvePrimaryLabel;
924 assert.equal(label, "Windows");
925 }).pipe(
926 Effect.provide(
927 DesktopBackendConfiguration.layer.pipe(
928 Layer.provideMerge(serverExposureLayer),
929 Layer.provideMerge(
930 DesktopAppSettings.layerTest({
931 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
932 wslBackendEnabled: true,
933 wslOnly: true,
934 wslDistro: "Ubuntu",
935 }),
936 ),
937 Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
938 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
939 ),
940 ),
941 );
942 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
943 );
944
945 it("resolvePrimaryLabel is runSync-safe against the real WSL availability probe", async () => {
946 // getLocalEnvironmentBootstraps is a sync IPC method: it resolves the
947 // primary instance's lazy label through Effect.runSync. The label chains
948 // to wslEnvironment.isAvailable, whose real layer probes the filesystem.
949 // That probe must run once at layer build and expose a resolved value, not
950 // a live async effect — otherwise runSync throws in the handler. Build the
951 // real WSL layer (not the sync test stub) and resolve the label with a
952 // top-level runSync, exactly as the handler does.
953 // 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.
954 const runtime = ManagedRuntime.make(
955 DesktopBackendConfiguration.layer.pipe(
956 Layer.provideMerge(serverExposureLayer),
957 Layer.provideMerge(DesktopAppSettings.layerTest()),
958 Layer.provideMerge(DesktopWslEnvironment.layer),
959 // isAvailable on win32 only touches the filesystem, never the spawner,
960 // so a die-stub is enough to satisfy the layer's deps.
961 Layer.provideMerge(
962 Layer.succeed(
963 ChildProcessSpawner.ChildProcessSpawner,
964 ChildProcessSpawner.make(() =>
965 Effect.die("spawner should not be used while probing WSL availability"),
966 ),
967 ),
968 ),
969 Layer.provideMerge(makeEnvironmentLayer("/tmp/t3-wsl-isavailable", { platform: "win32" })),
970 Layer.provide(NodeServices.layer),
971 ),
972 );
973 try {
974 const configuration = await runtime.runPromise(
975 DesktopBackendConfiguration.DesktopBackendConfiguration,
976 );
977 // oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- Same reason: this is the synchronous resolution the IPC handler performs.
978 const label = Effect.runSync(configuration.resolvePrimaryLabel);
979 assert.equal(typeof label, "string");
980 } finally {
981 await runtime.dispose();
982 }
983 });
984});