Skip to content
TypeScript

perf(mobile): streamed chunks cost about 8x less JS on long threads (#19135)

shivamcf55896339f1
diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx
index ff5bf3147e0..293f6aceac6 100644
--- a/apps/mobile/src/features/threads/ThreadFeed.tsx
+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx
@@ -174,6 +174,7 @@ import {
resolveMarkdownLinkPresentation,
} from "../../lib/markdownLinks";
import {
+ createThreadFeedCache,
failedFeedRunIds,
deriveThreadFeedPresentation,
threadFeedRunIsUnsettled,
@@ -1681,6 +1682,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const disclosureSettleFrameRef = useRef<number | null>(null);
const disclosureSettleSecondFrameRef = useRef<number | null>(null);
const disclosureAnchorKeyRef = useRef<string | null>(null);
+ const [feedCache] = useState(createThreadFeedCache);
const previousLatestTurnRef = useRef(props.latestRun);
const userScrollSettleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const headerMaterialVisibleRef = useRef(false);
@@ -2101,6 +2103,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
),
props.activeWorkStartedAt,
props.runlessWorkActive ?? false,
+ feedCache,
),
props.feed,
props.queuedMessages,
diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts
index f9fccc8a394..b443c0e3f7a 100644
--- a/apps/mobile/src/lib/threadActivity.test.ts
+++ b/apps/mobile/src/lib/threadActivity.test.ts
@@ -28,11 +28,14 @@ import {
workEntryRowLabel,
isContextHandoffActivityGroup,
buildThreadFeed,
+ createThreadFeedCache,
deriveThreadFeedPresentation,
threadFeedActivityIsVisible,
threadFeedRunIsUnsettled,
type ThreadFeedActivity,
+ type ThreadFeedCache,
type ThreadFeedEntry,
+ type ThreadFeedLatestRun,
togglePendingUserInputOptionSelection,
setPendingUserInputCustomAnswer,
isPendingUserInputOptionSelected,
@@ -2904,3 +2907,238 @@ describe("MCP apps", () => {
expect(feed("running").some((candidate) => candidate.type === "mcp-app")).toBe(false);
});
});
+
+describe("streamed feed updates", () => {
+ const runs = [RunId.make("run-1"), RunId.make("run-2"), RunId.make("run-3")] as const;
+ const at = (second: number) => `2026-06-20T00:00:${String(second).padStart(2, "0")}.000Z`;
+ const item = (id: string, second: number, run: RunId) => ({
+ ...base(id, at(second), second),
+ runId: run,
+ });
+ const user = (
+ id: string,
+ second: number,
+ run: RunId,
+ ): Extract<OrchestrationV2TurnItem, { type: "user_message" }> => ({
+ ...item(id, second, run),
+ type: "user_message",
+ messageId: MessageId.make(`message-${id}`),
+ createdBy: "user",
+ creationSource: "mobile",
+ inputIntent: "turn_start",
+ text: `Prompt ${id}`,
+ attachments: [],
+ });
+ const reply = (id: string, second: number, run: RunId, text = "Done", streaming = false) =>
+ ({
+ ...item(id, second, run),
+ ...(streaming ? { status: "running" as const, completedAt: null } : {}),
+ type: "assistant_message",
+ messageId: MessageId.make(`message-${id}`),
+ text,
+ streaming,
+ }) satisfies OrchestrationV2TurnItem;
+ const shell = (id: string, second: number, run: RunId): OrchestrationV2TurnItem => ({
+ ...item(id, second, run),
+ type: "command_execution",
+ input: `echo ${id}`,
+ output: id,
+ exitCode: 0,
+ });
+ const requestId = RuntimeRequestId.make("request-color");
+ const question = (answered: boolean): OrchestrationV2TurnItem => ({
+ ...item("question", 12, runs[1]),
+ type: "user_input_request",
+ requestId,
+ questions: [],
+ ...(answered
+ ? { questionAnswer: { requestId, answers: { color: "Blue" }, attachmentsByQuestionId: {} } }
+ : {}),
+ });
+ const answer: OrchestrationV2TurnItem = {
+ ...user("answer", 40, runs[1]),
+ messageId: MessageId.make(`async-answer:${requestId}`),
+ };
+ const delegation: OrchestrationV2TurnItem = {
+ ...item("delegation", 3, runs[0]),
+ type: "dynamic_tool",
+ toolName: "t3-code.delegate_task",
+ input: { task: "Check" },
+ output: { taskId: "child" },
+ };
+ const lateChild: OrchestrationV2TurnItem = {
+ ...item("late-child", 30, runs[0]),
+ type: "subagent",
+ subagentId: NodeId.make("child"),
+ origin: "app_owned",
+ driver: ProviderDriverKind.make("codex"),
+ providerInstanceId: ProviderInstanceId.make("codex"),
+ childThreadId: sourceThreadId,
+ prompt: "Check",
+ result: "Fine",
+ };
+ const resumed: OrchestrationV2TurnItem = {
+ ...lateChild,
+ ...item("resumed", 3, runs[2]),
+ subagentId: NodeId.make("resumed"),
+ origin: "provider_native",
+ childThreadId: null,
+ };
+ const history: OrchestrationV2TurnItem[] = [
+ user("u1", 1, runs[0]),
+ shell("s1", 2, runs[0]),
+ delegation,
+ reply("a1", 4, runs[0]),
+ user("u2", 10, runs[1]),
+ shell("s2", 11, runs[1]),
+ question(false),
+ reply("a2", 13, runs[1]),
+ user("u3", 20, runs[2]),
+ shell("s3", 21, runs[2]),
+ ];
+ const running = {
+ runId: runs[2],
+ status: "running" as const,
+ startedAt: at(20),
+ completedAt: null,
+ };
+ const settled = { ...running, status: "completed" as const, completedAt: at(50) };
+ // Each step is what one streamed event leaves behind, including the edits
+ // that reach back into earlier runs.
+ const steps: ReadonlyArray<{
+ readonly items: ReadonlyArray<OrchestrationV2TurnItem>;
+ readonly latestRun: ThreadFeedLatestRun;
+ }> = [
+ { items: [...history, reply("a3", 22, runs[2], "W", true)], latestRun: running },
+ { items: [...history, reply("a3", 22, runs[2], "Wor", true)], latestRun: running },
+ {
+ items: [...history, reply("a3", 22, runs[2], "Working", true), shell("s4", 23, runs[2])],
+ latestRun: running,
+ },
+ {
+ items: [
+ ...history,
+ reply("a3", 22, runs[2], "Working", true),
+ shell("s4", 23, runs[2]),
+ lateChild,
+ ],
+ latestRun: running,
+ },
+ {
+ items: [
+ ...history.map((entry) => (entry.id === "question" ? question(true) : entry)),
+ reply("a3", 22, runs[2], "Working", true),
+ shell("s4", 23, runs[2]),
+ lateChild,
+ answer,
+ ],
+ latestRun: running,
+ },
+ {
+ items: [
+ ...history.slice(0, 9),
+ shell("inserted", 20, runs[2]),
+ ...history.slice(9),
+ reply("a3", 22, runs[2], "Working", true),
+ shell("s4", 23, runs[2]),
+ ],
+ latestRun: running,
+ },
+ {
+ items: [...history, reply("a3", 22, runs[2], "Working on it"), shell("s4", 23, runs[2])],
+ latestRun: running,
+ },
+ {
+ items: [...history, reply("a3", 22, runs[2], "Working on it"), shell("s4", 23, runs[2])],
+ latestRun: settled,
+ },
+ {
+ items: [
+ ...history,
+ reply("a3", 22, runs[2], "Working on it"),
+ shell("s4", 23, runs[2]),
+ shell("late-s1", 45, runs[0]),
+ ],
+ latestRun: settled,
+ },
+ // The first run's fold above was timed to the late item; dropping it must reach back too.
+ {
+ items: [...history, reply("a3", 22, runs[2], "Working on it"), shell("s4", 23, runs[2])],
+ latestRun: settled,
+ },
+ // The latest run resumes a subagent from the first run: the item moves to
+ // the latest run but keeps its place, so it folds with the first run.
+ {
+ items: [
+ ...history.slice(0, 3),
+ resumed,
+ ...history.slice(3),
+ reply("a3", 22, runs[2], "Working on it"),
+ shell("s4", 23, runs[2]),
+ ],
+ latestRun: running,
+ },
+ {
+ items: [
+ ...history.slice(0, 3),
+ resumed,
+ ...history.slice(3),
+ reply("a3", 22, runs[2], "Working on it"),
+ shell("s4", 23, runs[2]),
+ reply("a4", 24, runs[2], "Still", true),
+ ],
+ latestRun: running,
+ },
+ ];
+ // Like the projection reducer, an unchanged item at an unchanged position keeps its row.
+ const rowsByItem = new Map<
+ OrchestrationV2TurnItem,
+ Map<number, OrchestrationV2ProjectedTurnItem>
+ >();
+ const row = (entry: OrchestrationV2TurnItem, position: number) => {
+ const byPosition = rowsByItem.get(entry) ?? new Map<number, OrchestrationV2ProjectedTurnItem>();
+ rowsByItem.set(entry, byPosition);
+ const cached = byPosition.get(position) ?? projected(entry, position);
+ byPosition.set(position, cached);
+ return cached;
+ };
+ const present = (
+ step: (typeof steps)[number],
+ expandedRunIds: ReadonlySet<RunId>,
+ cache?: ThreadFeedCache,
+ ) =>
+ deriveThreadFeedPresentation(
+ buildThreadFeed(step.items.map(row), { cache }),
+ step.latestRun,
+ expandedRunIds,
+ new Set(),
+ step.latestRun.status === "running" ? at(20) : null,
+ false,
+ cache,
+ );
+
+ it.each([
+ { folds: "collapsed", expandedRunIds: new Set<RunId>() },
+ { folds: "expanded", expandedRunIds: new Set<RunId>(runs) },
+ ])("matches a fresh build after every update with $folds runs", ({ expandedRunIds }) => {
+ const cache = createThreadFeedCache();
+ const streamed = steps.map((step) => present(step, expandedRunIds, cache));
+ const fresh = steps.map((step) => present(step, expandedRunIds));
+ // Closures on activities are not part of what a row shows.
+ const values = (rows: ReadonlyArray<ThreadFeedEntry>) => JSON.parse(JSON.stringify(rows));
+ for (const [index, rows] of streamed.entries()) {
+ expect(values(rows), `step ${index}`).toEqual(values(fresh[index]!));
+ }
+ });
+
+ it("hides a delegation once its child reaches back into the earlier run", () => {
+ const showsDelegation = (step: (typeof steps)[number]) =>
+ buildThreadFeed(step.items.map(row)).some(
+ (entry) =>
+ entry.type === "activity-group" &&
+ entry.activities.some((activity) => activity.projectedItem.item.id === "delegation"),
+ );
+ expect(showsDelegation(steps[2]!)).toBe(true);
+ expect(showsDelegation(steps[3]!)).toBe(false);
+ });
+});
diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts
index 631c2639357..ff68fa56f2e 100644
--- a/apps/mobile/src/lib/threadActivity.ts
+++ b/apps/mobile/src/lib/threadActivity.ts
@@ -887,16 +887,15 @@ function isEmptyMessage(entry: RawThreadFeedEntry): boolean {
);
}
-function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): ThreadFeedEntry[] {
- const childrenByRun = new Map<RunId, Set<string>>();
- for (const entry of entries) {
- if (entry.type !== "activity") continue;
- const item = entry.activity.projectedItem.item;
- if (item.type !== "subagent" || item.origin !== "app_owned" || item.runId === null) continue;
- const children = childrenByRun.get(item.runId) ?? new Set<string>();
- children.add(item.subagentId);
- childrenByRun.set(item.runId, children);
- }
+/**
+ * `onRestart` hears each entry after which no group is open, with the grouped
+ * length so far: the entries before it group the same whatever follows.
+ */
+function groupAdjacentActivities(
+ entries: ReadonlyArray<RawThreadFeedEntry>,
+ childrenByRun: ReadonlyMap<RunId, ReadonlySet<string>>,
+ onRestart?: (entryIndex: number, groupedLength: number) => void,
+): ThreadFeedEntry[] {
const grouped: ThreadFeedEntry[] = [];
let firstActivityEntry: Extract<RawThreadFeedEntry, { readonly type: "activity" }> | null = null;
let openGroupActivities: ThreadFeedActivity[] = [];
@@ -924,7 +923,8 @@ function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): Th
openGroupActivities = [];
};
- for (const entry of entries) {
+ for (let entryIndex = 0; entryIndex < entries.length; entryIndex += 1) {
+ const entry = entries[entryIndex]!;
if (entry.type === "activity") {
const item = entry.activity.projectedItem.item;
if (
@@ -950,6 +950,7 @@ function groupAdjacentActivities(entries: ReadonlyArray<RawThreadFeedEntry>): Th
if (entry.type !== "activity") {
flushGroup();
grouped.push(entry);
+ onRestart?.(entryIndex, grouped.length);
continue;
}
@@ -1245,6 +1246,79 @@ function settleSupersededReasoning(
return settled;
}
+interface ThreadFeedPresentationBuild {
+ readonly feed: ReadonlyArray<ThreadFeedEntry>;
+ readonly latestRun: ThreadFeedLatestRun | null;
+ readonly expandedRunIds: ReadonlySet<RunId>;
+ readonly expandedWorkGroupIds: ReadonlySet<string>;
+ readonly activeWorkStartedAt: string | null;
+ readonly runlessWorkActive: boolean;
+ readonly rows: ReadonlyArray<ThreadFeedEntry>;
+ /** Feed entry `entry` is a user message whose rows start at `rowsLength`. */
+ readonly restarts: ReadonlyArray<{ readonly entry: number; readonly rowsLength: number }>;
+ /** Where each run's entries begin, so a reused prefix never shares a run with the rest. */
+ readonly firstEntryByRun: ReadonlyMap<RunId, number>;
+}
+
+function latestRunsEqual(left: ThreadFeedLatestRun | null, right: ThreadFeedLatestRun | null) {
+ return (
+ left === right ||
+ (left !== null &&
+ right !== null &&
+ left.runId === right.runId &&
+ left.status === right.status &&
+ left.startedAt === right.startedAt &&
+ left.completedAt === right.completedAt &&
+ left.turnEnded === right.turnEnded)
+ );
+}
+
+function feedEntryRunId(entry: ThreadFeedEntry): RunId | null {
+ return entry.type === "message" ? (entry.message.runId ?? null) : entry.runId;
+}
+
+function isUserMessageEntry(entry: ThreadFeedEntry | undefined): boolean {
+ return entry?.type === "message" && entry.message.role === "user";
+}
+
+/**
+ * A user message starts every fold and is never hidden or grouped, so the
+ * rows before it depend only on the entries before it, their runs, and the
+ * shared inputs. Returns the user message entry to restart from, or null to
+ * present the whole feed.
+ */
+function presentationRestart(
+ previous: ThreadFeedPresentationBuild | null,
+ feed: ReadonlyArray<ThreadFeedEntry>,
+ latestRun: ThreadFeedLatestRun | null,
+ expandedRunIds: ReadonlySet<RunId>,
+ expandedWorkGroupIds: ReadonlySet<string>,
+ activeWorkStartedAt: string | null,
+ runlessWorkActive: boolean,
+): { readonly entry: number; readonly rowsLength: number; readonly index: number } | null {
+ if (
+ previous === null ||
+ !latestRunsEqual(previous.latestRun, latestRun) ||
+ previous.activeWorkStartedAt !== activeWorkStartedAt ||
+ previous.runlessWorkActive !== runlessWorkActive ||
+ !setsEqual(previous.expandedRunIds, expandedRunIds) ||
+ !setsEqual(previous.expandedWorkGroupIds, expandedWorkGroupIds)
+ ) {
+ return null;
+ }
+ const firstChanged = firstChangedIndex(previous.feed, feed);
+ let index = previous.restarts.length - 1;
+ while (index >= 0 && previous.restarts[index]!.entry > firstChanged) index -= 1;
+ const restart = previous.restarts[index];
+ if (restart === undefined || !isUserMessageEntry(feed[restart.entry])) return null;
+ for (let entryIndex = restart.entry; entryIndex < feed.length; entryIndex += 1) {
+ const runId = feedEntryRunId(feed[entryIndex]!);
+ const firstEntry = runId === null ? undefined : previous.firstEntryByRun.get(runId);
+ if (firstEntry !== undefined && firstEntry < restart.entry) return null;
+ }
+ return { ...restart, index };
+}
+
export function deriveThreadFeedPresentation(
feed: ReadonlyArray<ThreadFeedEntry>,
latestRun: ThreadFeedLatestRun | null,
@@ -1252,11 +1326,42 @@ export function deriveThreadFeedPresentation(
expandedWorkGroupIds: ReadonlySet<string> = new Set(),
activeWorkStartedAt: string | null = null,
runlessWorkActive = false,
+ cache?: ThreadFeedCache,
): ThreadFeedEntry[] {
- const retainedFeed = feed.filter(
- (entry) =>
- entry.type !== "run-fold" && entry.type !== "work-toggle" && entry.type !== "thinking",
+ const previous = cache?.presentation ?? null;
+ const restart = presentationRestart(
+ previous,
+ feed,
+ latestRun,
+ expandedRunIds,
+ expandedWorkGroupIds,
+ activeWorkStartedAt,
+ runlessWorkActive,
);
+ const start = restart?.entry ?? 0;
+ const result: ThreadFeedEntry[] =
+ restart === null ? [] : previous!.rows.slice(0, restart.rowsLength);
+ const restarts = restart === null ? [] : previous!.restarts.slice(0, restart.index);
+ const firstEntryByRun = new Map<RunId, number>();
+ if (restart !== null) {
+ for (const [runId, entry] of previous!.firstEntryByRun) {
+ if (entry < start) firstEntryByRun.set(runId, entry);
+ }
+ }
+ const tailStart = result.length;
+ const lastEntryByRun = new Map<RunId, number>();
+
+ const retainedFeed: Array<
+ Exclude<ThreadFeedEntry, { readonly type: "run-fold" | "work-toggle" | "thinking" }>
+ > = [];
+ const retainedFeedIndices: number[] = [];
+ for (let index = start; index < feed.length; index += 1) {
+ const entry = feed[index]!;
+ if (entry.type === "run-fold" || entry.type === "work-toggle" || entry.type === "thinking")
+ continue;
+ retainedFeed.push(entry);
+ retainedFeedIndices.push(index);
+ }
const sourceFeed = retainedFeed.map((entry, index) =>
settleSupersededReasoning(entry, index === retainedFeed.length - 1),
);
@@ -1276,8 +1381,17 @@ export function deriveThreadFeedPresentation(
for (const entryId of fold.hiddenEntryIds) collapsedEntryIds.add(entryId);
}
}
- const result: ThreadFeedEntry[] = [];
- for (const entry of sourceFeed) {
+ for (let sourceIndex = 0; sourceIndex < sourceFeed.length; sourceIndex += 1) {
+ const entry = sourceFeed[sourceIndex]!;
+ const feedIndex = retainedFeedIndices[sourceIndex]!;
+ if (isUserMessageEntry(entry)) {
+ restarts.push({ entry: feedIndex, rowsLength: result.length });
+ }
+ const runId = feedEntryRunId(entry);
+ if (runId !== null) {
+ if (!firstEntryByRun.has(runId)) firstEntryByRun.set(runId, feedIndex);
+ lastEntryByRun.set(runId, feedIndex);
+ }
const isActiveTailGroup =
isWorking &&
(activeRunId !== null || runlessWorkActive) &&
@@ -1356,15 +1470,51 @@ export function deriveThreadFeedPresentation(
) {
result.push(thinkingRow(activeWorkStartedAt, activeRunId));
}
- return result.map((row, index) => {
- if (!isWorkLogFeedRow(row) || !isWorkLogFeedRow(result[index + 1])) return row;
+ // Reused rows are final: the user message after them never continues a work log.
+ for (let index = tailStart; index < result.length; index += 1) {
+ const row = result[index]!;
+ if (!isWorkLogFeedRow(row) || !isWorkLogFeedRow(result[index + 1])) continue;
let continued = continuedWorkLogRows.get(row);
if (!continued) {
continued = { ...row, continuesWorkLog: true };
continuedWorkLogRows.set(row, continued);
}
- return continued;
+ result[index] = continued;
+ }
+ // A run that crosses a user message made the rows before it from entries
+ // after it, so a later build cannot restart there even once those entries
+ // are gone. Only runs of this build's own entries can cross its restarts.
+ const crossings = Array.from({ length: feed.length - start + 1 }, () => 0);
+ for (const [runId, last] of lastEntryByRun) {
+ const first = firstEntryByRun.get(runId)!;
+ if (first >= last) continue;
+ crossings[first - start + 1]! += 1;
+ crossings[last - start + 1]! -= 1;
+ }
+ let crossingRuns = 0;
+ let crossingIndex = 0;
+ const cleanRestarts = restarts.filter((candidate) => {
+ if (candidate.entry < start) return true;
+ while (crossingIndex <= candidate.entry - start) {
+ crossingRuns += crossings[crossingIndex]!;
+ crossingIndex += 1;
+ }
+ return crossingRuns === 0;
});
+ if (cache) {
+ cache.presentation = {
+ feed,
+ latestRun,
+ expandedRunIds,
+ expandedWorkGroupIds,
+ activeWorkStartedAt,
+ runlessWorkActive,
+ rows: result,
+ restarts: cleanRestarts,
+ firstEntryByRun,
+ };
+ }
+ return result;
}
const continuedWorkLogRows = new WeakMap<ThreadFeedEntry, ThreadFeedEntry>();
@@ -1744,15 +1894,69 @@ export function buildPendingUserInputAnswers(
return answers;
}
+interface ThreadFeedBuild {
+ readonly rows: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
+ readonly attempts: ReadonlyArray<OrchestrationV2RunAttempt> | undefined;
+ readonly nodes: ReadonlyArray<OrchestrationV2ExecutionNode> | undefined;
+ readonly foldedAnswerMessageIds: ReadonlySet<string>;
+ readonly delegatedChildrenByRun: ReadonlyMap<RunId, ReadonlySet<string>>;
+ readonly feed: ReadonlyArray<ThreadFeedEntry>;
+ /** Grouping is empty before `row`: the rows before it produced `feed.slice(0, feedLength)`. */
+ readonly restarts: ReadonlyArray<{ readonly row: number; readonly feedLength: number }>;
+}
+
+/**
+ * A streamed chunk changes the newest rows of a thread that can hold thousands.
+ * A consumer that keeps one cache across renders lets `buildThreadFeed` and
+ * `deriveThreadFeedPresentation` keep the unchanged prefix of their last
+ * result instead of redoing the whole thread. Each feed on screen owns its
+ * cache, so two threads rendering at once never evict each other.
+ */
+export interface ThreadFeedCache {
+ feedBuild: ThreadFeedBuild | null;
+ presentation: ThreadFeedPresentationBuild | null;
+}
+
+export function createThreadFeedCache(): ThreadFeedCache {
+ return { feedBuild: null, presentation: null };
+}
+
+function setsEqual<T>(left: ReadonlySet<T>, right: ReadonlySet<T>): boolean {
+ if (left.size !== right.size) return false;
+ for (const value of left) if (!right.has(value)) return false;
+ return true;
+}
+
+function setMapsEqual<K, V>(
+ left: ReadonlyMap<K, ReadonlySet<V>>,
+ right: ReadonlyMap<K, ReadonlySet<V>>,
+): boolean {
+ if (left.size !== right.size) return false;
+ for (const [key, values] of left) {
+ const other = right.get(key);
+ if (other === undefined || !setsEqual(values, other)) return false;
+ }
+ return true;
+}
+
+/** Index of the first entry that differs, or the shorter length when one extends the other. */
+function firstChangedIndex<T>(previous: ReadonlyArray<T>, next: ReadonlyArray<T>): number {
+ const limit = Math.min(previous.length, next.length);
+ let index = 0;
+ while (index < limit && previous[index] === next[index]) index += 1;
+ return index;
+}
+
export function buildThreadFeed(
visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
options?: {
readonly anchoredMessages?: ReadonlyArray<LocalThreadMessage>;
readonly attempts?: ReadonlyArray<OrchestrationV2RunAttempt>;
readonly nodes?: ReadonlyArray<OrchestrationV2ExecutionNode>;
+ readonly cache?: ThreadFeedCache;
},
): ThreadFeedEntry[] {
- const entries: RawThreadFeedEntry[] = [];
+ const anchoredMessages = options?.anchoredMessages ?? [];
const attemptByRootNodeId = new Map(
(options?.attempts ?? []).map((attempt) => [attempt.rootNodeId, attempt] as const),
);
@@ -1773,14 +1977,45 @@ export function buildThreadFeed(
}
return null;
};
- const foldedAnswerMessageIds = new Set(
- visibleTurnItems.flatMap(({ item }) =>
- item.type === "user_input_request" && item.questionAnswer
- ? [`async-answer:${item.questionAnswer.requestId}`]
- : [],
- ),
- );
- for (const row of visibleTurnItems) {
+ // Thread-wide facts that change rows anywhere in the feed. A cached prefix
+ // is reused only while these match the build that produced it.
+ const foldedAnswerMessageIds = new Set<string>();
+ const delegatedChildrenByRun = new Map<RunId, Set<string>>();
+ for (const { item } of visibleTurnItems) {
+ if (item.type === "user_input_request" && item.questionAnswer) {
+ foldedAnswerMessageIds.add(`async-answer:${item.questionAnswer.requestId}`);
+ } else if (item.type === "subagent" && item.origin === "app_owned" && item.runId !== null) {
+ const children = delegatedChildrenByRun.get(item.runId) ?? new Set<string>();
+ children.add(item.subagentId);
+ delegatedChildrenByRun.set(item.runId, children);
+ }
+ }
+
+ const cache = options?.cache;
+ const previous = cache?.feedBuild ?? null;
+ let restartIndex = -1;
+ if (
+ previous !== null &&
+ anchoredMessages.length === 0 &&
+ previous.attempts === options?.attempts &&
+ previous.nodes === options?.nodes &&
+ setsEqual(previous.foldedAnswerMessageIds, foldedAnswerMessageIds) &&
+ setMapsEqual(previous.delegatedChildrenByRun, delegatedChildrenByRun)
+ ) {
+ const firstChanged = firstChangedIndex(previous.rows, visibleTurnItems);
+ restartIndex = previous.restarts.length - 1;
+ while (restartIndex >= 0 && previous.restarts[restartIndex]!.row > firstChanged) {
+ restartIndex -= 1;
+ }
+ }
+ const restart = restartIndex === -1 ? null : previous!.restarts[restartIndex]!;
+ const prefix = restart === null ? [] : previous!.feed.slice(0, restart.feedLength);
+ const restarts = restart === null ? [] : previous!.restarts.slice(0, restartIndex + 1);
+
+ const entries: RawThreadFeedEntry[] = [];
+ const entryRows: number[] = [];
+ for (let index = restart?.row ?? 0; index < visibleTurnItems.length; index += 1) {
+ const row = visibleTurnItems[index]!;
const item = row.item;
if (turnItemIsWorkspacePreparation(item)) continue;
if (item.type === "todo_list" || item.type === "checkpoint") continue;
@@ -1792,6 +2027,7 @@ export function buildThreadFeed(
const cached = projectedEntriesCache.get(row);
if (cached?.attemptId === attemptId) {
entries.push(cached.entry);
+ entryRows.push(index);
continue;
}
const createdAt = DateTime.formatIso(item.startedAt ?? item.updatedAt);
@@ -1809,6 +2045,7 @@ export function buildThreadFeed(
};
projectedEntriesCache.set(row, { attemptId, entry });
entries.push(entry);
+ entryRows.push(index);
continue;
}
const app =
@@ -1828,6 +2065,7 @@ export function buildThreadFeed(
};
projectedEntriesCache.set(row, { attemptId, entry });
entries.push(entry);
+ entryRows.push(index);
continue;
}
if (item.type === "user_message" || item.type === "assistant_message") {
@@ -1862,6 +2100,7 @@ export function buildThreadFeed(
};
projectedEntriesCache.set(row, { attemptId, entry });
entries.push(entry);
+ entryRows.push(index);
continue;
}
const activity = toFeedActivity(row, attemptId);
@@ -1874,6 +2113,7 @@ export function buildThreadFeed(
};
projectedEntriesCache.set(row, { attemptId, entry });
entries.push(entry);
+ entryRows.push(index);
}
const retainedMessageIds = new Set([
...foldedAnswerMessageIds,
@@ -1903,7 +2143,7 @@ export function buildThreadFeed(
localMessageEntriesCache.set(message, entry);
return entry;
};
- for (const message of options?.anchoredMessages ?? []) {
+ for (const message of anchoredMessages) {
if (retainedMessageIds.has(message.id)) continue;
retainedMessageIds.add(message.id);
const entry = appendLocalMessage(message);
@@ -1913,5 +2153,32 @@ export function buildThreadFeed(
if (insertionIndex === -1) entries.push(entry);
else entries.splice(insertionIndex, 0, entry);
}
- return groupAdjacentActivities(entries);
+ const grouped = groupAdjacentActivities(
+ entries,
+ delegatedChildrenByRun,
+ // Anchored messages shift entries away from their rows; such a build is not reused.
+ anchoredMessages.length > 0
+ ? undefined
+ : (entryIndex, groupedLength) =>
+ restarts.push({
+ row: entryRows[entryIndex]! + 1,
+ feedLength: prefix.length + groupedLength,
+ }),
+ );
+ const feed = prefix.length === 0 ? grouped : prefix.concat(grouped);
+ if (cache) {
+ cache.feedBuild =
+ anchoredMessages.length > 0
+ ? null
+ : {
+ rows: visibleTurnItems,
+ attempts: options?.attempts,
+ nodes: options?.nodes,
+ foldedAnswerMessageIds,
+ delegatedChildrenByRun,
+ feed,
+ restarts,
+ };
+ }
+ return feed;
}
diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts
index bb2be14282e..c33cf3267fe 100644
--- a/apps/mobile/src/state/use-thread-composer-state.ts
+++ b/apps/mobile/src/state/use-thread-composer-state.ts
@@ -55,7 +55,7 @@ import {
} from "../lib/composerImages";
import type { DraftComposerImageAttachment } from "../lib/composerImages";
import { scopedThreadKey } from "../lib/scopedEntities";
-import { buildThreadFeed } from "../lib/threadActivity";
+import { buildThreadFeed, createThreadFeedCache } from "../lib/threadActivity";
import { acknowledgedThreadMessagesAtom } from "./acknowledged-thread-messages";
import { appendPendingThreadMessages } from "../features/threads/pending-thread-feed";
import { threadAllowsProviderSwitch } from "./thread-provider-switching";
@@ -245,6 +245,7 @@ export function useThreadComposerState() {
// detail is usually present but empty during a worktree checkout, so this
// cannot be an either/or with the loaded messages.
const pendingCreationMessage = selectedThreadCreation?.message ?? null;
+ const [feedCache] = useState(createThreadFeedCache);
const selectedThreadFeed = (() => {
const pendingCreation =
pendingCreationMessage !== null &&
@@ -255,6 +256,7 @@ export function useThreadComposerState() {
anchoredMessages: pendingCreation,
attempts: selectedThreadAttempts,
nodes: selectedThreadNodes,
+ cache: feedCache,
});
const pendingAcknowledgments = acknowledgedMessages.filter(
(message) =>
diff --git a/packages/client-runtime/src/state/orchestrationV2Projection.test.ts b/packages/client-runtime/src/state/orchestrationV2Projection.test.ts
index eb7a6217c77..ed6479b24e8 100644
--- a/packages/client-runtime/src/state/orchestrationV2Projection.test.ts
+++ b/packages/client-runtime/src/state/orchestrationV2Projection.test.ts
@@ -304,6 +304,74 @@ describe("applyOrchestrationV2ProjectionEvent", () => {
expect(next?.visibleTurnItems.map((row) => row.position)).toEqual([0, 1]);
});
+ it("moves an updated item to its new ordinal and renumbers the rows it passes", () => {
+ const inherited = {
+ ...commandItem("item-inherited", "parent", 0),
+ threadId: ThreadId.make("parent"),
+ };
+ const items = [
+ commandItem("item-a", "a", 1),
+ commandItem("item-b", "b", 2),
+ commandItem("item-c", "c", 2),
+ ];
+ const rows = [
+ {
+ position: 0,
+ visibility: "inherited" as const,
+ sourceThreadId: inherited.threadId,
+ sourceItemId: inherited.id,
+ item: inherited,
+ },
+ ...items.map((item, index) => ({
+ position: index + 1,
+ visibility: "local" as const,
+ sourceThreadId: threadId,
+ sourceItemId: item.id,
+ item,
+ })),
+ ];
+ const moved = commandItem("item-a", "moved", 2);
+ const next = applyOrchestrationV2ProjectionEvent(
+ { ...emptyProjection, runs: [run], turnItems: items, visibleTurnItems: rows },
+ {
+ id: "event-move",
+ type: "turn-item.updated",
+ threadId,
+ runId,
+ occurredAt: now,
+ payload: moved,
+ } as OrchestrationV2DomainEvent,
+ );
+
+ // Equal ordinals order by id, so item-a stays ahead of item-b.
+ expect(next?.visibleTurnItems.map((row) => [row.item.id, row.position])).toEqual([
+ ["item-inherited", 0],
+ ["item-a", 1],
+ ["item-b", 2],
+ ["item-c", 3],
+ ]);
+ expect(next?.visibleTurnItems[0]).toBe(rows[0]);
+ expect(next?.visibleTurnItems[1]?.item).toBe(moved);
+ expect(next?.turnItems.map((item) => item.id)).toEqual(["item-a", "item-b", "item-c"]);
+
+ const later = commandItem("item-a", "later", 3);
+ const last = applyOrchestrationV2ProjectionEvent(next, {
+ id: "event-move-later",
+ type: "turn-item.updated",
+ threadId,
+ runId,
+ occurredAt: now,
+ payload: later,
+ } as OrchestrationV2DomainEvent);
+ expect(last?.visibleTurnItems.map((row) => [row.item.id, row.position])).toEqual([
+ ["item-inherited", 0],
+ ["item-b", 1],
+ ["item-c", 2],
+ ["item-a", 3],
+ ]);
+ expect(last?.turnItems.at(0)).toBe(later);
+ });
+
describe("partial timeline", () => {
const queuedRunId = RunId.make("run-queued");
const steerRunId = RunId.make("run-steer");
diff --git a/packages/client-runtime/src/state/orchestrationV2Projection.ts b/packages/client-runtime/src/state/orchestrationV2Projection.ts
index c93044e93f2..d954e8a1eda 100644
--- a/packages/client-runtime/src/state/orchestrationV2Projection.ts
+++ b/packages/client-runtime/src/state/orchestrationV2Projection.ts
@@ -152,7 +152,10 @@ function upsertVisibleTurnItem(
latestLocalTurnOrdinal: number | null | undefined,
): OrchestrationV2ThreadProjection["visibleTurnItems"] {
const rows = projection.visibleTurnItems;
- const index = rows.findIndex((row) => row.sourceItemId === item.id);
+ // Streamed updates land on the newest rows. Item ids are unique, so the
+ // search can start there.
+ let index = rows.length - 1;
+ while (index >= 0 && rows[index]!.sourceItemId !== item.id) index -= 1;
const next = {
position: 0,
visibility: "local" as const,
@@ -177,16 +180,34 @@ function upsertVisibleTurnItem(
) {
return rows;
}
- const updated = index === -1 ? [...rows] : [...rows.slice(0, index), ...rows.slice(index + 1)];
- const insertionIndex = updated.findIndex(
- (row) =>
+ // The item goes before the first later local row, as if its old row were
+ // removed first. One pass builds and renumbers the result: this runs for
+ // every streamed chunk of a thread that can hold thousands of rows.
+ let insertion = rows.length;
+ for (let candidate = 0; candidate < rows.length; candidate += 1) {
+ const row = rows[candidate]!;
+ if (
+ candidate !== index &&
row.visibility === "local" &&
(row.item.ordinal > item.ordinal ||
(row.item.ordinal === item.ordinal &&
- String(row.item.id).localeCompare(String(item.id)) > 0)),
- );
- updated.splice(insertionIndex === -1 ? updated.length : insertionIndex, 0, next);
- return renumberVisibleItems(updated);
+ String(row.item.id).localeCompare(String(item.id)) > 0))
+ ) {
+ insertion = candidate;
+ break;
+ }
+ }
+ const updated: Array<(typeof rows)[number]> = [];
+ for (let source = 0; source < rows.length; source += 1) {
+ if (source === insertion) updated.push(next);
+ if (source !== index) updated.push(rows[source]!);
+ }
+ if (insertion === rows.length) updated.push(next);
+ for (let position = 0; position < updated.length; position += 1) {
+ const row = updated[position]!;
+ if (row.position !== position) updated[position] = { ...row, position };
+ }
+ return updated;
}
export function applyOrchestrationV2ProjectionEvent(
@@ -293,17 +314,25 @@ export function applyOrchestrationV2ProjectionEvent(
case "plan.updated":
return { ...base, plans: upsertEntity(base.plans, event.payload) };
case "turn-item.updated": {
+ // Streamed updates land on the newest items, so search from the end.
+ let itemIndex = projection.turnItems.length - 1;
+ while (itemIndex >= 0 && projection.turnItems[itemIndex]!.id !== event.payload.id) {
+ itemIndex -= 1;
+ }
if (
partialTimeline &&
- !projection.turnItems.some((candidate) => candidate.id === event.payload.id) &&
+ itemIndex === -1 &&
shouldDropMissingPartialTurnItem(projection, event.payload, latestLocalTurnOrdinal)
) {
return projection;
}
- const next = { ...base, turnItems: upsertEntity(base.turnItems, event.payload) };
+ const turnItems = [...projection.turnItems];
+ if (itemIndex === -1) turnItems.push(event.payload);
+ else turnItems[itemIndex] = event.payload;
+ const next = { ...base, turnItems };
// Only interrupt requests can change another item's visibility. Streaming
// text/tool updates must not recheck every row against every run.
- const previous = projection.turnItems.find((item) => item.id === event.payload.id);
+ const previous = itemIndex === -1 ? undefined : projection.turnItems[itemIndex];
const visible =
event.payload.type === "run_interrupt_request" || previous?.type === "run_interrupt_request"
? { ...next, visibleTurnItems: activeVisibleTurnItems(next) }