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 * as HostProcess from "@t3tools/shared/HostProcess";
10import { resolveSpawnCommand } from "@t3tools/shared/shell";
11import * as Config from "effect/Config";
12import * as Effect from "effect/Effect";
13import * as FileSystem from "effect/FileSystem";
14import * as Hash from "effect/Hash";
15import * as Layer from "effect/Layer";
16import * as Logger from "effect/Logger";
17import * as Option from "effect/Option";
18import * as Path from "effect/Path";
19import * as Schema from "effect/Schema";
20import { Argument, Command, Flag } from "effect/cli";
21import { ChildProcess } from "effect/process";
22
23import { defaultDevMemoryLimitBytes, enforceDevMemoryLimit } from "./lib/dev-memory-limit.ts";
24import { acquireDevRunnerLock } from "./lib/dev-runner-lock.ts";
25import { type DevShareError, shareDevServer, unshareDevServer } from "./lib/dev-share.ts";
26import { loadRepoEnv } from "./lib/public-config.ts";
27
28Object.assign(process.env, loadRepoEnv());
29
30const BASE_SERVER_PORT = 13773;
31const BASE_WEB_PORT = 5733;
32const MAX_HASH_OFFSET = 3000;
33const MAX_PORT = 65535;
34const DESKTOP_DEV_LOOPBACK_HOST = "127.0.0.1";
35// Browsers block these ports before networking even when curl accepts them.
36// https://fetch.spec.whatwg.org/#port-blocking
37const FETCH_BAD_PORTS = new Set([
38 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,
39 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137, 139, 143, 161, 179, 389, 427, 465,
40 512, 513, 514, 515, 526, 530, 531, 532, 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993,
41 995, 1719, 1720, 1723, 2049, 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668,
42 6669, 6679, 6697, 10080,
43]);
44// Dev binds loopback; other interfaces cannot establish port availability.
45const DEV_PORT_PROBE_HOSTS = ["127.0.0.1", "::1"] as const;
46// Migration prunes after copying, so large sources also need an automatic-seeding limit.
47const LARGE_DEV_DATABASE_BYTES = 500 * 1024 * 1024;
48
49/** Only loopback and wildcard binds keep the loopback proxy target reachable. */
50export function isProxiableBindHost(host: string): boolean {
51 const normalized = host.trim();
52 return (
53 normalized === "" ||
54 normalized === "localhost" ||
55 normalized === "127.0.0.1" ||
56 normalized === "::1" ||
57 normalized === "[::1]" ||
58 normalized === "0.0.0.0" ||
59 normalized === "::" ||
60 normalized === "[::]"
61 );
62}
63
64function sharedBackendTargetHost(host: string | undefined): string {
65 const normalized = host?.trim() ?? "";
66 if (normalized === "::1" || normalized === "[::1]") return "[::1]";
67 if (normalized === "localhost") return "localhost";
68 return "127.0.0.1";
69}
70
71export const DEFAULT_T3_HOME = Effect.map(Effect.service(Path.Path), (path) =>
72 path.join(NodeOS.homedir(), ".t3"),
73);
74
75const MODE_ARGS = {
76 dev: [
77 "run",
78 "--filter=@t3tools/contracts",
79 "--filter=@t3tools/web",
80 "--filter=t3",
81 "--parallel",
82 "dev",
83 ],
84 "dev:server": ["run", "--filter=t3", "dev"],
85 "dev:web": ["run", "--filter=@t3tools/web", "dev"],
86 "dev:desktop": ["run", "--filter=@t3tools/desktop", "--filter=@t3tools/web", "dev"],
87} as const satisfies Record<string, ReadonlyArray<string>>;
88
89// `--built`: the web package rebuilds into apps/web/dist and the backend serves
90// it, so no Vite dev server runs.
91const BUILT_DEV_ARGS = [
92 "run",
93 "--filter=@t3tools/web",
94 "--filter=t3",
95 "--parallel",
96 "dev:built",
97] as const;
98
99type DevMode = keyof typeof MODE_ARGS;
100// Only backend ports honor --host/T3CODE_HOST; web ports stay loopback.
101type PortAvailabilityCheck<R = never> = (
102 port: number,
103 role?: "server" | "web",
104) => Effect.Effect<boolean, NetService.NetListenError, R>;
105
106const DEV_RUNNER_MODES = Object.keys(MODE_ARGS) as Array<DevMode>;
107
108export function isBrowserAllowedPort(port: number): boolean {
109 return !FETCH_BAD_PORTS.has(port);
110}
111
112export class DevRunnerConfigurationError extends Schema.TaggedError<DevRunnerConfigurationError>()(
113 "DevRunnerConfigurationError",
114 {
115 configKeys: Schema.Array(Schema.String),
116 cause: Schema.Defect(),
117 },
118) {
119 override get message(): string {
120 return `Failed to read dev-runner configuration: ${this.configKeys.join(", ")}.`;
121 }
122}
123
124export class DevRunnerInvalidPortOffsetError extends Schema.TaggedError<DevRunnerInvalidPortOffsetError>()(
125 "DevRunnerInvalidPortOffsetError",
126 {
127 configKey: Schema.Literal("T3CODE_PORT_OFFSET"),
128 portOffset: Schema.Number,
129 minimum: Schema.Number,
130 },
131) {
132 override get message(): string {
133 return `${this.configKey} must be at least ${this.minimum}; received ${this.portOffset}.`;
134 }
135}
136
137export class DevRunnerPortExhaustedError extends Schema.TaggedError<DevRunnerPortExhaustedError>()(
138 "DevRunnerPortExhaustedError",
139 {
140 startOffset: Schema.Number,
141 requireServerPort: Schema.Boolean,
142 requireWebPort: Schema.Boolean,
143 baseServerPort: Schema.Number,
144 baseWebPort: Schema.Number,
145 maximumPort: Schema.Number,
146 },
147) {
148 override get message(): string {
149 return `No required dev ports were available from offset ${this.startOffset} through maximum port ${this.maximumPort}.`;
150 }
151}
152
153export class DevRunnerProcessError extends Schema.TaggedError<DevRunnerProcessError>()(
154 "DevRunnerProcessError",
155 {
156 operation: Schema.Literals(["spawn", "wait-for-exit"]),
157 mode: Schema.Literals(["dev", "dev:server", "dev:web", "dev:desktop"]),
158 executable: Schema.Literal("vp"),
159 argumentCount: Schema.Number,
160 shell: Schema.Boolean,
161 cause: Schema.Defect(),
162 },
163) {
164 override get message(): string {
165 return `Dev-runner process operation "${this.operation}" failed for mode "${this.mode}".`;
166 }
167}
168
169export class DevRunnerProcessExitError extends Schema.TaggedError<DevRunnerProcessExitError>()(
170 "DevRunnerProcessExitError",
171 {
172 mode: Schema.Literals(["dev", "dev:server", "dev:web", "dev:desktop"]),
173 executable: Schema.Literal("vp"),
174 argumentCount: Schema.Number,
175 shell: Schema.Boolean,
176 exitCode: Schema.Number,
177 },
178) {
179 override get message(): string {
180 return `Dev-runner process exited with code ${this.exitCode} in mode "${this.mode}".`;
181 }
182}
183
184export class DevRunnerHostNotProxiableError extends Schema.TaggedError<DevRunnerHostNotProxiableError>()(
185 "DevRunnerHostNotProxiableError",
186 {
187 mode: Schema.Literals(["dev", "dev:web"]),
188 host: Schema.String,
189 },
190) {
191 override get message(): string {
192 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.`;
193 }
194}
195
196export class DevRunnerBuiltNeedsShareError extends Schema.TaggedError<DevRunnerBuiltNeedsShareError>()(
197 "DevRunnerBuiltNeedsShareError",
198 {
199 mode: Schema.Literals(["dev", "dev:server", "dev:web", "dev:desktop"]),
200 },
201) {
202 override get message(): string {
203 return `--built only works with \`dev --share\` (got ${this.mode}${this.mode === "dev" ? " without --share" : ""}): the backend serves the built client on the tailnet URL.`;
204 }
205}
206
207const optionalStringConfig = (name: string): Config.Config<string | undefined> =>
208 Config.String(name).pipe(
209 Config.option,
210 Config.map((value) => Option.getOrUndefined(value)),
211 );
212const optionalBooleanConfig = (name: string): Config.Config<boolean | undefined> =>
213 Config.Boolean(name).pipe(
214 Config.option,
215 Config.map((value) => Option.getOrUndefined(value)),
216 );
217const optionalIntegerConfig = (name: string): Config.Config<number | undefined> =>
218 Config.Int(name).pipe(
219 Config.option,
220 Config.map((value) => Option.getOrUndefined(value)),
221 );
222const OffsetConfig = Config.all({
223 portOffset: optionalIntegerConfig("T3CODE_PORT_OFFSET"),
224 devInstance: optionalStringConfig("T3CODE_DEV_INSTANCE"),
225});
226
227export function resolveOffset(config: {
228 readonly portOffset: number | undefined;
229 readonly devInstance: string | undefined;
230 readonly worktreePath?: string | undefined;
231}): Effect.Effect<
232 { readonly offset: number; readonly source: string },
233 DevRunnerInvalidPortOffsetError
234> {
235 if (config.portOffset !== undefined) {
236 if (config.portOffset < 0) {
237 return Effect.fail(
238 new DevRunnerInvalidPortOffsetError({
239 configKey: "T3CODE_PORT_OFFSET",
240 portOffset: config.portOffset,
241 minimum: 0,
242 }),
243 );
244 }
245 return Effect.succeed({
246 offset: config.portOffset,
247 source: `T3CODE_PORT_OFFSET=${config.portOffset}`,
248 });
249 }
250
251 const seed = config.devInstance?.trim();
252 if (seed) {
253 if (/^\d+$/.test(seed)) {
254 return Effect.succeed({
255 offset: Number(seed),
256 source: `numeric T3CODE_DEV_INSTANCE=${seed}`,
257 });
258 }
259
260 const offset = ((Hash.string(seed) >>> 0) % MAX_HASH_OFFSET) + 1;
261 return Effect.succeed({ offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` });
262 }
263
264 const worktreePath = config.worktreePath?.trim();
265 if (worktreePath) {
266 const offset = ((Hash.string(worktreePath) >>> 0) % MAX_HASH_OFFSET) + 1;
267 return Effect.succeed({ offset, source: `worktree ${worktreePath}` });
268 }
269
270 return Effect.succeed({ offset: 0, source: "default ports" });
271}
272
273const resolveBaseDir = Effect.fn("dev-runner.resolveBaseDir")(function* (
274 baseDir: string | undefined,
275): Effect.fn.Return<string, never, Path.Path> {
276 const path = yield* Path.Path;
277 const configured = baseDir?.trim();
278
279 if (configured === "~") {
280 return yield* HostProcess.HomeDirectory;
281 }
282 if (configured?.startsWith("~/") || configured?.startsWith("~\\")) {
283 return path.join(yield* HostProcess.HomeDirectory, configured.slice(2));
284 }
285 if (configured) {
286 return path.resolve(configured);
287 }
288
289 return yield* DEFAULT_T3_HOME;
290});
291
292interface CreateDevRunnerEnvInput {
293 readonly mode: DevMode;
294 readonly baseEnv: NodeJS.ProcessEnv;
295 readonly serverOffset: number;
296 readonly webOffset: number;
297 readonly t3Home: string | undefined;
298 readonly browser: boolean | undefined;
299 readonly autoBootstrapProjectFromCwd: boolean | undefined;
300 readonly logWebSocketEvents: boolean | undefined;
301 readonly host: string | undefined;
302 readonly port: number | undefined;
303 readonly devUrl: URL | undefined;
304}
305
306export const createDevRunnerEnv = Effect.fn("dev-runner.createDevRunnerEnv")(function* ({
307 mode,
308 baseEnv,
309 serverOffset,
310 webOffset,
311 t3Home,
312 browser,
313 autoBootstrapProjectFromCwd,
314 logWebSocketEvents,
315 host,
316 port,
317 devUrl,
318}: CreateDevRunnerEnvInput): Effect.fn.Return<NodeJS.ProcessEnv, never, Path.Path> {
319 const serverPort = port ?? BASE_SERVER_PORT + serverOffset;
320 const webPort = BASE_WEB_PORT + webOffset;
321 const configuredBaseDir = t3Home?.trim() || undefined;
322 const resolvedBaseDir = yield* resolveBaseDir(configuredBaseDir);
323 const isDesktopMode = mode === "dev:desktop";
324
325 const output: NodeJS.ProcessEnv = {
326 ...baseEnv,
327 PORT: String(webPort),
328 VITE_DEV_SERVER_URL:
329 devUrl?.toString() ??
330 `http://${isDesktopMode ? DESKTOP_DEV_LOOPBACK_HOST : "localhost"}:${webPort}`,
331 };
332
333 const path = yield* Path.Path;
334 // The server stores an explicit home's state in userdata, which for ~/.t3 is the live
335 // install. Left implicit, dev state goes to ~/.t3/dev.
336 const isLiveHome = resolvedBaseDir === path.join(yield* HostProcess.HomeDirectory, ".t3");
337 if (configuredBaseDir !== undefined && !isLiveHome) {
338 output.T3CODE_HOME = resolvedBaseDir;
339 } else {
340 delete output.T3CODE_HOME;
341 }
342
343 // Managed T3 service shells leak launcher variables that make dev servers fail version checks.
344 // Dev-runner servers are never launcher-managed (serviceLauncherClient.ts resolveStartup).
345 delete output.T3_SERVICE_LAUNCHER_CONTEXT;
346 delete output.T3_BOOT_SERVICE_UNIT;
347
348 // Each worktree has its own state, so a dev server would count as a new
349 // install of the developer's real accounts. Set it explicitly to opt in.
350 output.T3CODE_TELEMETRY_ENABLED = baseEnv.T3CODE_TELEMETRY_ENABLED ?? "false";
351
352 if (!isDesktopMode) {
353 output.T3CODE_PORT = String(serverPort);
354 // An inherited HOST pins Vite's HMR socket via explicitHost in apps/web/vite.config.ts.
355 // Only desktop mode should set it.
356 delete output.HOST;
357 if (mode === "dev" || mode === "dev:web") {
358 // Browser dev is single-origin: everything (including /ws) is proxied
359 // through Vite, so the client must resolve its backend from
360 // window.location.origin rather than a baked-in localhost URL.
361 delete output.VITE_HTTP_URL;
362 delete output.VITE_WS_URL;
363 // Deleting is not enough on its own: vite.config.ts calls loadRepoEnv,
364 // which merges `.env`/`.env.local` *under* this env, so a developer
365 // with either URL in their `.env` would get it back and silently lose
366 // single-origin mode.
367 output.T3CODE_SINGLE_ORIGIN_DEV = "1";
368 } else {
369 output.VITE_HTTP_URL = `http://localhost:${serverPort}`;
370 output.VITE_WS_URL = `ws://localhost:${serverPort}`;
371 delete output.T3CODE_SINGLE_ORIGIN_DEV;
372 }
373 } else {
374 output.T3CODE_PORT = String(serverPort);
375 output.VITE_HTTP_URL = `http://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
376 output.VITE_WS_URL = `ws://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
377 // Desktop pins the renderer to loopback on purpose; an ambient marker
378 // must not make Vite drop those URLs.
379 delete output.T3CODE_SINGLE_ORIGIN_DEV;
380 delete output.T3CODE_MODE;
381 delete output.T3CODE_NO_BROWSER;
382 delete output.T3CODE_DEV_AUTH_TOKEN;
383 }
384
385 // Agent shells inherit the parent T3 server's bind settings; only --host widens the dev server.
386 delete output.T3CODE_LAN;
387 if (!isDesktopMode && host !== undefined) {
388 output.T3CODE_HOST = host;
389 } else {
390 delete output.T3CODE_HOST;
391 }
392
393 if (!isDesktopMode) {
394 output.T3CODE_NO_BROWSER = browser === true ? "0" : "1";
395 }
396
397 if (autoBootstrapProjectFromCwd !== undefined) {
398 output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD = autoBootstrapProjectFromCwd ? "1" : "0";
399 } else {
400 delete output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD;
401 }
402
403 if (logWebSocketEvents !== undefined) {
404 output.T3CODE_LOG_WS_EVENTS = logWebSocketEvents ? "1" : "0";
405 } else {
406 delete output.T3CODE_LOG_WS_EVENTS;
407 }
408
409 if (mode === "dev") {
410 output.T3CODE_MODE = "web";
411 delete output.T3CODE_DESKTOP_WS_URL;
412 }
413
414 if (mode === "dev:server" || mode === "dev:web") {
415 output.T3CODE_MODE = "web";
416 delete output.T3CODE_DESKTOP_WS_URL;
417 }
418
419 if (isDesktopMode) {
420 output.HOST = DESKTOP_DEV_LOOPBACK_HOST;
421 delete output.T3CODE_DESKTOP_WS_URL;
422 }
423
424 return output;
425});
426
427function portPairForOffset(offset: number): {
428 readonly serverPort: number;
429 readonly webPort: number;
430} {
431 return {
432 serverPort: BASE_SERVER_PORT + offset,
433 webPort: BASE_WEB_PORT + offset,
434 };
435}
436
437export const checkPortAvailabilityOnHosts = Effect.fn("dev-runner.checkPortAvailabilityOnHosts")(
438 function* <E, R>(
439 port: number,
440 hosts: ReadonlyArray<string>,
441 canListenOnHost: (port: number, host: string) => Effect.Effect<boolean, E, R>,
442 ): Effect.fn.Return<boolean, E, R> {
443 for (const host of hosts) {
444 if (!(yield* canListenOnHost(port, host))) {
445 return false;
446 }
447 }
448
449 return true;
450 },
451);
452
453export function devPortProbeHosts(configuredHost: string | undefined): ReadonlyArray<string> {
454 const host = configuredHost?.trim();
455 if (!host || DEV_PORT_PROBE_HOSTS.includes(host as (typeof DEV_PORT_PROBE_HOSTS)[number])) {
456 return DEV_PORT_PROBE_HOSTS;
457 }
458 return [...DEV_PORT_PROBE_HOSTS, host];
459}
460
461const makeDefaultCheckPortAvailability =
462 (configuredHost: string | undefined): PortAvailabilityCheck<NetService.NetService> =>
463 (port, role) =>
464 Effect.gen(function* () {
465 const net = yield* NetService.NetService;
466 const hosts = role === "web" ? DEV_PORT_PROBE_HOSTS : devPortProbeHosts(configuredHost);
467 return yield* checkPortAvailabilityOnHosts(port, hosts, (candidatePort, host) =>
468 net.probeListenOnHost(candidatePort, host),
469 );
470 });
471
472const defaultCheckPortAvailability = makeDefaultCheckPortAvailability(undefined);
473
474interface FindFirstAvailableOffsetInput<R = NetService.NetService> {
475 readonly startOffset: number;
476 readonly requireServerPort: boolean;
477 readonly requireWebPort: boolean;
478 readonly checkPortAvailability?: PortAvailabilityCheck<R>;
479}
480
481export const findFirstAvailableOffset = Effect.fn("dev-runner.findFirstAvailableOffset")(function* <
482 R = NetService.NetService,
483>({
484 startOffset,
485 requireServerPort,
486 requireWebPort,
487 checkPortAvailability,
488}: FindFirstAvailableOffsetInput<R>): Effect.fn.Return<
489 number,
490 DevRunnerPortExhaustedError | NetService.NetListenError,
491 R
492> {
493 const checkPort = (checkPortAvailability ??
494 defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
495
496 for (let candidate = startOffset; ; candidate += 1) {
497 const { serverPort, webPort } = portPairForOffset(candidate);
498 const serverPortOutOfRange = serverPort > MAX_PORT;
499 const webPortOutOfRange = webPort > MAX_PORT;
500
501 if (
502 (requireServerPort && serverPortOutOfRange) ||
503 (requireWebPort && webPortOutOfRange) ||
504 (!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange))
505 ) {
506 break;
507 }
508
509 if (requireWebPort && !isBrowserAllowedPort(webPort)) {
510 continue;
511 }
512
513 const checks: Array<Effect.Effect<boolean, NetService.NetListenError, R>> = [];
514 if (requireServerPort) {
515 checks.push(checkPort(serverPort, "server"));
516 }
517 if (requireWebPort) {
518 checks.push(checkPort(webPort, "web"));
519 }
520
521 if (checks.length === 0) {
522 return candidate;
523 }
524
525 const availability = yield* Effect.all(checks);
526 if (availability.every(Boolean)) {
527 return candidate;
528 }
529 }
530
531 return yield* new DevRunnerPortExhaustedError({
532 startOffset,
533 requireServerPort,
534 requireWebPort,
535 baseServerPort: BASE_SERVER_PORT,
536 baseWebPort: BASE_WEB_PORT,
537 maximumPort: MAX_PORT,
538 });
539});
540
541interface ResolveModePortOffsetsInput<R = NetService.NetService> {
542 readonly mode: DevMode;
543 readonly startOffset: number;
544 readonly hasExplicitServerPort: boolean;
545 readonly hasExplicitDevUrl: boolean;
546 readonly checkPortAvailability?: PortAvailabilityCheck<R>;
547}
548
549export const resolveModePortOffsets = Effect.fn("dev-runner.resolveModePortOffsets")(function* <
550 R = NetService.NetService,
551>({
552 mode,
553 startOffset,
554 hasExplicitServerPort,
555 hasExplicitDevUrl,
556 checkPortAvailability,
557}: ResolveModePortOffsetsInput<R>): Effect.fn.Return<
558 { readonly serverOffset: number; readonly webOffset: number },
559 DevRunnerPortExhaustedError | NetService.NetListenError,
560 R
561> {
562 const checkPort = (checkPortAvailability ??
563 defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
564
565 if (mode === "dev:web") {
566 if (hasExplicitDevUrl) {
567 return { serverOffset: startOffset, webOffset: startOffset };
568 }
569
570 const webOffset = yield* findFirstAvailableOffset({
571 startOffset,
572 requireServerPort: false,
573 requireWebPort: true,
574 checkPortAvailability: checkPort,
575 });
576 return { serverOffset: startOffset, webOffset };
577 }
578
579 if (mode === "dev:server") {
580 if (hasExplicitServerPort) {
581 return { serverOffset: startOffset, webOffset: startOffset };
582 }
583
584 const serverOffset = yield* findFirstAvailableOffset({
585 startOffset,
586 requireServerPort: true,
587 requireWebPort: false,
588 checkPortAvailability: checkPort,
589 });
590 return { serverOffset, webOffset: serverOffset };
591 }
592
593 const sharedOffset = yield* findFirstAvailableOffset({
594 startOffset,
595 requireServerPort: !hasExplicitServerPort,
596 requireWebPort: !hasExplicitDevUrl,
597 checkPortAvailability: checkPort,
598 });
599
600 return { serverOffset: sharedOffset, webOffset: sharedOffset };
601});
602
603/** Best effort: a failed first-start step warns, and dev still starts. */
604const runRepoScript = Effect.fn("dev-runner.runRepoScript")(function* (
605 script: string,
606 args: ReadonlyArray<string>,
607 env: NodeJS.ProcessEnv,
608) {
609 const path = yield* Path.Path;
610 const repoRoot = path.dirname(import.meta.dirname);
611 const exitCode = yield* ChildProcess.make(
612 yield* HostProcess.ExecutablePath,
613 [path.join(repoRoot, script), ...args],
614 { cwd: repoRoot, stdin: "ignore", stdout: "inherit", stderr: "inherit", env, extendEnv: false },
615 ).pipe(
616 Effect.flatMap((child) => child.exitCode),
617 Effect.scoped,
618 Effect.orElseSucceed(() => -1),
619 );
620 if (exitCode !== 0) {
621 yield* Effect.logWarning(`[dev-runner] ${script} failed; starting anyway.`);
622 }
623});
624
625/**
626 * The first start in a worktree seeds its empty database from a small live database,
627 * builds the native resource monitor, and warms the web dependency cache. Each step
628 * checks for its own output, so later starts skip it.
629 */
630const prepareFirstStart = Effect.fn("dev-runner.prepareFirstStart")(function* (input: {
631 readonly mode: DevMode;
632 readonly seed: boolean;
633 readonly worktreeHome: string | undefined;
634 readonly env: NodeJS.ProcessEnv;
635}) {
636 const fs = yield* FileSystem.FileSystem;
637 const path = yield* Path.Path;
638 const exists = (file: string) => fs.exists(file).pipe(Effect.orElseSucceed(() => false));
639
640 if (input.worktreeHome !== undefined && input.mode !== "dev:web") {
641 const stateDir = path.join(input.worktreeHome, "userdata");
642 for (const name of ["statev2.sqlite", "state.sqlite"]) {
643 const file = path.join(stateDir, name);
644 const info = yield* fs.stat(file).pipe(Effect.option);
645 if (Option.isSome(info) && Number(info.value.size) > LARGE_DEV_DATABASE_BYTES) {
646 yield* Effect.logWarning(
647 `[dev-runner] ${file} is ${Math.round(Number(info.value.size) / 1024 / 1024)} MB. With the dev server stopped, \`vp run migrate-dev-db\` rebuilds statev2.sqlite as a small copy of recent data.`,
648 );
649 }
650 }
651 const source = path.join(yield* HostProcess.HomeDirectory, ".t3", "userdata", "statev2.sqlite");
652 // A V1 state.sqlite counts as data too: the server imports it only while
653 // statev2.sqlite is missing, so seeding would hide it.
654 if (
655 input.seed &&
656 !(yield* exists(path.join(stateDir, "statev2.sqlite"))) &&
657 !(yield* exists(path.join(stateDir, "state.sqlite")))
658 ) {
659 const info = yield* fs.stat(source).pipe(Effect.option);
660 if (Option.isSome(info)) {
661 if (Number(info.value.size) > LARGE_DEV_DATABASE_BYTES) {
662 yield* Effect.logWarning(
663 `[dev-runner] ${source} exceeds 500 MiB; skipping automatic database seeding and starting with an empty database. Run \`vp run migrate-dev-db\` manually with dev stopped if needed; it may use substantial disk space before pruning.`,
664 );
665 } else {
666 yield* Effect.logInfo(
667 `[dev-runner] seeding ${input.worktreeHome} from ${source} (read-only). --no-seed or T3CODE_DEV_SEED=0 skips this.`,
668 );
669 yield* runRepoScript(
670 "apps/server/scripts/migrate-dev-db.ts",
671 ["--base-dir", input.worktreeHome, "--source", source],
672 input.env,
673 );
674 }
675 }
676 }
677 }
678
679 const repoRoot = path.dirname(import.meta.dirname);
680 // Dev backends load the monitor from its Cargo output, which a fresh
681 // checkout or worktree does not have yet.
682 if (input.mode !== "dev:web") {
683 const crate = path.join(repoRoot, "native/resource-monitor");
684 const binary =
685 (yield* HostProcess.Platform) === "win32" ? "t3-resource-monitor.exe" : "t3-resource-monitor";
686 if (
687 !(yield* exists(path.join(crate, "target/release", binary))) &&
688 !(yield* exists(path.join(crate, "target/debug", binary)))
689 ) {
690 yield* Effect.logInfo("[dev-runner] building the resource monitor (first start only).");
691 const exitCode = yield* ChildProcess.make(
692 "cargo",
693 ["build", "--locked", "--release", "--manifest-path", path.join(crate, "Cargo.toml")],
694 {
695 cwd: repoRoot,
696 stdin: "ignore",
697 stdout: "inherit",
698 stderr: "inherit",
699 env: input.env,
700 extendEnv: false,
701 },
702 ).pipe(
703 Effect.flatMap((child) => child.exitCode),
704 Effect.scoped,
705 Effect.orElseSucceed(() => -1),
706 );
707 if (exitCode !== 0) {
708 yield* Effect.logWarning(
709 "[dev-runner] could not build the resource monitor; starting without process telemetry. Install Rust and run `vp run build:resource-monitor`.",
710 );
711 }
712 }
713 }
714
715 if (
716 input.mode !== "dev:server" &&
717 !(yield* exists(path.join(repoRoot, "apps/web/node_modules/.vite/deps/_metadata.json")))
718 ) {
719 yield* runRepoScript("apps/web/scripts/warm-dep-cache.ts", [], input.env);
720 }
721});
722
723interface DevRunnerCliInput {
724 readonly mode: DevMode;
725 readonly t3Home: string | undefined;
726 readonly browser: boolean | undefined;
727 readonly autoBootstrapProjectFromCwd: boolean | undefined;
728 readonly logWebSocketEvents: boolean | undefined;
729 readonly host: string | undefined;
730 readonly port: number | undefined;
731 readonly devUrl: URL | undefined;
732 readonly dryRun: boolean;
733 readonly share: boolean;
734 readonly seed?: boolean | undefined;
735 readonly built: boolean;
736 readonly memoryLimitGb?: number | undefined;
737 readonly runArgs: ReadonlyArray<string>;
738}
739
740export const runDevRunnerWithInput = Effect.fn("dev-runner.runDevRunnerWithInput")(function* (
741 input: DevRunnerCliInput,
742) {
743 const { portOffset, devInstance } = yield* OffsetConfig.pipe(
744 Effect.mapError(
745 (cause) =>
746 new DevRunnerConfigurationError({
747 configKeys: ["T3CODE_PORT_OFFSET", "T3CODE_DEV_INSTANCE"],
748 cause,
749 }),
750 ),
751 );
752
753 if (
754 (input.mode === "dev" || input.mode === "dev:web") &&
755 input.host !== undefined &&
756 !isProxiableBindHost(input.host)
757 ) {
758 return yield* new DevRunnerHostNotProxiableError({ mode: input.mode, host: input.host });
759 }
760
761 if (input.built && (input.mode !== "dev" || !input.share)) {
762 return yield* new DevRunnerBuiltNeedsShareError({ mode: input.mode });
763 }
764
765 const worktreePath = yield* resolveGitWorktreePath(yield* HostProcess.WorkingDirectory);
766
767 const { offset, source } = yield* resolveOffset({
768 portOffset,
769 devInstance,
770 worktreePath,
771 });
772
773 const { serverOffset, webOffset } = yield* resolveModePortOffsets({
774 mode: input.mode,
775 startOffset: offset,
776 hasExplicitServerPort: input.port !== undefined,
777 hasExplicitDevUrl: input.devUrl !== undefined,
778 checkPortAvailability: makeDefaultCheckPortAvailability(input.host),
779 });
780
781 const hostEnvironment = yield* HostProcess.Environment;
782 // A dev server started inside a worktree defaults to that worktree's own
783 // (gitignored) `.t3` — see @t3tools/shared/devHome for why this must
784 // outrank an ambient T3CODE_HOME. `--home-dir` still wins.
785 const worktreeHome = yield* resolveWorktreeT3Home(yield* HostProcess.WorkingDirectory);
786 // Trim before choosing: `--home-dir ""` is not a selection, and treating it
787 // as one would skip the worktree default and land on the shared home —
788 // exactly the outcome this precedence exists to prevent.
789 const resolvedT3Home =
790 (input.t3Home?.trim() || undefined) ??
791 worktreeHome ??
792 (hostEnvironment.T3CODE_HOME?.trim() || undefined);
793 const env = yield* createDevRunnerEnv({
794 mode: input.mode,
795 baseEnv: hostEnvironment,
796 serverOffset,
797 webOffset,
798 t3Home: resolvedT3Home,
799 browser: input.browser,
800 autoBootstrapProjectFromCwd: input.autoBootstrapProjectFromCwd,
801 logWebSocketEvents: input.logWebSocketEvents,
802 host: input.host,
803 port: input.port,
804 devUrl: input.devUrl,
805 });
806
807 const selectionSuffix =
808 serverOffset !== offset || webOffset !== offset
809 ? ` selectedOffset(server=${serverOffset},web=${webOffset})`
810 : "";
811 const baseDir = env.T3CODE_HOME ?? (yield* DEFAULT_T3_HOME);
812
813 yield* Effect.logInfo(
814 `[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} baseDir=${baseDir}`,
815 );
816
817 // Before the share block: --dry-run only resolves and prints. Sharing would
818 // replace, then tear down, whatever mapping the port already had — a
819 // surprising side effect from a command documented as inert.
820 if (input.dryRun) {
821 return;
822 }
823
824 // Same state directory as the server's deriveServerPaths, so `dev:web` (no server) skips it.
825 if (input.mode !== "dev:web") {
826 const path = yield* Path.Path;
827 yield* acquireDevRunnerLock(
828 env.T3CODE_HOME ? path.join(env.T3CODE_HOME, "userdata") : path.join(baseDir, "dev"),
829 `pid ${String(process.pid)}, ${input.mode}, server port ${String(env.T3CODE_PORT)}, web port ${String(env.PORT)}`,
830 );
831 }
832
833 const sharedWebPort = BASE_WEB_PORT + webOffset;
834 let built = false;
835 if (input.share) {
836 if (input.mode === "dev:server") {
837 yield* Effect.logInfo("[dev-runner] --share has no effect for dev:server (no web server).");
838 } else if (input.mode === "dev:desktop") {
839 yield* Effect.logWarning(
840 "[dev-runner] --share is not supported for dev:desktop (the renderer is pinned to loopback). Use `dev`, which runs the whole browser stack.",
841 );
842 } else {
843 // acquireRelease, not share-then-addFinalizer: the mapping outlives this
844 // process (and reboots), so the cleanup has to be registered atomically
845 // with creating it. An interrupt landing in between would otherwise
846 // leave a mapping pointing at a port nothing is listening on.
847 const shared = yield* Effect.acquireRelease(
848 shareDevServer({
849 webPort: sharedWebPort,
850 // The backend binds 127.0.0.1 unless --host changes it. A wildcard
851 // still answers there; `--host ::1` binds only the IPv6 loopback, and
852 // `localhost` binds whichever loopback Node resolves first.
853 ...(input.built
854 ? {
855 localTarget: {
856 port: Number(env.T3CODE_PORT),
857 host: sharedBackendTargetHost(input.host),
858 },
859 }
860 : {}),
861 }),
862 () =>
863 unshareDevServer(sharedWebPort).pipe(
864 Effect.flatMap((result) =>
865 result.cleared
866 ? Effect.void
867 : Effect.logWarning(
868 `[dev-runner] could not remove the tailnet mapping for port ${String(sharedWebPort)}${
869 result.explanation ? `: ${result.explanation}` : ""
870 }. Remove it with \`tailscale serve --https=${String(sharedWebPort)} --set-path=/ off\`.`,
871 ),
872 ),
873 ),
874 ).pipe(
875 Effect.tapError((error: DevShareError) =>
876 Effect.logWarning(
877 `[dev-runner] could not share on the tailnet: ${error.message}${
878 error.hint ? ` — ${error.hint}` : ""
879 }`,
880 ),
881 ),
882 Effect.option,
883 Effect.map(Option.getOrUndefined),
884 );
885
886 if (shared) {
887 // The app is reached from the tailnet origin. Vite already allows
888 // *.ts.net hosts; the backend needs the origin for credentialed
889 // requests that bypass the proxy (desktop renderer, direct calls).
890 env.T3CODE_DEV_ALLOWED_ORIGINS = [
891 env.T3CODE_DEV_ALLOWED_ORIGINS,
892 new URL(shared.url).origin,
893 ]
894 .filter((entry) => entry && entry.length > 0)
895 .join(",");
896 if (input.devUrl === undefined) {
897 env.VITE_DEV_SERVER_URL = shared.url;
898 }
899 if (input.built) {
900 built = true;
901 env.T3CODE_BUILT_DEV = "1";
902 } else if (env.T3CODE_BUNDLED_DEV === undefined) {
903 // A shared origin serves a remote browser, where unbundled dev's
904 // per-module requests each pay a tailnet round trip — a cold module
905 // graph takes minutes to first paint. Bundled dev collapses that to a
906 // few chunk requests.
907 env.T3CODE_BUNDLED_DEV = "1";
908 }
909 yield* Effect.logInfo(`[dev-runner] shared on tailnet: ${shared.url}`);
910 } else if (input.built) {
911 yield* Effect.logWarning(
912 "[dev-runner] --built needs the tailnet share; running the Vite dev server instead.",
913 );
914 }
915 }
916 }
917
918 // After sharing, so the warm step sees the same bundled-dev env as Vite.
919 yield* prepareFirstStart({
920 mode: input.mode,
921 seed: input.seed !== false,
922 worktreeHome: baseDir === worktreeHome ? worktreeHome : undefined,
923 env,
924 });
925
926 const args = [...(built ? BUILT_DEV_ARGS : MODE_ARGS[input.mode]), ...input.runArgs];
927 const spawnCommand = yield* resolveSpawnCommand("vp", args, { env });
928 const processContext = {
929 mode: input.mode,
930 executable: "vp" as const,
931 argumentCount: args.length,
932 shell: spawnCommand.shell,
933 } as const;
934 const child = yield* ChildProcess.make(spawnCommand.command, spawnCommand.args, {
935 stdin: "inherit",
936 stdout: "inherit",
937 stderr: "inherit",
938 env,
939 extendEnv: false,
940 shell: spawnCommand.shell,
941 // Its own process group: teardown signals the whole group, because vp
942 // does not pass SIGTERM on to Vite and the server. Windows tears down with
943 // taskkill /T instead, and a detached shell there leaves vp to open a
944 // visible console of its own.
945 detached: (yield* HostProcess.Platform) !== "win32",
946 forceKillAfter: "1500 millis",
947 }).pipe(
948 Effect.mapError(
949 (cause) =>
950 new DevRunnerProcessError({
951 ...processContext,
952 operation: "spawn",
953 cause,
954 }),
955 ),
956 );
957
958 const memoryLimitBytes =
959 input.memoryLimitGb === undefined
960 ? defaultDevMemoryLimitBytes()
961 : input.memoryLimitGb * 1024 ** 3;
962 const exitCode = yield* child.exitCode.pipe(
963 Effect.mapError(
964 (cause) =>
965 new DevRunnerProcessError({
966 ...processContext,
967 operation: "wait-for-exit",
968 cause,
969 }),
970 ),
971 Effect.raceFirst(enforceDevMemoryLimit(memoryLimitBytes)),
972 );
973 if (exitCode !== 0) {
974 return yield* new DevRunnerProcessExitError({
975 ...processContext,
976 exitCode,
977 });
978 }
979});
980
981const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
982
983const devRunnerCli = Command.make("dev-runner", {
984 mode: Argument.Literals("mode", DEV_RUNNER_MODES).pipe(
985 Argument.withDescription("Development mode to run."),
986 ),
987 t3Home: Flag.String("home-dir").pipe(
988 Flag.withDescription(
989 "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.",
990 ),
991 Flag.optional,
992 Flag.map(Option.getOrUndefined),
993 ),
994 browser: Flag.Boolean("browser").pipe(
995 Flag.withDescription("Open a browser automatically (disabled by default for web dev)."),
996 Flag.withDefault(false),
997 ),
998 autoBootstrapProjectFromCwd: Flag.Boolean("auto-bootstrap-project-from-cwd").pipe(
999 Flag.withDescription(
1000 "Auto-bootstrap toggle (equivalent to T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD).",
1001 ),
1002 Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD")),
1003 ),
1004 logWebSocketEvents: Flag.Boolean("log-websocket-events").pipe(
1005 Flag.withDescription("WebSocket event logging toggle (equivalent to T3CODE_LOG_WS_EVENTS)."),
1006 Flag.withAlias("log-ws-events"),
1007 Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_LOG_WS_EVENTS")),
1008 ),
1009 host: Flag.String("host").pipe(
1010 Flag.withDescription(
1011 "Server host/interface override (forwards to T3CODE_HOST). Ambient T3CODE_HOST is ignored: agent shells inherit it from the T3 server that spawned them.",
1012 ),
1013 Flag.optional,
1014 Flag.map(Option.getOrUndefined),
1015 ),
1016 port: Flag.Int("port").pipe(
1017 Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
1018 Flag.withDescription(
1019 "Server port override (forwards to T3CODE_PORT). Ambient T3CODE_PORT is ignored: agent shells inherit it from the T3 server that spawned them.",
1020 ),
1021 Flag.optional,
1022 Flag.map(Option.getOrUndefined),
1023 ),
1024 devUrl: Flag.String("dev-url").pipe(
1025 Flag.withSchema(Schema.URLFromString),
1026 Flag.withDescription(
1027 "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.",
1028 ),
1029 Flag.optional,
1030 Flag.map(Option.getOrUndefined),
1031 ),
1032 dryRun: Flag.Boolean("dry-run").pipe(
1033 Flag.withDescription("Resolve mode/ports/env and print, but do not spawn Vite+."),
1034 Flag.withDefault(false),
1035 ),
1036 share: Flag.Boolean("share").pipe(
1037 Flag.withDescription(
1038 "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.",
1039 ),
1040 Flag.withDefault(false),
1041 ),
1042 seed: Flag.Boolean("seed").pipe(
1043 Flag.withDescription(
1044 "Seed an empty worktree database from ~/.t3 on first start (read-only, via migrate-dev-db) if the source is at most 500 MiB. On by default; --no-seed or T3CODE_DEV_SEED=0 skips it.",
1045 ),
1046 Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_DEV_SEED")),
1047 ),
1048 built: Flag.Boolean("built").pipe(
1049 Flag.withDescription(
1050 "With --share: serve a production web build from the backend instead of the Vite dev server. Rebuilds on change, no HMR, much smaller remote loads.",
1051 ),
1052 Flag.withDefault(false),
1053 ),
1054 memoryLimitGb: Flag.Int("memory-limit-gb").pipe(
1055 Flag.withSchema(NonNegativeInt),
1056 Flag.withDescription(
1057 "Stop the dev server when it and its child processes use more than this many GiB of RAM plus swap (equivalent to T3CODE_DEV_MEMORY_LIMIT_GB). Defaults to half of RAM, at most 16. 0 turns it off. Linux only.",
1058 ),
1059 Flag.withFallbackConfig(
1060 Config.schema(NonNegativeInt, "T3CODE_DEV_MEMORY_LIMIT_GB").pipe(
1061 Config.option,
1062 Config.map(Option.getOrUndefined),
1063 ),
1064 ),
1065 ),
1066 runArgs: Argument.String("run-arg").pipe(
1067 Argument.withDescription("Additional Vite+ run args (pass after `--`)."),
1068 Argument.variadic(),
1069 ),
1070}).pipe(
1071 Command.withDescription("Run monorepo development modes with deterministic port/env wiring."),
1072 Command.withHandler((input) => runDevRunnerWithInput(input)),
1073);
1074
1075const cliRuntimeLayer = Layer.mergeAll(
1076 Logger.layer([Logger.consolePretty()]),
1077 NodeServices.layer,
1078 NetService.layer,
1079);
1080
1081if (import.meta.main) {
1082 // runMain interrupts (running finalizers such as the --share unmapping) only
1083 // on SIGINT/SIGTERM; a closed terminal or dropped SSH session sends SIGHUP.
1084 process.on("SIGHUP", () => process.kill(process.pid, "SIGTERM"));
1085 Command.run(devRunnerCli, { version: "0.0.0" }).pipe(
1086 Effect.scoped,
1087 Effect.provide(cliRuntimeLayer),
1088 NodeRuntime.runMain,
1089 );
1090}