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

DesktopBackendConfiguration.test.ts

993 lines41.0 KB

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