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, 2), ["-d", "Ubuntu"]);
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 const observedProbeRoots: string[] = [];
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: (_distro, root) => {
410 observedProbeRoots.push(root);
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.deepEqual(observedProbeRoots, [linuxAppRoot]);
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 "--exec",
440 "env",
441 `PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${resolvedPath}`,
442 `${linuxAppRoot}/t3`,
443 "--bootstrap-fd",
444 "0",
445 ]);
446 assert.notInclude(config.args, "/usr/bin/node");
447 assert.equal(config.wslRuntimeId, `sha256-${archiveHash}`);
448 assert.equal(legacyCleanupCount, 1);
449 assert.isTrue(Option.isNone(config.preflightFailure));
450 }),
451 );
452 });
453
454 it.effect("resolveWsl changes the cache id when the packaged archive changes", () => {
455 const firstHash = "a".repeat(64);
456 const secondHash = "b".repeat(64);
457 const observedRuntimeIds: string[] = [];
458 return withPackagedWslHarness(
459 {
460 archiveHash: firstHash,
461 wsl: () => ({
462 prepareRuntime: (_distro, archive) => {
463 observedRuntimeIds.push(archive.runtimeId);
464 return { ok: true, linuxAppRoot: `/runtime/${archive.runtimeId}` };
465 },
466 ensureNodePty: () => ({
467 ok: true,
468 nodePath: "/usr/bin/node",
469 resolvedPath: "/usr/bin:/bin",
470 }),
471 }),
472 },
473 ({ hashPath, mountedAppRoot }) =>
474 Effect.gen(function* () {
475 const fileSystem = yield* FileSystem.FileSystem;
476 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
477 const first = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
478 yield* fileSystem.writeFileString(hashPath, secondHash);
479 const second = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
480 yield* fileSystem.writeFileString(hashPath, "not-a-sha256");
481 const invalidIdentity = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
482
483 assert.deepEqual(observedRuntimeIds, [`sha256-${firstHash}`, `sha256-${secondHash}`]);
484 assert.equal(first.wslRuntimeId, observedRuntimeIds[0]);
485 assert.include(first.args, `/runtime/sha256-${firstHash}/t3`);
486 assert.equal(second.wslRuntimeId, observedRuntimeIds[1]);
487 assert.include(second.args, `/runtime/sha256-${secondHash}/t3`);
488 assert.isUndefined(invalidIdentity.wslRuntimeId);
489 assert.include(invalidIdentity.args, "/usr/bin/node");
490 assert.include(invalidIdentity.args, `${mountedAppRoot}/apps/server/dist/bin.mjs`);
491 }),
492 );
493 });
494
495 it.effect("resolveWsl falls back to the mounted runtime when archive staging fails", () => {
496 const observedNodePtyRoots: string[] = [];
497 return withPackagedWslHarness(
498 {
499 archiveHash: "b".repeat(64),
500 wsl: () => ({
501 prepareRuntime: () => ({ ok: false, reason: "archive is corrupt" }),
502 invalidateRuntime: () => Effect.die("failed staging must not invalidate a runtime"),
503 ensureNodePty: (_distro, root) => {
504 observedNodePtyRoots.push(root);
505 return { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" };
506 },
507 }),
508 },
509 ({ mountedAppRoot, mountedEntryPath }) =>
510 Effect.gen(function* () {
511 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
512 const config = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
513
514 assert.deepEqual(observedNodePtyRoots, [mountedAppRoot]);
515 assert.equal(config.entryPath, mountedEntryPath);
516 assert.include(config.args, "/usr/bin/node");
517 assert.include(config.args, `${mountedAppRoot}/apps/server/dist/bin.mjs`);
518 assert.isUndefined(config.wslRuntimeId);
519 assert.isTrue(Option.isNone(config.preflightFailure));
520 }),
521 );
522 });
523
524 it.effect("resolveWsl retires a staged runtime whose executable does not start", () => {
525 const archiveHash = "c".repeat(64);
526 const stagedAppRoot = `/home/test/.t3/wsl-runtime/sha256-${archiveHash}`;
527 const observedProbeRoots: string[] = [];
528 const observedNodePtyRoots: string[] = [];
529 const invalidatedRuntimeIds: string[] = [];
530 return withPackagedWslHarness(
531 {
532 archiveHash,
533 wsl: () => ({
534 prepareRuntime: () => ({ ok: true, linuxAppRoot: stagedAppRoot }),
535 invalidateRuntime: (_distro, runtimeId) =>
536 Effect.sync(() => {
537 invalidatedRuntimeIds.push(runtimeId);
538 }),
539 probeRuntime: (_distro, root) => {
540 observedProbeRoots.push(root);
541 return { ok: false, reason: `${root}/t3 --version failed (exit 127)` };
542 },
543 ensureNodePty: (_distro, root) => {
544 observedNodePtyRoots.push(root);
545 return { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" };
546 },
547 }),
548 },
549 ({ mountedAppRoot, mountedEntryPath }) =>
550 Effect.gen(function* () {
551 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
552 const config = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
553
554 assert.deepEqual(observedProbeRoots, [stagedAppRoot]);
555 assert.deepEqual(observedNodePtyRoots, [mountedAppRoot]);
556 assert.include(config.args, "/usr/bin/node");
557 assert.include(config.args, `${mountedAppRoot}/apps/server/dist/bin.mjs`);
558 assert.notInclude(config.args, `${stagedAppRoot}/t3`);
559 assert.equal(config.entryPath, mountedEntryPath);
560 assert.isUndefined(config.wslRuntimeId);
561 assert.isTrue(Option.isNone(config.preflightFailure));
562 assert.deepEqual(invalidatedRuntimeIds, [`sha256-${archiveHash}`]);
563 }),
564 );
565 });
566
567 it.effect("resolveWsl keeps WSL retryable when the mounted fallback fails transiently", () => {
568 const stagedAppRoot = "/home/test/.t3/wsl-runtime/cache";
569 const invalidatedRuntimeIds: string[] = [];
570 return withPackagedWslHarness(
571 {
572 archiveHash: "f".repeat(64),
573 wsl: () => ({
574 prepareRuntime: () => ({ ok: true, linuxAppRoot: stagedAppRoot }),
575 invalidateRuntime: (_distro, runtimeId) =>
576 Effect.sync(() => {
577 invalidatedRuntimeIds.push(runtimeId);
578 }),
579 probeRuntime: () => ({ ok: false, reason: "t3 --version failed (exit 1)" }),
580 ensureNodePty: () => ({
581 ok: false,
582 reason: "WSL backend preflight timed out while probing for Node.js.",
583 fatal: false,
584 }),
585 }),
586 },
587 () =>
588 Effect.gen(function* () {
589 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
590 const config = yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
591 const failure = Option.getOrThrow(config.preflightFailure);
592
593 assert.isFalse(failure.fatal);
594 assert.equal(failure.retryLimit, 12);
595 assert.include(failure.reason, "timed out");
596 assert.deepEqual(invalidatedRuntimeIds, []);
597 }),
598 );
599 });
600
601 it.effect(
602 "resolveWsl preserves inherited PATH with quote-sensitive values as separate args",
603 () =>
604 Effect.gen(function* () {
605 const fileSystem = yield* FileSystem.FileSystem;
606 const path = yield* Path.Path;
607 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
608 prefix: "t3-desktop-backend-config-test-",
609 });
610 const entryPath = path.join(baseDir, "apps/server/dist/bin.mjs");
611 yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
612 yield* fileSystem.writeFileString(entryPath, "");
613
614 const nodePath = "/home/test user's/.nvm/versions/node/v22.0.0/bin/node";
615 const linuxAppRoot = "/tmp/t3 code's launch";
616 const linuxEntryPath = `${linuxAppRoot}/apps/server/dist/bin.mjs`;
617 const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
618 const devServerUrl = "http://127.0.0.1:5733/dev%20assets/?label=hello%20world";
619 const config = yield* Effect.gen(function* () {
620 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
621 return yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
622 }).pipe(
623 Effect.provide(
624 layerBackendConfiguration().pipe(
625 Layer.provideMerge(layerServerExposure),
626 Layer.provideMerge(DesktopAppSettings.layerTest()),
627 Layer.provideMerge(DesktopWslServerTree.layerTest()),
628 Layer.provideMerge(
629 DesktopWslEnvironment.layerTest({
630 isAvailable: true,
631 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
632 windowsToWslPath: () => Option.some(linuxAppRoot),
633 ensureNodePty: () => ({ ok: true, nodePath, resolvedPath }),
634 getDistroIp: () => Option.some("172.27.0.99"),
635 }),
636 ),
637 Layer.provideMerge(
638 layerEnvironment(baseDir, {
639 appPath: baseDir,
640 devServerUrl,
641 isPackaged: true,
642 platform: "win32",
643 resourcesPath: baseDir,
644 }),
645 ),
646 ),
647 ),
648 );
649
650 assert.equal(config.bootstrapDelivery, "stdin");
651 assert.deepEqual(config.args, [
652 "-d",
653 "Ubuntu",
654 "--exec",
655 "env",
656 "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",
657 nodePath,
658 linuxEntryPath,
659 "--bootstrap-fd",
660 "0",
661 "--dev-url",
662 devServerUrl,
663 ]);
664 assert.notInclude(config.args, "bash");
665 assert.notInclude(config.args, "/bin/sh");
666 assert.notInclude(config.args, "-c");
667 assert.isTrue(Option.isNone(config.preflightFailure));
668 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
669 );
670
671 it.effect("resolvePrimary and resolveWsl share one token under concurrent resolution", () =>
672 withHarness(
673 Effect.gen(function* () {
674 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
675
676 const [primary, wsl] = yield* Effect.all(
677 [configuration.resolvePrimary, configuration.resolveWsl({ port: 5000, distro: null })],
678 { concurrency: "unbounded" },
679 );
680
681 assert.equal(wsl.bootstrap.desktopBootstrapToken, primary.bootstrap.desktopBootstrapToken);
682 }),
683 ),
684 );
685
686 it.effect("resolveWsl carries the kill switch and resource attributes into the distro", () =>
687 Effect.gen(function* () {
688 const fileSystem = yield* FileSystem.FileSystem;
689 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
690 prefix: "t3-desktop-backend-config-test-",
691 });
692
693 yield* Effect.gen(function* () {
694 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
695 const config = yield* configuration.resolveWsl({ port: 5050, distro: null });
696
697 assert.equal(config.env.OTEL_SDK_DISABLED, "true");
698 assert.include((config.env.WSLENV ?? "").split(":"), "OTEL_SDK_DISABLED");
699 assert.equal(config.env.T3CODE_TELEMETRY_ENABLED, "false");
700 assert.include((config.env.WSLENV ?? "").split(":"), "T3CODE_TELEMETRY_ENABLED");
701 assert.equal(config.env.OTEL_RESOURCE_ATTRIBUTES, "deployment.environment.name=staging");
702 assert.include((config.env.WSLENV ?? "").split(":"), "OTEL_RESOURCE_ATTRIBUTES");
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 Effect.provideService(HostProcess.Environment, {
720 OTEL_SDK_DISABLED: "true",
721 T3CODE_TELEMETRY_ENABLED: "false",
722 OTEL_RESOURCE_ATTRIBUTES: "deployment.environment.name=staging",
723 }),
724 );
725 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
726 );
727
728 it.effect("resolveWsl preserves existing WSLENV entries when forwarding backend secrets", () =>
729 Effect.gen(function* () {
730 const fileSystem = yield* FileSystem.FileSystem;
731 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
732 prefix: "t3-desktop-backend-config-test-",
733 });
734
735 yield* Effect.gen(function* () {
736 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
737 const config = yield* configuration.resolveWsl({ port: 5050, distro: null });
738
739 assert.equal(config.executablePath, "wsl.exe");
740 assert.equal(config.bootstrap.port, 5050);
741 assert.equal(config.bootstrap.host, "0.0.0.0");
742 assert.equal(config.bootstrap.tailscaleServeEnabled, false);
743 assert.notProperty(config.bootstrap, "desktopTelemetryFd");
744 assert.notProperty(config.bootstrap, "resourceMonitorPath");
745 assert.equal(config.httpBaseUrl.href, "http://172.27.0.99:5050/");
746 assert.equal(config.env.OPENAI_API_KEY, "openai-key");
747 assert.equal(config.env.ANTHROPIC_API_KEY, "anthropic-key");
748 assert.equal(config.env.T3CODE_OTLP_PROTOCOL, "http/protobuf");
749 assert.equal(
750 config.env.WSLENV,
751 "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:ANTHROPIC_API_KEY:T3CODE_OTLP_HEADERS:T3CODE_OTLP_PROTOCOL",
752 );
753 }).pipe(
754 Effect.provide(
755 layerBackendConfiguration().pipe(
756 Layer.provideMerge(layerServerExposure),
757 Layer.provideMerge(DesktopAppSettings.layerTest()),
758 Layer.provideMerge(DesktopWslServerTree.layerTest()),
759 Layer.provideMerge(
760 DesktopWslEnvironment.layerTest({
761 isAvailable: true,
762 windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"),
763 getDistroIp: () => Option.some("172.27.0.99"),
764 }),
765 ),
766 Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })),
767 ),
768 ),
769 Effect.provideService(HostProcess.Environment, {
770 WSLENV: "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u",
771 OPENAI_API_KEY: "openai-key",
772 ANTHROPIC_API_KEY: "anthropic-key",
773 T3CODE_OTLP_HEADERS: 'authorization="Bearer%20my-token"',
774 T3CODE_OTLP_PROTOCOL: "http/protobuf",
775 }),
776 );
777 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
778 );
779
780 it.effect(
781 "resolvePrimary falls back to the Windows primary when wsl-only but WSL is unavailable",
782 () =>
783 Effect.gen(function* () {
784 const fileSystem = yield* FileSystem.FileSystem;
785 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
786 prefix: "t3-desktop-backend-config-test-",
787 });
788
789 yield* Effect.gen(function* () {
790 const environment = yield* DesktopEnvironment.DesktopEnvironment;
791 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
792 const config = yield* configuration.resolvePrimary;
793
794 assert.equal(config.executablePath, process.execPath);
795 assert.equal(config.bootstrap.t3Home, environment.baseDir);
796 assert.isTrue(Option.isNone(config.preflightFailure));
797 }).pipe(
798 Effect.provide(
799 layerBackendConfiguration().pipe(
800 Layer.provideMerge(layerServerExposure),
801 Layer.provideMerge(
802 DesktopAppSettings.layerTest({
803 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
804 wslBackendEnabled: true,
805 wslOnly: true,
806 }),
807 ),
808 Layer.provideMerge(DesktopWslServerTree.layerTest()),
809 Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
810 Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })),
811 ),
812 ),
813 );
814 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
815 );
816
817 it.effect(
818 "resolvePrimary marks a removed persisted WSL distro as a fatal preflight failure",
819 () =>
820 Effect.gen(function* () {
821 const fileSystem = yield* FileSystem.FileSystem;
822 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
823 prefix: "t3-desktop-backend-config-test-",
824 });
825
826 yield* Effect.gen(function* () {
827 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
828 const config = yield* configuration.resolvePrimary;
829 const failure = Option.getOrThrow(config.preflightFailure);
830
831 assert.equal(config.executablePath, "wsl.exe");
832 assert.isTrue(failure.fatal);
833 assert.include(failure.reason, "Removed-Distro");
834 }).pipe(
835 Effect.provide(
836 layerBackendConfiguration().pipe(
837 Layer.provideMerge(layerServerExposure),
838 Layer.provideMerge(
839 DesktopAppSettings.layerTest({
840 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
841 wslBackendEnabled: true,
842 wslOnly: true,
843 wslDistro: "Removed-Distro",
844 }),
845 ),
846 Layer.provideMerge(DesktopWslServerTree.layerTest()),
847 Layer.provideMerge(
848 DesktopWslEnvironment.layerTest({
849 isAvailable: true,
850 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
851 }),
852 ),
853 Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })),
854 ),
855 ),
856 );
857 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
858 );
859
860 it.effect("resolveWsl marks a missing packaged server entry as fatal", () =>
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.resolveWsl({ port: 5050, distro: "Ubuntu" });
870 const failure = Option.getOrThrow(config.preflightFailure);
871
872 assert.isTrue(failure.fatal);
873 assert.include(failure.reason, "missing server entry");
874 }).pipe(
875 Effect.provide(
876 layerBackendConfiguration().pipe(
877 Layer.provideMerge(layerServerExposure),
878 Layer.provideMerge(DesktopAppSettings.layerTest()),
879 Layer.provideMerge(DesktopWslServerTree.layerTest()),
880 Layer.provideMerge(
881 DesktopWslEnvironment.layerTest({
882 isAvailable: true,
883 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
884 }),
885 ),
886 Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })),
887 ),
888 ),
889 );
890 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
891 );
892
893 it.effect("prefers the external packaged resource monitor over the copy inside the asar", () =>
894 Effect.gen(function* () {
895 const fileSystem = yield* FileSystem.FileSystem;
896 const path = yield* Path.Path;
897 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
898 prefix: "t3-desktop-backend-config-test-",
899 });
900 const resourcesPath = path.join(baseDir, "resources");
901 const dirname = `${resourcesPath}/app.asar/apps/desktop/dist-electron`;
902 const embeddedMonitorPath = `${resourcesPath}/app.asar/apps/desktop/prod-resources/resource-monitor/t3-resource-monitor`;
903 const monitorPath = path.join(resourcesPath, "resource-monitor/t3-resource-monitor");
904 yield* fileSystem.makeDirectory(
905 `${resourcesPath}/app.asar/apps/desktop/prod-resources/resource-monitor`,
906 { recursive: true },
907 );
908 yield* fileSystem.makeDirectory(`${resourcesPath}/resource-monitor`, {
909 recursive: true,
910 });
911 yield* fileSystem.writeFileString(embeddedMonitorPath, "embedded");
912 yield* fileSystem.writeFileString(monitorPath, "binary");
913 yield* fileSystem.chmod(monitorPath, 0o755);
914
915 yield* Effect.gen(function* () {
916 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
917 const config = yield* configuration.resolvePrimary;
918 assert.equal(config.bootstrap.resourceMonitorPath, monitorPath);
919 assert.equal(config.bootstrap.desktopTelemetryFd, 4);
920 assert.equal(config.bootstrap.desktopTelemetryControlFd, 5);
921 }).pipe(
922 Effect.provide(
923 layerBackendConfiguration().pipe(
924 Layer.provideMerge(layerServerExposure),
925 Layer.provideMerge(DesktopAppSettings.layerTest()),
926 Layer.provideMerge(DesktopWslServerTree.layerTest()),
927 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
928 Layer.provideMerge(
929 layerEnvironment(baseDir, {
930 appPath: `${resourcesPath}/app.asar`,
931 dirname,
932 isPackaged: true,
933 resourcesPath,
934 }),
935 ),
936 ),
937 ),
938 );
939 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
940 );
941
942 it("resolvePrimaryLabel is runSync-safe against the real WSL availability probe", async () => {
943 // 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.
944 const runtime = ManagedRuntime.make(
945 layerBackendConfiguration().pipe(
946 Layer.provideMerge(layerServerExposure),
947 Layer.provideMerge(DesktopAppSettings.layerTest()),
948 Layer.provideMerge(DesktopWslServerTree.layerTest()),
949 Layer.provideMerge(DesktopWslEnvironment.layer),
950 Layer.provideMerge(DesktopManagedPolicy.layerTest()),
951 Layer.provideMerge(
952 Layer.succeed(
953 ChildProcessSpawner.ChildProcessSpawner,
954 ChildProcessSpawner.make(() =>
955 Effect.die("spawner should not be used while probing WSL availability"),
956 ),
957 ),
958 ),
959 Layer.provideMerge(layerEnvironment("/tmp/t3-wsl-isavailable", { platform: "win32" })),
960 Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
961 ),
962 );
963 try {
964 const configuration = await runtime.runPromise(
965 DesktopBackendConfiguration.DesktopBackendConfiguration,
966 );
967 // oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- Same reason: this is the synchronous resolution the IPC handler performs.
968 const label = Effect.runSync(configuration.resolvePrimaryLabel);
969 assert.equal(typeof label, "string");
970 } finally {
971 await runtime.dispose();
972 }
973 });
974});