diff --git a/.agents/skills/test-t3-app/SKILL.md b/.agents/skills/test-t3-app/SKILL.md index 85d92c2171..6db626a30b 100644 --- a/.agents/skills/test-t3-app/SKILL.md +++ b/.agents/skills/test-t3-app/SKILL.md @@ -56,13 +56,12 @@ bun run dev:pair # implicit ~/.t3 home bun run dev:pair -- --base-dir # explicit --home-dir environment ``` -It reads the running server's own `server-runtime.json`, so it needs no port and -builds the URL against the web origin already in use — including a `--share` -tailnet URL. Pass `--base-dir` only when the dev server was started with -`--home-dir`, and pass exactly the same path: `--base-dir` switches the state -directory from `/dev` to `/userdata`, and a mismatch writes the token -to a database the server isn't reading. Add `--ttl 1h` for a longer window or -`--json` for machine-readable output. +It finds the running server's own `server-runtime.json` under the base directory +— checking both the `dev` and `userdata` state directories and verifying the +recorded process is alive — so it needs no port and builds the URL against the +web origin already in use, including a `--share` tailnet URL. Pass `--base-dir` +only when the dev server was started with `--home-dir`. Add `--ttl 1h` for a +longer window or `--json` for machine-readable output. Use the printed `Pair URL` once. If the command reports no running server, the dev process has exited — restart it and use the URL from its own startup log. diff --git a/apps/server/src/cli/auth.ts b/apps/server/src/cli/auth.ts index 50b278687d..85450df9af 100644 --- a/apps/server/src/cli/auth.ts +++ b/apps/server/src/cli/auth.ts @@ -7,6 +7,7 @@ import * as Console from "effect/Console"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Path from "effect/Path"; import * as References from "effect/References"; import * as Schema from "effect/Schema"; import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli"; @@ -20,7 +21,11 @@ import { formatSessionList, } from "../cliAuthFormat.ts"; import * as ServerConfig from "../config.ts"; -import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts"; +import { + isPersistedServerRuntimeStateLive, + type PersistedServerRuntimeState, + readPersistedServerRuntimeState, +} from "../serverRuntimeState.ts"; import { authLocationFlags, type CliAuthLocationFlags, @@ -30,12 +35,11 @@ import { class NoRunningServerError extends Schema.TaggedErrorClass()( "NoRunningServerError", - { statePath: Schema.String }, + { baseDir: Schema.String }, ) { override get message(): string { return [ - "No running T3 Code server was found for this data directory.", - `Looked for: ${this.statePath}`, + `No running T3 Code server was found under ${this.baseDir}.`, "Start one with `bun run dev`, or point at another directory with --base-dir.", ].join("\n"); } @@ -128,6 +132,40 @@ const pairingCreateCommand = Command.make("create", { ), ); +/** + * The state directory is `/dev` for an implicit dev home and + * `/userdata` otherwise — a split that depends on flags the caller of + * this command should not have to reason about, and which silently mints + * tokens into a database the running server never reads when guessed wrong. + * So check both, and let the live server decide which one is right. + */ +const findLiveServerRuntimeState = Effect.fn("auth.findLiveServerRuntimeState")(function* ( + config: ServerConfig.ServerConfig["Service"], +) { + const path = yield* Path.Path; + const candidates = [ + config.serverRuntimeStatePath, + ...(["dev", "userdata"] as const).map((stateDir) => + path.join(config.baseDir, stateDir, "server-runtime.json"), + ), + ].filter((candidate, index, all) => all.indexOf(candidate) === index); + + for (const statePath of candidates) { + const state = yield* readPersistedServerRuntimeState(statePath); + if (Option.isNone(state)) { + continue; + } + // A file left behind by a killed or crashed server describes a port + // nothing is listening on. Minting against it produces a token the live + // server rejects with `invalid_credential`. + if (yield* isPersistedServerRuntimeStateLive(state.value)) { + return Option.some({ stateDir: path.dirname(statePath), state: state.value }); + } + } + + return Option.none<{ readonly stateDir: string; readonly state: PersistedServerRuntimeState }>(); +}); + /** * `t3 auth pairing url` — print a ready-to-open pairing link for a dev server * that is already running, without having to know its port, its state @@ -150,31 +188,40 @@ const pairingUrlCommand = Command.make("url", { Effect.gen(function* () { const logLevel = yield* GlobalFlag.LogLevel; const config = yield* resolveCliAuthConfig(flags, logLevel); - const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath); + const live = yield* findLiveServerRuntimeState(config); - if (Option.isNone(runtimeState)) { - return yield* new NoRunningServerError({ statePath: config.serverRuntimeStatePath }); + if (Option.isNone(live)) { + return yield* new NoRunningServerError({ baseDir: config.baseDir }); } + // Issue against the same state directory the server is using, whichever + // of the two it turned out to be. + const derivedPaths = yield* ServerConfig.deriveServerPaths(config.baseDir, config.devUrl, { + stateDir: live.value.stateDir, + }); + // Prefer the web origin the user actually opens; a server with no dev URL // serves the app itself, so its own origin is the right target. - const baseUrl = runtimeState.value.devUrl ?? runtimeState.value.origin; + const baseUrl = live.value.state.devUrl ?? live.value.state.origin; - return yield* runWithEnvironmentAuth( - flags, - (environmentAuth) => - Effect.gen(function* () { - const issued = yield* environmentAuth.createPairingLink({ - scopes: AuthStandardClientScopes, - subject: "one-time-token", - ...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}), - label: "cli-issued pairing url", - }); - yield* Console.log( - formatIssuedPairingCredential(issued, { json: flags.json, baseUrl }), - ); - }), - { quietLogs: flags.json }, + return yield* Effect.gen(function* () { + const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth; + const issued = yield* environmentAuth.createPairingLink({ + scopes: AuthStandardClientScopes, + subject: "one-time-token", + ...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}), + label: "cli-issued pairing url", + }); + yield* Console.log(formatIssuedPairingCredential(issued, { json: flags.json, baseUrl })); + }).pipe( + Effect.provide( + Layer.mergeAll(EnvironmentAuth.runtimeLayer).pipe( + Layer.provide(ServerConfig.layer({ ...config, ...derivedPaths })), + Layer.provide( + Layer.succeed(References.MinimumLogLevel, flags.json ? "Error" : config.logLevel), + ), + ), + ), ); }), ), diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index 3b081c95c3..b82b8767f8 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -47,6 +47,13 @@ export interface ServerDerivedPaths { export interface DeriveServerPathsOptions { readonly baseDirIsExplicit?: boolean; + /** + * Use this state directory verbatim instead of deriving `dev` vs `userdata`. + * For tooling that has already located a running server's state directory and + * must target it exactly, rather than re-running the heuristic and risking a + * different answer. + */ + readonly stateDir?: string; } /** @@ -98,10 +105,9 @@ export const deriveServerPaths = Effect.fn(function* ( options: DeriveServerPathsOptions = {}, ): Effect.fn.Return { const { join } = yield* Path.Path; - const stateDir = join( - baseDir, - devUrl !== undefined && !options.baseDirIsExplicit ? "dev" : "userdata", - ); + const stateDir = + options.stateDir ?? + join(baseDir, devUrl !== undefined && !options.baseDirIsExplicit ? "dev" : "userdata"); const dbPath = join(stateDir, "state.sqlite"); const attachmentsDir = join(stateDir, "attachments"); const logsDir = join(stateDir, "logs"); diff --git a/apps/server/src/serverRuntimeState.test.ts b/apps/server/src/serverRuntimeState.test.ts index 749fd3062e..8450ed7832 100644 --- a/apps/server/src/serverRuntimeState.test.ts +++ b/apps/server/src/serverRuntimeState.test.ts @@ -43,6 +43,35 @@ describe("serverRuntimeState", () => { }).pipe(Effect.provide(NodeServices.layer)), ); + // A server killed with SIGKILL never runs its release finalizer, so the file + // survives it. Trusting a leftover file points callers at a dead port. + describe("isPersistedServerRuntimeStateLive", () => { + const stateForPid = (pid: number): ServerRuntimeState.PersistedServerRuntimeState => ({ + version: 1, + pid, + port: 4_971, + origin: "http://127.0.0.1:4971", + startedAt: "2026-06-20T00:00:00.000Z", + }); + + it.effect("recognizes the current process as live", () => + Effect.gen(function* () { + assert.isTrue( + yield* ServerRuntimeState.isPersistedServerRuntimeStateLive(stateForPid(process.pid)), + ); + }), + ); + + it.effect("reports a pid that no longer exists as dead", () => + Effect.gen(function* () { + // Above the default pid_max, so it cannot be a live process. + assert.isFalse( + yield* ServerRuntimeState.isPersistedServerRuntimeStateLive(stateForPid(0x7ffffffe)), + ); + }), + ); + }); + it.effect("treats a missing runtime state file as absent", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/apps/server/src/serverRuntimeState.ts b/apps/server/src/serverRuntimeState.ts index ccd6038cec..b4d75bad7a 100644 --- a/apps/server/src/serverRuntimeState.ts +++ b/apps/server/src/serverRuntimeState.ts @@ -107,6 +107,31 @@ export const clearPersistedServerRuntimeState = (path: string) => ); }); +/** + * Whether the process that wrote a runtime-state file is still alive. + * + * The file is removed by a release finalizer, so a server killed with SIGKILL — + * or one that crashed — leaves it behind. Treating a leftover file as "the + * server is up" points callers at a port nothing is listening on. Signal 0 + * performs the permission and existence checks without delivering a signal. + * + * PIDs are reused eventually, so a false positive is possible in principle; + * that is acceptable for local dev tooling, where the alternative is an + * HTTP probe that has to guess how long to wait for a starting server. + */ +export const isPersistedServerRuntimeStateLive = ( + state: PersistedServerRuntimeState, +): Effect.Effect => + Effect.sync(() => { + try { + process.kill(state.pid, 0); + return true; + } catch (cause) { + // EPERM means the process exists but belongs to another user. + return (cause as NodeJS.ErrnoException).code === "EPERM"; + } + }); + export const readPersistedServerRuntimeState = (path: string) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/docs/reference/scripts.md b/docs/reference/scripts.md index 27845797df..8409c442ba 100644 --- a/docs/reference/scripts.md +++ b/docs/reference/scripts.md @@ -2,7 +2,7 @@ - `vp run dev` — Starts contracts, server, and web in watch mode. - `vp run dev --share` (or `vp run dev:share`) — Same, plus publishes the web port on this machine's tailnet over HTTPS via `tailscale serve`. Prints the shareable URL, and the pairing URL is built against it so it can be opened from a phone or another laptop as-is. The mapping is removed on exit; if the tailnet is unavailable, the dev server still starts locally and logs a warning. -- `vp run dev:pair` — Prints a fresh pairing URL for the dev server already running against this data directory, resolving its port and web origin from `server-runtime.json`. Add `--base-dir ` only when the server was started with `--home-dir`. +- `vp run dev:pair` — Prints a fresh pairing URL for the dev server already running against this data directory, resolving its port and web origin from `server-runtime.json`. Searches both the `dev` and `userdata` state directories and requires the recorded process to still be alive, so a crashed server's leftover state file is not mistaken for a running one. Add `--base-dir ` only when the server was started with `--home-dir`. - `vp run dev:server` — Starts just the WebSocket server. The server process runs on Bun (`@effect/platform-bun` + `BunPtyAdapter`), but task running uses `vp run`. - `vp run dev:web` — Starts just the Vite dev server for the web app. - Dev commands implicitly use `~/.t3/dev`, keeping development state separate from `~/.t3/userdata`. An explicit `--home-dir ` stores state under `/userdata`; the base directory remains available for caches, worktrees, and other shared data. diff --git a/scripts/dev-runner.test.ts b/scripts/dev-runner.test.ts index 3f0767fabe..197a1e4524 100644 --- a/scripts/dev-runner.test.ts +++ b/scripts/dev-runner.test.ts @@ -620,6 +620,34 @@ it.layer(NodeServices.layer)("dev-runner", (it) => { }); }); + // `tailscale serve` config outlives the process, so a dry run that shared + // would replace and then tear down whatever mapping the port already had. + it.effect("spawns nothing when --dry-run is combined with --share", () => { + let spawnCount = 0; + const spawnerLayer = Layer.succeed( + ChildProcessSpawner.ChildProcessSpawner, + ChildProcessSpawner.make(() => { + spawnCount += 1; + return Effect.succeed(mockProcess(0)); + }), + ); + + return Effect.gen(function* () { + yield* runDevRunnerWithInput({ + ...devServerInput, + mode: "dev", + port: undefined, + dryRun: true, + share: true, + }).pipe( + Effect.provide(Layer.mergeAll(emptyConfigLayer, netServiceLayer, spawnerLayer)), + Effect.provideService(HostProcessPlatform, "linux"), + ); + + assert.equal(spawnCount, 0); + }); + }); + it.effect("reports non-zero exits without manufacturing a cause", () => { const spawnerLayer = Layer.succeed( ChildProcessSpawner.ChildProcessSpawner, diff --git a/scripts/dev-runner.ts b/scripts/dev-runner.ts index 2ac3dc883c..705d052489 100644 --- a/scripts/dev-runner.ts +++ b/scripts/dev-runner.ts @@ -581,6 +581,13 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) { `[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} baseDir=${baseDir}`, ); + // Before the share block: --dry-run only resolves and prints. Sharing would + // replace, then tear down, whatever mapping the port already had — a + // surprising side effect from a command documented as inert. + if (input.dryRun) { + return; + } + const sharedWebPort = BASE_WEB_PORT + webOffset; if (input.share) { if (input.mode === "dev:server") { @@ -630,10 +637,6 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) { } } - if (input.dryRun) { - return; - } - const spawnCommand = yield* resolveSpawnCommand( "vp", [...MODE_ARGS[input.mode], ...input.runArgs],