Skip to content

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

fix(chat): keep scoped deliveries standalone and pair orphan trails only as a bijection\n\nTwo review findings on the assistant-ui projection, both about rows that carry\nno request id.\n\nCoalescing: a background/autonomous delivery persisted by the core has no\nrequest id, exactly like a legacy answer segment, so an adjacent pair merged\ninto one bubble with the delivery's text concatenated and its metadata\noverwriting the earlier row. Core writers stamp `extraMetadata.scope` on every\nsuch delivery and the legacy segmented path never did, so that marker is the\npositive signal: a scoped row is always its own turn and neither joins the run\nbefore it nor seeds the run after it.\n\nOrphan trails: positional pairing of unclaimed per-request trails with\nunanchored agent messages mis-attributes whenever there are more messages than\ntrails — an earlier trail-less answer consumed a later tool-using answer's\ntrail and the real answer rendered bare. Pair only when the two sets are the\nsame size; otherwise render the trail nowhere, which is the lesser wrong.\nTimestamp correlation would attach those too, but needs the turn boundary to\ncarry a timestamp on the wire.\n\nClaude-Session: https://claude.ai/code/session_012jp2WUNkZ8dxDVmDtu3JxX\n

Shanudf137879c08f
diff --git a/app/src/providers/__tests__/assistantUiMessages.test.ts b/app/src/providers/__tests__/assistantUiMessages.test.ts
index 0f6252986a..4a409046e9 100644
--- a/app/src/providers/__tests__/assistantUiMessages.test.ts
+++ b/app/src/providers/__tests__/assistantUiMessages.test.ts
@@ -279,6 +279,84 @@ describe('buildRuntimeMessages', () => {
expect(projected.map(message => message.id)).toEqual(['first', 'second']);
});
+ it('keeps a scoped standalone delivery out of the adjacent legacy runs', () => {
+ // Legacy segments carry no request id; a background delivery persisted by
+ // the core carries no request id either but is stamped with a `scope`.
+ // Without the marker the three rows read as one segmented answer and the
+ // delivery's text and metadata would be folded into its neighbours.
+ const projected = buildRuntimeMessages(
+ [
+ msg({ id: 'seg-a', sender: 'agent', content: 'first paragraph' }),
+ msg({
+ id: 'delivery',
+ sender: 'agent',
+ content: 'Background result: inbox digest',
+ extraMetadata: { scope: 'autonomous_task_result', success: true },
+ }),
+ msg({ id: 'seg-b', sender: 'agent', content: 'a later paragraph' }),
+ ],
+ null
+ );
+
+ expect(projected.map(message => message.id)).toEqual(['seg-a', 'delivery', 'seg-b']);
+ expect(projected[1]?.content).toEqual([
+ { type: 'text', text: 'Background result: inbox digest' },
+ ]);
+ });
+
+ it('does not let a scoped delivery absorb the identified segment before it', () => {
+ const projected = buildRuntimeMessages(
+ [
+ msg({
+ id: 'answer',
+ sender: 'agent',
+ content: 'answer',
+ extraMetadata: { requestId: 'r1' },
+ }),
+ msg({
+ id: 'delivery',
+ sender: 'agent',
+ content: 'worker output',
+ extraMetadata: { scope: 'worker_thread', requestId: 'r-worker' },
+ }),
+ ],
+ null
+ );
+
+ expect(projected.map(message => message.id)).toEqual(['answer', 'delivery']);
+ });
+
+ it('does not hand a later turn trail to an earlier trail-less answer', () => {
+ // Two unanchored answers, one unclaimed trail. Positional pairing would
+ // give the trail to `earlier` (which produced nothing) and leave `later`
+ // (which actually used the tool) bare — a wrong attribution, not a loss.
+ const projected = buildRuntimeMessages(
+ [
+ msg({ id: 'ask-1', content: 'first question' }),
+ msg({ id: 'earlier', sender: 'agent', content: 'plain answer', extraMetadata: {} }),
+ msg({ id: 'ask-2', content: 'second question' }),
+ msg({ id: 'later', sender: 'agent', content: 'tool answer', extraMetadata: {} }),
+ ],
+ null,
+ {
+ isRunning: false,
+ turnTimelines: { 'request-later': [tool({ id: 'later-tool', status: 'success' })] },
+ turnTranscripts: {
+ 'request-later': [{ kind: 'toolCall', round: 1, seq: 0, callId: 'later-tool' }],
+ },
+ }
+ );
+
+ const toolBearing = projected
+ .filter(
+ message =>
+ Array.isArray(message.content) && message.content.some(part => part.type === 'tool-call')
+ )
+ .map(message => message.id);
+ expect(toolBearing).not.toContain('earlier');
+ expect(projected[1]?.content).toEqual([{ type: 'text', text: 'plain answer' }]);
+ });
+
/**
* The crash this guards: assistant-ui keys tool parts as `toolCallId-${id}`
* and throws "Duplicate key … in useResources" on a repeat, taking the whole
diff --git a/app/src/providers/assistantUiMessages.ts b/app/src/providers/assistantUiMessages.ts
index ad39165b82..a261c8a415 100644
--- a/app/src/providers/assistantUiMessages.ts
+++ b/app/src/providers/assistantUiMessages.ts
@@ -262,12 +262,26 @@ function mergeAssistantRun(messages: readonly ThreadMessage[]): ThreadMessage {
};
}
+/**
+ * A row the core persisted as a complete, self-contained delivery — an
+ * autonomous task result, a worker-thread hand-off, a workflow proposal. Core
+ * writers stamp `extraMetadata.scope` on every such row; the legacy segmented
+ * path never did. That positive marker is what tells an async delivery apart
+ * from a paragraph of the answer next to it, since neither carries a request
+ * id on the wire.
+ */
+function isStandaloneDelivery(message: ThreadMessage): boolean {
+ return typeof message.extraMetadata?.scope === 'string';
+}
+
/**
* Collapse legacy paragraph/tool-envelope rows into one assistant turn.
*
* The old interactive-web delivery path persisted each segment as a separate
* agent message. Consecutive assistant rows cannot cross a user turn; when
- * both rows carry request ids, a differing id is the explicit boundary.
+ * both rows carry request ids, a differing id is the explicit boundary, and a
+ * scoped standalone delivery ({@link isStandaloneDelivery}) is always its own
+ * turn — it neither joins the run before it nor seeds the run after it.
*/
function coalesceAssistantSegments(messages: readonly ThreadMessage[]): ThreadMessage[] {
const out: ThreadMessage[] = [];
@@ -286,6 +300,12 @@ function coalesceAssistantSegments(messages: readonly ThreadMessage[]): ThreadMe
out.push(message);
continue;
}
+ if (isStandaloneDelivery(message)) {
+ flush();
+ run.push(message);
+ flush();
+ continue;
+ }
const requestId = requestIdOf(message);
if (run.length > 0 && runRequestId && requestId && runRequestId !== requestId) flush();
run.push(message);
@@ -437,6 +457,21 @@ export function buildRuntimeMessages(
...Object.keys(projection.turnTranscripts ?? {}),
]),
].filter(requestId => !claimedRequestIds.has(requestId));
+ // Async acknowledgements/background deliveries can be persisted without
+ // message-level request metadata. The transcript maps are chronological and
+ // request-keyed, so unclaimed trails can be paired with unanchored agent
+ // messages in order — but only when the two sets are the same size. With a
+ // surplus of unanchored messages, positional pairing hands a later turn's
+ // tools to an earlier trail-less answer and leaves the real answer bare;
+ // rendering those trails nowhere is the lesser wrong.
+ const unanchoredAgentCount = coalescedMessages.filter(
+ message =>
+ message.sender === 'agent' &&
+ !message.extraMetadata?.hidden &&
+ typeof message.extraMetadata?.requestId !== 'string'
+ ).length;
+ const pairOrphanTrails =
+ projectedRequestIds.length > 0 && projectedRequestIds.length === unanchoredAgentCount;
let orphanRequestCursor = 0;
const lastVisibleAgentId = [...coalescedMessages]
.reverse()
@@ -447,13 +482,11 @@ export function buildRuntimeMessages(
msg.sender === 'agent' && typeof msg.extraMetadata?.requestId === 'string'
? msg.extraMetadata.requestId
: undefined;
- // Async acknowledgements/background deliveries can be persisted without
- // message-level request metadata. The transcript maps are chronological
- // and request-keyed, so pair only unclaimed trails with unanchored agent
- // messages in the same order instead of dropping them from assistant-ui.
const effectiveRequestId =
requestId ??
- (msg.sender === 'agent' ? projectedRequestIds[orphanRequestCursor++] : undefined);
+ (msg.sender === 'agent' && pairOrphanTrails
+ ? projectedRequestIds[orphanRequestCursor++]
+ : undefined);
const persistedTimeline = effectiveRequestId
? projection.turnTimelines?.[effectiveRequestId]
: undefined;