@devries-cameron20 / t3code Mirror · read-only / commits / 5ee7f6fee8
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 23:30 UTC

fix(chat): show late async answers in their own runs (#23249)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Nov 11, 2026 at 11:18 UTC 5ee7f6fee8d1c52c17eb4abb6eec58985a1ae0fd
6 files changed +201 -14
apps/mobile/src/lib/threadActivity.test.ts
+42
@@ -393,6 +393,48 @@ describe("buildThreadFeed", () => {
393 expect(buildThreadFeed([projected(reply, 0)])[0]?.type).toBe("message");
394 });
395
396 + it.each([false, true])(
397 + "shows an async answer that started a later run where that run begins (cache: %s)",
398 + (cached) => {
399 + const requestId = RuntimeRequestId.make("late-question");
400 + const inRun = (item: OrchestrationV2TurnItem, run: string, position: number) =>
401 + projected({ ...item, runId: RunId.make(run) }, position);
402 + const message = (id: string, role: "user" | "assistant"): OrchestrationV2TurnItem => ({
403 + ...(role === "user" ? userMessage() : assistantMessage()),
404 + id: TurnItemId.make(id),
405 + messageId: MessageId.make(id),
406 + });
407 + const answerMessageId = `async-answer:${requestId}`;
408 + const settledPrefix = [
409 + inRun(
410 + {
411 + ...base("late-question", "2026-06-20T00:00:01.000Z", 0),
412 + type: "user_input_request",
413 + requestId,
414 + questions: [],
415 + questionAnswer: { requestId, answers: { color: "Blue" }, attachmentsByQuestionId: {} },
416 + },
417 + "run-8",
418 + 0,
419 + ),
420 + inRun(message("queued", "user"), "run-9", 1),
421 + inRun(message("reply-9", "assistant"), "run-9", 2),
422 + ];
423 + const rows = [
424 + ...settledPrefix,
425 + inRun(message(answerMessageId, "user"), "run-10", 3),
426 + inRun(message("reply-10", "assistant"), "run-10", 4),
427 + ];
428 + const cache = cached ? createThreadFeedCache() : undefined;
429 + if (cache) buildThreadFeed(settledPrefix, { cache });
430 + expect(
431 + buildThreadFeed(rows, { cache }).flatMap((entry) =>
432 + entry.type === "message" ? [entry.id] : [],
433 + ),
434 + ).toEqual(["queued", "reply-9", answerMessageId, "reply-10"]);
435 + },
436 + );
437 +
438 it.each([false, true])(
439 "keeps answered questions outside settled work (attachments only: %s)",
440 (attachmentsOnly) => {
apps/mobile/src/lib/threadActivity.ts
+20 -7
@@ -2114,7 +2114,7 @@ interface ThreadFeedBuild {
2114 readonly attempts: ReadonlyArray<OrchestrationV2RunAttempt> | undefined;
2115 readonly nodes: ReadonlyArray<OrchestrationV2ExecutionNode> | undefined;
2116 readonly checkpointSummaries: ReadonlyArray<ThreadCheckpointSummary> | undefined;
2117 - readonly foldedAnswerMessageIds: ReadonlySet<string>;
2117 + readonly foldedAnswerRunIdByMessageId: ReadonlyMap<string, RunId | null>;
2118 readonly delegatedChildrenByRun: ReadonlyMap<RunId, ReadonlySet<string>>;
2119 readonly feed: ReadonlyArray<ThreadFeedEntry>;
2120 /** Grouping is empty before `row`: the rows before it produced `feed.slice(0, feedLength)`. */
@@ -2164,6 +2164,14 @@ function checkpointSummariesEqual(
2164 });
2165 }
2166
2167 +function mapsEqual<K, V>(left: ReadonlyMap<K, V>, right: ReadonlyMap<K, V>): boolean {
2168 + if (left.size !== right.size) return false;
2169 + for (const [key, value] of left) {
2170 + if (!right.has(key) || right.get(key) !== value) return false;
2171 + }
2172 + return true;
2173 +}
2174 +
2175 function setMapsEqual<K, V>(
2176 left: ReadonlyMap<K, ReadonlySet<V>>,
2177 right: ReadonlyMap<K, ReadonlySet<V>>,
@@ -2217,11 +2225,12 @@ export function buildThreadFeed(
2225 };
2226 // Thread-wide facts that change rows anywhere in the feed. A cached prefix
2227 // is reused only while these match the build that produced it.
2220 - const foldedAnswerMessageIds = new Set<string>();
2228 + // An answer that started a later run stays a normal message at that run's position.
2229 + const foldedAnswerRunIdByMessageId = new Map<string, RunId | null>();
2230 const delegatedChildrenByRun = new Map<RunId, Set<string>>();
2231 for (const { item } of visibleTurnItems) {
2232 if (item.type === "user_input_request" && item.questionAnswer) {
2224 - foldedAnswerMessageIds.add(`async-answer:${item.questionAnswer.requestId}`);
2233 + foldedAnswerRunIdByMessageId.set(`async-answer:${item.questionAnswer.requestId}`, item.runId);
2234 } else if (item.type === "subagent" && item.origin === "app_owned" && item.runId !== null) {
2235 const children = delegatedChildrenByRun.get(item.runId) ?? new Set<string>();
2236 children.add(item.subagentId);
@@ -2238,7 +2247,7 @@ export function buildThreadFeed(
2247 previous.attempts === options?.attempts &&
2248 previous.nodes === options?.nodes &&
2249 checkpointSummariesEqual(previous.checkpointSummaries, options?.checkpointSummaries) &&
2241 - setsEqual(previous.foldedAnswerMessageIds, foldedAnswerMessageIds) &&
2250 + mapsEqual(previous.foldedAnswerRunIdByMessageId, foldedAnswerRunIdByMessageId) &&
2251 setMapsEqual(previous.delegatedChildrenByRun, delegatedChildrenByRun)
2252 ) {
2253 const firstChanged = firstChangedIndex(previous.rows, visibleTurnItems);
@@ -2276,7 +2285,11 @@ export function buildThreadFeed(
2285 item.status === "pending"
2286 )
2287 continue;
2279 - if (item.type === "user_message" && foldedAnswerMessageIds.has(item.messageId)) continue;
2288 + if (
2289 + item.type === "user_message" &&
2290 + foldedAnswerRunIdByMessageId.get(item.messageId) === item.runId
2291 + )
2292 + continue;
2293 if (
2294 item.type === "run_interrupt_request" ||
2295 (item.type === "run_interrupt_result" &&
@@ -2377,7 +2390,7 @@ export function buildThreadFeed(
2390 entryRows.push(index);
2391 }
2392 const retainedMessageIds = new Set([
2380 - ...foldedAnswerMessageIds,
2393 + ...foldedAnswerRunIdByMessageId.keys(),
2394 ...entries.flatMap((entry) => (entry.type === "message" ? [entry.id] : [])),
2395 ]);
2396 const appendLocalMessage = (message: LocalThreadMessage): RawThreadFeedEntry => {
@@ -2446,7 +2459,7 @@ export function buildThreadFeed(
2459 attempts: options?.attempts,
2460 nodes: options?.nodes,
2461 checkpointSummaries: options?.checkpointSummaries,
2449 - foldedAnswerMessageIds,
2462 + foldedAnswerRunIdByMessageId,
2463 delegatedChildrenByRun,
2464 feed,
2465 restarts,
apps/server/src/orchestration-v2/ThreadFind.test.ts
+44
@@ -563,6 +563,50 @@ describe("V2 thread find", () => {
563 }).pipe(Effect.provide(layerTest)),
564 );
565
566 + it.effect("finds an async answer that started a later run", () =>
567 + Effect.gen(function* () {
568 + yield* createProject(projectId);
569 + const projection = yield* ProjectionStore.ProjectionStoreV2;
570 + const queuedRun = RunId.make("run:queued");
571 + const answerRun = RunId.make("run:answer");
572 + yield* commit([
573 + thread(threadId, projectId),
574 + run(),
575 + run(threadId, queuedRun, 2),
576 + run(threadId, answerRun, 3),
577 + ]);
578 + const requestId = RuntimeRequestId.make("late");
579 + const question: OrchestrationV2TurnItem = {
580 + ...item("question", 1, ""),
581 + type: "user_input_request",
582 + requestId,
583 + questions: [],
584 + questionAnswer: { requestId, answers: {}, attachmentsByQuestionId: {} },
585 + };
586 + const items = [
587 + question,
588 + { ...item("queued", 2, "queued follow-up", "user_message"), runId: queuedRun },
589 + { ...item(`async-answer:${requestId}`, 3, "needle", "user_message"), runId: answerRun },
590 + ];
591 + yield* commit(
592 + items.map((payload) => ({
593 + id: EventId.make(`${payload.id}:initial`),
594 + threadId,
595 + occurredAt: at(1),
596 + type: "turn-item.updated" as const,
597 + payload,
598 + })),
599 + );
600 + const result = yield* projection.searchThread({ threadId, query: "needle" });
601 + assert.equal(result.totalMatches, 1);
602 + assert.deepEqual(result.match, {
603 + entryId: `async-answer:${requestId}`,
604 + runId: answerRun,
605 + occurrence: 0,
606 + });
607 + }).pipe(Effect.provide(layerTest)),
608 + );
609 +
610 it.effect(
611 "searches inherited fork history through the fork boundary, using source item identities",
612 () =>
apps/server/src/orchestration-v2/ThreadFind.ts
+7 -3
@@ -32,6 +32,7 @@ interface FindRow {
32 interface FindPayload extends FindRow {
33 readonly payload: string;
34 readonly entryId: string;
35 + readonly runId: OrchestrationV2TurnItem["runId"];
36 readonly type: OrchestrationV2TurnItem["type"];
37 }
38 interface FindDocument extends FindRow {
@@ -213,10 +214,12 @@ export const makeThreadFind = Effect.fn("makeThreadFind")(function* (
214 turn_item_id: string;
215 payload_json: string;
216 entry_id: string;
217 + run_id: OrchestrationV2TurnItem["runId"];
218 item_type: OrchestrationV2TurnItem["type"];
219 }>`
220 SELECT item.thread_id, item.turn_item_id, item.payload_json,
221 COALESCE(json_extract(item.payload_json, '$.messageId'), item.turn_item_id) AS entry_id,
222 + json_extract(item.payload_json, '$.runId') AS run_id,
223 json_extract(item.payload_json, '$.type') AS item_type
224 FROM orchestration_v2_projection_turn_items AS item
225 JOIN json_each(${sources}) AS wanted
@@ -237,6 +240,7 @@ export const makeThreadFind = Effect.fn("makeThreadFind")(function* (
240 ...row,
241 payload: payload.payload_json,
242 entryId: payload.entry_id,
243 + runId: payload.run_id,
244 type: payload.item_type,
245 });
246 });
@@ -343,17 +347,17 @@ export const makeThreadFind = Effect.fn("makeThreadFind")(function* (
347 ),
348 );
349 // Answers rendered inside question cards must not appear as separate matches.
346 - const foldedAnswers = new Set<string>();
350 + const foldedAnswerRunIds = new Map<string, OrchestrationV2TurnItem["runId"]>();
351 for (const payload of payloads) {
352 if (payload.type !== "user_input_request") continue;
353 const { item } = yield* decode(payload);
354 if (item.type === "user_input_request" && item.questionAnswer)
351 - foldedAnswers.add(`async-answer:${item.questionAnswer.requestId}`);
355 + foldedAnswerRunIds.set(`async-answer:${item.questionAnswer.requestId}`, item.runId);
356 }
357 const rows = payloads.filter(
358 (row) =>
359 row.type !== "user_input_request" &&
356 - !(row.type === "user_message" && foldedAnswers.has(row.entryId)),
360 + !(row.type === "user_message" && foldedAnswerRunIds.get(row.entryId) === row.runId),
361 );
362 const documents = new Map<number, FindDocument>();
363 const count = Effect.fnUntraced(function* (row: FindPayload) {
apps/web/src/session-logic.test.ts
+76
@@ -1123,6 +1123,82 @@ describe("native provider presentation in the v2 timeline", () => {
1123 ).toBe("message");
1124 });
1125
1126 + it("shows a late async answer that started a later run where that run begins", () => {
1127 + const requestId = RuntimeRequestId.make("late-question");
1128 + const inRun = (item: OrchestrationV2TurnItem, runId: string, ordinal: number) =>
1129 + visible({ ...item, runId: RunId.make(runId), ordinal });
1130 + const userMessage = (
1131 + id: string,
1132 + text: string,
1133 + ): Extract<OrchestrationV2TurnItem, { type: "user_message" }> => ({
1134 + ...base,
1135 + id: TurnItemId.make(id),
1136 + type: "user_message",
1137 + messageId: MessageId.make(id),
1138 + inputIntent: "queued_turn",
1139 + text,
1140 + createdBy: "user",
1141 + creationSource: "web",
1142 + attachments: [],
1143 + });
1144 + const assistantMessage = (id: string, text: string): OrchestrationV2TurnItem => ({
1145 + ...base,
1146 + id: TurnItemId.make(id),
1147 + type: "assistant_message",
1148 + messageId: MessageId.make(id),
1149 + text,
1150 + streaming: false,
1151 + });
1152 + const question = inRun(
1153 + {
1154 + ...base,
1155 + id: TurnItemId.make("late-question"),
1156 + type: "user_input_request",
1157 + requestId,
1158 + questions: [],
1159 + questionAnswer: { requestId, answers: { color: "Blue" }, attachmentsByQuestionId: {} },
1160 + },
1161 + "run-8",
1162 + 8_000_070,
1163 + );
1164 + const answerMessageId = MessageId.make(`async-answer:${requestId}`);
1165 + const settledPrefix = [
1166 + question,
1167 + inRun(userMessage("queued", "Queued follow-up"), "run-9", 9_000_001),
1168 + inRun(assistantMessage("reply-9", "RUN 9 REPLY"), "run-9", 9_000_002),
1169 + ];
1170 + const lateRun = [
1171 + inRun(
1172 + {
1173 + ...userMessage(answerMessageId, "Which color?\nBlue"),
1174 + inputIntent: "steer",
1175 + creationSource: "server",
1176 + },
1177 + "run-10",
1178 + 10_000_001,
1179 + ),
1180 + inRun(assistantMessage("reply-10", "RUN 10 ACKNOWLEDGED BLUE"), "run-10", 10_000_002),
1181 + ];
1182 + const input = { visibleTurnItems: [...settledPrefix, ...lateRun], optimisticMessages: [] };
1183 + const messageIds = (entries: ReadonlyArray<TimelineEntry>) =>
1184 + entries.flatMap((entry) => (entry.kind === "message" ? [entry.message.id] : []));
1185 + const expectedMessageIds = ["queued", "reply-9", answerMessageId, "reply-10"];
1186 +
1187 + expect
1188 + .soft(messageIds(deriveTimelineEntriesFromVisibleTurnItems(input)), "full projection")
1189 + .toEqual(expectedMessageIds);
1190 + const previous = deriveTimelineEntriesFromVisibleTurnItemsWithState({
1191 + ...input,
1192 + visibleTurnItems: settledPrefix,
1193 + });
1194 + expect
1195 + .soft(
1196 + messageIds(deriveTimelineEntriesFromVisibleTurnItemsWithState(input, previous).entries),
1197 + "incremental projection",
1198 + )
1199 + .toEqual(expectedMessageIds);
1200 + });
1201 +
1202 it("excludes checkpoint-only work from the timeline", () => {
1203 const message: OrchestrationV2TurnItem = {
1204 ...base,
apps/web/src/session-logic.ts
+12 -4
@@ -527,10 +527,11 @@ export function deriveTimelineEntriesFromVisibleTurnItems(
527 return undefined;
528 };
529
530 - const foldedAnswerMessageIds = new Set(
530 + // An answer that started a later run stays a normal message at that run's position.
531 + const foldedAnswerRunIdByMessageId = new Map<string, OrchestrationV2TurnItem["runId"]>(
532 input.visibleTurnItems.flatMap(({ item }) =>
533 item.type === "user_input_request" && item.questionAnswer
533 - ? [`async-answer:${item.questionAnswer.requestId}`]
534 + ? [[`async-answer:${item.questionAnswer.requestId}`, item.runId] as const]
535 : [],
536 ),
537 );
@@ -544,7 +545,11 @@ export function deriveTimelineEntriesFromVisibleTurnItems(
545 item.status === "pending"
546 )
547 continue;
547 - if (item.type === "user_message" && foldedAnswerMessageIds.has(item.messageId)) continue;
548 + if (
549 + item.type === "user_message" &&
550 + foldedAnswerRunIdByMessageId.get(item.messageId) === item.runId
551 + )
552 + continue;
553 const createdAt = projectedItemCreatedAt(row);
554 const attempt = resolveAttempt(item);
555 const attemptMetadata = attempt === undefined ? {} : { attempt };
@@ -682,7 +687,10 @@ export function deriveTimelineEntriesFromVisibleTurnItems(
687 });
688 }
689
685 - const retainedMessageIds = new Set([...committedMessageIds, ...foldedAnswerMessageIds]);
690 + const retainedMessageIds = new Set([
691 + ...committedMessageIds,
692 + ...foldedAnswerRunIdByMessageId.keys(),
693 + ]);
694 for (const message of input.anchoredMessages ?? []) {
695 if (retainedMessageIds.has(message.id)) continue;
696 retainedMessageIds.add(message.id);