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

DesktopBackendConfiguration.test.ts

969 lines40.0 KB

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 DesktopAppSettings from "../settings/DesktopAppSettings.ts";
23import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
24import * as DesktopWslServerTree from "../wsl/DesktopWslServerTree.ts";
25​
26const layerShellEnvironment = (prepared = true) =>
27 Layer.succeed(DesktopShellEnvironment.DesktopShellEnvironment, {
28 installIntoProcess: Effect.succeed(prepared),
29 awaitDiscovery: Effect.succeed(prepared),
30 updates: Stream.empty,
31 });
32​
33const layerBackendConfiguration = (prepared = true) =>
34 DesktopBackendConfiguration.layer.pipe(Layer.provide(layerShellEnvironment(prepared)));
35​
36const layerServerExposure = Layer.succeed(DesktopServerExposure.DesktopServerExposure, {
37 getState: Effect.die("unexpected getState"),
38 backendConfig: Effect.succeed({
39 port: 4888,
40 bindHost: "0.0.0.0",
41 httpBaseUrl: new URL("http://127.0.0.1:4888"),
42 tailscaleServeEnabled: true,
43 tailscaleServePort: 8443,
44 }),
45 configureFromSettings: () => Effect.die("unexpected configureFromSettings"),
46 setMode: () => Effect.die("unexpected setMode"),
47 setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
48 getAdvertisedEndpoints: Effect.succeed([]),
49} satisfies DesktopServerExposure.DesktopServerExposure["Service"]);
50​
51function layerEnvironment(
52 baseDir: string,
53 options?: {
54 readonly appPath?: string;
55 readonly dirname?: string;
56 readonly isPackaged?: boolean;
57 readonly devServerUrl?: string;
58 readonly platform?: NodeJS.Platform;
59 readonly resourcesPath?: string;
60 readonly appVersion?: string;
61 readonly processArch?: NodeJS.Architecture;
62 readonly otlpTracesUrl?: string;
63 readonly otlpMetricsUrl?: string;
64 readonly otlpLogsUrl?: string;
65 },
66) {
67 return DesktopEnvironment.layer({
68 dirname: options?.dirname ?? "/repo/apps/desktop/src",
69 homeDirectory: baseDir,
70 platform: options?.platform ?? "darwin",
71 processArch: options?.processArch ?? "x64",
72 appVersion: options?.appVersion ?? "1.2.3",
73 appPath: options?.appPath ?? "/repo",
74 isPackaged: options?.isPackaged ?? true,
75 resourcesPath: options?.resourcesPath ?? "/missing/resources",
76 runningUnderArm64Translation: false,
77 }).pipe(
78 Layer.provide(
79 Layer.mergeAll(
80 NodeServices.layer,
81 NodeCrypto.layer,
82 DesktopConfig.layerTest({
83 T3CODE_HOME: baseDir,
84 T3CODE_PORT: "9999",
85 T3CODE_MODE: "desktop",
86 T3CODE_DESKTOP_LAN_HOST: "192.168.1.50",
87 VITE_DEV_SERVER_URL: options?.devServerUrl,
88 T3CODE_OTLP_TRACES_URL: options?.otlpTracesUrl,
89 T3CODE_OTLP_METRICS_URL: options?.otlpMetricsUrl,
90 T3CODE_OTLP_LOGS_URL: options?.otlpLogsUrl,
91 }),
92 ),
93 ),
94 );
96​
97const withHarness = <A, E, R>(
98 effect: Effect.Effect<
99 A,
100 E,
101 | R
102 | DesktopEnvironment.DesktopEnvironment
103 | FileSystem.FileSystem
104 | DesktopBackendConfiguration.DesktopBackendConfiguration
105 >,
106 prepared = true,
107) =>
108 Effect.gen(function* () {
109 const fileSystem = yield* FileSystem.FileSystem;
110 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
111 prefix: "t3-desktop-backend-config-test-",
112 });
113​
114 return yield* effect.pipe(
115 Effect.provide(
116 layerBackendConfiguration(prepared).pipe(
117 Layer.provideMerge(layerServerExposure),
118 Layer.provideMerge(DesktopAppSettings.layerTest()),
119 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
120 Layer.provideMerge(DesktopWslServerTree.layerTest()),
121 Layer.provideMerge(layerEnvironment(baseDir)),
122 ),
123 ),
124 );
125 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)));
126​
127interface PackagedWslHarnessContext {
128 readonly baseDir: string;
129 readonly archivePath: string;
130 readonly hashPath: string;
131 readonly archiveHash: string;
132 readonly mountedAppRoot: string;
133 readonly mountedEntryPath: string;
135​
136const withPackagedWslHarness = <A, E, R>(
137 input: {
138 readonly archiveHash: string;
139 readonly wsl: (
140 context: PackagedWslHarnessContext,
141 ) => DesktopWslEnvironment.DesktopWslEnvironmentTestStub;
142 readonly forbidFallback?: string;
143 readonly cleanupLegacy?: Effect.Effect<void>;
144 readonly forbidCleanup?: string;
145 },
146 effect: (
147 context: PackagedWslHarnessContext,
148 ) => Effect.Effect<
149 A,
150 E,
151 R | FileSystem.FileSystem | Path.Path | DesktopBackendConfiguration.DesktopBackendConfiguration
152 >,
153) =>
154 Effect.gen(function* () {
155 const fileSystem = yield* FileSystem.FileSystem;
156 const path = yield* Path.Path;
157 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
158 prefix: "t3-desktop-backend-config-test-",
159 });
160 const archivePath = path.join(baseDir, "wsl-runtime.tar.gz");
161 const hashPath = `${archivePath}.sha256`;
162 const mountedAppRoot = "/mnt/c/app.asar.unpacked";
163 const mountedEntryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");
164 yield* fileSystem.makeDirectory(path.dirname(mountedEntryPath), { recursive: true });
165 yield* fileSystem.writeFileString(mountedEntryPath, "");
166 yield* fileSystem.writeFileString(archivePath, "archive");
167 yield* fileSystem.writeFileString(hashPath, `${input.archiveHash}\n`);
168​
169 const context = {
170 baseDir,
171 archivePath,
172 hashPath,
173 archiveHash: input.archiveHash,
174 mountedAppRoot,
175 mountedEntryPath,
176 } satisfies PackagedWslHarnessContext;
177 const layerServerTree = input.forbidFallback
178 ? Layer.succeed(
179 DesktopWslServerTree.DesktopWslServerTree,
180 DesktopWslServerTree.DesktopWslServerTree.of({
181 ensure: Effect.die(input.forbidFallback),
182 cleanupLegacy: input.forbidCleanup
183 ? Effect.die(input.forbidCleanup)
184 : (input.cleanupLegacy ?? Effect.void),
185 }),
186 )
187 : DesktopWslServerTree.layerTest({
188 result: { ok: true, root: path.join(baseDir, "app.asar.unpacked") },
189 cleanupLegacy: input.cleanupLegacy ?? Effect.void,
190 });
191​
192 return yield* effect(context).pipe(
193 Effect.provide(
194 layerBackendConfiguration().pipe(
195 Layer.provideMerge(layerServerExposure),
196 Layer.provideMerge(DesktopAppSettings.layerTest()),
197 Layer.provideMerge(layerServerTree),
198 Layer.provideMerge(
199 DesktopWslEnvironment.layerTest({
200 isAvailable: true,
201 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
202 windowsToWslPath: () => Option.some(mountedAppRoot),
203 getDistroIp: () => Option.some("172.27.0.99"),
204 ...input.wsl(context),
205 }),
206 ),
207 Layer.provideMerge(
208 layerEnvironment(baseDir, {
209 appPath: baseDir,
210 platform: "win32",
211 resourcesPath: baseDir,
212 }),
213 ),
214 ),
215 ),
216 );
217 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)));
218​
219describe("DesktopBackendConfiguration", () => {
220 it.effect("resolvePrimary produces a stable scoped bootstrap token", () =>
221 withHarness(
222 Effect.gen(function* () {
223 const environment = yield* DesktopEnvironment.DesktopEnvironment;
224 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
225​
226 const first = yield* configuration.resolvePrimary;
227 const second = yield* configuration.resolvePrimary;
228​
229 assert.equal(first.executablePath, process.execPath);
230 assert.deepEqual(first.args.slice(0, 3), [
231 "--require",
232 environment.compileCachePath,
233 environment.backendEntryPath,
234 ]);
235 assert.equal(first.entryPath, environment.backendEntryPath);
236 assert.equal(first.cwd, environment.backendCwd);
237 assert.equal(first.captureOutput, true);
238 assert.equal(first.env.ELECTRON_RUN_AS_NODE, "1");
239 assert.equal(first.env.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING, "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 yield* currentDesktopBootstrapToken(
259 first.bootstrap.desktopBootstrapSecret ?? "",
260 yield* Clock.currentTimeMillis,
261 ).pipe(Effect.provide(NodeCrypto.layerMac)),
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(Layer.mergeAll(NodeServices.layer, NodeCrypto.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(Layer.mergeAll(NodeServices.layer, NodeCrypto.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(Layer.mergeAll(NodeServices.layer, NodeCrypto.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 and resource attributes 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 yield* Effect.gen(function* () {
689 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
690 const config = yield* configuration.resolveWsl({ port: 5050, distro: null });
691​
692 assert.equal(config.env.OTEL_SDK_DISABLED, "true");
693 assert.include((config.env.WSLENV ?? "").split(":"), "OTEL_SDK_DISABLED");
694 assert.equal(config.env.T3CODE_TELEMETRY_ENABLED, "false");
695 assert.include((config.env.WSLENV ?? "").split(":"), "T3CODE_TELEMETRY_ENABLED");
696 assert.equal(config.env.OTEL_RESOURCE_ATTRIBUTES, "deployment.environment.name=staging");
697 assert.include((config.env.WSLENV ?? "").split(":"), "OTEL_RESOURCE_ATTRIBUTES");
698 }).pipe(
699 Effect.provide(
700 layerBackendConfiguration().pipe(
701 Layer.provideMerge(layerServerExposure),
702 Layer.provideMerge(DesktopAppSettings.layerTest()),
703 Layer.provideMerge(DesktopWslServerTree.layerTest()),
704 Layer.provideMerge(
705 DesktopWslEnvironment.layerTest({
706 isAvailable: true,
707 windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"),
708 getDistroIp: () => Option.some("172.27.0.99"),
709 }),
710 ),
711 Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })),
712 ),
713 ),
714 Effect.provideService(HostProcess.Environment, {
715 OTEL_SDK_DISABLED: "true",
716 T3CODE_TELEMETRY_ENABLED: "false",
717 OTEL_RESOURCE_ATTRIBUTES: "deployment.environment.name=staging",
718 }),
719 );
720 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
721 );
722​
723 it.effect("resolveWsl preserves existing WSLENV entries when forwarding backend secrets", () =>
724 Effect.gen(function* () {
725 const fileSystem = yield* FileSystem.FileSystem;
726 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
727 prefix: "t3-desktop-backend-config-test-",
728 });
729​
730 yield* Effect.gen(function* () {
731 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
732 const config = yield* configuration.resolveWsl({ port: 5050, distro: null });
733​
734 assert.equal(config.executablePath, "wsl.exe");
735 assert.equal(config.bootstrap.port, 5050);
736 assert.equal(config.bootstrap.host, "0.0.0.0");
737 assert.equal(config.bootstrap.tailscaleServeEnabled, false);
738 assert.notProperty(config.bootstrap, "desktopTelemetryFd");
739 assert.notProperty(config.bootstrap, "resourceMonitorPath");
740 assert.equal(config.httpBaseUrl.href, "http://172.27.0.99:5050/");
741 assert.equal(config.env.OPENAI_API_KEY, "openai-key");
742 assert.equal(config.env.ANTHROPIC_API_KEY, "anthropic-key");
743 assert.equal(config.env.T3CODE_OTLP_PROTOCOL, "http/protobuf");
744 assert.equal(
745 config.env.WSLENV,
746 "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:ANTHROPIC_API_KEY:T3CODE_OTLP_HEADERS:T3CODE_OTLP_PROTOCOL",
747 );
748 }).pipe(
749 Effect.provide(
750 layerBackendConfiguration().pipe(
751 Layer.provideMerge(layerServerExposure),
752 Layer.provideMerge(DesktopAppSettings.layerTest()),
753 Layer.provideMerge(DesktopWslServerTree.layerTest()),
754 Layer.provideMerge(
755 DesktopWslEnvironment.layerTest({
756 isAvailable: true,
757 windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"),
758 getDistroIp: () => Option.some("172.27.0.99"),
759 }),
760 ),
761 Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })),
762 ),
763 ),
764 Effect.provideService(HostProcess.Environment, {
765 WSLENV: "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u",
766 OPENAI_API_KEY: "openai-key",
767 ANTHROPIC_API_KEY: "anthropic-key",
768 T3CODE_OTLP_HEADERS: 'authorization="Bearer%20my-token"',
769 T3CODE_OTLP_PROTOCOL: "http/protobuf",
770 }),
771 );
772 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
773 );
774​
775 it.effect(
776 "resolvePrimary falls back to the Windows primary when wsl-only but WSL is unavailable",
777 () =>
778 Effect.gen(function* () {
779 const fileSystem = yield* FileSystem.FileSystem;
780 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
781 prefix: "t3-desktop-backend-config-test-",
782 });
783​
784 yield* Effect.gen(function* () {
785 const environment = yield* DesktopEnvironment.DesktopEnvironment;
786 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
787 const config = yield* configuration.resolvePrimary;
788​
789 assert.equal(config.executablePath, process.execPath);
790 assert.equal(config.bootstrap.t3Home, environment.baseDir);
791 assert.isTrue(Option.isNone(config.preflightFailure));
792 }).pipe(
793 Effect.provide(
794 layerBackendConfiguration().pipe(
795 Layer.provideMerge(layerServerExposure),
796 Layer.provideMerge(
797 DesktopAppSettings.layerTest({
798 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
799 wslBackendEnabled: true,
800 wslOnly: true,
801 }),
802 ),
803 Layer.provideMerge(DesktopWslServerTree.layerTest()),
804 Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
805 Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })),
806 ),
807 ),
808 );
809 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
810 );
811​
812 it.effect(
813 "resolvePrimary marks a removed persisted WSL distro as a fatal preflight failure",
814 () =>
815 Effect.gen(function* () {
816 const fileSystem = yield* FileSystem.FileSystem;
817 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
818 prefix: "t3-desktop-backend-config-test-",
819 });
820​
821 yield* Effect.gen(function* () {
822 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
823 const config = yield* configuration.resolvePrimary;
824 const failure = Option.getOrThrow(config.preflightFailure);
825​
826 assert.equal(config.executablePath, "wsl.exe");
827 assert.isTrue(failure.fatal);
828 assert.include(failure.reason, "Removed-Distro");
829 }).pipe(
830 Effect.provide(
831 layerBackendConfiguration().pipe(
832 Layer.provideMerge(layerServerExposure),
833 Layer.provideMerge(
834 DesktopAppSettings.layerTest({
835 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
836 wslBackendEnabled: true,
837 wslOnly: true,
838 wslDistro: "Removed-Distro",
839 }),
840 ),
841 Layer.provideMerge(DesktopWslServerTree.layerTest()),
842 Layer.provideMerge(
843 DesktopWslEnvironment.layerTest({
844 isAvailable: true,
845 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
846 }),
847 ),
848 Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })),
849 ),
850 ),
851 );
852 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
853 );
854​
855 it.effect("resolveWsl marks a missing packaged server entry as fatal", () =>
856 Effect.gen(function* () {
857 const fileSystem = yield* FileSystem.FileSystem;
858 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
859 prefix: "t3-desktop-backend-config-test-",
860 });
861​
862 yield* Effect.gen(function* () {
863 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
864 const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
865 const failure = Option.getOrThrow(config.preflightFailure);
866​
867 assert.isTrue(failure.fatal);
868 assert.include(failure.reason, "missing server entry");
869 }).pipe(
870 Effect.provide(
871 layerBackendConfiguration().pipe(
872 Layer.provideMerge(layerServerExposure),
873 Layer.provideMerge(DesktopAppSettings.layerTest()),
874 Layer.provideMerge(DesktopWslServerTree.layerTest()),
875 Layer.provideMerge(
876 DesktopWslEnvironment.layerTest({
877 isAvailable: true,
878 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
879 }),
880 ),
881 Layer.provideMerge(layerEnvironment(baseDir, { platform: "win32" })),
882 ),
883 ),
884 );
885 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
886 );
887​
888 it.effect("prefers the external packaged resource monitor over the copy inside the asar", () =>
889 Effect.gen(function* () {
890 const fileSystem = yield* FileSystem.FileSystem;
891 const path = yield* Path.Path;
892 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
893 prefix: "t3-desktop-backend-config-test-",
894 });
895 const resourcesPath = path.join(baseDir, "resources");
896 const dirname = `${resourcesPath}/app.asar/apps/desktop/dist-electron`;
897 const embeddedMonitorPath = `${resourcesPath}/app.asar/apps/desktop/prod-resources/resource-monitor/t3-resource-monitor`;
898 const monitorPath = path.join(resourcesPath, "resource-monitor/t3-resource-monitor");
899 yield* fileSystem.makeDirectory(
900 `${resourcesPath}/app.asar/apps/desktop/prod-resources/resource-monitor`,
901 { recursive: true },
902 );
903 yield* fileSystem.makeDirectory(`${resourcesPath}/resource-monitor`, {
904 recursive: true,
905 });
906 yield* fileSystem.writeFileString(embeddedMonitorPath, "embedded");
907 yield* fileSystem.writeFileString(monitorPath, "binary");
908 yield* fileSystem.chmod(monitorPath, 0o755);
909​
910 yield* Effect.gen(function* () {
911 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
912 const config = yield* configuration.resolvePrimary;
913 assert.equal(config.bootstrap.resourceMonitorPath, monitorPath);
914 assert.equal(config.bootstrap.desktopTelemetryFd, 4);
915 assert.equal(config.bootstrap.desktopTelemetryControlFd, 5);
916 }).pipe(
917 Effect.provide(
918 layerBackendConfiguration().pipe(
919 Layer.provideMerge(layerServerExposure),
920 Layer.provideMerge(DesktopAppSettings.layerTest()),
921 Layer.provideMerge(DesktopWslServerTree.layerTest()),
922 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
923 Layer.provideMerge(
924 layerEnvironment(baseDir, {
925 appPath: `${resourcesPath}/app.asar`,
926 dirname,
927 isPackaged: true,
928 resourcesPath,
929 }),
930 ),
931 ),
932 ),
933 );
934 }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))),
935 );
936​
937 it("resolvePrimaryLabel is runSync-safe against the real WSL availability probe", async () => {
938 // 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.
939 const runtime = ManagedRuntime.make(
940 layerBackendConfiguration().pipe(
941 Layer.provideMerge(layerServerExposure),
942 Layer.provideMerge(DesktopAppSettings.layerTest()),
943 Layer.provideMerge(DesktopWslServerTree.layerTest()),
944 Layer.provideMerge(DesktopWslEnvironment.layer),
945 Layer.provideMerge(DesktopManagedPolicy.layerTest()),
946 Layer.provideMerge(
947 Layer.succeed(
948 ChildProcessSpawner.ChildProcessSpawner,
949 ChildProcessSpawner.make(() =>
950 Effect.die("spawner should not be used while probing WSL availability"),
951 ),
952 ),
953 ),
954 Layer.provideMerge(layerEnvironment("/tmp/t3-wsl-isavailable", { platform: "win32" })),
955 Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
956 ),
957 );
958 try {
959 const configuration = await runtime.runPromise(
960 DesktopBackendConfiguration.DesktopBackendConfiguration,
961 );
962 // oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- Same reason: this is the synchronous resolution the IPC handler performs.
963 const label = Effect.runSync(configuration.resolvePrimaryLabel);
964 assert.equal(typeof label, "string");
965 } finally {
966 await runtime.dispose();
967 }
968 });
969});