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

dev-runner.ts

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