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