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

DesktopBackendConfiguration.test.ts

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