fix(server): load long thread history in bounded pages #26240
main fromrefs/pull/26240/headmerged by Yash-Singh1(GitHub profile, opens in a new tab) View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- packages/client-runtime/src/state/threads.ts line 753OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -660,2 +733,21 @@660733 throughEntryId?: string,661734 ) {735+ const revealTarget = Effect.fn("EnvironmentThreadState.revealHistoryTarget")(function* () {736+ if (throughEntryId === undefined) return;737+ const visible =738+ Option.getOrNull((yield* SubscriptionRef.get(state)).data)?.visibleTurnItems ?? [];739+ const hasTarget = () =>740+ SubscriptionRef.get(state).pipe(741+ Effect.map(742+ (current) =>743+ Option.getOrNull(current.data)?.visibleTurnItems.some(744+ ({ item }) =>745+ item.id === throughEntryId ||746+ ("messageId" in item && item.messageId === throughEntryId),747+ ) === true,748+ ),749+ );750+ if (yield* hasTarget()) return;751+ for (const row of visible) {752+ if (row.item.deferredWork === undefined) continue;753+ const result = yield* loadWork(row.sourceItemId);apps/server/src/orchestration-v2/ProjectionStore.ts line 2989Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -3123,7 +3173,11 @@31233173 -- CROSS JOIN keeps the sorted IDs as the outer loop, so SQLite31243174 -- skips sorting again once the payloads are attached. Carry the31253175 -- rowid through selection to avoid a second string-key index lookup.3126- SELECT item.payload_json3176+ SELECT item.payload_json, tail.turn_item_id AS work_last_id,3177+ deferred.last_ordinal AS work_last_ordinal, deferred.item_count AS work_item_count31273178 FROM retained31283179 CROSS JOIN orchestration_v2_projection_turn_items AS item31293180 ON item.rowid = retained.item_rowid3181+ LEFT JOIN deferred_work deferred ON deferred.run_id = item.run_id3182+ AND deferred.first_ordinal = item.ordinal3183+ LEFT JOIN orchestration_v2_projection_turn_items tail
- apps/mobile/src/features/threads/ThreadFeed.tsx line 1262OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1234,0 +1242,21 @@1242+}: {1243+ entry: Extract<ThreadFeedEntry, { type: "run-fold" }>;1244+ environmentId: EnvironmentId;1245+ threadId: ThreadId;1246+ onToggle: (runId: RunId) => void;1247+ rowSizing: ReturnType<typeof deriveThreadWorkLogSizing>;1248+ iconColor: ColorValue;1249+}) {1250+ const loadWork = useAtomCommand(threadEnvironment.loadWorkHistory, { reportFailure: false });1251+ const anchorsKey = entry.deferredWorkItemIds?.join("\n") ?? "";1252+ const [failure, setFailure] = useState<{ attempt: number; message: string } | null>(null);1253+ const [retry, setRetry] = useState(0);1254+ const error = anchorsKey && failure?.attempt === retry ? failure.message : null;1255+ const loading = entry.expanded && anchorsKey !== "" && error === null;1256+ const requestWork = useEffectEvent(1257+ (anchorIds: string[], environmentId: EnvironmentId, threadId: ThreadId) =>1258+ Promise.all(1259+ anchorIds.map((anchorId) => loadWork({ environmentId, input: { threadId, anchorId } })),1260+ ),1261+ );1262+ // oxlint-disable-next-line t3code/react-effect-budget -- Expanded folds restore their deferred server history.apps/web/src/components/chat/MessagesTimeline.tsx line 1574OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1552,3 +1556,19 @@1552155615531557 function TurnFoldTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "turn-fold" }> }) {15541558 const ctx = use(TimelineRowCtx);1559+ const loadWork = useAtomCommand(threadEnvironment.loadWorkHistory, { reportFailure: false });1560+ const ref = parseScopedThreadKey(ctx.routeThreadKey);1561+ const environmentId = ref?.environmentId;1562+ const threadId = ref?.threadId;1563+ const anchorsKey = row.deferredWorkItemIds?.join("\n") ?? "";1564+ const [failure, setFailure] = useState<{ attempt: number; message: string } | null>(null);1565+ const [retry, setRetry] = useState(0);1566+ const error = anchorsKey && failure?.attempt === retry ? failure.message : null;1567+ const loading = row.expanded && anchorsKey !== "" && error === null;1568+ const requestWork = useEffectEvent(1569+ (anchorIds: string[], environmentId: EnvironmentId, threadId: ThreadId) =>1570+ Promise.all(1571+ anchorIds.map((anchorId) => loadWork({ environmentId, input: { threadId, anchorId } })),1572+ ),1573+ );1574+ // oxlint-disable-next-line t3code/react-effect-budget -- Expanded folds restore their deferred server history.
- apps/server/src/orchestration-v2/ProjectionStore.ts line 7912OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -7742,4 +7894,19 @@7894+ items: visible,7895+ cursor,7896+ throughEntryId,7897+ snapshotSequence,7898+ })7899+ : selectHistoryPageFromCursor({7900+ items:7901+ workMode === "deferred"7902+ ? deferWorkHistoryRows(visible, projection.runs)7903+ : visible,7904+ cursor,7905+ throughEntryId,7906+ snapshotSequence,7907+ });77427908 const items = [7743- ...missingInterruptRequests(visible, page.items),7909+ ...(workMode === "work" ? [] : missingInterruptRequests(visible, page.items)),77447910 ...page.items,7745- ].map((row, position) => ({ ...row, position }));7911+ ]7912+ .sort((left, right) => left.position - right.position)
- apps/server/src/orchestration-v2/ProjectionStore.ts lines 5577 to 5580OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -5471,8 +5566,15 @@54715566 turn_item_id: string;54725567 run_id: string | null;54735568 node_id: string | null;5569+ parent_item_id: string | null;54745570 type: OrchestrationV2TurnItem["type"];54755571 input_intent: NonNullable<TimelineIndexItem["inputIntent"]> | null;54765572 created_by: "user" | "agent" | "system" | null;54775573 message_id: string | null;5478- }>`SELECT turn_item_id, run_id, node_id, type,5574+ status: OrchestrationV2TurnItem["status"];5575+ ordinal: number;5576+ persistent_output: number;5577+ }>`SELECT turn_item_id, run_id, node_id, parent_item_id, type, status, ordinal,5578+ CASE WHEN type = 'dynamic_tool' AND (payload_json LIKE '%htmlRender%'5579+ OR payload_json LIKE ${`%${MCP_APP_OUTPUT_KEY}%`}5580+ OR payload_json LIKE '%"viewedImagePath"%') THEN 1 ELSE 0 END AS persistent_output,
- apps/mobile/src/features/threads/ThreadFeed.tsx line 1244OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1209,0 +1224,21 @@1224+}) {1225+ const loadWork = useAtomCommand(threadEnvironment.loadEarlierHistory, { reportFailure: false });1226+ const anchorsKey = entry.deferredWorkItemIds?.join("\n") ?? "";1227+ const [failed, setFailed] = useState(false);1228+ const load = () => {1229+ if (!anchorsKey) return Promise.resolve([]);1230+ return Promise.all(1231+ anchorsKey1232+ .split("\n")1233+ .map((workAnchorId) => loadWork({ environmentId, input: { threadId, workAnchorId } })),1234+ );1235+ };1236+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Restored expanded folds load their deferred server history on mount.1237+ useEffect(() => {1238+ if (entry.expanded)1239+ void load().then((results) =>1240+ setFailed(1241+ results.some((result) => result._tag === "Failure" || result.value._tag === "error"),1242+ ),1243+ );1244+ }, [entry.expanded, load]);
- apps/web/src/components/chat/MessagesTimeline.tsx line 1634Resolvedby Yash-Singh1(GitHub profile, opens in a new tab)@@ -1553,2 +1557,21 @@15531557 function TurnFoldTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "turn-fold" }> }) {15541558 const ctx = use(TimelineRowCtx);1559+ const loadWork = useAtomCommand(threadEnvironment.loadEarlierHistory, { reportFailure: false });1560+ const ref = parseScopedThreadKey(ctx.routeThreadKey);1561+ const environmentId = ref?.environmentId;1562+ const threadId = ref?.threadId;1563+ const anchorsKey = row.deferredWorkItemIds?.join("\n") ?? "";1564+ const [failed, setFailed] = useState(false);1565+ const load = () => {1566+ if (!anchorsKey || environmentId === undefined || threadId === undefined)1567+ return Promise.resolve([]);1568+ return Promise.all(1569+ anchorsKey1570+ .split("\n")1571+ .map((workAnchorId) => loadWork({ environmentId, input: { threadId, workAnchorId } })),1572+ );1573+ };1574+ const loadOnExpand = useEffectEvent(() => {1575+ void load().then((results) =>1576+ setFailed(1577+ results.some((result) => result._tag === "Failure" || result.value._tag === "error"),
- packages/client-runtime/src/state/threads.ts line 689Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -670,13 +680,12 @@670680 }671- if (current.history.loading) {681+ if (workAnchorId === undefined && current.history.loading) {672682 return { _tag: "busy" } satisfies ThreadHistoryController.ThreadHistoryLoadEarlierResult;673683 }674684675- // Capture the cursor that initiated this request. Completions/failures must676- // no-op if a socket or new bounded snapshot replaced progressive meta mid-flight.677- const requestCursor = current.history.historyCursor;678- yield* patchHistoryMeta((history) =>679- isActiveHistoryRequestCursor(requestCursor, history)680- ? { ...history, loading: true, error: null }681- : history,682- );685+ const isCurrent = (latest: EnvironmentThreadState) =>686+ workAnchorId === undefined687+ ? isActiveHistoryRequestCursor(requestCursor, latest.history)688+ : Option.getOrNull(latest.data)?.visibleTurnItems.find(689+ (row) => row.sourceItemId === workAnchorId,690+ )?.item.deferredWork?.cursor === requestCursor;691+ if (workAnchorId === undefined)apps/server/src/orchestration-v2/threadHistoryPaging.ts lines 199 to 199OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -167,3 +179,21 @@167179 );168180 }169181182+const DEFERRED_WORK_ITEM_TYPES = [183+ "command_execution",184+ "reasoning",185+ "file_change",186+ "file_search",187+ "web_search",188+ "dynamic_tool",189+] as const;190+191+function isDeferrableWorkItem(192+ item: Pick<OrchestrationV2TurnItem, "type" | "status"> & {193+ readonly persistentOutput?: boolean;194+ readonly toolName?: string | null;195+ readonly output?: unknown;196+ readonly viewedImagePath?: string;197+ },198+): boolean {199+ if (item.status !== "completed" || item.persistentOutput === true) return false;
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/web/src/components/chat/MessagesTimeline.tsx line 1644OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1609,0 +1624,21 @@1624+ const anchorsKey = row.deferredWorkItemIds?.join("\n") ?? "";1625+ const [failed, setFailed] = useState(false);1626+ const load = () => {1627+ if (!anchorsKey || environmentId === undefined || threadId === undefined) return;1628+ void Promise.all(1629+ anchorsKey1630+ .split("\n")1631+ .map((workAnchorId) => loadWork({ environmentId, input: { threadId, workAnchorId } })),1632+ ).then((results) =>1633+ setFailed(1634+ results.some((result) => result._tag === "Failure" || result.value._tag === "error"),1635+ ),1636+ );1637+ };1638+ const loadOnExpand = useEffectEvent(load);1639+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Restored expanded folds load their deferred server history on mount.1640+ useEffect(() => {1641+ if (row.expanded && anchorsKey && environmentId && threadId) loadOnExpand();1642+ }, [row.expanded, anchorsKey, environmentId, threadId]);1643+ const error = anchorsKey && failed ? "Couldn't load work. Click to retry." : null;1644+ const loading = row.expanded && anchorsKey !== "" && !failed;
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
Yash-Singh1(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed