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