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

DesktopBackendConfiguration.test.ts

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