Skip to content

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

fix(chat): refresh the settled transcript incrementally, one fetch at a time

M3gA-Mindd1502a2f0ff9
diff --git a/app/src/providers/__tests__/useCoreTranscriptProjection.test.tsx b/app/src/providers/__tests__/useCoreTranscriptProjection.test.tsx
index 9ad7f093c2..3fb419fcda 100644
--- a/app/src/providers/__tests__/useCoreTranscriptProjection.test.tsx
+++ b/app/src/providers/__tests__/useCoreTranscriptProjection.test.tsx
@@ -137,31 +137,121 @@ describe('history refresh stability', () => {
await act(async () => rerender({ revision: 'try-now' }));
expect(result.current).toBe(previous);
});
+});
- it('does not erase older cards while paging a next-turn refresh', async () => {
- let resolveOlder!: (value: DerivedTranscriptPage) => void;
- const older = new Promise<DerivedTranscriptPage>(resolve => {
- resolveOlder = resolve;
- });
+/**
+ * #7731: a refresh fetches only the newest page and merges it with the held
+ * older items, unless the history shrank or the page leaves a gap.
+ */
+describe('useCoreTranscriptProjection incremental refresh', () => {
+ const load = async () => {
vi.mocked(threadApi.getDerivedTranscript)
.mockReset()
.mockResolvedValueOnce(
- page({ items: [...turn('new', 'new-call'), ...turn('old', 'old-call')] })
+ page({ items: turn('b', 'b-call'), total: 6, hasMore: true, nextCursor: 'c1' })
)
+ .mockResolvedValueOnce(page({ items: turn('a', 'a-call'), total: 6 }));
+ const hook = renderHook(
+ ({ revision }) => useCoreTranscriptProjection(THREAD, revision, undefined),
+ { initialProps: { revision: 'rev-1' } }
+ );
+ await waitFor(() => expect(Object.keys(hook.result.current.timelines)).toHaveLength(2));
+ return hook;
+ };
+
+ it.each([
+ {
+ name: 'unchanged history fetches only the newest page',
+ pages: [page({ items: turn('b', 'b-call'), total: 6, hasMore: true, nextCursor: 'c1' })],
+ turns: ['a', 'b'],
+ },
+ {
+ 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'],
+ },
+ {
+ name: 'a gap past the held items walks the full history',
+ pages: [
+ page({ items: turn('d', 'd-call'), total: 12, hasMore: true, nextCursor: 'c3' }),
+ page({ items: turn('c', 'c-call'), total: 12 }),
+ ],
+ turns: ['c', 'd'],
+ },
+ {
+ name: 'a shrunk history walks in full and keeps no stale items',
+ pages: [page({ items: turn('b2', 'b2-call'), total: 3 })],
+ turns: ['b2'],
+ },
+ ])('$name', async ({ pages, turns }) => {
+ const { result, rerender } = await load();
+ const held = result.current.timelines.a;
+ for (const next of pages) vi.mocked(threadApi.getDerivedTranscript).mockResolvedValueOnce(next);
+
+ rerender({ revision: 'rev-2' });
+
+ 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);
+ });
+
+ it('coalesces a burst of revisions into one in-flight fetch', async () => {
+ const { result, rerender } = await load();
+ let active = 0;
+ let maxActive = 0;
+ const release: Array<() => void> = [];
+ vi.mocked(threadApi.getDerivedTranscript).mockImplementation(() => {
+ active += 1;
+ maxActive = Math.max(maxActive, active);
+ return new Promise(resolve =>
+ release.push(() => {
+ active -= 1;
+ resolve(page({ items: turn('c', 'c-call'), total: 9, hasMore: true, nextCursor: 'c2' }));
+ })
+ );
+ });
+
+ rerender({ revision: 'rev-2' });
+ rerender({ revision: 'rev-3' });
+ rerender({ revision: 'rev-4' });
+ expect(release).toHaveLength(1);
+ await act(async () => release[0]());
+ await waitFor(() => expect(release).toHaveLength(2));
+ await act(async () => release[1]());
+
+ await waitFor(() =>
+ expect(Object.keys(result.current.timelines).sort()).toEqual(['a', 'b', 'c'])
+ );
+ expect(threadApi.getDerivedTranscript).toHaveBeenCalledTimes(4);
+ expect(maxActive).toBe(1);
+ });
+
+ it('loads the full history of a thread it switches to', async () => {
+ vi.mocked(threadApi.getDerivedTranscript)
+ .mockReset()
+ .mockResolvedValueOnce(page({ items: turn('a', 'a-call'), total: 3 }))
.mockResolvedValueOnce(
- page({ items: turn('new', 'new-call'), hasMore: true, nextCursor: 'older' })
+ page({
+ threadId: 'other',
+ items: turn('y', 'y-call'),
+ total: 6,
+ hasMore: true,
+ nextCursor: 'c1',
+ })
)
- .mockReturnValueOnce(older);
+ .mockResolvedValueOnce(page({ threadId: 'other', items: turn('x', 'x-call'), total: 6 }));
const { result, rerender } = renderHook(
- ({ revision }) => useCoreTranscriptProjection(THREAD, revision, undefined),
- { initialProps: { revision: 'before' } }
+ ({ thread }) => useCoreTranscriptProjection(thread, 'rev-1', undefined),
+ { initialProps: { thread: THREAD as string } }
);
- await waitFor(() => expect(result.current.timelines.old).toHaveLength(1));
- const old = result.current.timelines.old;
- await act(async () => rerender({ revision: 'try-now' }));
- await waitFor(() => expect(threadApi.getDerivedTranscript).toHaveBeenCalledTimes(3));
- expect(result.current.timelines.old).toBe(old);
- await act(async () => resolveOlder(page({ items: turn('old', 'old-call') })));
- expect(result.current.timelines.old).toBe(old);
+ await waitFor(() => expect(Object.keys(result.current.timelines)).toEqual(['a']));
+
+ rerender({ thread: 'other' });
+
+ await waitFor(() => expect(Object.keys(result.current.timelines).sort()).toEqual(['x', 'y']));
+ expect(threadApi.getDerivedTranscript).toHaveBeenLastCalledWith('other', {
+ limit: 500,
+ cursor: 'c1',
+ });
});
});
diff --git a/app/src/providers/useOpenHumanExternalStore.ts b/app/src/providers/useOpenHumanExternalStore.ts
index 45a7696372..73cde4d5cc 100644
--- a/app/src/providers/useOpenHumanExternalStore.ts
+++ b/app/src/providers/useOpenHumanExternalStore.ts
@@ -7,7 +7,7 @@ import type {
ThreadSuggestion,
} from '@assistant-ui/react';
import debug from 'debug';
-import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { toast } from '../components/ui/Toast';
import { useOpenHumanQueueAdapter } from '../features/conversations/aui/queueAdapter';
@@ -147,6 +147,18 @@ export function useCoreTranscriptProjection(
liveRequestId: string | undefined
): CoreTranscriptProjection {
const [projection, setProjection] = useState<CoreTranscriptProjection>(EMPTY_CORE_TRANSCRIPT);
+ // Read by the fetch loop after each await: the thread may have changed.
+ const latest = useRef({ threadId, liveRequestId });
+ 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).
+ 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.
+ const inFlight = useRef<string | null>(null);
+ const rerun = useRef(false);
useEffect(() => {
if (!threadId) {
@@ -159,10 +171,14 @@ export function useCoreTranscriptProjection(
setProjection({ threadId, timelines: EMPTY_TURN_MAP, transcripts: EMPTY_TURN_MAP });
return;
}
- let cancelled = false;
- const skipRequestIds = liveRequestId ? new Set([liveRequestId]) : undefined;
+ if (inFlight.current === threadId) {
+ rerun.current = true;
+ return;
+ }
+ const stale = () => latest.current.threadId !== threadId;
const project = (items: DerivedDisplayItem[], partial = false) => {
- const mapped = mapDisplayItems(items, { skipRequestIds });
+ const live = latest.current.liveRequestId;
+ const mapped = mapDisplayItems(items, { skipRequestIds: live ? new Set([live]) : undefined });
setProjection(previous => {
if (partial && previous.threadId === threadId && Object.keys(previous.timelines).length > 0)
return previous;
@@ -177,23 +193,31 @@ export function useCoreTranscriptProjection(
return { threadId, timelines, transcripts };
});
};
- void (async () => {
- try {
- const first = await threadApi.getDerivedTranscript(threadId, {
- limit: DERIVED_TRANSCRIPT_PAGE_LIMIT,
- });
- if (cancelled) return;
- if (!first.hasTranscript) {
- setProjection({ threadId, timelines: EMPTY_TURN_MAP, transcripts: EMPTY_TURN_MAP });
- return;
- }
+ const refresh = async () => {
+ const first = await threadApi.getDerivedTranscript(threadId, {
+ limit: DERIVED_TRANSCRIPT_PAGE_LIMIT,
+ });
+ if (stale()) return;
+ if (!first.hasTranscript) {
+ held.current = null;
+ setProjection({ threadId, timelines: EMPTY_TURN_MAP, transcripts: EMPTY_TURN_MAP });
+ return;
+ }
+ const prev = held.current?.threadId === threadId ? held.current : null;
+ // 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) {
+ // 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)];
+ } else {
// Paint the newest page immediately, then walk the older pages and
- // re-project once with the whole history. A single page silently
- // dropped everything older than 500 items on a long thread, and a
- // page that begins mid-turn hides that turn's leading tool calls until
- // its boundary is in view — both only resolve with the full list.
- let items = first.items;
- project(items, first.hasMore);
+ // re-project once with the whole history. A page that begins mid-turn
+ // hides that turn's leading tool calls until its boundary is in view.
+ if (first.hasMore) project(items, true);
let cursor = first.hasMore ? first.nextCursor : undefined;
let pages = 1;
while (cursor && pages < DERIVED_TRANSCRIPT_MAX_PAGES) {
@@ -201,24 +225,32 @@ export function useCoreTranscriptProjection(
limit: DERIVED_TRANSCRIPT_PAGE_LIMIT,
cursor,
});
- if (cancelled) return;
+ if (stale()) return;
// Pages are newest-first and each next page is older, so appending
// keeps the newest-first order `mapDisplayItems` expects.
items = [...items, ...page.items];
pages += 1;
cursor = page.hasMore ? page.nextCursor : undefined;
}
- if (pages > 1) project(items);
+ }
+ held.current = { threadId, total: first.total, items };
+ project(items);
+ };
+ inFlight.current = threadId;
+ void (async () => {
+ try {
+ do {
+ rerun.current = false;
+ 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.
- // The return below already masks projections belonging to another thread.
+ } finally {
+ if (inFlight.current === threadId) inFlight.current = null;
}
})();
- return () => {
- cancelled = true;
- };
}, [liveRequestId, revision, threadId]);
return projection.threadId === threadId ? projection : EMPTY_CORE_TRANSCRIPT;