Skip to content

Commit 2607da1

Browse files
committed
fix(mobile): load deferred work when expanding thread history
1 parent dc84b09 commit 2607da1

33 files changed

Lines changed: 1378 additions & 94 deletions

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

Lines changed: 86 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1232,6 +1232,84 @@ function compactionLabel(label: string, title: string | undefined) {
12321232
: label;
12331233
}
12341234

1235+
function RunFoldButton({
1236+
entry,
1237+
environmentId,
1238+
threadId,
1239+
onToggle,
1240+
rowSizing,
1241+
iconColor,
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.
1263+
useEffect(() => {
1264+
if (!entry.expanded || !anchorsKey) return;
1265+
let active = true;
1266+
void requestWork(anchorsKey.split("\n"), environmentId, threadId).then((results) => {
1267+
if (!active) return;
1268+
const failed = results.some(
1269+
(result) => result._tag === "Failure" || result.value._tag === "error",
1270+
);
1271+
setFailure(failed ? { attempt: retry, message: "Couldn't load work. Tap to retry." } : null);
1272+
});
1273+
return () => {
1274+
active = false;
1275+
};
1276+
}, [entry.expanded, anchorsKey, retry, environmentId, threadId]);
1277+
const toggle = () => {
1278+
if (error !== null && entry.expanded) {
1279+
setFailure(null);
1280+
setRetry((value) => value + 1);
1281+
} else {
1282+
setFailure(null);
1283+
onToggle(entry.runId);
1284+
}
1285+
};
1286+
return (
1287+
<Pressable
1288+
accessibilityRole="button"
1289+
accessibilityState={{ expanded: entry.expanded, busy: loading }}
1290+
onPress={toggle}
1291+
hitSlop={4}
1292+
className="min-h-11 min-w-0 flex-1 flex-row items-center gap-2"
1293+
style={{ minHeight: Math.max(TURN_FOLD_HEIGHT - 3.5, rowSizing.estimatedRowHeight) }}
1294+
>
1295+
<Text
1296+
key={rowSizing.textSizeKey}
1297+
numberOfLines={1}
1298+
className="shrink font-t3-medium text-sm tabular-nums text-foreground-muted"
1299+
>
1300+
{entry.label}
1301+
{loading ? " · Loading work..." : error ? ` · ${error}` : ""}
1302+
</Text>
1303+
<ThreadDisclosureChevron
1304+
expanded={entry.expanded}
1305+
collapsedDirection="right"
1306+
size={15}
1307+
tintColor={iconColor}
1308+
/>
1309+
</Pressable>
1310+
);
1311+
}
1312+
12351313
function renderFeedEntry(
12361314
info: { item: ThreadFeedRow; index: number },
12371315
props: Pick<
@@ -1303,30 +1381,14 @@ function renderFeedEntry(
13031381
if (entry.type === "run-fold") {
13041382
return (
13051383
<View className="mb-1 flex-row items-center border-b border-border-subtle px-2">
1306-
<Pressable
1307-
accessibilityRole="button"
1308-
accessibilityState={{ expanded: entry.expanded }}
1309-
onPress={() => props.onToggleTurnFold(entry.runId)}
1310-
hitSlop={4}
1311-
className="min-h-11 min-w-0 flex-1 flex-row items-center gap-2"
1312-
style={{
1313-
minHeight: Math.max(TURN_FOLD_HEIGHT - 3.5, props.workRowSizing.estimatedRowHeight),
1314-
}}
1315-
>
1316-
<Text
1317-
key={props.workRowSizing.textSizeKey}
1318-
numberOfLines={1}
1319-
className="shrink font-t3-medium text-sm tabular-nums text-foreground-muted"
1320-
>
1321-
{entry.label}
1322-
</Text>
1323-
<ThreadDisclosureChevron
1324-
expanded={entry.expanded}
1325-
collapsedDirection="right"
1326-
size={15}
1327-
tintColor={iconSubtleColor}
1328-
/>
1329-
</Pressable>
1384+
<RunFoldButton
1385+
entry={entry}
1386+
environmentId={props.environmentId}
1387+
threadId={props.threadId}
1388+
onToggle={props.onToggleTurnFold}
1389+
rowSizing={props.workRowSizing}
1390+
iconColor={iconSubtleColor}
1391+
/>
13301392
{entry.checkpointSummary ? (
13311393
<TurnDiffStat
13321394
checkpoint={entry.checkpointSummary}

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

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,35 @@ function assistantMessage(updatedAt = "2026-06-20T00:00:03.000Z") {
354354
}
355355

356356
describe("buildThreadFeed", () => {
357+
it("keeps deferred work attached to its collapsed run and drops the cursor after loading", () => {
358+
const work = {
359+
...command(),
360+
deferredWork: { cursor: "work", itemCount: 100, lastOrdinal: 100 },
361+
};
362+
const rows = [
363+
projected(userMessage(), 0),
364+
projected(work, 1),
365+
projected(assistantMessage(), 2),
366+
];
367+
const cache = createThreadFeedCache();
368+
const presented = deriveThreadFeedPresentation(
369+
buildThreadFeed(rows, { cache }),
370+
null,
371+
new Set(),
372+
);
373+
expect(presented.map((entry) => entry.type)).toEqual(["message", "run-fold", "message"]);
374+
expect(presented[1]).toMatchObject({ deferredWorkItemIds: [work.id], expanded: false });
375+
const loaded = deriveThreadFeedPresentation(
376+
buildThreadFeed([rows[0]!, projected(command(), 1), rows[2]!], { cache }),
377+
null,
378+
new Set([runId]),
379+
);
380+
expect(loaded.find((entry) => entry.type === "run-fold")).toMatchObject({ expanded: true });
381+
expect(loaded.find((entry) => entry.type === "run-fold")).not.toHaveProperty(
382+
"deferredWorkItemIds",
383+
);
384+
});
385+
357386
it("keeps async answers in question history instead of user bubbles", () => {
358387
const requestId = RuntimeRequestId.make("question");
359388
const question: OrchestrationV2TurnItem = {

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

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -231,6 +231,7 @@ type ThreadFeedEntryContent =
231231
}
232232
| {
233233
readonly type: "run-fold";
234+
readonly deferredWorkItemIds?: ReadonlyArray<string>;
234235
readonly id: string;
235236
readonly createdAt: string;
236237
readonly runId: RunId;
@@ -1083,6 +1084,7 @@ export function threadFeedActivityIsVisible(
10831084
}
10841085

10851086
interface ThreadFeedRunFold {
1087+
readonly deferredWorkItemIds?: ReadonlyArray<string>;
10861088
readonly runId: RunId;
10871089
readonly createdAt: string;
10881090
readonly hiddenEntryIds: ReadonlySet<string>;
@@ -1274,7 +1276,17 @@ function deriveThreadFeedRunFolds(
12741276
const duration = elapsedMs === null ? null : formatDuration(elapsedMs);
12751277
const interrupted =
12761278
latestRunMatches && (latestRun.status === "interrupted" || latestRun.status === "cancelled");
1279+
const deferredWorkItemIds = group.entries.flatMap((entry) =>
1280+
entry.type === "activity-group"
1281+
? entry.activities.flatMap((activity) =>
1282+
activity.projectedItem.item.deferredWork
1283+
? [String(activity.projectedItem.sourceItemId)]
1284+
: [],
1285+
)
1286+
: [],
1287+
);
12771288
foldsByAnchorId.set(firstHiddenEntry.id, {
1289+
...(deferredWorkItemIds.length > 0 ? { deferredWorkItemIds } : {}),
12781290
runId,
12791291
createdAt: firstHiddenEntry.createdAt,
12801292
hiddenEntryIds,
@@ -1502,11 +1514,13 @@ export function deriveThreadFeedPresentation(
15021514
row.runId !== fold.runId ||
15031515
row.createdAt !== fold.createdAt ||
15041516
row.label !== fold.label ||
1505-
row.expanded !== expanded
1517+
row.expanded !== expanded ||
1518+
row.deferredWorkItemIds?.join("|") !== fold.deferredWorkItemIds?.join("|")
15061519
) {
15071520
row = {
15081521
type: "run-fold",
15091522
id: `run-fold:${fold.runId}`,
1523+
...(fold.deferredWorkItemIds ? { deferredWorkItemIds: fold.deferredWorkItemIds } : {}),
15101524
createdAt: fold.createdAt,
15111525
runId: fold.runId,
15121526
label: fold.label,

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

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -347,6 +347,7 @@ export interface OrchestratorV2Shape {
347347
cursor: string,
348348
throughEntryId?: string,
349349
conversationOnly?: boolean,
350+
workMode?: "deferred" | "work",
350351
) => Effect.Effect<OrchestrationV2ThreadHistoryPage, OrchestratorV2Error>;
351352
readonly getTimelinePage: (
352353
threadId: ThreadId,
@@ -384,6 +385,7 @@ export interface OrchestratorV2Shape {
384385
readonly schemaVersion: number;
385386
readonly snapshotSequence: number;
386387
readonly projection: OrchestrationV2ThreadProjection;
388+
readonly historyContextItems?: OrchestrationV2ThreadProjection["visibleTurnItems"];
387389
},
388390
OrchestratorV2Error
389391
>;
@@ -12688,9 +12690,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1268812690
);
1268912691
}),
1269012692
getThreadHistoryPage: Effect.fn("OrchestratorV2.getThreadHistoryPage")(
12691-
function (threadId, cursor, throughEntryId, conversationOnly) {
12693+
function (threadId, cursor, throughEntryId, conversationOnly, workMode) {
1269212694
return projectionStore
12693-
.getThreadHistoryPage(threadId, cursor, throughEntryId, conversationOnly)
12695+
.getThreadHistoryPage(threadId, cursor, throughEntryId, conversationOnly, workMode)
1269412696
.pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause })));
1269512697
},
1269612698
),

‎apps/server/src/orchestration-v2/ProjectionStore.test.ts‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
type ModelSelection,
1111
type OrchestrationV2ProviderThread,
1212
type OrchestrationV2TurnItem,
13+
type OrchestrationV2ThreadHistoryPage,
1314
type OrchestrationV2ThreadShellSnapshot,
1415
NodeId,
1516
PlanId,
@@ -1916,6 +1917,89 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
19161917
Array.from({ length: 1_000 }, (_, index) => `turn-item:bounded-sql-history:${index + 1}`),
19171918
);
19181919

1920+
yield* setNewestTurnType("command_execution");
1921+
yield* sql`
1922+
UPDATE orchestration_v2_projection_turn_items
1923+
SET run_id = 'run:bounded-sql-history:1',
1924+
payload_json = json_set(payload_json, '$.runId', 'run:bounded-sql-history:1')
1925+
WHERE thread_id = ${threadId}
1926+
`;
1927+
const longTurnSnapshot = yield* humanWindow();
1928+
assert.lengthOf(longTurnSnapshot.projection.visibleTurnItems, sqlPageLimit);
1929+
const longTurnPage = buildBoundedThreadProjection({
1930+
...longTurnSnapshot,
1931+
});
1932+
const promptId = TurnItemId.make("turn-item:bounded-sql-history:1");
1933+
assert.strictEqual(longTurnPage.projection.visibleTurnItems[0]?.sourceItemId, promptId);
1934+
const longTurnIds = new Set(
1935+
longTurnPage.projection.visibleTurnItems.map((row) => row.sourceItemId),
1936+
);
1937+
let longTurnCursor = longTurnPage.historyCursor;
1938+
for (let pages = 0; longTurnCursor !== null; pages += 1) {
1939+
assert.isBelow(pages, 20);
1940+
assert.notStrictEqual(decodeThreadHistoryCursor(longTurnCursor).si, promptId);
1941+
const page = yield* projectionStore.getThreadHistoryPage(threadId, longTurnCursor);
1942+
assert.strictEqual(page.items[0]?.sourceItemId, promptId);
1943+
for (const row of page.items) longTurnIds.add(row.sourceItemId);
1944+
longTurnCursor = page.nextCursor;
1945+
}
1946+
assert.strictEqual(longTurnIds.size, 1_000);
1947+
const conversation = yield* projectionStore.getThreadHistoryPage(
1948+
threadId,
1949+
longTurnPage.historyCursor!,
1950+
undefined,
1951+
true,
1952+
);
1953+
assert.strictEqual(conversation.items[0]?.sourceItemId, promptId);
1954+
const deferred = yield* projectionStore.getThreadSnapshotWindow(threadId, {
1955+
rowLimit: sqlPageLimit,
1956+
userTurnLimit: 10,
1957+
deferWork: true,
1958+
});
1959+
assert.lengthOf(deferred.projection.visibleTurnItems, 3);
1960+
assert.strictEqual(deferred.projection.visibleTurnItems[0]?.sourceItemId, promptId);
1961+
const anchor = deferred.projection.visibleTurnItems[1]!;
1962+
assert.strictEqual(anchor.item.deferredWork?.itemCount, 999);
1963+
const workIds = new Set<TurnItemId>();
1964+
let workCursor: string | null = anchor.item.deferredWork!.cursor;
1965+
for (let pages = 0; workCursor !== null; pages += 1) {
1966+
assert.isBelow(pages, 20);
1967+
const page: OrchestrationV2ThreadHistoryPage = yield* projectionStore.getThreadHistoryPage(
1968+
threadId,
1969+
workCursor,
1970+
anchor.sourceItemId,
1971+
false,
1972+
"work",
1973+
);
1974+
assert.isAtMost(page.items.length, 75);
1975+
for (const row of page.items) workIds.add(row.sourceItemId);
1976+
workCursor = page.nextCursor;
1977+
}
1978+
assert.strictEqual(workIds.size, 999);
1979+
yield* sql`
1980+
UPDATE orchestration_v2_projection_turn_items
1981+
SET type = 'command_execution', payload_json = json_set(payload_json, '$.type', 'command_execution')
1982+
WHERE thread_id = ${threadId} AND ordinal = 1
1983+
`;
1984+
const backgroundWindow = yield* projectionStore.getThreadSnapshotWindow(threadId, {
1985+
rowLimit: sqlPageLimit,
1986+
userTurnLimit: 10,
1987+
deferWork: true,
1988+
});
1989+
assert.lengthOf(backgroundWindow.projection.visibleTurnItems, sqlPageLimit);
1990+
yield* sql`
1991+
UPDATE orchestration_v2_projection_turn_items
1992+
SET type = 'user_message', payload_json = json_set(payload_json, '$.type', 'user_message')
1993+
WHERE thread_id = ${threadId} AND ordinal = 1
1994+
`;
1995+
yield* sql`
1996+
UPDATE orchestration_v2_projection_turn_items
1997+
SET run_id = 'run:bounded-sql-history:' || ordinal,
1998+
payload_json = json_set(payload_json, '$.runId', 'run:bounded-sql-history:' || ordinal)
1999+
WHERE thread_id = ${threadId}
2000+
`;
2001+
yield* setNewestTurnType("user_message");
2002+
19192003
const tiedIds = [
19202004
TurnItemId.make("turn-item:bounded-sql-history:tie:b"),
19212005
TurnItemId.make("turn-item:bounded-sql-history:tie:a"),

0 commit comments

Comments
 (0)