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

dev-runner.ts

930 lines34.0 KB

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 );
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];
104​
105export function isBrowserAllowedPort(port: number): boolean {
106 return !FETCH_BAD_PORTS.has(port);
108​
109export class DevRunnerConfigurationError extends Schema.TaggedErrorClass<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 }
120​
121export class DevRunnerInvalidPortOffsetError extends Schema.TaggedErrorClass<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 }
133​
134export class DevRunnerPortExhaustedError extends Schema.TaggedErrorClass<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 }
149​
150export class DevRunnerProcessError extends Schema.TaggedErrorClass<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 }
165​
166export class DevRunnerProcessExitError extends Schema.TaggedErrorClass<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 }
180​
181export class DevRunnerHostNotProxiableError extends Schema.TaggedErrorClass<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 }
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" });
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 });
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;
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 }
392​
393 if (!isDesktopMode && host !== undefined) {
394 output.T3CODE_HOST = host;
395 }
396​
397 if (!isDesktopMode) {
398 output.T3CODE_NO_BROWSER = browser === true ? "0" : "1";
399 }
400​
401 if (autoBootstrapProjectFromCwd !== undefined) {
402 output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD = autoBootstrapProjectFromCwd ? "1" : "0";
403 } else {
404 delete output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD;
405 }
406​
407 if (logWebSocketEvents !== undefined) {
408 output.T3CODE_LOG_WS_EVENTS = logWebSocketEvents ? "1" : "0";
409 } else {
410 delete output.T3CODE_LOG_WS_EVENTS;
411 }
412​
413 if (mode === "dev") {
414 output.T3CODE_MODE = "web";
415 delete output.T3CODE_DESKTOP_WS_URL;
416 }
417​
418 if (mode === "dev:server" || mode === "dev:web") {
419 output.T3CODE_MODE = "web";
420 delete output.T3CODE_DESKTOP_WS_URL;
421 }
422​
423 if (isDesktopMode) {
424 output.HOST = DESKTOP_DEV_LOOPBACK_HOST;
425 delete output.T3CODE_DESKTOP_WS_URL;
426 }
427​
428 return output;
429 });
431​
432function portPairForOffset(offset: number): {
433 readonly serverPort: number;
434 readonly webPort: number;
435} {
436 return {
437 serverPort: BASE_SERVER_PORT + offset,
438 webPort: BASE_WEB_PORT + offset,
439 };
441​
442export function checkPortAvailabilityOnHosts<R>(
443 port: number,
444 hosts: ReadonlyArray<string>,
445 canListenOnHost: (port: number, host: string) => Effect.Effect<boolean, never, R>,
446): Effect.Effect<boolean, never, R> {
447 return Effect.gen(function* () {
448 for (const host of hosts) {
449 if (!(yield* canListenOnHost(port, host))) {
450 return false;
451 }
452 }
453​
454 return true;
455 });
457​
458/**
459 * Hosts to probe for a dev server bound to `configuredHost`.
460 *
461 * Loopback is always checked because the web server and the desktop renderer
462 * target reach it there. When `--host`/`T3CODE_HOST` moves the backend onto
463 * another interface, that interface decides whether the bind actually
464 * succeeds — probing only loopback would hand back a port that is free here
465 * and taken there, and the server would fail to start.
466 *
467 * `configuredHost` applies to the *backend* only. Vite takes its bind address
468 * from `HOST`, which the runner sets for desktop alone, so the web port stays
469 * on loopback and must not be judged against the backend's interface —
470 * a port free on loopback but busy on that interface would otherwise be
471 * rejected for a server that was never going to bind there.
472 */
473export function devPortProbeHosts(configuredHost: string | undefined): ReadonlyArray<string> {
474 const host = configuredHost?.trim();
475 if (!host || DEV_PORT_PROBE_HOSTS.includes(host as (typeof DEV_PORT_PROBE_HOSTS)[number])) {
476 return DEV_PORT_PROBE_HOSTS;
477 }
478 return [...DEV_PORT_PROBE_HOSTS, host];
480​
481const makeDefaultCheckPortAvailability =
482 (configuredHost: string | undefined): PortAvailabilityCheck<NetService.NetService> =>
483 (port, role) =>
484 Effect.gen(function* () {
485 const net = yield* NetService.NetService;
486 const hosts = role === "web" ? DEV_PORT_PROBE_HOSTS : devPortProbeHosts(configuredHost);
487 return yield* checkPortAvailabilityOnHosts(port, hosts, (candidatePort, host) =>
488 net.canListenOnHost(candidatePort, host),
489 );
490 });
491​
492const defaultCheckPortAvailability = makeDefaultCheckPortAvailability(undefined);
493​
494interface FindFirstAvailableOffsetInput<R = NetService.NetService> {
495 readonly startOffset: number;
496 readonly requireServerPort: boolean;
497 readonly requireWebPort: boolean;
498 readonly checkPortAvailability?: PortAvailabilityCheck<R>;
500​
501export function findFirstAvailableOffset<R = NetService.NetService>({
502 startOffset,
503 requireServerPort,
504 requireWebPort,
505 checkPortAvailability,
506}: FindFirstAvailableOffsetInput<R>): Effect.Effect<number, DevRunnerPortExhaustedError, R> {
507 return Effect.gen(function* () {
508 const checkPort = (checkPortAvailability ??
509 defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
510​
511 for (let candidate = startOffset; ; candidate += 1) {
512 const { serverPort, webPort } = portPairForOffset(candidate);
513 const serverPortOutOfRange = serverPort > MAX_PORT;
514 const webPortOutOfRange = webPort > MAX_PORT;
515​
516 if (
517 (requireServerPort && serverPortOutOfRange) ||
518 (requireWebPort && webPortOutOfRange) ||
519 (!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange))
520 ) {
521 break;
522 }
523​
524 if (requireWebPort && !isBrowserAllowedPort(webPort)) {
525 continue;
526 }
527​
528 const checks: Array<Effect.Effect<boolean, never, R>> = [];
529 if (requireServerPort) {
530 checks.push(checkPort(serverPort, "server"));
531 }
532 if (requireWebPort) {
533 checks.push(checkPort(webPort, "web"));
534 }
535​
536 if (checks.length === 0) {
537 return candidate;
538 }
539​
540 const availability = yield* Effect.all(checks);
541 if (availability.every(Boolean)) {
542 return candidate;
543 }
544 }
545​
546 return yield* new DevRunnerPortExhaustedError({
547 startOffset,
548 requireServerPort,
549 requireWebPort,
550 baseServerPort: BASE_SERVER_PORT,
551 baseWebPort: BASE_WEB_PORT,
552 maximumPort: MAX_PORT,
553 });
554 });
556​
557interface ResolveModePortOffsetsInput<R = NetService.NetService> {
558 readonly mode: DevMode;
559 readonly startOffset: number;
560 readonly hasExplicitServerPort: boolean;
561 readonly hasExplicitDevUrl: boolean;
562 readonly checkPortAvailability?: PortAvailabilityCheck<R>;
564​
565export function resolveModePortOffsets<R = NetService.NetService>({
566 mode,
567 startOffset,
568 hasExplicitServerPort,
569 hasExplicitDevUrl,
570 checkPortAvailability,
571}: ResolveModePortOffsetsInput<R>): Effect.Effect<
572 { readonly serverOffset: number; readonly webOffset: number },
573 DevRunnerPortExhaustedError,
574 R
575> {
576 return Effect.gen(function* () {
577 const checkPort = (checkPortAvailability ??
578 defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
579​
580 if (mode === "dev:web") {
581 if (hasExplicitDevUrl) {
582 return { serverOffset: startOffset, webOffset: startOffset };
583 }
584​
585 const webOffset = yield* findFirstAvailableOffset({
586 startOffset,
587 requireServerPort: false,
588 requireWebPort: true,
589 checkPortAvailability: checkPort,
590 });
591 return { serverOffset: startOffset, webOffset };
592 }
593​
594 if (mode === "dev:server") {
595 if (hasExplicitServerPort) {
596 return { serverOffset: startOffset, webOffset: startOffset };
597 }
598​
599 const serverOffset = yield* findFirstAvailableOffset({
600 startOffset,
601 requireServerPort: true,
602 requireWebPort: false,
603 checkPortAvailability: checkPort,
604 });
605 return { serverOffset, webOffset: serverOffset };
606 }
607​
608 const sharedOffset = yield* findFirstAvailableOffset({
609 startOffset,
610 requireServerPort: !hasExplicitServerPort,
611 requireWebPort: !hasExplicitDevUrl,
612 checkPortAvailability: checkPort,
613 });
614​
615 return { serverOffset: sharedOffset, webOffset: sharedOffset };
616 });
618​
619interface DevRunnerCliInput {
620 readonly mode: DevMode;
621 readonly t3Home: string | undefined;
622 readonly browser: boolean | undefined;
623 readonly autoBootstrapProjectFromCwd: boolean | undefined;
624 readonly logWebSocketEvents: boolean | undefined;
625 readonly host: string | undefined;
626 readonly port: number | undefined;
627 readonly devUrl: URL | undefined;
628 readonly dryRun: boolean;
629 readonly share: boolean;
630 readonly runArgs: ReadonlyArray<string>;
632​
633export function runDevRunnerWithInput(input: DevRunnerCliInput) {
634 return Effect.gen(function* () {
635 const { portOffset, devInstance } = yield* OffsetConfig.pipe(
636 Effect.mapError(
637 (cause) =>
638 new DevRunnerConfigurationError({
639 configKeys: ["T3CODE_PORT_OFFSET", "T3CODE_DEV_INSTANCE"],
640 cause,
641 }),
642 ),
643 );
644​
645 // Single-origin browser dev proxies the backend at localhost. A wildcard
646 // bind still answers there; a specific non-loopback interface does not,
647 // which breaks every proxied request in a way that reads as "server is
648 // broken" rather than "flag combination is unsupported". Reject it up
649 // front instead. (dev:server and dev:desktop don't proxy — untouched.)
650 if (
651 (input.mode === "dev" || input.mode === "dev:web") &&
652 input.host !== undefined &&
653 !isProxiableBindHost(input.host)
654 ) {
655 return yield* new DevRunnerHostNotProxiableError({ mode: input.mode, host: input.host });
656 }
657​
658 const worktreePath = yield* resolveGitWorktreePath(yield* HostProcessWorkingDirectory);
659​
660 const { offset, source } = yield* resolveOffset({
661 portOffset,
662 devInstance,
663 worktreePath,
664 });
665​
666 const { serverOffset, webOffset } = yield* resolveModePortOffsets({
667 mode: input.mode,
668 startOffset: offset,
669 hasExplicitServerPort: input.port !== undefined,
670 hasExplicitDevUrl: input.devUrl !== undefined,
671 // A non-loopback bind host decides whether the backend can actually take
672 // the port, so it has to be probed alongside loopback.
673 checkPortAvailability: makeDefaultCheckPortAvailability(input.host),
674 });
675​
676 const hostEnvironment = yield* HostProcessEnvironment;
677 // A dev server started inside a worktree defaults to that worktree's own
678 // (gitignored) `.t3` — see @t3tools/shared/devHome for why this must
679 // outrank an ambient T3CODE_HOME. `--home-dir` still wins.
680 const worktreeHome = yield* resolveWorktreeT3Home(yield* HostProcessWorkingDirectory);
681 // Trim before choosing: `--home-dir ""` is not a selection, and treating it
682 // as one would skip the worktree default and land on the shared home —
683 // exactly the outcome this precedence exists to prevent.
684 const resolvedT3Home =
685 (input.t3Home?.trim() || undefined) ??
686 worktreeHome ??
687 (hostEnvironment.T3CODE_HOME?.trim() || undefined);
688 const env = yield* createDevRunnerEnv({
689 mode: input.mode,
690 baseEnv: hostEnvironment,
691 serverOffset,
692 webOffset,
693 t3Home: resolvedT3Home,
694 browser: input.browser,
695 autoBootstrapProjectFromCwd: input.autoBootstrapProjectFromCwd,
696 logWebSocketEvents: input.logWebSocketEvents,
697 host: input.host,
698 port: input.port,
699 devUrl: input.devUrl,
700 });
701​
702 const selectionSuffix =
703 serverOffset !== offset || webOffset !== offset
704 ? ` selectedOffset(server=${serverOffset},web=${webOffset})`
705 : "";
706 const baseDir = env.T3CODE_HOME ?? (yield* DEFAULT_T3_HOME);
707​
708 yield* Effect.logInfo(
709 `[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} baseDir=${baseDir}`,
710 );
711​
712 // Before the share block: --dry-run only resolves and prints. Sharing would
713 // replace, then tear down, whatever mapping the port already had — a
714 // surprising side effect from a command documented as inert.
715 if (input.dryRun) {
716 return;
717 }
718​
719 const sharedWebPort = BASE_WEB_PORT + webOffset;
720 if (input.share) {
721 if (input.mode === "dev:server") {
722 yield* Effect.logInfo("[dev-runner] --share has no effect for dev:server (no web server).");
723 } else if (input.mode === "dev:desktop") {
724 // Desktop is not single-origin: the renderer gets VITE_HTTP_URL and
725 // VITE_WS_URL baked to loopback, so a tailnet visitor would load the UI
726 // and then watch it dial its own 127.0.0.1 for the backend. Worse,
727 // sharing would overwrite VITE_DEV_SERVER_URL, which is the origin
728 // Electron itself loads the renderer from. Refuse rather than hand out
729 // a URL that is broken in a way the user cannot see.
730 yield* Effect.logWarning(
731 "[dev-runner] --share is not supported for dev:desktop (the renderer is pinned to loopback). Use `dev`, which runs the whole browser stack.",
732 );
733 } else {
734 // acquireRelease, not share-then-addFinalizer: the mapping outlives this
735 // process (and reboots), so the cleanup has to be registered atomically
736 // with creating it. An interrupt landing in between would otherwise
737 // leave a mapping pointing at a port nothing is listening on.
738 //
739 // Deliberately no ownership tracking beyond that: if a second runner
740 // takes this port during a fast restart, the first's exit can briefly
741 // tear down the new mapping — visible (the URL stops working) and fixed
742 // by re-running --share. A lease protocol closing that window existed
743 // and was removed as more machinery than a dev convenience warrants.
744 //
745 // A tailnet that isn't up shouldn't stop the dev server from starting —
746 // warn, and carry on serving locally.
747 const shared = yield* Effect.acquireRelease(
748 shareDevServer({ webPort: sharedWebPort }),
749 () =>
750 // Serve config outlives this process, so a cleanup that did not
751 // take leaves a tailnet URL pointing at a port nothing serves.
752 unshareDevServer(sharedWebPort).pipe(
753 Effect.flatMap((result) =>
754 result.cleared
755 ? Effect.void
756 : Effect.logWarning(
757 `[dev-runner] could not remove the tailnet mapping for port ${String(sharedWebPort)}${
758 result.explanation ? `: ${result.explanation}` : ""
759 }. Remove it with \`tailscale serve --https=${String(sharedWebPort)} off\`.`,
760 ),
761 ),
762 ),
763 ).pipe(
764 Effect.tapError((error: DevShareError) =>
765 Effect.logWarning(
766 `[dev-runner] could not share on the tailnet: ${error.message}${
767 error.hint ? ` — ${error.hint}` : ""
768 }`,
769 ),
770 ),
771 Effect.option,
772 Effect.map(Option.getOrUndefined),
773 );
774​
775 if (shared) {
776 // The app is reached from the tailnet origin. Vite already allows
777 // *.ts.net hosts; the backend needs the origin for credentialed
778 // requests that bypass the proxy (desktop renderer, direct calls).
779 env.T3CODE_DEV_ALLOWED_ORIGINS = [
780 env.T3CODE_DEV_ALLOWED_ORIGINS,
781 new URL(shared.url).origin,
782 ]
783 .filter((entry) => entry && entry.length > 0)
784 .join(",");
785 // The server builds its pairing URL from this, so the URL printed at
786 // startup is already the shareable one — no rewriting by hand. An
787 // explicit --dev-url still wins.
788 if (input.devUrl === undefined) {
789 env.VITE_DEV_SERVER_URL = shared.url;
790 }
791 // A shared origin serves a remote browser, where unbundled dev's
792 // per-module requests each pay a tailnet round trip — a cold module
793 // graph takes minutes to first paint. Bundled dev collapses that to
794 // a few chunk requests. Only defaulted, so T3CODE_BUNDLED_DEV=0
795 // still opts a --share run back out.
796 if (env.T3CODE_BUNDLED_DEV === undefined) {
797 env.T3CODE_BUNDLED_DEV = "1";
798 }
799 yield* Effect.logInfo(`[dev-runner] shared on tailnet: ${shared.url}`);
800 }
801 }
802 }
803​
804 const spawnCommand = yield* resolveSpawnCommand(
805 "vp",
806 [...MODE_ARGS[input.mode], ...input.runArgs],
807 { env },
808 );
809 const processContext = {
810 mode: input.mode,
811 executable: "vp" as const,
812 argumentCount: spawnCommand.args.length,
813 shell: spawnCommand.shell,
814 } as const;
815 const child = yield* ChildProcess.make(spawnCommand.command, spawnCommand.args, {
816 stdin: "inherit",
817 stdout: "inherit",
818 stderr: "inherit",
819 env,
820 extendEnv: false,
821 shell: spawnCommand.shell,
822 // Keep Vite+ in the same process group so terminal signals (Ctrl+C)
823 // reach it directly. Effect defaults to detached: true on non-Windows,
824 // which would put the runner in a new group and require manual forwarding.
825 detached: false,
826 forceKillAfter: "1500 millis",
827 }).pipe(
828 Effect.mapError(
829 (cause) =>
830 new DevRunnerProcessError({
831 ...processContext,
832 operation: "spawn",
833 cause,
834 }),
835 ),
836 );
837​
838 const exitCode = yield* child.exitCode.pipe(
839 Effect.mapError(
840 (cause) =>
841 new DevRunnerProcessError({
842 ...processContext,
843 operation: "wait-for-exit",
844 cause,
845 }),
846 ),
847 );
848 if (exitCode !== 0) {
849 return yield* new DevRunnerProcessExitError({
850 ...processContext,
851 exitCode,
852 });
853 }
854 });
856​
857const devRunnerCli = Command.make("dev-runner", {
858 mode: Argument.choice("mode", DEV_RUNNER_MODES).pipe(
859 Argument.withDescription("Development mode to run."),
860 ),
861 t3Home: Flag.string("home-dir").pipe(
862 Flag.withDescription(
863 "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.",
864 ),
865 Flag.optional,
866 Flag.map(Option.getOrUndefined),
867 ),
868 browser: Flag.boolean("browser").pipe(
869 Flag.withDescription("Open a browser automatically (disabled by default for web dev)."),
870 ),
871 autoBootstrapProjectFromCwd: Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
872 Flag.withDescription(
873 "Auto-bootstrap toggle (equivalent to T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD).",
874 ),
875 Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD")),
876 ),
877 logWebSocketEvents: Flag.boolean("log-websocket-events").pipe(
878 Flag.withDescription("WebSocket event logging toggle (equivalent to T3CODE_LOG_WS_EVENTS)."),
879 Flag.withAlias("log-ws-events"),
880 Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_LOG_WS_EVENTS")),
881 ),
882 host: Flag.string("host").pipe(
883 Flag.withDescription("Server host/interface override (forwards to T3CODE_HOST)."),
884 Flag.withFallbackConfig(optionalStringConfig("T3CODE_HOST")),
885 ),
886 port: Flag.integer("port").pipe(
887 Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
888 Flag.withDescription("Server port override (forwards to T3CODE_PORT)."),
889 Flag.withFallbackConfig(optionalPortConfig("T3CODE_PORT")),
890 ),
891 devUrl: Flag.string("dev-url").pipe(
892 Flag.withSchema(Schema.URLFromString),
893 Flag.withDescription(
894 "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.",
895 ),
896 Flag.optional,
897 Flag.map(Option.getOrUndefined),
898 ),
899 dryRun: Flag.boolean("dry-run").pipe(
900 Flag.withDescription("Resolve mode/ports/env and print, but do not spawn Vite+."),
901 Flag.withDefault(false),
902 ),
903 share: Flag.boolean("share").pipe(
904 Flag.withDescription(
905 "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.",
906 ),
907 Flag.withDefault(false),
908 ),
909 runArgs: Argument.string("run-arg").pipe(
910 Argument.withDescription("Additional Vite+ run args (pass after `--`)."),
911 Argument.variadic(),
912 ),
913}).pipe(
914 Command.withDescription("Run monorepo development modes with deterministic port/env wiring."),
915 Command.withHandler((input) => runDevRunnerWithInput(input)),
916);
917​
918const cliRuntimeLayer = Layer.mergeAll(
919 Logger.layer([Logger.consolePretty()]),
920 NodeServices.layer,
921 NetService.layer,
922);
923​
924if (import.meta.main) {
925 Command.run(devRunnerCli, { version: "0.0.0" }).pipe(
926 Effect.scoped,
927 Effect.provide(cliRuntimeLayer),
928 NodeRuntime.runMain,
929 );