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

dev-runner.ts

1,109 lines39.1 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 { 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 );
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";
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);
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 }
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 }
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 }
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 }
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 }
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 }
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 }
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" });
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;
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 };
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];
460​
461// Windows reserves port ranges (Hyper-V, WSL, Docker), so one port can be denied while binding
462// still works.
463const probePortSkippingReserved = (
464 net: NetService.NetServiceShape,
465 port: number,
466 host: string,
467): Effect.Effect<boolean, NetService.NetListenError> =>
468 net.probeListenOnHost(port, host).pipe(
469 Effect.catchTags({
470 NetListenError: (error) =>
471 error.code === "EACCES" || error.code === "EPERM"
472 ? net.probeListenOnHost(0, host).pipe(
473 Effect.as(false),
474 Effect.mapError(() => error),
475 )
476 : Effect.fail(error),
477 }),
478 );
479​
480const makeDefaultCheckPortAvailability =
481 (configuredHost: string | undefined): PortAvailabilityCheck<NetService.NetService> =>
482 (port, role) =>
483 Effect.gen(function* () {
484 const net = yield* NetService.NetService;
485 const hosts = role === "web" ? DEV_PORT_PROBE_HOSTS : devPortProbeHosts(configuredHost);
486 return yield* checkPortAvailabilityOnHosts(port, hosts, (candidatePort, host) =>
487 probePortSkippingReserved(net, candidatePort, host),
488 );
489 });
490​
491const defaultCheckPortAvailability = makeDefaultCheckPortAvailability(undefined);
492​
493interface FindFirstAvailableOffsetInput<R = NetService.NetService> {
494 readonly startOffset: number;
495 readonly requireServerPort: boolean;
496 readonly requireWebPort: boolean;
497 readonly checkPortAvailability?: PortAvailabilityCheck<R>;
499​
500export const findFirstAvailableOffset = Effect.fn("dev-runner.findFirstAvailableOffset")(function* <
501 R = NetService.NetService,
502>({
503 startOffset,
504 requireServerPort,
505 requireWebPort,
506 checkPortAvailability,
507}: FindFirstAvailableOffsetInput<R>): Effect.fn.Return<
508 number,
509 DevRunnerPortExhaustedError | NetService.NetListenError,
510 R
511> {
512 const checkPort = (checkPortAvailability ??
513 defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
514​
515 for (let candidate = startOffset; ; candidate += 1) {
516 const { serverPort, webPort } = portPairForOffset(candidate);
517 const serverPortOutOfRange = serverPort > MAX_PORT;
518 const webPortOutOfRange = webPort > MAX_PORT;
519​
520 if (
521 (requireServerPort && serverPortOutOfRange) ||
522 (requireWebPort && webPortOutOfRange) ||
523 (!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange))
524 ) {
525 break;
526 }
527​
528 if (requireWebPort && !isBrowserAllowedPort(webPort)) {
529 continue;
530 }
531​
532 const checks: Array<Effect.Effect<boolean, NetService.NetListenError, R>> = [];
533 if (requireServerPort) {
534 checks.push(checkPort(serverPort, "server"));
535 }
536 if (requireWebPort) {
537 checks.push(checkPort(webPort, "web"));
538 }
539​
540 if (checks.length === 0) {
541 return candidate;
542 }
543​
544 const availability = yield* Effect.all(checks);
545 if (availability.every(Boolean)) {
546 return candidate;
547 }
548 }
549​
550 return yield* new DevRunnerPortExhaustedError({
551 startOffset,
552 requireServerPort,
553 requireWebPort,
554 baseServerPort: BASE_SERVER_PORT,
555 baseWebPort: BASE_WEB_PORT,
556 maximumPort: MAX_PORT,
557 });
558});
559​
560interface ResolveModePortOffsetsInput<R = NetService.NetService> {
561 readonly mode: DevMode;
562 readonly startOffset: number;
563 readonly hasExplicitServerPort: boolean;
564 readonly hasExplicitDevUrl: boolean;
565 readonly checkPortAvailability?: PortAvailabilityCheck<R>;
567​
568export const resolveModePortOffsets = Effect.fn("dev-runner.resolveModePortOffsets")(function* <
569 R = NetService.NetService,
570>({
571 mode,
572 startOffset,
573 hasExplicitServerPort,
574 hasExplicitDevUrl,
575 checkPortAvailability,
576}: ResolveModePortOffsetsInput<R>): Effect.fn.Return<
577 { readonly serverOffset: number; readonly webOffset: number },
578 DevRunnerPortExhaustedError | NetService.NetListenError,
579 R
580> {
581 const checkPort = (checkPortAvailability ??
582 defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
583​
584 if (mode === "dev:web") {
585 if (hasExplicitDevUrl) {
586 return { serverOffset: startOffset, webOffset: startOffset };
587 }
588​
589 const webOffset = yield* findFirstAvailableOffset({
590 startOffset,
591 requireServerPort: false,
592 requireWebPort: true,
593 checkPortAvailability: checkPort,
594 });
595 return { serverOffset: startOffset, webOffset };
596 }
597​
598 if (mode === "dev:server") {
599 if (hasExplicitServerPort) {
600 return { serverOffset: startOffset, webOffset: startOffset };
601 }
602​
603 const serverOffset = yield* findFirstAvailableOffset({
604 startOffset,
605 requireServerPort: true,
606 requireWebPort: false,
607 checkPortAvailability: checkPort,
608 });
609 return { serverOffset, webOffset: serverOffset };
610 }
611​
612 const sharedOffset = yield* findFirstAvailableOffset({
613 startOffset,
614 requireServerPort: !hasExplicitServerPort,
615 requireWebPort: !hasExplicitDevUrl,
616 checkPortAvailability: checkPort,
617 });
618​
619 return { serverOffset: sharedOffset, webOffset: sharedOffset };
620});
621​
622/** Best effort: a failed first-start step warns, and dev still starts. */
623const runRepoScript = Effect.fn("dev-runner.runRepoScript")(function* (
624 script: string,
625 args: ReadonlyArray<string>,
626 env: NodeJS.ProcessEnv,
627) {
628 const path = yield* Path.Path;
629 const repoRoot = path.dirname(import.meta.dirname);
630 const exitCode = yield* ChildProcess.make(
631 yield* HostProcess.ExecutablePath,
632 [path.join(repoRoot, script), ...args],
633 { cwd: repoRoot, stdin: "ignore", stdout: "inherit", stderr: "inherit", env, extendEnv: false },
634 ).pipe(
635 Effect.flatMap((child) => child.exitCode),
636 Effect.scoped,
637 Effect.orElseSucceed(() => -1),
638 );
639 if (exitCode !== 0) {
640 yield* Effect.logWarning(`[dev-runner] ${script} failed; starting anyway.`);
641 }
642});
643​
644/**
645 * The first start in a worktree seeds its empty database from a small live database,
646 * builds the native resource monitor, and warms the web dependency cache. Each step
647 * checks for its own output, so later starts skip it.
648 */
649const prepareFirstStart = Effect.fn("dev-runner.prepareFirstStart")(function* (input: {
650 readonly mode: DevMode;
651 readonly seed: boolean;
652 readonly worktreeHome: string | undefined;
653 readonly env: NodeJS.ProcessEnv;
654}) {
655 const fs = yield* FileSystem.FileSystem;
656 const path = yield* Path.Path;
657 const exists = (file: string) => fs.exists(file).pipe(Effect.orElseSucceed(() => false));
658​
659 if (input.worktreeHome !== undefined && input.mode !== "dev:web") {
660 const stateDir = path.join(input.worktreeHome, "userdata");
661 for (const name of ["statev2.sqlite", "state.sqlite"]) {
662 const file = path.join(stateDir, name);
663 const info = yield* fs.stat(file).pipe(Effect.option);
664 if (Option.isSome(info) && Number(info.value.size) > LARGE_DEV_DATABASE_BYTES) {
665 yield* Effect.logWarning(
666 `[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.`,
667 );
668 }
669 }
670 const source = path.join(yield* HostProcess.HomeDirectory, ".t3", "userdata", "statev2.sqlite");
671 // A V1 state.sqlite counts as data too: the server imports it only while
672 // statev2.sqlite is missing, so seeding would hide it.
673 if (
674 input.seed &&
675 !(yield* exists(path.join(stateDir, "statev2.sqlite"))) &&
676 !(yield* exists(path.join(stateDir, "state.sqlite")))
677 ) {
678 const info = yield* fs.stat(source).pipe(Effect.option);
679 if (Option.isSome(info)) {
680 if (Number(info.value.size) > LARGE_DEV_DATABASE_BYTES) {
681 yield* Effect.logWarning(
682 `[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.`,
683 );
684 } else {
685 yield* Effect.logInfo(
686 `[dev-runner] seeding ${input.worktreeHome} from ${source} (read-only). --no-seed or T3CODE_DEV_SEED=0 skips this.`,
687 );
688 yield* runRepoScript(
689 "apps/server/scripts/migrate-dev-db.ts",
690 ["--base-dir", input.worktreeHome, "--source", source],
691 input.env,
692 );
693 }
694 }
695 }
696 }
697​
698 const repoRoot = path.dirname(import.meta.dirname);
699 // Dev backends load the monitor from its Cargo output, which a fresh
700 // checkout or worktree does not have yet.
701 if (input.mode !== "dev:web") {
702 const crate = path.join(repoRoot, "native/resource-monitor");
703 const binary =
704 (yield* HostProcess.Platform) === "win32" ? "t3-resource-monitor.exe" : "t3-resource-monitor";
705 if (
706 !(yield* exists(path.join(crate, "target/release", binary))) &&
707 !(yield* exists(path.join(crate, "target/debug", binary)))
708 ) {
709 yield* Effect.logInfo("[dev-runner] building the resource monitor (first start only).");
710 const exitCode = yield* ChildProcess.make(
711 "cargo",
712 ["build", "--locked", "--release", "--manifest-path", path.join(crate, "Cargo.toml")],
713 {
714 cwd: repoRoot,
715 stdin: "ignore",
716 stdout: "inherit",
717 stderr: "inherit",
718 env: input.env,
719 extendEnv: false,
720 },
721 ).pipe(
722 Effect.flatMap((child) => child.exitCode),
723 Effect.scoped,
724 Effect.orElseSucceed(() => -1),
725 );
726 if (exitCode !== 0) {
727 yield* Effect.logWarning(
728 "[dev-runner] could not build the resource monitor; starting without process telemetry. Install Rust and run `vp run build:resource-monitor`.",
729 );
730 }
731 }
732 }
733​
734 if (
735 input.mode !== "dev:server" &&
736 !(yield* exists(path.join(repoRoot, "apps/web/node_modules/.vite/deps/_metadata.json")))
737 ) {
738 yield* runRepoScript("apps/web/scripts/warm-dep-cache.ts", [], input.env);
739 }
740});
741​
742interface DevRunnerCliInput {
743 readonly mode: DevMode;
744 readonly t3Home: string | undefined;
745 readonly browser: boolean | undefined;
746 readonly autoBootstrapProjectFromCwd: boolean | undefined;
747 readonly logWebSocketEvents: boolean | undefined;
748 readonly host: string | undefined;
749 readonly port: number | undefined;
750 readonly devUrl: URL | undefined;
751 readonly dryRun: boolean;
752 readonly share: boolean;
753 readonly seed?: boolean | undefined;
754 readonly built: boolean;
755 readonly memoryLimitGb?: number | undefined;
756 readonly runArgs: ReadonlyArray<string>;
758​
759export const runDevRunnerWithInput = Effect.fn("dev-runner.runDevRunnerWithInput")(function* (
760 input: DevRunnerCliInput,
761) {
762 const { portOffset, devInstance } = yield* OffsetConfig.pipe(
763 Effect.mapError(
764 (cause) =>
765 new DevRunnerConfigurationError({
766 configKeys: ["T3CODE_PORT_OFFSET", "T3CODE_DEV_INSTANCE"],
767 cause,
768 }),
769 ),
770 );
771​
772 if (
773 (input.mode === "dev" || input.mode === "dev:web") &&
774 input.host !== undefined &&
775 !isProxiableBindHost(input.host)
776 ) {
777 return yield* new DevRunnerHostNotProxiableError({ mode: input.mode, host: input.host });
778 }
779​
780 if (input.built && (input.mode !== "dev" || !input.share)) {
781 return yield* new DevRunnerBuiltNeedsShareError({ mode: input.mode });
782 }
783​
784 const worktreePath = yield* resolveGitWorktreePath(yield* HostProcess.WorkingDirectory);
785​
786 const { offset, source } = yield* resolveOffset({
787 portOffset,
788 devInstance,
789 worktreePath,
790 });
791​
792 const { serverOffset, webOffset } = yield* resolveModePortOffsets({
793 mode: input.mode,
794 startOffset: offset,
795 hasExplicitServerPort: input.port !== undefined,
796 hasExplicitDevUrl: input.devUrl !== undefined,
797 checkPortAvailability: makeDefaultCheckPortAvailability(input.host),
798 });
799​
800 const hostEnvironment = yield* HostProcess.Environment;
801 // A dev server started inside a worktree defaults to that worktree's own
802 // (gitignored) `.t3` — see @t3tools/shared/devHome for why this must
803 // outrank an ambient T3CODE_HOME. `--home-dir` still wins.
804 const worktreeHome = yield* resolveWorktreeT3Home(yield* HostProcess.WorkingDirectory);
805 // Trim before choosing: `--home-dir ""` is not a selection, and treating it
806 // as one would skip the worktree default and land on the shared home —
807 // exactly the outcome this precedence exists to prevent.
808 const resolvedT3Home =
809 (input.t3Home?.trim() || undefined) ??
810 worktreeHome ??
811 (hostEnvironment.T3CODE_HOME?.trim() || undefined);
812 const env = yield* createDevRunnerEnv({
813 mode: input.mode,
814 baseEnv: hostEnvironment,
815 serverOffset,
816 webOffset,
817 t3Home: resolvedT3Home,
818 browser: input.browser,
819 autoBootstrapProjectFromCwd: input.autoBootstrapProjectFromCwd,
820 logWebSocketEvents: input.logWebSocketEvents,
821 host: input.host,
822 port: input.port,
823 devUrl: input.devUrl,
824 });
825​
826 const selectionSuffix =
827 serverOffset !== offset || webOffset !== offset
828 ? ` selectedOffset(server=${serverOffset},web=${webOffset})`
829 : "";
830 const baseDir = env.T3CODE_HOME ?? (yield* DEFAULT_T3_HOME);
831​
832 yield* Effect.logInfo(
833 `[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} baseDir=${baseDir}`,
834 );
835​
836 // Before the share block: --dry-run only resolves and prints. Sharing would
837 // replace, then tear down, whatever mapping the port already had — a
838 // surprising side effect from a command documented as inert.
839 if (input.dryRun) {
840 return;
841 }
842​
843 // Same state directory as the server's deriveServerPaths, so `dev:web` (no server) skips it.
844 if (input.mode !== "dev:web") {
845 const path = yield* Path.Path;
846 yield* acquireDevRunnerLock(
847 env.T3CODE_HOME ? path.join(env.T3CODE_HOME, "userdata") : path.join(baseDir, "dev"),
848 `pid ${String(process.pid)}, ${input.mode}, server port ${String(env.T3CODE_PORT)}, web port ${String(env.PORT)}`,
849 );
850 }
851​
852 const sharedWebPort = BASE_WEB_PORT + webOffset;
853 let built = false;
854 if (input.share) {
855 if (input.mode === "dev:server") {
856 yield* Effect.logInfo("[dev-runner] --share has no effect for dev:server (no web server).");
857 } else if (input.mode === "dev:desktop") {
858 yield* Effect.logWarning(
859 "[dev-runner] --share is not supported for dev:desktop (the renderer is pinned to loopback). Use `dev`, which runs the whole browser stack.",
860 );
861 } else {
862 // acquireRelease, not share-then-addFinalizer: the mapping outlives this
863 // process (and reboots), so the cleanup has to be registered atomically
864 // with creating it. An interrupt landing in between would otherwise
865 // leave a mapping pointing at a port nothing is listening on.
866 const shared = yield* Effect.acquireRelease(
867 shareDevServer({
868 webPort: sharedWebPort,
869 // The backend binds 127.0.0.1 unless --host changes it. A wildcard
870 // still answers there; `--host ::1` binds only the IPv6 loopback, and
871 // `localhost` binds whichever loopback Node resolves first.
872 ...(input.built
873 ? {
874 localTarget: {
875 port: Number(env.T3CODE_PORT),
876 host: sharedBackendTargetHost(input.host),
877 },
878 }
879 : {}),
880 }),
881 () =>
882 unshareDevServer(sharedWebPort).pipe(
883 Effect.flatMap((result) =>
884 result.cleared
885 ? Effect.void
886 : Effect.logWarning(
887 `[dev-runner] could not remove the tailnet mapping for port ${String(sharedWebPort)}${
888 result.explanation ? `: ${result.explanation}` : ""
889 }. Remove it with \`tailscale serve --https=${String(sharedWebPort)} --set-path=/ off\`.`,
890 ),
891 ),
892 ),
893 ).pipe(
894 Effect.tapError((error: DevShareError) =>
895 Effect.logWarning(
896 `[dev-runner] could not share on the tailnet: ${error.message}${
897 error.hint ? ` — ${error.hint}` : ""
898 }`,
899 ),
900 ),
901 Effect.option,
902 Effect.map(Option.getOrUndefined),
903 );
904​
905 if (shared) {
906 // The app is reached from the tailnet origin. Vite already allows
907 // *.ts.net hosts; the backend needs the origin for credentialed
908 // requests that bypass the proxy (desktop renderer, direct calls).
909 env.T3CODE_DEV_ALLOWED_ORIGINS = [
910 env.T3CODE_DEV_ALLOWED_ORIGINS,
911 new URL(shared.url).origin,
912 ]
913 .filter((entry) => entry && entry.length > 0)
914 .join(",");
915 if (input.devUrl === undefined) {
916 env.VITE_DEV_SERVER_URL = shared.url;
917 }
918 if (input.built) {
919 built = true;
920 env.T3CODE_BUILT_DEV = "1";
921 } else if (env.T3CODE_BUNDLED_DEV === undefined) {
922 // A shared origin serves a remote browser, where unbundled dev's
923 // per-module requests each pay a tailnet round trip — a cold module
924 // graph takes minutes to first paint. Bundled dev collapses that to a
925 // few chunk requests.
926 env.T3CODE_BUNDLED_DEV = "1";
927 }
928 yield* Effect.logInfo(`[dev-runner] shared on tailnet: ${shared.url}`);
929 } else if (input.built) {
930 yield* Effect.logWarning(
931 "[dev-runner] --built needs the tailnet share; running the Vite dev server instead.",
932 );
933 }
934 }
935 }
936​
937 // After sharing, so the warm step sees the same bundled-dev env as Vite.
938 yield* prepareFirstStart({
939 mode: input.mode,
940 seed: input.seed !== false,
941 worktreeHome: baseDir === worktreeHome ? worktreeHome : undefined,
942 env,
943 });
944​
945 const args = [...(built ? BUILT_DEV_ARGS : MODE_ARGS[input.mode]), ...input.runArgs];
946 const spawnCommand = yield* resolveSpawnCommand("vp", args, { env });
947 const processContext = {
948 mode: input.mode,
949 executable: "vp" as const,
950 argumentCount: args.length,
951 shell: spawnCommand.shell,
952 } as const;
953 const child = yield* ChildProcess.make(spawnCommand.command, spawnCommand.args, {
954 stdin: "inherit",
955 stdout: "inherit",
956 stderr: "inherit",
957 env,
958 extendEnv: false,
959 shell: spawnCommand.shell,
960 // Its own process group: teardown signals the whole group, because vp
961 // does not pass SIGTERM on to Vite and the server. Windows tears down with
962 // taskkill /T instead, and a detached shell there leaves vp to open a
963 // visible console of its own.
964 detached: (yield* HostProcess.Platform) !== "win32",
965 forceKillAfter: "1500 millis",
966 }).pipe(
967 Effect.mapError(
968 (cause) =>
969 new DevRunnerProcessError({
970 ...processContext,
971 operation: "spawn",
972 cause,
973 }),
974 ),
975 );
976​
977 const memoryLimitBytes =
978 input.memoryLimitGb === undefined
979 ? defaultDevMemoryLimitBytes()
980 : input.memoryLimitGb * 1024 ** 3;
981 const exitCode = yield* child.exitCode.pipe(
982 Effect.mapError(
983 (cause) =>
984 new DevRunnerProcessError({
985 ...processContext,
986 operation: "wait-for-exit",
987 cause,
988 }),
989 ),
990 Effect.raceFirst(enforceDevMemoryLimit(memoryLimitBytes)),
991 );
992 if (exitCode !== 0) {
993 return yield* new DevRunnerProcessExitError({
994 ...processContext,
995 exitCode,
996 });
997 }
998});
999​
1000const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
1001​
1002const devRunnerCli = Command.make("dev-runner", {
1003 mode: Argument.Literals("mode", DEV_RUNNER_MODES).pipe(
1004 Argument.withDescription("Development mode to run."),
1005 ),
1006 t3Home: Flag.String("home-dir").pipe(
1007 Flag.withDescription(
1008 "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.",
1009 ),
1010 Flag.optional,
1011 Flag.map(Option.getOrUndefined),
1012 ),
1013 browser: Flag.Boolean("browser").pipe(
1014 Flag.withDescription("Open a browser automatically (disabled by default for web dev)."),
1015 Flag.withDefault(false),
1016 ),
1017 autoBootstrapProjectFromCwd: Flag.Boolean("auto-bootstrap-project-from-cwd").pipe(
1018 Flag.withDescription(
1019 "Auto-bootstrap toggle (equivalent to T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD).",
1020 ),
1021 Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD")),
1022 ),
1023 logWebSocketEvents: Flag.Boolean("log-websocket-events").pipe(
1024 Flag.withDescription("WebSocket event logging toggle (equivalent to T3CODE_LOG_WS_EVENTS)."),
1025 Flag.withAlias("log-ws-events"),
1026 Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_LOG_WS_EVENTS")),
1027 ),
1028 host: Flag.String("host").pipe(
1029 Flag.withDescription(
1030 "Server host/interface override (forwards to T3CODE_HOST). Ambient T3CODE_HOST is ignored: agent shells inherit it from the T3 server that spawned them.",
1031 ),
1032 Flag.optional,
1033 Flag.map(Option.getOrUndefined),
1034 ),
1035 port: Flag.Int("port").pipe(
1036 Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
1037 Flag.withDescription(
1038 "Server port override (forwards to T3CODE_PORT). Ambient T3CODE_PORT is ignored: agent shells inherit it from the T3 server that spawned them.",
1039 ),
1040 Flag.optional,
1041 Flag.map(Option.getOrUndefined),
1042 ),
1043 devUrl: Flag.String("dev-url").pipe(
1044 Flag.withSchema(Schema.URLFromString),
1045 Flag.withDescription(
1046 "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.",
1047 ),
1048 Flag.optional,
1049 Flag.map(Option.getOrUndefined),
1050 ),
1051 dryRun: Flag.Boolean("dry-run").pipe(
1052 Flag.withDescription("Resolve mode/ports/env and print, but do not spawn Vite+."),
1053 Flag.withDefault(false),
1054 ),
1055 share: Flag.Boolean("share").pipe(
1056 Flag.withDescription(
1057 "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.",
1058 ),
1059 Flag.withDefault(false),
1060 ),
1061 seed: Flag.Boolean("seed").pipe(
1062 Flag.withDescription(
1063 "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.",
1064 ),
1065 Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_DEV_SEED")),
1066 ),
1067 built: Flag.Boolean("built").pipe(
1068 Flag.withDescription(
1069 "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.",
1070 ),
1071 Flag.withDefault(false),
1072 ),
1073 memoryLimitGb: Flag.Int("memory-limit-gb").pipe(
1074 Flag.withSchema(NonNegativeInt),
1075 Flag.withDescription(
1076 "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.",
1077 ),
1078 Flag.withFallbackConfig(
1079 Config.schema(NonNegativeInt, "T3CODE_DEV_MEMORY_LIMIT_GB").pipe(
1080 Config.option,
1081 Config.map(Option.getOrUndefined),
1082 ),
1083 ),
1084 ),
1085 runArgs: Argument.String("run-arg").pipe(
1086 Argument.withDescription("Additional Vite+ run args (pass after `--`)."),
1087 Argument.variadic(),
1088 ),
1089}).pipe(
1090 Command.withDescription("Run monorepo development modes with deterministic port/env wiring."),
1091 Command.withHandler((input) => runDevRunnerWithInput(input)),
1093​
1094const cliRuntimeLayer = Layer.mergeAll(
1095 Logger.layer([Logger.consolePretty()]),
1096 NodeServices.layer,
1097 NetService.layer,
1099​
1100if (import.meta.main) {
1101 // runMain interrupts (running finalizers such as the --share unmapping) only
1102 // on SIGINT/SIGTERM; a closed terminal or dropped SSH session sends SIGHUP.
1103 process.on("SIGHUP", () => process.kill(process.pid, "SIGTERM"));
1104 Command.run(devRunnerCli, { version: "0.0.0" }).pipe(
1105 Effect.scoped,
1106 Effect.provide(cliRuntimeLayer),
1107 NodeRuntime.runMain,
1108 );