Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(chat): harden the incremental transcript refresh (review)

M3gA-Mindab2a3777925e
diff --git a/app/src/providers/__tests__/useCoreTranscriptProjection.test.tsx b/app/src/providers/__tests__/useCoreTranscriptProjection.test.tsx
index 3fb419fcda..ce9f55a476 100644
--- a/app/src/providers/__tests__/useCoreTranscriptProjection.test.tsx
+++ b/app/src/providers/__tests__/useCoreTranscriptProjection.test.tsx
@@ -18,6 +18,11 @@ function turn(requestId: string, callId: string): DerivedDisplayItem[] {
];
}
+/** A sub-agent card attached to turn `a`, which the core updates in place. */
+function subagent(status: 'running' | 'completed'): DerivedDisplayItem {
+ return { kind: 'subagent', id: 'sub-1', status, requestId: 'a', items: [] };
+}
+
function page(over: Partial<DerivedTranscriptPage>): DerivedTranscriptPage {
return { threadId: THREAD, items: [], total: 0, hasMore: false, hasTranscript: true, ...over };
}
@@ -144,13 +149,14 @@ describe('history refresh stability', () => {
* older items, unless the history shrank or the page leaves a gap.
*/
describe('useCoreTranscriptProjection incremental refresh', () => {
- const load = async () => {
+ const load = async (older: DerivedDisplayItem[] = turn('a', 'a-call')) => {
+ const total = 3 + older.length;
vi.mocked(threadApi.getDerivedTranscript)
.mockReset()
.mockResolvedValueOnce(
- page({ items: turn('b', 'b-call'), total: 6, hasMore: true, nextCursor: 'c1' })
+ page({ items: turn('b', 'b-call'), total, hasMore: true, nextCursor: 'c1' })
)
- .mockResolvedValueOnce(page({ items: turn('a', 'a-call'), total: 6 }));
+ .mockResolvedValueOnce(page({ items: older, total }));
const hook = renderHook(
({ revision }) => useCoreTranscriptProjection(THREAD, revision, undefined),
{ initialProps: { revision: 'rev-1' } }
@@ -164,11 +170,24 @@ describe('useCoreTranscriptProjection incremental refresh', () => {
name: 'unchanged history fetches only the newest page',
pages: [page({ items: turn('b', 'b-call'), total: 6, hasMore: true, nextCursor: 'c1' })],
turns: ['a', 'b'],
+ reusesA: true,
},
{
name: 'an appended turn is merged with the held older items',
pages: [page({ items: turn('c', 'c-call'), total: 9, hasMore: true, nextCursor: 'c2' })],
turns: ['a', 'b', 'c'],
+ reusesA: true,
+ },
+ {
+ // A detached sub-agent finishes in place, outside the newest page.
+ name: 'a held older item still running walks the full history',
+ older: [subagent('running'), ...turn('a', 'a-call')],
+ pages: [
+ page({ items: turn('c', 'c-call'), total: 10, hasMore: true, nextCursor: 'c2' }),
+ page({ items: turn('b', 'b-call'), total: 10, hasMore: true, nextCursor: 'c3' }),
+ page({ items: [subagent('completed'), ...turn('a', 'a-call')], total: 10 }),
+ ],
+ turns: ['a', 'b', 'c'],
},
{
name: 'a gap past the held items walks the full history',
@@ -183,8 +202,8 @@ describe('useCoreTranscriptProjection incremental refresh', () => {
pages: [page({ items: turn('b2', 'b2-call'), total: 3 })],
turns: ['b2'],
},
- ])('$name', async ({ pages, turns }) => {
- const { result, rerender } = await load();
+ ])('$name', async ({ older, pages, turns, reusesA }) => {
+ const { result, rerender } = await load(older);
const held = result.current.timelines.a;
for (const next of pages) vi.mocked(threadApi.getDerivedTranscript).mockResolvedValueOnce(next);
@@ -192,7 +211,7 @@ describe('useCoreTranscriptProjection incremental refresh', () => {
await waitFor(() => expect(Object.keys(result.current.timelines).sort()).toEqual(turns));
expect(threadApi.getDerivedTranscript).toHaveBeenCalledTimes(2 + pages.length);
- if (turns.includes('a')) expect(result.current.timelines.a).toBe(held);
+ if (reusesA) expect(result.current.timelines.a).toBe(held);
});
it('coalesces a burst of revisions into one in-flight fetch', async () => {
@@ -254,4 +273,100 @@ describe('useCoreTranscriptProjection incremental refresh', () => {
cursor: 'c1',
});
});
+
+ it('honours a queued pass after a refresh fails', async () => {
+ const { result, rerender } = await load();
+ let fail!: (error: Error) => void;
+ vi.mocked(threadApi.getDerivedTranscript)
+ .mockReturnValueOnce(
+ new Promise((_, reject) => {
+ fail = reject;
+ })
+ )
+ .mockResolvedValueOnce(
+ page({ items: turn('c', 'c-call'), total: 9, hasMore: true, nextCursor: 'c2' })
+ );
+
+ rerender({ revision: 'rev-2' });
+ rerender({ revision: 'rev-3' });
+ await act(async () => fail(new Error('temporary RPC failure')));
+
+ await waitFor(() =>
+ expect(Object.keys(result.current.timelines).sort()).toEqual(['a', 'b', 'c'])
+ );
+ expect(threadApi.getDerivedTranscript).toHaveBeenCalledTimes(4);
+ });
+
+ it('keeps a loop abandoned by a thread round trip from writing', async () => {
+ let resolveZombie!: (value: DerivedTranscriptPage) => void;
+ vi.mocked(threadApi.getDerivedTranscript)
+ .mockReset()
+ .mockResolvedValueOnce(
+ page({ items: turn('a2', 'a2-call'), total: 6, hasMore: true, nextCursor: 'c1' })
+ )
+ .mockReturnValueOnce(
+ new Promise(resolve => {
+ resolveZombie = resolve;
+ })
+ )
+ .mockResolvedValueOnce(page({ threadId: 'other', items: turn('y', 'y-call'), total: 3 }))
+ .mockResolvedValueOnce(
+ page({ items: turn('a2', 'a2-call'), total: 6, hasMore: true, nextCursor: 'c1' })
+ )
+ .mockResolvedValueOnce(page({ items: turn('a1', 'a1-call'), total: 6 }));
+ const { result, rerender } = renderHook(
+ ({ thread }) => useCoreTranscriptProjection(thread, 'rev-1', undefined),
+ { initialProps: { thread: THREAD as string } }
+ );
+ await waitFor(() => expect(threadApi.getDerivedTranscript).toHaveBeenCalledTimes(2));
+
+ rerender({ thread: 'other' });
+ await waitFor(() => expect(Object.keys(result.current.timelines)).toEqual(['y']));
+ rerender({ thread: THREAD });
+ await waitFor(() => expect(Object.keys(result.current.timelines).sort()).toEqual(['a1', 'a2']));
+
+ await act(async () => resolveZombie(page({ items: turn('zombie', 'z-call'), total: 6 })));
+ expect(Object.keys(result.current.timelines).sort()).toEqual(['a1', 'a2']);
+ });
+
+ it('keeps a merged history within the full-walk cap', async () => {
+ // 3,332 filler turns plus the oldest turn: 9,999 items over 20 pages.
+ const history: DerivedDisplayItem[] = [];
+ for (let i = 3331; i >= 0; i -= 1) history.push(...turn(`f${i}`, `f${i}-call`));
+ history.push(...turn('oldest', 'oldest-call'));
+ const mock = vi.mocked(threadApi.getDerivedTranscript).mockReset();
+ for (let start = 0; start < history.length; start += 500) {
+ const more = start + 500 < history.length;
+ mock.mockResolvedValueOnce(
+ page({
+ items: history.slice(start, start + 500),
+ total: history.length,
+ hasMore: more,
+ nextCursor: more ? `c${start + 500}` : undefined,
+ })
+ );
+ }
+ const { result, rerender } = renderHook(
+ ({ revision }) => useCoreTranscriptProjection(THREAD, revision, undefined),
+ { initialProps: { revision: 'rev-1' } }
+ );
+ await waitFor(() => expect(result.current.timelines.oldest).toBeDefined());
+
+ // Six new items push the merged list five past the 10,000 cap, so the
+ // oldest turn's three items fall off its end.
+ const fresh = [...turn('n2', 'n2-call'), ...turn('n1', 'n1-call')];
+ mock.mockResolvedValueOnce(
+ page({
+ items: [...fresh, ...history.slice(0, 494)],
+ total: history.length + fresh.length,
+ hasMore: true,
+ nextCursor: 'c-next',
+ })
+ );
+ rerender({ revision: 'rev-2' });
+
+ await waitFor(() => expect(result.current.timelines.n2).toBeDefined());
+ expect(result.current.timelines.oldest).toBeUndefined();
+ expect(threadApi.getDerivedTranscript).toHaveBeenCalledTimes(21);
+ });
});
diff --git a/app/src/providers/useOpenHumanExternalStore.ts b/app/src/providers/useOpenHumanExternalStore.ts
index 73cde4d5cc..51677b8f74 100644
--- a/app/src/providers/useOpenHumanExternalStore.ts
+++ b/app/src/providers/useOpenHumanExternalStore.ts
@@ -54,6 +54,10 @@ const DERIVED_TRANSCRIPT_PAGE_LIMIT = 500;
*/
const DERIVED_TRANSCRIPT_MAX_PAGES = 20;
+/** A projected item the core still rewrites in place: a running sub-agent or tool call. */
+const isUnsettled = (item: DerivedDisplayItem) =>
+ (item.kind === 'subagent' || item.kind === 'toolCall') && item.status === 'running';
+
/**
* Everything the assistant-ui surface needs about the *currently running* turn
* that is not a message, a tool part or a stream delta.
@@ -152,13 +156,16 @@ export function useCoreTranscriptProjection(
latest.current = { threadId, liveRequestId };
// Newest-first items already fetched for one thread, and the thread's
// `total` when they were. Cursors are chronological, so items older than the
- // newest page never move and a refresh only needs that page (#7731).
+ // newest page keep their position and a refresh only needs that page (#7731).
const held = useRef<{ threadId: string; total: number; items: DerivedDisplayItem[] } | null>(
null
);
// One fetch loop at a time; a change while it runs asks for one more pass.
+ // `loop` numbers the loops, so an abandoned one stays stale even when its
+ // thread is selected again.
const inFlight = useRef<string | null>(null);
const rerun = useRef(false);
+ const loop = useRef(0);
useEffect(() => {
if (!threadId) {
@@ -175,7 +182,8 @@ export function useCoreTranscriptProjection(
rerun.current = true;
return;
}
- const stale = () => latest.current.threadId !== threadId;
+ const id = ++loop.current;
+ const stale = () => loop.current !== id || latest.current.threadId !== threadId;
const project = (items: DerivedDisplayItem[], partial = false) => {
const live = latest.current.liveRequestId;
const mapped = mapDisplayItems(items, { skipRequestIds: live ? new Set([live]) : undefined });
@@ -207,12 +215,16 @@ export function useCoreTranscriptProjection(
// Chronological index of the page's oldest item.
const lower = Math.max(0, first.total - first.items.length);
let items = first.items;
- if (prev && first.total >= prev.total && lower <= prev.total) {
+ const older = prev ? prev.items.slice(prev.total - lower) : [];
+ if (prev && first.total >= prev.total && lower <= prev.total && !older.some(isUnsettled)) {
// The newest page reaches into what is held: keep the held items older
- // than it. A shrunk total (edit, regenerate) or a gap walks in full.
- // ponytail: assumes items older than the newest page never change; if
- // the core starts rewriting old items, refetch the overlap instead.
- items = [...items, ...prev.items.slice(prev.total - lower)];
+ // than it, within the same cap as a full walk. A shrunk total (edit,
+ // regenerate), a gap, or an older item still running (a detached
+ // sub-agent finishes in place) walks in full.
+ items = [...items, ...older].slice(
+ 0,
+ DERIVED_TRANSCRIPT_PAGE_LIMIT * DERIVED_TRANSCRIPT_MAX_PAGES
+ );
} else {
// Paint the newest page immediately, then walk the older pages and
// re-project once with the whole history. A page that begins mid-turn
@@ -238,18 +250,18 @@ export function useCoreTranscriptProjection(
};
inFlight.current = threadId;
void (async () => {
- try {
- do {
- rerun.current = false;
+ do {
+ rerun.current = false;
+ try {
await refresh();
- } while (rerun.current && !stale());
- } catch {
- // A missing/older core has no settled process trail; message text and
- // the live socket projection remain usable. Navigation must not fail.
- // A transient refresh failure must not erase the last complete trail.
- } finally {
- if (inFlight.current === threadId) inFlight.current = null;
- }
+ } catch {
+ // A missing/older core has no settled process trail; message text and
+ // the live socket projection remain usable. Navigation must not fail.
+ // A transient refresh failure must not erase the last complete trail,
+ // and a pass queued meanwhile still runs.
+ }
+ } while (rerun.current && !stale());
+ if (loop.current === id) inFlight.current = null;
})();
}, [liveRequestId, revision, threadId]);