Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat(dev): Make t3 code dev instances shareable over Tailscale #4556

Mergedt3dotgg(GitHub profile, opens in a new tab)merged 24 commits intomain fromrefs/pull/4556/headmerged by t3dotgg(GitHub profile, opens in a new tab) View on GitHub

Note

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

What

  • Make browser development single-origin by proxying backend HTTP, WebSocket, OAuth, and well-known routes through Vite.
  • Add dev:share / --share support that publishes the web port with Tailscale and cleans up the mapping on exit.
  • Make pairing grants and cookies work correctly from the shared HTTPS origin.
  • Centralize dev proxy configuration and cover the runner, sharing, auth, and Tailscale behavior with focused tests.

Why

Remote browsers could load the frontend but then try to connect to their own localhost for backend traffic. Sharing also needed the startup pairing URL, cookie policy, allowed origins, and Tailscale lifecycle to agree on the same public origin.

Impact

This is PR 2 of 3 and is stacked on #4555. Its diff is limited to single-origin browser hosting and Tailscale sharing.

Verification

  • 64 focused tests across the dev runner, sharing helper, auth policy, and Tailscale package
  • targeted lint
  • typechecks for shared, Tailscale, server, and web packages
  • isolated dev-stack startup smoke test

Note

Add --share flag to publish dev instances over Tailscale

  • Adds a --share flag (and dev:share npm script) to the dev runner that publishes the web dev server over HTTPS on the tailnet via tailscale serve, augmenting T3CODE_DEV_ALLOWED_ORIGINS with the tailnet origin so the backend accepts CORS requests from it.
  • Browser dev modes (dev, dev:web) now run in single-origin mode: VITE_HTTP_URL/VITE_WS_URL are cleared and Vite proxies backend path prefixes (/api, /oauth, /.well-known, /ws) so the app resolves the backend from window.location.origin rather than a hardcoded URL, enabling access from non-localhost origins.
  • Tailscale stderr is now classified into safe diagnostic labels (TailscaleStderrDiagnostic) to produce sanitized error messages without leaking secrets or node names; share/unshare failures surface structured DevShareError types with stage-specific messages.
  • Session cookie names are now port-scoped (e.g. t3_session_<port>) in desktop mode and in web dev mode when a devUrl is configured, so multiple instances on different ports do not collide.
  • Startup pairing tokens in dev environments now use a 24-hour TTL instead of the previous short default.
  • Risk: dev and dev:web now reject specific non-loopback --host values with DevRunnerHostNotProxiableError; inheriting a non-loopback HOST env var will also be rejected.
Macroscope summarized 83783d0.

Note

Medium Risk Touches authentication (cookies, pairing TTL, CORS) and dev networking; mistakes could break local login or leak sensitive Tailscale stderr, though changes are dev-scoped with broad test coverage.

Overview Browser dev becomes single-origin so the same UI works on localhost, tailnet, or LAN without baking in localhost backend URLs. The dev runner clears VITE_HTTP_URL / VITE_WS_URL, sets T3CODE_SINGLE_ORIGIN_DEV=1, and Vite proxies /api, /oauth, /.well-known, and /ws via a shared DEV_PROXIED_PATH_PREFIXES list; the server 404s those paths in dev instead of redirecting to Vite. Vite allows *.ts.net hosts and only pins HMR when HOST is set (desktop).

--share / dev:share publishes the web port with Tailscale (scripts/lib/dev-share.ts), sets VITE_DEV_SERVER_URL and appends the tailnet origin to T3CODE_DEV_ALLOWED_ORIGINS, and removes the mapping on exit (skipped for dry-run and warned for dev:desktop). Tailscale CLI failures now expose sanitized stderrDiagnostic labels instead of raw stderr.

Auth and cookies align with multi-instance dev: session cookies are t3_session_<port> when devUrl is set or in desktop mode; startup pairing tokens get a 24h TTL in dev via purpose: "startup"; dev CORS includes configured and shared origins.

Dev runner gains worktree-stable port offsets, loopback-focused port probing (avoids fighting tailscale serve), bind-host-aware server probes, rejection of non-proxiable --host for dev/dev:web, and DevRunnerHostNotProxiableError.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 83783d0562db8c69ab55859f5244c92ba4f486cd. 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 shared browser development via dev:share, publishing the web app over HTTPS on a tailnet.
    • Improved single-origin browser development with automatic proxying for backend and WebSocket routes.
    • Added support for configurable development hosts and allowed origins.
    • Startup pairing links now remain valid for up to 24 hours.
  • Bug Fixes

    • Prevented session collisions when running multiple development servers.
    • Improved port selection across worktrees and concurrent environments.
    • Replaced potentially sensitive Tailscale error output with safer diagnostic messages.
  • Documentation

    • Added guidance for shared development, browser proxying, port selection, and server startup output.
    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 25.00% 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 matches the main change: adding Tailscale sharing for dev instances.
      Description check✅ PassedIt covers what changed, why, impact, and verification, which satisfies the template's required information.
      ✨ 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-server-sharing`

      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 a new Tailscale sharing feature with significant runtime behavior changes including port-scoped session cookies, extended dev token TTLs (5min→24h), new CORS configuration, and Tailscale CLI integration. An unresolved medium-severity comment identifies an issue with orphan process cleanup. Human review recommended for these auth-adjacent and feature-enablement changes.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    4. Took ownership of this PR, reviewed it, and pushed one fix.

      Fixed: --share silently half-worked for dev:desktop (edc8e4f0b)

      The share block only guarded dev:server, so dev:desktop --share fell through and shared. That's broken in a way the user can't see:

      • Desktop keeps VITE_HTTP_URL/VITE_WS_URL baked to 127.0.0.1 (it's deliberately not single-origin), so a tailnet visitor loads the UI and then watches it dial their own loopback for the backend.
      • Worse, the share block overwrites VITE_DEV_SERVER_URL when --dev-url is unset — and that's the origin Electron loads the renderer from (DesktopApp.ts:176, Option.getOrThrow(environment.devServerUrl)).

      Now warns and carries on serving locally, matching the dev:server treatment. Added a test asserting it still spawns the stack.

      Verified, not just read

      • Loopback-only port probing is safe. The switch from probing ["127.0.0.1","0.0.0.0","::1","::"] to ["127.0.0.1","::1"] looked like it could hand out an occupied port. Empirically it can't — a wildcard 0.0.0.0 listener still makes a subsequent 127.0.0.1 bind fail EADDRINUSE, so loopback alone is a sufficient test.
      • Single-origin proxying works end to end. Booted the stack and probed: /.well-known/t3/environment through Vite → 200 with a real descriptor; / → 200; /api/foo straight at the backend → 404 (not a redirect loop); /somepage at the backend → 302 to Vite. The DEV_PROXIED_PATH_PREFIXES contract holds on both sides.
      • Port stability holds. I saw ports climb 8579→8580→8581 mid-review and suspected a bug in the worktree-hash offset — it was my own overlapping dev servers. With a clean process table the offset is stable at server=2849,web=2849 across runs.
      • Dropping /attachments from the proxy list is dead-code removal, not a regression. There is no /attachments HTTP route on the server and no client that fetches one; attachmentsDir is filesystem-only, and attachments are served under /api/assets (ASSET_ROUTE_PREFIX), which /api already covers.

      Deliberate behavior changes worth flagging for reviewers

      Both are correct, but they're the kind of thing that generates a bug report:

      1. Every dev session's cookie is renamed — t3_session → t3_session_<port> in web mode too. Anyone with a live browser session gets logged out once and re-pairs. The reasoning (cookies are host-scoped but not port-scoped, so concurrent servers clobber each other) is sound and the alternative is the far worse "Invalid session token signature" loop.
      2. Startup pairing tokens now live 24h instead of 5m, gated on devUrl !== undefined && purpose === "startup" — so it's dev-only; user-issued links and real servers keep 5 minutes. Correct gating.

      typecheck clean (0 errors), lint clean on changed files, 40/40 tests passing in dev-runner.test.ts + dev-share.test.ts.

      I'm babysitting this PR and will pick up review comments as they land.

    5. Rebased onto the updated base — #4555 picked up two new commits (e52d10409, 6404fc1a8) that touch scripts/dev-runner.ts in the same region as this PR, so GitHub flipped to CONFLICTING.

      Resolution kept the base's improvements and adapted this PR to them:

      • Took HostProcessWorkingDirectory over process.cwd(), including for the new worktree port-offset hash this PR adds — it was the one remaining raw process.cwd() call, and using the service keeps it testable and consistent with the base.
      • Kept the base's blank---home-dir trim fix in the resolvedT3Home precedence chain.

      45/45 tests passing (the base's 5 new tests merged in cleanly), typecheck 0 errors, and the runner still resolves the same stable offset (server=2849,web=2849) for both dev and dev:desktop.

    6. Review round converged — CI green on 37e1c7978, mergeable, all six threads answered.

      Fixed

      dbad3bc9f--share silently half-worked for dev:desktop — shared a URL whose renderer dials the visitor's own loopback, and clobbered the VITE_DEV_SERVER_URL Electron loads from
      ce4664d92raw tailscale stderr (auth keys, node names) reached logs via stderrPreview; bind host was never probed after the loopback narrowing
      2869a9e84a repo .env revived VITE_HTTP_URL/VITE_WS_URL and silently defeated single-origin mode
      37e1c7978the web port was judged against the backend's bind interface (a flaw in my own earlier fix)

      Declined, with reasoning

      Refusing --share for dev:web. It's the documented "Vite only" mode, meant to pair with a separately-running dev:server, and that combination is legitimate to share; refusing it blocks a working setup to guard against a misconfiguration that announces itself the moment a request 502s. I did fix the half that was right — the dev:desktop refusal message pointed at dev:web, which was bad advice, and now points at dev. dev:desktop stays refused because it's broken even when everything runs correctly.

      Things I checked empirically rather than by reading

      • Loopback-only probing is safe — a wildcard 0.0.0.0 listener still makes a later 127.0.0.1 bind fail EADDRINUSE, so loopback already catches wildcard squatters. This is why the narrowing was right and why I fixed the host gap by probing the specific configured host rather than restoring the wildcards.
      • The .env leak, by A/B — served module carried "http://localhost:13773" without the fix and "" with it, proxy still 200.
      • Single-origin proxying, end to end — descriptor through Vite 200, /api/foo at the backend 404 (no redirect loop), /somepage 302 to Vite.
      • Port stability — stable offset across restarts; earlier drift I saw was my own overlapping dev servers, not the worktree hash.

      Still worth a human eye

      Two intentional behavior changes that will generate reports if they surprise people: session cookies are renamed to t3_session_<port> in web mode, so every live dev session logs out once; and startup pairing tokens go to 24h (correctly gated to devUrl !== undefined && purpose === "startup", so real servers keep 5 minutes).

      65 tests, typecheck 0 errors, lint clean on changed files. Still babysitting.

    7. Actionable comments posted: 3

      🧹 Nitpick comments (5)
      scripts/dev-runner.ts (3)

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

      Recomputes the web port instead of reusing env.PORT.

      createDevRunnerEnv already derived the same value into env.PORT; duplicating the BASE_WEB_PORT + webOffset arithmetic here is a second source of truth that will drift if web-port resolution ever changes.

      ♻️ Suggested change
      -    const sharedWebPort = BASE_WEB_PORT + webOffset;
      +    const sharedWebPort = Number(env.PORT);
      🤖 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-runner.ts` at line 639, Update the code near sharedWebPort to
      reuse the resolved env.PORT value produced by createDevRunnerEnv instead of
      recomputing BASE_WEB_PORT + webOffset. Remove the duplicate arithmetic while
      preserving the existing shared web-port behavior.

      295-324: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

      T3CODE_PORT is now set identically in both branches.

      Lines 296 and 319 assign the same value; hoisting it above the isDesktopMode split would make the branch about the Vite URL/marker policy only.

      🤖 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-runner.ts` around lines 295 - 324, Move the shared T3CODE_PORT
      assignment above the isDesktopMode conditional, then remove the duplicate
      assignments from both branches. Keep the existing Vite URL and
      T3CODE_SINGLE_ORIGIN_DEV handling unchanged so the split only controls URL and
      marker policy.

      206-216: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

      Numeric T3CODE_DEV_INSTANCE bypasses the bounds applied elsewhere.

      Unlike T3CODE_PORT_OFFSET (negative-checked) and the hashed path (% MAX_HASH_OFFSET), a numeric seed is used verbatim, so T3CODE_DEV_INSTANCE=90000 resolves to an out-of-range port pair and surfaces as DevRunnerPortExhaustedError rather than a message naming the bad input. Consider validating it against the same offset range.

      🤖 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-runner.ts` around lines 206 - 216, Update the numeric-seed branch
      in the dev-runner offset resolution to validate Number(seed) against the same
      allowed offset bounds used by the other paths, rejecting values outside that
      range with an error that identifies the invalid T3CODE_DEV_INSTANCE input;
      preserve the existing hashed behavior and valid numeric offsets.
      scripts/lib/dev-share.test.ts (1)

      86-161: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

      Consider covering the no-tailnet-name / tailscale-unavailable branches.

      Both produce user-facing hints and neither is exercised — a status payload without Self.DNSName and a non-zero status exit would close the gap cheaply given the existing spawnerLayer.

      🤖 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-share.test.ts` around lines 86 - 161, Add tests in the
      shareDevServer suite for the no-tailnet-name and tailscale-unavailable branches:
      configure spawnerLayer with a successful status response whose payload omits
      Self.DNSName, and with a non-zero status exit respectively. Flip each effect and
      assert the resulting DevShareError reason and user-facing hint message.
      packages/tailscale/src/tailscale.ts (1)

      252-254: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

      Duplicate stderrDiagnosticOf(stderr) evaluation in both error constructions. Both sites call the classifier once for the presence check and again for the value; binding the result once makes the intent clearer and avoids re-running the regex list.

      • packages/tailscale/src/tailscale.ts#L252-L254: hoist const stderrDiagnostic = stderrDiagnosticOf(stderr); before the TailscaleCommandExitError construction and spread ...(stderrDiagnostic ? { stderrDiagnostic } : {}).
      • packages/tailscale/src/tailscale.ts#L318-L320: apply the same hoist inside runTailscaleCommand.
      🤖 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 252 - 254, Hoist the result
      of stderrDiagnosticOf(stderr) into a local stderrDiagnostic before each
      TailscaleCommandExitError construction, then reuse it for the conditional
      stderrDiagnostic property. Apply this at packages/tailscale/src/tailscale.ts
      lines 252-254 and 318-320 within runTailscaleCommand, preserving the existing
      behavior when no diagnostic is available.
      🤖 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 `@apps/server/src/auth/EnvironmentAuth.test.ts`:
      - Around line 18-26: The makeServerConfigLayer helper currently allows overrides
      to replace TEST_SERVER_PORT, which can desynchronize the server port and
      makeCookieRequest’s fixed cookie name. Apply ...overrides before assigning port:
      TEST_SERVER_PORT so the test port is always pinned while preserving all other
      overrides.
      
      In `@docs/reference/scripts.md`:
      - Line 4: Update the documented base and sharing commands in the web-stack
      startup instructions to use the required Bun workflow: replace the base command
      with “bun run dev” and the sharing variant with “bun run dev:share”. Preserve
      the existing descriptions of sharing behavior.
      
      In `@packages/tailscale/src/tailscale.test.ts`:
      - Around line 29-40: Update assertCarriesNoSecret to recursively inspect strings
      inside nested objects, arrays, and causes, while preserving the message check.
      Track visited objects with cycle protection so cyclic error structures terminate
      safely, and retain field-specific context in assertion failures where practical.
      
      ---
      
      Nitpick comments:
      In `@packages/tailscale/src/tailscale.ts`:
      - Around line 252-254: Hoist the result of stderrDiagnosticOf(stderr) into a
      local stderrDiagnostic before each TailscaleCommandExitError construction, then
      reuse it for the conditional stderrDiagnostic property. Apply this at
      packages/tailscale/src/tailscale.ts lines 252-254 and 318-320 within
      runTailscaleCommand, preserving the existing behavior when no diagnostic is
      available.
      
      In `@scripts/dev-runner.ts`:
      - Line 639: Update the code near sharedWebPort to reuse the resolved env.PORT
      value produced by createDevRunnerEnv instead of recomputing BASE_WEB_PORT +
      webOffset. Remove the duplicate arithmetic while preserving the existing shared
      web-port behavior.
      - Around line 295-324: Move the shared T3CODE_PORT assignment above the
      isDesktopMode conditional, then remove the duplicate assignments from both
      branches. Keep the existing Vite URL and T3CODE_SINGLE_ORIGIN_DEV handling
      unchanged so the split only controls URL and marker policy.
      - Around line 206-216: Update the numeric-seed branch in the dev-runner offset
      resolution to validate Number(seed) against the same allowed offset bounds used
      by the other paths, rejecting values outside that range with an error that
      identifies the invalid T3CODE_DEV_INSTANCE input; preserve the existing hashed
      behavior and valid numeric offsets.
      
      In `@scripts/lib/dev-share.test.ts`:
      - Around line 86-161: Add tests in the shareDevServer suite for the
      no-tailnet-name and tailscale-unavailable branches: configure spawnerLayer with
      a successful status response whose payload omits Self.DNSName, and with a
      non-zero status exit respectively. Flip each effect and assert the resulting
      DevShareError reason and user-facing hint message.
      🪄 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: 6650ded2-f1b8-41f0-88dd-2bcf360de729

      📥 Commits

      Reviewing files that changed from the base of the PR and between 6404fc1a8e042e3ec079ea749413602e79e7002d and 37e1c7978ce827fa4c8fd5cf1585be4969dd4a52.

      ⛔ Files ignored due to path filters (1)
      • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
      📒 Files selected for processing (22)
      • .agents/skills/test-t3-app/SKILL.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/http.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.test.ts
      • packages/tailscale/src/tailscale.ts
      • scripts/dev-runner.test.ts
      • scripts/dev-runner.ts
      • scripts/lib/dev-share.test.ts
      • scripts/lib/dev-share.ts
      • scripts/package.json
    8. Fixed the failing Effect Service Conventions check in 2db512ad4.

      The check was right, and its finding had been sitting in an orphaned inline comment from an earlier commit — the force-pushes marked it outdated, so it never showed up in my unreplied-thread sweep. My fault for only ever checking live threads.

      DevShareError violated four rules of .macroscope/check-run-agents/effect-service-conventions.md at once:

      • a reason discriminator chose both the user-facing message and the caller's remedy (hint) — the convention says split those into separate classes
      • the message getter was a lookup table over that discriminator, which the convention names explicitly
      • detail copied cause.message and was then used to construct the wrapper message — also named explicitly
      • the underlying TailscaleCommandError was discarded entirely, so the error chain ended at the wrapper

      Now three classes. TailscaleUnavailableError and TailnetNameMissingError each have one fixed message and one remedy, so the discriminator disappears. DevServeFailedError keeps a stage field — that one is legitimate under the convention, since both stages share the same semantics (a tailscale serve invocation failed for this port) and differ only in which one, which the message states plainly. The stage distinction matters operationally: clear-existing means the prior mapping survived, serve means it was already torn down.

      Every wrapping construction now keeps the immediate error as cause, and messages derive solely from structural fields. unshareDevServer returns the structured cause instead of a flattened string so its caller can preserve the chain too. TailnetNameMissingError has no cause because there is no underlying failure — the status read succeeded and simply had no name, which is the case the convention describes as legitimately optional.

      Verified the chain survives rather than assuming it: the wrapped TailscaleCommandExitError is reachable with exitCode and stderrDiagnostic intact, and the auth token seeded into stderr still never reaches the message — so this doesn't undo the earlier secret-leak fix.

      204 tests passing across scripts/ and packages/tailscale/, typecheck 0 errors, lint clean.

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

    10. Pushed two fixes from a fresh review pass, and answered the remaining threads.

      Fixed

      2071c986aDesktop cookie regression — switching the cookie-name discriminator to devUrl alone reverted #1898: packaged desktop (no devUrl) went back to bare t3_session, but desktop instances scan upward from 3773 and share 127.0.0.1, so two of them clobber each other's session. Now scoped on devUrl or desktop mode; restored the two test assertions that had been relaxed to match the regression (EnvironmentAuthPolicy.test.ts, server.test.ts — the latter runs mode: "desktop" and was asserting the regressed name).
      63b261387Inherited HOST defeated single-origin dev — the runner only sets HOST for desktop and never cleared it, so an exported one (container, CI, HOST=0.0.0.0 habit) reached Vite in dev/dev:web and pinned the HMR socket to that address. Same class as the .env revival fixed in 2869a9e84, same treatment: cleared in the non-desktop branch. Verified live — with HOST=0.0.0.0 exported, Vite binds 127.0.0.1 only and the served @vite/client falls back to the page origin.

      Declined, with reasoning (in the threads)

      • --host <specific-interface> breaks the Vite proxy target — real but loud (every request 502s immediately), and wildcard/unset hosts — the common cases — are unaffected since loopback stays bound. Threading the bind host into the proxy adds shared wildcard-detection machinery for a config that single-origin dev makes nearly pointless.
      • Lease read error mistaken for "superseded" — worst case is one stale mapping, and prepareDevShare already clears stale mappings on the next share of that port (it must: SIGKILL leaves the same state with no finalizer at all). The pre-clear is the recovery path for this class.
      • The claim-ordering thread was already resolved by 3b4765b42…0a504fa8e; replied with the mapping from report to commit.

      A deliberate line in the sand, per review discussion: the lease machinery at HEAD is internally consistent (prepare → claim → publish, uninterruptible, restore on failure) and this is a dev-only convenience feature — further hardening rounds against ever-rarer races are out of scope.

      Verified: full server suite 1623 passed, scripts 180, typecheck 0 errors, and a live dev --share end-to-end over the tailnet (pairing included) both before and after these fixes.

      🤖 Generated with Claude Code

    11. Removed the lease protocol in 1c8e54057 — a deliberate simplification, not a fix.

      The five commits of ownership machinery (4333a66fd…0a504fa8e: lease files, claim/handoff ordering, restore-on-failure) closed one race: a fast restart where the old runner's finalizer tears down the mapping a new runner just installed on the same port. For a dev-only convenience that failure is visible — your shared URL stops working — and re-running --share fixes it. Each hardening round was also surfacing new races inside the mechanism itself, which is a sign the mechanism was the problem.

      Back to the plain shape: clear any stale mapping, serve, unshare on exit, registered atomically via acquireRelease. Stale mappings from SIGKILLed runs were always recovered by the pre-clear on the next share (a killed process runs no finalizer, lease or not), and still are.

      To reviewers and bots alike: the fast-restart teardown race is now accepted behavior, documented in the comment at the share block in scripts/dev-runner.ts. Findings that rediscover it are working as intended.

      Net: −286 lines, PR is now 1,288 insertions (630 product / 632 tests). Verified after the cut: 175 script tests, typecheck 0 errors, and a live dev --share end-to-end — tailnet URL 200, /ws upgrade reaches the backend (401), mapping removed on SIGTERM.

      🤖 Generated with Claude Code

    12. Two more commits: the dev-runner now prints the exact stop command at startup.

      [dev-runner] stop: kill -TERM -"$(ps -o pgid= -p <pid> | tr -d ' ')" (kills this runner and every child; never kill by name pattern)

      Why (faf646707): stopping the stack had no printed right answer, and both wrong answers happened today on this branch's own history. Killing just the runner PID orphans the node --watch server children — vp doesn't reap them, and they keep holding the server port (I found three such orphans from earlier runs, one per past dev invocation). And guessing a pkill/pgrep pattern has killed the driving agent itself twice — its argv contains the worktree path — and can reach other worktrees' servers.

      The printed command targets the process group, with the pgid resolved via ps at kill time because under bun run dev the group leader is bun, not the runner — a hardcoded kill -- -<runnerPid> would name a nonexistent group. Verified live: ran the printed command verbatim against a running stack; zero surviving processes with the worktree's T3CODE_HOME, other worktrees' servers untouched. taskkill /pid <pid> /T on Windows. AGENTS.md and the test-t3-app skill now point at the stop: line and name the pattern-kill footgun.

      08d926081 is a lint follow-up (platform via HostProcessPlatform instead of process.platform).

      177 script tests, typecheck 0 errors, lint clean.

      🤖 Generated with Claude Code

    13. Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

      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 08d9260817b9e1fae5a8641e6ad8a6499e00bb73. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -353,0 +425,21 @@
      425+ }
      426+ return [...DEV_PORT_PROBE_HOSTS, host];
      427+}
      428+
      429+/**
      430+ * The exact command that stops this runner and everything it spawned, printed
      431+ * at startup. Exists because the alternative — guessing a `pkill` pattern —
      432+ * has twice killed the agent running the session (its argv contains the
      433+ * worktree path) and can reach other worktrees' dev servers.
      434+ *
      435+ * Targets the process group: children are spawned with `detached: false`, so
      436+ * the whole stack (including the `node --watch` server processes, which keep
      437+ * the group after re-parenting to init) shares it. The pgid is resolved via
      438+ * `ps` rather than assumed equal to our PID — under `bun run dev` the group
      439+ * leader is bun, not this runner, and `kill -- -<runnerPid>` would name a
      440+ * group that does not exist.
      441+ */
      442+export function resolveStopCommand(pid: number, platform: NodeJS.Platform): string {
      443+ return platform === "win32"
      444+ ? `taskkill /pid ${String(pid)} /T`
      445+ : `kill -TERM -"$(ps -o pgid= -p ${String(pid)} | tr -d ' ')"`;

      Deferred PGID breaks orphan cleanup

      Medium Severity

      The Unix stop command embeds the runner PID and resolves the process group with ps only when the user runs it. After the runner has exited, that lookup fails or can hit a recycled PID, so the logged command may not stop orphaned node --watch children even though the new skill text says it should.

      Additional Locations (1)
      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 08d9260817b9e1fae5a8641e6ad8a6499e00bb73. Configure [here](https://www.cursor.com/dashboard/bugbot).

      Also resolved by the revert in 9055f7c5d — the stop command, and the skill text claiming it cleans up watchers, are both gone.

      The finding is correct: resolving the pgid at execution time means the command stops meaning anything the moment the runner exits (lookup fails, or worse, hits a recycled PID). Together with the sibling thread about inherited process groups, the two failure modes bracket the design — wrong while running under a harness, wrong after exiting anywhere — so the right fix was removal, not repair.

    14. Acted on the external review feedback in 9055f7c5d and 83783d056.

      Removed: the printed stop command (9055f7c5d)

      Both findings were right, and together they bracket the design: wrong while running (a harness-spawned runner inherits the harness's pgid, so the printed group-kill reaches the harness itself — reproduced with a plain child_process.spawn; my earlier live check passed only because bash job control gave the backgrounded runner its own group) and wrong after exit (the deferred ps lookup fails or hits a recycled PID, so it can't clean orphaned watchers either). A safe version needs setsid at spawn — which conflicts with the deliberate detached: false Ctrl+C forwarding — plus a pidfile. That's more machinery than a convenience line justifies, so the feature is gone rather than repaired, docs included.

      Fixed: specific-interface --host now rejected for browser dev (83783d056)

      Reversing my earlier decline — the reviewer's framing ('fix or explicitly reject') was better than mine. I had declined the fix (threading the bind host into the proxy) as machinery; rejection gets the user a clear message instead of a silently broken server, for ~20 lines. --host 192.168.1.10 with dev/dev:web now fails at startup naming the two working alternatives (wildcard bind, --share). Wildcards still work — they keep loopback answering, so the proxy target stays valid — and dev:server/dev:desktop are untouched since they don't proxy. Three tests cover reject/wildcard/dev:server.

      Same commit returns the docs this PR touched to vp run dev — vp is the repo's task runner; the bun run wording was introduced by this PR itself and matched neither main nor the surrounding lines.

      On the other two review points

      • Is Tailscale publication a repo feature or a personal-launcher feature? Genuinely the maintainer's call, but the repo-feature case: the failure modes this PR fixes (baked loopback URLs, port drift, cookie collisions, pairing-URL origin) all live in repo code, so an external launcher can't fix them — it can only proxy a URL whose bundle still dials the wrong machine, which is exactly what the pre-existing personal script did.
      • Splitting single-origin / cookies from sharing: agreed in principle; at this point in the stack (PR 2 of 3, both halves reviewed together, #4557 stacked on top) a split would churn more than it clarifies. Noting it as the shape future work should take.

      178 script tests, typecheck 0 errors, lint clean. Verified live: --host 192.168.1.10 fails with the new error, --host 0.0.0.0 and plain dev --share --dry-run unchanged.

      🤖 Generated with Claude Code

Sign in to join this conversation.