Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat(orchestrator): move a running thread between devices #5544

ClosedBil0000(GitHub profile, opens in a new tab)wants to merge 250+ commits intot3code/codex-turn-mapping fromrefs/pull/5544/headopened View on GitHub

Closes #5363.

Stacked on #2829 (t3code/codex-turn-mapping). main and the orchestrator branch share no common ancestor; every primitive this builds on exists only there.

What this does

Run on picks the machine a thread starts on and locks once it has a message — a thread is born on one device and dies there. This makes that reversible: pick another connected environment from the same control, and the conversation, the provider continuation, and the git working state move there. Pull it back later from the same control, which shows where the thread originally ran.

Verified live: real threads moved repeatedly between a MacBook (desktop app) and a Linux server and continued on each side, through the actual relay-free client-brokered transfer — including round trips, pull-backs, and the failure modes listed under Verification.

The safety model

  • A branch tip only ever moves to a descendant of itself, on either machine. Diverged or unrelated history parks the sender's commits at refs/handoff/<environment>/<handoff>/<branch> and stops with both machines untouched.
  • Exactly one side is live. thread.handoff.depart locks the giving side before any bundle is applied anywhere; mutations on an away thread are refused in the orchestrator (a small allowlist of local-copy lifecycle verbs excepted). An interrupted transfer releases the lock; a stranded one has a Continue here escape hatch, offered only while the transfer never landed. A completed handoff can no longer be aborted or repointed.
  • Old tip tagged and dirty worktrees stashed (root and destination worktree independently) before any pointer moves; patches dry-run first; a failed apply rolls the repository back and cleans up everything it extracted. Rollback metadata (pre-tag, stashes, apply directory) is persisted before the patch lands, so startup recovery can restore the tree from any crash point — including a first arrival that died before its thread projection existed.
  • A busy thread is interrupted first and the transfer starts when it goes idle; the depart command re-checks for active runs under the dispatch lock, so a racing message cannot slip a live run past the snapshot.
  • Payload ceilings (200 MB warn / 1 GB refuse) enforced during prepare and again per chunk on the receiving side. First hops cut the bundle against the repo's remote-tracking refs; a fully pushed branch ships no bundle at all.
  • Untracked files that would overwrite tracked files on the receiver refuse the hop (checked on real extracted paths in a staging directory, immune to path tricks). ThreadHandoffId is schema-restricted to a URL- and git-ref-safe alphabet.

What travels

Branch + unpushed commits (git bundle, checkpoint refs ride along so revert keeps working), tracked changes (binary patch), untracked files (null-delimited tar), the conversation (turn items + covered run ordinals), attachments (original names, which the items reference), terminal scrollback (restored on first open like after a restart), workspace shape (worktree threads land in worktrees — reuse the branch's worktree or provision one, detached when git forbids attaching). A target that lacks the repository entirely clones it from the bundle — no remote, credentials, or network needed on the receiving machine.

How it moves

Manifest inline, large parts content-addressed and fetched by digest in resumable 4 MB chunks; the receiver rejects a chunk that does not continue the staged bytes and treats an exact re-send of already-staged bytes as a no-op, so interrupted uploads resume. The client brokers the copy — the only component authenticated to both environments — and only offers targets that are connected and advertise the capability. Arrivals go through the event sink, so the thread appears in every connected client's sidebar the moment it lands.

Lineage, not direction

Each hop records the previous hop in a lineage table; a return trip is an ordinary hop toward an environment already in the chain, and the receiver revives the prior thread pair even when the client no longer remembers it — one conversation, one sidebar row, wherever it currently runs. A caller-named return target is validated against that lineage before anything is applied. Provenance survives round trips: every arrival keeps a link recording where the thread came from. Lifecycle actions (delete, archive, rename) apply to the pair once.

Version skew

threadHandoff capability follows the threadSettlement contract: absent means the environment is not offered as a destination.

Verification

  • contracts 266 · client-runtime 621 · web 118 · server suites green (orchestration-v2, persistence, environment, ws, startup, terminal) · monorepo typecheck, lint, fmt clean.
  • New coverage: tip-classification table, ref-name sanitization, full dispatch-path depart/refuse/complete/abort with reason surfacing, payload ceilings, chunk windows, sidebar pair-visibility rules, migration idempotency and mid-apply recovery.
  • Live smoke: repeated MacBook ↔ Linux server transfers of real threads, including the failure modes found and fixed along the way (full-history bundle timeout, empty bundle on a fully pushed branch, missing dispatch routing, JSON codec gap on the handoff timestamp, arrivals invisible to connected clients, post-push navigation, pair dedup after round trips).
  • Code review: all Macroscope findings across the review rounds addressed and resolved, including the crash-recovery, payload-abuse, and single-live-side race classes.
  • #2829 — orchestration V2 (base of this stack; this PR targets its branch)
  • #5499 — session import on a sibling branch; claims a migration id in the same range as 047–049 here — whichever merges second renumbers
  • #5589 — worktree lifecycle management on orchestrator V2; touches the same worktree-provisioning surface the receive path uses
  • #5363 — the feature request this implements: one-click transfer of a provider-native session between T3 Connect environments
  • #5215 — rehoming a thread to another project: adjacent ask, not covered here (this PR moves threads between environments, within the same logical project)
  • #5003 / #4664 — other orchestration-V2 stacked work, listed for merge-ordering awareness

Migrations

047 (orchestration_v2_thread_handoffs lineage table), 048 (apply_cwd column for projection-independent crash recovery) and 049 (root_stash_ref/root_cwd so root and worktree stashes recover independently). 047 was renumbered from 046 after the base branch inserted a migration.

Note

Add thread handoff to move a running thread between devices

  • Introduces an end-to-end thread handoff system allowing a running thread to be transferred between execution environments (devices), preserving git state, conversation history, terminals, and attachments.
  • Adds OrchestrationV2HandoffBundleV1 manifest contract, typed part kinds (git-bundle, tracked-patch, untracked-tar, etc.), and versioned DB migrations (047–050) for the orchestration_v2_thread_handoffs table.
  • Exposes readHandoffPart/writeHandoffPart HTTP endpoints on the environment API with offset-validated, idempotent chunked transfer and a 4 MB chunk size.
  • Adds prepareThreadHandoff and receiveThreadHandoff WebSocket RPCs (requiring AuthOrchestrationOperateScope) handled in the server WS layer and wired into production startup with a handoff recovery phase.
  • The web UI gains a ThreadHandoffDialog for progress-tracked moves, a banner for threads running elsewhere (with pull-back and continue-here actions), and sidebar deduplication hiding the 'away' copy when the 'here' peer is visible.
  • The mobile UI gains a ThreadHandoffBanner to surface away threads and resume them locally.
  • Archiving, unarchiving, and deleting a thread now best-effort mirrors the operation to the handoff peer thread.
  • Risk: handoff recovery runs at server startup; interrupted handoffs from a prior session are automatically resumed, which may replay partial git or file operations.
Macroscope summarized 0250f02.
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro Plus

      Run ID: f38d45d4-abf4-498e-bf1f-f44233f84eeb

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review

      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. One finding on the new handoff error contract; the migration, its tests, and the bundle schemas otherwise follow the Effect conventions (subpath namespace imports, no service-instance injection, no ManagedRuntime/runPromise, no Layer.succeed shortcuts).

      Posted via Macroscope — Effect Service Conventions
    3. Effect service conventions review of the two new service modules. Three findings, all in apps/server/src/orchestration-v2/. Earlier feedback on OrchestrationV2HandoffError.message still stands and is not repeated here.

      Posted via Macroscope — Effect Service Conventions
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Same here: ThreadHandoffGitShape should be inlined into the Context.Service<ThreadHandoffGit, { ... }>() declaration, with the local implementation bindings annotated as ThreadHandoffGit["Service"]["resolveTip"] and so on, instead of exporting a separate shape type.

      Posted via Macroscope — Effect Service Conventions
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      orchestration-v2/ThreadHandoffService.ts:160

      handoffError only forwards its arguments into new OrchestrationV2HandoffError({ ... }), so it adds an indirection without normalization. Consider constructing the error directly at each failure boundary (the optional-field spreads are only needed for handoffId/cause, which each call site already knows) and keeping asHandoffError as the one mapper, since that one does real work by passing through an existing handoff error.

      No longer relevant as of 23af1e7f4701c1e7dd5d7fd0c2647b5c560659d3

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

      orchestration-v2/ThreadHandoffService.ts:115

      New service modules should define the service interface inline in the Context.Service declaration rather than keeping a standalone ThreadHandoffServiceShape. Consider moving this body into Context.Service<ThreadHandoffService, { ... }>() below and referring to members as ThreadHandoffService["Service"]["partPath"] etc. at the implementation sites (partPath, verifyStagedPart, prepare, receive, recoverInterrupted).

      No longer relevant as of 23af1e7f4701c1e7dd5d7fd0c2647b5c560659d3

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

      🟠 High

      https://github.com/pingdotgg/t3code/blob/4ad8e2776d89c4ccb62ec0f02221aece0a4c659c/packages/contracts/src/orchestrationV2.ts#L111

      JSON payloads with a non-null handoff fail to decode as OrchestrationV2AppThread because handoff.updatedAt is declared as Schema.DateTimeUtc (which expects a DateTime.Utc runtime value) instead of a string-decoding schema like Schema.DateTimeUtcFromString. When the JSON wire format provides an ISO string for that nested field, decoding rejects it. The top-level createdAt/updatedAt fields use Schema.DateTimeUtc and presumably work because OrchestrationV2AppThreadJson replaces them with Schema.DateTimeUtcFromString, but the nested handoff field is spread unchanged and retains the non-string-decoding schema. Consider using Schema.DateTimeUtcFromString (or the same pattern applied to the top-level timestamp fields) for OrchestrationV2ThreadHandoffLink.updatedAt so JSON payloads decode correctly.

      No longer relevant as of 77318f45788c76f593236ed2e8f977fee7caa998

    5. Bil0000(GitHub profile, opens in a new tab) changed the title

    6. 🟡 Medium

      https://github.com/pingdotgg/t3code/blob/84eb7fdfea03b91a89615274493af207e70345f7/apps/web/src/components/BranchToolbar.tsx#L407

      When layout === "panel", onMoveThread is never forwarded to BranchToolbarEnvironmentSelector — the panel branch returns at line 406, before the only forwarding site at line 472. As a result, a locked thread rendered in the thread-details panel cannot be moved to another environment even when the caller supplies onMoveThread: the environment selector collapses to a static label instead of offering move targets. The panel branch should forward onMoveThread to its own BranchToolbarEnvironmentSelector (or to the BranchToolbar that renders it), so the move-thread control stays interactive in the panel layout.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/web/src/components/BranchToolbar.tsx around line 407:
      
      When `layout === "panel"`, `onMoveThread` is never forwarded to `BranchToolbarEnvironmentSelector` — the panel branch returns at line 406, before the only forwarding site at line 472. As a result, a locked thread rendered in the thread-details panel cannot be moved to another environment even when the caller supplies `onMoveThread`: the environment selector collapses to a static label instead of offering move targets. The panel branch should forward `onMoveThread` to its own `BranchToolbarEnvironmentSelector` (or to the `BranchToolbar` that renders it), so the move-thread control stays interactive in the panel layout.
    7. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    8. Retained conventions issues in this PR's Effect service code.

      New finding this run:

      • apps/server/src/orchestration-v2/runtimeLayer.ts: the four new service-boundary imports alias layer, which erases the module namespace.

      Previously flagged and still present (not re-commented):

      • apps/server/src/orchestration-v2/ThreadHandoffService.ts: standalone ThreadHandoffServiceShape instead of an inline Context.Service interface, and the handoffError construction helper.
      • apps/server/src/orchestration-v2/ThreadHandoffGit.ts: standalone ThreadHandoffGitShape.
      • packages/contracts/src/orchestrationV2.ts: required free-form message on OrchestrationV2HandoffError duplicating its structural reason/handoffId.
      Posted via Macroscope — Effect Service Conventions
    9. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High

      https://github.com/pingdotgg/t3code/blob/242575b705b3a4644f0b76eabb8648a1d25197da/apps/web/src/components/ChatView.tsx#L1

      The environment picker for "Move thread to" includes disconnected environments and environments that lack thread-handoff support. Selecting either one opens the ThreadHandoffDialog, but threadHandoff.move requires a live target connection and server-side handoff capability, so the transfer always fails. logicalProjectEnvironments is built from every registered environment matching the logical project and is not filtered by connection state or by serverConfig.environment.capabilities.threadHandoff, and canMoveThread only checks logicalProjectEnvironments.length > 1. Consider filtering the destination list to connected environments whose server advertises handoff capability, and gating canMoveThread on that filtered set.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/web/src/components/ChatView.tsx around line 1:
      
      The environment picker for "Move thread to" includes disconnected environments and environments that lack thread-handoff support. Selecting either one opens the `ThreadHandoffDialog`, but `threadHandoff.move` requires a live target connection and server-side handoff capability, so the transfer always fails. `logicalProjectEnvironments` is built from every registered environment matching the logical project and is not filtered by connection state or by `serverConfig.environment.capabilities.threadHandoff`, and `canMoveThread` only checks `logicalProjectEnvironments.length > 1`. Consider filtering the destination list to connected environments whose server advertises handoff capability, and gating `canMoveThread` on that filtered set.
    10. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High

      https://github.com/pingdotgg/t3code/blob/8b221379ef6dedc653070aa2f1707202d718739d/apps/web/src/components/ChatView.tsx#L6111

      moveTargetEnvironmentId is not reset when the active thread changes. If the user opens the move dialog for thread A, then navigates to thread B before confirming, the dialog re-renders with thread B's serverThread and the stale moveTargetEnvironmentId. Pressing "Send thread" then moves thread B instead of the thread that originally opened the dialog. Consider resetting moveTargetEnvironmentId to null in the effect keyed on activeThread?.id.

      No longer relevant as of 47d31cf97732578873bbb1d34fbb046f7c343a98

    11. Effect service conventions: two new service-boundary import findings below. The findings from earlier runs on this PR are still present and unaddressed (standalone ThreadHandoffGitShape / ThreadHandoffServiceShape instead of an inline Context.Service interface, the pass-through handoffError helper, the alias imports in runtimeLayer.ts, and the required free-form message on OrchestrationV2HandoffError); they are not re-commented here.

      Posted via Macroscope — Effect Service Conventions
    12. Reviewed the new handoff service modules and their call sites against the Effect service conventions. One new finding below; the findings from earlier runs on this PR (standalone ThreadHandoffServiceShape / ThreadHandoffGitShape instead of inline Context.Service interfaces, service-boundary named/aliased imports in ThreadHandoffService.ts, ThreadHandoffGit.ts and runtimeLayer.ts, the pass-through handoffError helper, and the required free-form message on OrchestrationV2HandoffError) are unchanged at this head and are not re-posted.

      Posted via Macroscope — Effect Service Conventions
    13. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High

      https://github.com/pingdotgg/t3code/blob/823d4fb460e4f0c7b462012393c8b019ee3afbdf/apps/server/src/orchestration-v2/Orchestrator.ts#L1378

      A departed thread (where thread.handoff.presence === "away") is supposed to be read-only, but only dispatchMessage enforces this. Other mutations — notably thread.delete — still reach dispatchThreadMutation and tombstone the thread while the peer is live. When the conversation later returns, the arrival path (thread.handoff.complete) updates the handoff link but never clears deletedAt, so the returned thread remains deleted and unusable. Consider rejecting non-handoff mutations (at minimum thread.delete and thread.archive) while presence === "away", or clearing deletedAt/archivedAt in the arrival path.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Orchestrator.ts around line 1378:
      
      A departed thread (where `thread.handoff.presence === "away"`) is supposed to be read-only, but only `dispatchMessage` enforces this. Other mutations — notably `thread.delete` — still reach `dispatchThreadMutation` and tombstone the thread while the peer is live. When the conversation later returns, the arrival path (`thread.handoff.complete`) updates the handoff link but never clears `deletedAt`, so the returned thread remains deleted and unusable. Consider rejecting non-handoff mutations (at minimum `thread.delete` and `thread.archive`) while `presence === "away"`, or clearing `deletedAt`/`archivedAt` in the arrival path.
    14. Two service-shape conventions are still outstanding after the latest fixes. Previously reported findings that remain unchanged (the handoffError construction helper in ThreadHandoffService.ts and the required free-form message field on OrchestrationV2HandoffError in packages/contracts/src/orchestrationV2.ts) are not re-commented here.

      Posted via Macroscope — Effect Service Conventions
    15. Done — removed the exported ThreadHandoffGitShape alias; implementation bindings are annotated as ThreadHandoffGit["Service"]["…"].

    16. Sorry, I'm unable to act on this request because you do not have permissions within this repository.

    17. Fixed — the thread-details panel now renders its own BranchToolbarEnvironmentSelector with onMoveThread (and the provenance label) forwarded from ThreadDetailsPanel.tsx, so a locked thread can be moved from the panel.

    18. Sorry, I'm unable to act on this request because you do not have permissions within this repository.

Sign in to join this conversation.