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

DesktopBackendConfiguration.test.ts

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