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