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 23, 00:30 UTC
perf(mobile): streamed chunks cost about 8x less JS on long threads (#19135)
Co-authored-by: PR Batch Tester <agent@local.test> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>
shivam committed
Oct 20, 2026 at 07:35 UTC
cf55896339f17d874ff6885afcf8b029f6878997
6 files changed
+649
-42
apps/mobile/src/features/threads/ThreadFeed.tsx
+3
@@ -174,6 +174,7 @@ import {
174
resolveMarkdownLinkPresentation,
175
} from "../../lib/markdownLinks";
176
import {
177
+ createThreadFeedCache,
178
failedFeedRunIds,
179
deriveThreadFeedPresentation,
180
threadFeedRunIsUnsettled,
@@ -1681,6 +1682,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
1682
const disclosureSettleFrameRef = useRef<number | null>(null);
1683
const disclosureSettleSecondFrameRef = useRef<number | null>(null);
1684
const disclosureAnchorKeyRef = useRef<string | null>(null);
1685
+ const [feedCache] = useState(createThreadFeedCache);
1686
const previousLatestTurnRef = useRef(props.latestRun);
1687
const userScrollSettleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
1688
const headerMaterialVisibleRef = useRef(false);
@@ -2101,6 +2103,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
2103
),
2104
props.activeWorkStartedAt,
2105
props.runlessWorkActive ?? false,
2106
+ feedCache,
2107
),
2108
props.feed,
2109
props.queuedMessages,
apps/mobile/src/lib/threadActivity.test.ts
+238
@@ -28,11 +28,14 @@ import {
28
workEntryRowLabel,
29
isContextHandoffActivityGroup,
30
buildThreadFeed,
31
+ createThreadFeedCache,
32
deriveThreadFeedPresentation,
33
threadFeedActivityIsVisible,
34
threadFeedRunIsUnsettled,
35
type ThreadFeedActivity,
36
+ type ThreadFeedCache,
37
type ThreadFeedEntry,
38
+ type ThreadFeedLatestRun,
39
togglePendingUserInputOptionSelection,
40
setPendingUserInputCustomAnswer,
41
isPendingUserInputOptionSelected,
@@ -2904,3 +2907,238 @@ describe("MCP apps", () => {
2907
expect(feed("running").some((candidate) => candidate.type === "mcp-app")).toBe(false);
2908
});
2909
});
2910
+
2911
+describe("streamed feed updates", () => {
2912
+ const runs = [RunId.make("run-1"), RunId.make("run-2"), RunId.make("run-3")] as const;
2913
+ const at = (second: number) => `2026-06-20T00:00:${String(second).padStart(2, "0")}.000Z`;
2914
+ const item = (id: string, second: number, run: RunId) => ({
2915
+ ...base(id, at(second), second),
2916
+ runId: run,
2917
+ });
2918
+ const user = (
2919
+ id: string,
2920
+ second: number,
2921
+ run: RunId,
2922
+ ): Extract<OrchestrationV2TurnItem, { type: "user_message" }> => ({
2923
+ ...item(id, second, run),
2924
+ type: "user_message",
2925
+ messageId: MessageId.make(`message-${id}`),
2926
+ createdBy: "user",
2927
+ creationSource: "mobile",
2928
+ inputIntent: "turn_start",
2929
+ text: `Prompt ${id}`,
2930
+ attachments: [],
2931
+ });
2932
+ const reply = (id: string, second: number, run: RunId, text = "Done", streaming = false) =>
2933
+ ({
2934
+ ...item(id, second, run),
2935
+ ...(streaming ? { status: "running" as const, completedAt: null } : {}),
2936
+ type: "assistant_message",
2937
+ messageId: MessageId.make(`message-${id}`),
2938
+ text,
2939
+ streaming,
2940
+ }) satisfies OrchestrationV2TurnItem;
2941
+ const shell = (id: string, second: number, run: RunId): OrchestrationV2TurnItem => ({
2942
+ ...item(id, second, run),
2943
+ type: "command_execution",
2944
+ input: `echo ${id}`,
2945
+ output: id,
2946
+ exitCode: 0,
2947
+ });
2948
+ const requestId = RuntimeRequestId.make("request-color");
2949
+ const question = (answered: boolean): OrchestrationV2TurnItem => ({
2950
+ ...item("question", 12, runs[1]),
2951
+ type: "user_input_request",
2952
+ requestId,
2953
+ questions: [],
2954
+ ...(answered
2955
+ ? { questionAnswer: { requestId, answers: { color: "Blue" }, attachmentsByQuestionId: {} } }
2956
+ : {}),
2957
+ });
2958
+ const answer: OrchestrationV2TurnItem = {
2959
+ ...user("answer", 40, runs[1]),
2960
+ messageId: MessageId.make(`async-answer:${requestId}`),
2961
+ };
2962
+ const delegation: OrchestrationV2TurnItem = {
2963
+ ...item("delegation", 3, runs[0]),
2964
+ type: "dynamic_tool",
2965
+ toolName: "t3-code.delegate_task",
2966
+ input: { task: "Check" },
2967
+ output: { taskId: "child" },
2968
+ };
2969
+ const lateChild: OrchestrationV2TurnItem = {
2970
+ ...item("late-child", 30, runs[0]),
2971
+ type: "subagent",
2972
+ subagentId: NodeId.make("child"),
2973
+ origin: "app_owned",
2974
+ driver: ProviderDriverKind.make("codex"),
2975
+ providerInstanceId: ProviderInstanceId.make("codex"),
2976
+ childThreadId: sourceThreadId,
2977
+ prompt: "Check",
2978
+ result: "Fine",
2979
+ };
2980
+ const resumed: OrchestrationV2TurnItem = {
2981
+ ...lateChild,
2982
+ ...item("resumed", 3, runs[2]),
2983
+ subagentId: NodeId.make("resumed"),
2984
+ origin: "provider_native",
2985
+ childThreadId: null,
2986
+ };
2987
+ const history: OrchestrationV2TurnItem[] = [
2988
+ user("u1", 1, runs[0]),
2989
+ shell("s1", 2, runs[0]),
2990
+ delegation,
2991
+ reply("a1", 4, runs[0]),
2992
+ user("u2", 10, runs[1]),
2993
+ shell("s2", 11, runs[1]),
2994
+ question(false),
2995
+ reply("a2", 13, runs[1]),
2996
+ user("u3", 20, runs[2]),
2997
+ shell("s3", 21, runs[2]),
2998
+ ];
2999
+ const running = {
3000
+ runId: runs[2],
3001
+ status: "running" as const,
3002
+ startedAt: at(20),
3003
+ completedAt: null,
3004
+ };
3005
+ const settled = { ...running, status: "completed" as const, completedAt: at(50) };
3006
+ // Each step is what one streamed event leaves behind, including the edits
3007
+ // that reach back into earlier runs.
3008
+ const steps: ReadonlyArray<{
3009
+ readonly items: ReadonlyArray<OrchestrationV2TurnItem>;
3010
+ readonly latestRun: ThreadFeedLatestRun;
3011
+ }> = [
3012
+ { items: [...history, reply("a3", 22, runs[2], "W", true)], latestRun: running },
3013
+ { items: [...history, reply("a3", 22, runs[2], "Wor", true)], latestRun: running },
3014
+ {
3015
+ items: [...history, reply("a3", 22, runs[2], "Working", true), shell("s4", 23, runs[2])],
3016
+ latestRun: running,
3017
+ },
3018
+ {
3019
+ items: [
3020
+ ...history,
3021
+ reply("a3", 22, runs[2], "Working", true),
3022
+ shell("s4", 23, runs[2]),
3023
+ lateChild,
3024
+ ],
3025
+ latestRun: running,
3026
+ },
3027
+ {
3028
+ items: [
3029
+ ...history.map((entry) => (entry.id === "question" ? question(true) : entry)),
3030
+ reply("a3", 22, runs[2], "Working", true),
3031
+ shell("s4", 23, runs[2]),
3032
+ lateChild,
3033
+ answer,
3034
+ ],
3035
+ latestRun: running,
3036
+ },
3037
+ {
3038
+ items: [
3039
+ ...history.slice(0, 9),
3040
+ shell("inserted", 20, runs[2]),
3041
+ ...history.slice(9),
3042
+ reply("a3", 22, runs[2], "Working", true),
3043
+ shell("s4", 23, runs[2]),
3044
+ ],
3045
+ latestRun: running,
3046
+ },
3047
+ {
3048
+ items: [...history, reply("a3", 22, runs[2], "Working on it"), shell("s4", 23, runs[2])],
3049
+ latestRun: running,
3050
+ },
3051
+ {
3052
+ items: [...history, reply("a3", 22, runs[2], "Working on it"), shell("s4", 23, runs[2])],
3053
+ latestRun: settled,
3054
+ },
3055
+ {
3056
+ items: [
3057
+ ...history,
3058
+ reply("a3", 22, runs[2], "Working on it"),
3059
+ shell("s4", 23, runs[2]),
3060
+ shell("late-s1", 45, runs[0]),
3061
+ ],
3062
+ latestRun: settled,
3063
+ },
3064
+ // The first run's fold above was timed to the late item; dropping it must reach back too.
3065
+ {
3066
+ items: [...history, reply("a3", 22, runs[2], "Working on it"), shell("s4", 23, runs[2])],
3067
+ latestRun: settled,
3068
+ },
3069
+ // The latest run resumes a subagent from the first run: the item moves to
3070
+ // the latest run but keeps its place, so it folds with the first run.
3071
+ {
3072
+ items: [
3073
+ ...history.slice(0, 3),
3074
+ resumed,
3075
+ ...history.slice(3),
3076
+ reply("a3", 22, runs[2], "Working on it"),
3077
+ shell("s4", 23, runs[2]),
3078
+ ],
3079
+ latestRun: running,
3080
+ },
3081
+ {
3082
+ items: [
3083
+ ...history.slice(0, 3),
3084
+ resumed,
3085
+ ...history.slice(3),
3086
+ reply("a3", 22, runs[2], "Working on it"),
3087
+ shell("s4", 23, runs[2]),
3088
+ reply("a4", 24, runs[2], "Still", true),
3089
+ ],
3090
+ latestRun: running,
3091
+ },
3092
+ ];
3093
+ // Like the projection reducer, an unchanged item at an unchanged position keeps its row.
3094
+ const rowsByItem = new Map<
3095
+ OrchestrationV2TurnItem,
3096
+ Map<number, OrchestrationV2ProjectedTurnItem>
3097
+ >();
3098
+ const row = (entry: OrchestrationV2TurnItem, position: number) => {
3099
+ const byPosition = rowsByItem.get(entry) ?? new Map<number, OrchestrationV2ProjectedTurnItem>();
3100
+ rowsByItem.set(entry, byPosition);
3101
+ const cached = byPosition.get(position) ?? projected(entry, position);
3102
+ byPosition.set(position, cached);
3103
+ return cached;
3104
+ };
3105
+ const present = (
3106
+ step: (typeof steps)[number],
3107
+ expandedRunIds: ReadonlySet<RunId>,
3108
+ cache?: ThreadFeedCache,
3109
+ ) =>
3110
+ deriveThreadFeedPresentation(
3111
+ buildThreadFeed(step.items.map(row), { cache }),
3112
+ step.latestRun,
3113
+ expandedRunIds,
3114
+ new Set(),
3115
+ step.latestRun.status === "running" ? at(20) : null,
3116
+ false,
3117
+ cache,
3118
+ );
3119
+
3120
+ it.each([
3121
+ { folds: "collapsed", expandedRunIds: new Set<RunId>() },
3122
+ { folds: "expanded", expandedRunIds: new Set<RunId>(runs) },
3123
+ ])("matches a fresh build after every update with $folds runs", ({ expandedRunIds }) => {
3124
+ const cache = createThreadFeedCache();
3125
+ const streamed = steps.map((step) => present(step, expandedRunIds, cache));
3126
+ const fresh = steps.map((step) => present(step, expandedRunIds));
3127
+ // Closures on activities are not part of what a row shows.
3128
+ const values = (rows: ReadonlyArray<ThreadFeedEntry>) => JSON.parse(JSON.stringify(rows));
3129
+ for (const [index, rows] of streamed.entries()) {
3130
+ expect(values(rows), `step ${index}`).toEqual(values(fresh[index]!));
3131
+ }
3132
+ });
3133
+
3134
+ it("hides a delegation once its child reaches back into the earlier run", () => {
3135
+ const showsDelegation = (step: (typeof steps)[number]) =>
3136
+ buildThreadFeed(step.items.map(row)).some(
3137
+ (entry) =>
3138
+ entry.type === "activity-group" &&
3139
+ entry.activities.some((activity) => activity.projectedItem.item.id === "delegation"),
3140
+ );
3141
+ expect(showsDelegation(steps[2]!)).toBe(true);
3142
+ expect(showsDelegation(steps[3]!)).toBe(false);
3143
+ });
3144
+});
apps/mobile/src/lib/threadActivity.ts
+297
-30
@@ -887,16 +887,15 @@ function isEmptyMessage(entry: RawThreadFeedEntry): boolean {
887
);
888
}
889
890
-function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): ThreadFeedEntry[] {
891
- const childrenByRun = new Map<RunId, Set<string>>();
892
- for (const entry of entries) {
893
- if (entry.type !== "activity") continue;
894
- const item = entry.activity.projectedItem.item;
895
- if (item.type !== "subagent" || item.origin !== "app_owned" || item.runId === null) continue;
896
- const children = childrenByRun.get(item.runId) ?? new Set<string>();
897
- children.add(item.subagentId);
898
- childrenByRun.set(item.runId, children);
899
- }
890
+/**
891
+ * `onRestart` hears each entry after which no group is open, with the grouped
892
+ * length so far: the entries before it group the same whatever follows.
893
+ */
894
+function groupAdjacentActivities(
895
+ entries: ReadonlyArray<RawThreadFeedEntry>,
896
+ childrenByRun: ReadonlyMap<RunId, ReadonlySet<string>>,
897
+ onRestart?: (entryIndex: number, groupedLength: number) => void,
898
+): ThreadFeedEntry[] {
899
const grouped: ThreadFeedEntry[] = [];
900
let firstActivityEntry: Extract<RawThreadFeedEntry, { readonly type: "activity" }> | null = null;
901
let openGroupActivities: ThreadFeedActivity[] = [];
@@ -924,7 +923,8 @@ function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): Th
923
openGroupActivities = [];
924
};
925
927
- for (const entry of entries) {
926
+ for (let entryIndex = 0; entryIndex < entries.length; entryIndex += 1) {
927
+ const entry = entries[entryIndex]!;
928
if (entry.type === "activity") {
929
const item = entry.activity.projectedItem.item;
930
if (
@@ -950,6 +950,7 @@ function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): Th
950
if (entry.type !== "activity") {
951
flushGroup();
952
grouped.push(entry);
953
+ onRestart?.(entryIndex, grouped.length);
954
continue;
955
}
956
@@ -1245,6 +1246,79 @@ function settleSupersededReasoning(
1246
return settled;
1247
}
1248
1249
+interface ThreadFeedPresentationBuild {
1250
+ readonly feed: ReadonlyArray<ThreadFeedEntry>;
1251
+ readonly latestRun: ThreadFeedLatestRun | null;
1252
+ readonly expandedRunIds: ReadonlySet<RunId>;
1253
+ readonly expandedWorkGroupIds: ReadonlySet<string>;
1254
+ readonly activeWorkStartedAt: string | null;
1255
+ readonly runlessWorkActive: boolean;
1256
+ readonly rows: ReadonlyArray<ThreadFeedEntry>;
1257
+ /** Feed entry `entry` is a user message whose rows start at `rowsLength`. */
1258
+ readonly restarts: ReadonlyArray<{ readonly entry: number; readonly rowsLength: number }>;
1259
+ /** Where each run's entries begin, so a reused prefix never shares a run with the rest. */
1260
+ readonly firstEntryByRun: ReadonlyMap<RunId, number>;
1261
+}
1262
+
1263
+function latestRunsEqual(left: ThreadFeedLatestRun | null, right: ThreadFeedLatestRun | null) {
1264
+ return (
1265
+ left === right ||
1266
+ (left !== null &&
1267
+ right !== null &&
1268
+ left.runId === right.runId &&
1269
+ left.status === right.status &&
1270
+ left.startedAt === right.startedAt &&
1271
+ left.completedAt === right.completedAt &&
1272
+ left.turnEnded === right.turnEnded)
1273
+ );
1274
+}
1275
+
1276
+function feedEntryRunId(entry: ThreadFeedEntry): RunId | null {
1277
+ return entry.type === "message" ? (entry.message.runId ?? null) : entry.runId;
1278
+}
1279
+
1280
+function isUserMessageEntry(entry: ThreadFeedEntry | undefined): boolean {
1281
+ return entry?.type === "message" && entry.message.role === "user";
1282
+}
1283
+
1284
+/**
1285
+ * A user message starts every fold and is never hidden or grouped, so the
1286
+ * rows before it depend only on the entries before it, their runs, and the
1287
+ * shared inputs. Returns the user message entry to restart from, or null to
1288
+ * present the whole feed.
1289
+ */
1290
+function presentationRestart(
1291
+ previous: ThreadFeedPresentationBuild | null,
1292
+ feed: ReadonlyArray<ThreadFeedEntry>,
1293
+ latestRun: ThreadFeedLatestRun | null,
1294
+ expandedRunIds: ReadonlySet<RunId>,
1295
+ expandedWorkGroupIds: ReadonlySet<string>,
1296
+ activeWorkStartedAt: string | null,
1297
+ runlessWorkActive: boolean,
1298
+): { readonly entry: number; readonly rowsLength: number; readonly index: number } | null {
1299
+ if (
1300
+ previous === null ||
1301
+ !latestRunsEqual(previous.latestRun, latestRun) ||
1302
+ previous.activeWorkStartedAt !== activeWorkStartedAt ||
1303
+ previous.runlessWorkActive !== runlessWorkActive ||
1304
+ !setsEqual(previous.expandedRunIds, expandedRunIds) ||
1305
+ !setsEqual(previous.expandedWorkGroupIds, expandedWorkGroupIds)
1306
+ ) {
1307
+ return null;
1308
+ }
1309
+ const firstChanged = firstChangedIndex(previous.feed, feed);
1310
+ let index = previous.restarts.length - 1;
1311
+ while (index >= 0 && previous.restarts[index]!.entry > firstChanged) index -= 1;
1312
+ const restart = previous.restarts[index];
1313
+ if (restart === undefined || !isUserMessageEntry(feed[restart.entry])) return null;
1314
+ for (let entryIndex = restart.entry; entryIndex < feed.length; entryIndex += 1) {
1315
+ const runId = feedEntryRunId(feed[entryIndex]!);
1316
+ const firstEntry = runId === null ? undefined : previous.firstEntryByRun.get(runId);
1317
+ if (firstEntry !== undefined && firstEntry < restart.entry) return null;
1318
+ }
1319
+ return { ...restart, index };
1320
+}
1321
+
1322
export function deriveThreadFeedPresentation(
1323
feed: ReadonlyArray<ThreadFeedEntry>,
1324
latestRun: ThreadFeedLatestRun | null,
@@ -1252,11 +1326,42 @@ export function deriveThreadFeedPresentation(
1326
expandedWorkGroupIds: ReadonlySet<string> = new Set(),
1327
activeWorkStartedAt: string | null = null,
1328
runlessWorkActive = false,
1329
+ cache?: ThreadFeedCache,
1330
): ThreadFeedEntry[] {
1256
- const retainedFeed = feed.filter(
1257
- (entry) =>
1258
- entry.type !== "run-fold" && entry.type !== "work-toggle" && entry.type !== "thinking",
1331
+ const previous = cache?.presentation ?? null;
1332
+ const restart = presentationRestart(
1333
+ previous,
1334
+ feed,
1335
+ latestRun,
1336
+ expandedRunIds,
1337
+ expandedWorkGroupIds,
1338
+ activeWorkStartedAt,
1339
+ runlessWorkActive,
1340
);
1341
+ const start = restart?.entry ?? 0;
1342
+ const result: ThreadFeedEntry[] =
1343
+ restart === null ? [] : previous!.rows.slice(0, restart.rowsLength);
1344
+ const restarts = restart === null ? [] : previous!.restarts.slice(0, restart.index);
1345
+ const firstEntryByRun = new Map<RunId, number>();
1346
+ if (restart !== null) {
1347
+ for (const [runId, entry] of previous!.firstEntryByRun) {
1348
+ if (entry < start) firstEntryByRun.set(runId, entry);
1349
+ }
1350
+ }
1351
+ const tailStart = result.length;
1352
+ const lastEntryByRun = new Map<RunId, number>();
1353
+
1354
+ const retainedFeed: Array<
1355
+ Exclude<ThreadFeedEntry, { readonly type: "run-fold" | "work-toggle" | "thinking" }>
1356
+ > = [];
1357
+ const retainedFeedIndices: number[] = [];
1358
+ for (let index = start; index < feed.length; index += 1) {
1359
+ const entry = feed[index]!;
1360
+ if (entry.type === "run-fold" || entry.type === "work-toggle" || entry.type === "thinking")
1361
+ continue;
1362
+ retainedFeed.push(entry);
1363
+ retainedFeedIndices.push(index);
1364
+ }
1365
const sourceFeed = retainedFeed.map((entry, index) =>
1366
settleSupersededReasoning(entry, index === retainedFeed.length - 1),
1367
);
@@ -1276,8 +1381,17 @@ export function deriveThreadFeedPresentation(
1381
for (const entryId of fold.hiddenEntryIds) collapsedEntryIds.add(entryId);
1382
}
1383
}
1279
- const result: ThreadFeedEntry[] = [];
1280
- for (const entry of sourceFeed) {
1384
+ for (let sourceIndex = 0; sourceIndex < sourceFeed.length; sourceIndex += 1) {
1385
+ const entry = sourceFeed[sourceIndex]!;
1386
+ const feedIndex = retainedFeedIndices[sourceIndex]!;
1387
+ if (isUserMessageEntry(entry)) {
1388
+ restarts.push({ entry: feedIndex, rowsLength: result.length });
1389
+ }
1390
+ const runId = feedEntryRunId(entry);
1391
+ if (runId !== null) {
1392
+ if (!firstEntryByRun.has(runId)) firstEntryByRun.set(runId, feedIndex);
1393
+ lastEntryByRun.set(runId, feedIndex);
1394
+ }
1395
const isActiveTailGroup =
1396
isWorking &&
1397
(activeRunId !== null || runlessWorkActive) &&
@@ -1356,15 +1470,51 @@ export function deriveThreadFeedPresentation(
1470
) {
1471
result.push(thinkingRow(activeWorkStartedAt, activeRunId));
1472
}
1359
- return result.map((row, index) => {
1360
- if (!isWorkLogFeedRow(row) || !isWorkLogFeedRow(result[index + 1])) return row;
1473
+ // Reused rows are final: the user message after them never continues a work log.
1474
+ for (let index = tailStart; index < result.length; index += 1) {
1475
+ const row = result[index]!;
1476
+ if (!isWorkLogFeedRow(row) || !isWorkLogFeedRow(result[index + 1])) continue;
1477
let continued = continuedWorkLogRows.get(row);
1478
if (!continued) {
1479
continued = { ...row, continuesWorkLog: true };
1480
continuedWorkLogRows.set(row, continued);
1481
}
1366
- return continued;
1482
+ result[index] = continued;
1483
+ }
1484
+ // A run that crosses a user message made the rows before it from entries
1485
+ // after it, so a later build cannot restart there even once those entries
1486
+ // are gone. Only runs of this build's own entries can cross its restarts.
1487
+ const crossings = Array.from({ length: feed.length - start + 1 }, () => 0);
1488
+ for (const [runId, last] of lastEntryByRun) {
1489
+ const first = firstEntryByRun.get(runId)!;
1490
+ if (first >= last) continue;
1491
+ crossings[first - start + 1]! += 1;
1492
+ crossings[last - start + 1]! -= 1;
1493
+ }
1494
+ let crossingRuns = 0;
1495
+ let crossingIndex = 0;
1496
+ const cleanRestarts = restarts.filter((candidate) => {
1497
+ if (candidate.entry < start) return true;
1498
+ while (crossingIndex <= candidate.entry - start) {
1499
+ crossingRuns += crossings[crossingIndex]!;
1500
+ crossingIndex += 1;
1501
+ }
1502
+ return crossingRuns === 0;
1503
});
1504
+ if (cache) {
1505
+ cache.presentation = {
1506
+ feed,
1507
+ latestRun,
1508
+ expandedRunIds,
1509
+ expandedWorkGroupIds,
1510
+ activeWorkStartedAt,
1511
+ runlessWorkActive,
1512
+ rows: result,
1513
+ restarts: cleanRestarts,
1514
+ firstEntryByRun,
1515
+ };
1516
+ }
1517
+ return result;
1518
}
1519
1520
const continuedWorkLogRows = new WeakMap<ThreadFeedEntry, ThreadFeedEntry>();
@@ -1744,15 +1894,69 @@ export function buildPendingUserInputAnswers(
1894
return answers;
1895
}
1896
1897
+interface ThreadFeedBuild {
1898
+ readonly rows: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
1899
+ readonly attempts: ReadonlyArray<OrchestrationV2RunAttempt> | undefined;
1900
+ readonly nodes: ReadonlyArray<OrchestrationV2ExecutionNode> | undefined;
1901
+ readonly foldedAnswerMessageIds: ReadonlySet<string>;
1902
+ readonly delegatedChildrenByRun: ReadonlyMap<RunId, ReadonlySet<string>>;
1903
+ readonly feed: ReadonlyArray<ThreadFeedEntry>;
1904
+ /** Grouping is empty before `row`: the rows before it produced `feed.slice(0, feedLength)`. */
1905
+ readonly restarts: ReadonlyArray<{ readonly row: number; readonly feedLength: number }>;
1906
+}
1907
+
1908
+/**
1909
+ * A streamed chunk changes the newest rows of a thread that can hold thousands.
1910
+ * A consumer that keeps one cache across renders lets `buildThreadFeed` and
1911
+ * `deriveThreadFeedPresentation` keep the unchanged prefix of their last
1912
+ * result instead of redoing the whole thread. Each feed on screen owns its
1913
+ * cache, so two threads rendering at once never evict each other.
1914
+ */
1915
+export interface ThreadFeedCache {
1916
+ feedBuild: ThreadFeedBuild | null;
1917
+ presentation: ThreadFeedPresentationBuild | null;
1918
+}
1919
+
1920
+export function createThreadFeedCache(): ThreadFeedCache {
1921
+ return { feedBuild: null, presentation: null };
1922
+}
1923
+
1924
+function setsEqual<T>(left: ReadonlySet<T>, right: ReadonlySet<T>): boolean {
1925
+ if (left.size !== right.size) return false;
1926
+ for (const value of left) if (!right.has(value)) return false;
1927
+ return true;
1928
+}
1929
+
1930
+function setMapsEqual<K, V>(
1931
+ left: ReadonlyMap<K, ReadonlySet<V>>,
1932
+ right: ReadonlyMap<K, ReadonlySet<V>>,
1933
+): boolean {
1934
+ if (left.size !== right.size) return false;
1935
+ for (const [key, values] of left) {
1936
+ const other = right.get(key);
1937
+ if (other === undefined || !setsEqual(values, other)) return false;
1938
+ }
1939
+ return true;
1940
+}
1941
+
1942
+/** Index of the first entry that differs, or the shorter length when one extends the other. */
1943
+function firstChangedIndex<T>(previous: ReadonlyArray<T>, next: ReadonlyArray<T>): number {
1944
+ const limit = Math.min(previous.length, next.length);
1945
+ let index = 0;
1946
+ while (index < limit && previous[index] === next[index]) index += 1;
1947
+ return index;
1948
+}
1949
+
1950
export function buildThreadFeed(
1951
visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
1952
options?: {
1953
readonly anchoredMessages?: ReadonlyArray<LocalThreadMessage>;
1954
readonly attempts?: ReadonlyArray<OrchestrationV2RunAttempt>;
1955
readonly nodes?: ReadonlyArray<OrchestrationV2ExecutionNode>;
1956
+ readonly cache?: ThreadFeedCache;
1957
},
1958
): ThreadFeedEntry[] {
1755
- const entries: RawThreadFeedEntry[] = [];
1959
+ const anchoredMessages = options?.anchoredMessages ?? [];
1960
const attemptByRootNodeId = new Map(
1961
(options?.attempts ?? []).map((attempt) => [attempt.rootNodeId, attempt] as const),
1962
);
@@ -1773,14 +1977,45 @@ export function buildThreadFeed(
1977
}
1978
return null;
1979
};
1776
- const foldedAnswerMessageIds = new Set(
1777
- visibleTurnItems.flatMap(({ item }) =>
1778
- item.type === "user_input_request" && item.questionAnswer
1779
- ? [`async-answer:${item.questionAnswer.requestId}`]
1780
- : [],
1781
- ),
1782
- );
1783
- for (const row of visibleTurnItems) {
1980
+ // Thread-wide facts that change rows anywhere in the feed. A cached prefix
1981
+ // is reused only while these match the build that produced it.
1982
+ const foldedAnswerMessageIds = new Set<string>();
1983
+ const delegatedChildrenByRun = new Map<RunId, Set<string>>();
1984
+ for (const { item } of visibleTurnItems) {
1985
+ if (item.type === "user_input_request" && item.questionAnswer) {
1986
+ foldedAnswerMessageIds.add(`async-answer:${item.questionAnswer.requestId}`);
1987
+ } else if (item.type === "subagent" && item.origin === "app_owned" && item.runId !== null) {
1988
+ const children = delegatedChildrenByRun.get(item.runId) ?? new Set<string>();
1989
+ children.add(item.subagentId);
1990
+ delegatedChildrenByRun.set(item.runId, children);
1991
+ }
1992
+ }
1993
+
1994
+ const cache = options?.cache;
1995
+ const previous = cache?.feedBuild ?? null;
1996
+ let restartIndex = -1;
1997
+ if (
1998
+ previous !== null &&
1999
+ anchoredMessages.length === 0 &&
2000
+ previous.attempts === options?.attempts &&
2001
+ previous.nodes === options?.nodes &&
2002
+ setsEqual(previous.foldedAnswerMessageIds, foldedAnswerMessageIds) &&
2003
+ setMapsEqual(previous.delegatedChildrenByRun, delegatedChildrenByRun)
2004
+ ) {
2005
+ const firstChanged = firstChangedIndex(previous.rows, visibleTurnItems);
2006
+ restartIndex = previous.restarts.length - 1;
2007
+ while (restartIndex >= 0 && previous.restarts[restartIndex]!.row > firstChanged) {
2008
+ restartIndex -= 1;
2009
+ }
2010
+ }
2011
+ const restart = restartIndex === -1 ? null : previous!.restarts[restartIndex]!;
2012
+ const prefix = restart === null ? [] : previous!.feed.slice(0, restart.feedLength);
2013
+ const restarts = restart === null ? [] : previous!.restarts.slice(0, restartIndex + 1);
2014
+
2015
+ const entries: RawThreadFeedEntry[] = [];
2016
+ const entryRows: number[] = [];
2017
+ for (let index = restart?.row ?? 0; index < visibleTurnItems.length; index += 1) {
2018
+ const row = visibleTurnItems[index]!;
2019
const item = row.item;
2020
if (turnItemIsWorkspacePreparation(item)) continue;
2021
if (item.type === "todo_list" || item.type === "checkpoint") continue;
@@ -1792,6 +2027,7 @@ export function buildThreadFeed(
2027
const cached = projectedEntriesCache.get(row);
2028
if (cached?.attemptId === attemptId) {
2029
entries.push(cached.entry);
2030
+ entryRows.push(index);
2031
continue;
2032
}
2033
const createdAt = DateTime.formatIso(item.startedAt ?? item.updatedAt);
@@ -1809,6 +2045,7 @@ export function buildThreadFeed(
2045
};
2046
projectedEntriesCache.set(row, { attemptId, entry });
2047
entries.push(entry);
2048
+ entryRows.push(index);
2049
continue;
2050
}
2051
const app =
@@ -1828,6 +2065,7 @@ export function buildThreadFeed(
2065
};
2066
projectedEntriesCache.set(row, { attemptId, entry });
2067
entries.push(entry);
2068
+ entryRows.push(index);
2069
continue;
2070
}
2071
if (item.type === "user_message" || item.type === "assistant_message") {
@@ -1862,6 +2100,7 @@ export function buildThreadFeed(
2100
};
2101
projectedEntriesCache.set(row, { attemptId, entry });
2102
entries.push(entry);
2103
+ entryRows.push(index);
2104
continue;
2105
}
2106
const activity = toFeedActivity(row, attemptId);
@@ -1874,6 +2113,7 @@ export function buildThreadFeed(
2113
};
2114
projectedEntriesCache.set(row, { attemptId, entry });
2115
entries.push(entry);
2116
+ entryRows.push(index);
2117
}
2118
const retainedMessageIds = new Set([
2119
...foldedAnswerMessageIds,
@@ -1903,7 +2143,7 @@ export function buildThreadFeed(
2143
localMessageEntriesCache.set(message, entry);
2144
return entry;
2145
};
1906
- for (const message of options?.anchoredMessages ?? []) {
2146
+ for (const message of anchoredMessages) {
2147
if (retainedMessageIds.has(message.id)) continue;
2148
retainedMessageIds.add(message.id);
2149
const entry = appendLocalMessage(message);
@@ -1913,5 +2153,32 @@ export function buildThreadFeed(
2153
if (insertionIndex === -1) entries.push(entry);
2154
else entries.splice(insertionIndex, 0, entry);
2155
}
1916
- return groupAdjacentActivities(entries);
2156
+ const grouped = groupAdjacentActivities(
2157
+ entries,
2158
+ delegatedChildrenByRun,
2159
+ // Anchored messages shift entries away from their rows; such a build is not reused.
2160
+ anchoredMessages.length > 0
2161
+ ? undefined
2162
+ : (entryIndex, groupedLength) =>
2163
+ restarts.push({
2164
+ row: entryRows[entryIndex]! + 1,
2165
+ feedLength: prefix.length + groupedLength,
2166
+ }),
2167
+ );
2168
+ const feed = prefix.length === 0 ? grouped : prefix.concat(grouped);
2169
+ if (cache) {
2170
+ cache.feedBuild =
2171
+ anchoredMessages.length > 0
2172
+ ? null
2173
+ : {
2174
+ rows: visibleTurnItems,
2175
+ attempts: options?.attempts,
2176
+ nodes: options?.nodes,
2177
+ foldedAnswerMessageIds,
2178
+ delegatedChildrenByRun,
2179
+ feed,
2180
+ restarts,
2181
+ };
2182
+ }
2183
+ return feed;
2184
}
apps/mobile/src/state/use-thread-composer-state.ts
+3
-1
@@ -55,7 +55,7 @@ import {
55
} from "../lib/composerImages";
56
import type { DraftComposerImageAttachment } from "../lib/composerImages";
57
import { scopedThreadKey } from "../lib/scopedEntities";
58
-import { buildThreadFeed } from "../lib/threadActivity";
58
+import { buildThreadFeed, createThreadFeedCache } from "../lib/threadActivity";
59
import { acknowledgedThreadMessagesAtom } from "./acknowledged-thread-messages";
60
import { appendPendingThreadMessages } from "../features/threads/pending-thread-feed";
61
import { threadAllowsProviderSwitch } from "./thread-provider-switching";
@@ -245,6 +245,7 @@ export function useThreadComposerState() {
245
// detail is usually present but empty during a worktree checkout, so this
246
// cannot be an either/or with the loaded messages.
247
const pendingCreationMessage = selectedThreadCreation?.message ?? null;
248
+ const [feedCache] = useState(createThreadFeedCache);
249
const selectedThreadFeed = (() => {
250
const pendingCreation =
251
pendingCreationMessage !== null &&
@@ -255,6 +256,7 @@ export function useThreadComposerState() {
256
anchoredMessages: pendingCreation,
257
attempts: selectedThreadAttempts,
258
nodes: selectedThreadNodes,
259
+ cache: feedCache,
260
});
261
const pendingAcknowledgments = acknowledgedMessages.filter(
262
(message) =>
packages/client-runtime/src/state/orchestrationV2Projection.test.ts
+68
@@ -304,6 +304,74 @@ describe("applyOrchestrationV2ProjectionEvent", () => {
304
expect(next?.visibleTurnItems.map((row) => row.position)).toEqual([0, 1]);
305
});
306
307
+ it("moves an updated item to its new ordinal and renumbers the rows it passes", () => {
308
+ const inherited = {
309
+ ...commandItem("item-inherited", "parent", 0),
310
+ threadId: ThreadId.make("parent"),
311
+ };
312
+ const items = [
313
+ commandItem("item-a", "a", 1),
314
+ commandItem("item-b", "b", 2),
315
+ commandItem("item-c", "c", 2),
316
+ ];
317
+ const rows = [
318
+ {
319
+ position: 0,
320
+ visibility: "inherited" as const,
321
+ sourceThreadId: inherited.threadId,
322
+ sourceItemId: inherited.id,
323
+ item: inherited,
324
+ },
325
+ ...items.map((item, index) => ({
326
+ position: index + 1,
327
+ visibility: "local" as const,
328
+ sourceThreadId: threadId,
329
+ sourceItemId: item.id,
330
+ item,
331
+ })),
332
+ ];
333
+ const moved = commandItem("item-a", "moved", 2);
334
+ const next = applyOrchestrationV2ProjectionEvent(
335
+ { ...emptyProjection, runs: [run], turnItems: items, visibleTurnItems: rows },
336
+ {
337
+ id: "event-move",
338
+ type: "turn-item.updated",
339
+ threadId,
340
+ runId,
341
+ occurredAt: now,
342
+ payload: moved,
343
+ } as OrchestrationV2DomainEvent,
344
+ );
345
+
346
+ // Equal ordinals order by id, so item-a stays ahead of item-b.
347
+ expect(next?.visibleTurnItems.map((row) => [row.item.id, row.position])).toEqual([
348
+ ["item-inherited", 0],
349
+ ["item-a", 1],
350
+ ["item-b", 2],
351
+ ["item-c", 3],
352
+ ]);
353
+ expect(next?.visibleTurnItems[0]).toBe(rows[0]);
354
+ expect(next?.visibleTurnItems[1]?.item).toBe(moved);
355
+ expect(next?.turnItems.map((item) => item.id)).toEqual(["item-a", "item-b", "item-c"]);
356
+
357
+ const later = commandItem("item-a", "later", 3);
358
+ const last = applyOrchestrationV2ProjectionEvent(next, {
359
+ id: "event-move-later",
360
+ type: "turn-item.updated",
361
+ threadId,
362
+ runId,
363
+ occurredAt: now,
364
+ payload: later,
365
+ } as OrchestrationV2DomainEvent);
366
+ expect(last?.visibleTurnItems.map((row) => [row.item.id, row.position])).toEqual([
367
+ ["item-inherited", 0],
368
+ ["item-b", 1],
369
+ ["item-c", 2],
370
+ ["item-a", 3],
371
+ ]);
372
+ expect(last?.turnItems.at(0)).toBe(later);
373
+ });
374
+
375
describe("partial timeline", () => {
376
const queuedRunId = RunId.make("run-queued");
377
const steerRunId = RunId.make("run-steer");
packages/client-runtime/src/state/orchestrationV2Projection.ts
+40
-11
@@ -152,7 +152,10 @@ function upsertVisibleTurnItem(
152
latestLocalTurnOrdinal: number | null | undefined,
153
): OrchestrationV2ThreadProjection["visibleTurnItems"] {
154
const rows = projection.visibleTurnItems;
155
- const index = rows.findIndex((row) => row.sourceItemId === item.id);
155
+ // Streamed updates land on the newest rows. Item ids are unique, so the
156
+ // search can start there.
157
+ let index = rows.length - 1;
158
+ while (index >= 0 && rows[index]!.sourceItemId !== item.id) index -= 1;
159
const next = {
160
position: 0,
161
visibility: "local" as const,
@@ -177,16 +180,34 @@ function upsertVisibleTurnItem(
180
) {
181
return rows;
182
}
180
- const updated = index === -1 ? [...rows] : [...rows.slice(0, index), ...rows.slice(index + 1)];
181
- const insertionIndex = updated.findIndex(
182
- (row) =>
183
+ // The item goes before the first later local row, as if its old row were
184
+ // removed first. One pass builds and renumbers the result: this runs for
185
+ // every streamed chunk of a thread that can hold thousands of rows.
186
+ let insertion = rows.length;
187
+ for (let candidate = 0; candidate < rows.length; candidate += 1) {
188
+ const row = rows[candidate]!;
189
+ if (
190
+ candidate !== index &&
191
row.visibility === "local" &&
192
(row.item.ordinal > item.ordinal ||
193
(row.item.ordinal === item.ordinal &&
186
- String(row.item.id).localeCompare(String(item.id)) > 0)),
187
- );
188
- updated.splice(insertionIndex === -1 ? updated.length : insertionIndex, 0, next);
189
- return renumberVisibleItems(updated);
194
+ String(row.item.id).localeCompare(String(item.id)) > 0))
195
+ ) {
196
+ insertion = candidate;
197
+ break;
198
+ }
199
+ }
200
+ const updated: Array<(typeof rows)[number]> = [];
201
+ for (let source = 0; source < rows.length; source += 1) {
202
+ if (source === insertion) updated.push(next);
203
+ if (source !== index) updated.push(rows[source]!);
204
+ }
205
+ if (insertion === rows.length) updated.push(next);
206
+ for (let position = 0; position < updated.length; position += 1) {
207
+ const row = updated[position]!;
208
+ if (row.position !== position) updated[position] = { ...row, position };
209
+ }
210
+ return updated;
211
}
212
213
export function applyOrchestrationV2ProjectionEvent(
@@ -293,17 +314,25 @@ export function applyOrchestrationV2ProjectionEvent(
314
case "plan.updated":
315
return { ...base, plans: upsertEntity(base.plans, event.payload) };
316
case "turn-item.updated": {
317
+ // Streamed updates land on the newest items, so search from the end.
318
+ let itemIndex = projection.turnItems.length - 1;
319
+ while (itemIndex >= 0 && projection.turnItems[itemIndex]!.id !== event.payload.id) {
320
+ itemIndex -= 1;
321
+ }
322
if (
323
partialTimeline &&
298
- !projection.turnItems.some((candidate) => candidate.id === event.payload.id) &&
324
+ itemIndex === -1 &&
325
shouldDropMissingPartialTurnItem(projection, event.payload, latestLocalTurnOrdinal)
326
) {
327
return projection;
328
}
303
- const next = { ...base, turnItems: upsertEntity(base.turnItems, event.payload) };
329
+ const turnItems = [...projection.turnItems];
330
+ if (itemIndex === -1) turnItems.push(event.payload);
331
+ else turnItems[itemIndex] = event.payload;
332
+ const next = { ...base, turnItems };
333
// Only interrupt requests can change another item's visibility. Streaming
334
// text/tool updates must not recheck every row against every run.
306
- const previous = projection.turnItems.find((item) => item.id === event.payload.id);
335
+ const previous = itemIndex === -1 ? undefined : projection.turnItems[itemIndex];
336
const visible =
337
event.payload.type === "run_interrupt_request" || previous?.type === "run_interrupt_request"
338
? { ...next, visibleTurnItems: activeVisibleTurnItems(next) }