Skip to content

Commit a7fcd16

Browse files
fix(orchestration): fork from a response a steer cut off
Active steering writes the steer into the same run as the response it interrupts, and a fork point was always a whole run. So a response a steer cut off never got a Fork button, and forking its run would have carried the steer and the reply to it into the fork. A fork can now end at one assistant response. `thread.fork` takes a `turn_item` source point (run plus item). The server checks that the item is a finished assistant message of that run and records the cut on the transfer and as `forkedFrom.throughTurnItemId`. The inherited timeline, the windowed history read, search and the shell item count all stop at that item. Provider context follows the cut. Claude forks natively: an assistant item's native id is the SDK message uuid, which `forkSession` accepts as an inclusive `upToMessageId`. A new optional `canForkFromItem` capability says so. Codex `thread/fork` only cuts at turn ends, so it and every provider without the capability get the portable handoff cut at the item, never the run end. Web and mobile show the response meta row and Fork on the last assistant message before each steer as well as the run's last one. Forks from a mid-run response send the item point; run-end forks still send the run point. A reply the user stopped mid-stream (interrupted) can be forked too, matching the server's existing run status rule. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 57b3780 commit a7fcd16

22 files changed

Lines changed: 758 additions & 40 deletions

File tree

‎apps/mobile/src/features/threads/ThreadFeed.tsx‎

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,7 @@ import {
161161
} from "@t3tools/mobile-markdown-text/links";
162162
import {
163163
failedFeedRunIds,
164+
terminalFeedAssistantMessageIds,
164165
deriveThreadFeedPresentation,
165166
threadFeedRunIsUnsettled,
166167
isContextCompactionActivityGroup,
@@ -321,6 +322,8 @@ function AssistantForkButton(props: {
321322
readonly environmentId: EnvironmentId;
322323
readonly iconColor: ColorValue;
323324
readonly projectedItem: OrchestrationV2ProjectedTurnItem;
325+
/** A later response in the run follows, so the fork cuts at this item. */
326+
readonly midRun: boolean;
324327
readonly sourceTitle: string;
325328
}) {
326329
const support = useV2ItemSupport({
@@ -354,6 +357,7 @@ function AssistantForkButton(props: {
354357
sourceThreadId: props.projectedItem.sourceThreadId,
355358
targetThreadId,
356359
runId,
360+
...(props.midRun ? { turnItemId: props.projectedItem.item.id } : {}),
357361
title: `${props.sourceTitle} fork`,
358362
creationSource: "mobile",
359363
},
@@ -1525,7 +1529,7 @@ function renderFeedEntry(
15251529
readonly expandedWorkRows: Record<string, boolean>;
15261530
readonly workRowSizing: ReturnType<typeof deriveThreadWorkLogSizing>;
15271531
readonly workGroupScrollPositions: Map<string, ThreadWorkGroupScrollPosition>;
1528-
readonly terminalAssistantMessageIds: ReadonlySet<string>;
1532+
readonly terminalAssistantMessageIds: ReturnType<typeof terminalFeedAssistantMessageIds>;
15291533
readonly unsettledTurnId: RunId | null;
15301534
readonly failedRunIds: ReadonlySet<RunId>;
15311535
readonly onCopyWorkRow: (rowId: string, value: string) => void;
@@ -1694,7 +1698,7 @@ function renderFeedEntry(
16941698
message.runId === props.unsettledTurnId;
16951699
const showAssistantMeta =
16961700
message.role === "assistant" &&
1697-
props.terminalAssistantMessageIds.has(message.id) &&
1701+
props.terminalAssistantMessageIds.terminalIds.has(message.id) &&
16981702
!assistantTurnStillInProgress &&
16991703
!message.streaming;
17001704

@@ -1966,6 +1970,7 @@ function renderFeedEntry(
19661970
environmentId={props.environmentId}
19671971
iconColor={iconSubtleColor}
19681972
projectedItem={message.projectedItem}
1973+
midRun={props.terminalAssistantMessageIds.midRunIds.has(message.id)}
19691974
sourceTitle={props.threadTitle}
19701975
/>
19711976
) : null}
@@ -2761,15 +2766,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
27612766
() => failedFeedRunIds(props.feed, props.latestRun),
27622767
[props.feed, props.latestRun],
27632768
);
2764-
const terminalAssistantMessageIds = useMemo(() => {
2765-
const terminalIdsByTurn = new Map<RunId, string>();
2766-
for (const entry of props.feed) {
2767-
if (entry.type === "message" && entry.message.role === "assistant" && entry.message.runId) {
2768-
terminalIdsByTurn.set(entry.message.runId, entry.message.id);
2769-
}
2770-
}
2771-
return new Set(terminalIdsByTurn.values());
2772-
}, [props.feed]);
2769+
const terminalAssistantMessageIds = useMemo(
2770+
() => terminalFeedAssistantMessageIds(props.feed),
2771+
[props.feed],
2772+
);
27732773
useEffect(() => {
27742774
const previous = previousLatestTurnRef.current;
27752775
previousLatestTurnRef.current = props.latestRun;

‎apps/mobile/src/lib/threadActivity.test.ts‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import {
3131
deriveThreadFeedPresentation,
3232
threadFeedActivityIsVisible,
3333
threadFeedRunIsUnsettled,
34+
terminalFeedAssistantMessageIds,
3435
type ThreadFeedActivity,
3536
type ThreadFeedEntry,
3637
togglePendingUserInputOptionSelection,
@@ -2028,6 +2029,56 @@ const multiSelectQuestion = {
20282029
multiSelect: true,
20292030
} as const;
20302031

2032+
describe("terminalFeedAssistantMessageIds", () => {
2033+
const runId = RunId.make("steered-run");
2034+
const message = (
2035+
id: string,
2036+
role: "user" | "assistant",
2037+
inputIntent?: "turn_start" | "steer",
2038+
): ThreadFeedEntry => ({
2039+
type: "message",
2040+
id,
2041+
createdAt: "2026-04-01T00:00:00.000Z",
2042+
message: {
2043+
id: MessageId.make(id),
2044+
role,
2045+
text: id,
2046+
attachments: [],
2047+
runId,
2048+
streaming: false,
2049+
...(inputIntent === undefined ? {} : { inputIntent }),
2050+
visibility: "local",
2051+
sourceThreadId: ThreadId.make("thread"),
2052+
createdAt: "2026-04-01T00:00:00.000Z",
2053+
updatedAt: "2026-04-01T00:00:00.000Z",
2054+
},
2055+
});
2056+
2057+
it("ends a response at each steer and marks only the cut-off one as mid-run", () => {
2058+
const ids = terminalFeedAssistantMessageIds([
2059+
message("prompt", "user", "turn_start"),
2060+
message("commentary", "assistant"),
2061+
message("cut-off", "assistant"),
2062+
message("steer", "user", "steer"),
2063+
message("final", "assistant"),
2064+
]);
2065+
2066+
expect([...ids.terminalIds]).toEqual(["cut-off", "final"]);
2067+
expect([...ids.midRunIds]).toEqual(["cut-off"]);
2068+
});
2069+
2070+
it("keeps one terminal message for an unsteered run", () => {
2071+
const ids = terminalFeedAssistantMessageIds([
2072+
message("prompt", "user", "turn_start"),
2073+
message("commentary", "assistant"),
2074+
message("final", "assistant"),
2075+
]);
2076+
2077+
expect([...ids.terminalIds]).toEqual(["final"]);
2078+
expect(ids.midRunIds.size).toBe(0);
2079+
});
2080+
});
2081+
20312082
describe("pending user input answers", () => {
20322083
it("preserves exact editor text, including a deliberately cleared answer", () => {
20332084
const question = { ...singleSelectQuestion, initialAnswer: " Proposed message\n" };

‎apps/mobile/src/lib/threadActivity.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1048,6 +1048,31 @@ export function failedFeedRunIds(
10481048
return failed;
10491049
}
10501050

1051+
/**
1052+
* The assistant messages that end a stretch of output and so carry metadata:
1053+
* each run's last one, plus the last one before a later user message in the
1054+
* same run (a steer). Forking from one in `midRunIds` must cut inside its run.
1055+
*/
1056+
export function terminalFeedAssistantMessageIds(feed: ReadonlyArray<ThreadFeedEntry>) {
1057+
const lastIdBySegment = new Map<string, string>();
1058+
const lastIdByRun = new Map<RunId, string>();
1059+
const segmentByRun = new Map<RunId, number>();
1060+
for (const entry of feed) {
1061+
if (entry.type !== "message" || !entry.message.runId) continue;
1062+
const runId = entry.message.runId;
1063+
if (entry.message.role === "user") {
1064+
segmentByRun.set(runId, (segmentByRun.get(runId) ?? 0) + 1);
1065+
continue;
1066+
}
1067+
lastIdByRun.set(runId, entry.message.id);
1068+
lastIdBySegment.set(`${runId}:${segmentByRun.get(runId) ?? 0}`, entry.message.id);
1069+
}
1070+
const terminalIds = new Set(lastIdBySegment.values());
1071+
const runEndIds = new Set(lastIdByRun.values());
1072+
const midRunIds = new Set([...terminalIds].filter((id) => !runEndIds.has(id)));
1073+
return { terminalIds, midRunIds };
1074+
}
1075+
10511076
/**
10521077
* A prompt without a run (a provider-native subagent, or a turn imported from
10531078
* V1) folds its response like a run. `runlessWorkActive` keeps the latest

‎apps/server/src/mcp/toolkits/thread/tools.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ const transferResult = Schema.Struct({ sequence: NonNegativeInt, targetThreadId:
203203
const ThreadForkTool = Tool.make("t3_thread_fork", {
204204
...commandTool,
205205
description:
206-
"Fork a thread from a stable run or checkpoint using the existing fork command. Omit threadId to fork this thread. The fork inherits the source configuration. Acceptance does not mean a provider turn has completed.",
206+
"Fork a thread from a stable run, a checkpoint, or one finished assistant response (turn_item, which leaves out the rest of its run such as a steer) using the existing fork command. Omit threadId to fork this thread. The fork inherits the source configuration. Acceptance does not mean a provider turn has completed.",
207207
parameters: Schema.Struct({
208208
threadId: Schema.optional(ThreadId),
209209
sourcePoint: OrchestrationV2ThreadForkSourcePoint,

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import {
2727
RunAttemptId,
2828
RunId,
2929
ThreadId,
30+
TurnItemId,
3031
} from "@t3tools/contracts";
3132
import { assert, describe, it } from "@effect/vitest";
3233
import * as Context from "effect/Context";
@@ -1759,6 +1760,43 @@ describe("ClaudeAdapterV2 native fork", () => {
17591760
assert.equal(forkedProviderThread.forkedFrom?.providerThreadId, sourceProviderThread.id);
17601761
assert.equal(forkedProviderThread.forkedFrom?.providerTurnId, providerTurnId);
17611762

1763+
// A response a steer cut off is mid-turn: its assistant item carries the
1764+
// SDK message uuid, which forkSession takes as an inclusive cut.
1765+
yield* runtime.forkThread({
1766+
sourceProviderThread,
1767+
sourceProviderTurns: [],
1768+
providerTurnId,
1769+
throughTurnItem: {
1770+
id: TurnItemId.make("turn-item-claude-cut-off"),
1771+
threadId: sourceThreadId,
1772+
runId: RunId.make("run-claude-steered"),
1773+
nodeId: null,
1774+
providerThreadId: sourceProviderThread.id,
1775+
providerTurnId,
1776+
nativeItemRef: {
1777+
driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
1778+
nativeId: "cut-off-assistant-uuid",
1779+
strength: "strong",
1780+
},
1781+
parentItemId: null,
1782+
ordinal: 2,
1783+
status: "completed",
1784+
title: null,
1785+
startedAt: now,
1786+
completedAt: now,
1787+
updatedAt: now,
1788+
type: "assistant_message",
1789+
messageId: MessageId.make("message-claude-cut-off"),
1790+
text: "cut off by a steer",
1791+
streaming: false,
1792+
},
1793+
targetThreadId: ThreadId.make("thread-claude-fork-steered-target"),
1794+
});
1795+
assert.deepEqual(forkCalls[1]?.options, {
1796+
dir: "/workspace",
1797+
upToMessageId: "cut-off-assistant-uuid",
1798+
});
1799+
17621800
yield* runtime.startTurn({
17631801
appThread: {
17641802
createdBy: "user",

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,7 @@ export const ClaudeProviderCapabilitiesV2 = {
196196
canRollbackThread: true,
197197
canForkThread: true,
198198
canForkFromTurn: true,
199+
canForkFromItem: true,
199200
canForkFromSubagentThread: false,
200201
exposesNativeThreadId: true,
201202
},
@@ -1226,6 +1227,25 @@ const getNativeConversationHeadId = Effect.fnUntraced(function* (
12261227

12271228
const resolveClaudeForkUpToMessageId = Effect.fn("ClaudeAdapterV2.resolveForkUpToMessageId")(
12281229
function* (input: ProviderAdapter.ProviderAdapterV2ForkThreadInput) {
1230+
// Assistant items carry the SDK message uuid, which forkSession accepts as
1231+
// an inclusive cut, so a fork can end before a steer in the same turn.
1232+
const throughItem = input.throughTurnItem;
1233+
if (throughItem !== undefined) {
1234+
const nativeId = throughItem.nativeItemRef?.nativeId;
1235+
if (
1236+
throughItem.type !== "assistant_message" ||
1237+
throughItem.nativeItemRef?.driver !== CLAUDE_PROVIDER ||
1238+
nativeId === undefined ||
1239+
nativeId === null
1240+
) {
1241+
return yield* new ProviderAdapter.ProviderAdapterForkThreadError({
1242+
driver: CLAUDE_PROVIDER,
1243+
providerThreadId: input.sourceProviderThread.id,
1244+
cause: `Cannot fork Claude thread at item ${throughItem.id}: it has no SDK assistant message id.`,
1245+
});
1246+
}
1247+
return nativeId;
1248+
}
12291249
if (input.providerTurnId === undefined || input.sourceProviderTurns === undefined) {
12301250
return undefined;
12311251
}

‎apps/server/src/orchestration-v2/CommandPolicy.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,7 @@ export interface CommandPolicyV2Shape {
197197
readonly ensureNativeFork: (
198198
input: CapabilityCheckInput & {
199199
readonly fromSpecificTurn: boolean;
200+
readonly fromSpecificItem?: boolean;
200201
},
201202
) => Effect.Effect<void, CommandPolicyV2Error>;
202203
readonly decideForkExecution: (
@@ -205,6 +206,8 @@ export interface CommandPolicyV2Shape {
205206
readonly hasStrongNativeSource: boolean;
206207
readonly sourceRunStatus: OrchestrationV2Run["status"];
207208
readonly fromSpecificTurn: boolean;
209+
/** The fork ends at a response inside the run, e.g. one a steer cut off. */
210+
readonly fromSpecificItem?: boolean;
208211
},
209212
) => Effect.Effect<ForkExecutionPolicyV2, CommandPolicyV2Error>;
210213
readonly ensureRollback: (
@@ -291,6 +294,11 @@ const ensureNativeFork: CommandPolicyV2Shape["ensureNativeFork"] = (input) => {
291294
),
292295
);
293296
}
297+
if (input.fromSpecificItem === true && input.capabilities.threads.canForkFromItem !== true) {
298+
return Effect.fail(
299+
unsupported(input, "fork_from_turn", "providerInstanceId cannot fork inside a turn"),
300+
);
301+
}
294302
if (input.capabilities.identity.nativeThreadIds !== "strong") {
295303
return Effect.fail(
296304
unsupported(
@@ -371,6 +379,8 @@ const decideForkExecution: CommandPolicyV2Shape["decideForkExecution"] = (input)
371379
input.hasStrongNativeSource &&
372380
input.capabilities.threads.canForkThread &&
373381
(!input.fromSpecificTurn || input.capabilities.threads.canForkFromTurn) &&
382+
// A native fork that can only cut at turn ends would keep a steer made after the response.
383+
(input.fromSpecificItem !== true || input.capabilities.threads.canForkFromItem === true) &&
374384
input.capabilities.identity.nativeThreadIds === "strong";
375385

376386
if (canForkNatively) {

0 commit comments

Comments
 (0)