The best way to control Claude Code, Codex and more from any computer or phone

main
ts 1,022 lines 36.1 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off
2 import * as NodeChildProcess from "node:child_process";
3 import * as NodeEvents from "node:events";
4 import * as NodeFS from "node:fs";
5 import * as NodeOS from "node:os";
6
7 import { assert, expect, it } from "@effect/vitest";
8 import * as ConfigProvider from "effect/ConfigProvider";
9 import * as Effect from "effect/Effect";
10 import * as FileSystem from "effect/FileSystem";
11 import * as Layer from "effect/Layer";
12 import * as Option from "effect/Option";
13 import * as Path from "effect/Path";
14 import * as Redacted from "effect/Redacted";
15 import * as Result from "effect/Result";
16 import * as Schema from "effect/Schema";
17
18 import {
19 DesktopBackendBootstrap,
20 type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
21 } from "@t3tools/contracts";
22 import * as NetService from "@t3tools/shared/Net";
23 import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
24 import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
25 import * as NodeServices from "@effect/platform-node/NodeServices";
26 import * as HostProcess from "@t3tools/shared/HostProcess";
27 import packageJson from "../../package.json" with { type: "json" };
28 import { ServiceLauncherHostProcess } from "../cloud/serviceLauncherClient.ts";
29 import {
30 SERVICE_LAUNCHER_CONTEXT_ENV,
31 SERVICE_LAUNCHER_PROTOCOL,
32 } from "../cloud/serviceProtocol.ts";
33 import { deriveServerPaths } from "../config.ts";
34 import { resolveServerConfig } from "./config.ts";
35
36 const deriveExplicitServerPaths = (baseDir: string, devUrl: URL | undefined) =>
37 deriveServerPaths(baseDir, devUrl, { baseDirIsExplicit: true });
38
39 const minimalDesktopFlags = (baseDir: string) => ({
40 mode: Option.some("desktop" as const),
41 port: Option.some(4888),
42 host: Option.none<string>(),
43 baseDir: Option.some(baseDir),
44 cwd: Option.none<string>(),
45 devUrl: Option.none<URL>(),
46 noBrowser: Option.none<boolean>(),
47 bootstrapFd: Option.none<number>(),
48 autoBootstrapProjectFromCwd: Option.none<boolean>(),
49 logWebSocketEvents: Option.none<boolean>(),
50 tailscaleServeEnabled: Option.none<boolean>(),
51 tailscaleServePort: Option.none<number>(),
52 lan: Option.none<boolean>(),
53 });
54
55 const encodeDesktopBootstrap = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
56 const encodeUnknownJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Unknown));
57
58 const makeDesktopBootstrap = (
59 overrides: Partial<DesktopBackendBootstrapValue> = {},
60 ): DesktopBackendBootstrapValue => ({
61 mode: "desktop",
62 noBrowser: true,
63 port: 4888,
64 t3Home: "/tmp/t3-bootstrap-home",
65 host: "127.0.0.1",
66 desktopBootstrapToken: "desktop-bootstrap-token",
67 tailscaleServeEnabled: false,
68 tailscaleServePort: 443,
69 ...overrides,
70 });
71
72 const liveProcess = Effect.acquireRelease(
73 Effect.promise(async () => {
74 const child = NodeChildProcess.spawn(process.execPath, ["-e", "process.stdin.resume()"], {
75 stdio: ["pipe", "ignore", "ignore"],
76 });
77 await NodeEvents.EventEmitter.once(child, "spawn");
78 return child;
79 }),
80 (child) =>
81 Effect.promise(async () => {
82 const exited = NodeEvents.EventEmitter.once(child, "exit");
83 child.kill();
84 await exited;
85 }),
86 );
87
88 it.layer(NodeServices.layer)("cli config resolution", (it) => {
89 const defaultObservabilityConfig = {
90 traceMinLevel: "Info",
91 traceTimingEnabled: true,
92 traceBatchWindowMs: 1_000,
93 traceMaxBytes: 10 * 1024 * 1024,
94 traceMaxFiles: 10,
95 otlpTracesUrl: undefined,
96 otlpMetricsUrl: undefined,
97 otlpLogsUrl: undefined,
98 otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
99 otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
100 otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
101 otelEnvironment: OtelEnvironment.none,
102 devAllowedOrigins: [],
103 } as const;
104
105 const openBootstrapFd = Effect.fn(function* (payload: DesktopBackendBootstrapValue) {
106 const fs = yield* FileSystem.FileSystem;
107 const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
108 const encoded = yield* encodeDesktopBootstrap(payload);
109 yield* fs.writeFileString(filePath, `${encoded}\n`);
110 return yield* Effect.acquireRelease(
111 Effect.sync(() => NodeFS.openSync(filePath, "r")),
112 // Windows cannot reopen the fd through /proc or /dev/fd, so the reader closes it.
113 (fd) =>
114 Effect.sync(() => {
115 try {
116 NodeFS.closeSync(fd);
117 } catch (error) {
118 if ((error as NodeJS.ErrnoException).code !== "EBADF") throw error;
119 }
120 }),
121 );
122 });
123
124 it.effect("keeps stale records and supervised startup out of the manual launch preflight", () =>
125 Effect.gen(function* () {
126 const fs = yield* FileSystem.FileSystem;
127 const path = yield* Path.Path;
128 const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-preflight-" });
129 const child = yield* liveProcess;
130 assert(child.pid !== undefined);
131 for (const [name, pid, mode, rejectRunningServer] of [
132 ["stale", 2_147_483_647, "web", true],
133 ["own-pid", process.pid, "web", true],
134 ["desktop", child.pid, "desktop", true],
135 ["serve", child.pid, "web", false],
136 ] as const) {
137 const baseDir = path.join(root, name);
138 const stateDir = path.join(baseDir, "userdata");
139 yield* fs.makeDirectory(stateDir, { recursive: true });
140 yield* fs.writeFileString(
141 path.join(stateDir, "server-runtime.json"),
142 yield* encodeUnknownJson({
143 version: 1,
144 pid,
145 port: 3773,
146 origin: "http://127.0.0.1:3773",
147 startedAt: "2026-10-01T00:00:00.000Z",
148 }),
149 );
150 const cwd = path.join(root, `${name}-project`);
151 const configResult = yield* resolveServerConfig(
152 {
153 ...minimalWebFlags(baseDir),
154 mode: Option.some(mode),
155 port: Option.some(8788),
156 cwd: Option.some(cwd),
157 },
158 Option.none(),
159 { rejectRunningServer },
160 ).pipe(
161 Effect.provide(
162 Layer.merge(
163 NetService.layer,
164 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
165 ),
166 ),
167 Effect.result,
168 );
169 assert(Result.isSuccess(configResult));
170 expect(configResult.success.cwd).toBe(cwd);
171 expect(yield* fs.exists(cwd)).toBe(true);
172 }
173 }),
174 );
175
176 it.effect(
177 "refuses a manual web launch when a runtime record belongs to another live process",
178 () =>
179 Effect.gen(function* () {
180 const fs = yield* FileSystem.FileSystem;
181 const path = yield* Path.Path;
182 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-preflight-live-" });
183 const child = yield* liveProcess;
184 assert(child.pid !== undefined);
185 const stateDir = path.join(baseDir, "userdata");
186 yield* fs.makeDirectory(stateDir, { recursive: true });
187 yield* fs.writeFileString(
188 path.join(stateDir, "server-runtime.json"),
189 yield* encodeUnknownJson({
190 version: 1,
191 pid: child.pid,
192 port: 3773,
193 origin: "http://127.0.0.1:3773",
194 startedAt: "2026-10-01T00:00:00.000Z",
195 }),
196 );
197 const cwd = path.join(baseDir, "project");
198 const error = yield* resolveServerConfig(
199 { ...minimalWebFlags(baseDir), cwd: Option.some(cwd) },
200 Option.none(),
201 { rejectRunningServer: true },
202 ).pipe(
203 Effect.provide(
204 Layer.merge(
205 NetService.layer,
206 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
207 ),
208 ),
209 Effect.flip,
210 );
211 expect(String(error)).toContain("A T3 Code server is already running");
212 expect(String(error)).toContain(`pid ${child.pid}`);
213 expect(yield* fs.exists(cwd)).toBe(false);
214 }),
215 );
216
217 it.effect("names the pair command for the refused server's home", () =>
218 Effect.gen(function* () {
219 const fs = yield* FileSystem.FileSystem;
220 const path = yield* Path.Path;
221 const child = yield* liveProcess;
222 assert(child.pid !== undefined);
223 for (const source of ["flag", "T3CODE_HOME", "default"] as const) {
224 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-preflight-pair-" });
225 const baseDir = source === "default" ? path.join(home, ".t3") : home;
226 const stateDir = path.join(baseDir, "userdata");
227 yield* fs.makeDirectory(stateDir, { recursive: true });
228 yield* fs.writeFileString(
229 path.join(stateDir, "server-runtime.json"),
230 yield* encodeUnknownJson({
231 version: 1,
232 pid: child.pid,
233 port: 3773,
234 origin: "http://127.0.0.1:3773",
235 startedAt: "2026-10-01T00:00:00.000Z",
236 }),
237 );
238 const error = yield* resolveServerConfig(
239 {
240 ...minimalWebFlags(baseDir),
241 baseDir: source === "flag" ? Option.some(baseDir) : Option.none(),
242 cwd: Option.some(path.join(home, "project")),
243 },
244 Option.none(),
245 { rejectRunningServer: true },
246 ).pipe(
247 Effect.provide(
248 Layer.merge(
249 NetService.layer,
250 ConfigProvider.layer(
251 ConfigProvider.fromEnv({
252 env: source === "T3CODE_HOME" ? { T3CODE_HOME: baseDir } : {},
253 }),
254 ),
255 ),
256 ),
257 Effect.provideService(HostProcess.HomeDirectory, home),
258 Effect.provideService(HostProcess.Platform, "linux"),
259 Effect.flip,
260 );
261 // A temp dir with spaces or backslashes is single-quoted for the shell.
262 const homePattern = baseDir.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
263 expect(String(error)).toMatch(
264 new RegExp(`pair --base-dir (${homePattern}|'${homePattern}')`),
265 );
266 }
267 }),
268 );
269
270 it.effect("enables a trimmed reusable auth token only for web dev mode", () =>
271 Effect.gen(function* () {
272 const baseDir = yield* FileSystem.FileSystem.pipe(
273 Effect.flatMap((fs) => fs.makeTempDirectoryScoped({ prefix: "t3-cli-dev-auth-" })),
274 );
275 const flags = {
276 mode: Option.some("web" as const),
277 port: Option.some(8788),
278 host: Option.none<string>(),
279 baseDir: Option.some(baseDir),
280 cwd: Option.none<string>(),
281 devUrl: Option.some(new URL("http://127.0.0.1:5173")),
282 noBrowser: Option.none<boolean>(),
283 bootstrapFd: Option.none<number>(),
284 autoBootstrapProjectFromCwd: Option.none<boolean>(),
285 logWebSocketEvents: Option.none<boolean>(),
286 tailscaleServeEnabled: Option.none<boolean>(),
287 tailscaleServePort: Option.none<number>(),
288 lan: Option.none<boolean>(),
289 };
290 const layerConfig = ConfigProvider.layer(
291 ConfigProvider.fromEnv({
292 env: {
293 T3CODE_DEV_AUTH_TOKEN: " reusable-dev-auth-token-that-is-long-enough ",
294 },
295 }),
296 );
297 const web = yield* resolveServerConfig(flags, Option.none()).pipe(
298 Effect.provide(Layer.mergeAll(layerConfig, NetService.layer)),
299 );
300 const desktop = yield* resolveServerConfig(
301 { ...flags, mode: Option.some("desktop" as const) },
302 Option.none(),
303 ).pipe(Effect.provide(Layer.mergeAll(layerConfig, NetService.layer)));
304
305 expect(web.devAuthToken).toBeDefined();
306 if (web.devAuthToken === undefined) {
307 return yield* Effect.die("Expected reusable dev auth token.");
308 }
309 expect(Redacted.value(web.devAuthToken)).toBe("reusable-dev-auth-token-that-is-long-enough");
310 expect(desktop.devAuthToken).toBeUndefined();
311 }),
312 );
313
314 it.effect("does not expose an invalid reusable auth token", () =>
315 Effect.gen(function* () {
316 const secret = "short-secret";
317 const baseDir = yield* FileSystem.FileSystem.pipe(
318 Effect.flatMap((fs) => fs.makeTempDirectoryScoped({ prefix: "t3-cli-dev-auth-invalid-" })),
319 );
320 const flags = {
321 mode: Option.some("web" as const),
322 port: Option.some(8788),
323 host: Option.none<string>(),
324 baseDir: Option.some(baseDir),
325 cwd: Option.none<string>(),
326 devUrl: Option.some(new URL("http://127.0.0.1:5173")),
327 noBrowser: Option.none<boolean>(),
328 bootstrapFd: Option.none<number>(),
329 autoBootstrapProjectFromCwd: Option.none<boolean>(),
330 logWebSocketEvents: Option.none<boolean>(),
331 tailscaleServeEnabled: Option.none<boolean>(),
332 tailscaleServePort: Option.none<number>(),
333 lan: Option.none<boolean>(),
334 };
335 const layerConfig = ConfigProvider.layer(
336 ConfigProvider.fromEnv({ env: { T3CODE_DEV_AUTH_TOKEN: secret } }),
337 );
338 const error = yield* resolveServerConfig(flags, Option.none()).pipe(
339 Effect.provide(Layer.mergeAll(layerConfig, NetService.layer)),
340 Effect.flip,
341 );
342 const desktop = yield* resolveServerConfig(
343 { ...flags, mode: Option.some("desktop" as const) },
344 Option.none(),
345 ).pipe(Effect.provide(Layer.mergeAll(layerConfig, NetService.layer)));
346 const staticWeb = yield* resolveServerConfig(
347 { ...flags, devUrl: Option.none() },
348 Option.none(),
349 ).pipe(Effect.provide(Layer.mergeAll(layerConfig, NetService.layer)));
350
351 expect(String(error)).not.toContain(secret);
352 const serialized = yield* encodeUnknownJson(error);
353 expect(serialized).not.toContain(secret);
354 expect(desktop.devAuthToken).toBeUndefined();
355 expect(staticWeb.devAuthToken).toBeUndefined();
356 }),
357 );
358
359 it.effect("preserves explicit false CLI boolean flags over env and bootstrap values", () =>
360 Effect.gen(function* () {
361 const { join } = yield* Path.Path;
362 const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-false-flags");
363 const fd = yield* openBootstrapFd(
364 makeDesktopBootstrap({
365 noBrowser: true,
366 tailscaleServeEnabled: false,
367 tailscaleServePort: 443,
368 }),
369 );
370 const derivedPaths = yield* deriveExplicitServerPaths(
371 baseDir,
372 new URL("http://127.0.0.1:4173"),
373 );
374
375 const resolved = yield* resolveServerConfig(
376 {
377 mode: Option.some("web"),
378 port: Option.some(8788),
379 host: Option.some("127.0.0.1"),
380 baseDir: Option.some(baseDir),
381 cwd: Option.none(),
382 devUrl: Option.some(new URL("http://127.0.0.1:4173")),
383 noBrowser: Option.some(false),
384 bootstrapFd: Option.none(),
385 autoBootstrapProjectFromCwd: Option.some(false),
386 logWebSocketEvents: Option.some(false),
387 tailscaleServeEnabled: Option.none(),
388 tailscaleServePort: Option.none(),
389 lan: Option.none(),
390 },
391 Option.none(),
392 ).pipe(
393 Effect.provide(
394 Layer.mergeAll(
395 ConfigProvider.layer(
396 ConfigProvider.fromEnv({
397 env: {
398 T3CODE_BOOTSTRAP_FD: String(fd),
399 T3CODE_NO_BROWSER: "true",
400 T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
401 T3CODE_LOG_WS_EVENTS: "true",
402 },
403 }),
404 ),
405 NetService.layer,
406 ),
407 ),
408 );
409
410 expect(resolved).toEqual({
411 logLevel: "Info",
412 ...defaultObservabilityConfig,
413 mode: "web",
414 port: 8788,
415 cwd: process.cwd(),
416 baseDir,
417 ...derivedPaths,
418 host: "127.0.0.1",
419 staticDir: undefined,
420 devUrl: new URL("http://127.0.0.1:4173"),
421 noBrowser: false,
422 startupPresentation: "browser",
423 desktopBootstrapToken: "desktop-bootstrap-token",
424 autoBootstrapProjectFromCwd: false,
425 logWebSocketEvents: false,
426 tailscaleServeEnabled: false,
427 tailscaleServePort: 443,
428 });
429 }),
430 );
431
432 it.effect("applies flag then env precedence over bootstrap envelope values", () =>
433 Effect.gen(function* () {
434 const { join } = yield* Path.Path;
435 const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-env-wins");
436 const fd = yield* openBootstrapFd(
437 makeDesktopBootstrap({
438 port: 4888,
439 host: "127.0.0.2",
440 t3Home: "/tmp/t3-bootstrap-home",
441 noBrowser: false,
442 desktopBootstrapToken: "desktop-token",
443 tailscaleServeEnabled: false,
444 tailscaleServePort: 443,
445 }),
446 );
447 const derivedPaths = yield* deriveExplicitServerPaths(
448 baseDir,
449 new URL("http://127.0.0.1:4173"),
450 );
451
452 const resolved = yield* resolveServerConfig(
453 {
454 mode: Option.none(),
455 port: Option.some(8788),
456 host: Option.some("127.0.0.1"),
457 baseDir: Option.none(),
458 cwd: Option.none(),
459 devUrl: Option.some(new URL("http://127.0.0.1:4173")),
460 noBrowser: Option.none(),
461 bootstrapFd: Option.none(),
462 autoBootstrapProjectFromCwd: Option.none(),
463 logWebSocketEvents: Option.none(),
464 tailscaleServeEnabled: Option.none(),
465 tailscaleServePort: Option.none(),
466 lan: Option.none(),
467 },
468 Option.some("Debug"),
469 ).pipe(
470 Effect.provide(
471 Layer.mergeAll(
472 ConfigProvider.layer(
473 ConfigProvider.fromEnv({
474 env: {
475 T3CODE_MODE: "web",
476 T3CODE_BOOTSTRAP_FD: String(fd),
477 T3CODE_HOME: baseDir,
478 T3CODE_NO_BROWSER: "true",
479 T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
480 T3CODE_LOG_WS_EVENTS: "true",
481 },
482 }),
483 ),
484 NetService.layer,
485 ),
486 ),
487 );
488
489 expect(resolved).toEqual({
490 logLevel: "Debug",
491 ...defaultObservabilityConfig,
492 mode: "web",
493 port: 8788,
494 cwd: process.cwd(),
495 baseDir,
496 ...derivedPaths,
497 host: "127.0.0.1",
498 staticDir: undefined,
499 devUrl: new URL("http://127.0.0.1:4173"),
500 noBrowser: true,
501 startupPresentation: "browser",
502 desktopBootstrapToken: "desktop-token",
503 autoBootstrapProjectFromCwd: true,
504 logWebSocketEvents: true,
505 tailscaleServeEnabled: false,
506 tailscaleServePort: 443,
507 });
508 }),
509 );
510
511 it.effect("reports the desktop bootstrap as the source of endpoints it supplied", () =>
512 Effect.gen(function* () {
513 const fs = yield* FileSystem.FileSystem;
514 const baseDir = yield* fs.makeTempDirectoryScoped({
515 prefix: "t3-cli-config-otlp-bootstrap-",
516 });
517 const fd = yield* openBootstrapFd(
518 makeDesktopBootstrap({
519 otlpTracesUrl: "http://localhost:4318/v1/traces",
520 otlpMetricsUrl: "http://localhost:4318/v1/metrics",
521 otlpLogsUrl: "http://localhost:4318/v1/logs",
522 }),
523 );
524
525 const resolved = yield* resolveServerConfig(
526 { ...minimalDesktopFlags(baseDir), bootstrapFd: Option.some(fd) },
527 Option.none(),
528 ).pipe(
529 Effect.provide(
530 Layer.mergeAll(
531 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
532 NetService.layer,
533 ),
534 ),
535 );
536
537 expect(resolved).toMatchObject({
538 otlpTracesUrl: "http://localhost:4318/v1/traces",
539 otlpTracesSource: "bootstrap",
540 otlpMetricsSource: "bootstrap",
541 otlpLogsSource: "bootstrap",
542 });
543 }),
544 );
545
546 it.effect("reports saved settings as the source of endpoints read from settings.json", () =>
547 Effect.gen(function* () {
548 const fs = yield* FileSystem.FileSystem;
549 const path = yield* Path.Path;
550 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-otlp-settings-" });
551 const derivedPaths = yield* deriveExplicitServerPaths(baseDir, undefined);
552 yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
553 yield* fs.writeFileString(
554 derivedPaths.settingsPath,
555 `${JSON.stringify({
556 observability: {
557 otlpTracesUrl: "http://localhost:4318/v1/traces",
558 otlpMetricsUrl: "http://localhost:4318/v1/metrics",
559 otlpLogsUrl: "http://localhost:4318/v1/logs",
560 },
561 })}\n`,
562 );
563
564 const resolved = yield* resolveServerConfig(minimalDesktopFlags(baseDir), Option.none()).pipe(
565 Effect.provide(
566 Layer.mergeAll(
567 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
568 NetService.layer,
569 ),
570 ),
571 );
572
573 expect(resolved).toMatchObject({
574 otlpTracesUrl: "http://localhost:4318/v1/traces",
575 otlpTracesSource: "settings",
576 otlpMetricsSource: "settings",
577 otlpLogsSource: "settings",
578 });
579 }),
580 );
581
582 it.effect("zeroes an endpoint stored in Settings when the SDK is disabled", () =>
583 Effect.gen(function* () {
584 const fs = yield* FileSystem.FileSystem;
585 const path = yield* Path.Path;
586 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-otel-off-" });
587 const derivedPaths = yield* deriveExplicitServerPaths(baseDir, undefined);
588 yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
589 yield* fs.writeFileString(
590 derivedPaths.settingsPath,
591 `${JSON.stringify({
592 observability: {
593 otlpTracesUrl: "http://localhost:4318/v1/traces",
594 otlpMetricsUrl: "http://localhost:4318/v1/metrics",
595 otlpLogsUrl: "http://localhost:4318/v1/logs",
596 },
597 })}\n`,
598 );
599
600 const resolved = yield* resolveServerConfig(
601 {
602 mode: Option.some("desktop"),
603 port: Option.some(4888),
604 host: Option.none(),
605 baseDir: Option.some(baseDir),
606 cwd: Option.none(),
607 devUrl: Option.none(),
608 noBrowser: Option.none(),
609 bootstrapFd: Option.none(),
610 autoBootstrapProjectFromCwd: Option.none(),
611 logWebSocketEvents: Option.none(),
612 tailscaleServeEnabled: Option.none(),
613 tailscaleServePort: Option.none(),
614 lan: Option.none(),
615 },
616 Option.none(),
617 ).pipe(
618 Effect.provide(
619 Layer.mergeAll(
620 ConfigProvider.layer(ConfigProvider.fromEnv({ env: { OTEL_SDK_DISABLED: "true" } })),
621 NetService.layer,
622 ),
623 ),
624 );
625
626 expect(resolved.otlpTracesUrl).toBeUndefined();
627 expect(resolved.otlpMetricsUrl).toBeUndefined();
628 expect(resolved.otlpLogsUrl).toBeUndefined();
629 expect(resolved.otelEnvironment.disabled).toBe(true);
630 }),
631 );
632
633 it.effect("lets T3CODE_OTEL_SDK_DISABLED=false override an ambient OTEL_SDK_DISABLED=true", () =>
634 Effect.gen(function* () {
635 const fs = yield* FileSystem.FileSystem;
636 const path = yield* Path.Path;
637 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-otel-on-" });
638 const derivedPaths = yield* deriveExplicitServerPaths(baseDir, undefined);
639 yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
640 yield* fs.writeFileString(
641 derivedPaths.settingsPath,
642 `${JSON.stringify({
643 observability: {
644 otlpTracesUrl: "http://localhost:4318/v1/traces",
645 },
646 })}\n`,
647 );
648
649 const resolved = yield* resolveServerConfig(
650 {
651 mode: Option.some("desktop"),
652 port: Option.some(4888),
653 host: Option.none(),
654 baseDir: Option.some(baseDir),
655 cwd: Option.none(),
656 devUrl: Option.none(),
657 noBrowser: Option.none(),
658 bootstrapFd: Option.none(),
659 autoBootstrapProjectFromCwd: Option.none(),
660 logWebSocketEvents: Option.none(),
661 tailscaleServeEnabled: Option.none(),
662 tailscaleServePort: Option.none(),
663 lan: Option.none(),
664 },
665 Option.none(),
666 ).pipe(
667 Effect.provide(
668 Layer.mergeAll(
669 ConfigProvider.layer(
670 ConfigProvider.fromEnv({
671 env: { T3CODE_OTEL_SDK_DISABLED: "false", OTEL_SDK_DISABLED: "true" },
672 }),
673 ),
674 NetService.layer,
675 ),
676 ),
677 );
678
679 expect(resolved.otelEnvironment.disabled).toBe(false);
680 expect(resolved.otlpTracesUrl).toBe("http://localhost:4318/v1/traces");
681 }),
682 );
683
684 it.effect("forces noBrowser and disables auto-bootstrap for headless startup presentation", () =>
685 Effect.gen(function* () {
686 const { join } = yield* Path.Path;
687 const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-headless-base");
688 const derivedPaths = yield* deriveExplicitServerPaths(baseDir, undefined);
689
690 const resolved = yield* resolveServerConfig(
691 {
692 mode: Option.some("web"),
693 port: Option.some(3773),
694 host: Option.none(),
695 baseDir: Option.some(baseDir),
696 cwd: Option.none(),
697 devUrl: Option.none(),
698 noBrowser: Option.none(),
699 bootstrapFd: Option.none(),
700 autoBootstrapProjectFromCwd: Option.none(),
701 logWebSocketEvents: Option.none(),
702 tailscaleServeEnabled: Option.none(),
703 tailscaleServePort: Option.none(),
704 lan: Option.none(),
705 },
706 Option.none(),
707 {
708 startupPresentation: "headless",
709 },
710 ).pipe(
711 Effect.provide(
712 Layer.mergeAll(
713 ConfigProvider.layer(
714 ConfigProvider.fromEnv({
715 env: {
716 T3CODE_NO_BROWSER: "false",
717 T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
718 },
719 }),
720 ),
721 NetService.layer,
722 ),
723 ),
724 );
725
726 expect(resolved).toEqual({
727 logLevel: "Info",
728 ...defaultObservabilityConfig,
729 mode: "web",
730 port: 3773,
731 cwd: process.cwd(),
732 baseDir,
733 ...derivedPaths,
734 host: undefined,
735 staticDir: resolved.staticDir,
736 devUrl: undefined,
737 noBrowser: true,
738 startupPresentation: "headless",
739 desktopBootstrapToken: undefined,
740 autoBootstrapProjectFromCwd: false,
741 logWebSocketEvents: false,
742 tailscaleServeEnabled: false,
743 tailscaleServePort: 443,
744 });
745 }),
746 );
747
748 it.effect("keeps whitespace-separated pairs and literal equals signs in OTLP headers", () =>
749 Effect.gen(function* () {
750 const { join } = yield* Path.Path;
751 const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-otlp-headers-loose-base");
752
753 const resolved = yield* resolveServerConfig(
754 {
755 mode: Option.some("web"),
756 port: Option.some(3773),
757 host: Option.none(),
758 baseDir: Option.some(baseDir),
759 cwd: Option.none(),
760 devUrl: Option.none(),
761 noBrowser: Option.none(),
762 bootstrapFd: Option.none(),
763 autoBootstrapProjectFromCwd: Option.none(),
764 logWebSocketEvents: Option.none(),
765 tailscaleServeEnabled: Option.none(),
766 tailscaleServePort: Option.none(),
767 lan: Option.none(),
768 },
769 Option.none(),
770 ).pipe(
771 Effect.provide(
772 Layer.mergeAll(
773 ConfigProvider.layer(
774 ConfigProvider.fromEnv({
775 env: {
776 T3CODE_OTLP_HEADERS: "authorization=Bearer abc==, x-tenant=t3",
777 T3CODE_OTLP_TRACES_URL: "http://collector.internal:4318",
778 },
779 }),
780 ),
781 NetService.layer,
782 ),
783 ),
784 );
785
786 expect(resolved.otlpTracesExport.headers).toEqual({
787 authorization: "Bearer abc==",
788 "x-tenant": "t3",
789 });
790 expect(resolved.otlpTracesUrl).toBe("http://collector.internal:4318");
791 }),
792 );
793
794 const minimalWebFlags = (baseDir: string) => ({
795 mode: Option.some("web" as const),
796 port: Option.some(3773),
797 host: Option.none<string>(),
798 baseDir: Option.some(baseDir),
799 cwd: Option.none<string>(),
800 devUrl: Option.none<URL>(),
801 noBrowser: Option.none<boolean>(),
802 bootstrapFd: Option.none<number>(),
803 autoBootstrapProjectFromCwd: Option.none<boolean>(),
804 logWebSocketEvents: Option.none<boolean>(),
805 tailscaleServeEnabled: Option.none<boolean>(),
806 tailscaleServePort: Option.none<number>(),
807 lan: Option.none<boolean>(),
808 });
809
810 it.effect("uses the automatic port selector only when no port is configured", () =>
811 Effect.gen(function* () {
812 const baseDir = yield* FileSystem.FileSystem.pipe(
813 Effect.flatMap((fs) => fs.makeTempDirectoryScoped({ prefix: "t3-cli-auto-port-" })),
814 );
815 const selected: number[] = [];
816 const selectAutomaticPort = (preferred: number) =>
817 Effect.sync(() => {
818 selected.push(preferred);
819 return 50_123;
820 });
821 const resolvePort = (flags: {
822 readonly mode?: Option.Option<"web" | "desktop">;
823 readonly port: Option.Option<number>;
824 }) =>
825 resolveServerConfig({ ...minimalWebFlags(baseDir), ...flags }, Option.none(), {
826 selectAutomaticPort,
827 }).pipe(
828 Effect.map((config) => config.port),
829 Effect.provide(
830 Layer.merge(
831 NetService.layer,
832 ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
833 ),
834 ),
835 );
836
837 expect(yield* resolvePort({ port: Option.none() })).toBe(50_123);
838 expect(selected).toEqual([3773]);
839 expect(yield* resolvePort({ port: Option.some(8788) })).toBe(8788);
840 expect(
841 yield* resolvePort({ mode: Option.some("desktop" as const), port: Option.none() }),
842 ).toBe(3773);
843 expect(selected).toEqual([3773]);
844 }),
845 );
846
847 it.effect(
848 "resolves each signal's endpoint through T3CODE_OTLP_*_URL, an OTEL endpoint, the bootstrap envelope, and persisted Settings, in that order",
849 () =>
850 Effect.gen(function* () {
851 const fs = yield* FileSystem.FileSystem;
852 const path = yield* Path.Path;
853 const baseDir = yield* fs.makeTempDirectoryScoped({
854 prefix: "t3-cli-config-otel-precedence-",
855 });
856 const derivedPaths = yield* deriveExplicitServerPaths(baseDir, undefined);
857 yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
858 yield* fs.writeFileString(
859 derivedPaths.settingsPath,
860 `${JSON.stringify({ observability: { otlpLogsUrl: "http://settings:4318/v1/logs" } })}\n`,
861 );
862
863 const fd = yield* openBootstrapFd(
864 makeDesktopBootstrap({
865 otlpMetricsUrl: "http://bootstrap:4318/v1/metrics",
866 otlpLogsUrl: "",
867 }),
868 );
869
870 const resolved = yield* resolveServerConfig(
871 {
872 ...minimalWebFlags(baseDir),
873 mode: Option.some("desktop"),
874 port: Option.some(4888),
875 bootstrapFd: Option.some(fd),
876 },
877 Option.none(),
878 ).pipe(
879 Effect.provide(
880 Layer.mergeAll(
881 ConfigProvider.layer(
882 ConfigProvider.fromEnv({
883 env: {
884 T3CODE_OTLP_TRACES_URL: "http://t3:4318/v1/traces",
885 T3CODE_OTLP_HEADERS: "x-key=secret",
886 OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: "http://otel-traces:4318/custom",
887 OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: "http://otel-metrics:4318/custom",
888 OTEL_EXPORTER_OTLP_HEADERS: "x-key=otel",
889 },
890 }),
891 ),
892 NetService.layer,
893 ),
894 ),
895 );
896
897 expect(resolved.otlpTracesUrl).toBe("http://t3:4318/v1/traces");
898 expect(resolved.otlpTracesExport.headers).toEqual({ "x-key": "secret" });
899 expect(resolved.otlpMetricsUrl).toBe("http://otel-metrics:4318/custom");
900 expect(resolved.otlpMetricsExport).toEqual({
901 ...DEFAULT_SIGNAL_EXPORT,
902 protocol: "http/protobuf",
903 headers: { "x-key": "otel" },
904 });
905 expect(resolved.otlpLogsUrl).toBe("http://settings:4318/v1/logs");
906 expect(resolved.otlpLogsExport.headers).toEqual({ "x-key": "secret" });
907 expect(resolved).toMatchObject({
908 otlpTracesVariable: "T3CODE_OTLP_TRACES_URL",
909 otlpMetricsVariable: "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT",
910 });
911 expect(resolved.otlpLogsVariable).toBeUndefined();
912 }),
913 );
914
915 it.effect(
916 "exports nothing for a signal an OTEL endpoint claimed with a protocol or headers that do not read",
917 () =>
918 Effect.gen(function* () {
919 const fs = yield* FileSystem.FileSystem;
920 const path = yield* Path.Path;
921 const baseDir = yield* fs.makeTempDirectoryScoped({
922 prefix: "t3-cli-config-otel-off-",
923 });
924 const derivedPaths = yield* deriveExplicitServerPaths(baseDir, undefined);
925 yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
926 yield* fs.writeFileString(
927 derivedPaths.settingsPath,
928 `${JSON.stringify({ observability: { otlpLogsUrl: "http://settings:4318/v1/logs" } })}\n`,
929 );
930
931 const fd = yield* openBootstrapFd(
932 makeDesktopBootstrap({ otlpMetricsUrl: "http://bootstrap:4318/v1/metrics" }),
933 );
934
935 const resolved = yield* resolveServerConfig(
936 {
937 ...minimalWebFlags(baseDir),
938 mode: Option.some("desktop"),
939 port: Option.some(4888),
940 bootstrapFd: Option.some(fd),
941 },
942 Option.none(),
943 ).pipe(
944 Effect.provide(
945 Layer.mergeAll(
946 ConfigProvider.layer(
947 ConfigProvider.fromEnv({
948 env: {
949 T3CODE_OTLP_TRACES_URL: "http://t3:4318/v1/traces",
950 OTEL_EXPORTER_OTLP_ENDPOINT: "http://otel:4318",
951 OTEL_EXPORTER_OTLP_HEADERS: "x-key=%zz",
952 },
953 }),
954 ),
955 NetService.layer,
956 ),
957 ),
958 );
959
960 expect(resolved.otlpTracesUrl).toBe("http://t3:4318/v1/traces");
961 expect(resolved.otlpMetricsUrl).toBeUndefined();
962 expect(resolved.otlpLogsUrl).toBeUndefined();
963 }),
964 );
965
966 it.effect("listens on private networks per T3CODE_LAN, else under the service launcher", () =>
967 Effect.gen(function* () {
968 const { join } = yield* Path.Path;
969 const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-service-host");
970 const resolveHost = (input: {
971 readonly connected: boolean;
972 readonly env?: Record<string, string>;
973 }) =>
974 resolveServerConfig(minimalWebFlags(baseDir), Option.none()).pipe(
975 Effect.map(({ host, privateNetworkOnly }) => ({ host, privateNetworkOnly })),
976 Effect.provide(
977 Layer.mergeAll(
978 ConfigProvider.layer(ConfigProvider.fromEnv({ env: input.env ?? {} })),
979 NetService.layer,
980 ),
981 ),
982 Effect.provideService(HostProcess.Environment, {
983 [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify({
984 protocol: SERVICE_LAUNCHER_PROTOCOL,
985 childVersion: packageJson.version,
986 }),
987 }),
988 Effect.provideService(ServiceLauncherHostProcess, {
989 connected: input.connected,
990 send: () => false,
991 on: () => undefined,
992 off: () => undefined,
993 }),
994 );
995
996 // A service installed before T3CODE_LAN existed.
997 expect(yield* resolveHost({ connected: true })).toEqual({
998 host: "0.0.0.0",
999 privateNetworkOnly: true,
1000 });
1001 // `service.env` reaches the server as its environment.
1002 expect(yield* resolveHost({ connected: true, env: { T3CODE_HOST: "127.0.0.1" } })).toEqual({
1003 host: "127.0.0.1",
1004 privateNetworkOnly: undefined,
1005 });
1006 expect(yield* resolveHost({ connected: true, env: { T3CODE_LAN: "false" } })).toEqual({
1007 host: undefined,
1008 privateNetworkOnly: undefined,
1009 });
1010 expect(yield* resolveHost({ connected: false, env: { T3CODE_LAN: "true" } })).toEqual({
1011 host: "0.0.0.0",
1012 privateNetworkOnly: true,
1013 });
1014 // Without the launcher's IPC channel the context was inherited, e.g. by
1015 // `t3 serve` started from an agent inside the service.
1016 expect(yield* resolveHost({ connected: false })).toEqual({
1017 host: undefined,
1018 privateNetworkOnly: undefined,
1019 });
1020 }),
1021 );
1022 });