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

DesktopBackendConfiguration.test.ts

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