Skip to content

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

feat(chat): show reasoning inline again, and fix the order parts render in

M3gA-Mind0c90b99135f3
diff --git a/app/src/providers/__tests__/assistantUiMessages.test.ts b/app/src/providers/__tests__/assistantUiMessages.test.ts
index 5c6d1438b1..d248070a03 100644
--- a/app/src/providers/__tests__/assistantUiMessages.test.ts
+++ b/app/src/providers/__tests__/assistantUiMessages.test.ts
@@ -21,11 +21,11 @@ function msg(over: Partial<ThreadMessage> = {}): ThreadMessage {
};
}
-// `file_write` rather than a read-only name on purpose: only tools that might
-// have changed something outside the app still render on the main surface
-// (`toolRowStaysOnMainSurface`), so a read-only default would make every
-// identity / status / naming assertion below vacuous. The visibility rule
-// itself is covered separately in `main-surface tool visibility`.
+// Every tool row renders on the main surface now, so this default is no longer
+// load-bearing the way it was while a read-only allowlist could drop a row and
+// quietly make the identity / status / naming assertions below vacuous. Left as
+// `file_write` so those assertions keep naming a concrete tool rather than a
+// category boundary.
function tool(over: Partial<ToolTimelineEntry> = {}): ToolTimelineEntry {
return { id: 'call-1', name: 'file_write', round: 1, seq: 0, status: 'running', ...over };
}
@@ -85,20 +85,42 @@ describe('streamingTailMessage', () => {
});
});
- it('keeps streamed thinking off the main surface', () => {
- // Reasoning is not dropped — it stays in `processingByThread` and in the
- // persisted transcript, and renders in the process rail. It just does not
- // belong in the answer stream; `RunningStatus` is the in-flight signal.
+ it('renders streamed thinking as a reasoning part above the answer', () => {
+ // The disclosure is collapsed once settled and held open while it streams,
+ // so this is one quiet line rather than the prose firehose that got the
+ // block removed in the first place. It goes FIRST: it is what the agent
+ // thought before it answered.
const tail = streamingTailMessage({ requestId: 'r', content: 'answer', thinking: 'reasoning' });
- expect(tail?.content).toEqual([{ type: 'text', text: 'answer' }]);
+ expect(tail?.content).toEqual([
+ { type: 'reasoning', text: 'reasoning' },
+ { type: 'text', text: 'answer' },
+ ]);
});
- it('mints no tail at all for a turn that has only produced thinking', () => {
- // Nothing to paint: no answer yet, no visible tool. The status line under
- // the last message is what tells the user the turn is alive.
- expect(streamingTailMessage({ requestId: 'r', content: '', thinking: 'still working' })).toBe(
- null
+ it('does not double the reasoning once the transcript has recorded it', () => {
+ // `assistantParts` already emits the transcript's `thinking` item in its
+ // proper place; the live unshift must stand down or the block renders twice.
+ const tail = streamingTailMessage(
+ { requestId: 'r', content: 'answer', thinking: 'recorded' },
+ [],
+ [{ kind: 'thinking', round: 1, seq: 0, text: 'recorded' }]
);
+ expect(tail?.content).toEqual([
+ { type: 'reasoning', text: 'recorded' },
+ { type: 'text', text: 'answer' },
+ ]);
+ });
+
+ it('mints a reasoning-only tail for a turn that has so far only thought', () => {
+ // There IS something to paint now: the live reasoning block, expanded while
+ // it streams. Before the block came back this minted nothing at all and the
+ // status line carried the whole burden of showing the turn was alive.
+ const tail = streamingTailMessage({ requestId: 'r', content: '', thinking: 'still working' });
+ expect(tail).toMatchObject({
+ id: STREAMING_TAIL_ID,
+ status: { type: 'running' },
+ content: [{ type: 'reasoning', text: 'still working' }],
+ });
});
it('keeps a running delegation on args and adds result only when complete', () => {
@@ -157,12 +179,13 @@ describe('buildRuntimeMessages', () => {
expect(ids).toEqual(['answer']);
expect(ids).not.toContain(STREAMING_TAIL_ID);
expect(projected[0]?.content).toEqual([
+ { type: 'reasoning', text: 'already finished thinking' },
expect.objectContaining({ type: 'tool-call', toolCallId: 'stale-tool' }),
{ type: 'text', text: 'hello' },
]);
});
- it('replays a settled turn tool calls from its request id, without its prose', () => {
+ it('replays a settled turn with its reasoning and tools, but without its narration', () => {
const answer = msg({
id: 'answer',
sender: 'agent',
@@ -182,8 +205,10 @@ describe('buildRuntimeMessages', () => {
turnTranscripts: { 'req-1': transcript },
})[0]?.content
).toEqual([
- // No `reasoning` part and no narration `text` part: both are process and
- // live in the rail. Only the tool row and the answer remain.
+ // Reasoning comes back inline, in the transcript's own order. Narration
+ // does NOT: it is the turn's running commentary, it duplicates the answer
+ // on the final round, and it stays in the rail behind the turn footer.
+ { type: 'reasoning', text: 'need to search' },
expect.objectContaining({
type: 'tool-call',
toolCallId: 'call-1',
@@ -213,6 +238,7 @@ describe('buildRuntimeMessages', () => {
})[0]?.content;
expect(content).toEqual([
+ { type: 'reasoning', text: 'delegate this research' },
expect.objectContaining({ type: 'tool-call', toolCallId: 'async-tool' }),
{ type: 'text', text: 'Accepted background work' },
]);
@@ -265,12 +291,20 @@ describe('buildRuntimeMessages', () => {
expect(projected[1]).toMatchObject({ id: 'final', role: 'assistant' });
// One bubble, carrying the final text once — the intro segment is a prefix
// of it and must not render twice.
- expect(projected[1]?.content).toEqual([{ type: 'text', text: finalText }]);
- // The trail still belongs to the coalesced bubble; it is just no longer
- // painted inline. The timeline row is named `tool` and is renamed to
- // `web_search_tool` from the envelope BEFORE the visibility filter runs, so
- // a recovered name decides visibility exactly as a declared one does — and
- // a search is read-only, so it moves to the rail behind the footer.
+ // The row is minted as `tool` and recovered to `web_search_tool` from the
+ // envelope. That rename used to be asserted only INDIRECTLY, through a
+ // read-only visibility filter that dropped the row once it was renamed —
+ // so with the filter gone the old assertion would have quietly stopped
+ // testing the rename at all. It is named directly here instead.
+ expect(projected[1]?.content).toEqual([
+ expect.objectContaining({
+ type: 'tool-call',
+ toolCallId: 'call-search',
+ toolName: 'web_search_tool',
+ }),
+ { type: 'text', text: finalText },
+ ]);
+ // The trail still belongs to the coalesced bubble.
expect(
(projected[1]?.metadata as { custom?: { processTrail?: unknown } } | undefined)?.custom
?.processTrail
@@ -499,7 +533,7 @@ describe('terminal tool status', () => {
});
});
-describe('main-surface tool visibility', () => {
+describe('main-surface tool rows', () => {
const partsOf = (entries: ToolTimelineEntry[]) =>
toThreadMessageLike(msg({ id: 'a', sender: 'agent', content: 'done' }), entries)
.content as unknown as { type: string; toolCallId?: string }[];
@@ -508,15 +542,16 @@ describe('main-surface tool visibility', () => {
.filter(part => part.type === 'tool-call')
.map(part => part.toolCallId);
- it('drops a read-only step to the rail', () => {
- // Reading, listing and searching are process. The row is not lost — it is
- // still in the timeline the turn footer opens — it just does not stack
- // above the answer.
+ it('renders a read-only step instead of dropping it to the rail', () => {
+ // These four used to be filtered off the surface as "process". They are
+ // back: assistant-ui coalesces consecutive tool rows into ONE collapsed
+ // group, so the clutter argument that justified hiding them no longer
+ // holds — the cost is a count in a group header, and the benefit is that
+ // the transcript shows what the agent actually did.
//
- // `web_search_tool` is the name a real search row carries: `web_search` is
- // the settings-family id the core expands from (`tools/user_filter.rs:79-80`),
- // and it is the canonical name — not the alias — that a live turn produces.
- // Both are asserted so neither can regress.
+ // `web_search_tool` is the name a real search row carries; `web_search` is
+ // the settings-family id the core expands from. Both are asserted so
+ // neither can regress.
expect(
visibleIds([
tool({ id: 'r1', name: 'file_read', seq: 0, status: 'success' }),
@@ -524,13 +559,10 @@ describe('main-surface tool visibility', () => {
tool({ id: 'r3', name: 'web_search_tool', seq: 2, status: 'success' }),
tool({ id: 'r4', name: 'web_search', seq: 3, status: 'success' }),
])
- ).toEqual([]);
+ ).toEqual(['r1', 'r2', 'r3', 'r4']);
});
- it('keeps a tool it cannot prove is read-only', () => {
- // The fail-SAFE direction, and the whole point of the allowlist: an agent
- // sending an email or spending money behind a collapsed panel is a trust
- // problem. An unmapped name lands in `other` and keeps its line.
+ it('renders a side-effecting step', () => {
expect(
visibleIds([
tool({ id: 'w', name: 'file_write', seq: 0, status: 'success' }),
@@ -541,9 +573,7 @@ describe('main-surface tool visibility', () => {
).toEqual(['w', 's', 'x', 'f']);
});
- it('keeps a read-only step that failed or is waiting on the user', () => {
- // An error and a parked approval are the user's to see and to answer, so
- // they outrank the category.
+ it('renders a step that failed or is waiting on the user', () => {
expect(
visibleIds([
tool({ id: 'e', name: 'file_read', seq: 0, status: 'error' }),
@@ -552,13 +582,95 @@ describe('main-surface tool visibility', () => {
).toEqual(['e', 'a']);
});
- it('keeps a delegation row — it is the only door to the sub-agent drawer', () => {
+ it('renders a delegation row — it is the only door to the sub-agent drawer', () => {
expect(visibleIds([tool({ id: 'd', name: 'subagent:researcher', status: 'success' })])).toEqual(
['d']
);
});
});
+describe('part ordering', () => {
+ const contentOf = (
+ entries: ToolTimelineEntry[],
+ transcript: Parameters<typeof toThreadMessageLike>[2]
+ ) =>
+ toThreadMessageLike(msg({ id: 'a', sender: 'agent', content: 'done' }), entries, transcript)
+ .content as unknown as { type: string; toolCallId?: string; text?: string }[];
+
+ it('follows the transcript, reasoning first, answer last', () => {
+ expect(
+ contentOf(
+ [
+ tool({ id: 'c1', seq: 0, status: 'success' }),
+ tool({ id: 'c2', seq: 1, status: 'success' }),
+ ],
+ [
+ { kind: 'thinking', round: 1, seq: 0, text: 'plan it' },
+ { kind: 'toolCall', round: 1, seq: 1, callId: 'c1' },
+ { kind: 'toolCall', round: 1, seq: 2, callId: 'c2' },
+ ]
+ ).map(part => part.toolCallId ?? part.type)
+ ).toEqual(['reasoning', 'c1', 'c2', 'text']);
+ });
+
+ it('places a row the transcript never named by its own seq, not at the end', () => {
+ // THE ordering defect. `c-early` was issued FIRST (seq 0) but no transcript
+ // pointer ever landed for it — a live turn mints the row before the pointer
+ // arrives, and a legacy snapshot has no transcript at all. It used to be
+ // appended after every row the transcript DID name, so the first call the
+ // agent made rendered last.
+ expect(
+ contentOf(
+ [
+ tool({ id: 'c-early', seq: 0, status: 'success' }),
+ tool({ id: 'c-named', seq: 1, status: 'success' }),
+ ],
+ [{ kind: 'toolCall', round: 1, seq: 0, callId: 'c-named' }]
+ ).map(part => part.toolCallId ?? part.type)
+ ).toEqual(['c-early', 'c-named', 'text']);
+ });
+
+ it('keeps an unnamed later row after the named row it followed', () => {
+ // The mirror of the case above, so the fix cannot be "always put unnamed
+ // rows first", which would pass the previous test while still being wrong.
+ expect(
+ contentOf(
+ [
+ tool({ id: 'c-named', seq: 0, status: 'success' }),
+ tool({ id: 'c-late', seq: 1, status: 'success' }),
+ ],
+ [{ kind: 'toolCall', round: 1, seq: 0, callId: 'c-named' }]
+ ).map(part => part.toolCallId ?? part.type)
+ ).toEqual(['c-named', 'c-late', 'text']);
+ });
+
+ it('orders a legacy snapshot with no transcript by seq', () => {
+ expect(
+ contentOf(
+ [
+ tool({ id: 'second', seq: 5, status: 'success' }),
+ tool({ id: 'first', seq: 1, status: 'success' }),
+ ],
+ []
+ ).map(part => part.toolCallId ?? part.type)
+ ).toEqual(['first', 'second', 'text']);
+ });
+
+ it('emits one part for a row two transcript pointers both name', () => {
+ // assistant-ui THROWS on a duplicate `toolCallId` and takes the whole
+ // thread render down, so this is an invariant rather than tidiness.
+ expect(
+ contentOf(
+ [tool({ id: 'dup', seq: 0, status: 'success' })],
+ [
+ { kind: 'toolCall', round: 1, seq: 0, callId: 'dup' },
+ { kind: 'toolCall', round: 1, seq: 1, callId: 'dup' },
+ ]
+ ).filter(part => part.type === 'tool-call')
+ ).toHaveLength(1);
+ });
+});
+
describe('turn process footer metadata', () => {
const trailOf = (message: { metadata?: unknown }) =>
(message.metadata as { custom?: { processTrail?: unknown } } | undefined)?.custom?.processTrail;
diff --git a/app/src/providers/assistantUiMessages.ts b/app/src/providers/assistantUiMessages.ts
index 3c53647f98..7ef23c9df8 100644
--- a/app/src/providers/assistantUiMessages.ts
+++ b/app/src/providers/assistantUiMessages.ts
@@ -15,7 +15,6 @@ import {
type ToolTimelineEntry,
} from '../store/chatRuntimeSlice';
import type { ThreadMessage } from '../types/thread';
-import { categorizeTool, type ToolCategory } from '../utils/toolTimelineFormatting';
/**
* Redux -> assistant-ui message mapping.
@@ -206,78 +205,51 @@ function withApproval(
}
/**
- * Categories `categorizeTool` can prove are read-only. Everything else —
- * including its `other` default, which is where every unmapped tool lands — is
- * treated as potentially side-effecting.
+ * Project one assistant message into assistant-ui parts.
*
- * The direction is the point: this is a fail-SAFE allowlist, not a
- * classification. An agent sending an email or writing a file behind a
- * collapsed panel is a trust problem, not a clutter fix, so an unrecognised
- * tool keeps its line on the main surface. Being wrong here costs one extra
- * row; being wrong the other way hides a real-world action.
+ * The surface carries the turn as it happened: the agent's reasoning as a
+ * COLLAPSED disclosure, every tool row in issue order, then the answer.
*
- * `web_fetch` / `http_request` / `curl` (`fetch`) and `browser*` (`browse`) are
- * deliberately NOT here: a `curl` can POST and a browser click can buy
- * something.
+ * ## What is here, and what stays in the rail
*
- * **This is a stand-in.** The core already models exactly this, precisely, as
- * `PermissionLevel` (`ReadOnly` / `Write` / `Execute` / `Dangerous`,
- * `vendor/tinyagents/vendor/tinytools/.../permission/types.rs:18-30`) on every
- * tool. It is simply not on the wire: `AgentProgress::ToolCallStarted`
- * (`crates/openhuman-core/src/agent/progress.rs:31-47`) carries no permission field, so the
- * renderer cannot see it. When that field is plumbed through to
- * `ToolTimelineEntry`, delete this set and the function below and test
- * `entry.permissionLevel === 'read_only'` instead.
- */
-const READ_ONLY_TOOL_CATEGORIES: ReadonlySet<ToolCategory> = new Set<ToolCategory>([
- 'read',
- 'search',
-]);
-
-/**
- * Whether this tool row still earns a line on the main `/chat` surface.
+ * Reasoning (`kind: 'thinking'`) renders inline again. It is collapsed by
+ * default and expands while it streams, so a turn that thought for ten seconds
+ * shows one quiet line rather than ten seconds of prose — which is what made it
+ * clutter the first time round.
*
- * Read-only steps (reading a file, searching memory, listing) are process, and
- * move to the rail behind the turn footer. Everything else keeps one line:
+ * Narration is deliberately NOT restored. It is the turn's running commentary,
+ * it duplicates the answer on the final round, and it is the bulk of what made
+ * the old surface a firehose. It stays in `processingByThread` and renders in
+ * the process rail behind {@link TurnProcessTrail}, which is unchanged.
*
- * - anything not provably read-only — the side-effect exception above;
- * - a failed call, because an error is the user's to see;
- * - a parked call, because an approval gate is the user's to answer. The part's
- * `approval` is attached later by {@link withApproval}, so the check here is
- * on the row's own `awaiting_user` status.
+ * ## Ordering
*
- * A `subagent:*` delegation also stays, for two reasons that outrank tidiness:
- * its card is the only route to the sub-agent drawer on this surface (see
- * `ChatToolParts.SubagentCall`), and a delegation spends real money and can act
- * outside the app through its own tools. Its *transcript* is already behind the
- * drawer, which is where the brief wanted it; the row itself is one line.
- */
-function toolRowStaysOnMainSurface(entry: ToolTimelineEntry): boolean {
- if (entry.status === 'error' || entry.status === 'awaiting_user') return true;
- if (entry.name.startsWith('subagent:')) return true;
- return !READ_ONLY_TOOL_CATEGORIES.has(categorizeTool(entry.name));
-}
-
-/**
- * Project one assistant message into assistant-ui parts.
+ * The transcript is the ordered record of the turn and is walked in array
+ * order. Timeline rows the transcript never names — a legacy snapshot has no
+ * transcript at all, and a live turn can mint a row before its pointer lands —
+ * are merged in by their own `seq` rather than appended after everything else,
+ * which is what previously let a row the agent issued FIRST render last.
+ *
+ * The two `seq` fields are NOT one ordering space, whatever
+ * `PersistedToolTimelineEntry.seq`'s doc comment says: a transcript item's
+ * `seq` is its index in the transcript array (`chatRuntimeSlice.ts`, the
+ * `toolCall` push uses `seq: list.length`) while a timeline row's comes from
+ * the per-thread `toolTimelineSeqByThread` counter. So the merge below compares
+ * timeline `seq` to timeline `seq` only, never across the two.
*
- * The main surface carries **the answer, plus anything the user must see or
- * act on** — a failed or parked tool call, and any call that might have changed
- * something outside the app. The agent's *explanation* of how it got there —
- * reasoning, narration prose, and the arguments and results of read-only steps
- * — is not dropped: it stays in Redux and in the persisted transcript, and
- * renders in the process rail reached from the turn footer
- * (`TurnFooter` → `AgentProcessSourcePanel`). Nothing here changes what is
- * stored, only what is painted.
+ * The answer text is appended last, and that is correct rather than merely
+ * convenient: it is the persisted `msg.content`, i.e. what the agent said when
+ * it had finished, so nothing it produced can belong after it. Anything the
+ * agent said BEFORE a tool call is narration, which lives in the rail.
*
* **Every tool part must have a distinct `toolCallId`.** assistant-ui keys them
* as `toolCallId-${id}` and *throws* on a repeat ("Duplicate key … in
* useResources"), which takes the whole thread render down rather than dropping
* a row — so this is a hard invariant, not a tidiness rule, and it is enforced
- * here at the boundary as well as at each producer. `emittedToolIds` guards
- * both passes below; the sources upstream (the live Redux slice and the derived
- * transcript mapper) also mint unique ids, but threads persisted before those
- * fixes still carry colliding ones.
+ * here at the boundary as well as at each producer. `claim` guards every emit
+ * below; the sources upstream (the live Redux slice and the derived transcript
+ * mapper) also mint unique ids, but threads persisted before those fixes still
+ * carry colliding ones.
*/
function assistantParts(
text: string,
@@ -287,36 +259,53 @@ function assistantParts(
const parts: ThreadAssistantMessagePart[] = [];
const timelineById = new Map(timeline.map(entry => [entry.id, entry]));
const emittedToolIds = new Set<string>();
- // A row is considered once, whether or not it is painted. Both passes apply
- // the same filter, so this is belt-and-braces rather than load-bearing — it
- // is here so the two can never disagree and mint a duplicate `toolCallId`,
- // which assistant-ui throws on.
const claim = (entry: ToolTimelineEntry): boolean => {
if (emittedToolIds.has(entry.id)) return false;
emittedToolIds.add(entry.id);
return true;
};
+ // Rows the transcript names. Two pointers can resolve to the same row (a
+ // provider that emits tool calls without ids writes the empty string for all
+ // of them), which is why this is a set of resolved row ids rather than a
+ // count of pointers.
+ const referenced = new Set<string>();
for (const item of transcript) {
- // `thinking` and `narration` are the turn's explanation of itself. Both
- // live on in `processingByThread` / the persisted transcript and render in
- // the rail; neither belongs in the answer stream.
- if (item.kind === 'toolCall') {
- const entry = timelineById.get(item.callId);
- // Guarded here too, not only in the timeline pass below: two transcript
- // pointers can name the same `callId` (a provider that emits tool calls
- // without ids writes the empty string for all of them), and both resolve
- // to the same timeline row.
- if (entry && claim(entry) && toolRowStaysOnMainSurface(entry)) {
- parts.push(toolPart(entry));
- }
- }
+ if (item.kind !== 'toolCall') continue;
+ const entry = timelineById.get(item.callId);
+ if (entry) referenced.add(entry.id);
}
- for (const entry of [...timeline].sort((a, b) => a.seq - b.seq)) {
- if (!claim(entry)) continue;
- if (toolRowStaysOnMainSurface(entry)) parts.push(toolPart(entry));
+ // Rows with no pointer, oldest first. These are merged into the walk below
+ // rather than appended after it.
+ const unreferenced = timeline
+ .filter(entry => !referenced.has(entry.id))
+ .sort((a, b) => a.seq - b.seq);
+ let nextUnreferenced = 0;
+ /** Emit every unreferenced row the agent issued before `seq` (all of them at the end). */
+ const drainBefore = (seq: number | null) => {
+ while (nextUnreferenced < unreferenced.length) {
+ const entry = unreferenced[nextUnreferenced];
+ if (entry === undefined || (seq !== null && entry.seq >= seq)) break;
+ nextUnreferenced += 1;
+ if (claim(entry)) parts.push(toolPart(entry));
+ }
+ };
+
+ for (const item of transcript) {
+ if (item.kind === 'thinking') {
+ if (item.text.trim().length > 0) parts.push({ type: 'reasoning', text: item.text });
+ continue;
+ }
+ // Narration is the turn explaining itself; it stays in the rail.
+ if (item.kind !== 'toolCall') continue;
+ const entry = timelineById.get(item.callId);
+ if (!entry) continue;
+ drainBefore(entry.seq);
+ if (claim(entry)) parts.push(toolPart(entry));
}
+ drainBefore(null);
+
if (text.length > 0) parts.push({ type: 'text', text });
return parts;
}
@@ -574,11 +563,20 @@ export function streamingTailMessage(
): ThreadMessageLike | null {
if (!approval && !streaming && timeline.length === 0 && transcript.length === 0) return null;
const text = streaming?.content ?? '';
- // `streaming.thinking` is deliberately not projected: reasoning does not
- // render on the main surface any more. While the turn runs, `RunningStatus`
- // is the in-flight signal; the thinking itself is in `processingByThread`
- // and reachable through the rail. See `assistantParts`.
let parts = assistantParts(text, timeline, transcript);
+ // The live reasoning block. Only when the transcript has not yet recorded a
+ // `thinking` item for this turn — once it has, `assistantParts` above is
+ // already emitting it in its proper place and this would double it.
+ //
+ // It goes FIRST because it is what the agent thought before it answered, and
+ // `Reasoning` renders it expanded while it streams, then collapses it. A turn
+ // that has so far produced only thinking now mints a tail rather than
+ // nothing, which is the point: the block is the in-flight signal, alongside
+ // `RunningStatus`.
+ if (streaming?.thinking.trim()) {
+ const hasTranscriptThinking = transcript.some(item => item.kind === 'thinking');
+ if (!hasTranscriptThinking) parts.unshift({ type: 'reasoning', text: streaming.thinking });
+ }
if (approval) parts = withApproval(parts, approval);
if (parts.length === 0) return null;
return {