The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
Merge upstream/main into chat-stream-parity
Steven Enamakel08abd16b859c
diff --cc app/src/components/assistant-ui/elements/reasoning-panel.test.tsxindex 0000000000,73f31c3bda..f6a352c656mode 000000,100644..100644--- a/app/src/components/assistant-ui/elements/reasoning-panel.test.tsx+++ b/app/src/components/assistant-ui/elements/reasoning-panel.test.tsx@@@ -1,0 -1,280 +1,286 @@@+ import { act, fireEvent, render, screen } from '@testing-library/react';+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++ import { ReasoningPanel } from './reasoning-panel';+ import { ReasoningTrace, ReasoningTraceText } from './reasoning-trace';++ /**+ * Regression coverage for the static reasoning panel (assistant-ui+ * `elements-reasoning-panel`) and the `ReasoningTrace` wrapper every surface+ * renders through. These pin the behaviours the reasoning boxes used to get+ * wrong: a hard-coded "Reasoning" label, no duration ever shown, a shimmer+ * class that styled nothing, and one opaque block instead of titled steps.+ */++ const STEPS = [+ { title: 'Reading the request', body: 'The user wants **a summary**.' },+ { title: 'Planning the fix', body: '- patch parser\n- add tests' },+ ];++ const trigger = () => screen.getByRole('button');+ // `SwapLabel` stacks the live and resting labels as two layers and hides the+ // inactive one with aria-hidden.+ const liveLayer = (root: HTMLElement) =>+ root.querySelector('[data-slot="reasoning-panel-live-label"]')!.parentElement as HTMLElement;+ const restingLayer = (root: HTMLElement) =>+ root.querySelector('[data-slot="reasoning-panel-resting-label"]')!.parentElement as HTMLElement;++ describe('ReasoningPanel (collapsible)', () => {+ it('renders titled steps with markdown bodies when open', () => {+ render(+ <ReasoningPanel+ steps={STEPS}+ streaming={false}+ defaultOpen+ liveLabel="Thinking"+ restingLabel="Thought for 12s"+ />+ );+ const titles = screen.getAllByText(/Reading the request|Planning the fix/);+ expect(titles.map(el => el.textContent)).toEqual(['Reading the request', 'Planning the fix']);+ // Body markdown is rendered, not shown as raw syntax.+ expect(screen.getByText('a summary').tagName).toBe('STRONG');+ expect(screen.getAllByRole('listitem').some(li => li.textContent === 'patch parser')).toBe(+ true+ );+ });++ it('is collapsed by default once settled and shows the resting label', () => {+ const { container } = render(+ <ReasoningPanel+ steps={STEPS}+ streaming={false}+ liveLabel="Thinking"+ restingLabel="Thought for 12s"+ data-testid="panel"+ />+ );+ expect(trigger().getAttribute('aria-expanded')).toBe('false');+ expect(screen.queryByText('Reading the request')).toBeNull();+ const root = screen.getByTestId('panel');+ expect(restingLayer(root).textContent).toBe('Thought for 12s');+ expect(restingLayer(root).getAttribute('aria-hidden')).toBe('false');+ expect(liveLayer(root).getAttribute('aria-hidden')).toBe('true');+ expect(container.querySelector('.shimmer')).toBeNull();+ });++ it('toggles open and closed from the trigger', () => {+ render(+ <ReasoningPanel steps={STEPS} streaming={false} liveLabel="Thinking" restingLabel="Thought" />+ );+ fireEvent.click(trigger());+ expect(trigger().getAttribute('aria-expanded')).toBe('true');+ expect(screen.getByText('Planning the fix')).toBeTruthy();+ fireEvent.click(trigger());+ expect(trigger().getAttribute('aria-expanded')).toBe('false');+ });++ it('opens while streaming with a shimmering live label and elapsed badge', () => {+ const { container } = render(+ <ReasoningPanel+ steps={STEPS}+ streaming+ liveLabel="Planning the fix"+ restingLabel="Thought"+ elapsed="4s"+ data-testid="panel"+ />+ );+ const root = screen.getByTestId('panel');+ expect(trigger().getAttribute('aria-expanded')).toBe('true');+ expect(liveLayer(root).getAttribute('aria-hidden')).toBe('false');+ const shimmer = container.querySelector('.shimmer');+ expect(shimmer?.textContent).toBe('Planning the fix');+ expect(shimmer?.className).toContain('shimmer');+ expect(root.querySelector('[data-slot="reasoning-panel-elapsed"]')?.textContent).toBe('4s');+ // The newest step is the active one on the timeline.+ const steps = root.querySelectorAll('[data-slot="reasoning-panel-step"]');+ expect(steps[steps.length - 1]?.hasAttribute('data-active')).toBe(true);+ expect(steps[0]?.hasAttribute('data-active')).toBe(false);+ });++ it('collapses when streaming ends, unless the reader toggled it', () => {+ const props = { steps: STEPS, liveLabel: 'Thinking', restingLabel: 'Thought for 3s' };+ const onAnimationStart = vi.fn();+ const { rerender } = render(+ <ReasoningPanel {...props} streaming onAnimationStart={onAnimationStart} />+ );+ expect(trigger().getAttribute('aria-expanded')).toBe('true');+ rerender(<ReasoningPanel {...props} streaming={false} onAnimationStart={onAnimationStart} />);+ expect(trigger().getAttribute('aria-expanded')).toBe('false');++ // The automatic collapse does not take the host's scroll lock: it runs++ // while the thread follows the reply to the bottom, and the lock dragging++ // `scrollTop` back read as the reader scrolling away — following stopped++ // for the rest of the turn. Only the reader's own toggle locks.++ expect(onAnimationStart).not.toHaveBeenCalled();++ fireEvent.click(trigger());+ expect(onAnimationStart).toHaveBeenCalledTimes(1);++ // A second instance the reader keeps open across the transition.+ const second = render(<ReasoningPanel {...props} streaming data-testid="kept" />);+ const keptTrigger = second.getByTestId('kept').querySelector('button')!;+ fireEvent.click(keptTrigger); // close+ fireEvent.click(keptTrigger); // reopen: the reader has taken over+ second.rerender(<ReasoningPanel {...props} streaming={false} data-testid="kept" />);+ expect(keptTrigger.getAttribute('aria-expanded')).toBe('true');+ });++ it('disables the trigger and hides the chevron when there are no steps yet', () => {+ const { container } = render(+ <ReasoningPanel steps={[]} streaming liveLabel="Thinking" restingLabel="Thought" />+ );+ expect((trigger() as HTMLButtonElement).disabled).toBe(true);+ expect(container.querySelector('svg')).toBeNull();+ });++ it('reveals only visibleSteps, clamping out-of-range values', () => {+ const { rerender } = render(+ <ReasoningPanel+ steps={STEPS}+ visibleSteps={1}+ streaming+ liveLabel="Thinking"+ restingLabel="Thought"+ />+ );+ expect(screen.getAllByRole('listitem', { hidden: true }).length).toBeGreaterThanOrEqual(1);+ expect(screen.queryByText('Planning the fix')).toBeNull();+ rerender(+ <ReasoningPanel+ steps={STEPS}+ visibleSteps={-3}+ streaming+ liveLabel="Thinking"+ restingLabel="Thought"+ />+ );+ expect(screen.queryByText('Reading the request')).toBeNull();+ });+ });++ describe('ReasoningPanel (non-collapsible)', () => {+ it('renders the header and steps inline with no disclosure button', () => {+ render(+ <ReasoningPanel+ steps={STEPS}+ streaming={false}+ collapsible={false}+ liveLabel="Thinking"+ restingLabel="Thought for 12s"+ data-testid="static"+ />+ );+ expect(screen.queryByRole('button')).toBeNull();+ const root = screen.getByTestId('static');+ expect(root.getAttribute('data-variant')).toBe('static');+ expect(screen.getByText('Reading the request')).toBeTruthy();+ expect(screen.getByText('Planning the fix')).toBeTruthy();+ expect(restingLayer(root).textContent).toBe('Thought for 12s');+ });++ it('bounds and marks a live trace as busy while streaming', () => {+ render(+ <ReasoningPanel+ steps={STEPS}+ streaming+ collapsible={false}+ liveLabel="Planning the fix"+ restingLabel="Thought"+ data-testid="static"+ />+ );+ const root = screen.getByTestId('static');+ expect(root.getAttribute('aria-busy')).toBe('true');+ expect(root.querySelector('[data-slot="reasoning-panel-scroll"]')?.className).toContain(+ 'max-h-80'+ );+ });+ });++ describe('ReasoningTrace', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-09-24T10:00:10Z'));+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ const start = Date.parse('2026-09-24T10:00:00Z');++ it('shows "Thought for Ns" from the recorded timestamps once settled', () => {+ render(+ <ReasoningTrace+ texts={['**Reading**\nok']}+ timings={[{ startedAt: start, endedAt: start + 12_000 }]}+ streaming={false}+ data-testid="trace"+ />+ );+ expect(restingLayer(screen.getByTestId('trace')).textContent).toBe('Thought for 12s');+ });++ it('spans several parts: earliest start to latest end', () => {+ render(+ <ReasoningTrace+ texts={['**A**\na', '**B**\nb']}+ timings={[+ { startedAt: start, endedAt: start + 2_000 },+ { startedAt: start + 30_000, endedAt: start + 75_000 },+ ]}+ streaming={false}+ data-testid="trace"+ />+ );+ expect(restingLayer(screen.getByTestId('trace')).textContent).toBe('Thought for 1m 15s');+ });++ it('falls back to "Thought" for rows recorded before timing existed', () => {+ render(<ReasoningTrace texts={['plain text.']} streaming={false} data-testid="trace" />);+ expect(restingLayer(screen.getByTestId('trace')).textContent).toBe('Thought');+ });++ it('ticks the elapsed badge every second while streaming', () => {+ render(+ <ReasoningTrace+ texts={['**Planning the fix**\nworking']}+ timings={[{ startedAt: start, endedAt: start + 1_000 }]}+ streaming+ data-testid="trace"+ />+ );+ const badge = () =>+ screen.getByTestId('trace').querySelector('[data-slot="reasoning-panel-elapsed"]')+ ?.textContent;+ expect(badge()).toBe('10s');+ act(() => {+ vi.advanceTimersByTime(3_000);+ });+ expect(badge()).toBe('13s');+ });++ it('uses the newest heading as the live label, "Thinking" before any heading', () => {+ const { rerender } = render(+ <ReasoningTrace texts={['still working this out']} streaming data-testid="trace" />+ );+ const live = () =>+ screen.getByTestId('trace').querySelector('[data-slot="reasoning-panel-live-label"]')+ ?.textContent;+ expect(live()).toBe('Thinking');+ rerender(+ <ReasoningTrace+ texts={['**Reading**\nok\n**Planning the fix**\nnext']}+ streaming+ data-testid="trace"+ />+ );+ expect(live()).toBe('Planning the fix');+ });++ it('never renders the old hard-coded "Reasoning" label', () => {+ const { container } = render(+ <ReasoningTraceText text="**Plan**\nx" streaming={false} data-testid="trace" />+ );+ expect(container.textContent).not.toMatch(/\bReasoning\b/);+ });+ });diff --cc app/src/components/assistant-ui/elements/reasoning-panel.tsxindex 0000000000,9ea75c7d7d..a4d636f875mode 000000,100644..100644--- a/app/src/components/assistant-ui/elements/reasoning-panel.tsx+++ b/app/src/components/assistant-ui/elements/reasoning-panel.tsx@@@ -1,0 -1,279 +1,279 @@@+ 'use client';++ /**+ * The static reasoning element, vendored from assistant-ui's+ * `elements-reasoning-panel` registry item+ * (https://r.assistant-ui.com/elements-reasoning-panel.json). The markup and+ * classes are upstream's; the local additions are all behavioural:+ *+ * - `collapsible={false}` renders the same header and step list with no+ * disclosure, for surfaces where reasoning stays inline and visible.+ * - `open` is optional. Uncontrolled, it follows the runtime reasoning+ * element's rule: open while streaming, back to `defaultOpen` once settled,+ * and a manual toggle wins from then on.+ * - `liveLabel` replaces the hard-coded "Thinking" (the newest step title+ * reads best, Codex style) and localizes it.+ * - Step bodies render through the registry's own `MarkdownText` (via+ * assistant-ui's `TextMessagePartProvider`) instead of a plain `<p>`.+ * - A streaming list stays pinned to its newest step inside a bounded+ * scroll region (the runtime element's `ReasoningText` behaviour).+ */+ import { cn } from '@/components/assistant-ui/lib/utils';+ import { MarkdownText } from '@/components/assistant-ui/markdown-text';+ import {+ Collapsible,+ CollapsibleContent,+ CollapsibleTrigger,+ } from '@/components/assistant-ui/ui/collapsible';+ import { TextMessagePartProvider } from '@assistant-ui/react';+ import { ChevronDownIcon } from 'lucide-react';+ import { useCallback, useEffect, useRef, useState } from 'react';++ import { take } from '../utils/range';+ import type { ReasoningStep } from './reasoningSteps';+ import { collapsePanel, mono, ShimmerLabel, SwapLabel } from './surfaces';++ export type { ReasoningStep } from './reasoningSteps';++ export interface ReasoningPanelProps {+ steps: readonly ReasoningStep[];+ /** How many steps to reveal; defaults to all of them. */+ visibleSteps?: number;+ streaming: boolean;+ /** Label once streaming ends, e.g. "Thought for 12s". */+ restingLabel: string;+ /** Label while streaming (upstream hard-codes "Thinking"). */+ liveLabel: string;+ /** Elapsed badge beside the live label, e.g. "4s". */+ elapsed?: string;+ /** Disclosure (default) or an always-visible trace. */+ collapsible?: boolean;+ open?: boolean;+ onOpenChange?: (open: boolean) => void;+ defaultOpen?: boolean;+ /** Called right before the disclosure animates (scroll-lock hook point). */+ onAnimationStart?: () => void;+ className?: string;+ 'data-testid'?: string;+ }++ /**+ * Keeps a bounded scroll region pinned to its newest content while `active`;+ * following pauses while the reader is scrolled up. Ported from the runtime+ * reasoning element's `ReasoningText`.+ */+ function usePinnedScroll(active: boolean) {+ const scrollRef = useRef<HTMLDivElement>(null);+ const contentRef = useRef<HTMLOListElement>(null);++ useEffect(() => {+ if (!active) return;+ const scrollEl = scrollRef.current;+ const contentEl = contentRef.current;+ if (!scrollEl || !contentEl) return;++ let pinned = true;+ let lastScrollTop = scrollEl.scrollTop;+ let lastScrollHeight = scrollEl.scrollHeight;+ const isAtBottom = () =>+ Math.abs(scrollEl.scrollHeight - scrollEl.scrollTop - scrollEl.clientHeight) <= 1 ||+ scrollEl.scrollHeight <= scrollEl.clientHeight;+ const pin = () => {+ if (pinned) scrollEl.scrollTop = scrollEl.scrollHeight;+ };+ // A pin's own scroll event can land after new content grew the height and+ // read as "not at bottom"; only an upward move at unchanged height is the+ // reader's intent.+ const onScroll = () => {+ if (isAtBottom()) pinned = true;+ else if (scrollEl.scrollTop < lastScrollTop && scrollEl.scrollHeight === lastScrollHeight) {+ pinned = false;+ }+ lastScrollTop = scrollEl.scrollTop;+ lastScrollHeight = scrollEl.scrollHeight;+ };++ pin();+ scrollEl.addEventListener('scroll', onScroll);+ const observer = new ResizeObserver(pin);+ observer.observe(contentEl);+ return () => {+ scrollEl.removeEventListener('scroll', onScroll);+ observer.disconnect();+ };+ }, [active]);++ return { scrollRef, contentRef };+ }++ function PanelLabel({+ streaming,+ liveLabel,+ restingLabel,+ elapsed,+ }: Pick<ReasoningPanelProps, 'streaming' | 'liveLabel' | 'restingLabel' | 'elapsed'>) {+ return (+ <SwapLabel active={streaming ? 0 : 1} className="text-start">+ <>+ <ShimmerLabel+ active={streaming}+ data-slot="reasoning-panel-live-label"+ className="relative inline-block leading-none">+ {liveLabel}+ </ShimmerLabel>+ {elapsed !== undefined && (+ <span+ data-slot="reasoning-panel-elapsed"+ className={cn(mono, 'text-foreground/30 tabular-nums')}>+ {elapsed}+ </span>+ )}+ </>+ <span data-slot="reasoning-panel-resting-label">{restingLabel}</span>+ </SwapLabel>+ );+ }++ function StepList({+ steps,+ streaming,+ bounded,+ }: {+ steps: readonly ReasoningStep[];+ streaming: boolean;+ bounded: boolean;+ }) {+ const { scrollRef, contentRef } = usePinnedScroll(streaming && bounded);+ return (+ <div+ ref={scrollRef}+ data-slot="reasoning-panel-scroll"+ className={cn(bounded && 'max-h-80 overflow-y-auto')}>+ <ol ref={contentRef} className="flex flex-col gap-4 pt-3 pb-1">+ {steps.map((step, i) => {+ const active = streaming && i === steps.length - 1;+ return (+ <li+ // Titles can repeat across rounds, so the index is the key.+ key={i}+ data-slot="reasoning-panel-step"+ data-active={active ? '' : undefined}+ className="fade-in slide-in-from-bottom-1 animate-in fill-mode-both flex gap-3 duration-300">+ <span+ aria-hidden+ className={cn(+ 'mt-[7px] size-[5px] shrink-0 rounded-full transition-colors duration-300',+ active ? 'animate-pulse bg-blue-500 dark:bg-blue-400' : 'bg-foreground/20'+ )}+ />+ <span className="flex min-w-0 flex-1 flex-col">+ <p+ data-slot="reasoning-step-title"+ className="text-foreground/90 text-[13.5px] font-medium">+ {step.title}+ </p>+ {step.body ? (+ <div+ data-slot="reasoning-step-body"+ className="text-foreground/50 mt-0.5 text-[13px] leading-relaxed break-words">+ <TextMessagePartProvider text={step.body} isRunning={active}>+ <MarkdownText />+ </TextMessagePartProvider>+ </div>+ ) : null}+ </span>+ </li>+ );+ })}+ </ol>+ </div>+ );+ }++ export function ReasoningPanel({+ steps,+ visibleSteps,+ streaming,+ restingLabel,+ liveLabel,+ elapsed,+ collapsible = true,+ open: controlledOpen,+ onOpenChange,+ defaultOpen = false,+ onAnimationStart,+ className,+ 'data-testid': testId,+ }: ReasoningPanelProps) {+ const shown = take(steps, visibleSteps ?? steps.length);+ const [userOpen, setUserOpen] = useState<boolean | null>(null);+ const isControlled = controlledOpen !== undefined;+ const isOpen = isControlled ? controlledOpen : (userOpen ?? (streaming || defaultOpen));++ // Streaming → settled collapses the panel (unless the reader took over),- // an animation the host may need to scroll-lock.- const prevStreaming = useRef(streaming);- useEffect(() => {- if (prevStreaming.current === streaming) return;- prevStreaming.current = streaming;- if (!isControlled && userOpen === null && !defaultOpen) onAnimationStart?.();- }, [streaming, isControlled, userOpen, defaultOpen, onAnimationStart]);++ // and that collapse deliberately does NOT call `onAnimationStart`. The host++ // wires it to assistant-ui's `useScrollLock`, which pins `scrollTop` by++ // writing it back on every scroll event for the animation's length — and an++ // automatic collapse happens while the thread is following the reply to the++ // bottom. The follower scrolled down, the lock dragged it back, and the++ // follower read the drop as the reader leaving: following stopped for the++ // rest of the turn. The lock is for a toggle the READER makes (below).++ const handleOpenChange = useCallback(+ (next: boolean) => {+ onAnimationStart?.();+ if (!isControlled) setUserOpen(next);+ onOpenChange?.(next);+ },+ [onAnimationStart, isControlled, onOpenChange]+ );++ const label = (+ <PanelLabel+ streaming={streaming}+ liveLabel={liveLabel}+ restingLabel={restingLabel}+ elapsed={elapsed}+ />+ );++ if (!collapsible) {+ return (+ <div+ data-slot="reasoning-panel"+ data-variant="static"+ data-testid={testId}+ aria-busy={streaming || undefined}+ className={cn('w-full', className)}>+ <div className="text-foreground/55 flex items-center gap-1.5 py-1 text-[13.5px]">+ {label}+ </div>+ {shown.length > 0 && <StepList steps={shown} streaming={streaming} bounded={streaming} />}+ </div>+ );+ }++ return (+ <Collapsible+ data-slot="reasoning-panel"+ data-variant="collapsible"+ data-testid={testId}+ open={isOpen}+ onOpenChange={handleOpenChange}+ className={cn('w-full', className)}>+ <CollapsibleTrigger+ disabled={shown.length === 0}+ className="group/trigger text-foreground/55 hover:text-foreground/90 flex items-center gap-1.5 py-1 text-[13.5px] transition-[color,scale] outline-none active:scale-[0.98] disabled:pointer-events-none">+ {label}+ {shown.length > 0 && (+ <ChevronDownIcon className="size-3.5 shrink-0 opacity-60 transition-transform duration-200 ease-[cubic-bezier(0.32,0.72,0,1)] group-data-[state=open]/trigger:rotate-180 motion-reduce:transition-none" />+ )}+ </CollapsibleTrigger>+ <CollapsibleContent+ aria-busy={streaming || undefined}+ className={cn(collapsePanel, 'outline-none')}>+ <StepList steps={shown} streaming={streaming} bounded />+ </CollapsibleContent>+ </Collapsible>+ );+ }diff --cc app/src/providers/assistantUiMessages.tsindex fde6fb1a77,bb26a5aeca..33b13cd126--- a/app/src/providers/assistantUiMessages.ts+++ b/app/src/providers/assistantUiMessages.ts@@@ -225,33 -244,21 +244,37 @@@ export function reasoningPart/*** Project one assistant message into assistant-ui parts.*- * 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.+ * The surface carries the turn as it happened, in the order it happened:+ * reasoning as a disclosure, what the agent said between tool rounds, every+ * tool row where it was issued, then the answer.*- * ## What is here, and what stays in the rail+ * ## One shape, live and settled*- * Reasoning (`kind: 'thinking'`) renders inline again, through the static- * reasoning panel: collapsed by default to one "Thought for Ns" line, expanded- * into titled steps 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.+ * The live tail and the settled message are the SAME projection of the same+ * transcript, and that is the property everything else here serves. A live+ * turn that projected differently from its settled self (text always last,+ * narration shown then wiped, reasoning unshifted to the front) re-shaped on+ * every event and again at completion — and assistant-ui keys text and+ * reasoning parts by their INDEX, so each reshaping remounted the markdown,+ * restarted its reveal from nothing, reset every disclosure and jumped the+ * scroll. So:*- * 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.++ * - **Reasoning** (`kind: 'thinking'`) renders through the static reasoning++ * panel: one "Thought for Ns" line once settled, titled steps while it++ * streams.++ *+ * - **Narration renders inline** where it was said, live and on reload. It is+ * the agent explaining the call it is about to make; showing it and then+ * wiping it was the flicker, never showing it on reload was the mismatch.+ * - **Parts are append-only while a turn streams.** New events add parts at+ * the end; nothing is inserted before an existing part.+ * - **The answer takes the final narration's slot.** Live, the final round's+ * text IS a narration item (`streamDeltaReceived` coalesces every content+ * delta into one per round). Settled, the persisted `msg.content` is that+ * same text, so narration after the turn's last tool call is replaced by the+ * answer in place: same index, same key, no remount at completion. The core+ * projection (`mapDisplayItems`) only emits interim narration, so a reloaded+ * turn has no trailing narration and the answer lands in the same place.** ## Ordering*@@@ -321,28 -330,15 +344,30 @@@ function assistantParts}};- for (const item of transcript) {+ // Settled: narration after the last tool call is the answer, spoken live;+ // the persisted answer replaces it in its slot. With no answer to show+ // (an empty or stopped reply) the narration stays — it is all there is.+ const answerText = answer.trim().length > 0 ? answer : '';+ const replaceTrailingNarration = mode === 'settled' && answerText.length > 0;+ let answerEmitted = false;++ for (const [index, item] of transcript.entries()) {if (item.kind === 'thinking') {- if (item.text.trim().length > 0) parts.push({ type: 'reasoning', text: item.text });+ if (item.text.trim().length > 0) {+ parts.push(reasoningPart(item.text, item.startedAt, item.endedAt));+ }continue;}- // Narration is the turn explaining itself; it stays in the rail.- if (item.kind !== 'toolCall') continue;+ if (item.kind === 'narration') {+ if (item.text.trim().length === 0) continue;+ if (replaceTrailingNarration && index > lastToolPointer) {+ if (!answerEmitted) parts.push({ type: 'text', text: answerText });+ answerEmitted = true;+ continue;+ }+ parts.push({ type: 'text', text: item.text });+ continue;+ }const entry = timelineById.get(item.callId);if (!entry) continue;drainBefore(entry.seq);@@@ -634,23 -622,24 +659,25 @@@ export function streamingTailMessageapproval: PendingApproval | null = null): ThreadMessageLike | null {if (!approval && !streaming && timeline.length === 0 && transcript.length === 0) return null;- const text = streaming?.content ?? '';- 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.+ let parts = assistantParts('', timeline, transcript, 'live');+ // The streaming buffers, for a turn whose transcript has not recorded them+ // (a snapshot-hydrated turn mid-answer): normally `streamDeltaReceived`+ // writes every thinking and content delta into the transcript as well, and+ // `assistantParts` above already emits them in place — these would double+ // them. Reasoning before text: what the agent thought before it answered.//- // 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(- reasoningPart(streaming.thinking, streaming.thinkingStartedAt, streaming.thinkingEndedAt)- );- }+ // Appended, never unshifted: the tail's parts are append-only (see+ // `assistantParts`), and a part inserted at the front shifts the index — and+ // so the key — of every part after it, remounting the answer mid-stream. A+ // turn that has so far produced only thinking still mints a tail, which is+ // the point: the block is the in-flight signal, alongside `RunningStatus`.+ if (streaming?.thinking.trim() && !transcript.some(item => item.kind === 'thinking')) {- parts.push({ type: 'reasoning', text: streaming.thinking });++ parts.push(++ reasoningPart(streaming.thinking, streaming.thinkingStartedAt, streaming.thinkingEndedAt)++ );+ }+ if (streaming?.content.trim() && !transcript.some(item => item.kind === 'narration')) {+ parts.push({ type: 'text', text: streaming.content });}if (approval) parts = withApproval(parts, approval);if (parts.length === 0) return null;diff --cc docs/TEST-COVERAGE-MATRIX.mdindex bf2b629d4b,37e236d2bb..69f89ca9c2--- a/docs/TEST-COVERAGE-MATRIX.md+++ b/docs/TEST-COVERAGE-MATRIX.md@@@ -193,7 -193,6 +193,7 @@@ Canonical mapping of every product feat| 4.2.9 | Share cards ("Look what my agent did" post to X / LinkedIn) | VU | `app/src/features/share/shareContent.test.ts`, `app/src/features/share/shareTargets.test.ts`, `app/src/features/share/shareCaption.test.ts`, `app/src/features/share/shareCard.test.ts`, `app/src/features/share/ShareMessageButton.test.tsx`, `app/src/features/share/ShareCardModal.test.tsx` | ✅ | Hover Share button under completed agent messages opens a Canvas 2D branded card; LLM-drafted headline/caption via `inference_agent_chat_simple` with deterministic offline fallback; X/LinkedIn intent URLs + copy/save PNG; secrets/paths/emails redacted before render. MVP wires only the completed-task trigger; workflow-run + Human-tab triggers are follow-ups. WD E2E deferred || 4.2.10 | Durable agent reply (core stores it before announcing `chat_done`) | RU+VU | `crates/openhuman-core/src/web_chat/reply_persistence_tests.rs`, `crates/openhuman-core/src/web_chat/presentation_tests.rs`, `app/src/providers/__tests__/ChatRuntimeProvider.test.tsx` | ✅ | `deliver_response` persists an unsegmented reply under `agent:<request_id>` before publishing the terminal event, so a dropped socket, a failed `threads_message_append` or a reloaded webview costs a repaint rather than the answer; the client's append collapses onto that row by id. RU covers the write, its idempotency, the empty-reply and missing-thread paths, and that delivery still announces when the store refuses. VU covers the mirrored id, the segmented exception, the refetch that recovers a failed append, and the reconnect that rejoins orphaned thread rooms. WD E2E (kill the append mid-turn) is a follow-up || 4.2.11 | Links open in the default browser; the main webview never loads a remote page | RU+VU+MS | `crates/openhuman-app/src/external_navigation_tests.rs`, `app/src/utils/openUrl.test.ts`, `app/src/utils/externalLinkGuard.test.ts`, `app/src/components/Announcement/AnnouncementModal.test.tsx`, release-manual-smoke | 🟡 | RU covers the shell's navigation policy: remote http(s) navigation of `main` is cancelled and handed to the OS opener; `tauri://localhost`, `tauri.localhost`, `about:`/`data:`/`blob:` and the `tauri dev` server stay in the webview; other webviews are untouched. VU covers `openUrl` never falling back to `window.open` in the desktop shell (including the IPC bridge bootstrap gap) and the click guard. Real macOS click verified manually; automated desktop E2E is a follow-up (the WDIO desktop runner still assumes CEF) |- | 4.2.12 | Live stream renders like the reopened thread (parity, append-only, atomic settle) | VU+WD | `app/src/providers/__tests__/liveHistoryParity.test.tsx`, `app/src/store/__tests__/chatRuntimeSlice.liveParity.test.ts`, `app/src/features/conversations/derived/mapDisplayItems.test.ts`, `app/src/services/chatDeltaCoalescer.test.ts`, `app/src/features/conversations/components/AssistantUiToolCall.disclosure.test.tsx`, `app/src/components/assistant-ui/__tests__/reasoning.scrollLock.test.tsx`, `app/src/components/assistant-ui/thread.followBottom.test.tsx`, `chat-live-history-parity.spec.ts` | ✅ | One scripted turn (`app/src/test/fixtures/streamedTurn.ts`) is told as socket events and as the core transcript. VU drives it through the real socket handlers: the settled reply equals the reload projection, the tail is append-only while it streams, and `chat_done` swaps tail for reply in one store update at one index. Also covered: in-place sub-agent promotion on both sides, args-delta row adoption, a superseded settle, frame-coalesced deltas, disclosure state across remounts, and following that survives a collapse. WD samples the real DOM while streaming, checks the viewport still follows, and compares with the reopened thread |++| 4.2.12 | Live stream renders like the reopened thread (parity, append-only, atomic settle) | VU+WD | `app/src/providers/__tests__/liveHistoryParity.test.tsx`, `app/src/store/__tests__/chatRuntimeSlice.liveParity.test.ts`, `app/src/features/conversations/derived/mapDisplayItems.test.ts`, `app/src/services/chatDeltaCoalescer.test.ts`, `app/src/features/conversations/components/AssistantUiToolCall.disclosure.test.tsx`, `app/src/components/assistant-ui/elements/reasoning-panel.test.tsx`, `app/src/components/assistant-ui/thread.followBottom.test.tsx`, `chat-live-history-parity.spec.ts` | ✅ | One scripted turn (`app/src/test/fixtures/streamedTurn.ts`) is told as socket events and as the core transcript. VU drives it through the real socket handlers: the settled reply equals the reload projection, the tail is append-only while it streams, and `chat_done` swaps tail for reply in one store update at one index. Also covered: in-place sub-agent promotion on both sides, args-delta row adoption, a superseded settle, frame-coalesced deltas, disclosure state across remounts, and following that survives a collapse. WD samples the real DOM while streaming, checks the viewport still follows, and compares with the reopened thread |### 4.3 Tool Invocation