Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Logger from "effect/Logger";
7import * as ManagedRuntime from "effect/ManagedRuntime";
8import * as Option from "effect/Option";
9import * as Path from "effect/Path";
10import * as PlatformError from "effect/PlatformError";
11import * as Schema from "effect/Schema";
12import { ChildProcessSpawner } from "effect/unstable/process";
13
14import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
15import * as DesktopBackendConfiguration from "./DesktopBackendConfiguration.ts";
16import * as DesktopConfig from "../app/DesktopConfig.ts";
17import * as DesktopServerExposure from "./DesktopServerExposure.ts";
18import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
19import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
20import * as DesktopWslServerTree from "../wsl/DesktopWslServerTree.ts";
21
22const PersistedServerObservabilitySettingsDocument = Schema.Struct({
23 observability: Schema.Struct({
24 otlpTracesUrl: Schema.String,
25 otlpMetricsUrl: Schema.String,
26 }),
27});
28
29const encodePersistedServerObservabilitySettingsDocument = Schema.encodeEffect(
30 Schema.fromJsonString(PersistedServerObservabilitySettingsDocument),
31);
32
33const isDesktopBackendObservabilitySettingsReadError = Schema.is(
34 DesktopBackendConfiguration.DesktopBackendObservabilitySettingsReadError,
35);
36
37const serverExposureLayer = Layer.succeed(DesktopServerExposure.DesktopServerExposure, {
38 getState: Effect.die("unexpected getState"),
39 backendConfig: Effect.succeed({
40 port: 4888,
41 bindHost: "0.0.0.0",
42 httpBaseUrl: new URL("http://127.0.0.1:4888"),
43 tailscaleServeEnabled: true,
44 tailscaleServePort: 8443,
45 }),
46 configureFromSettings: () => Effect.die("unexpected configureFromSettings"),
47 setMode: () => Effect.die("unexpected setMode"),
48 setTailscaleServeEnabled: () => Effect.die("unexpected setTailscaleServeEnabled"),
49 getAdvertisedEndpoints: Effect.succeed([]),
50} satisfies DesktopServerExposure.DesktopServerExposure["Service"]);
51
52function makeEnvironmentLayer(
53 baseDir: string,
54 options?: {
55 readonly appPath?: string;
56 readonly dirname?: string;
57 readonly isPackaged?: boolean;
58 readonly devServerUrl?: string;
59 readonly platform?: NodeJS.Platform;
60 readonly resourcesPath?: string;
61 },
62) {
63 return DesktopEnvironment.layer({
64 dirname: options?.dirname ?? "/repo/apps/desktop/src",
65 homeDirectory: baseDir,
66 platform: options?.platform ?? "darwin",
67 processArch: "x64",
68 appVersion: "1.2.3",
69 appPath: options?.appPath ?? "/repo",
70 isPackaged: options?.isPackaged ?? true,
71 resourcesPath: options?.resourcesPath ?? "/missing/resources",
72 runningUnderArm64Translation: false,
73 }).pipe(
74 Layer.provide(
75 Layer.mergeAll(
76 NodeServices.layer,
77 DesktopConfig.layerTest({
78 T3CODE_HOME: baseDir,
79 T3CODE_PORT: "9999",
80 T3CODE_MODE: "desktop",
81 T3CODE_DESKTOP_LAN_HOST: "192.168.1.50",
82 VITE_DEV_SERVER_URL: options?.devServerUrl,
83 }),
84 ),
85 ),
86 );
87}
88
89const restoreEnv = (name: string, value: string | undefined) => {
90 if (value === undefined) {
91 delete process.env[name];
92 } else {
93 process.env[name] = value;
94 }
95};
96
97const withHarness = <A, E, R>(
98 effect: Effect.Effect<
99 A,
100 E,
101 | R
102 | DesktopEnvironment.DesktopEnvironment
103 | FileSystem.FileSystem
104 | DesktopBackendConfiguration.DesktopBackendConfiguration
105 >,
106) =>
107 Effect.gen(function* () {
108 const fileSystem = yield* FileSystem.FileSystem;
109 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
110 prefix: "t3-desktop-backend-config-test-",
111 });
112
113 return yield* effect.pipe(
114 Effect.provide(
115 DesktopBackendConfiguration.layer.pipe(
116 Layer.provideMerge(serverExposureLayer),
117 Layer.provideMerge(DesktopAppSettings.layerTest()),
118 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
119 Layer.provideMerge(DesktopWslServerTree.layerTest()),
120 Layer.provideMerge(makeEnvironmentLayer(baseDir)),
121 ),
122 ),
123 );
124 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer));
125
126describe("DesktopBackendConfiguration", () => {
127 it.effect("resolvePrimary produces a stable scoped bootstrap token", () =>
128 withHarness(
129 Effect.gen(function* () {
130 const environment = yield* DesktopEnvironment.DesktopEnvironment;
131 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
132
133 const first = yield* configuration.resolvePrimary;
134 const second = yield* configuration.resolvePrimary;
135
136 assert.equal(first.executablePath, process.execPath);
137 assert.equal(first.entryPath, environment.backendEntryPath);
138 assert.equal(first.cwd, environment.backendCwd);
139 assert.equal(first.captureOutput, true);
140 assert.equal(first.env.ELECTRON_RUN_AS_NODE, "1");
141 assert.isUndefined(first.env.T3CODE_PORT);
142 assert.isUndefined(first.env.T3CODE_MODE);
143 assert.isUndefined(first.env.T3CODE_DESKTOP_LAN_HOST);
144
145 assert.equal(first.bootstrap.mode, "desktop");
146 assert.equal(first.bootstrap.noBrowser, true);
147 assert.equal(first.bootstrap.port, 4888);
148 assert.equal(first.bootstrap.host, "0.0.0.0");
149 assert.equal(first.bootstrap.t3Home, environment.baseDir);
150 assert.equal(first.bootstrap.tailscaleServeEnabled, true);
151 assert.equal(first.bootstrap.tailscaleServePort, 8443);
152 assert.match(first.bootstrap.desktopBootstrapToken, /^[0-9a-f]{48}$/i);
153 assert.equal(second.bootstrap.desktopBootstrapToken, first.bootstrap.desktopBootstrapToken);
154 }),
155 ),
156 );
157
158 it.effect("resolvePrimary starts from server.asar without materializing the WSL tree", () =>
159 Effect.gen(function* () {
160 const fileSystem = yield* FileSystem.FileSystem;
161 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
162 prefix: "t3-desktop-backend-config-test-",
163 });
164 const resourcesPath = `${baseDir}/resources`;
165
166 const config = yield* Effect.gen(function* () {
167 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
168 return yield* configuration.resolvePrimary;
169 }).pipe(
170 Effect.provide(
171 DesktopBackendConfiguration.layer.pipe(
172 Layer.provideMerge(serverExposureLayer),
173 Layer.provideMerge(DesktopAppSettings.layerTest()),
174 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
175 Layer.provideMerge(
176 Layer.succeed(
177 DesktopWslServerTree.DesktopWslServerTree,
178 DesktopWslServerTree.DesktopWslServerTree.of({
179 ensure: Effect.die("Windows primary must not extract the WSL server tree"),
180 }),
181 ),
182 ),
183 Layer.provideMerge(
184 makeEnvironmentLayer(baseDir, {
185 appPath: `${resourcesPath}/app.asar`,
186 platform: "win32",
187 resourcesPath,
188 }),
189 ),
190 ),
191 ),
192 );
193
194 assert.equal(config.entryPath, `${resourcesPath}/server.asar/apps/server/dist/bin.mjs`);
195 assert.equal(config.env.ELECTRON_RUN_AS_NODE, "1");
196 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
197 );
198
199 it.effect("resolveWsl reuses the primary's bootstrap token", () =>
200 withHarness(
201 Effect.gen(function* () {
202 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
203
204 const primary = yield* configuration.resolvePrimary;
205 const wsl = yield* configuration.resolveWsl({ port: 5000, distro: null });
206
207 assert.equal(wsl.bootstrap.desktopBootstrapToken, primary.bootstrap.desktopBootstrapToken);
208 }),
209 ),
210 );
211
212 it.effect("resolveWsl pins a default-tracking run to the concrete default distro", () =>
213 Effect.gen(function* () {
214 const fileSystem = yield* FileSystem.FileSystem;
215 const path = yield* Path.Path;
216 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
217 prefix: "t3-desktop-backend-config-test-",
218 });
219 const entryPath = path.join(baseDir, "apps/server/dist/bin.mjs");
220 yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
221 yield* fileSystem.writeFileString(entryPath, "");
222
223 const observedDistros: Array<string | null> = [];
224 const config = yield* Effect.gen(function* () {
225 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
226 return yield* configuration.resolveWsl({ port: 5000, distro: null });
227 }).pipe(
228 Effect.provide(
229 DesktopBackendConfiguration.layer.pipe(
230 Layer.provideMerge(serverExposureLayer),
231 Layer.provideMerge(DesktopAppSettings.layerTest()),
232 Layer.provideMerge(DesktopWslServerTree.layerTest()),
233 Layer.provideMerge(
234 DesktopWslEnvironment.layerTest({
235 isAvailable: true,
236 distros: [
237 { name: "Debian", isDefault: false, version: 2 },
238 { name: "Ubuntu", isDefault: true, version: 2 },
239 ],
240 windowsToWslPath: (distro) => {
241 observedDistros.push(distro);
242 return Option.some("/repo/apps/server/dist/bin.mjs");
243 },
244 ensureNodePty: (distro) => {
245 observedDistros.push(distro);
246 return { ok: true, nodePath: "/usr/bin/node", resolvedPath: "/usr/bin:/bin" };
247 },
248 getDistroIp: (distro) => {
249 observedDistros.push(distro);
250 return Option.some("172.27.0.99");
251 },
252 }),
253 ),
254 Layer.provideMerge(
255 makeEnvironmentLayer(baseDir, {
256 appPath: baseDir,
257 platform: "win32",
258 resourcesPath: baseDir,
259 }),
260 ),
261 ),
262 ),
263 );
264
265 assert.equal(config.runningDistro, "Ubuntu");
266 assert.deepEqual(config.args.slice(0, 2), ["-d", "Ubuntu"]);
267 assert.deepEqual(observedDistros, ["Ubuntu", "Ubuntu", "Ubuntu"]);
268 assert.isTrue(Option.isNone(config.preflightFailure));
269 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
270 );
271
272 it.effect(
273 "resolveWsl preserves inherited PATH with quote-sensitive values as separate args",
274 () =>
275 Effect.gen(function* () {
276 const fileSystem = yield* FileSystem.FileSystem;
277 const path = yield* Path.Path;
278 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
279 prefix: "t3-desktop-backend-config-test-",
280 });
281 const entryPath = path.join(baseDir, "apps/server/dist/bin.mjs");
282 yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
283 yield* fileSystem.writeFileString(entryPath, "");
284
285 const nodePath = "/home/test user's/.nvm/versions/node/v22.0.0/bin/node";
286 const linuxEntryPath = "/tmp/t3 code's launch/entry file.mjs";
287 const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
288 const devServerUrl = "http://127.0.0.1:5733/dev%20assets/?label=hello%20world";
289 const config = yield* Effect.gen(function* () {
290 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
291 return yield* configuration.resolveWsl({ port: 5000, distro: "Ubuntu" });
292 }).pipe(
293 Effect.provide(
294 DesktopBackendConfiguration.layer.pipe(
295 Layer.provideMerge(serverExposureLayer),
296 Layer.provideMerge(DesktopAppSettings.layerTest()),
297 Layer.provideMerge(DesktopWslServerTree.layerTest()),
298 Layer.provideMerge(
299 DesktopWslEnvironment.layerTest({
300 isAvailable: true,
301 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
302 windowsToWslPath: () => Option.some(linuxEntryPath),
303 ensureNodePty: () => ({ ok: true, nodePath, resolvedPath }),
304 getDistroIp: () => Option.some("172.27.0.99"),
305 }),
306 ),
307 Layer.provideMerge(
308 makeEnvironmentLayer(baseDir, {
309 appPath: baseDir,
310 devServerUrl,
311 isPackaged: true,
312 platform: "win32",
313 resourcesPath: baseDir,
314 }),
315 ),
316 ),
317 ),
318 );
319
320 assert.equal(config.bootstrapDelivery, "stdin");
321 assert.deepEqual(config.args, [
322 "-d",
323 "Ubuntu",
324 "--exec",
325 "env",
326 "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",
327 nodePath,
328 linuxEntryPath,
329 "--bootstrap-fd",
330 "0",
331 "--dev-url",
332 devServerUrl,
333 ]);
334 assert.notInclude(config.args, "bash");
335 assert.notInclude(config.args, "/bin/sh");
336 assert.notInclude(config.args, "-c");
337 assert.isTrue(Option.isNone(config.preflightFailure));
338 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
339 );
340
341 it.effect("resolvePrimary and resolveWsl share one token under concurrent resolution", () =>
342 withHarness(
343 Effect.gen(function* () {
344 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
345
346 // Resolve both before any token is cached, concurrently, so the
347 // generate step (a yield point) can interleave. The atomic
348 // get-or-create must still hand both the same token; a non-atomic
349 // Ref would let each generate its own and break the shared-token
350 // invariant.
351 const [primary, wsl] = yield* Effect.all(
352 [configuration.resolvePrimary, configuration.resolveWsl({ port: 5000, distro: null })],
353 { concurrency: "unbounded" },
354 );
355
356 assert.equal(wsl.bootstrap.desktopBootstrapToken, primary.bootstrap.desktopBootstrapToken);
357 }),
358 ),
359 );
360
361 it.effect("resolvePrimary surfaces persisted backend observability endpoints", () =>
362 withHarness(
363 Effect.gen(function* () {
364 const fileSystem = yield* FileSystem.FileSystem;
365 const environment = yield* DesktopEnvironment.DesktopEnvironment;
366 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
367
368 yield* fileSystem.makeDirectory(environment.path.dirname(environment.serverSettingsPath), {
369 recursive: true,
370 });
371 yield* fileSystem.writeFileString(
372 environment.serverSettingsPath,
373 yield* encodePersistedServerObservabilitySettingsDocument({
374 observability: {
375 otlpTracesUrl: " http://127.0.0.1:4318/v1/traces ",
376 otlpMetricsUrl: " http://127.0.0.1:4318/v1/metrics ",
377 },
378 }),
379 );
380
381 const config = yield* configuration.resolvePrimary;
382 assert.equal(config.bootstrap.otlpTracesUrl, "http://127.0.0.1:4318/v1/traces");
383 assert.equal(config.bootstrap.otlpMetricsUrl, "http://127.0.0.1:4318/v1/metrics");
384 }),
385 ),
386 );
387
388 it.effect("resolvePrimary omits backend observability endpoints when settings are missing", () =>
389 withHarness(
390 Effect.gen(function* () {
391 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
392 const config = yield* configuration.resolvePrimary;
393
394 assert.isUndefined(config.bootstrap.otlpTracesUrl);
395 assert.isUndefined(config.bootstrap.otlpMetricsUrl);
396 }),
397 ),
398 );
399
400 it.effect("logs structured context when persisted observability settings cannot be read", () =>
401 Effect.gen(function* () {
402 const fileSystem = yield* FileSystem.FileSystem;
403 const path = yield* Path.Path;
404 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
405 prefix: "t3-desktop-backend-config-test-",
406 });
407 const settingsPath = path.join(baseDir, "userdata", "settings.json");
408 const cause = PlatformError.systemError({
409 _tag: "PermissionDenied",
410 module: "FileSystem",
411 method: "readFileString",
412 pathOrDescriptor: settingsPath,
413 });
414 const messages: Array<unknown> = [];
415 const logger = Logger.make(({ message }) => {
416 messages.push(message);
417 });
418 const failingFileSystemLayer = Layer.succeed(
419 FileSystem.FileSystem,
420 FileSystem.makeNoop({
421 readFileString: () => Effect.fail(cause),
422 }),
423 );
424
425 const config = yield* Effect.gen(function* () {
426 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
427 return yield* configuration.resolvePrimary;
428 }).pipe(
429 Effect.provide(
430 Layer.mergeAll(
431 DesktopBackendConfiguration.layer.pipe(
432 Layer.provideMerge(serverExposureLayer),
433 Layer.provideMerge(DesktopAppSettings.layerTest()),
434 Layer.provideMerge(DesktopWslServerTree.layerTest()),
435 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
436 Layer.provideMerge(makeEnvironmentLayer(baseDir)),
437 Layer.provideMerge(failingFileSystemLayer),
438 ),
439 Logger.layer([logger], { mergeWithExisting: false }),
440 ),
441 ),
442 );
443
444 assert.isUndefined(config.bootstrap.otlpTracesUrl);
445 assert.isUndefined(config.bootstrap.otlpMetricsUrl);
446
447 const error = messages
448 .flatMap((message) => (Array.isArray(message) ? message : [message]))
449 .find(isDesktopBackendObservabilitySettingsReadError);
450 assert.isDefined(error);
451 assert.equal(error.settingsPath, settingsPath);
452 assert.equal(error.cause, cause);
453 assert.equal(
454 error.message,
455 `Failed to read persisted backend observability settings at ${settingsPath}.`,
456 );
457 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
458 );
459
460 it.effect("resolvePrimary captures backend output in dev so child logs can be persisted", () =>
461 Effect.gen(function* () {
462 const fileSystem = yield* FileSystem.FileSystem;
463 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
464 prefix: "t3-desktop-backend-config-test-",
465 });
466
467 yield* Effect.gen(function* () {
468 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
469 const config = yield* configuration.resolvePrimary;
470 assert.equal(config.captureOutput, true);
471 }).pipe(
472 Effect.provide(
473 DesktopBackendConfiguration.layer.pipe(
474 Layer.provideMerge(serverExposureLayer),
475 Layer.provideMerge(DesktopAppSettings.layerTest()),
476 Layer.provideMerge(DesktopWslServerTree.layerTest()),
477 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
478 Layer.provideMerge(
479 makeEnvironmentLayer(baseDir, {
480 isPackaged: false,
481 devServerUrl: "http://127.0.0.1:5733",
482 }),
483 ),
484 ),
485 ),
486 );
487 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
488 );
489
490 it.effect("resolveWsl preserves existing WSLENV entries when forwarding backend secrets", () =>
491 Effect.gen(function* () {
492 const fileSystem = yield* FileSystem.FileSystem;
493 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
494 prefix: "t3-desktop-backend-config-test-",
495 });
496
497 const previousWslEnv = process.env.WSLENV;
498 const previousOpenAiKey = process.env.OPENAI_API_KEY;
499 const previousAnthropicKey = process.env.ANTHROPIC_API_KEY;
500 const previousBitbucketAccessToken = process.env.T3CODE_BITBUCKET_ACCESS_TOKEN;
501 const previousBitbucketEmail = process.env.T3CODE_BITBUCKET_EMAIL;
502 const previousBitbucketApiToken = process.env.T3CODE_BITBUCKET_API_TOKEN;
503 try {
504 process.env.WSLENV = "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u";
505 process.env.OPENAI_API_KEY = "openai-key";
506 process.env.ANTHROPIC_API_KEY = "anthropic-key";
507 process.env.T3CODE_BITBUCKET_ACCESS_TOKEN = "bitbucket-access-token";
508 process.env.T3CODE_BITBUCKET_EMAIL = "developer@example.com";
509 process.env.T3CODE_BITBUCKET_API_TOKEN = "bitbucket-api-token";
510
511 yield* Effect.gen(function* () {
512 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
513 const config = yield* configuration.resolveWsl({ port: 5050, distro: null });
514
515 assert.equal(config.executablePath, "wsl.exe");
516 assert.equal(config.bootstrap.port, 5050);
517 // Binds to 0.0.0.0 inside WSL so the backend is reachable via
518 // both wslhost-forwarded localhost and the distro's eth0 IP.
519 assert.equal(config.bootstrap.host, "0.0.0.0");
520 assert.equal(config.bootstrap.tailscaleServeEnabled, false);
521 assert.notProperty(config.bootstrap, "desktopTelemetryFd");
522 assert.notProperty(config.bootstrap, "resourceMonitorPath");
523 // httpBaseUrl uses the resolved distro IP from the test stub,
524 // not localhost — the renderer reaches the backend directly to
525 // avoid relying on wslhost forwarding.
526 assert.equal(config.httpBaseUrl.href, "http://172.27.0.99:5050/");
527 assert.equal(config.env.OPENAI_API_KEY, "openai-key");
528 assert.equal(config.env.ANTHROPIC_API_KEY, "anthropic-key");
529 assert.equal(config.env.T3CODE_BITBUCKET_ACCESS_TOKEN, "bitbucket-access-token");
530 assert.equal(config.env.T3CODE_BITBUCKET_EMAIL, "developer@example.com");
531 assert.equal(config.env.T3CODE_BITBUCKET_API_TOKEN, "bitbucket-api-token");
532 // The existing WSLENV is preserved byte-for-byte (note the empty
533 // "::" segment survives — WSL ignores it, so we don't normalize
534 // it away) and missing credentials are appended. OPENAI_API_KEY is
535 // already declared, so it isn't forwarded twice.
536 assert.equal(
537 config.env.WSLENV,
538 "GOPATH/p:OPENAI_API_KEY/u:EMPTY::AZURE_DEVOPS_EXT_PAT/u:ANTHROPIC_API_KEY:T3CODE_BITBUCKET_ACCESS_TOKEN:T3CODE_BITBUCKET_EMAIL:T3CODE_BITBUCKET_API_TOKEN",
539 );
540 }).pipe(
541 Effect.provide(
542 DesktopBackendConfiguration.layer.pipe(
543 Layer.provideMerge(serverExposureLayer),
544 Layer.provideMerge(DesktopAppSettings.layerTest()),
545 Layer.provideMerge(DesktopWslServerTree.layerTest()),
546 Layer.provideMerge(
547 DesktopWslEnvironment.layerTest({
548 isAvailable: true,
549 windowsToWslPath: () => Option.some("/mnt/c/repo/apps/server/src/index.ts"),
550 getDistroIp: () => Option.some("172.27.0.99"),
551 }),
552 ),
553 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
554 ),
555 ),
556 );
557 } finally {
558 restoreEnv("WSLENV", previousWslEnv);
559 restoreEnv("OPENAI_API_KEY", previousOpenAiKey);
560 restoreEnv("ANTHROPIC_API_KEY", previousAnthropicKey);
561 restoreEnv("T3CODE_BITBUCKET_ACCESS_TOKEN", previousBitbucketAccessToken);
562 restoreEnv("T3CODE_BITBUCKET_EMAIL", previousBitbucketEmail);
563 restoreEnv("T3CODE_BITBUCKET_API_TOKEN", previousBitbucketApiToken);
564 }
565 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
566 );
567
568 it.effect(
569 "resolvePrimary falls back to the Windows primary when wsl-only but WSL is unavailable",
570 () =>
571 Effect.gen(function* () {
572 const fileSystem = yield* FileSystem.FileSystem;
573 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
574 prefix: "t3-desktop-backend-config-test-",
575 });
576
577 yield* Effect.gen(function* () {
578 const environment = yield* DesktopEnvironment.DesktopEnvironment;
579 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
580 const config = yield* configuration.resolvePrimary;
581
582 // wsl-only is persisted but WSL is unavailable, so the primary must
583 // not spawn wsl.exe (which would loop on preflight failures while the
584 // Connections backend control is hidden). Resolve the Windows primary.
585 assert.equal(config.executablePath, process.execPath);
586 assert.equal(config.bootstrap.t3Home, environment.baseDir);
587 assert.isTrue(Option.isNone(config.preflightFailure));
588 }).pipe(
589 Effect.provide(
590 DesktopBackendConfiguration.layer.pipe(
591 Layer.provideMerge(serverExposureLayer),
592 Layer.provideMerge(
593 DesktopAppSettings.layerTest({
594 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
595 wslBackendEnabled: true,
596 wslOnly: true,
597 }),
598 ),
599 Layer.provideMerge(DesktopWslServerTree.layerTest()),
600 Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
601 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
602 ),
603 ),
604 );
605 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
606 );
607
608 it.effect(
609 "resolvePrimary marks a removed persisted WSL distro as a fatal preflight failure",
610 () =>
611 Effect.gen(function* () {
612 const fileSystem = yield* FileSystem.FileSystem;
613 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
614 prefix: "t3-desktop-backend-config-test-",
615 });
616
617 yield* Effect.gen(function* () {
618 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
619 const config = yield* configuration.resolvePrimary;
620 const failure = Option.getOrThrow(config.preflightFailure);
621
622 assert.equal(config.executablePath, "wsl.exe");
623 assert.isTrue(failure.fatal);
624 assert.include(failure.reason, "Removed-Distro");
625 }).pipe(
626 Effect.provide(
627 DesktopBackendConfiguration.layer.pipe(
628 Layer.provideMerge(serverExposureLayer),
629 Layer.provideMerge(
630 DesktopAppSettings.layerTest({
631 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
632 wslBackendEnabled: true,
633 wslOnly: true,
634 wslDistro: "Removed-Distro",
635 }),
636 ),
637 Layer.provideMerge(DesktopWslServerTree.layerTest()),
638 Layer.provideMerge(
639 DesktopWslEnvironment.layerTest({
640 isAvailable: true,
641 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
642 }),
643 ),
644 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
645 ),
646 ),
647 );
648 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
649 );
650
651 it.effect("resolveWsl keeps a transient distro-list failure retryable", () =>
652 Effect.gen(function* () {
653 const fileSystem = yield* FileSystem.FileSystem;
654 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
655 prefix: "t3-desktop-backend-config-test-",
656 });
657
658 yield* Effect.gen(function* () {
659 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
660 const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
661 const failure = Option.getOrThrow(config.preflightFailure);
662
663 assert.isFalse(failure.fatal);
664 assert.equal(failure.retryLimit, 12);
665 assert.include(failure.reason, "timed out");
666 }).pipe(
667 Effect.provide(
668 DesktopBackendConfiguration.layer.pipe(
669 Layer.provideMerge(serverExposureLayer),
670 Layer.provideMerge(DesktopAppSettings.layerTest()),
671 Layer.provideMerge(DesktopWslServerTree.layerTest()),
672 Layer.provideMerge(
673 DesktopWslEnvironment.layerTest({
674 isAvailable: true,
675 distroListError: new DesktopWslEnvironment.DesktopWslDistroListError({
676 reason: "wsl.exe --list --verbose timed out",
677 }),
678 }),
679 ),
680 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
681 ),
682 ),
683 );
684 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
685 );
686
687 it.effect("resolveWsl marks a missing packaged server entry as fatal", () =>
688 Effect.gen(function* () {
689 const fileSystem = yield* FileSystem.FileSystem;
690 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
691 prefix: "t3-desktop-backend-config-test-",
692 });
693
694 yield* Effect.gen(function* () {
695 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
696 const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
697 const failure = Option.getOrThrow(config.preflightFailure);
698
699 assert.isTrue(failure.fatal);
700 assert.include(failure.reason, "missing server entry");
701 }).pipe(
702 Effect.provide(
703 DesktopBackendConfiguration.layer.pipe(
704 Layer.provideMerge(serverExposureLayer),
705 Layer.provideMerge(DesktopAppSettings.layerTest()),
706 Layer.provideMerge(DesktopWslServerTree.layerTest()),
707 Layer.provideMerge(
708 DesktopWslEnvironment.layerTest({
709 isAvailable: true,
710 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
711 }),
712 ),
713 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
714 ),
715 ),
716 );
717 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
718 );
719
720 it.effect("resolveWsl surfaces sidecar extraction failures through typed preflight", () =>
721 Effect.gen(function* () {
722 const fileSystem = yield* FileSystem.FileSystem;
723 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
724 prefix: "t3-desktop-backend-config-test-",
725 });
726
727 yield* Effect.gen(function* () {
728 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
729 const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
730 const failure = Option.getOrThrow(config.preflightFailure);
731
732 assert.isFalse(failure.fatal);
733 assert.equal(failure.retryLimit, 12);
734 assert.include(failure.reason, "could not be extracted");
735 }).pipe(
736 Effect.provide(
737 DesktopBackendConfiguration.layer.pipe(
738 Layer.provideMerge(serverExposureLayer),
739 Layer.provideMerge(DesktopAppSettings.layerTest()),
740 Layer.provideMerge(
741 DesktopWslServerTree.layerTest({
742 result: {
743 ok: false,
744 reason: "WSL server files could not be extracted",
745 fatal: false,
746 },
747 }),
748 ),
749 Layer.provideMerge(
750 DesktopWslEnvironment.layerTest({
751 isAvailable: true,
752 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
753 }),
754 ),
755 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
756 ),
757 ),
758 );
759 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
760 );
761
762 it.effect("resolveWsl marks a missing selected distro as a fatal preflight failure", () =>
763 Effect.gen(function* () {
764 const fileSystem = yield* FileSystem.FileSystem;
765 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
766 prefix: "t3-desktop-backend-config-test-",
767 });
768
769 yield* Effect.gen(function* () {
770 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
771 const config = yield* configuration.resolveWsl({ port: 5050, distro: "Removed-Distro" });
772 const failure = Option.getOrThrow(config.preflightFailure);
773
774 assert.isTrue(failure.fatal);
775 assert.include(failure.reason, "Removed-Distro");
776 }).pipe(
777 Effect.provide(
778 DesktopBackendConfiguration.layer.pipe(
779 Layer.provideMerge(serverExposureLayer),
780 Layer.provideMerge(DesktopAppSettings.layerTest()),
781 Layer.provideMerge(DesktopWslServerTree.layerTest()),
782 Layer.provideMerge(
783 DesktopWslEnvironment.layerTest({
784 isAvailable: true,
785 distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
786 }),
787 ),
788 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
789 ),
790 ),
791 );
792 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
793 );
794
795 it.effect("resolvePrimaryLabel reports the WSL distro when wsl-only and WSL is available", () =>
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 configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
804 const label = yield* configuration.resolvePrimaryLabel;
805 assert.equal(label, "WSL (Ubuntu)");
806 }).pipe(
807 Effect.provide(
808 DesktopBackendConfiguration.layer.pipe(
809 Layer.provideMerge(serverExposureLayer),
810 Layer.provideMerge(
811 DesktopAppSettings.layerTest({
812 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
813 wslBackendEnabled: true,
814 wslOnly: true,
815 wslDistro: "Ubuntu",
816 }),
817 ),
818 Layer.provideMerge(DesktopWslServerTree.layerTest()),
819 Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
820 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
821 ),
822 ),
823 );
824 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
825 );
826
827 it.effect("prefers the external packaged resource monitor over the copy inside the asar", () =>
828 Effect.gen(function* () {
829 const fileSystem = yield* FileSystem.FileSystem;
830 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
831 prefix: "t3-desktop-backend-config-test-",
832 });
833 const resourcesPath = `${baseDir}/resources`;
834 const dirname = `${resourcesPath}/app.asar/apps/desktop/dist-electron`;
835 const embeddedMonitorPath = `${resourcesPath}/app.asar/apps/desktop/prod-resources/resource-monitor/t3-resource-monitor`;
836 const monitorPath = `${resourcesPath}/resource-monitor/t3-resource-monitor`;
837 yield* fileSystem.makeDirectory(
838 `${resourcesPath}/app.asar/apps/desktop/prod-resources/resource-monitor`,
839 { recursive: true },
840 );
841 yield* fileSystem.makeDirectory(`${resourcesPath}/resource-monitor`, {
842 recursive: true,
843 });
844 yield* fileSystem.writeFileString(embeddedMonitorPath, "embedded");
845 yield* fileSystem.writeFileString(monitorPath, "binary");
846 yield* fileSystem.chmod(monitorPath, 0o755);
847
848 yield* Effect.gen(function* () {
849 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
850 const config = yield* configuration.resolvePrimary;
851 assert.equal(config.bootstrap.resourceMonitorPath, monitorPath);
852 assert.equal(config.bootstrap.desktopTelemetryFd, 4);
853 assert.equal(config.bootstrap.desktopTelemetryControlFd, 5);
854 }).pipe(
855 Effect.provide(
856 DesktopBackendConfiguration.layer.pipe(
857 Layer.provideMerge(serverExposureLayer),
858 Layer.provideMerge(DesktopAppSettings.layerTest()),
859 Layer.provideMerge(DesktopWslServerTree.layerTest()),
860 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
861 Layer.provideMerge(
862 makeEnvironmentLayer(baseDir, {
863 appPath: `${resourcesPath}/app.asar`,
864 dirname,
865 isPackaged: true,
866 resourcesPath,
867 }),
868 ),
869 ),
870 ),
871 );
872 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
873 );
874
875 it.effect("prefers the release resource monitor when both development builds exist", () =>
876 Effect.gen(function* () {
877 const fileSystem = yield* FileSystem.FileSystem;
878 const path = yield* Path.Path;
879 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
880 prefix: "t3-desktop-backend-config-test-",
881 });
882 const dirname = path.join(baseDir, "apps/desktop/src");
883 const releaseMonitorPath = path.join(
884 baseDir,
885 "native/resource-monitor/target/release/t3-resource-monitor",
886 );
887 const debugMonitorPath = path.join(
888 baseDir,
889 "native/resource-monitor/target/debug/t3-resource-monitor",
890 );
891 yield* fileSystem.makeDirectory(path.dirname(releaseMonitorPath), { recursive: true });
892 yield* fileSystem.makeDirectory(path.dirname(debugMonitorPath), { recursive: true });
893 yield* fileSystem.writeFileString(releaseMonitorPath, "release");
894 yield* fileSystem.writeFileString(debugMonitorPath, "debug");
895
896 yield* Effect.gen(function* () {
897 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
898 const config = yield* configuration.resolvePrimary;
899 assert.equal(config.bootstrap.resourceMonitorPath, releaseMonitorPath);
900 }).pipe(
901 Effect.provide(
902 DesktopBackendConfiguration.layer.pipe(
903 Layer.provideMerge(serverExposureLayer),
904 Layer.provideMerge(DesktopAppSettings.layerTest()),
905 Layer.provideMerge(DesktopWslServerTree.layerTest()),
906 Layer.provideMerge(DesktopWslEnvironment.layerTest()),
907 Layer.provideMerge(
908 makeEnvironmentLayer(baseDir, {
909 dirname,
910 devServerUrl: "http://127.0.0.1:5733",
911 isPackaged: false,
912 }),
913 ),
914 ),
915 ),
916 );
917 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
918 );
919
920 it.effect("resolvePrimaryLabel reports the local environment on non-Windows platforms", () =>
921 withHarness(
922 Effect.gen(function* () {
923 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
924 const label = yield* configuration.resolvePrimaryLabel;
925 assert.equal(label, "Local environment");
926 }),
927 ),
928 );
929
930 it.effect("resolvePrimaryLabel reports Windows when wsl-only but WSL is unavailable", () =>
931 Effect.gen(function* () {
932 const fileSystem = yield* FileSystem.FileSystem;
933 const baseDir = yield* fileSystem.makeTempDirectoryScoped({
934 prefix: "t3-desktop-backend-config-test-",
935 });
936
937 yield* Effect.gen(function* () {
938 const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
939 // Mirrors the resolvePrimary fall-back: the label must follow the
940 // backend that actually resolves, not the persisted preference, so the
941 // env switcher can't show "WSL" for a Windows backend.
942 const label = yield* configuration.resolvePrimaryLabel;
943 assert.equal(label, "Windows");
944 }).pipe(
945 Effect.provide(
946 DesktopBackendConfiguration.layer.pipe(
947 Layer.provideMerge(serverExposureLayer),
948 Layer.provideMerge(
949 DesktopAppSettings.layerTest({
950 ...DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
951 wslBackendEnabled: true,
952 wslOnly: true,
953 wslDistro: "Ubuntu",
954 }),
955 ),
956 Layer.provideMerge(DesktopWslServerTree.layerTest()),
957 Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
958 Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
959 ),
960 ),
961 );
962 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
963 );
964
965 it("resolvePrimaryLabel is runSync-safe against the real WSL availability probe", async () => {
966 // getLocalEnvironmentBootstraps is a sync IPC method: it resolves the
967 // primary instance's lazy label through Effect.runSync. The label chains
968 // to wslEnvironment.isAvailable, whose real layer probes the filesystem.
969 // That probe must run once at layer build and expose a resolved value, not
970 // a live async effect — otherwise runSync throws in the handler. Build the
971 // real WSL layer (not the sync test stub) and resolve the label with a
972 // top-level runSync, exactly as the handler does.
973 // 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.
974 const runtime = ManagedRuntime.make(
975 DesktopBackendConfiguration.layer.pipe(
976 Layer.provideMerge(serverExposureLayer),
977 Layer.provideMerge(DesktopAppSettings.layerTest()),
978 Layer.provideMerge(DesktopWslServerTree.layerTest()),
979 Layer.provideMerge(DesktopWslEnvironment.layer),
980 // isAvailable on win32 only touches the filesystem, never the spawner,
981 // so a die-stub is enough to satisfy the layer's deps.
982 Layer.provideMerge(
983 Layer.succeed(
984 ChildProcessSpawner.ChildProcessSpawner,
985 ChildProcessSpawner.make(() =>
986 Effect.die("spawner should not be used while probing WSL availability"),
987 ),
988 ),
989 ),
990 Layer.provideMerge(makeEnvironmentLayer("/tmp/t3-wsl-isavailable", { platform: "win32" })),
991 Layer.provide(NodeServices.layer),
992 ),
993 );
994 try {
995 const configuration = await runtime.runPromise(
996 DesktopBackendConfiguration.DesktopBackendConfiguration,
997 );
998 // oxlint-disable-next-line t3code/no-manual-effect-runtime-in-tests -- Same reason: this is the synchronous resolution the IPC handler performs.
999 const label = Effect.runSync(configuration.resolvePrimaryLabel);
1000 assert.equal(typeof label, "string");
1001 } finally {
1002 await runtime.dispose();
1003 }
1004 });
1005});