diff --git a/.agents/skills/test-t3-app/SKILL.md b/.agents/skills/test-t3-app/SKILL.md index 90abf22247..259af9fe97 100644 --- a/.agents/skills/test-t3-app/SKILL.md +++ b/.agents/skills/test-t3-app/SKILL.md @@ -13,7 +13,7 @@ Use this skill for the web client. For iOS Simulator, Android Emulator, or physi 2. Choose a base directory that belongs only to the current worktree or test: - Use the repository's ignored `.t3` directory for reusable worktree-local state. - Use `mktemp -d /tmp/t3code-test.XXXXXX` for disposable state and retain the printed absolute path. -3. Start the full web stack with `vp run dev`. Add `--share` when the user needs to open it from another tailnet device. In a linked worktree it defaults to that worktree's gitignored `.t3`; pass `--home-dir ` only when the test needs a different isolated directory. +3. Start the full web stack with `bun run dev`. Use `bun run dev:share` when the user needs to open it from another tailnet device. In a linked worktree it defaults to that worktree's gitignored `.t3`; pass `--home-dir ` only when the test needs a different isolated directory. 4. Keep the terminal session alive and read the selected server port, web port, base directory, and pairing URL from its output. Treat a base directory as disposable only when it was created or deliberately selected for the current test. Never delete or directly seed the shared `~/.t3` directory. Prefer starting with a new temporary base directory over clearing state of uncertain ownership. diff --git a/apps/server/src/cli/auth.test.ts b/apps/server/src/cli/auth.test.ts index 7466a6d527..742ee96ed3 100644 --- a/apps/server/src/cli/auth.test.ts +++ b/apps/server/src/cli/auth.test.ts @@ -71,6 +71,29 @@ describe("findLiveServerRuntimeState", () => { }).pipe(Effect.provide(NodeServices.layer)), ); + it.effect("prefers a legacy dev state without a dev URL", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const config = yield* makeBaseDir(); + yield* writeRuntimeState({ + baseDir: config.baseDir, + stateDir: "userdata", + pid: process.pid, + port: 16_601, + }); + yield* writeRuntimeState({ + baseDir: config.baseDir, + stateDir: "dev", + pid: process.pid, + port: 16_602, + }); + + const live = Option.getOrThrow(yield* findLiveServerRuntimeState(config)); + assert.equal(live.stateDir, path.join(config.baseDir, "dev")); + assert.equal(live.state.port, 16_602); + }).pipe(Effect.provide(NodeServices.layer)), + ); + it.effect("falls back to a live non-dev server when no dev server is running", () => Effect.gen(function* () { const path = yield* Path.Path; diff --git a/apps/server/src/cli/auth.ts b/apps/server/src/cli/auth.ts index d688c9dd61..10b4ce7a02 100644 --- a/apps/server/src/cli/auth.ts +++ b/apps/server/src/cli/auth.ts @@ -171,11 +171,14 @@ export const findLiveServerRuntimeState = Effect.fn("auth.findLiveServerRuntimeS // `devUrl` is only recorded by a server fronted by a web dev server, so it // distinguishes the dev instance from a production-style one when both are - // running under the same base directory. This command is about dev, so a dev - // server wins regardless of which state directory the flags happened to - // resolve to. + // running under the same base directory. Older runtime-state files predate + // that field, but an implicit dev server still lives in `/dev`, which is + // enough to prefer it over a production-style `/userdata` server. + const devStateDir = path.join(config.baseDir, "dev"); return Option.fromNullishOr( - live.find((candidate) => candidate.state.devUrl !== undefined) ?? live[0], + live.find((candidate) => candidate.state.devUrl !== undefined) ?? + live.find((candidate) => candidate.stateDir === devStateDir) ?? + live[0], ); }); diff --git a/docs/reference/scripts.md b/docs/reference/scripts.md index a859d775da..2dd949b5b2 100644 --- a/docs/reference/scripts.md +++ b/docs/reference/scripts.md @@ -1,9 +1,9 @@ # Scripts -- `vp run dev` — Starts contracts, server, and web in watch mode. -- `vp run dev --share` — Also publishes the web port over HTTPS on this machine's tailnet. The startup pairing URL is built against the shared origin, and the mapping is removed on exit. -- `vp run dev:pair` — Prints a fresh pairing URL for the running dev server, using its recorded state directory, port, and web origin. Add `--base-dir ` only when the server was started with `--home-dir`. -- `vp run dev:seed` — Copies recent projects and threads from the shared home into the isolated dev database. Stop the server before running it, then restart. Tune the copy with `--threads` and `--activities`; it refuses to write to the shared home. +- `bun run dev` — Starts contracts, server, and web in watch mode. +- `bun run dev:share` — Also publishes the web port over HTTPS on this machine's tailnet. The startup pairing URL is built against the shared origin, and the mapping is removed on exit. +- `bun run dev:pair` — Prints a fresh pairing URL for the running dev server, using its recorded state directory, port, and web origin. Add `--base-dir ` only when the server was started with `--home-dir`. +- `bun run dev:seed` — Copies recent projects and threads from the shared home into the isolated dev database. Stop the server before running it, then restart. Tune the copy with `--threads` and `--activities`; it refuses to write to the shared home. - `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 run from a linked **git worktree** default to that worktree's gitignored `.t3`, even when `T3CODE_HOME` is set, storing state in `/.t3/userdata`. Pass `--home-dir ` to choose another isolated directory explicitly. Submodules are not worktrees and keep the normal precedence. diff --git a/scripts/dev-runner.ts b/scripts/dev-runner.ts index 1d3b3bf281..1f97a752ac 100644 --- a/scripts/dev-runner.ts +++ b/scripts/dev-runner.ts @@ -730,12 +730,6 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) { // with creating it. An interrupt landing in between would otherwise // leave a mapping pointing at a port nothing is listening on. // - // Deliberately no ownership tracking beyond that: if a second runner - // takes this port during a fast restart, the first's exit can briefly - // tear down the new mapping — visible (the URL stops working) and fixed - // by re-running --share. A lease protocol closing that window existed - // and was removed as more machinery than a dev convenience warrants. - // // A tailnet that isn't up shouldn't stop the dev server from starting — // warn, and carry on serving locally. const shared = yield* Effect.gen(function* () { diff --git a/scripts/dev-seed-cli.test.ts b/scripts/dev-seed-cli.test.ts new file mode 100644 index 0000000000..dff7709072 --- /dev/null +++ b/scripts/dev-seed-cli.test.ts @@ -0,0 +1,46 @@ +// @effect-diagnostics nodeBuiltinImport:off - exercises the executable path guard in a child process. +import { assert, it } from "@effect/vitest"; +import * as NodeChildProcess from "node:child_process"; +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; + +it("refuses to seed a target inside T3CODE_HOME through a symlink", () => { + const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-dev-seed-cli-")); + try { + const sharedHome = NodePath.join(root, "shared"); + const sharedStateDir = NodePath.join(sharedHome, "userdata"); + const targetBaseDir = NodePath.join(root, "target"); + NodeFS.mkdirSync(sharedStateDir, { recursive: true }); + NodeFS.mkdirSync(targetBaseDir, { recursive: true }); + NodeFS.writeFileSync(NodePath.join(sharedStateDir, "state.sqlite"), "must stay untouched"); + NodeFS.symlinkSync(sharedStateDir, NodePath.join(targetBaseDir, "userdata"), "dir"); + + const result = NodeChildProcess.spawnSync( + process.execPath, + [ + NodePath.join(import.meta.dirname, "dev-seed.ts"), + "--from", + NodePath.join(root, "source"), + "--to", + targetBaseDir, + ], + { + encoding: "utf8", + env: { ...process.env, NO_COLOR: "1", T3CODE_HOME: sharedHome }, + }, + ); + + assert.notEqual(result.status, 0); + assert.include( + `${result.stdout}${result.stderr}`, + "that database lives in the shared T3 Code home", + ); + assert.equal( + NodeFS.readFileSync(NodePath.join(sharedStateDir, "state.sqlite"), "utf8"), + "must stay untouched", + ); + } finally { + NodeFS.rmSync(root, { recursive: true, force: true }); + } +}); diff --git a/scripts/dev-seed.ts b/scripts/dev-seed.ts index cbc2da1b57..495c4e4e4a 100644 --- a/scripts/dev-seed.ts +++ b/scripts/dev-seed.ts @@ -23,6 +23,21 @@ import { findRunningServerPid, findRunningServerPidSync } from "./lib/server-run const DEFAULT_THREAD_LIMIT = 25; const DEFAULT_ACTIVITY_LIMIT = 200; +const resolveSharedHome = (path: Path.Path): string => { + const configured = process.env.T3CODE_HOME?.trim(); + if (!configured) { + return path.join(NodeOS.homedir(), ".t3"); + } + if (configured === "~") { + return NodeOS.homedir(); + } + return path.resolve( + configured.startsWith("~/") || configured.startsWith("~\\") + ? path.join(NodeOS.homedir(), configured.slice(2)) + : configured, + ); +}; + class DevSeedTargetError extends Schema.TaggedErrorClass()( "DevSeedTargetError", { @@ -156,10 +171,6 @@ const copyAttachments = Effect.fn("devSeed.copyAttachments")(function* (input: { const entries = yield* fileSystem .readDirectory(input.sourceDir) .pipe(Effect.orElseSucceed(() => [] as Array)); - if (entries.length === 0) { - return 0; - } - const wanted = new Set(input.attachmentIds); const matches = entries.filter((entry) => wanted.has(path.parse(entry).name)); if (matches.length === 0) { @@ -188,7 +199,7 @@ const copyAttachments = Effect.fn("devSeed.copyAttachments")(function* (input: { const devSeedCli = Command.make("dev-seed", { from: Flag.string("from").pipe( Flag.withDescription( - "Base directory to copy from (default: the shared T3 Code home, ~/.t3). Read-only.", + "Base directory to copy from (default: T3CODE_HOME, or ~/.t3). Read-only.", ), Flag.optional, Flag.map(Option.getOrUndefined), @@ -229,7 +240,7 @@ const devSeedCli = Command.make("dev-seed", { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const sharedHome = path.join(NodeOS.homedir(), ".t3"); + const sharedHome = resolveSharedHome(path); const sourceBaseDir = input.from ? path.resolve(input.from) : sharedHome; const defaultTarget = yield* resolveWorktreeT3Home(process.cwd()); diff --git a/scripts/lib/dev-seed.ts b/scripts/lib/dev-seed.ts index 2260816fed..b41667387f 100644 --- a/scripts/lib/dev-seed.ts +++ b/scripts/lib/dev-seed.ts @@ -232,7 +232,7 @@ function copyRows(input: { // at the limit instead of ranking every row. const statement = input.source.prepare( `SELECT ${selectList} FROM ${input.table} WHERE "${input.keyColumn}" = ? - ORDER BY ${input.perKeyLimit.orderBy} DESC LIMIT ?`, + ORDER BY ${input.perKeyLimit.orderBy} LIMIT ?`, ); for (const key of input.keys) { insertFrom(statement.iterate(key, input.perKeyLimit.limit)); @@ -590,8 +590,8 @@ export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary { // back to the timestamp — same drift tolerance as the rest of the copy. perKeyLimit: { orderBy: hasColumn(source, "projection_thread_activities", "sequence") - ? `"sequence" DESC, "created_at" DESC, "activity_id"` - : `"created_at" DESC, "activity_id"`, + ? `"sequence" DESC, "created_at" DESC, "activity_id" DESC` + : `"created_at" DESC, "activity_id" DESC`, limit: options.activityLimit, }, }), diff --git a/scripts/lib/dev-share.test.ts b/scripts/lib/dev-share.test.ts index e3e806e60a..e940f02b59 100644 --- a/scripts/lib/dev-share.test.ts +++ b/scripts/lib/dev-share.test.ts @@ -192,6 +192,40 @@ describe("shareDevServer", () => { }); it.layer(NodeServices.layer)("dev share cleanup ownership", (it) => { + it.effect("claims ownership via an atomic rename", () => + Effect.gen(function* () { + const leasePath = "/leases/5788.owner"; + const tempDirectory = "/leases/5788.owner.temp"; + const writes: Array = []; + const renames: Array = []; + + yield* claimDevShareLease({ leasePath, ownerId: "new-runner", webPort: 5788 }).pipe( + Effect.provideService( + FileSystem.FileSystem, + FileSystem.makeNoop({ + makeDirectory: () => Effect.void, + makeTempDirectoryScoped: (options) => { + assert.equal(options?.directory, "/leases"); + assert.equal(options?.prefix, "5788.owner."); + return Effect.succeed(tempDirectory); + }, + writeFileString: (path, contents) => { + writes.push([path, contents]); + return Effect.void; + }, + rename: (from, to) => { + renames.push([from, to]); + return Effect.void; + }, + }), + ), + ); + + assert.deepEqual(writes, [[`${tempDirectory}/owner.tmp`, "new-runner"]]); + assert.deepEqual(renames, [[`${tempDirectory}/owner.tmp`, leasePath]]); + }), + ); + it.effect("keeps the prior owner when clearing its mapping fails", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; diff --git a/scripts/lib/dev-share.ts b/scripts/lib/dev-share.ts index 67455f5eec..6e5515af27 100644 --- a/scripts/lib/dev-share.ts +++ b/scripts/lib/dev-share.ts @@ -199,8 +199,19 @@ export const claimDevShareLease = Effect.fn("devShare.claimDevShareLease")(funct ) { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; - yield* fileSystem.makeDirectory(path.dirname(lease.leasePath), { recursive: true }).pipe( - Effect.andThen(fileSystem.writeFileString(lease.leasePath, lease.ownerId)), + yield* Effect.scoped( + Effect.gen(function* () { + const leaseDirectory = path.dirname(lease.leasePath); + yield* fileSystem.makeDirectory(leaseDirectory, { recursive: true }); + const tempDirectory = yield* fileSystem.makeTempDirectoryScoped({ + directory: leaseDirectory, + prefix: `${path.basename(lease.leasePath)}.`, + }); + const tempPath = path.join(tempDirectory, "owner.tmp"); + yield* fileSystem.writeFileString(tempPath, lease.ownerId); + yield* fileSystem.rename(tempPath, lease.leasePath); + }), + ).pipe( Effect.mapError((cause) => new DevShareLeaseClaimError({ leasePath: lease.leasePath, cause })), ); return lease;