Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat(threads): add agent-requested handoffs #7487

Closedmrmg(GitHub profile, opens in a new tab)wants to merge 1 commit intomain fromrefs/pull/7487/headopened View on GitHub

Summary

Adds a durable, agent-requested thread handoff lifecycle.

  • Exposes an in-thread MCP handoff request and settles it only after the requesting turn succeeds.
  • Adds user-confirmed Open/Dismiss handoff cards on web/desktop and mobile.
  • Creates linked, unstarted target drafts with inherited settings and an editable seeded composer prompt.
  • Migrates Plan → new-thread to the same handoff path.

Why

Agents can now prepare a new-thread continuation without creating or starting it themselves; users retain the final decision to open, edit, and send the target draft.

Validation

  • Scoped contracts, client-runtime, server, web, and mobile typechecks
  • 8 focused suites / 147 tests
  • git diff --check

Built with gpt-5.6-terra via Codex.

Note

Add agent-requested thread handoffs across server, client, and mobile

  • Introduces a full thread handoff lifecycle (request → available → accept/dismiss/cancel) via new orchestration commands, server-side decider logic, and contract schemas in packages/contracts/src/orchestration.ts.
  • Adds a request_thread_handoff MCP tool so AI providers can programmatically hand off to a new thread with a title, prompt, and artifact references.
  • On turn completion or abortion, ProviderRuntimeIngestion detects pending handoffs and dispatches thread.handoff.turn-settle to resolve them.
  • Web ChatView and mobile ThreadRouteScreen surface available handoffs as cards with Open/Dismiss actions and auto-seed the composer prompt when a handoff is accepted.
  • Composer drafts on both web and mobile now persist seededHandoffIds so a cleared handoff prompt is not reinserted on reload.
📊 Macroscope summarized d8fac27. 19 files reviewed, 0 issues evaluated, 0 issues filtered, 0 comments posted

🗂️ Filtered Issues

No issues evaluated.

    1. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    2. 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: 88d6270c-7c6d-449c-9fd7-cedc140b0160

      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.
    3. One consistency finding in the new web handoff card: the action controls re-create the shared Button primitive as raw <button> elements and lose its interaction/accessibility behavior. Details inline.

      Posted via Macroscope — UI Consistency
      @@ -0,0 +20,21 @@
      20+ <p className="truncate text-xs text-muted-foreground">
      21+ {handoff.artifactReferences.join(" · ")}
      22+ </p>
      23+ ) : null}
      24+ </div>
      25+ <button
      26+ type="button"
      27+ disabled={busy}
      28+ onClick={onOpen}
      29+ className="rounded-md bg-primary px-2.5 py-1.5 font-medium text-primary-foreground disabled:opacity-50"
      30+ >
      31+ Open {handoff.title} thread
      32+ </button>
      33+ <button
      34+ type="button"
      35+ disabled={busy}
      36+ onClick={onDismiss}
      37+ className="rounded-md px-2.5 py-1.5 text-muted-foreground hover:bg-muted disabled:opacity-50"
      38+ >
      39+ Dismiss
      40+ </button>
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      These two raw <button> elements reconstruct the shared Button primitive (~/components/ui/button) and drop behavior it owns: cursor-pointer, the focus-visible:ring-2 ring-ring ring-offset-* ring, disabled:pointer-events-none (currently only opacity changes, so a busy button still receives hover/click), the rounded-[var(--control-radius)] token instead of a hard-coded rounded-md, the primary variant's border/inset-shadow and pressed states, and the pointer-coarse 44px minimum hit target. The sibling banner in the same stack (ThreadErrorBanner) composes Alert + Button for exactly this reason.

      Suggest using the primitive with its sm size and ghost variant, and adding import { Button } from "../ui/button"; at the top of the file (Button already defaults type="button"):

      Suggested change
      25- <button
      26- type="button"
      27- disabled={busy}
      28- onClick={onOpen}
      29- className="rounded-md bg-primary px-2.5 py-1.5 font-medium text-primary-foreground disabled:opacity-50"
      30- >
      31- Open {handoff.title} thread
      32- </button>
      33- <button
      34- type="button"
      35- disabled={busy}
      36- onClick={onDismiss}
      37- className="rounded-md px-2.5 py-1.5 text-muted-foreground hover:bg-muted disabled:opacity-50"
      38- >
      39- Dismiss
      40- </button>
      25+ <Button size="sm" disabled={busy} onClick={onOpen}>
      26+ Open {handoff.title} thread
      27+ </Button>
      28+ <Button size="sm" variant="ghost" disabled={busy} onClick={onDismiss}>
      29+ Dismiss
      30+ </Button>
      Posted via Macroscope — UI Consistency
    4. Reviewed the new Effect-facing code (MCP handoff toolkit, orchestration decider/handoff helpers, client-runtime commands) against the service conventions. Service acquisition, layer wiring, and effect/* subpath namespace imports look correct; the findings below are about how the new MCP tool failure is modeled.

      Posted via Macroscope — Effect Service Conventions
      @@ -0,0 +1,20 @@
      1+import { ThreadHandoffId, TrimmedNonEmptyString } from "@t3tools/contracts";
      2+import * as Crypto from "effect/Crypto";
      3+import * as Effect from "effect/Effect";
      4+import * as Schema from "effect/Schema";
      5+import { Tool, Toolkit } from "effect/unstable/ai";
      6+
      7+import * as McpInvocationContext from "../../McpInvocationContext.ts";
      8+import { OrchestrationEngineService } from "../../../orchestration/Services/OrchestrationEngine.ts";
      9+
      10+export const RequestThreadHandoffInput = Schema.Struct({
      11+ title: TrimmedNonEmptyString,
      12+ prompt: TrimmedNonEmptyString,
      13+ artifactReferences: Schema.Array(TrimmedNonEmptyString).pipe(
      14+ Schema.withDecodingDefault(Effect.succeed([])),
      15+ ),
      16+});
      17+
      18+export const ThreadHandoffToolFailure = Schema.Struct({
      19+ message: Schema.String,
      20+});
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      The tool failure is an unstructured { message: string } struct, which stores the message as the only data. Consider a Schema.TaggedErrorClass with stable structural attributes plus a cause, deriving message from those attributes (the sibling preview toolkit already uses tagged PreviewAutomationError classes for failure).

      -export const ThreadHandoffToolFailure = Schema.Struct({
      -  message: Schema.String,
      -});
      +export class ThreadHandoffToolError extends Schema.TaggedErrorClass<ThreadHandoffToolError>()(
      +  "ThreadHandoffToolError",
      +  {
      +    threadId: ThreadId,
      +    handoffId: ThreadHandoffId,
      +    cause: Schema.Defect(),
      +  },
      +) {
      +  override get message(): string {
      +    return `Unable to request a thread handoff for thread ${this.threadId}.`;
      +  }
      +}

      This also needs ThreadId added to the @t3tools/contracts import and failure: ThreadHandoffToolError on the tool.

      Posted via Macroscope — Effect Service Conventions
      @@ -0,0 +1,8 @@
      1+import { ThreadHandoffId, TrimmedNonEmptyString } from "@t3tools/contracts";
      2+import * as Crypto from "effect/Crypto";
      3+import * as Effect from "effect/Effect";
      4+import * as Schema from "effect/Schema";
      5+import { Tool, Toolkit } from "effect/unstable/ai";
      6+
      7+import * as McpInvocationContext from "../../McpInvocationContext.ts";
      8+import { OrchestrationEngineService } from "../../../orchestration/Services/OrchestrationEngine.ts";
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      At this service boundary the local service module is imported by named tag instead of as a namespace (same in handlers.ts and tools.test.ts). Suggest matching the adjacent McpInvocationContext/PreviewAutomationBroker style so the module shape stays visible:

      Suggested change
      7-import * as McpInvocationContext from "../../McpInvocationContext.ts";
      8-import { OrchestrationEngineService } from "../../../orchestration/Services/OrchestrationEngine.ts";
      7+import * as McpInvocationContext from "../../McpInvocationContext.ts";
      8+import * as OrchestrationEngine from "../../../orchestration/Services/OrchestrationEngine.ts";

      References then become OrchestrationEngine.OrchestrationEngineService.

      Posted via Macroscope — Effect Service Conventions
      @@ -0,0 +18,21 @@
      18+ const createdAt = yield* DateTime.now.pipe(Effect.map(DateTime.formatIso));
      19+ yield* orchestrationEngine.dispatch({
      20+ type: "thread.handoff.request",
      21+ commandId: CommandId.make(requestId),
      22+ threadId: invocation.threadId,
      23+ handoffId: ThreadHandoffId.make(handoffId),
      24+ title: input.title,
      25+ prompt: input.prompt,
      26+ artifactReferences: input.artifactReferences,
      27+ createdAt,
      28+ });
      29+ return { handoffId: ThreadHandoffId.make(handoffId) };
      30+ },
      31+);
      32+
      33+export const ThreadHandoffToolkitHandlersLive = ThreadHandoffToolkit.toLayer({
      34+ request_thread_handoff: (input) =>
      35+ requestThreadHandoff(input).pipe(
      36+ Effect.mapError((error) => ({
      37+ message: error instanceof Error ? error.message : "Unable to request a thread handoff.",
      38+ })),
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      mapError erases the structured OrchestrationDispatchError into a string and derives the wrapper message from cause.message, dropping the cause chain. Consider constructing a tagged error at the failure boundary (the dispatch call) so threadId/handoffId and the original error survive:

      -    yield* orchestrationEngine.dispatch({
      +    yield* orchestrationEngine.dispatch({
             type: "thread.handoff.request",
             ...
      -    });
      +    }).pipe(
      +      Effect.mapError(
      +        (cause) =>
      +          new ThreadHandoffToolError({
      +            threadId: invocation.threadId,
      +            handoffId: ThreadHandoffId.make(handoffId),
      +            cause,
      +          }),
      +      ),
      +    );

      The toolkit entry can then be request_thread_handoff: (input) => requestThreadHandoff(input) with no message stringification.

      Posted via Macroscope — Effect Service Conventions
    5. @@ -5740,16 +5763,10 @@
      5740- titleSeed: nextThreadTitle,
      5741- runtimeMode,
      5742- interactionMode: "default",
      5743- sourceProposedPlan: {
      5744- threadId: activeThread.id,
      5745- planId: activeProposedPlan.id,
      5746- },
      5747- createdAt,
      5763+ threadId: activeThread.id,
      5764+ handoffId,
      5765+ targetThreadId: nextThreadId,
      57485766 },
      57495767 });
      5750- failure = startResult._tag === "Failure" ? startResult : null;
      5768+ failure = acceptResult._tag === "Failure" ? acceptResult : null;
      57515769 }
      57525770
      57535771 if (failure === null) {
      5754- const startedResult = await settlePromise(() =>
      5755- waitForStartedServerThread(scopeThreadRef(activeThread.environmentId, nextThreadId)),
      5772+ seedHandoffPrompt(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High components/ChatView.tsx:5772

      The Plan → new-thread flow leaves the target draft in plan mode, so sending the seeded PLEASE IMPLEMENT THIS PLAN prompt starts another planning turn instead of implementing the plan. acceptThreadHandoff inherits the source thread's mode, and this path only seeds the prompt; set the target draft's interaction mode to default before navigating.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/web/src/components/ChatView.tsx around line 5772:
      
      The Plan → new-thread flow leaves the target draft in `plan` mode, so sending the seeded `PLEASE IMPLEMENT THIS PLAN` prompt starts another planning turn instead of implementing the plan. `acceptThreadHandoff` inherits the source thread's mode, and this path only seeds the prompt; set the target draft's interaction mode to `default` before navigating.
      @@ -5716,14 +5748,13 @@
      57165748 title: nextThreadTitle,
      5717- modelSelection: nextThreadModelSelection,
      5718- runtimeMode,
      5719- interactionMode: "default",
      5720- branch: activeThreadBranch,
      5721- worktreePath: activeThread.worktreePath,
      5722- createdAt,
      5749+ prompt: outgoingImplementationPrompt,
      5750+ artifactReferences: [],
      5751+ ...(activeProposedPlan.turnId
      5752+ ? { requestingTurnId: activeProposedPlan.turnId, availableImmediately: true as const }
      5753+ : {}),
      57235754 },
      57245755 });
      57255756 let failure: AtomCommandResult<unknown, unknown> | null =
      5726- createResult._tag === "Failure" ? createResult : null;
      5757+ requestResult._tag === "Failure" ? requestResult : null;
      57275758
      57285759 if (failure === null) {
      5729- const startResult = await startThreadTurn({
      5760+ const acceptResult = await acceptThreadHandoff({
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium components/ChatView.tsx:5760

      onImplementPlanInNewThread creates the target through acceptThreadHandoff, so the new thread inherits the source thread’s persisted runtimeMode and ignores the composer’s current mode. A user who switches supervision or access mode before opening the implementation thread therefore gets the wrong permission mode; carry runtimeMode through the handoff or apply it to the target before navigation.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/web/src/components/ChatView.tsx around line 5760:
      
      `onImplementPlanInNewThread` creates the target through `acceptThreadHandoff`, so the new thread inherits the source thread’s persisted `runtimeMode` and ignores the composer’s current mode. A user who switches supervision or access mode before opening the implementation thread therefore gets the wrong permission mode; carry `runtimeMode` through the handoff or apply it to the target before navigation.
      @@ -5716,14 +5748,13 @@
      57165748 title: nextThreadTitle,
      5717- modelSelection: nextThreadModelSelection,
      5718- runtimeMode,
      5719- interactionMode: "default",
      5720- branch: activeThreadBranch,
      5721- worktreePath: activeThread.worktreePath,
      5722- createdAt,
      5749+ prompt: outgoingImplementationPrompt,
      5750+ artifactReferences: [],
      5751+ ...(activeProposedPlan.turnId
      5752+ ? { requestingTurnId: activeProposedPlan.turnId, availableImmediately: true as const }
      5753+ : {}),
      57235754 },
      57245755 });
      57255756 let failure: AtomCommandResult<unknown, unknown> | null =
      5726- createResult._tag === "Failure" ? createResult : null;
      5757+ requestResult._tag === "Failure" ? requestResult : null;
      57275758
      57285759 if (failure === null) {
      5729- const startResult = await startThreadTurn({
      5760+ const acceptResult = await acceptThreadHandoff({
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium components/ChatView.tsx:5760

      Choosing “implement in new thread” drops the composer’s current sendCtx.selectedModelSelection, so the accepted target is created with the source thread’s persisted model/provider instead of the user’s latest selection. This also means outgoingImplementationPrompt may be formatted for a different provider than the target uses; pass the current model selection through the handoff creation/accept path.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/web/src/components/ChatView.tsx around line 5760:
      
      Choosing “implement in new thread” drops the composer’s current `sendCtx.selectedModelSelection`, so the accepted target is created with the source thread’s persisted model/provider instead of the user’s latest selection. This also means `outgoingImplementationPrompt` may be formatted for a different provider than the target uses; pass the current model selection through the handoff creation/accept path.
      @@ -0,0 +1,18 @@
      1+import type { ThreadHandoff } from "@t3tools/contracts";
      2+import { Pressable, View } from "react-native";
      3+
      4+import { AppText as Text } from "../../components/AppText";
      5+import { presentThreadHandoff } from "./thread-handoff-presentation";
      6+
      7+export function ThreadHandoffCard(props: {
      8+ readonly handoff: ThreadHandoff;
      9+ readonly busy?: boolean;
      10+ readonly onOpen: () => void;
      11+ readonly onDismiss: () => void;
      12+}) {
      13+ const { handoff, busy = false, onOpen, onDismiss } = props;
      14+ const presentation = presentThreadHandoff(handoff);
      15+ return (
      16+ <View
      17+ accessibilityLabel={presentation.accessibilityLabel}
      18+ className="absolute left-3 right-3 top-2 z-20 rounded-2xl border border-border bg-surface px-3 py-2 shadow-sm"
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium threads/ThreadHandoffCard.tsx:18

      When availableHandoffs contains multiple items, only the topmost ThreadHandoffCard is usable; every card renders at the same absolute left-3 right-3 top-2 position, so earlier handoffs and their Open/Dismiss controls are covered. Render a single handoff or give the mapped cards a non-overlapping layout.

      Also found in 1 other location(s)

      apps/mobile/src/features/threads/ThreadDetailScreen.tsx:590

      Every ThreadHandoffCard rendered by this map uses the same absolute left-3 right-3 top-2 position. When availableHandoffs contains more than one item, the cards stack directly on top of each other, hiding the earlier handoffs and making their Open/Dismiss controls inaccessible. Render only one card or give the collection a non-overlapping layout.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/mobile/src/features/threads/ThreadHandoffCard.tsx around line 18:
      
      When `availableHandoffs` contains multiple items, only the topmost `ThreadHandoffCard` is usable; every card renders at the same absolute `left-3 right-3 top-2` position, so earlier handoffs and their Open/Dismiss controls are covered. Render a single handoff or give the mapped cards a non-overlapping layout.
      
      Also found in 1 other location(s):
      - apps/mobile/src/features/threads/ThreadDetailScreen.tsx:590 -- Every `ThreadHandoffCard` rendered by this map uses the same absolute `left-3 right-3 top-2` position. When `availableHandoffs` contains more than one item, the cards stack directly on top of each other, hiding the earlier handoffs and making their Open/Dismiss controls inaccessible. Render only one card or give the collection a non-overlapping layout.
      
      @@ -1162,3 +1231,10 @@
      11621231 };
      11631232 }
      11641233
      1234+ case "thread.handoff.request": {
      1235+ const thread = yield* requireThreadNotArchived({
      1236+ readModel,
      1237+ command,
      1238+ threadId: command.threadId,
      1239+ });
      1240+ const requestingTurnId = command.requestingTurnId ?? thread.session?.activeTurnId;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration/decider.ts:1240

      A client can bind thread.handoff.request to an old or arbitrary requestingTurnId, leaving the durable handoff permanently pending when that turn's completion has already been ingested and no future thread.handoff.turn-settle can resolve it. Reject an explicitly supplied ID unless it matches the current active turn, while retaining the completed-turn exception for availableImmediately requests.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration/decider.ts around line 1240:
      
      A client can bind `thread.handoff.request` to an old or arbitrary `requestingTurnId`, leaving the durable handoff permanently `pending` when that turn's completion has already been ingested and no future `thread.handoff.turn-settle` can resolve it. Reject an explicitly supplied ID unless it matches the current active turn, while retaining the completed-turn exception for `availableImmediately` requests.
      @@ -496,3 +519,6 @@
      496519 },
      497520 });
      498521 }, [interruptThreadTurn, selectedThread]);
      522+ const handleOpenHandoff = useCallback(
      523+ async (handoff: ReturnType<typeof findThreadHandoffs>[number]) => {
      524+ if (!selectedThread || handoffActionId !== null) {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium threads/ThreadRouteScreen.tsx:524

      Two rapid Open/Dismiss presses both observe handoffActionId === null before React commits the state update, so they dispatch concurrent handoff commands; duplicate Open presses can create different target threads, while Open/Dismiss can race and produce a spurious failure or navigation. Use a synchronously updated ref/lock before awaiting either command.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/mobile/src/features/threads/ThreadRouteScreen.tsx around line 524:
      
      Two rapid Open/Dismiss presses both observe `handoffActionId === null` before React commits the state update, so they dispatch concurrent handoff commands; duplicate Open presses can create different target threads, while Open/Dismiss can race and produce a spurious failure or navigation. Use a synchronously updated ref/lock before awaiting either command.
    6. Note

      🤖 GPT-5.6 Sol responding on behalf of Theo

      Closing this PR after an automated pass over open pull requests. Adds an unsolicited product feature or cross-system architecture change that exceeds the contribution policy.

Sign in to join this conversation.