Open History to see the last commit
1#!/usr/bin/env node
2
3import * as NodeOS from "node:os";
4
5import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import * as NetService from "@t3tools/shared/Net";
8import { resolveGitWorktreePath, resolveWorktreeT3Home } from "@t3tools/shared/devHome";
9import { HostProcessEnvironment, HostProcessWorkingDirectory } from "@t3tools/shared/hostProcess";
10import { resolveSpawnCommand } from "@t3tools/shared/shell";
11import * as Config from "effect/Config";
12import * as Effect from "effect/Effect";
13import * as Hash from "effect/Hash";
14import * as Layer from "effect/Layer";
15import * as Logger from "effect/Logger";
16import * as Option from "effect/Option";
17import * as Path from "effect/Path";
18import * as Schema from "effect/Schema";
19import { Argument, Command, Flag } from "effect/unstable/cli";
20import { ChildProcess } from "effect/unstable/process";
21
22import { type DevShareError, shareDevServer, unshareDevServer } from "./lib/dev-share.ts";
23import { loadRepoEnv } from "./lib/public-config.ts";
24
25Object.assign(process.env, loadRepoEnv());
26
27const BASE_SERVER_PORT = 13773;
28const BASE_WEB_PORT = 5733;
29const MAX_HASH_OFFSET = 3000;
30const MAX_PORT = 65535;
31const DESKTOP_DEV_LOOPBACK_HOST = "127.0.0.1";
32// HTTP(S) requests to these ports are blocked by the Fetch standard before a
33// browser reaches the network. Keep the complete list here so explicit or
34// future wider offsets cannot produce a URL that curl accepts but browsers
35// reject. https://fetch.spec.whatwg.org/#port-blocking
36const FETCH_BAD_PORTS = new Set([
37 0, 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 69, 77, 79, 87, 95, 101, 102,
38 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137, 139, 143, 161, 179, 389, 427, 465,
39 512, 513, 514, 515, 526, 530, 531, 532, 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993,
40 995, 1719, 1720, 1723, 2049, 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668,
41 6669, 6679, 6697, 10080,
42]);
43// Dev servers bind loopback, so loopback is the only interface whose
44// availability decides whether we can use a port. Probing wildcards too made
45// the runner walk away from a perfectly free port whenever something else held
46// the same number on another interface — `tailscale serve` does exactly that,
47// which silently moved the ports out from under a URL that had just been shared.
48const DEV_PORT_PROBE_HOSTS = ["127.0.0.1", "::1"] as const;
49
50/**
51 * Bind hosts on which a backend still answers `http://localhost:<port>`, which
52 * is where single-origin browser dev proxies to. Loopback and the wildcards
53 * qualify; a specific interface (e.g. a LAN IP) does not — the OS binds only
54 * that address and the proxy target goes dark.
55 */
56export function isProxiableBindHost(host: string): boolean {
57 const normalized = host.trim();
58 return (
59 normalized === "" ||
60 normalized === "localhost" ||
61 normalized === "127.0.0.1" ||
62 normalized === "::1" ||
63 normalized === "[::1]" ||
64 normalized === "0.0.0.0" ||
65 normalized === "::" ||
66 normalized === "[::]"
67 );
68}
69
70export const DEFAULT_T3_HOME = Effect.map(Effect.service(Path.Path), (path) =>
71 path.join(NodeOS.homedir(), ".t3"),
72);
73
74const MODE_ARGS = {
75 dev: [
76 "run",
77 "--filter=@t3tools/contracts",
78 "--filter=@t3tools/web",
79 "--filter=t3",
80 "--parallel",
81 "dev",
82 ],
83 "dev:server": ["run", "--filter=t3", "dev"],
84 "dev:web": ["run", "--filter=@t3tools/web", "dev"],
85 "dev:desktop": ["run", "--filter=@t3tools/desktop", "--filter=@t3tools/web", "dev"],
86} as const satisfies Record<string, ReadonlyArray<string>>;
87
88type DevMode = keyof typeof MODE_ARGS;
89/**
90 * `role` matters because only the backend honours `--host`/`T3CODE_HOST`; the
91 * web port is always loopback. Passed explicitly rather than inferred from the
92 * port number, which stops distinguishing them under a large port offset.
93 */
94type PortAvailabilityCheck<R = never> = (
95 port: number,
96 role?: "server" | "web",
97) => Effect.Effect<boolean, never, R>;
98
99const DEV_RUNNER_MODES = Object.keys(MODE_ARGS) as Array<DevMode>;
100
101export function getDevRunnerModeArgs(mode: DevMode): ReadonlyArray<string> {
102 return MODE_ARGS[mode];
103}
104
105export function isBrowserAllowedPort(port: number): boolean {
106 return !FETCH_BAD_PORTS.has(port);
107}
108
109export class DevRunnerConfigurationError extends Schema.TaggedError<DevRunnerConfigurationError>()(
110 "DevRunnerConfigurationError",
111 {
112 configKeys: Schema.Array(Schema.String),
113 cause: Schema.Defect(),
114 },
115) {
116 override get message(): string {
117 return `Failed to read dev-runner configuration: ${this.configKeys.join(", ")}.`;
118 }
119}
120
121export class DevRunnerInvalidPortOffsetError extends Schema.TaggedError<DevRunnerInvalidPortOffsetError>()(
122 "DevRunnerInvalidPortOffsetError",
123 {
124 configKey: Schema.Literal("T3CODE_PORT_OFFSET"),
125 portOffset: Schema.Number,
126 minimum: Schema.Number,
127 },
128) {
129 override get message(): string {
130 return `${this.configKey} must be at least ${this.minimum}; received ${this.portOffset}.`;
131 }
132}
133
134export class DevRunnerPortExhaustedError extends Schema.TaggedError<DevRunnerPortExhaustedError>()(
135 "DevRunnerPortExhaustedError",
136 {
137 startOffset: Schema.Number,
138 requireServerPort: Schema.Boolean,
139 requireWebPort: Schema.Boolean,
140 baseServerPort: Schema.Number,
141 baseWebPort: Schema.Number,
142 maximumPort: Schema.Number,
143 },
144) {
145 override get message(): string {
146 return `No required dev ports were available from offset ${this.startOffset} through maximum port ${this.maximumPort}.`;
147 }
148}
149
150export class DevRunnerProcessError extends Schema.TaggedError<DevRunnerProcessError>()(
151 "DevRunnerProcessError",
152 {
153 operation: Schema.Literals(["spawn", "wait-for-exit"]),
154 mode: Schema.Literals(["dev", "dev:server", "dev:web", "dev:desktop"]),
155 executable: Schema.Literal("vp"),
156 argumentCount: Schema.Number,
157 shell: Schema.Boolean,
158 cause: Schema.Defect(),
159 },
160) {
161 override get message(): string {
162 return `Dev-runner process operation "${this.operation}" failed for mode "${this.mode}".`;
163 }
164}
165
166export class DevRunnerProcessExitError extends Schema.TaggedError<DevRunnerProcessExitError>()(
167 "DevRunnerProcessExitError",
168 {
169 mode: Schema.Literals(["dev", "dev:server", "dev:web", "dev:desktop"]),
170 executable: Schema.Literal("vp"),
171 argumentCount: Schema.Number,
172 shell: Schema.Boolean,
173 exitCode: Schema.Number,
174 },
175) {
176 override get message(): string {
177 return `Dev-runner process exited with code ${this.exitCode} in mode "${this.mode}".`;
178 }
179}
180
181export class DevRunnerHostNotProxiableError extends Schema.TaggedError<DevRunnerHostNotProxiableError>()(
182 "DevRunnerHostNotProxiableError",
183 {
184 mode: Schema.Literals(["dev", "dev:web"]),
185 host: Schema.String,
186 },
187) {
188 override get message(): string {
189 return `--host ${this.host} cannot be combined with ${this.mode}: single-origin browser dev proxies the backend at localhost, and a backend bound only to ${this.host} leaves localhost unanswered, so every proxied request fails. Use a wildcard (0.0.0.0 or ::) to serve that interface and loopback together, or --share for remote access.`;
190 }
191}
192
193export const DevRunnerError = Schema.Union([
194 DevRunnerConfigurationError,
195 DevRunnerHostNotProxiableError,
196 DevRunnerInvalidPortOffsetError,
197 DevRunnerPortExhaustedError,
198 DevRunnerProcessError,
199 DevRunnerProcessExitError,
200]);
201export type DevRunnerError = typeof DevRunnerError.Type;
202export const isDevRunnerError = Schema.is(DevRunnerError);
203
204const optionalStringConfig = (name: string): Config.Config<string | undefined> =>
205 Config.string(name).pipe(
206 Config.option,
207 Config.map((value) => Option.getOrUndefined(value)),
208 );
209const optionalBooleanConfig = (name: string): Config.Config<boolean | undefined> =>
210 Config.boolean(name).pipe(
211 Config.option,
212 Config.map((value) => Option.getOrUndefined(value)),
213 );
214const optionalPortConfig = (name: string): Config.Config<number | undefined> =>
215 Config.port(name).pipe(
216 Config.option,
217 Config.map((value) => Option.getOrUndefined(value)),
218 );
219const optionalIntegerConfig = (name: string): Config.Config<number | undefined> =>
220 Config.int(name).pipe(
221 Config.option,
222 Config.map((value) => Option.getOrUndefined(value)),
223 );
224const OffsetConfig = Config.all({
225 portOffset: optionalIntegerConfig("T3CODE_PORT_OFFSET"),
226 devInstance: optionalStringConfig("T3CODE_DEV_INSTANCE"),
227});
228
229export function resolveOffset(config: {
230 readonly portOffset: number | undefined;
231 readonly devInstance: string | undefined;
232 readonly worktreePath?: string | undefined;
233}): Effect.Effect<
234 { readonly offset: number; readonly source: string },
235 DevRunnerInvalidPortOffsetError
236> {
237 if (config.portOffset !== undefined) {
238 if (config.portOffset < 0) {
239 return Effect.fail(
240 new DevRunnerInvalidPortOffsetError({
241 configKey: "T3CODE_PORT_OFFSET",
242 portOffset: config.portOffset,
243 minimum: 0,
244 }),
245 );
246 }
247 return Effect.succeed({
248 offset: config.portOffset,
249 source: `T3CODE_PORT_OFFSET=${config.portOffset}`,
250 });
251 }
252
253 const seed = config.devInstance?.trim();
254 if (seed) {
255 if (/^\d+$/.test(seed)) {
256 return Effect.succeed({
257 offset: Number(seed),
258 source: `numeric T3CODE_DEV_INSTANCE=${seed}`,
259 });
260 }
261
262 const offset = ((Hash.string(seed) >>> 0) % MAX_HASH_OFFSET) + 1;
263 return Effect.succeed({ offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` });
264 }
265
266 // Worktrees get ports derived from their path so each one is stable across
267 // restarts and distinct from its siblings. Without this every worktree starts
268 // at offset 0 and scan-collides onto whatever happens to be free that minute,
269 // so ports move under you between runs — which breaks any URL you already
270 // shared. The main checkout keeps the documented 5733/13773.
271 const worktreePath = config.worktreePath?.trim();
272 if (worktreePath) {
273 const offset = ((Hash.string(worktreePath) >>> 0) % MAX_HASH_OFFSET) + 1;
274 return Effect.succeed({ offset, source: `worktree ${worktreePath}` });
275 }
276
277 return Effect.succeed({ offset: 0, source: "default ports" });
278}
279
280function resolveBaseDir(baseDir: string | undefined): Effect.Effect<string, never, Path.Path> {
281 return Effect.gen(function* () {
282 const path = yield* Path.Path;
283 const configured = baseDir?.trim();
284
285 if (configured) {
286 return path.resolve(configured);
287 }
288
289 return yield* DEFAULT_T3_HOME;
290 });
291}
292
293interface CreateDevRunnerEnvInput {
294 readonly mode: DevMode;
295 readonly baseEnv: NodeJS.ProcessEnv;
296 readonly serverOffset: number;
297 readonly webOffset: number;
298 readonly t3Home: string | undefined;
299 readonly browser: boolean | undefined;
300 readonly autoBootstrapProjectFromCwd: boolean | undefined;
301 readonly logWebSocketEvents: boolean | undefined;
302 readonly host: string | undefined;
303 readonly port: number | undefined;
304 readonly devUrl: URL | undefined;
305}
306
307export function createDevRunnerEnv({
308 mode,
309 baseEnv,
310 serverOffset,
311 webOffset,
312 t3Home,
313 browser,
314 autoBootstrapProjectFromCwd,
315 logWebSocketEvents,
316 host,
317 port,
318 devUrl,
319}: CreateDevRunnerEnvInput): Effect.Effect<NodeJS.ProcessEnv, never, Path.Path> {
320 return Effect.gen(function* () {
321 const serverPort = port ?? BASE_SERVER_PORT + serverOffset;
322 const webPort = BASE_WEB_PORT + webOffset;
323 // Precedence (--home-dir > worktree .t3 > ambient T3CODE_HOME) is resolved
324 // by the caller; an unset t3Home here genuinely means "use the default".
325 const configuredBaseDir = t3Home?.trim() || undefined;
326 const resolvedBaseDir = yield* resolveBaseDir(configuredBaseDir);
327 const isDesktopMode = mode === "dev:desktop";
328
329 const output: NodeJS.ProcessEnv = {
330 ...baseEnv,
331 PORT: String(webPort),
332 VITE_DEV_SERVER_URL:
333 devUrl?.toString() ??
334 `http://${isDesktopMode ? DESKTOP_DEV_LOOPBACK_HOST : "localhost"}:${webPort}`,
335 };
336
337 if (configuredBaseDir !== undefined) {
338 output.T3CODE_HOME = resolvedBaseDir;
339 } else {
340 delete output.T3CODE_HOME;
341 }
342
343 // A dev-runner server is never launcher-managed. When the shell that runs
344 // this script was itself spawned by the machine's managed t3 service (an
345 // agent working inside T3 Code), these leak through and the child server
346 // fails startup with "The service launcher started a different t3 version"
347 // (serviceLauncherClient.ts resolveStartup).
348 delete output.T3_SERVICE_LAUNCHER_CONTEXT;
349 delete output.T3_BOOT_SERVICE_UNIT;
350
351 if (!isDesktopMode) {
352 output.T3CODE_PORT = String(serverPort);
353 // HOST is Vite's own bind address, and the desktop branch below is the
354 // only place we set it. An inherited one (an exported HOST, a container,
355 // a `HOST=0.0.0.0 npm start` habit) would otherwise reach Vite and pin
356 // its HMR socket to that address — see the `explicitHost` gate in
357 // apps/web/vite.config.ts. Over a shared origin that is invisible: the
358 // page loads and only HMR quietly dials the wrong machine.
359 delete output.HOST;
360 if (mode === "dev" || mode === "dev:web") {
361 // Browser dev is single-origin: everything (including /ws) is proxied
362 // through Vite, so the client must resolve its backend from
363 // window.location.origin rather than a baked-in localhost URL. See
364 // resolveConfiguredPrimaryTarget in apps/web/src/environments/primary/target.ts
365 // — it only defers to the origin when both of these are absent. Baking
366 // localhost here is what breaks any non-localhost origin (tailnet, LAN,
367 // phone): the remote browser dials its own machine.
368 delete output.VITE_HTTP_URL;
369 delete output.VITE_WS_URL;
370 // Deleting is not enough on its own: vite.config.ts calls loadRepoEnv,
371 // which merges `.env`/`.env.local` *under* this env, so a developer
372 // with either URL in their `.env` would get it back and silently lose
373 // single-origin mode. This states the intent positively so Vite can
374 // ignore those values rather than infer from their absence.
375 output.T3CODE_SINGLE_ORIGIN_DEV = "1";
376 } else {
377 output.VITE_HTTP_URL = `http://localhost:${serverPort}`;
378 output.VITE_WS_URL = `ws://localhost:${serverPort}`;
379 delete output.T3CODE_SINGLE_ORIGIN_DEV;
380 }
381 } else {
382 output.T3CODE_PORT = String(serverPort);
383 output.VITE_HTTP_URL = `http://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
384 output.VITE_WS_URL = `ws://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
385 // Desktop pins the renderer to loopback on purpose; an ambient marker
386 // must not make Vite drop those URLs.
387 delete output.T3CODE_SINGLE_ORIGIN_DEV;
388 delete output.T3CODE_MODE;
389 delete output.T3CODE_NO_BROWSER;
390 delete output.T3CODE_HOST;
391 delete output.T3CODE_DEV_AUTH_TOKEN;
392 }
393
394 if (!isDesktopMode && host !== undefined) {
395 output.T3CODE_HOST = host;
396 }
397
398 if (!isDesktopMode) {
399 output.T3CODE_NO_BROWSER = browser === true ? "0" : "1";
400 }
401
402 if (autoBootstrapProjectFromCwd !== undefined) {
403 output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD = autoBootstrapProjectFromCwd ? "1" : "0";
404 } else {
405 delete output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD;
406 }
407
408 if (logWebSocketEvents !== undefined) {
409 output.T3CODE_LOG_WS_EVENTS = logWebSocketEvents ? "1" : "0";
410 } else {
411 delete output.T3CODE_LOG_WS_EVENTS;
412 }
413
414 if (mode === "dev") {
415 output.T3CODE_MODE = "web";
416 delete output.T3CODE_DESKTOP_WS_URL;
417 }
418
419 if (mode === "dev:server" || mode === "dev:web") {
420 output.T3CODE_MODE = "web";
421 delete output.T3CODE_DESKTOP_WS_URL;
422 }
423
424 if (isDesktopMode) {
425 output.HOST = DESKTOP_DEV_LOOPBACK_HOST;
426 delete output.T3CODE_DESKTOP_WS_URL;
427 }
428
429 return output;
430 });
431}
432
433function portPairForOffset(offset: number): {
434 readonly serverPort: number;
435 readonly webPort: number;
436} {
437 return {
438 serverPort: BASE_SERVER_PORT + offset,
439 webPort: BASE_WEB_PORT + offset,
440 };
441}
442
443export function checkPortAvailabilityOnHosts<R>(
444 port: number,
445 hosts: ReadonlyArray<string>,
446 canListenOnHost: (port: number, host: string) => Effect.Effect<boolean, never, R>,
447): Effect.Effect<boolean, never, R> {
448 return Effect.gen(function* () {
449 for (const host of hosts) {
450 if (!(yield* canListenOnHost(port, host))) {
451 return false;
452 }
453 }
454
455 return true;
456 });
457}
458
459/**
460 * Hosts to probe for a dev server bound to `configuredHost`.
461 *
462 * Loopback is always checked because the web server and the desktop renderer
463 * target reach it there. When `--host`/`T3CODE_HOST` moves the backend onto
464 * another interface, that interface decides whether the bind actually
465 * succeeds — probing only loopback would hand back a port that is free here
466 * and taken there, and the server would fail to start.
467 *
468 * `configuredHost` applies to the *backend* only. Vite takes its bind address
469 * from `HOST`, which the runner sets for desktop alone, so the web port stays
470 * on loopback and must not be judged against the backend's interface —
471 * a port free on loopback but busy on that interface would otherwise be
472 * rejected for a server that was never going to bind there.
473 */
474export function devPortProbeHosts(configuredHost: string | undefined): ReadonlyArray<string> {
475 const host = configuredHost?.trim();
476 if (!host || DEV_PORT_PROBE_HOSTS.includes(host as (typeof DEV_PORT_PROBE_HOSTS)[number])) {
477 return DEV_PORT_PROBE_HOSTS;
478 }
479 return [...DEV_PORT_PROBE_HOSTS, host];
480}
481
482const makeDefaultCheckPortAvailability =
483 (configuredHost: string | undefined): PortAvailabilityCheck<NetService.NetService> =>
484 (port, role) =>
485 Effect.gen(function* () {
486 const net = yield* NetService.NetService;
487 const hosts = role === "web" ? DEV_PORT_PROBE_HOSTS : devPortProbeHosts(configuredHost);
488 return yield* checkPortAvailabilityOnHosts(port, hosts, (candidatePort, host) =>
489 net.canListenOnHost(candidatePort, host),
490 );
491 });
492
493const defaultCheckPortAvailability = makeDefaultCheckPortAvailability(undefined);
494
495interface FindFirstAvailableOffsetInput<R = NetService.NetService> {
496 readonly startOffset: number;
497 readonly requireServerPort: boolean;
498 readonly requireWebPort: boolean;
499 readonly checkPortAvailability?: PortAvailabilityCheck<R>;
500}
501
502export function findFirstAvailableOffset<R = NetService.NetService>({
503 startOffset,
504 requireServerPort,
505 requireWebPort,
506 checkPortAvailability,
507}: FindFirstAvailableOffsetInput<R>): Effect.Effect<number, DevRunnerPortExhaustedError, R> {
508 return Effect.gen(function* () {
509 const checkPort = (checkPortAvailability ??
510 defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
511
512 for (let candidate = startOffset; ; candidate += 1) {
513 const { serverPort, webPort } = portPairForOffset(candidate);
514 const serverPortOutOfRange = serverPort > MAX_PORT;
515 const webPortOutOfRange = webPort > MAX_PORT;
516
517 if (
518 (requireServerPort && serverPortOutOfRange) ||
519 (requireWebPort && webPortOutOfRange) ||
520 (!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange))
521 ) {
522 break;
523 }
524
525 if (requireWebPort && !isBrowserAllowedPort(webPort)) {
526 continue;
527 }
528
529 const checks: Array<Effect.Effect<boolean, never, R>> = [];
530 if (requireServerPort) {
531 checks.push(checkPort(serverPort, "server"));
532 }
533 if (requireWebPort) {
534 checks.push(checkPort(webPort, "web"));
535 }
536
537 if (checks.length === 0) {
538 return candidate;
539 }
540
541 const availability = yield* Effect.all(checks);
542 if (availability.every(Boolean)) {
543 return candidate;
544 }
545 }
546
547 return yield* new DevRunnerPortExhaustedError({
548 startOffset,
549 requireServerPort,
550 requireWebPort,
551 baseServerPort: BASE_SERVER_PORT,
552 baseWebPort: BASE_WEB_PORT,
553 maximumPort: MAX_PORT,
554 });
555 });
556}
557
558interface ResolveModePortOffsetsInput<R = NetService.NetService> {
559 readonly mode: DevMode;
560 readonly startOffset: number;
561 readonly hasExplicitServerPort: boolean;
562 readonly hasExplicitDevUrl: boolean;
563 readonly checkPortAvailability?: PortAvailabilityCheck<R>;
564}
565
566export function resolveModePortOffsets<R = NetService.NetService>({
567 mode,
568 startOffset,
569 hasExplicitServerPort,
570 hasExplicitDevUrl,
571 checkPortAvailability,
572}: ResolveModePortOffsetsInput<R>): Effect.Effect<
573 { readonly serverOffset: number; readonly webOffset: number },
574 DevRunnerPortExhaustedError,
575 R
576> {
577 return Effect.gen(function* () {
578 const checkPort = (checkPortAvailability ??
579 defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
580
581 if (mode === "dev:web") {
582 if (hasExplicitDevUrl) {
583 return { serverOffset: startOffset, webOffset: startOffset };
584 }
585
586 const webOffset = yield* findFirstAvailableOffset({
587 startOffset,
588 requireServerPort: false,
589 requireWebPort: true,
590 checkPortAvailability: checkPort,
591 });
592 return { serverOffset: startOffset, webOffset };
593 }
594
595 if (mode === "dev:server") {
596 if (hasExplicitServerPort) {
597 return { serverOffset: startOffset, webOffset: startOffset };
598 }
599
600 const serverOffset = yield* findFirstAvailableOffset({
601 startOffset,
602 requireServerPort: true,
603 requireWebPort: false,
604 checkPortAvailability: checkPort,
605 });
606 return { serverOffset, webOffset: serverOffset };
607 }
608
609 const sharedOffset = yield* findFirstAvailableOffset({
610 startOffset,
611 requireServerPort: !hasExplicitServerPort,
612 requireWebPort: !hasExplicitDevUrl,
613 checkPortAvailability: checkPort,
614 });
615
616 return { serverOffset: sharedOffset, webOffset: sharedOffset };
617 });
618}
619
620interface DevRunnerCliInput {
621 readonly mode: DevMode;
622 readonly t3Home: string | undefined;
623 readonly browser: boolean | undefined;
624 readonly autoBootstrapProjectFromCwd: boolean | undefined;
625 readonly logWebSocketEvents: boolean | undefined;
626 readonly host: string | undefined;
627 readonly port: number | undefined;
628 readonly devUrl: URL | undefined;
629 readonly dryRun: boolean;
630 readonly share: boolean;
631 readonly runArgs: ReadonlyArray<string>;
632}
633
634export function runDevRunnerWithInput(input: DevRunnerCliInput) {
635 return Effect.gen(function* () {
636 const { portOffset, devInstance } = yield* OffsetConfig.pipe(
637 Effect.mapError(
638 (cause) =>
639 new DevRunnerConfigurationError({
640 configKeys: ["T3CODE_PORT_OFFSET", "T3CODE_DEV_INSTANCE"],
641 cause,
642 }),
643 ),
644 );
645
646 // Single-origin browser dev proxies the backend at localhost. A wildcard
647 // bind still answers there; a specific non-loopback interface does not,
648 // which breaks every proxied request in a way that reads as "server is
649 // broken" rather than "flag combination is unsupported". Reject it up
650 // front instead. (dev:server and dev:desktop don't proxy — untouched.)
651 if (
652 (input.mode === "dev" || input.mode === "dev:web") &&
653 input.host !== undefined &&
654 !isProxiableBindHost(input.host)
655 ) {
656 return yield* new DevRunnerHostNotProxiableError({ mode: input.mode, host: input.host });
657 }
658
659 const worktreePath = yield* resolveGitWorktreePath(yield* HostProcessWorkingDirectory);
660
661 const { offset, source } = yield* resolveOffset({
662 portOffset,
663 devInstance,
664 worktreePath,
665 });
666
667 const { serverOffset, webOffset } = yield* resolveModePortOffsets({
668 mode: input.mode,
669 startOffset: offset,
670 hasExplicitServerPort: input.port !== undefined,
671 hasExplicitDevUrl: input.devUrl !== undefined,
672 // A non-loopback bind host decides whether the backend can actually take
673 // the port, so it has to be probed alongside loopback.
674 checkPortAvailability: makeDefaultCheckPortAvailability(input.host),
675 });
676
677 const hostEnvironment = yield* HostProcessEnvironment;
678 // A dev server started inside a worktree defaults to that worktree's own
679 // (gitignored) `.t3` — see @t3tools/shared/devHome for why this must
680 // outrank an ambient T3CODE_HOME. `--home-dir` still wins.
681 const worktreeHome = yield* resolveWorktreeT3Home(yield* HostProcessWorkingDirectory);
682 // Trim before choosing: `--home-dir ""` is not a selection, and treating it
683 // as one would skip the worktree default and land on the shared home —
684 // exactly the outcome this precedence exists to prevent.
685 const resolvedT3Home =
686 (input.t3Home?.trim() || undefined) ??
687 worktreeHome ??
688 (hostEnvironment.T3CODE_HOME?.trim() || undefined);
689 const env = yield* createDevRunnerEnv({
690 mode: input.mode,
691 baseEnv: hostEnvironment,
692 serverOffset,
693 webOffset,
694 t3Home: resolvedT3Home,
695 browser: input.browser,
696 autoBootstrapProjectFromCwd: input.autoBootstrapProjectFromCwd,
697 logWebSocketEvents: input.logWebSocketEvents,
698 host: input.host,
699 port: input.port,
700 devUrl: input.devUrl,
701 });
702
703 const selectionSuffix =
704 serverOffset !== offset || webOffset !== offset
705 ? ` selectedOffset(server=${serverOffset},web=${webOffset})`
706 : "";
707 const baseDir = env.T3CODE_HOME ?? (yield* DEFAULT_T3_HOME);
708
709 yield* Effect.logInfo(
710 `[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} baseDir=${baseDir}`,
711 );
712
713 // Before the share block: --dry-run only resolves and prints. Sharing would
714 // replace, then tear down, whatever mapping the port already had — a
715 // surprising side effect from a command documented as inert.
716 if (input.dryRun) {
717 return;
718 }
719
720 const sharedWebPort = BASE_WEB_PORT + webOffset;
721 if (input.share) {
722 if (input.mode === "dev:server") {
723 yield* Effect.logInfo("[dev-runner] --share has no effect for dev:server (no web server).");
724 } else if (input.mode === "dev:desktop") {
725 // Desktop is not single-origin: the renderer gets VITE_HTTP_URL and
726 // VITE_WS_URL baked to loopback, so a tailnet visitor would load the UI
727 // and then watch it dial its own 127.0.0.1 for the backend. Worse,
728 // sharing would overwrite VITE_DEV_SERVER_URL, which is the origin
729 // Electron itself loads the renderer from. Refuse rather than hand out
730 // a URL that is broken in a way the user cannot see.
731 yield* Effect.logWarning(
732 "[dev-runner] --share is not supported for dev:desktop (the renderer is pinned to loopback). Use `dev`, which runs the whole browser stack.",
733 );
734 } else {
735 // acquireRelease, not share-then-addFinalizer: the mapping outlives this
736 // process (and reboots), so the cleanup has to be registered atomically
737 // with creating it. An interrupt landing in between would otherwise
738 // leave a mapping pointing at a port nothing is listening on.
739 //
740 // Deliberately no ownership tracking beyond that: if a second runner
741 // takes this port during a fast restart, the first's exit can briefly
742 // tear down the new mapping — visible (the URL stops working) and fixed
743 // by re-running --share. A lease protocol closing that window existed
744 // and was removed as more machinery than a dev convenience warrants.
745 //
746 // A tailnet that isn't up shouldn't stop the dev server from starting —
747 // warn, and carry on serving locally.
748 const shared = yield* Effect.acquireRelease(
749 shareDevServer({ webPort: sharedWebPort }),
750 () =>
751 // Serve config outlives this process, so a cleanup that did not
752 // take leaves a tailnet URL pointing at a port nothing serves.
753 unshareDevServer(sharedWebPort).pipe(
754 Effect.flatMap((result) =>
755 result.cleared
756 ? Effect.void
757 : Effect.logWarning(
758 `[dev-runner] could not remove the tailnet mapping for port ${String(sharedWebPort)}${
759 result.explanation ? `: ${result.explanation}` : ""
760 }. Remove it with \`tailscale serve --https=${String(sharedWebPort)} off\`.`,
761 ),
762 ),
763 ),
764 ).pipe(
765 Effect.tapError((error: DevShareError) =>
766 Effect.logWarning(
767 `[dev-runner] could not share on the tailnet: ${error.message}${
768 error.hint ? ` — ${error.hint}` : ""
769 }`,
770 ),
771 ),
772 Effect.option,
773 Effect.map(Option.getOrUndefined),
774 );
775
776 if (shared) {
777 // The app is reached from the tailnet origin. Vite already allows
778 // *.ts.net hosts; the backend needs the origin for credentialed
779 // requests that bypass the proxy (desktop renderer, direct calls).
780 env.T3CODE_DEV_ALLOWED_ORIGINS = [
781 env.T3CODE_DEV_ALLOWED_ORIGINS,
782 new URL(shared.url).origin,
783 ]
784 .filter((entry) => entry && entry.length > 0)
785 .join(",");
786 // The server builds its pairing URL from this, so the URL printed at
787 // startup is already the shareable one — no rewriting by hand. An
788 // explicit --dev-url still wins.
789 if (input.devUrl === undefined) {
790 env.VITE_DEV_SERVER_URL = shared.url;
791 }
792 // A shared origin serves a remote browser, where unbundled dev's
793 // per-module requests each pay a tailnet round trip — a cold module
794 // graph takes minutes to first paint. Bundled dev collapses that to
795 // a few chunk requests. Only defaulted, so T3CODE_BUNDLED_DEV=0
796 // still opts a --share run back out.
797 if (env.T3CODE_BUNDLED_DEV === undefined) {
798 env.T3CODE_BUNDLED_DEV = "1";
799 }
800 yield* Effect.logInfo(`[dev-runner] shared on tailnet: ${shared.url}`);
801 }
802 }
803 }
804
805 const spawnCommand = yield* resolveSpawnCommand(
806 "vp",
807 [...MODE_ARGS[input.mode], ...input.runArgs],
808 { env },
809 );
810 const processContext = {
811 mode: input.mode,
812 executable: "vp" as const,
813 argumentCount: spawnCommand.args.length,
814 shell: spawnCommand.shell,
815 } as const;
816 const child = yield* ChildProcess.make(spawnCommand.command, spawnCommand.args, {
817 stdin: "inherit",
818 stdout: "inherit",
819 stderr: "inherit",
820 env,
821 extendEnv: false,
822 shell: spawnCommand.shell,
823 // Keep Vite+ in the same process group so terminal signals (Ctrl+C)
824 // reach it directly. Effect defaults to detached: true on non-Windows,
825 // which would put the runner in a new group and require manual forwarding.
826 detached: false,
827 forceKillAfter: "1500 millis",
828 }).pipe(
829 Effect.mapError(
830 (cause) =>
831 new DevRunnerProcessError({
832 ...processContext,
833 operation: "spawn",
834 cause,
835 }),
836 ),
837 );
838
839 const exitCode = yield* child.exitCode.pipe(
840 Effect.mapError(
841 (cause) =>
842 new DevRunnerProcessError({
843 ...processContext,
844 operation: "wait-for-exit",
845 cause,
846 }),
847 ),
848 );
849 if (exitCode !== 0) {
850 return yield* new DevRunnerProcessExitError({
851 ...processContext,
852 exitCode,
853 });
854 }
855 });
856}
857
858const devRunnerCli = Command.make("dev-runner", {
859 mode: Argument.choice("mode", DEV_RUNNER_MODES).pipe(
860 Argument.withDescription("Development mode to run."),
861 ),
862 t3Home: Flag.string("home-dir").pipe(
863 Flag.withDescription(
864 "Explicit T3 Code data directory; runtime state is stored under userdata (equivalent to T3CODE_HOME). Inside a git worktree this defaults to that worktree's own .t3 so dev state stays off the shared home.",
865 ),
866 Flag.optional,
867 Flag.map(Option.getOrUndefined),
868 ),
869 browser: Flag.boolean("browser").pipe(
870 Flag.withDescription("Open a browser automatically (disabled by default for web dev)."),
871 Flag.withDefault(false),
872 ),
873 autoBootstrapProjectFromCwd: Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
874 Flag.withDescription(
875 "Auto-bootstrap toggle (equivalent to T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD).",
876 ),
877 Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD")),
878 ),
879 logWebSocketEvents: Flag.boolean("log-websocket-events").pipe(
880 Flag.withDescription("WebSocket event logging toggle (equivalent to T3CODE_LOG_WS_EVENTS)."),
881 Flag.withAlias("log-ws-events"),
882 Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_LOG_WS_EVENTS")),
883 ),
884 host: Flag.string("host").pipe(
885 Flag.withDescription("Server host/interface override (forwards to T3CODE_HOST)."),
886 Flag.withFallbackConfig(optionalStringConfig("T3CODE_HOST")),
887 ),
888 port: Flag.integer("port").pipe(
889 Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
890 Flag.withDescription("Server port override (forwards to T3CODE_PORT)."),
891 Flag.withFallbackConfig(optionalPortConfig("T3CODE_PORT")),
892 ),
893 devUrl: Flag.string("dev-url").pipe(
894 Flag.withSchema(Schema.URLFromString),
895 Flag.withDescription(
896 "Explicit web dev URL override (forwards to VITE_DEV_SERVER_URL). Ambient VITE_DEV_SERVER_URL values are ignored so a parent dev app cannot redirect the child runner.",
897 ),
898 Flag.optional,
899 Flag.map(Option.getOrUndefined),
900 ),
901 dryRun: Flag.boolean("dry-run").pipe(
902 Flag.withDescription("Resolve mode/ports/env and print, but do not spawn Vite+."),
903 Flag.withDefault(false),
904 ),
905 share: Flag.boolean("share").pipe(
906 Flag.withDescription(
907 "Publish the web dev server on this machine's tailnet over HTTPS (via `tailscale serve`) and print the pairing URL for it. Removed again on exit.",
908 ),
909 Flag.withDefault(false),
910 ),
911 runArgs: Argument.string("run-arg").pipe(
912 Argument.withDescription("Additional Vite+ run args (pass after `--`)."),
913 Argument.variadic(),
914 ),
915}).pipe(
916 Command.withDescription("Run monorepo development modes with deterministic port/env wiring."),
917 Command.withHandler((input) => runDevRunnerWithInput(input)),
918);
919
920const cliRuntimeLayer = Layer.mergeAll(
921 Logger.layer([Logger.consolePretty()]),
922 NodeServices.layer,
923 NetService.layer,
924);
925
926if (import.meta.main) {
927 Command.run(devRunnerCli, { version: "0.0.0" }).pipe(
928 Effect.scoped,
929 Effect.provide(cliRuntimeLayer),
930 NodeRuntime.runMain,
931 );
932}