Skip to content

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

fix(chat): a bare chat_done no longer adopts the previous turn's trail

M3gA-Minde53b12334354
diff --git a/app/src/providers/__tests__/assistantUiMessages.test.ts b/app/src/providers/__tests__/assistantUiMessages.test.ts
index fbfc475d7a..5f0e3a15de 100644
--- a/app/src/providers/__tests__/assistantUiMessages.test.ts
+++ b/app/src/providers/__tests__/assistantUiMessages.test.ts
@@ -210,6 +210,28 @@ describe('buildRuntimeMessages', () => {
]);
});
+ it("hands the live rows to the settled reply they belong to, never to another request's", () => {
+ const reply = (requestId: string) =>
+ msg({ id: `agent:${requestId}`, sender: 'agent', extraMetadata: { requestId } });
+ const liveTimeline = [tool({ id: 'call-1', status: 'success' })];
+ const toolIds = (liveTimelineRequestId: string | undefined, requestId: string) => {
+ const [message] = buildRuntimeMessages([reply(requestId)], null, {
+ isRunning: false,
+ liveTimeline,
+ liveTimelineRequestId,
+ });
+ return typeof message.content === 'string'
+ ? []
+ : message.content.flatMap(part => (part.type === 'tool-call' ? [part.toolCallId] : []));
+ };
+ // The just-settled turn's own rows, and rows of unknown owner: unchanged.
+ expect(toolIds('req-1', 'req-1')).toEqual(['call-1']);
+ expect(toolIds(undefined, 'req-1')).toEqual(['call-1']);
+ // A reply that settled without an `inference_start` (a background
+ // delivery) does not show the previous turn's cards again.
+ expect(toolIds('req-1', 'bgdeliver-1')).toEqual([]);
+ });
+
it('replays a settled turn with its reasoning, narration and tools in the order they happened', () => {
const answer = msg({
id: 'answer',
diff --git a/app/src/providers/__tests__/liveHistoryParity.test.tsx b/app/src/providers/__tests__/liveHistoryParity.test.tsx
index 2a10365870..14a88f9529 100644
--- a/app/src/providers/__tests__/liveHistoryParity.test.tsx
+++ b/app/src/providers/__tests__/liveHistoryParity.test.tsx
@@ -122,6 +122,7 @@ function project(): ThreadMessageLike[] {
isRunning: lifecycle === 'started' || lifecycle === 'streaming',
liveTimeline: runtime.toolTimelineByThread[TURN_THREAD] ?? [],
liveTranscript: runtime.processingByThread[TURN_THREAD] ?? [],
+ liveTimelineRequestId: runtime.toolTimelineRequestByThread[TURN_THREAD],
pendingApproval: runtime.pendingApprovalByThread[TURN_THREAD] ?? null,
settledTurns: runtime.settledTurnsByThread?.[TURN_THREAD] ?? {},
liveRequestId: runtime.liveRequestIdByThread?.[TURN_THREAD] ?? streaming?.requestId,
@@ -491,3 +492,168 @@ describe('async delegation settles after its turn', () => {
expect(cards.filter(([, status]) => status === 'running')).toEqual([]);
});
});
+
+/**
+ * A reply that settles with no `inference_start` of its own — a background
+ * delivery — must not adopt the previous turn's rows as its trail. Seen live:
+ * after an async delegation finished, the delivery reply showed a second copy
+ * of that turn's "Delegated to … · async" card (spinning, before #6729).
+ */
+describe("a bare chat_done does not borrow the previous turn's trail", () => {
+ const spawnedStep = LIVE_TURN_STEPS.find(step => step.listener === 'onSubagentSpawned');
+ const doneStep = LIVE_TURN_STEPS.find(step => step.listener === 'onSubagentDone');
+ if (!spawnedStep || !doneStep) throw new Error('fixture lost its delegation');
+ const asyncSteps = LIVE_TURN_STEPS.filter(step => step !== doneStep).map(step =>
+ step === spawnedStep
+ ? ({
+ ...step,
+ event: { ...step.event, subagent: { mode: 'async', parent_call_id: 'call-spawn' } },
+ } as SocketStep)
+ : step
+ );
+ const DELIVERY_REQUEST = 'bgdeliver-1';
+ // A completed snapshot as the core persists it (core row ids).
+ const snapshot = (requestId: string, subagentStatus: 'running' | 'success') => ({
+ threadId: TURN_THREAD,
+ requestId,
+ lifecycle: 'completed' as const,
+ iteration: 3,
+ maxIterations: 10,
+ streamingText: '',
+ thinking: '',
+ startedAt: '2026-09-28T11:03:05Z',
+ updatedAt: '2026-09-28T11:04:06Z',
+ toolTimeline: [
+ { id: 'call-spawn', name: 'spawn_subagent', status: 'success' as const, round: 2 },
+ {
+ id: 'subagent:sub-1',
+ name: 'subagent:researcher',
+ status: subagentStatus,
+ round: 2,
+ subagent: {
+ taskId: 'sub-1',
+ agentId: 'researcher',
+ mode: 'async',
+ parentCallId: 'call-spawn',
+ toolCalls: [],
+ },
+ },
+ ],
+ });
+
+ /** Tool-call parts on screen per message: `[messageId, toolName, settled status | 'running']`. */
+ function toolCards(): [string | undefined, string, string][] {
+ return project().flatMap(message =>
+ typeof message.content === 'string'
+ ? []
+ : message.content.flatMap(part =>
+ part.type === 'tool-call'
+ ? [
+ [
+ message.id,
+ part.toolName,
+ (part.result as { status?: string } | undefined)?.status ??
+ (part.result === undefined ? 'running' : 'done'),
+ ] as [string | undefined, string, string],
+ ]
+ : []
+ )
+ );
+ }
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ store.dispatch(clearAllThreads());
+ store.dispatch(clearAllChatRuntime());
+ vi.mocked(threadApi.appendMessage).mockImplementation(async (_tid, message) => message);
+ vi.mocked(threadApi.getThreads).mockResolvedValue({ threads: [], count: 0 });
+ vi.mocked(threadApi.listRuns).mockResolvedValue([]);
+ vi.mocked(threadApi.generateTitleIfNeeded).mockResolvedValue({
+ id: TURN_THREAD,
+ title: 'Today',
+ } as never);
+ });
+
+ afterEach(() => {
+ store.dispatch(setStatusForUser({ userId: '__pending__', status: 'disconnected' }));
+ });
+
+ async function settleAsyncTurn(listeners: chatService.ChatEventListeners) {
+ await store.dispatch(addMessageLocal({ threadId: TURN_THREAD, message: USER_MESSAGE }));
+ store.dispatch(beginInferenceTurn({ threadId: TURN_THREAD }));
+ for (const step of asyncSteps) fire(listeners, step);
+ act(() => listeners.onDone?.(DONE_EVENT));
+ await waitFor(() =>
+ expect(store.getState().chatRuntime.toolTimelineByThread[TURN_THREAD]?.[1]?.id).toBe(
+ 'subagent:sub-1'
+ )
+ );
+ }
+
+ it('the delivery reply shows no tool cards of the turn before it', async () => {
+ vi.mocked(threadApi.getTurnState).mockResolvedValue(snapshot(TURN_REQUEST, 'running') as never);
+ const listeners = renderProvider();
+ await settleAsyncTurn(listeners);
+ const turnCards = toolCards();
+ expect(turnCards.every(([messageId]) => messageId === `agent:${TURN_REQUEST}`)).toBe(true);
+
+ // The child finishes; its result arrives as a host-authored turn: a bare
+ // `chat_done` with no `inference_start`.
+ fire(listeners, doneStep);
+ vi.mocked(threadApi.getTurnState).mockResolvedValue(snapshot(TURN_REQUEST, 'success') as never);
+ act(() =>
+ listeners.onDone?.({
+ ...DONE_EVENT,
+ request_id: DELIVERY_REQUEST,
+ full_response: 'The research finished.',
+ })
+ );
+ await waitFor(() =>
+ expect(
+ store
+ .getState()
+ .thread.messagesByThreadId[
+ TURN_THREAD
+ ]?.some(message => message.id === `agent:${DELIVERY_REQUEST}`)
+ ).toBe(true)
+ );
+ // Let the delivery's completed-snapshot hydrate land.
+ await waitFor(() =>
+ expect(store.getState().chatRuntime.toolTimelineByThread[TURN_THREAD]?.[1]?.status).toBe(
+ 'success'
+ )
+ );
+
+ const cards = toolCards();
+ expect(cards.filter(([messageId]) => messageId === `agent:${DELIVERY_REQUEST}`)).toEqual([]);
+ expect(store.getState().chatRuntime.settledTurnsByThread[TURN_THREAD]?.[DELIVERY_REQUEST]).toBe(
+ undefined
+ );
+ // The turn that ran the delegation keeps its own trail.
+ expect(cards.filter(([messageId]) => messageId === `agent:${TURN_REQUEST}`).length).toBe(
+ turnCards.length
+ );
+ });
+
+ it("an older snapshot arriving after chat_done does not hide the settled turn's own trail", async () => {
+ // Snapshot lag: the completed-snapshot fetch returns the PREVIOUS turn's
+ // snapshot, so the live rows (and their owner) become that turn's.
+ vi.mocked(threadApi.getTurnState).mockResolvedValue(snapshot('req-older', 'success') as never);
+ const listeners = renderProvider();
+ await store.dispatch(addMessageLocal({ threadId: TURN_THREAD, message: USER_MESSAGE }));
+ store.dispatch(beginInferenceTurn({ threadId: TURN_THREAD }));
+ for (const step of LIVE_TURN_STEPS) fire(listeners, step);
+ const live = toolCards().map(([, toolName, status]) => [toolName, status]);
+ act(() => listeners.onDone?.(DONE_EVENT));
+ await waitFor(() =>
+ expect(store.getState().chatRuntime.toolTimelineRequestByThread[TURN_THREAD]).toBe(
+ 'req-older'
+ )
+ );
+
+ // Same cards, same statuses, on the settled message — nothing hidden.
+ const settled = toolCards();
+ expect(settled.every(([messageId]) => messageId === `agent:${TURN_REQUEST}`)).toBe(true);
+ expect(settled.map(([, toolName, status]) => [toolName, status])).toEqual(live);
+ });
+});
diff --git a/app/src/providers/assistantUiMessages.ts b/app/src/providers/assistantUiMessages.ts
index 4565b2f560..b210ec7f22 100644
--- a/app/src/providers/assistantUiMessages.ts
+++ b/app/src/providers/assistantUiMessages.ts
@@ -1026,6 +1026,12 @@ export type AssistantUiProjection = {
pendingApproval?: PendingApproval | null;
liveTimeline?: readonly ToolTimelineEntry[];
liveTranscript?: readonly ProcessingTranscriptItem[];
+ /**
+ * The request whose rows `liveTimeline` holds, when known
+ * (`chatRuntime.toolTimelineRequestByThread`). A settled message never
+ * borrows another request's live rows as its trail.
+ */
+ liveTimelineRequestId?: string;
turnTimelines?: Readonly<Record<string, readonly ToolTimelineEntry[]>>;
turnTranscripts?: Readonly<Record<string, readonly ProcessingTranscriptItem[]>>;
/**
@@ -1148,12 +1154,20 @@ export function buildRuntimeMessages(
// Not while a gate is parked: the tail below is minted unconditionally in
// that case and would emit the same rows a second time, and a repeated
// `toolCallId` throws inside assistant-ui rather than dropping a row.
+ // Nor when those rows are provably another turn's: a reply that settled
+ // with no `inference_start` of its own (a background delivery) otherwise
+ // showed the previous turn's tool cards a second time under itself.
+ const liveRowsAreForeign =
+ projection.liveTimelineRequestId !== undefined &&
+ requestId !== undefined &&
+ projection.liveTimelineRequestId !== requestId;
const useSettledLiveFallback =
projection.isRunning === false &&
!pendingApproval &&
msg.id === lastVisibleAgentId &&
!persistedTimeline &&
- !persistedTranscript;
+ !persistedTranscript &&
+ !liveRowsAreForeign;
out.push(
toThreadMessageLike(
msg,
diff --git a/app/src/providers/useOpenHumanExternalStore.ts b/app/src/providers/useOpenHumanExternalStore.ts
index 59b0869f23..24926db251 100644
--- a/app/src/providers/useOpenHumanExternalStore.ts
+++ b/app/src/providers/useOpenHumanExternalStore.ts
@@ -391,6 +391,9 @@ export function useOpenHumanExternalStore(
const liveRequestId = useAppSelector(state =>
threadId ? state.chatRuntime.liveRequestIdByThread?.[threadId] : undefined
);
+ const liveTimelineRequestId = useAppSelector(state =>
+ threadId ? state.chatRuntime.toolTimelineRequestByThread?.[threadId] : undefined
+ );
const settledTurns = useAppSelector(state =>
threadId ? (state.chatRuntime.settledTurnsByThread?.[threadId] ?? EMPTY_SETTLED) : EMPTY_SETTLED
);
@@ -412,6 +415,7 @@ export function useOpenHumanExternalStore(
isRunning,
liveTimeline,
liveTranscript,
+ liveTimelineRequestId,
pendingApproval,
turnTimelines: coreTranscript.timelines,
turnTranscripts: coreTranscript.transcripts,
@@ -424,6 +428,7 @@ export function useOpenHumanExternalStore(
isRunning,
liveTimeline,
liveTranscript,
+ liveTimelineRequestId,
pendingApproval,
coreTranscript,
settledTurns,
diff --git a/app/src/store/__tests__/chatRuntimeSlice.liveParity.test.ts b/app/src/store/__tests__/chatRuntimeSlice.liveParity.test.ts
index 3e994c0d46..cd7be9b963 100644
--- a/app/src/store/__tests__/chatRuntimeSlice.liveParity.test.ts
+++ b/app/src/store/__tests__/chatRuntimeSlice.liveParity.test.ts
@@ -188,6 +188,56 @@ describe('turnSettled', () => {
expect(kept).toHaveLength(20);
expect(kept.at(-1)).toBe('req-29');
});
+
+ it("does not freeze another turn's rows as the trail of a reply with no inference_start", () => {
+ // A background delivery settles with a bare `chat_done`: the live rows are
+ // still the turn before it, which settled already.
+ const settled = run(
+ [
+ turnSettled({ threadId: T, requestId: 'req-1' }),
+ turnSettled({ threadId: T, requestId: 'bgdeliver-1' }),
+ ],
+ live()
+ );
+ expect(settled.settledTurnsByThread[T]?.['bgdeliver-1']).toBeUndefined();
+ expect(settled.settledTurnsByThread[T]?.['req-1']?.timeline.map(row => row.id)).toEqual([
+ 'call-a',
+ ]);
+ // The rows stay where they are (the background-process panel reads them).
+ expect(settled.toolTimelineByThread[T]?.map(row => row.id)).toEqual(['call-a']);
+ expect(settled.toolTimelineRequestByThread[T]).toBe('req-1');
+ });
+
+ it('a turn whose inference_start was missed still freezes its own rows', () => {
+ // req-1 settled and left its claim; req-2's `inference_start` never
+ // arrived (a reconnect mid-turn), but its own rows did. The rows it
+ // mints drop the stale claim, so req-2 freezes as it always did.
+ const settled = run(
+ [
+ turnSettled({ threadId: T, requestId: 'req-1' }),
+ toolCallReceived({ threadId: T, round: 1, toolName: 'shell', toolCallId: 'call-b' }),
+ turnSettled({ threadId: T, requestId: 'req-2' }),
+ ],
+ live()
+ );
+ expect(settled.settledTurnsByThread[T]?.['req-2']?.timeline.map(row => row.id)).toEqual([
+ 'call-a',
+ 'call-b',
+ ]);
+ });
+
+ it('still freezes rows whose owner is unknown, as before', () => {
+ // No `inference_start` was seen (e.g. a reconnect mid-turn): no claim
+ // either way, so the reply keeps the rows it is settling with.
+ const settled = run([
+ toolCallReceived({ threadId: T, round: 1, toolName: 'shell', toolCallId: 'call-a' }),
+ turnSettled({ threadId: T, requestId: 'req-9' }),
+ ]);
+ expect(settled.toolTimelineRequestByThread[T]).toBeUndefined();
+ expect(settled.settledTurnsByThread[T]?.['req-9']?.timeline.map(row => row.id)).toEqual([
+ 'call-a',
+ ]);
+ });
});
describe('turn boundaries', () => {
diff --git a/app/src/store/chatRuntimeSlice.ts b/app/src/store/chatRuntimeSlice.ts
index cab38479a4..b1e14c2150 100644
--- a/app/src/store/chatRuntimeSlice.ts
+++ b/app/src/store/chatRuntimeSlice.ts
@@ -893,6 +893,16 @@ interface ChatRuntimeState {
* tell the live turn's own persisted rows apart from earlier ones.
*/
liveRequestIdByThread: Record<string, string>;
+ /**
+ * The `request_id` whose rows {@link toolTimelineByThread} currently holds,
+ * when known: set by the turn's `inference_start` and by a snapshot hydrate,
+ * cleared whenever the timeline is reset. Unlike {@link liveRequestIdByThread}
+ * it survives the turn settling, because the rows do. A reply that settles
+ * with no `inference_start` of its own (a background delivery, a proactive
+ * message) must not adopt another turn's rows as its trail; unknown means
+ * no claim either way.
+ */
+ toolTimelineRequestByThread: Record<string, string>;
/**
* The partial assistant answer left behind by an INTERRUPTED turn (the core
* process that was streaming it is gone), keyed by thread. Surfaced on restore
@@ -970,6 +980,7 @@ const initialState: ChatRuntimeState = {
turnTranscriptsByThread: {},
settledTurnsByThread: {},
liveRequestIdByThread: {},
+ toolTimelineRequestByThread: {},
interruptedAssistantByThread: {},
processingByThread: {},
inferenceTurnLifecycleByThread: {},
@@ -987,6 +998,19 @@ const initialState: ChatRuntimeState = {
* the frozen turn as well as the live timeline so the settled message remains
* current without changing its row identity.
*/
+/**
+ * A row just minted by the live stream belongs to the live turn, when one is
+ * known. With none (its `inference_start` was missed, e.g. a reconnect
+ * mid-turn), the timeline's owner becomes unknown rather than staying the
+ * turn that settled before: a stale claim would make `turnSettled` refuse to
+ * freeze this turn's own rows.
+ */
+function claimTimelineForLiveTurn(state: ChatRuntimeState, threadId: string): void {
+ const live = state.liveRequestIdByThread[threadId];
+ if (live) state.toolTimelineRequestByThread[threadId] = live;
+ else delete state.toolTimelineRequestByThread[threadId];
+}
+
function subagentRows(
state: ChatRuntimeState,
threadId: string,
@@ -1376,9 +1400,15 @@ const chatRuntimeSlice = createSlice({
action: PayloadAction<{ threadId: string; entries: ToolTimelineEntry[] }>
) => {
state.toolTimelineByThread[action.payload.threadId] = action.payload.entries;
+ // A reset starts a timeline nobody owns yet; the next `inference_start`
+ // claims it.
+ if (action.payload.entries.length === 0) {
+ delete state.toolTimelineRequestByThread[action.payload.threadId];
+ }
},
clearToolTimelineForThread: (state, action: PayloadAction<{ threadId: string }>) => {
delete state.toolTimelineByThread[action.payload.threadId];
+ delete state.toolTimelineRequestByThread[action.payload.threadId];
delete state.toolTimelineSeqByThread[action.payload.threadId];
delete state.processingByThread[action.payload.threadId];
},
@@ -1517,6 +1547,7 @@ const chatRuntimeSlice = createSlice({
} else {
const seq = state.toolTimelineSeqByThread[threadId] ?? 0;
state.toolTimelineSeqByThread[threadId] = seq + 1;
+ claimTimelineForLiveTurn(state, threadId);
entries.push(
decorateEntry({
id: rowId,
@@ -1712,6 +1743,7 @@ const chatRuntimeSlice = createSlice({
} else {
const seq = state.toolTimelineSeqByThread[threadId] ?? 0;
state.toolTimelineSeqByThread[threadId] = seq + 1;
+ claimTimelineForLiveTurn(state, threadId);
entries.push(
decorateEntry({
// Same stable fallback `toolCallReceived` generates. This branch
@@ -1831,6 +1863,7 @@ const chatRuntimeSlice = createSlice({
sourceToolName = spawnEntry?.name;
seq = state.toolTimelineSeqByThread[threadId] ?? 0;
state.toolTimelineSeqByThread[threadId] = seq + 1;
+ claimTimelineForLiveTurn(state, threadId);
entries.push(
decorateEntry({
id: rowId,
@@ -1865,6 +1898,7 @@ const chatRuntimeSlice = createSlice({
const spawnSeq = spawnIdx >= 0 ? entries[spawnIdx].seq : undefined;
seq = spawnSeq ?? state.toolTimelineSeqByThread[threadId] ?? 0;
if (spawnSeq === undefined) state.toolTimelineSeqByThread[threadId] = seq + 1;
+ claimTimelineForLiveTurn(state, threadId);
const row = decorateEntry({
id: rowId,
name: `subagent:${agentId}`,
@@ -2486,6 +2520,7 @@ const chatRuntimeSlice = createSlice({
const { threadId, requestId } = action.payload;
if (!requestId || state.parallelRequestThreads[requestId] !== undefined) return;
state.liveRequestIdByThread[threadId] = requestId;
+ state.toolTimelineRequestByThread[threadId] = requestId;
},
/**
* Settle the live turn in ONE store transition.
@@ -2529,7 +2564,13 @@ const chatRuntimeSlice = createSlice({
return;
}
const requestId = action.payload.requestId ?? live;
- if (requestId) {
+ // The live rows are provably another turn's (it settled already and its
+ // rows stayed on screen): this reply arrived without an
+ // `inference_start` of its own. Freezing them here gave the reply a
+ // copy of that turn's trail — a second, stale delegation card.
+ const owner = state.toolTimelineRequestByThread[threadId];
+ const foreignRows = requestId !== undefined && owner !== undefined && owner !== requestId;
+ if (requestId && !foreignRows) {
// Rows are frozen as they are: one still running at `chat_done` has no
// result, and inventing `success` for it is the wrong answer. The core
// projection's terminal status for the same row id is overlaid at
@@ -2579,6 +2620,7 @@ const chatRuntimeSlice = createSlice({
delete state.parallelStreamsByThread[action.payload.threadId];
}
delete state.toolTimelineByThread[action.payload.threadId];
+ delete state.toolTimelineRequestByThread[action.payload.threadId];
delete state.toolTimelineSeqByThread[action.payload.threadId];
delete state.processingByThread[action.payload.threadId];
// `settledTurnsByThread` is kept: those turns are finished, and their
@@ -2609,6 +2651,7 @@ const chatRuntimeSlice = createSlice({
state.turnTranscriptsByThread = {};
state.settledTurnsByThread = {};
state.liveRequestIdByThread = {};
+ state.toolTimelineRequestByThread = {};
state.interruptedAssistantByThread = {};
state.processingByThread = {};
state.inferenceTurnLifecycleByThread = {};
@@ -2781,6 +2824,7 @@ const chatRuntimeSlice = createSlice({
// row count so events arriving after this hydration keep counting
// up rather than restarting at 0 and colliding with existing seqs.
state.toolTimelineSeqByThread[threadId] = snapshot.toolTimeline.length;
+ state.toolTimelineRequestByThread[threadId] = snapshot.requestId;
}
// An interrupted turn was killed mid-answer (its core process is gone,
// so no `chat_done` will ever complete it). The partial reply +
@@ -2843,6 +2887,7 @@ const chatRuntimeSlice = createSlice({
// Persisted order is issue order — seed the live counter with the row
// count so events arriving after this hydration keep counting up.
state.toolTimelineSeqByThread[threadId] = snapshot.toolTimeline.length;
+ state.toolTimelineRequestByThread[threadId] = snapshot.requestId;
state.processingByThread[threadId] = orderTranscriptBySeq(snapshot.transcript ?? []);
},
/**