TypeScript
perf(dev): faster first load for shared dev servers (#22776)
Theo Browne1dfb57287174
diff --git a/apps/server/package.json b/apps/server/package.jsonindex b29b7cc3370..44a2abf3800 100644--- a/apps/server/package.json+++ b/apps/server/package.json@@ -16,6 +16,7 @@"type": "module","scripts": {"dev": "node --watch --watch-path=src --watch-path=../../packages --watch-path=package.json src/bin.ts",+ "dev:built": "vp run dev","build:bundle": "vp pack","build:exe": "node scripts/cli.ts build-exe","start": "node dist/bin.mjs",diff --git a/apps/server/src/http.ts b/apps/server/src/http.tsindex 6ba9579f04b..8871a5df345 100644--- a/apps/server/src/http.ts+++ b/apps/server/src/http.ts@@ -581,6 +581,14 @@ const handleStaticAndDevRequest = Effect.fn("handleStaticAndDevRequest")(const staticDir =config.staticDir ?? (config.devUrl ? yield* ServerConfig.resolveStaticDir() : undefined);+ if (!staticDir && config.devUrl) {+ // `vp run dev --share --built` prints the pairing URL before its first+ // web build lands in apps/web/dist. Reload until it does.+ return HttpServerResponse.text(+ '<!doctype html><meta http-equiv="refresh" content="2"><p>Waiting for the first web build. This page reloads by itself.</p>',+ { status: 503, contentType: "text/html", headers: { "Retry-After": "2" } },+ );+ }if (!staticDir) {return HttpServerResponse.text("No static directory configured and no dev URL set.", {status: 503,diff --git a/apps/web/package.json b/apps/web/package.jsonindex 8e217119277..1fc7fd6eb5f 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -6,6 +6,7 @@"scripts": {"build:ghostty-wasm": "bash scripts/build-libghostty-wasm.sh","dev": "vp dev",+ "dev:built": "vp build --watch","build": "vp build","preview": "vp preview","test": "vp test run --passWithNoTests --project unit --project browser"diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.tsindex 6b91bf21de6..f376d7b6eb2 100644--- a/apps/web/vite.config.ts+++ b/apps/web/vite.config.ts@@ -62,6 +62,10 @@ const configuredHostedAppUrl = (() => {})();const sourcemapEnv = process.env.T3CODE_WEB_SOURCEMAP?.trim().toLowerCase();+// `vp run dev --share --built` rebuilds on every change. The license manifest+// is about 2 s of each build, and nothing in that mode reads it.+const builtDev = process.env.T3CODE_BUILT_DEV === "1";+const bundledDevEnv = process.env.T3CODE_BUNDLED_DEV?.trim().toLowerCase();const bundledDev = bundledDevEnv === "1" || bundledDevEnv === "true";@@ -196,15 +200,17 @@ export default defineConfig(() => {assetsInclude: ["**/*.wasm"],plugins: [devCompressionPlugin(),- thirdPartyLicensesPlugin({- bundleName: "web",- configFile: new URL("../../third-party-licenses.config.json", import.meta.url),- packageManifests: [- { bundle: "web", path: new URL("./package.json", import.meta.url) },- { bundle: "server", path: new URL("../server/package.json", import.meta.url) },- { bundle: "desktop", path: new URL("../desktop/package.json", import.meta.url) },- ],- }),+ builtDev+ ? undefined+ : thirdPartyLicensesPlugin({+ bundleName: "web",+ configFile: new URL("../../third-party-licenses.config.json", import.meta.url),+ packageManifests: [+ { bundle: "web", path: new URL("./package.json", import.meta.url) },+ { bundle: "server", path: new URL("../server/package.json", import.meta.url) },+ { bundle: "desktop", path: new URL("../desktop/package.json", import.meta.url) },+ ],+ }),tanstackRouter({ autoCodeSplitting: true }),react({ compiler: true }),tailwindPlugins(bundledDev),diff --git a/docs/operations/development.md b/docs/operations/development.mdindex 5fcd6883641..8f4feef0d76 100644--- a/docs/operations/development.md+++ b/docs/operations/development.md@@ -60,6 +60,14 @@ The workarounds live in the [web entry](../../apps/web/src/bootstrap.ts),[Tailwind plugin](../../apps/web/vite/tailwind.ts), and[startup warmup](../../apps/web/vite/warmBundledDev.ts).+`vp run dev --share --built` skips the Vite dev server. It runs `vp build --watch` for the web+app, and the backend serves `apps/web/dist` on the same tailnet URL and pairing flow. Use it when+someone tests over a slow link or only needs to use the app: loads are production size, and the+first load does not wait for dev bundling. There is no HMR. After an edit, wait for the+`built in` line (about 6 s), then reload. Until the first build exists, the URL shows a page that+reloads by itself. The license manifest is not generated in this mode. `--built` requires+`--share` and the `dev` mode.+#### Reusable dev credentialUse this only on a hostname where you trust every service. Browsers send cookies to all portsdiff --git a/scripts/dev-runner.test.ts b/scripts/dev-runner.test.tsindex cdf4ea2cc0f..95b43ddd735 100644--- a/scripts/dev-runner.test.ts+++ b/scripts/dev-runner.test.ts@@ -62,6 +62,7 @@ const devServerInput = {devUrl: undefined,dryRun: false,share: false,+ built: false,runArgs: ["--inspect", "secret-token-value"],} as const;@@ -420,10 +421,16 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {// per-module waterfall pays a tailnet round trip per import level. The// runner defaults bundled dev on for the spawned stack, but only// defaults: an explicit T3CODE_BUNDLED_DEV (even "0") must pass through.- describe("--share bundled dev default", () => {- const shareSpawnedEnv = (input: { readonly ambientBundledDev: string | undefined }) =>+ describe("--share spawn wiring", () => {+ const shareSpawned = (input: {+ readonly ambientBundledDev?: string | undefined;+ readonly built?: boolean;+ readonly host?: string;+ }) =>Effect.gen(function* () {let captured: Record<string, string | undefined> | undefined;+ let vpArgs: ReadonlyArray<string> = [];+ const tailscaleCalls: Array<ReadonlyArray<string>> = [];const spawnerLayer = Layer.succeed(ChildProcessSpawner.ChildProcessSpawner,ChildProcessSpawner.make((command) => {@@ -434,8 +441,10 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {};if (spawned.command === "vp") {captured = spawned.options?.env;+ vpArgs = spawned.args;return Effect.succeed(mockProcess(0));}+ tailscaleCalls.push(spawned.args);return Effect.succeed(ChildProcessSpawner.makeHandle({pid: ChildProcessSpawner.ProcessId(2),@@ -465,6 +474,8 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {mode: "dev",port: undefined,share: true,+ built: input.built ?? false,+ host: input.host,}).pipe(Effect.provide(Layer.mergeAll(emptyConfigLayer, netServiceLayer, spawnerLayer)),Effect.provideService(HostProcess.Platform, "linux"),@@ -476,15 +487,76 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {),);- return captured;+ return { env: captured, vpArgs, tailscaleCalls };});it.effect("keeps an explicit T3CODE_BUNDLED_DEV=0 opt-out", () =>Effect.gen(function* () {- const env = yield* shareSpawnedEnv({ ambientBundledDev: "0" });+ const { env } = yield* shareSpawned({ ambientBundledDev: "0" });assert.equal(env?.T3CODE_BUNDLED_DEV, "0");}),);++ it.effect("--built serves the backend on the web port's tailnet URL", () =>+ Effect.gen(function* () {+ const { env, vpArgs, tailscaleCalls } = yield* shareSpawned({ built: true });+ assert.include(vpArgs, "dev:built");+ assert.equal(env?.T3CODE_BUILT_DEV, "1");+ assert.equal(env?.T3CODE_BUNDLED_DEV, undefined);+ assert.equal(env?.VITE_DEV_SERVER_URL, `https://host.example.ts.net:${env?.PORT}/`);+ const serve = tailscaleCalls.find((args) => args.includes("--bg"));+ assert.deepEqual(serve?.slice(-2), [+ `--https=${env?.PORT}`,+ `http://127.0.0.1:${env?.T3CODE_PORT}`,+ ]);+ }),+ );++ it.effect("--built --host ::1 targets the backend's IPv6 loopback", () =>+ Effect.gen(function* () {+ const { env, tailscaleCalls } = yield* shareSpawned({ built: true, host: "::1" });+ const serve = tailscaleCalls.find((args) => args.includes("--bg"));+ assert.equal(serve?.at(-1), `http://[::1]:${env?.T3CODE_PORT}`);+ }),+ );++ it.effect("without --built keeps Vite behind the tailnet URL", () =>+ Effect.gen(function* () {+ const { env, vpArgs, tailscaleCalls } = yield* shareSpawned({});+ assert.include(vpArgs, "dev");+ assert.notInclude(vpArgs, "dev:built");+ assert.equal(env?.T3CODE_BUNDLED_DEV, "1");+ const serve = tailscaleCalls.find((args) => args.includes("--bg"));+ assert.equal(serve?.at(-1), `http://localhost:${env?.PORT}`);+ }),+ );+ });++ it.effect.each([+ { mode: "dev", share: false },+ { mode: "dev:web", share: true },+ { mode: "dev:desktop", share: true },+ ] as const)("rejects --built for $mode with share=$share", ({ mode, share }) => {+ const spawnerLayer = Layer.succeed(+ ChildProcessSpawner.ChildProcessSpawner,+ ChildProcessSpawner.make(() => Effect.succeed(mockProcess(0))),+ );++ return Effect.gen(function* () {+ const error = yield* runDevRunnerWithInput({+ ...devServerInput,+ mode,+ port: undefined,+ share,+ built: true,+ }).pipe(+ Effect.provide(Layer.mergeAll(emptyConfigLayer, netServiceLayer, spawnerLayer)),+ Effect.provideService(HostProcess.Platform, "linux"),+ Effect.flip,+ );++ assert.equal(error._tag, "DevRunnerBuiltNeedsShareError");+ });});it.effect("reports non-zero exits without manufacturing a cause", () => {diff --git a/scripts/dev-runner.ts b/scripts/dev-runner.tsindex 391941a7271..ff09a66e9da 100644--- a/scripts/dev-runner.ts+++ b/scripts/dev-runner.ts@@ -84,6 +84,16 @@ const MODE_ARGS = {"dev:desktop": ["run", "--filter=@t3tools/desktop", "--filter=@t3tools/web", "dev"],} as const satisfies Record<string, ReadonlyArray<string>>;+// `--built`: the web package rebuilds into apps/web/dist and the backend serves+// it, so no Vite dev server runs.+const BUILT_DEV_ARGS = [+ "run",+ "--filter=@t3tools/web",+ "--filter=t3",+ "--parallel",+ "dev:built",+] as const;+type DevMode = keyof typeof MODE_ARGS;/*** `role` matters because only the backend honours `--host`/`T3CODE_HOST`; the@@ -184,6 +194,17 @@ export class DevRunnerHostNotProxiableError extends Schema.TaggedError<DevRunner}}+export class DevRunnerBuiltNeedsShareError extends Schema.TaggedError<DevRunnerBuiltNeedsShareError>()(+ "DevRunnerBuiltNeedsShareError",+ {+ mode: Schema.Literals(["dev", "dev:server", "dev:web", "dev:desktop"]),+ },+) {+ override get message(): string {+ 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.`;+ }+}+const optionalStringConfig = (name: string): Config.Config<string | undefined> =>Config.String(name).pipe(Config.option,@@ -659,6 +680,7 @@ interface DevRunnerCliInput {readonly dryRun: boolean;readonly share: boolean;readonly seed?: boolean | undefined;+ readonly built: boolean;readonly runArgs: ReadonlyArray<string>;}@@ -683,6 +705,10 @@ export const runDevRunnerWithInput = Effect.fn("dev-runner.runDevRunnerWithInputreturn yield* new DevRunnerHostNotProxiableError({ mode: input.mode, host: input.host });}+ if (input.built && (input.mode !== "dev" || !input.share)) {+ return yield* new DevRunnerBuiltNeedsShareError({ mode: input.mode });+ }+const worktreePath = yield* resolveGitWorktreePath(yield* HostProcess.WorkingDirectory);const { offset, source } = yield* resolveOffset({@@ -743,6 +769,7 @@ export const runDevRunnerWithInput = Effect.fn("dev-runner.runDevRunnerWithInput}const sharedWebPort = BASE_WEB_PORT + webOffset;+ let built = false;if (input.share) {if (input.mode === "dev:server") {yield* Effect.logInfo("[dev-runner] --share has no effect for dev:server (no web server).");@@ -755,18 +782,32 @@ export const runDevRunnerWithInput = Effect.fn("dev-runner.runDevRunnerWithInput// process (and reboots), so the cleanup has to be registered atomically// with creating it. An interrupt landing in between would otherwise// leave a mapping pointing at a port nothing is listening on.- const shared = yield* Effect.acquireRelease(shareDevServer({ webPort: sharedWebPort }), () =>- unshareDevServer(sharedWebPort).pipe(- Effect.flatMap((result) =>- result.cleared- ? Effect.void- : Effect.logWarning(- `[dev-runner] could not remove the tailnet mapping for port ${String(sharedWebPort)}${- result.explanation ? `: ${result.explanation}` : ""- }. Remove it with \`tailscale serve --https=${String(sharedWebPort)} off\`.`,- ),+ const shared = yield* Effect.acquireRelease(+ shareDevServer({+ webPort: sharedWebPort,+ // The backend binds 127.0.0.1 unless --host changes it. A wildcard+ // still answers there; `--host ::1` binds only the IPv6 loopback.+ ...(input.built+ ? {+ localTarget: {+ port: Number(env.T3CODE_PORT),+ host: ["::1", "[::1]"].includes(input.host?.trim() ?? "") ? "[::1]" : "127.0.0.1",+ },+ }+ : {}),+ }),+ () =>+ unshareDevServer(sharedWebPort).pipe(+ Effect.flatMap((result) =>+ result.cleared+ ? Effect.void+ : Effect.logWarning(+ `[dev-runner] could not remove the tailnet mapping for port ${String(sharedWebPort)}${+ result.explanation ? `: ${result.explanation}` : ""+ }. Remove it with \`tailscale serve --https=${String(sharedWebPort)} off\`.`,+ ),+ ),),- ),).pipe(Effect.tapError((error: DevShareError) =>Effect.logWarning(@@ -792,14 +833,21 @@ export const runDevRunnerWithInput = Effect.fn("dev-runner.runDevRunnerWithInputif (input.devUrl === undefined) {env.VITE_DEV_SERVER_URL = shared.url;}- // A shared origin serves a remote browser, where unbundled dev's- // per-module requests each pay a tailnet round trip — a cold module- // graph takes minutes to first paint. Bundled dev collapses that to a- // few chunk requests.- if (env.T3CODE_BUNDLED_DEV === undefined) {+ if (input.built) {+ built = true;+ env.T3CODE_BUILT_DEV = "1";+ } else if (env.T3CODE_BUNDLED_DEV === undefined) {+ // A shared origin serves a remote browser, where unbundled dev's+ // per-module requests each pay a tailnet round trip — a cold module+ // graph takes minutes to first paint. Bundled dev collapses that to a+ // few chunk requests.env.T3CODE_BUNDLED_DEV = "1";}yield* Effect.logInfo(`[dev-runner] shared on tailnet: ${shared.url}`);+ } else if (input.built) {+ yield* Effect.logWarning(+ "[dev-runner] --built needs the tailnet share; running the Vite dev server instead.",+ );}}}@@ -812,7 +860,7 @@ export const runDevRunnerWithInput = Effect.fn("dev-runner.runDevRunnerWithInputenv,});- const args = [...MODE_ARGS[input.mode], ...input.runArgs];+ const args = [...(built ? BUILT_DEV_ARGS : MODE_ARGS[input.mode]), ...input.runArgs];const spawnCommand = yield* resolveSpawnCommand("vp", args, { env });const processContext = {mode: input.mode,@@ -920,6 +968,12 @@ const devRunnerCli = Command.make("dev-runner", {),Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_DEV_SEED")),),+ built: Flag.Boolean("built").pipe(+ Flag.withDescription(+ "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.",+ ),+ Flag.withDefault(false),+ ),runArgs: Argument.String("run-arg").pipe(Argument.withDescription("Additional Vite+ run args (pass after `--`)."),Argument.variadic(),diff --git a/scripts/lib/dev-share.ts b/scripts/lib/dev-share.tsindex 8bcccd8c982..c37a094b811 100644--- a/scripts/lib/dev-share.ts+++ b/scripts/lib/dev-share.ts@@ -127,8 +127,14 @@ export interface DevShareResult {readonly host: string;}+/**+ * Publishes `webPort` on the tailnet. The tailnet port always matches the web+ * port so the URL is stable; `localTarget` points it at the backend instead+ * when the backend serves a built client (`--built`).+ */export const shareDevServer = Effect.fn("devShare.shareDevServer")(function* (input: {readonly webPort: number;+ readonly localTarget?: { readonly port: number; readonly host: string };}) {const status = yield* readTailscaleStatus.pipe(Effect.mapError((error) => new TailscaleUnavailableError({ cause: error })),@@ -155,9 +161,9 @@ export const shareDevServer = Effect.fn("devShare.shareDevServer")(function* (in// first, so it only binds the IPv6 loopback and a 127.0.0.1 target has// nothing behind it (tailscale answers 502).yield* ensureTailscaleServe({- localPort: input.webPort,+ localPort: input.localTarget?.port ?? input.webPort,servePort: input.webPort,- localHost: "localhost",+ localHost: input.localTarget?.host ?? "localhost",}).pipe(Effect.mapError((error) => {const explanation = explainCommandFailure(error);