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