feat(dev): dev server pairing and seed utilities #4557
Closedt3dotgg(GitHub profile, opens in a new tab)wants to merge 30 commits into
main fromagent/dev-utilitiesopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- scripts/dev-seed.ts lines 107 to 113OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +93,21 @@93+ const fileSystem = yield* FileSystem.FileSystem;94+ const path = yield* Path.Path;95+96+ const sharedHome = path.join(NodeOS.homedir(), ".t3");97+ const sourceBaseDir = input.from ? path.resolve(input.from) : sharedHome;98+99+ const defaultTarget = yield* resolveWorktreeT3Home(process.cwd());100+ const targetBaseDir = input.to ? path.resolve(input.to) : defaultTarget;101+ if (targetBaseDir === undefined) {102+ return yield* new DevSeedTargetError({ reason: "not-a-worktree", detail: process.cwd() });103+ }104+105+ // The whole point is to keep dev data off the real home; overwriting it106+ // here would be the exact accident this command exists to avoid.107+ const [canonicalTarget, canonicalShared] = yield* Effect.all([108+ fileSystem.realPath(targetBaseDir).pipe(Effect.orElseSucceed(() => targetBaseDir)),109+ fileSystem.realPath(sharedHome).pipe(Effect.orElseSucceed(() => sharedHome)),110+ ]);111+ if (canonicalTarget === canonicalShared) {112+ return yield* new DevSeedTargetError({ reason: "shared-home", detail: targetBaseDir });113+ }
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- scripts/lib/dev-seed.ts lines 251 to 257OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +237,21 @@237+ */238+function settleUnfinishedTurns(239+ target: NodeSqlite.DatabaseSync,240+ threadIds: ReadonlyArray<string>,241+): void {242+ if (threadIds.length === 0 || !hasColumn(target, "projection_turns", "state")) {243+ return;244+ }245+ // completed_at is what marks a turn settled alongside its state; an246+ // unfinished turn has none, and leaving it null keeps the thread unsettled247+ // regardless of the state written here.248+ const setCompletedAt = hasColumn(target, "projection_turns", "completed_at")249+ ? `, completed_at = COALESCE(completed_at, requested_at)`250+ : "";251+ target252+ .prepare(253+ `UPDATE projection_turns SET state = 'interrupted'${setCompletedAt}254+ WHERE state IN (${placeholders(UNSETTLED_TURN_STATES.length)})255+ AND thread_id IN (${placeholders(threadIds.length)})`,256+ )257+ .run(...UNSETTLED_TURN_STATES, ...threadIds);
- scripts/lib/dev-seed.ts lines 277 to 279Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +238,21 @@238+ * Settles turns copied mid-flight, matching what the server does to a turn239+ * whose session leaves "running": `settledTurnStateForSessionStatus` in240+ * apps/server/src/orchestration/Layers/ProjectionPipeline.ts maps the "stopped"241+ * status the sessions are copied with to "interrupted".242+ *243+ * An UPDATE rather than a copy override, because only the rows that were244+ * actually unsettled should change; the rest keep their real recorded state.245+ */246+function settleUnfinishedTurns(247+ target: NodeSqlite.DatabaseSync,248+ threadIds: ReadonlyArray<string>,249+): void {250+ if (threadIds.length === 0 || !hasColumn(target, "projection_turns", "state")) {251+ return;252+ }253+ // completed_at is what marks a turn settled alongside its state; an254+ // unfinished turn has none, and leaving it null keeps the thread unsettled255+ // regardless of the state written here.256+ const setCompletedAt = hasColumn(target, "projection_turns", "completed_at")257+ ? `, completed_at = COALESCE(completed_at, requested_at)`258+ : "";scripts/lib/dev-seed.ts line 246OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +226,21 @@226+ */227+const UNSETTLED_TURN_STATES = ["running", "pending"] as const;228+229+/**230+ * Inlined rather than bound, so the statement below costs exactly one variable231+ * per thread. `--threads` is capped at SQLite's variable ceiling, so two extra232+ * bindings put the maximum documented value two over the limit. Safe to233+ * interpolate: these are internal literals, never input.234+ */235+const UNSETTLED_TURN_STATES_SQL = UNSETTLED_TURN_STATES.map((state) => `'${state}'`).join(", ");236+237+/**238+ * Settles turns copied mid-flight, matching what the server does to a turn239+ * whose session leaves "running": `settledTurnStateForSessionStatus` in240+ * apps/server/src/orchestration/Layers/ProjectionPipeline.ts maps the "stopped"241+ * status the sessions are copied with to "interrupted".242+ *243+ * An UPDATE rather than a copy override, because only the rows that were244+ * actually unsettled should change; the rest keep their real recorded state.245+ */246+function settleUnfinishedTurns(
- scripts/dev-seed.ts line 196OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +176,21 @@176+ }177+178+ // The whole point is to keep dev data off the real home; overwriting it179+ // here would be the exact accident this command exists to avoid.180+ const [canonicalTarget, canonicalSource, canonicalShared] = yield* Effect.all([181+ fileSystem.realPath(targetBaseDir).pipe(Effect.orElseSucceed(() => targetBaseDir)),182+ fileSystem.realPath(sourceBaseDir).pipe(Effect.orElseSucceed(() => sourceBaseDir)),183+ fileSystem.realPath(sharedHome).pipe(Effect.orElseSucceed(() => sharedHome)),184+ ]);185+ if (canonicalTarget === canonicalShared) {186+ return yield* new DevSeedTargetError({ reason: "shared-home", detail: targetBaseDir });187+ }188+ // Seeding a directory from itself is not the data loss it looks like —189+ // the source reads a pre-transaction snapshot, so the copy puts the rows190+ // back. What does not come back is the event log and the cursors, and191+ // anything outside the caps. Nobody means to ask for that.192+ if (canonicalTarget === canonicalSource) {193+ return yield* new DevSeedTargetError({ reason: "same-source", detail: targetBaseDir });194+ }195+196+ const targetDbPath = stateDbPath(path, targetBaseDir);
- scripts/lib/dev-seed.ts lines 370 to 374OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +354,21 @@354+355+ try {356+ // Threads the user actually touched most recently. Mirrors the sidebar's own357+ // ordering (packages/client-runtime/src/state/threadSort.ts). Both recency358+ // columns arrived in later migrations, so an older source database is read359+ // with whichever of them it actually has — the rest of the copy tolerates360+ // schema drift, and this query must too.361+ const recencyColumns = ["latest_user_message_at", "updated_at", "created_at"].filter((column) =>362+ hasColumn(source, "projection_threads", column),363+ );364+ const activeFilters = ["deleted_at", "archived_at"]365+ .filter((column) => hasColumn(source, "projection_threads", column))366+ .map((column) => `${column} IS NULL`);367+ const threadIds = (368+ source369+ .prepare(370+ `SELECT thread_id FROM projection_threads371+ ${activeFilters.length > 0 ? `WHERE ${activeFilters.join(" AND ")}` : ""}372+ ORDER BY COALESCE(${recencyColumns.join(", ")}) DESC373+ LIMIT ?`,374+ )scripts/lib/dev-seed.ts lines 354 to 359Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +296,21 @@296+ target297+ .prepare(298+ `DELETE FROM projection_turns299+ WHERE state = 'pending'300+ AND turn_id IS NULL301+ ${excludeCheckpoints}302+ AND thread_id IN (${placeholders(threadIds.length)})`,303+ )304+ .run(...threadIds);305+}306+307+export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary {308+ // Checked before anything is opened, and certainly before the target is309+ // emptied: overrunning the ceiling mid-copy destroys the target's data and310+ // rolls back without replacing it.311+ if (options.threadLimit > MAX_SEED_THREAD_LIMIT) {312+ throw new DevSeedError(313+ `cannot copy more than ${String(MAX_SEED_THREAD_LIMIT)} threads in one pass`,314+ "Each thread costs one SQLite bound variable, and that is the engine's limit.",315+ );316+ }
- @@ -0,0 +75,21 @@75+ * The state directory holding a base directory's database.76+ *77+ * `deriveServerPaths` picks `dev` for an implicit dev home and `userdata`78+ * otherwise — a split that depends on how the server was started, which the79+ * person seeding has no reason to know. Hard-coding `userdata` made a80+ * main-checkout `bun run dev` (whose state lives in `<base>/dev`) unreachable:81+ * the seed reported "no database, start the dev server so migrations run" about82+ * a server that was already running.83+ *84+ * Whichever one exists wins; `userdata` breaks the tie, since that is what an85+ * explicit `--home-dir` produces.86+ */87+const resolveStateDir = Effect.fn("devSeed.resolveStateDir")(function* (baseDir: string) {88+ const fileSystem = yield* FileSystem.FileSystem;89+ const path = yield* Path.Path;90+ for (const stateDir of ["userdata", "dev"] as const) {91+ if (yield* fileSystem.exists(path.join(baseDir, stateDir, "state.sqlite"))) {92+ return stateDir;93+ }94+ }95+ return "userdata";
- scripts/dev-seed.ts lines 96 to 107OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +87,21 @@87+ * the last server to run actually opened. The chosen path is printed, so a88+ * wrong guess is visible rather than silent.89+ */90+const resolveStateDir = Effect.fn("devSeed.resolveStateDir")(function* (baseDir: string) {91+ const fileSystem = yield* FileSystem.FileSystem;92+ const path = yield* Path.Path;93+94+ const candidates: Array<{ readonly stateDir: string; readonly modifiedAtMs: number }> = [];95+ for (const stateDir of ["userdata", "dev"] as const) {96+ const info = yield* fileSystem97+ .stat(path.join(baseDir, stateDir, "state.sqlite"))98+ .pipe(Effect.option);99+ if (Option.isSome(info)) {100+ candidates.push({101+ stateDir,102+ modifiedAtMs: Option.match(info.value.mtime, {103+ onSome: (mtime) => mtime.getTime(),104+ onNone: () => 0,105+ }),106+ });107+ }
- .agents/skills/test-t3-app/SKILL.md lines 57 to 64Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -44,17 +48,11 @@44484549 ## Recover a consumed or expired pairing token465047-Create another token against the same database and web URL as the running dev server:51+Ask the running server for a fresh pairing URL:48524953 ```bash50-T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \51- --base-dir <base-dir> \52- --dev-url <web-url> \53- --base-url <web-url> \54- --ttl 15m \55- --label agent-ui-test54+bun run dev:pair55+bun run dev:pair -- --base-dir <base-dir>5656 ```575758-Use the `Pair URL` from this command once. Derive `<server-port>` and `<web-url>` from the current dev-runner output, including any automatically selected port offset. Setting `T3CODE_PORT` keeps the administrative CLI from probing for an unrelated free port.59-60-Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.58+It finds the live server state under either the `dev` or `userdata` state directory and reuses the recorded web origin, including a tailnet URL. Pass `--base-dir` only when the server was started with `--home-dir`. Use the printed URL once.docs/reference/scripts.md lines 4 to 6OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -1,3 +1,6 @@11 # Scripts2233 `vp run dev` — Starts contracts, server, and web in watch mode.4+`vp run dev --share` (or `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.5+`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 <path>` only when the server was started with `--home-dir`.6+`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.docs/reference/scripts.md lines 54 to 55OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -37,3 +41,15 @@3741 Azure authentication env vars are also required (for example service principal with secret):3842 `AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.394344+## Browser development45+46+`dev` and `dev:web` leave `VITE_HTTP_URL` and `VITE_WS_URL` unset so the browser resolves the backend from `window.location.origin`. Vite proxies `/api`, `/ws`, `/oauth`, and `/.well-known` to the server, allowing the same bundle to work from localhost or a tailnet hostname.47+48+Worktrees derive a preferred port offset from their path. The runner shifts both ports together when either is occupied, so treat the `[dev-runner]` output as authoritative.49+50+An isolated dev database starts empty. `vp run dev:seed` copies projection data only, clears the target event log, and resets every projector cursor to zero so later events are not skipped or replayed over unrelated projections. Because no live agent accompanies the copy, it also settles anything that would otherwise wait on one: sessions are stopped, running turns are interrupted, streaming messages are finished, pending interaction counts are cleared, and orphaned provider bindings are removed. Files backing copied image attachments are copied alongside the rows. The copy tolerates source/target migration drift and remains local because it includes real message bodies and host paths.51+52+`dev:seed` refuses to run while a server is using the target directory: it replaces the projections and event log that server is holding open, and it has no way to tell the running process its read model was swapped underneath it. Stop the server, seed, then start it again.53+54+Both source and target follow whichever state directory actually holds a database — `userdata` when present, otherwise `dev` — so a main-checkout `bun run dev`, whose state lives in `~/.t3/dev`, is seedable without naming the directory.55+
- scripts/dev-seed.ts line 257OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +237,21 @@237+ // anything outside the caps. Nobody means to ask for that.238+ if (canonicalTarget === canonicalSource) {239+ return yield* new DevSeedTargetError({ reason: "same-source", detail: targetBaseDir });240+ }241+242+ const [sourceStateDir, targetStateDir] = yield* Effect.all([243+ resolveStateDir(sourceBaseDir),244+ resolveStateDir(targetBaseDir),245+ ]);246+ const sourceDbPath = stateDbPath(path, sourceBaseDir, sourceStateDir);247+ const targetDbPath = stateDbPath(path, targetBaseDir, targetStateDir);248+ if (!(yield* fileSystem.exists(targetDbPath))) {249+ return yield* new DevSeedTargetError({ reason: "missing-target", detail: targetDbPath });250+ }251+252+ // SQLite locking is not enough on its own: the seed's transaction can take253+ // the write lock between a running server's own writes and commit cleanly.254+ // What it cannot do is tell that server the projections it is holding in255+ // memory, and the event log it is appending to, were both replaced under256+ // it. Its next write then lands on top of a read model it never built.257+ const runningPid = yield* findRunningServerPid(targetBaseDir);
- @@ -0,0 +548,21 @@548+ );549+ const activities = record(550+ copyRows({551+ source,552+ target,553+ table: "projection_thread_activities",554+ keyColumn: "thread_id",555+ keys: threadIds,556+ // Ordered the way the app reads these back — `sequence` first, then557+ // `created_at` (ProjectionSnapshotQuery). Capping on `created_at`558+ // alone cuts arbitrarily among rows sharing a timestamp, which is the559+ // common case for a burst of tool activity: the "newest N" kept can be560+ // the oldest N in the order the timeline actually displays.561+ //562+ // `sequence` arrived in migration 008, so a source without it falls563+ // back to the timestamp — same drift tolerance as the rest of the copy.564+ perKeyLimit: {565+ orderBy: hasColumn(source, "projection_thread_activities", "sequence")566+ ? `"created_at" DESC, "sequence"`567+ : `"created_at"`,568+ limit: options.activityLimit,@@ -0,0 +252,21 @@252+ const [sourceStateDir, targetStateDir] = yield* Effect.all([253+ resolveStateDir(sourceBaseDir),254+ resolveStateDir(targetBaseDir),255+ ]);256+ const sourceDbPath = stateDbPath(path, sourceBaseDir, sourceStateDir);257+ const targetDbPath = stateDbPath(path, targetBaseDir, targetStateDir);258+ if (!(yield* fileSystem.exists(targetDbPath))) {259+ return yield* new DevSeedTargetError({ reason: "missing-target", detail: targetDbPath });260+ }261+262+ // SQLite locking is not enough on its own: the seed's transaction can take263+ // the write lock between a running server's own writes and commit cleanly.264+ // What it cannot do is tell that server the projections it is holding in265+ // memory, and the event log it is appending to, were both replaced under266+ // it. Its next write then lands on top of a read model it never built.267+ const runningPid = yield* findRunningServerPid(targetBaseDir);268+ if (Option.isSome(runningPid)) {269+ return yield* new DevSeedTargetError({270+ reason: "server-running",271+ detail: String(runningPid.value),272+ });
- scripts/dev-seed.ts line 236OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +216,21 @@216+}).pipe(217+ Command.withDescription(218+ "Copy recent projects and threads from a T3 Code data directory into an isolated dev one.",219+ ),220+ Command.withHandler((input) =>221+ Effect.gen(function* () {222+ const fileSystem = yield* FileSystem.FileSystem;223+ const path = yield* Path.Path;224+225+ const sharedHome = path.join(NodeOS.homedir(), ".t3");226+ const sourceBaseDir = input.from ? path.resolve(input.from) : sharedHome;227+228+ const defaultTarget = yield* resolveWorktreeT3Home(process.cwd());229+ const targetBaseDir = input.to ? path.resolve(input.to) : defaultTarget;230+ if (targetBaseDir === undefined) {231+ return yield* new DevSeedTargetError({ reason: "not-a-worktree", detail: process.cwd() });232+ }233+234+ // The whole point is to keep dev data off the real home; overwriting it235+ // here would be the exact accident this command exists to avoid.236+ const [canonicalTarget, canonicalSource, canonicalShared] = yield* Effect.all([
t3dotgg(GitHub profile, opens in a new tab) changed the title
- @@ -0,0 +238,21 @@238+ const sourceDbPath = stateDbPath(path, sourceBaseDir, sourceStateDir);239+ const targetDbPath = stateDbPath(path, targetBaseDir, targetStateDir);240+ if (!(yield* fileSystem.exists(targetDbPath))) {241+ return yield* new DevSeedTargetError({ reason: "missing-target", detail: targetDbPath });242+ }243+244+ // The whole point is to keep dev data off the real home; overwriting it245+ // here would be the exact accident this command exists to avoid.246+ //247+ // Guarded on the canonical *database* paths, not the base directories: a248+ // base can canonicalize to itself while its `userdata` or `dev`249+ // subdirectory is a symlink into the shared home, and comparing bases250+ // then waves through a seed whose actual write target is the real251+ // database. The db path is what gets opened, so it is what gets checked.252+ const [canonicalTargetDb, canonicalSourceDb, canonicalShared] = yield* Effect.all([253+ fileSystem.realPath(targetDbPath).pipe(Effect.orElseSucceed(() => targetDbPath)),254+ fileSystem.realPath(sourceDbPath).pipe(Effect.orElseSucceed(() => sourceDbPath)),255+ fileSystem.realPath(sharedHome).pipe(Effect.orElseSucceed(() => sharedHome)),256+ ]);257+ if (canonicalTargetDb.startsWith(`${canonicalShared}${path.sep}`)) {258+ return yield* new DevSeedTargetError({ reason: "shared-home", detail: canonicalTargetDb });
- @@ -0,0 +237,21 @@237+ ]);238+ const sourceDbPath = stateDbPath(path, sourceBaseDir, sourceStateDir);239+ const targetDbPath = stateDbPath(path, targetBaseDir, targetStateDir);240+241+ // The whole point is to keep dev data off the real home; overwriting it242+ // here would be the exact accident this command exists to avoid.243+ //244+ // Guarded on the canonical *database* paths, not the base directories: a245+ // base can canonicalize to itself while its `userdata` or `dev`246+ // subdirectory is a symlink into the shared home, and comparing bases247+ // then waves through a seed whose actual write target is the real248+ // database. The directory is canonicalized and the filename re-joined249+ // because the database may not exist yet — realPath fails on a missing250+ // final component, and falling back to the literal path would lose the251+ // symlink resolution in exactly the case where the next error's advice252+ // ("start the dev server") would create the database in the shared home.253+ const canonicalDbPath = (databasePath: string) =>254+ fileSystem.realPath(path.dirname(databasePath)).pipe(255+ Effect.map((directory) => path.join(directory, path.basename(databasePath))),256+ Effect.orElseSucceed(() => databasePath),257+ );@@ -0,0 +258,21 @@258+ const [canonicalTargetDb, canonicalSourceDb, canonicalShared] = yield* Effect.all([259+ canonicalDbPath(targetDbPath),260+ canonicalDbPath(sourceDbPath),261+ fileSystem.realPath(sharedHome).pipe(Effect.orElseSucceed(() => sharedHome)),262+ ]);263+ if (canonicalTargetDb.startsWith(`${canonicalShared}${path.sep}`)) {264+ return yield* new DevSeedTargetError({ reason: "shared-home", detail: canonicalTargetDb });265+ }266+ // Seeding a database from itself is not the data loss it looks like —267+ // the source reads a pre-transaction snapshot, so the copy puts the rows268+ // back. What does not come back is the event log and the cursors, and269+ // anything outside the caps. Nobody means to ask for that.270+ if (canonicalTargetDb === canonicalSourceDb) {271+ return yield* new DevSeedTargetError({ reason: "same-source", detail: canonicalTargetDb });272+ }273+274+ // After the refusals: this error's advice is to start a dev server, which275+ // creates the database — the right next step everywhere the guards above276+ // did not already rule the target out.277+ if (!(yield* fileSystem.exists(targetDbPath))) {278+ return yield* new DevSeedTargetError({ reason: "missing-target", detail: targetDbPath });
- @@ -0,0 +422,21 @@422+ // SQLite's COALESCE requires at least two arguments, so a source down to a423+ // single recency column — the pre-migration-017 case this filter exists to424+ // support — would throw rather than degrade. `created_at` is NOT NULL from425+ // migration 005 on, so there is always at least one.426+ const recencyOrder =427+ recencyColumns.length > 1428+ ? `COALESCE(${recencyColumns.join(", ")})`429+ : (recencyColumns[0] ?? "rowid");430+ const activeFilters = ["deleted_at", "archived_at"]431+ .filter((column) => hasColumn(source, "projection_threads", column))432+ .map((column) => `${column} IS NULL`);433+ const threadIds = (434+ source435+ .prepare(436+ `SELECT thread_id FROM projection_threads437+ ${activeFilters.length > 0 ? `WHERE ${activeFilters.join(" AND ")}` : ""}438+ ORDER BY ${recencyOrder} DESC439+ LIMIT ?`,440+ )441+ .all(options.threadLimit) as Array<{ thread_id: string }>442+ ).map((row) => row.thread_id);@@ -0,0 +308,21 @@308+ try: () =>309+ seedDevDatabase({310+ sourceDbPath,311+ targetDbPath,312+ threadLimit: input.threads,313+ activityLimit: input.activities,314+ seededAt,315+ // The check above happens before the copy, which can take seconds.316+ // Re-checked just before the commit so a server that started in317+ // between aborts the seed instead of having its database swapped.318+ findRunningServerPid: () => findRunningServerPidSync(targetBaseDir, targetStateDir),319+ }),320+ catch: (cause) => cause as DevSeedError,321+ });322+323+ // Attachments sit beside the database, so they follow the same state dir.324+ const copiedAttachments = yield* copyAttachments({325+ sourceDir: path.join(sourceBaseDir, sourceStateDir, "attachments"),326+ targetDir: path.join(targetBaseDir, targetStateDir, "attachments"),327+ attachmentIds: summary.attachmentIds,328+ });
- @@ -0,0 +550,21 @@550+ copyRows({551+ source,552+ target,553+ table: "projection_thread_activities",554+ keyColumn: "thread_id",555+ keys: threadIds,556+ // Ordered the way the app reads these back — `sequence` first, then557+ // `created_at` (ProjectionSnapshotQuery). Any other key order can keep558+ // rows the timeline treats as oldest: timestamps tie within a burst of559+ // tool activity, and can even disagree with `sequence` outright when560+ // events arrive with skewed clocks. Descending, a NULL `sequence`561+ // sorts last, mirroring where the app's ascending reads place it.562+ //563+ // `sequence` arrived in migration 008, so a source without it falls564+ // back to the timestamp — same drift tolerance as the rest of the copy.565+ perKeyLimit: {566+ orderBy: hasColumn(source, "projection_thread_activities", "sequence")567+ ? `"sequence" DESC, "created_at"`568+ : `"created_at"`,569+ limit: options.activityLimit,570+ },
- @@ -0,0 +516,21 @@516+ }),517+ );518+ // row_id is an AUTOINCREMENT surrogate; let the target assign its own.519+ const turns = record(520+ copyRows({521+ source,522+ target,523+ table: "projection_turns",524+ keyColumn: "thread_id",525+ keys: threadIds,526+ omitColumns: ["row_id"],527+ }),528+ );529+ // A thread copied mid-turn has no agent to finish it. The session status is530+ // forced to "stopped" below, but the turn is read independently: an531+ // unfinished turn keeps the thread unsettled and unfoldable forever532+ // (deriveUnsettledTurnId in MessagesTimeline.logic.ts). Interrupted is what533+ // the server itself settles an abandoned turn to; a pending start is534+ // something it deletes outright.535+ settleRunningTurns(target, threadIds);536+ dropPendingTurnStarts(target, threadIds);@@ -0,0 +564,21 @@564+ // back to the timestamp — same drift tolerance as the rest of the copy.565+ perKeyLimit: {566+ orderBy: hasColumn(source, "projection_thread_activities", "sequence")567+ ? `"sequence" DESC, "created_at"`568+ : `"created_at"`,569+ limit: options.activityLimit,570+ },571+ }),572+ );573+ const sessions = record(574+ copyRows({575+ source,576+ target,577+ table: "projection_thread_sessions",578+ keyColumn: "thread_id",579+ keys: threadIds,580+ // No agent process is attached in the copy. A carried-over "running"581+ // status with an active turn renders a thread that spins forever, and582+ // ProviderSessionReaper skips reaping anything with an active turn.583+ overrides: { status: "stopped", active_turn_id: null, last_error: null },584+ }),
- @@ -163,3 +188,10 @@163188 readonly host: string;164189 }165190191+export interface DevShareLease {192+ readonly leasePath: string;193+ readonly ownerId: string;194+ readonly webPort: number;195+}196+197+export const claimDevShareLease = Effect.fn("devShare.claimDevShareLease")(function* (
- @@ -0,0 +256,21 @@256+ // symlink — and fall back to resolving the directory and re-joining the257+ // filename when the file does not exist yet: a nonexistent file cannot258+ // be a link to anything, but its directory still can be, and this is259+ // exactly the case where the missing-target advice ("start the dev260+ // server") would otherwise create the database in the shared home.261+ const canonicalDbPath = (databasePath: string) =>262+ fileSystem.realPath(databasePath).pipe(263+ Effect.catch(() =>264+ fileSystem265+ .realPath(path.dirname(databasePath))266+ .pipe(Effect.map((directory) => path.join(directory, path.basename(databasePath)))),267+ ),268+ Effect.orElseSucceed(() => databasePath),269+ );270+ const [canonicalTargetDb, canonicalSourceDb, canonicalShared] = yield* Effect.all([271+ canonicalDbPath(targetDbPath),272+ canonicalDbPath(sourceDbPath),273+ fileSystem.realPath(sharedHome).pipe(Effect.orElseSucceed(() => sharedHome)),274+ ]);275+ if (canonicalTargetDb.startsWith(`${canonicalShared}${path.sep}`)) {276+ return yield* new DevSeedTargetError({ reason: "shared-home", detail: canonicalTargetDb });@@ -217,0 +344,21 @@344+ return yield* Effect.gen(function* () {345+ const host = yield* prepareDevShare({ webPort: lease.webPort });346+ yield* claimDevShareLease(lease).pipe(347+ Effect.catch((error: DevShareLeaseClaimError) =>348+ publishDevShare({ host, webPort: lease.webPort }).pipe(349+ Effect.matchEffect({350+ onFailure: (restoreCause) =>351+ Effect.fail(352+ new DevShareLeaseClaimError({353+ leasePath: lease.leasePath,354+ cause: error.cause,355+ restoreCause,356+ }),357+ ),358+ onSuccess: () => Effect.fail(error),359+ }),360+ ),361+ ),362+ );363+ return yield* publishDevShare({ host, webPort: lease.webPort });364+ }).pipe(Effect.uninterruptible);@@ -115,0 +159,21 @@159+ for (const statePath of candidatePaths) {160+ const state = yield* readPersistedServerRuntimeState(statePath);161+ if (Option.isNone(state)) {162+ continue;163+ }164+ // A file left behind by a killed or crashed server describes a port165+ // nothing is listening on. Minting against it produces a token the live166+ // server rejects with `invalid_credential`.167+ if (yield* isPersistedServerRuntimeStateLive(state.value)) {168+ live.push({ stateDir: path.dirname(statePath), state: state.value });169+ }170+ }171+172+ // `devUrl` is only recorded by a server fronted by a web dev server, so it173+ // distinguishes the dev instance from a production-style one when both are174+ // running under the same base directory. This command is about dev, so a dev175+ // server wins regardless of which state directory the flags happened to176+ // resolve to.177+ return Option.fromNullishOr(178+ live.find((candidate) => candidate.state.devUrl !== undefined) ?? live[0],179+ );
t3dotgg(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.


🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
✨ Finishing Touches
📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share