Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat(dev): dev server pairing and seed utilities #4557

Closedt3dotgg(GitHub profile, opens in a new tab)wants to merge 30 commits intomain fromagent/dev-utilitiesopened View on GitHub

Note

Dev mode overhaul — PR 3 of 3. The stack moves from worktree-isolated dev state → single-origin and Tailscale sharing → pairing and seed utilities. This final PR is stacked on #4556.

What

  • Add dev:pair to find a live dev server’s recorded state and issue a fresh pairing URL with the correct web origin.
  • Add dev:seed to copy recent projection data into an isolated dev database while refusing to write to the shared home.
  • Record the dev URL in runtime state and ignore stale server records.
  • Share the projection-table list with the mobile showcase tooling and document the workflows.

Why

Isolated worktree databases are intentionally empty, and replacing a consumed pairing URL previously required reconstructing internal ports, state paths, and origins by hand. These are useful developer conveniences, but they are not required for the hosting fix itself.

Impact

This is PR 3 of 3 and is stacked on #4556. Keeping these optional utilities last lets the core isolation and sharing changes land without the larger data-copy implementation.

Verification

  • vp test run scripts/lib/dev-seed.test.ts apps/server/src/cli/auth.test.ts apps/server/src/serverRuntimeState.test.ts (24 tests)
  • targeted lint
  • server and scripts typechecks

Note

Add dev server pairing URL command and database seeding CLI with tailnet lease management

  • Adds dev:pair npm script (t3 auth pairing url) that discovers a live dev or userdata server runtime state and prints a one-time pairing URL, preferring the dev instance when both are running.
  • Adds dev:seed npm script (scripts/dev-seed.ts) that seeds recent projects, threads, messages, turns, sessions, and activities from a source T3 data directory into a target dev database; refuses to run against a live server or a path inside the shared home.
  • Adds lease-based tailnet share ownership in scripts/lib/dev-share.ts: acquireDevShare atomically claims a per-port owner file before publishing, and cleanupOwnedDevShare restores a successor's mapping if ownership changes during teardown.
  • Adds findRunningServerPid in scripts/lib/server-runtime-probe.ts to synchronously detect live server PIDs from server-runtime.json state files, used by both the seed CLI and the pairing URL command.
  • Behavioral Change: resolveSessionCookieName drops the port suffix for desktop (non-dev) sessions; cookie name is now t3_session instead of t3_session_<port> when devUrl is absent, affecting existing desktop sessions on upgrade.
Macroscope summarized 6588b84.

Note

Medium Risk Desktop and hosted sessions now use a single cookie name (users may need to re-pair), while dev:seed is destructive to target projections/event logs though guarded against the shared home and live servers.

Overview Dev pairing and seeding — bun run dev:pair (auth pairing url) locates a live server by reading server-runtime.json under dev/userdata, verifies the recorded PID is still alive, and mints a one-time pairing URL using the stored web origin (including tailnet devUrl). bun run dev:seed copies a capped slice of projection data (and attachment files) from ~/.t3 into a worktree-isolated database, with guards against the shared home (including symlinked paths), same-source seeds, and seeding while a server holds the target DB open (with a late re-check before commit).

Runtime state and config — Persisted runtime state now optionally records devUrl; stale files from crashed processes are ignored via PID liveness probing. deriveServerPaths accepts an explicit stateDir so pairing tooling targets the same database the running server uses.

Auth cookies — resolveSessionCookieName no longer special-cases desktop: production/desktop use t3_session; only servers with a devUrl get port-scoped t3_session_<port>.

Tailscale --share — Dev sharing uses file leases (acquireDevShare / cleanupOwnedDevShare) so one runner’s exit does not tear down another’s mapping; cleanup can restore a mapping if ownership changed mid-flight.

Docs and tests — Agent skills and scripts.md document bun run dev, dev:pair, and dev:seed; sqlite fixture docs note projection_state cursors; large test coverage for seeding, auth CLI discovery, runtime liveness, and share leases.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 6588b843da90ba8865a541af05f9961156639649. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Summary by CodeRabbit

  • New Features

    • Added commands to share local development servers, generate pairing URLs, and seed isolated development data.
    • Development servers now support worktree-specific ports and improved browser proxying.
    • Shared development environments can use HTTPS tailnet URLs with configurable allowed origins.
    • Session cookies are isolated by server port, preventing conflicts between concurrent instances.
    • Tailscale errors now include concise diagnostic details.
  • Documentation

    • Expanded development setup guidance, browser workflow instructions, pairing recovery, port handling, and database seeding safety notes.
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      🚥 Pre-merge checks | ✅ 4 | ❌ 1

      ❌ Failed checks (1 warning)

      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 46.67% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
      ✅ Passed checks (4 passed)
      Check nameStatusExplanation
      Linked Issues check✅ PassedCheck skipped because no linked issues were found for this pull request.
      Out of Scope Changes check✅ PassedCheck skipped because no linked issues were found for this pull request.
      Title check✅ PassedThe title clearly names the main change: dev server pairing and seeding utilities.
      Description check✅ PassedThe description covers what, why, impact, and verification, though it does not use the exact template headings or checklist.
      ✨ Finishing Touches
      📝 Generate docstrings
      • Create stacked PR
      • Commit on current branch
      🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Commit unit tests in branch `agent/dev-utilities`

      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
      Comment `@coderabbitai help` to get the list of available commands.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted

    3. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Needs human review

      This PR introduces substantial new developer tooling features including database seeding utilities with complex SQLite manipulation, new CLI commands, and changes to session cookie scoping behavior. The scope of new functionality and auth-adjacent changes warrant human review.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    4. Picked this up, reviewed it, and pushed fixes in 331fc7124.

      Review found five ways a seeded database could describe something the copy cannot back up. All are in the dev:seed path; dev:pair reviewed clean.

      dev:seed ran against a live server. The docs said "stop the server first" but nothing enforced it. SQLite locking isn't sufficient on its own — the seed's transaction can take the write lock between the running server's own writes and commit cleanly. What it can't do is tell that server the projections it holds in memory, and the event log it appends to, were both replaced underneath it. Now refused via a pid probe over both state directories, with stale files from a SIGKILLed server ignored so seeding can't get permanently blocked.

      Turns copied mid-flight stayed running. The status: "stopped" session override didn't cover this: the turn is read independently, and deriveUnsettledTurnId keeps the thread unsettled and its timeline unfoldable as long as the turn is running — with no agent left to finish it. Now settled to interrupted, matching settledTurnStateForSessionStatus for the stopped status the sessions are copied with. Streaming messages are finished for the same reason.

      Attachment metadata was copied without the files. attachments_json came along but the bytes live on disk beside the database, so a seeded thread rendered an image whose request 404s. The seeder now reports referenced ids and the CLI copies the matching files. Matched by directory listing rather than reconstructing the extension, since the server infers that at upload time.

      Orphaned provider bindings survived. provider_session_runtime was neither copied nor cleared, so rows naming just-deleted threads outlived them. ProviderSessionReaper sweeps every non-stopped binding, finds no thread behind it, so never reaches its active-turn guard — it just tries to stop a session for a thread that doesn't exist, against a provider instance the worktree may not define.

      --threads had no upper bound. Each selected thread is one bound parameter in the copy's IN (...); past SQLite's 32766 ceiling the seed dies with "too many SQL variables" after the target has been emptied.

      Also corrected a comment: it claimed sequence restarts at 1 after the log is emptied. orchestration_events.sequence is AUTOINCREMENT, so DELETE doesn't reset the high-water mark. Zero is still the right cursor — it's below every future sequence either way — but for a different reason than the one written down.

      Verification: 33 tests pass (9 new covering the guard, turn settling, streaming, attachment ids, and binding cleanup), scripts typecheck and lint clean.

    5. Second round pushed in 73669b3d5, covering the Macroscope comment and findings from a follow-up review of the pairing path.

      isPersistedServerRuntimeStateLive reported non-positive pids as live. The highest-severity item this round. process.kill reads 0 and -1 as signal-group targets rather than process lookups — 0 signals the caller's own group, -1 every permitted process — so neither throws, and both landed in the "didn't throw, so it's running" branch. Verified directly. A truncated or hand-edited state file recording either would be believed indefinitely, and since a dev candidate wins the devUrl preference it also outranks a genuinely live server elsewhere, minting tokens into a database nothing reads. Rejected in the schema and re-checked at the call site. The errno cast is now a guard, since an out-of-range pid throws a TypeError with no code. Regression tests confirmed failing without the fix.

      pairing url --json emitted warnings on stdout ahead of the payload. The probe reads both state directories, so a corrupt file in the one not in use broke JSON for anything piping it — the quiet-logs layer was only applied around the issuing step that runs afterward. Reproduced with a crafted fixture; stdout is now valid JSON on the success path.

      Turns copied in the pending state were left unsettled — same defect class as the running case from the first round, one state short. That's a user message accepted before its provider turn started, which only that thread's next message would ever clear.

      The source was read across a dozen implicit transactions while the installed app may be writing to it, so a project could vanish between the query that selected it and the copy that read its row — leaving an orphaned thread, with no foreign keys to catch it. Now one deferred read transaction pinning every query to a single snapshot.

      --from and --to resolving to the same directory is refused. Details in the inline reply — the wipe described in the review comment doesn't reproduce (the source reads a pre-transaction snapshot, so the rows come back; verified in both journal modes), but the event log, cursors, and anything outside the caps genuinely don't, so it's guarded on that basis.

      Verification: 38 tests pass, full-repo typecheck reports 0 errors, lint clean on changed files.

    6. Actionable comments posted: 3

      🧹 Nitpick comments (4)
      scripts/mobile-showcase-environment.ts (1)

      2-2: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

      Finish the dedup: PROJECTION_TABLES_IN_DEPENDENCY_ORDER is also exported now.

      seedDatabase still inlines the same nine-table delete list that the new module exports, so the two can drift the moment a projection table is added.

      ♻️ Import the shared list too
      -import { PROJECTOR_NAMES } from "./lib/projection-tables.ts";
      +import {
      +  PROJECTION_TABLES_IN_DEPENDENCY_ORDER,
      +  PROJECTOR_NAMES,
      +} from "./lib/projection-tables.ts";

      Then in seedDatabase:

      for (const table of PROJECTION_TABLES_IN_DEPENDENCY_ORDER) {
        database.exec(`DELETE FROM ${table}`);
      }
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@scripts/mobile-showcase-environment.ts` at line 2, Update the imports in
      scripts/mobile-showcase-environment.ts to include
      PROJECTION_TABLES_IN_DEPENDENCY_ORDER, then replace seedDatabase’s inline
      projection-table delete list with iteration over that shared exported list while
      preserving the existing DELETE execution.
      scripts/dev-seed.ts (1)

      266-276: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

      catch: (cause) => cause as DevSeedError is an unchecked cast.

      seedDevDatabase wraps its own failures today, so this holds in practice, but any future throw that isn't a DevSeedError (or isn't an Error at all) reaches the tapError at Line 312-315 and dereferences .message on it. Normalizing here keeps the error channel type honest.

      ♻️ Normalize unexpected causes
      -        catch: (cause) => cause as DevSeedError,
      +        catch: (cause) =>
      +          cause instanceof DevSeedError
      +            ? cause
      +            : new DevSeedError(`could not seed the dev database: ${String(cause)}`),
      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@scripts/dev-seed.ts` around lines 266 - 276, Replace the unchecked cast in
      the Effect.try catch handler around seedDevDatabase with normalization that
      preserves existing DevSeedError instances and converts unexpected thrown values
      into a DevSeedError-compatible error. Ensure non-Error causes are also safely
      represented so the downstream tapError handling can access message without
      throwing.
      scripts/lib/dev-seed.test.ts (1)

      545-572: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

      Consider marking the 32k-thread fixture as a slow test.

      Building 32,766 thread and turn rows on every run of this file is the one materially slow case here. A it.skipIf/tag or a longer explicit timeout keeps the focused-test workflow snappy without losing the ceiling guarantee in CI.

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@scripts/lib/dev-seed.test.ts` around lines 545 - 572, Mark the
      maximum-thread-limit test identified by its “seeds at the maximum thread limit
      without exhausting SQL variables” description as slow, using the project’s
      existing skip/tag mechanism or an explicit extended timeout. Preserve its CI
      execution and the existing ceiling assertions while keeping focused local test
      runs fast.
      packages/tailscale/src/tailscale.ts (1)

      219-228: 📐 Maintainability & Code Quality | 🔵 Trivial

      Minor: stderrPreviewOf(stderr) computed twice per call site.

      Both readTailscaleStatus and runTailscaleCommand call stderrPreviewOf(stderr) once in the ternary condition and again in the object body. Hoisting into a local avoids the redundant (if cheap) call and reads slightly cleaner.

      ♻️ Proposed dedup
      -        ...(stderrPreviewOf(stderr) !== undefined
      -          ? { stderrPreview: stderrPreviewOf(stderr) }
      -          : {}),
      +        ...(preview !== undefined ? { stderrPreview: preview } : {}),

      (with const preview = stderrPreviewOf(stderr); added above each call site)

      Also applies to: 286-295

      🤖 Prompt for AI Agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      In `@packages/tailscale/src/tailscale.ts` around lines 219 - 228, Deduplicate
      stderrPreviewOf(stderr) in both readTailscaleStatus and runTailscaleCommand by
      assigning its result to a local preview variable before constructing
      TailscaleCommandExitError, then reuse that variable for the conditional property
      and stderrPreview value.
      🤖 Prompt for all review comments with AI agents
      Verify each finding against current code. Fix only still-valid issues, skip the
      rest with a brief reason, keep changes minimal, and validate.
      
      Inline comments:
      In @.agents/skills/test-t3-app/SKILL.md:
      - Around line 51-58: Update the later troubleshooting guidance that recommends
      manually minting replacement tokens to direct agents to run the existing `bun
      run dev:pair` workflow instead, preserving the documented `--base-dir` usage
      when applicable and removing the obsolete manual-token recovery instructions.
      
      In `@docs/reference/scripts.md`:
      - Around line 54-55: Update the runtime-state documentation to describe probing
      both dev and userdata for the directory containing the active database,
      resolving dev/userdata ties by modification time. In docs/reference/scripts.md
      at lines 54-55, replace the userdata-first wording; in
      .agents/skills/test-t3-app/SKILL.md at line 58, explain that pairing checks both
      directories and applies the same active-state selection rule.
      - Around line 4-6: Standardize the documented development workflow on the
      repository’s bun wrappers: in docs/reference/scripts.md lines 4-6, replace the
      vp run dev, vp run dev:share, vp run dev:pair, and vp run dev:seed examples with
      their bun run equivalents while preserving the existing options and
      descriptions; in .agents/skills/test-t3-app/SKILL.md line 16, replace vp run dev
      with bun run dev and keep the sharing variant as bun run dev:share.
      
      ---
      
      Nitpick comments:
      In `@packages/tailscale/src/tailscale.ts`:
      - Around line 219-228: Deduplicate stderrPreviewOf(stderr) in both
      readTailscaleStatus and runTailscaleCommand by assigning its result to a local
      preview variable before constructing TailscaleCommandExitError, then reuse that
      variable for the conditional property and stderrPreview value.
      
      In `@scripts/dev-seed.ts`:
      - Around line 266-276: Replace the unchecked cast in the Effect.try catch
      handler around seedDevDatabase with normalization that preserves existing
      DevSeedError instances and converts unexpected thrown values into a
      DevSeedError-compatible error. Ensure non-Error causes are also safely
      represented so the downstream tapError handling can access message without
      throwing.
      
      In `@scripts/lib/dev-seed.test.ts`:
      - Around line 545-572: Mark the maximum-thread-limit test identified by its
      “seeds at the maximum thread limit without exhausting SQL variables” description
      as slow, using the project’s existing skip/tag mechanism or an explicit extended
      timeout. Preserve its CI execution and the existing ceiling assertions while
      keeping focused local test runs fast.
      
      In `@scripts/mobile-showcase-environment.ts`:
      - Line 2: Update the imports in scripts/mobile-showcase-environment.ts to
      include PROJECTION_TABLES_IN_DEPENDENCY_ORDER, then replace seedDatabase’s
      inline projection-table delete list with iteration over that shared exported
      list while preserving the existing DELETE execution.
      🪄 Autofix (Beta)

      Fix all unresolved CodeRabbit comments on this PR:

      • Push a commit to this branch (recommended)
      • Create a new PR with the fixes

      ℹ️ Review info
      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: 1139449d-5adc-49f6-a961-eb622b3e4674

      📥 Commits

      Reviewing files that changed from the base of the PR and between dbad3bc9f4f97704dd07cedba8bf2f8a18fdb165 and 3fa657864dd0de17bbce36c563cae06001dec173.

      ⛔ Files ignored due to path filters (1)
      • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
      📒 Files selected for processing (34)
      • .agents/skills/test-t3-app/SKILL.md
      • .agents/skills/test-t3-app/references/sqlite-fixtures.md
      • AGENTS.md
      • apps/server/src/auth/EnvironmentAuth.test.ts
      • apps/server/src/auth/EnvironmentAuth.ts
      • apps/server/src/auth/EnvironmentAuthPolicy.test.ts
      • apps/server/src/auth/EnvironmentAuthPolicy.ts
      • apps/server/src/auth/PairingGrantStore.ts
      • apps/server/src/auth/SessionStore.ts
      • apps/server/src/auth/utils.ts
      • apps/server/src/cli/auth.test.ts
      • apps/server/src/cli/auth.ts
      • apps/server/src/config.ts
      • apps/server/src/http.ts
      • apps/server/src/serverRuntimeState.test.ts
      • apps/server/src/serverRuntimeState.ts
      • apps/web/vite.config.ts
      • docs/reference/scripts.md
      • package.json
      • packages/shared/package.json
      • packages/shared/src/devProxy.ts
      • packages/tailscale/src/tailscale.ts
      • scripts/dev-runner.test.ts
      • scripts/dev-runner.ts
      • scripts/dev-seed.ts
      • scripts/lib/dev-seed.test.ts
      • scripts/lib/dev-seed.ts
      • scripts/lib/dev-share.test.ts
      • scripts/lib/dev-share.ts
      • scripts/lib/projection-tables.ts
      • scripts/lib/server-runtime-probe.test.ts
      • scripts/lib/server-runtime-probe.ts
      • scripts/mobile-showcase-environment.ts
      • scripts/package.json
    7. On the docstring coverage warning: added docs to the exported surface in 33fcf80b7 — the parts a caller genuinely needs to know. Specifically that seedDevDatabase is destructive and not incremental, that it validates before opening anything so a rejected run leaves the target untouched, that the caller still owns copying the attachment files, and that DevSeedError.hint is the actionable half the CLI prints on its own line.

      I stopped short of the 80% threshold deliberately. The remaining undocumented declarations are things like placeholders, hasTable, columnsOf, and stateDbPath — one-line helpers whose names and signatures say everything a comment would. For context on convention: the rest of scripts/ documents roughly 2% of its top-level declarations, and these files were already at ~47% before this commit. Padding those four to satisfy a generic threshold would add noise without adding information, and would read as inconsistent with the surrounding code.

      Happy to revisit if the 80% target is a deliberate repo standard rather than a CodeRabbit default — that's a maintainer call, not one I want to make unilaterally on someone else's codebase.

    8. t3dotgg(GitHub profile, opens in a new tab) changed the title

    9. Cursor Bugbot has reviewed your changes using high effort and found 3 potential issues.

      Fix All in Cursor ❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot). Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 2187054482495faaa537a6b133796c880efa7373. Configure [here](https://www.cursor.com/dashboard/bugbot).
    10. Closing because both remaining jobs now have smaller replacements: #4955 generalizes dev pairing into t3 pair, and #4949 standardized the simple VACUUM INTO snapshot workflow instead of a projection-aware seeder.

Sign in to join this conversation.