Skip to content

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

feat(conversations): add subagent call awaiting user state

Steven Enamakel88aa8d4df3d5
diff --git a/app/src/features/conversations/components/AgentTimelineRail.tsx b/app/src/features/conversations/components/AgentTimelineRail.tsx
deleted file mode 100644
index 282f2f98e3..0000000000
--- a/app/src/features/conversations/components/AgentTimelineRail.tsx
+++ /dev/null
@@ -1,104 +0,0 @@
-import type { ReactNode } from 'react';
-
-import type { ToolTimelineEntryStatus } from '../../../store/chatRuntimeSlice';
-
-/**
- * Small "spark" glyph used as each agent's node on the timeline rail —
- * mirrors the Figma "Intelligence" icon. Inherits `currentColor` so the
- * caller controls its tone (muted while running, solid when done).
- */
-export function AgentSparkIcon({ className }: { className?: string }) {
- return (
- <svg
- viewBox="0 0 12 12"
- width="12"
- height="12"
- aria-hidden
- className={className}
- focusable="false">
- <path
- d="M6 0.4 L7.25 4.75 L11.6 6 L7.25 7.25 L6 11.6 L4.75 7.25 L0.4 6 L4.75 4.75 Z"
- fill="currentColor"
- />
- </svg>
- );
-}
-
-/**
- * Map a timeline row's lifecycle status to the agent-name text treatment.
- *
- * The Figma "Agentic task insights" design conveys per-agent progress
- * through the *name text* rather than a progress bar: an in-flight agent
- * pulses in a muted tone, a finished agent reads solid/full-strength, and
- * a failed agent is tinted with the coral error token. (Per product
- * direction — no numeric progress signal exists from the core, so we never
- * fabricate one.)
- */
-export function agentNameTone(status: ToolTimelineEntryStatus | undefined): string {
- switch (status) {
- case 'success':
- // Done — full-strength foreground ("full white" in the dark mockup).
- return 'text-content-secondary dark:text-content';
- case 'error':
- return 'text-coral-600 dark:text-coral-300';
- case 'awaiting_user':
- return 'animate-pulse text-amber-600 dark:text-amber-300';
- case 'cancelled':
- // Cancelled — terminal, so muted but NOT pulsing (it isn't in progress).
- return 'text-content-faint';
- default:
- // running / unknown — in progress: muted + blinking.
- return 'animate-pulse text-content-faint';
- }
-}
-
-/**
- * One row on the agent-insights timeline rail: a left column carrying the
- * spark node icon plus the vertical connector that threads consecutive
- * agents together, and an indented content column for the row body.
- *
- * The connector is drawn as two absolutely-positioned segments (above /
- * below the icon) so the line visually breaks at each node and is clipped
- * at the first/last rows — producing the continuous-but-segmented rail in
- * the Figma frames. The icon sits on an opaque chip matching the chat
- * surface so the line reads as passing *behind* it.
- */
-export function AgentTimelineRail({
- isFirst = false,
- isLast = false,
- icon,
- iconClassName,
- children,
-}: {
- isFirst?: boolean;
- isLast?: boolean;
- /** Override the default spark glyph (e.g. the "thoughts" reasoning row). */
- icon?: ReactNode;
- /** Tone applied to the default spark glyph. */
- iconClassName?: string;
- children: ReactNode;
-}) {
- return (
- <div className="relative flex gap-2.5" data-testid="agent-timeline-row">
- {/* Left rail: connector segments + spark node */}
- <div className="relative flex w-3 shrink-0 justify-center">
- {!isFirst ? (
- <span
- aria-hidden
- className="absolute top-0 left-1/2 h-[9px] w-px -translate-x-1/2 bg-surface-strong"
- />
- ) : null}
- {!isLast ? (
- <span
- aria-hidden
- className="absolute top-[9px] bottom-0 left-1/2 w-px -translate-x-1/2 bg-surface-strong"
- />
- ) : null}
- <span className="relative z-10 mt-0.5 flex h-3 w-3 items-center justify-center bg-[#f6f6f6] dark:bg-surface-canvas">
- {icon ?? <AgentSparkIcon className={iconClassName ?? 'text-content-faint'} />}
- </span>
- </div>
- <div className="min-w-0 flex-1 pb-2">{children}</div>
- </div>
- );
-}
diff --git a/app/src/features/conversations/components/AssistantUiSubagentCall.awaitingUser.test.tsx b/app/src/features/conversations/components/AssistantUiSubagentCall.awaitingUser.test.tsx
deleted file mode 100644
index 8ceaa8d1c0..0000000000
--- a/app/src/features/conversations/components/AssistantUiSubagentCall.awaitingUser.test.tsx
+++ /dev/null
@@ -1,279 +0,0 @@
-/**
- * A sub-agent that stops to ask the user a question must look different from
- * one that is working, and the user must be able to answer it.
- *
- * Both halves regressed in the assistant-ui migration. `onSubagentAwaitingUser`
- * reached the surface, but the row rendered through `isActiveSubagentStatus`,
- * which folds `awaiting_user` into `running`: the delegation card showed a
- * spinning "running" chip for as long as the gate stayed open, the question was
- * never carried out of the socket event at all, and the only surface that could
- * have shown it (`SubagentDrawer`) was then mounted only by the legacy
- * transcript, which `/chat` did not render.
- */
-import { combineReducers, configureStore } from '@reduxjs/toolkit';
-import { act, render, screen, waitFor } from '@testing-library/react';
-import userEvent from '@testing-library/user-event';
-import { Provider } from 'react-redux';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-
-import { AssistantUiRuntimeProvider } from '../../../providers/AssistantUiRuntimeProvider';
-import { __resetChatSurfaces, registerChatSurface } from '../../../providers/chatSurfaceHandlers';
-import chatRuntimeReducer, {
- type SubagentActivity,
- subagentAwaitingUser,
- subagentSpawned,
-} from '../../../store/chatRuntimeSlice';
-import threadReducer from '../../../store/threadSlice';
-import { SubagentTaskCard } from '../aui/SubagentTaskCard';
-import { AssistantUiSubagentCall } from './AssistantUiSubagentCall';
-
-vi.mock('../../../services/api/threadApi', () => ({
- threadApi: {
- getDerivedTranscript: vi
- .fn()
- .mockResolvedValue({
- threadId: 't-await',
- items: [],
- total: 0,
- hasMore: false,
- hasTranscript: false,
- }),
- },
-}));
-
-const THREAD_ID = 't-await';
-const ROW_ID = `${THREAD_ID}:subagent:sub-1:researcher`;
-
-const activity: SubagentActivity = {
- taskId: 'sub-1',
- agentId: 'researcher',
- displayName: 'Researcher',
- toolCalls: [],
-};
-
-function buildStore() {
- return configureStore({
- reducer: combineReducers({ thread: threadReducer, chatRuntime: chatRuntimeReducer }),
- preloadedState: {
- thread: {
- threads: [],
- selectedThreadId: THREAD_ID,
- activeThreadIds: {},
- welcomeThreadId: null,
- messagesByThreadId: { [THREAD_ID]: [] },
- messages: [],
- isLoadingThreads: false,
- isLoadingMessages: false,
- messagesError: null,
- },
- } as never,
- });
-}
-
-/** One `subagent_spawned`, identified the way the provider identifies them. */
-function spawn(store: ReturnType<typeof buildStore>, spawnEventId?: string) {
- store.dispatch(
- subagentSpawned({
- threadId: THREAD_ID,
- round: 1,
- rowId: ROW_ID,
- taskId: 'sub-1',
- agentId: 'researcher',
- displayName: 'Researcher',
- spawnEventId,
- })
- );
-}
-
-/** Drive the row through the real reducers, exactly as the socket does. */
-function parkTheDelegation(
- store: ReturnType<typeof buildStore>,
- question: string,
- spawnEventId = 'req-1:3'
-) {
- spawn(store, spawnEventId);
- store.dispatch(subagentAwaitingUser({ threadId: THREAD_ID, rowId: ROW_ID, question }));
-}
-
-function rowOf(store: ReturnType<typeof buildStore>) {
- return store.getState().chatRuntime.toolTimelineByThread[THREAD_ID]?.[0];
-}
-
-afterEach(() => __resetChatSurfaces());
-
-describe('sub-agent awaiting user', () => {
- describe('the data half', () => {
- it('carries the question out of the socket event onto the timeline row', () => {
- const store = buildStore();
- parkTheDelegation(store, 'Which of the two repos should I patch?');
-
- const row = store.getState().chatRuntime.toolTimelineByThread[THREAD_ID]?.[0];
- expect(row?.status).toBe('awaiting_user');
- expect(row?.subagent?.status).toBe('awaiting_user');
- // Before the fix the reducer took only {threadId, rowId} and the
- // question — the entire content of the pause — was dropped on the floor.
- expect(row?.subagent?.awaitingQuestion).toBe('Which of the two repos should I patch?');
- });
-
- it('unparks the row when continue_subagent republishes the spawn', () => {
- const store = buildStore();
- parkTheDelegation(store, 'Which repo?');
-
- // `continue_subagent` resumes a paused child by republishing
- // `subagent_spawned` for the SAME task/agent, so the row id is identical.
- // The idempotency guard used to swallow it wholesale, leaving the card
- // asking a question the user had already answered for the rest of the run.
- // The resume is a new emission, so it carries a new `(request_id, seq)`
- // -- in practice a whole new parent turn, since the user's answer is what
- // triggers it.
- spawn(store, 'req-2:0');
-
- const rows = store.getState().chatRuntime.toolTimelineByThread[THREAD_ID] ?? [];
- expect(rows).toHaveLength(1); // still idempotent: no duplicate row
- expect(rows[0]?.status).toBe('running');
- expect(rows[0]?.subagent?.status).toBe('running');
- expect(rows[0]?.subagent?.awaitingQuestion).toBeUndefined();
- });
-
- it('keeps the pending question when the ORIGINAL spawn is redelivered', () => {
- // This socket reconnects and replays freely -- 13+ times in one measured
- // session. A redelivered `subagent_spawned` arriving after
- // `subagent_awaiting_user` is shape-identical to `continue_subagent`
- // resuming the child, so the unpark used to fire on it and the question
- // vanished while the child was still blocked on the user: a spinner with
- // nothing to answer, which is the exact bug this whole change exists to
- // remove. The redelivery repeats the identity the core stamped, so it is
- // recognisable as a replay.
- const store = buildStore();
- parkTheDelegation(store, 'Which of the two repos should I patch?', 'req-1:3');
-
- spawn(store, 'req-1:3'); // <- the same emission, delivered twice
-
- const rows = store.getState().chatRuntime.toolTimelineByThread[THREAD_ID] ?? [];
- expect(rows).toHaveLength(1);
- expect(rows[0]?.status).toBe('awaiting_user');
- expect(rows[0]?.subagent?.status).toBe('awaiting_user');
- expect(rows[0]?.subagent?.awaitingQuestion).toBe('Which of the two repos should I patch?');
- });
-
- it('keeps the pending question when the spawn cannot be identified at all', () => {
- // An older core stamps no `seq`, so a replay inside one request collapses
- // to the same string as the original. Failing towards "this is a replay"
- // is deliberate: a stale question is visible and still settles on
- // `subagent_done`, while a silently cleared one strands the user.
- const store = buildStore();
- parkTheDelegation(store, 'Which repo?', undefined);
-
- spawn(store, undefined);
-
- expect(rowOf(store)?.status).toBe('awaiting_user');
- expect(rowOf(store)?.subagent?.awaitingQuestion).toBe('Which repo?');
- });
-
- it('leaves a running row alone when its spawn is redelivered', () => {
- // The replay guard must not disturb the ordinary case it also covers.
- const store = buildStore();
- spawn(store, 'req-1:3');
- spawn(store, 'req-1:3');
-
- const rows = store.getState().chatRuntime.toolTimelineByThread[THREAD_ID] ?? [];
- expect(rows).toHaveLength(1);
- expect(rows[0]?.status).toBe('running');
- });
- });
-
- describe('the render half', () => {
- it('renders a parked delegation as awaiting input, not as a running spinner', () => {
- render(
- <AssistantUiSubagentCall
- activity={{
- ...activity,
- status: 'awaiting_user',
- awaitingQuestion: 'Which of the two repos should I patch?',
- }}
- // The assistant-ui surface passes `running` from `result === undefined`,
- // which is true for a parked delegation too. The card must not believe it.
- running
- />
- );
-
- expect(screen.getByTestId('subagent-awaiting-chip')).toBeInTheDocument();
- expect(screen.queryByText('running')).not.toBeInTheDocument();
- expect(screen.getByTestId('subagent-awaiting-question')).toHaveTextContent(
- 'Which of the two repos should I patch?'
- );
- // The question is worthless if the card stays collapsed around it.
- expect(screen.getByTestId('assistant-ui-subagent-call')).toHaveAttribute(
- 'data-state',
- 'open'
- );
- });
-
- it('still renders an ordinary running delegation as running', () => {
- render(<AssistantUiSubagentCall activity={{ ...activity, status: 'running' }} running />);
- expect(screen.getByText('running')).toBeInTheDocument();
- expect(screen.queryByTestId('subagent-awaiting-chip')).not.toBeInTheDocument();
- expect(screen.queryByTestId('subagent-awaiting-user')).not.toBeInTheDocument();
- });
-
- it('offers no reply box on a read-only surface', () => {
- render(
- <AssistantUiSubagentCall
- activity={{ ...activity, status: 'awaiting_user', awaitingQuestion: 'Which repo?' }}
- />
- );
- expect(screen.getByTestId('subagent-awaiting-question')).toBeInTheDocument();
- expect(screen.queryByTestId('subagent-answer-input')).not.toBeInTheDocument();
- });
- });
-
- describe('answering, via SubagentTaskCard (the toolkit-registered `task` renderer)', () => {
- it('sends the answer through the thread the composer sends through', async () => {
- const send = vi.fn(async () => {});
- registerChatSurface(THREAD_ID, { send });
- const store = buildStore();
-
- render(
- <Provider store={store}>
- <AssistantUiRuntimeProvider>
- <SubagentTaskCard
- type="tool-call"
- toolName="task"
- toolCallId={ROW_ID}
- args={
- {
- subagent_type: 'researcher',
- progress: {
- ...activity,
- status: 'awaiting_user',
- awaitingQuestion: 'Which repo?',
- },
- } as never
- }
- argsText="{}"
- result={undefined}
- status={{ type: 'running' }}
- addResult={() => {}}
- resume={() => {}}
- respondToApproval={async () => {}}
- />
- </AssistantUiRuntimeProvider>
- </Provider>
- );
-
- await act(async () => {
- await userEvent.type(screen.getByTestId('subagent-answer-input'), 'the second one');
- });
- await act(async () => {
- await userEvent.click(screen.getByTestId('subagent-answer-send'));
- });
-
- // The orchestrator is holding the [SUBAGENT_AWAITING_USER] envelope and
- // resumes the child with continue_subagent once the user answers, so the
- // answer is an ordinary user turn (`aui.thread.append`) on the
- // registered chat surface.
- await waitFor(() => expect(send).toHaveBeenCalledWith('the second one'));
- expect(screen.getByTestId('subagent-answer-sent')).toBeInTheDocument();
- });
- });
-});
diff --git a/app/src/features/conversations/components/AssistantUiSubagentCall.tsx b/app/src/features/conversations/components/AssistantUiSubagentCall.tsx
deleted file mode 100644
index 930ac0c546..0000000000
--- a/app/src/features/conversations/components/AssistantUiSubagentCall.tsx
+++ /dev/null
@@ -1,389 +0,0 @@
-import {
- CheckIcon,
- ChevronDownIcon,
- CircleXIcon,
- Loader2Icon,
- MessageCircleQuestionIcon,
-} from 'lucide-react';
-import { useState } from 'react';
-
-import { cn } from '../../../components/assistant-ui/lib/utils';
-import {
- Collapsible,
- CollapsibleContent,
- CollapsibleTrigger,
-} from '../../../components/assistant-ui/ui/collapsible';
-import { Button } from '../../../components/ui';
-import Badge from '../../../components/ui/Badge';
-import WorktreeActions from '../../../components/worktree/WorktreeActions';
-import { useT } from '../../../lib/i18n/I18nContext';
-import {
- isActiveTimelineStatus,
- type SubagentActivity,
- type SubagentToolCallEntry,
- type SubagentTranscriptItem,
-} from '../../../store/chatRuntimeSlice';
-import { basename } from '../../../utils/pathUtils';
-import { stripToolCallEnvelopes } from '../../../utils/toolTimelineFormatting';
-import { ToolIcon } from '../tools/ToolIcon';
-import { describeToolCall } from '../tools/toolPresentation';
-import { BubbleMarkdown } from './AgentMessageBubble';
-import { AssistantUiToolCallCard } from './AssistantUiToolCall';
-
-type ChildToolCall = SubagentToolCallEntry | Extract<SubagentTranscriptItem, { kind: 'tool' }>;
-
-function ChildToolCallCard({ call }: { call: ChildToolCall }) {
- return (
- <AssistantUiToolCallCard
- toolName={call.toolName}
- args={call.args}
- result={call.result}
- status={call.status}
- displayName={call.displayName}
- detail={call.detail}
- elapsedMs={call.elapsedMs}
- failure={call.failure}
- />
- );
-}
-
-function Thought({ text }: { text: string }) {
- const clean = stripToolCallEnvelopes(text).trim();
- if (!clean) return null;
- return (
- <div
- data-testid="subagent-thought"
- className="my-0.5 wrap-break-word [&_.prose]:text-[12px] [&_.prose]:leading-relaxed [&_.prose]:text-content-muted [&_.prose_strong]:text-content-muted [&_.prose_:is(h1,h2,h3,h4,h5,h6)]:text-[12px] [&_.prose_:is(h1,h2,h3,h4,h5,h6)]:text-content-muted">
- <BubbleMarkdown content={clean} />
- </div>
- );
-}
-
-function SubagentDetails({
- subagent,
- onView,
-}: {
- subagent: SubagentActivity;
- onView?: () => void;
-}) {
- const { t } = useT();
- const headerBits: string[] = [];
- if (subagent.mode) headerBits.push(subagent.mode);
- if (subagent.dedicatedThread) headerBits.push(t('conversations.toolTimeline.workerThread'));
- if (subagent.childIteration != null) {
- headerBits.push(
- subagent.childMaxIterations != null
- ? `${t('conversations.toolTimeline.turn')} ${subagent.childIteration}/${subagent.childMaxIterations}`
- : `${t('conversations.toolTimeline.step')} ${subagent.childIteration}`
- );
- } else if (subagent.iterations != null) {
- headerBits.push(
- subagent.iterations === 1
- ? `${subagent.iterations} ${t('chat.turn')}`
- : `${subagent.iterations} ${t('chat.turns')}`
- );
- }
- if (subagent.elapsedMs != null) {
- headerBits.push(
- subagent.elapsedMs >= 1000
- ? `${(subagent.elapsedMs / 1000).toFixed(1)}s`
- : `${subagent.elapsedMs}ms`
- );
- }
- const transcript = subagent.transcript ?? [];
-
- return (
- <div
- className="mt-1 space-y-0.5 text-[12px] text-content-muted"
- data-testid="subagent-activity">
- {headerBits.length > 0 ? (
- <div className="flex flex-wrap items-center gap-1.5">
- {headerBits.map(bit => (
- <Badge key={bit} className="rounded-full">
- {bit}
- </Badge>
- ))}
- </div>
- ) : null}
- {transcript.length > 0 ? (
- <div className="ml-1 space-y-0.5" data-testid="subagent-transcript">
- {transcript.map((item, index) =>
- item.kind === 'tool' ? (
- <ChildToolCallCard key={item.callId} call={item} />
- ) : (
- <Thought key={`thought-${index}`} text={item.text} />
- )
- )}
- </div>
- ) : subagent.toolCalls.length > 0 ? (
- <div className="ml-1 space-y-0.5">
- {subagent.toolCalls.map(call => (
- <ChildToolCallCard key={call.callId} call={call} />
- ))}
- </div>
- ) : null}
- {subagent.worktreePath ? (
- <div
- className="mt-1 space-y-1 rounded-md border border-line bg-surface-muted/70 p-1.5"
- data-testid="subagent-worktree">
- <div className="flex flex-wrap items-center gap-1.5">
- <span className="font-medium text-content-secondary">{t('worktree.label')}</span>
- <span
- className="truncate font-mono text-[12px] text-content-muted"
- title={subagent.worktreePath}>
- {basename(subagent.worktreePath)}
- </span>
- <Badge variant={subagent.isDirty ? 'warning' : 'success'} className="rounded-full">
- {subagent.isDirty ? t('worktree.dirty') : t('worktree.clean')}
- </Badge>
- {subagent.changedFiles?.length ? (
- <span className="text-[11px] text-content-faint">
- {subagent.changedFiles.length}{' '}
- {subagent.changedFiles.length === 1
- ? t('worktree.changedFile')
- : t('worktree.changedFiles')}
- </span>
- ) : null}
- </div>
- <WorktreeActions path={subagent.worktreePath} isDirty={subagent.isDirty} compact />
- </div>
- ) : null}
- {onView ? (
- <button
- type="button"
- onClick={onView}
- data-testid="subagent-view-processing"
- className="mt-0.5 rounded-full px-1.5 py-0.5 text-[12px] font-medium text-primary-600 hover:bg-primary-50 dark:text-primary-300 dark:hover:bg-primary-500/15">
- {t('conversations.subagent.viewProcessing')} →
- </button>
- ) : null}
- </div>
- );
-}
-
-/**
- * Statuses that mean the delegation is still in flight.
- *
- * `SubagentActivity.status` carries `running` | `awaiting_user` | `completed` |
- * `failed`, and collapsing that to a boolean is what produced two opposite
- * rendering bugs: a caller that omitted `running` showed a *failed* delegation
- * with a success check, while `status !== 'completed'` gave the same row an
- * endless spinner. Both call sites now ask this one question.
- *
- * The question itself is `isActiveTimelineStatus`, which the timeline row's
- * top-level `status` is also read through. This name survives because ~4 call
- * sites and their tests use it and it reads better beside a `SubagentActivity`
- * — but it must never grow a second opinion about what "active" means.
- */
-export function isActiveSubagentStatus(status: string | undefined): boolean {
- return isActiveTimelineStatus(status);
-}
-
-/** Statuses that mean the delegation stopped without succeeding. */
-function isFailedSubagentStatus(status: string | undefined): boolean {
- return status === 'failed' || status === 'cancelled';
-}
-
-/**
- * The delegation is parked on `ask_user_clarification` and cannot progress
- * until the user answers.
- *
- * Deliberately NOT a sub-case of {@link isActiveSubagentStatus}: both are true
- * at once and they answer different questions. "Active" decides whether the row
- * is still in flight (dashed border, no success check); "awaiting" decides
- * whether the blockage is *the user*. Folding the second into the first is what
- * rendered a child asking a question as an ordinary spinner labelled "running"
- * for as long as the gate stayed open.
- */
-export function isAwaitingUserSubagentStatus(status: string | undefined): boolean {
- return status === 'awaiting_user';
-}
-
-/**
- * The child's question plus, when the host supplies `onAnswer`, a reply box.
- *
- * The answer is an ordinary user turn: the orchestrator is holding a
- * `[SUBAGENT_AWAITING_USER]` envelope that instructs it to relay the question
- * and resume with `continue_subagent` once the user responds
- * (`orchestration/tools/awaiting_user.rs`). So sending here goes through the
- * same composer path as typing the answer by hand, which is what makes the
- * queued-vs-new-turn decision in one place.
- *
- * `onAnswer` is optional because this card also renders on read-only,
- * historical surfaces (the process drawer, past-turn insights). Those pass no
- * handler and get the question without a dead reply box.
- */
-function SubagentAwaitingUser({
- question,
- onAnswer,
-}: {
- question?: string;
- onAnswer?: (text: string) => void;
-}) {
- const { t } = useT();
- const [draft, setDraft] = useState('');
- // Local, optimistic: the core has no "answer received" event for this row.
- // It resumes by republishing `subagent_spawned`, which flips the status back
- // to running and unmounts this panel; until then the user needs to see that
- // their answer went somewhere.
- const [sent, setSent] = useState(false);
-
- const submit = () => {
- const text = draft.trim();
- if (!text || !onAnswer) return;
- onAnswer(text);
- setDraft('');
- setSent(true);
- };
-
- return (
- <div
- data-testid="subagent-awaiting-user"
- className="mt-1 space-y-1.5 rounded-lg border border-amber-300/70 bg-amber-50/70 p-2 dark:border-amber-400/30 dark:bg-amber-500/10">
- <p className="text-[12px] font-medium text-amber-800 dark:text-amber-200">
- {t('conversations.subagent.awaitingTitle')}
- </p>
- {question ? (
- // Plain text, not markdown: this is sub-agent-authored free text and
- // the card gains nothing from rendering links or images out of it.
- <p
- data-testid="subagent-awaiting-question"
- className="wrap-break-word whitespace-pre-wrap text-[12px] text-content-secondary">
- {question}
- </p>
- ) : null}
- {onAnswer ? (
- sent ? (
- <p className="text-[11px] text-content-muted" data-testid="subagent-answer-sent">
- {t('conversations.subagent.answerSent')}
- </p>
- ) : (
- <div className="flex items-end gap-1.5">
- <textarea
- rows={1}
- value={draft}
- data-testid="subagent-answer-input"
- aria-label={t('conversations.subagent.answerPlaceholder')}
- placeholder={t('conversations.subagent.answerPlaceholder')}
- onChange={event => setDraft(event.target.value)}
- onKeyDown={event => {
- // Enter sends, Shift+Enter is a newline. Matches the composer.
- if (event.key === 'Enter' && !event.shiftKey) {
- event.preventDefault();
- submit();
- }
- }}
- className="min-h-[28px] flex-1 resize-y rounded-md border border-line bg-surface px-2 py-1 text-[12px] text-content outline-none focus:border-primary-500"
- />
- <Button
- type="button"
- size="xs"
- variant="primary"
- analyticsId="subagent-answer-send"
- data-testid="subagent-answer-send"
- disabled={draft.trim().length === 0}
- onClick={submit}>
- {t('conversations.subagent.answerSend')}
- </Button>
- </div>
- )
- ) : null}
- </div>
- );
-}
-
-export function AssistantUiSubagentCall({
- activity,
- running,
- description,
- onView,
- onAnswer,
- defaultOpen = false,
-}: {
- activity: SubagentActivity;
- running?: boolean;
- description?: string;
- onView?: () => void;
- /**
- * Send the user's reply to a delegation parked on `ask_user_clarification`.
- * Supplied only by the live chat surface; omit on read-only/historical
- * renders so no dead reply box appears.
- */
- onAnswer?: (text: string) => void;
- defaultOpen?: boolean;
-}) {
- const { t } = useT();
- const name = activity.displayName ?? activity.agentId ?? 'subagent';
- // Default to the activity's own lifecycle rather than `false`: most call
- // sites pass no `running` prop at all, and treating every non-running
- // activity as finished-successfully is what rendered a failed delegation
- // with a success check.
- const active = running ?? isActiveSubagentStatus(activity.status);
- // Read from the activity, never from `running`: the assistant-ui surface
- // passes `running={result === undefined}`, which is `true` for a parked
- // delegation too, so a caller-supplied `running` cannot distinguish the two.
- const awaiting = isAwaitingUserSubagentStatus(activity.status);
- const failed = !active && isFailedSubagentStatus(activity.status);
- const [open, setOpen] = useState(defaultOpen);
- // A question the user cannot see is a question they cannot answer, and the
- // row is normally already mounted (and collapsed) as `running` by the time
- // the pause arrives, so `defaultOpen` is too late. Derived rather than an
- // effect that forces the state: the disclosure is pinned open only for as
- // long as the delegation is actually blocked on the user, and the user's own
- // open/closed choice is remembered underneath and restored on resume.
- const disclosureOpen = open || awaiting;
- const presentation = describeToolCall({ name: `subagent:${activity.agentId ?? 'subagent'}` });
- const [before, after] = t('conversations.tools.delegatedTo').split('{agent}');
- return (
- <Collapsible
- open={disclosureOpen}
- onOpenChange={setOpen}
- data-slot="aui_subagent-call"
- data-testid="assistant-ui-subagent-call"
- data-status={activity.status ?? (active ? 'running' : 'completed')}
- className={cn(
- 'aui-subagent-call border-border/60 dark:border-muted-foreground/15 rounded-xl border',
- active && 'border-dashed',
- awaiting && 'border-solid border-amber-300 dark:border-amber-400/40'
- )}>
- <CollapsibleTrigger className="group/subagent text-muted-foreground hover:text-foreground flex w-full items-center gap-2 px-3 py-2 text-sm transition-colors">
- <ToolIcon presentation={presentation} className="size-4" />
- <span className="text-start leading-none">
- {before}
- <b className="text-foreground">{name}</b>
- {after}
- </span>
- {awaiting ? (
- // Not a spinner: the child is not working, it is blocked on the user.
- <span
- data-testid="subagent-awaiting-chip"
- className="flex shrink-0 items-center gap-1.5 rounded-full bg-amber-100 px-2 py-0.5 text-[11px] leading-none text-amber-800 dark:bg-amber-500/20 dark:text-amber-200">
- <MessageCircleQuestionIcon className="size-3" />
- {t('conversations.subagent.statusAwaitingUser')}
- </span>
- ) : active ? (
- <span className="bg-muted text-muted-foreground flex shrink-0 items-center gap-1.5 rounded-full px-2 py-0.5 text-[11px] leading-none">
- <Loader2Icon className="size-3 animate-spin [animation-duration:0.6s]" />{' '}
- {t('conversations.tools.status.running')}
- </span>
- ) : (
- <span className="text-muted-foreground flex shrink-0 items-center gap-1.5 text-[11px] leading-none">
- {failed ? <CircleXIcon className="size-3.5" /> : <CheckIcon className="size-3.5" />}
- {failed ? <span>{activity.status}</span> : null}
- {activity.elapsedMs != null ? (
- <span className="tabular-nums">{(activity.elapsedMs / 1000).toFixed(1)}s</span>
- ) : null}
- </span>
- )}
- <ChevronDownIcon className="ml-auto size-4 shrink-0 -rotate-90 transition-transform group-data-[state=open]/subagent:rotate-0" />
- </CollapsibleTrigger>
- <CollapsibleContent className="px-3 pb-3">
- {description ? <p className="text-muted-foreground text-xs">{description}</p> : null}
- {awaiting ? (
- <SubagentAwaitingUser question={activity.awaitingQuestion} onAnswer={onAnswer} />
- ) : null}
- <SubagentDetails subagent={activity} onView={onView} />
- </CollapsibleContent>
- </Collapsible>
- );
-}
diff --git a/app/src/features/conversations/components/ProcessingTranscriptView.test.tsx b/app/src/features/conversations/components/ProcessingTranscriptView.test.tsx
deleted file mode 100644
index f2d8a23122..0000000000
--- a/app/src/features/conversations/components/ProcessingTranscriptView.test.tsx
+++ /dev/null
@@ -1,161 +0,0 @@
-import { render, screen, waitFor } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import type { ToolTimelineEntry } from '../../../store/chatRuntimeSlice';
-import { ProcessingTranscriptView } from './ProcessingTranscriptView';
-
-// Echo i18n: return the fallback when one is provided (so localized copy keys
-// resolve to the English source we pass), otherwise the key itself. This lets
-// us assert on the human strings carried on the failure payload.
-vi.mock('../../../lib/i18n/I18nContext', () => ({
- useT: () => ({ t: (key: string, fallback?: string) => fallback ?? key, locale: 'en' }),
-}));
-
-function failedEntry(overrides: Partial<ToolTimelineEntry> = {}): ToolTimelineEntry {
- return {
- id: 'call-1',
- name: 'read_file',
- round: 1,
- seq: 0,
- status: 'error',
- failure: {
- class: 'MissingPermission',
- category: 'NeedsUserConfirmation',
- recoverable: false,
- causePlain: 'No permission yet.',
- nextAction: 'Grant it, then retry.',
- },
- ...overrides,
- };
-}
-
-describe('ProcessingTranscriptView tool failure explanation', () => {
- it('renders the cause + next-action under a failed tool row', () => {
- // Empty transcript → single tool group over all entries (legacy path).
- render(<ProcessingTranscriptView transcript={[]} entries={[failedEntry()]} />);
-
- const failure = screen.getByTestId('processing-tool-failure');
- expect(failure).toBeTruthy();
- expect(failure.textContent).toContain('No permission yet.');
- expect(failure.textContent).toContain('Grant it, then retry.');
- });
-
- it('falls back to the plain English copy for an unrecognized class', () => {
- render(
- <ProcessingTranscriptView
- transcript={[]}
- entries={[
- failedEntry({
- failure: {
- class: 'SomethingBrandNew',
- category: 'Recoverable',
- recoverable: true,
- causePlain: 'Mystery cause.',
- nextAction: 'Mystery next.',
- },
- }),
- ]}
- />
- );
-
- const failure = screen.getByTestId('processing-tool-failure');
- expect(failure.textContent).toContain('Mystery cause.');
- expect(failure.textContent).toContain('Mystery next.');
- });
-
- it('does not render the failure block for a successful entry', () => {
- render(
- <ProcessingTranscriptView
- transcript={[]}
- entries={[failedEntry({ status: 'success', failure: undefined })]}
- />
- );
- expect(screen.queryByTestId('processing-tool-failure')).toBeNull();
- });
-});
-
-describe('ProcessingTranscriptView live thinking', () => {
- const thought = (seq: number, text: string) =>
- ({ kind: 'thinking', round: 1, seq, text }) as const;
-
- it('renders the trailing thought expanded while the turn is live', () => {
- render(
- <ProcessingTranscriptView
- transcript={[thought(0, 'The user wants a week in Kashmir in October.')]}
- entries={[]}
- live
- />
- );
- const live = screen.getByTestId('processing-thinking-live');
- // Rendered as a step of the live reasoning panel (its title drops the
- // sentence's closing period).
- expect(live.textContent).toContain('The user wants a week in Kashmir in October');
- expect(live.getAttribute('aria-busy')).toBe('true');
- expect(live.querySelector('.shimmer')).not.toBeNull();
- // No settled row for the same thought.
- expect(screen.queryByTestId('processing-thinking')).toBeNull();
- });
-
- it('renders settled thoughts as a quiet, non-collapsible reasoning panel', () => {
- render(
- <ProcessingTranscriptView
- transcript={[thought(0, 'Settled reasoning that should stay quiet.')]}
- entries={[]}
- />
- );
- expect(screen.queryByTestId('processing-thinking-live')).toBeNull();
- const settled = screen.getByTestId('processing-thinking');
- // The rail keeps the trail visible: no disclosure, no live shimmer.
- expect(settled.getAttribute('data-variant')).toBe('static');
- expect(settled.querySelector('button')).toBeNull();
- expect(settled.querySelector('.shimmer')).toBeNull();
- expect(settled.textContent).toContain('Settled reasoning that should stay quiet');
- });
-
- it('labels a settled thought with its recorded duration', () => {
- render(
- <ProcessingTranscriptView
- transcript={[{ ...thought(0, '**Planning**\nok'), startedAt: 1_000, endedAt: 13_000 }]}
- entries={[]}
- />
- );
- const settled = screen.getByTestId('processing-thinking');
- // `useT` is mocked to echo keys: the timed "Thought for {n}" key is
- // chosen, not the untimed "Thought" fallback.
- expect(settled.querySelector('[data-slot="reasoning-panel-resting-label"]')?.textContent).toBe(
- 'chat.reasoning.thoughtFor'
- );
- expect(settled.querySelector('[data-slot="reasoning-step-title"]')?.textContent).toBe(
- 'Planning'
- );
- });
-
- it('only expands the LAST thought while live; earlier ones stay collapsed', () => {
- render(
- <ProcessingTranscriptView
- transcript={[
- thought(0, 'First pass of reasoning.'),
- { kind: 'narration', round: 1, seq: 1, text: 'Let me look that up.' },
- thought(2, 'Second pass of reasoning.'),
- ]}
- entries={[]}
- live
- />
- );
- expect(screen.getAllByTestId('processing-thinking')).toHaveLength(1);
- expect(screen.getByTestId('processing-thinking').textContent).toContain('First pass');
- expect(screen.getByTestId('processing-thinking-live').textContent).toContain('Second pass');
- });
-
- it('keeps a long live thought whole inside a bounded, bottom-pinned scroll region', async () => {
- const long = 'x'.repeat(2000) + ' TAIL';
- render(<ProcessingTranscriptView transcript={[thought(0, long)]} entries={[]} live />);
- const live = screen.getByTestId('processing-thinking-live');
- // The live step body streams in through assistant-ui's smoothed
- // MarkdownText, so the tail appears once the reveal catches up.
- await waitFor(() => expect(live.textContent).toContain('TAIL'));
- const scroll = live.querySelector('[data-slot="reasoning-panel-scroll"]');
- expect(scroll?.className).toContain('max-h-80');
- expect(scroll?.className).toContain('overflow-y-auto');
- });
-});
diff --git a/app/src/features/conversations/components/ProcessingTranscriptView.tsx b/app/src/features/conversations/components/ProcessingTranscriptView.tsx
deleted file mode 100644
index a3c885cfcc..0000000000
--- a/app/src/features/conversations/components/ProcessingTranscriptView.tsx
+++ /dev/null
@@ -1,229 +0,0 @@
-import { ReasoningTraceText } from '@/components/assistant-ui/elements/reasoning-trace';
-import type { ReasoningTiming } from '@/components/assistant-ui/elements/reasoningSteps';
-
-import { useT } from '../../../lib/i18n/I18nContext';
-import type {
- ProcessingTranscriptItem,
- ToolTimelineEntry,
- ToolTimelineEntryStatus,
-} from '../../../store/chatRuntimeSlice';
-import {
- buildProcessingBlocks,
- formatTimelineEntry,
- presentTimelineEntry,
- stripToolCallEnvelopes,
-} from '../../../utils/toolTimelineFormatting';
-import { ToolIcon } from '../tools/ToolIcon';
-import { ToolFailureLines } from './ToolFailureLines';
-
-/**
- * The Hermes-style "View processing" body: the agent's narration and hidden
- * reasoning flow inline as prose, while runs of consecutive tool calls
- * collapse into a single group under a human summary ("Read 2 files"), each
- * step a sentence + a type icon, ending in a single "Done" check. Shared by
- * the process-source panel and (eventually) the inline rail so main-agent and
- * sub-agent activity render through one path.
- *
- * Falls back to a single tool group when no ordered transcript is present
- * (legacy snapshot), so older turns still show their steps.
- */
-export function ProcessingTranscriptView({
- transcript,
- entries,
- renderSubagent,
- live = false,
-}: {
- transcript: ProcessingTranscriptItem[];
- entries: ToolTimelineEntry[];
- /**
- * True while the turn that produced `transcript` is still in flight. The
- * trailing thinking block then renders EXPANDED through
- * {@link LiveThinkingBlock} — a reasoning-tier model can spend the whole
- * time-to-first-token window streaming `thinking_delta`s and nothing else,
- * and a collapsed 💭 row hides the only evidence the agent is working. Once
- * the turn settles (or a later block lands) it becomes the quiet collapsed
- * block every other thought uses.
- */
- live?: boolean;
- /**
- * Renders a delegated sub-agent's nested activity (its own child tool calls,
- * transcript and thoughts) under the row that spawned it.
- *
- * Injected rather than imported because the assistant-ui delegation card lives in
- * `ToolTimelineBlock`, which imports THIS component for the inline rail —
- * importing it back would be a cycle. Without this, a `subagent:*` row
- * rendered as a bare one-line step and every child tool call it made was
- * invisible, even though the entry carries them. Omit it and rows degrade to
- * that one-line form rather than breaking.
- */
- renderSubagent?: (subagent: NonNullable<ToolTimelineEntry['subagent']>) => React.ReactNode;
-}) {
- const { t } = useT();
- const blocks = buildProcessingBlocks(transcript, entries, t);
- if (blocks.length === 0) return null;
-
- return (
- <div className="space-y-2.5" data-testid="processing-transcript">
- {blocks.map((block, index) => {
- if (block.kind === 'narration') {
- return (
- <p
- key={block.key}
- data-testid="processing-narration"
- className="text-[13px] leading-relaxed wrap-break-word whitespace-pre-wrap text-content-secondary">
- {block.text}
- </p>
- );
- }
- if (block.kind === 'thinking') {
- const timing =
- block.startedAt !== undefined || block.endedAt !== undefined
- ? { startedAt: block.startedAt, endedAt: block.endedAt }
- : undefined;
- return live && index === blocks.length - 1 ? (
- <LiveThinkingBlock key={block.key} text={block.text} timing={timing} />
- ) : (
- <ThinkingBlock key={block.key} text={block.text} timing={timing} />
- );
- }
- return (
- <ToolGroupBlock
- key={block.key}
- summary={block.summary}
- entries={block.entries}
- renderSubagent={renderSubagent}
- />
- );
- })}
- </div>
- );
-}
-
-/**
- * The agent's reasoning, rendered through the shared static reasoning panel
- * in its non-collapsible form: the rail is the place the trail stays visible,
- * so a settled thought shows its "Thought for Ns" header and titled steps
- * inline rather than behind a disclosure.
- */
-function ThinkingBlock({ text, timing }: { text: string; timing?: ReasoningTiming }) {
- const clean = stripToolCallEnvelopes(text).trim();
- if (!clean) return null;
- return (
- <ReasoningTraceText
- text={clean}
- timing={timing}
- streaming={false}
- collapsible={false}
- data-testid="processing-thinking"
- />
- );
-}
-
-/** The agent's reasoning while it is still streaming: the same static panel,
- * live — the newest heading shimmers beside a ticking elapsed badge, and a
- * long trace scrolls inside a bounded region pinned to its newest tokens,
- * so the user sees the turn progressing during the window before any
- * narration or tool call exists to show. */
-function LiveThinkingBlock({ text, timing }: { text: string; timing?: ReasoningTiming }) {
- const clean = stripToolCallEnvelopes(text).trim();
- if (!clean) return null;
- return (
- <div aria-live="polite">
- <ReasoningTraceText
- text={clean}
- timing={timing}
- streaming
- collapsible={false}
- data-testid="processing-thinking-live"
- />
- </div>
- );
-}
-
-/** A collapsible group of consecutive tool rows under a human summary. */
-function ToolGroupBlock({
- summary,
- entries,
- renderSubagent,
-}: {
- summary: string;
- entries: ToolTimelineEntry[];
- renderSubagent?: (subagent: NonNullable<ToolTimelineEntry['subagent']>) => React.ReactNode;
-}) {
- const { t } = useT();
- const allSettled = entries.every(e => e.status !== 'running');
- const anyError = entries.some(e => e.status === 'error');
- return (
- <details open className="group/group" data-testid="processing-tool-group">
- <summary className="flex cursor-pointer list-none items-center gap-1.5 select-none marker:hidden">
- <span className="text-[12px] font-medium text-content-secondary">{summary}</span>
- <span className="text-[9px] text-content-faint transition-transform group-open/group:rotate-90">
- ▶
- </span>
- </summary>
- <ul className="mt-1 ml-1 space-y-1 border-l border-line pl-3">
- {entries.map(entry => (
- <ToolRow key={entry.id} entry={entry} renderSubagent={renderSubagent} />
- ))}
- {allSettled ? (
- <li className="flex items-center gap-1.5 pt-0.5">
- <StatusGlyph status={anyError ? 'error' : 'success'} />
- <span className="text-[11px] text-content-faint">
- {t('conversations.agentTaskInsights.done')}
- </span>
- </li>
- ) : null}
- </ul>
- </details>
- );
-}
-
-/** One tool step: type icon + human sentence + contextual detail chip. */
-function ToolRow({
- entry,
- renderSubagent,
-}: {
- entry: ToolTimelineEntry;
- renderSubagent?: (subagent: NonNullable<ToolTimelineEntry['subagent']>) => React.ReactNode;
-}) {
- const { t } = useT();
- const { title, detail } = formatTimelineEntry(entry, t);
- return (
- <li className="flex flex-col gap-1" data-testid="processing-tool-row">
- <div className="flex items-start gap-1.5">
- <span className="mt-0.5 shrink-0 text-content-faint">
- <ToolIcon presentation={presentTimelineEntry(entry)} className="size-3" />
- </span>
- <span className="min-w-0 text-[12px] text-content-secondary">
- {title}
- {detail ? (
- <span className="ml-1 rounded bg-surface-subtle px-1 py-px font-mono text-[10px] text-content-muted">
- {detail}
- </span>
- ) : null}
- {entry.status === 'error' && entry.failure ? (
- <ToolFailureLines failure={entry.failure} />
- ) : null}
- </span>
- </div>
- {/* A delegated sub-agent's own tool calls hang off the parent entry, so
- without this the whole child run collapsed into this single line.
- Rendered as a `<div>` SIBLING under the `<li>` (indented past the
- icon), not nested inside the label `<span>` — the delegation card
- renders a `<div>`, and `<div>`-inside-`<span>` is invalid nesting. */}
- {entry.subagent && renderSubagent ? (
- <div className="ml-5" data-testid="processing-subagent">
- {renderSubagent(entry.subagent)}
- </div>
- ) : null}
- </li>
- );
-}
-
-/** Compact terminal status glyph for the group's "Done" line. */
-function StatusGlyph({ status }: { status: ToolTimelineEntryStatus }) {
- if (status === 'error') {
- return <span className="text-[11px] text-coral-600 dark:text-coral-300">✕</span>;
- }
- return <span className="text-[11px] text-sage-600 dark:text-sage-300">✓</span>;
-}
diff --git a/app/src/features/conversations/components/SubagentDrawer.tsx b/app/src/features/conversations/components/SubagentDrawer.tsx
deleted file mode 100644
index 6275d7067b..0000000000
--- a/app/src/features/conversations/components/SubagentDrawer.tsx
+++ /dev/null
@@ -1,408 +0,0 @@
-import { ReasoningTraceText } from '@/components/assistant-ui/elements/reasoning-trace';
-import createDebug from 'debug';
-import { type ReactNode, useEffect, useState } from 'react';
-
-import Badge, { type BadgeVariant } from '../../../components/ui/Badge';
-import Button from '../../../components/ui/Button';
-import { SheetContent, SheetRoot, SheetTitle } from '../../../components/ui/Sheet';
-import { useT } from '../../../lib/i18n/I18nContext';
-import { threadApi } from '../../../services/api/threadApi';
-import type {
- SubagentActivity,
- SubagentTranscriptItem,
- ToolTimelineEntryStatus,
-} from '../../../store/chatRuntimeSlice';
-import type { ThreadMessage } from '../../../types/thread';
-import { stripToolCallEnvelopes } from '../../../utils/toolTimelineFormatting';
-import { BubbleMarkdown } from './AgentMessageBubble';
-import { AssistantUiToolCallCard } from './AssistantUiToolCall';
-
-const log = createDebug('app:conversations:subagent-drawer');
-
-function formatElapsed(ms: number): string {
- return ms >= 1000 ? `${(ms / 1000).toFixed(1)}s` : `${ms}ms`;
-}
-
-function subagentStatusVariant(status: ToolTimelineEntryStatus | undefined): BadgeVariant {
- if (status === 'success') return 'success';
- if (status === 'error') return 'danger';
- if (status === 'cancelled') return 'neutral';
- return 'warning';
-}
-
-function useSubagentStatusLabel(status: ToolTimelineEntryStatus | undefined): string {
- const { t } = useT();
- if (status === 'success') return t('conversations.subagent.statusCompleted');
- if (status === 'error') return t('conversations.subagent.statusFailed');
- if (status === 'cancelled') return t('conversations.subagent.statusCancelled');
- if (status === 'awaiting_user') return t('conversations.subagent.statusAwaitingUser');
- return t('conversations.subagent.statusRunning');
-}
-
-/**
- * Rebuild a renderable transcript from a worker sub-thread's persisted
- * messages so a delegation can be reopened from memory after its live
- * stream is gone (navigation / cold boot). The first `user` message is the
- * parent's delegation prompt; `agent` messages with a `tool_name` in their
- * metadata are tool calls, the rest are the sub-agent's visible text.
- * Streamed reasoning isn't persisted, so reopened transcripts omit it.
- */
-function transcriptFromMessages(messages: ThreadMessage[]): {
- prompt?: string;
- items: SubagentTranscriptItem[];
-} {
- let prompt: string | undefined;
- const items: SubagentTranscriptItem[] = [];
- for (const m of messages) {
- const meta = m.extraMetadata ?? {};
- const iteration = typeof meta.iteration === 'number' ? meta.iteration : undefined;
- if (m.sender === 'user') {
- if (prompt === undefined) prompt = m.content;
- continue;
- }
- const toolName = typeof meta.tool_name === 'string' ? meta.tool_name : undefined;
- if (toolName) {
- items.push({ kind: 'tool', iteration, callId: m.id, toolName, status: 'success' });
- } else if (m.content.trim().length > 0) {
- items.push({ kind: 'text', iteration, text: m.content });
- }
- }
- return { prompt, items };
-}
-
-/**
- * The status dot beside the sub-agent's name. Only the *dot* is hand-drawn —
- * the textual status is a shared {@link Badge}, so the tone vocabulary lives
- * in `subagentStatusVariant` and this maps the same statuses to the matching
- * fill.
- */
-function statusDot(status: ToolTimelineEntryStatus | undefined): string {
- switch (status) {
- case 'success':
- return 'bg-sage-500';
- case 'error':
- return 'bg-coral-500';
- case 'cancelled':
- return 'bg-content-faint';
- case 'awaiting_user':
- return 'bg-amber-400 animate-pulse';
- default:
- return 'bg-amber-500 animate-pulse';
- }
-}
-
-/**
- * Full live-transcript view for one sub-agent, slid in from the right.
- *
- * Driven entirely off the live [`SubagentActivity`] the caller passes —
- * because the caller re-derives that object from Redux on every render,
- * the drawer updates token-by-token as `subagent_text_delta` /
- * `subagent_thinking_delta` events stream in. Shows the streamed
- * reasoning (collapsible), the streamed visible output (rendered as
- * Markdown), and the chronological list of child tool calls with their
- * status and timings.
- *
- * Rendered as `null` when no subagent is selected, so the parent can
- * mount it unconditionally and just flip `subagent`.
- *
- * The overlay itself is the shared Radix-backed {@link SheetRoot}: the
- * hand-rolled `createPortal` + backdrop `<button>` + `keydown` listener it
- * replaced had no focus trap, no scroll lock and no focus restore on close.
- */
-export function SubagentDrawer({
- subagent,
- status,
- onCancel,
- onClose,
-}: {
- subagent: SubagentActivity | null;
- /** Lifecycle status of the owning timeline row (running/success/error). */
- status?: ToolTimelineEntryStatus;
- /**
- * Cancel this still-running detached sub-agent. When provided and the run is
- * running, a "Cancel task" affordance is shown. The parent owns the actual
- * abort + chat delivery (via `subagentApi.cancel`); the drawer only manages
- * the in-flight / error UI and closes on success. Rejecting surfaces an error.
- */
- onCancel?: () => Promise<void>;
- onClose: () => void;
-}) {
- const { t } = useT();
- // Cancel-in-flight + last-error state for the "Cancel task" affordance.
- // The parent keys this drawer by task id, so a different sub-agent remounts
- // with fresh state — no effect-driven reset needed (which would trip the
- // repo's `react-hooks/set-state-in-effect` rule).
- const [cancelling, setCancelling] = useState(false);
- const [cancelError, setCancelError] = useState(false);
-
- // Reopen-from-memory: when there's no live transcript (the row was
- // restored from a snapshot, or the user navigated back after the turn
- // ended) but a worker sub-thread backs it, load that thread's persisted
- // messages and render them as the conversation. Failures fall back to the
- // empty/working placeholder rather than blocking the drawer.
- // Tagged with the worker thread it was fetched for, so a pending request
- // for a previous thread can't paint the wrong conversation after the user
- // switches subagents.
- const [fetched, setFetched] = useState<{
- workerThreadId: string;
- prompt?: string;
- items: SubagentTranscriptItem[];
- } | null>(null);
- const liveTranscript = subagent?.transcript ?? [];
- const workerThreadId = subagent?.workerThreadId;
- const needsFetch = Boolean(subagent && workerThreadId && liveTranscript.length === 0);
-
- const statusLabel = useSubagentStatusLabel(status);
-
- useEffect(() => {
- if (!needsFetch || !workerThreadId) {
- setFetched(null);
- return;
- }
- // Clear any prior thread's transcript up front so it can't linger while
- // the new request is in flight.
- setFetched(null);
- let cancelled = false;
- log('reopen-from-memory: fetching worker thread %s', workerThreadId);
- void threadApi
- .getThreadMessages(workerThreadId)
- .then(data => {
- log('reopen-from-memory: %s returned %d messages', workerThreadId, data.messages.length);
- if (!cancelled) setFetched({ workerThreadId, ...transcriptFromMessages(data.messages) });
- })
- .catch(() => {
- log('reopen-from-memory: fetch failed for %s', workerThreadId);
- if (!cancelled) setFetched(null);
- });
- return () => {
- cancelled = true;
- };
- }, [needsFetch, workerThreadId]);
-
- if (!subagent) return null;
-
- const isRunning = status !== 'success' && status !== 'error' && status !== 'cancelled';
- // The "Cancel task" CTA is only meaningful for a live, still-running run the
- // parent gave us a cancel handler for.
- const canCancel = status === 'running' && Boolean(onCancel);
-
- const handleCancel = async () => {
- if (!onCancel || cancelling) return;
- log('cancel requested for task %s', subagent.taskId);
- setCancelling(true);
- setCancelError(false);
- try {
- await onCancel();
- // Success: the parent flips the row to cancelled and the notice rides the
- // idle-delivery path into chat — close the drawer.
- log('cancel succeeded for task %s', subagent.taskId);
- onClose();
- } catch {
- log('cancel FAILED for task %s', subagent.taskId);
- setCancelling(false);
- setCancelError(true);
- }
- };
- // Only trust the fetched transcript when it belongs to the current worker.
- const fetchedForCurrent =
- fetched && workerThreadId && fetched.workerThreadId === workerThreadId ? fetched : null;
- const transcript = liveTranscript.length > 0 ? liveTranscript : (fetchedForCurrent?.items ?? []);
- const promptText = subagent.prompt ?? fetchedForCurrent?.prompt;
- // The last visible-text item gets the live cursor while the run is in
- // flight (the model is mid-sentence on its final/visible output).
- let lastTextIdx = -1;
- for (let i = transcript.length - 1; i >= 0; i -= 1) {
- if (transcript[i].kind === 'text') {
- lastTextIdx = i;
- break;
- }
- }
-
- return (
- // `open` is hard-coded because this component renders nothing when there is
- // no subagent (the early return above) — `onOpenChange` is what routes
- // Escape / outside-click back to the caller's `onClose`.
- <SheetRoot
- open
- onOpenChange={next => {
- if (!next) onClose();
- }}>
- <SheetContent
- side="right"
- aria-describedby={undefined}
- data-testid="subagent-drawer"
- className="max-w-md">
- {/* Header */}
- <header className="flex shrink-0 items-center gap-2.5 border-b border-line px-4 py-3">
- <span
- aria-hidden
- className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary-50 text-base dark:bg-primary-500/15">
- 🤖
- </span>
- <div className="min-w-0 flex-1">
- <div className="flex items-center gap-2">
- {/* `asChild` keeps the historical inline span so the drawer's
- layout is unchanged while Radix gets its required title. */}
- <SheetTitle asChild>
- <span className="truncate font-semibold text-content">{subagent.agentId}</span>
- </SheetTitle>
- <span aria-hidden className={`h-2 w-2 shrink-0 rounded-full ${statusDot(status)}`} />
- </div>
- <div className="flex flex-wrap items-center gap-1.5 text-[11px] text-content-muted">
- <Badge variant={subagentStatusVariant(status)}>{statusLabel}</Badge>
- {subagent.childIteration != null ? (
- <span>
- {subagent.childMaxIterations != null
- ? `${t('conversations.toolTimeline.turn')} ${subagent.childIteration}/${subagent.childMaxIterations}`
- : `${t('conversations.toolTimeline.step')} ${subagent.childIteration}`}
- </span>
- ) : subagent.iterations != null ? (
- <span>
- {subagent.iterations} {t('conversations.toolTimeline.turn')}
- </span>
- ) : null}
- {subagent.elapsedMs != null ? <span>{formatElapsed(subagent.elapsedMs)}</span> : null}
- {subagent.mode ? <span>{subagent.mode}</span> : null}
- </div>
- </div>
- {canCancel ? (
- <Button
- variant="secondary"
- tone="danger"
- size="sm"
- onClick={handleCancel}
- disabled={cancelling}
- data-testid="subagent-cancel"
- className="shrink-0 rounded-full">
- {cancelling
- ? t('conversations.subagent.cancelling')
- : t('conversations.subagent.cancel')}
- </Button>
- ) : null}
- <Button
- iconOnly
- variant="tertiary"
- size="sm"
- onClick={onClose}
- aria-label={t('conversations.subagent.close')}
- className="shrink-0 rounded-full">
- ✕
- </Button>
- </header>
- {cancelError ? (
- <div
- role="alert"
- data-testid="subagent-cancel-error"
- className="shrink-0 border-b border-coral-200 bg-coral-50 px-4 py-2 text-xs text-coral-700 dark:border-coral-500/30 dark:bg-coral-500/10 dark:text-coral-300">
- {t('conversations.subagent.cancelFailed')}
- </div>
- ) : null}
-
- {/* Body — a parent↔subagent conversation: the parent's delegation
- prompt opens it, then the sub-agent replies as one chronological
- transcript (thinking, the text it produced, the tool calls that
- text triggered, the next turn — exactly as it was emitted). */}
- <div className="flex-1 space-y-3 overflow-y-auto px-4 py-4">
- {/* Parent → sub-agent: the delegation prompt (the "input"). */}
- {promptText ? (
- <div className="flex justify-end" data-testid="subagent-parent-prompt">
- <div className="max-w-[85%] rounded-2xl rounded-br-md bg-primary-500 px-3 py-2 text-sm text-content-inverted">
- <div className="mb-0.5 text-[10px] font-semibold uppercase tracking-wide text-content-inverted/70">
- {t('conversations.subagent.parent')}
- </div>
- <div className="whitespace-pre-wrap wrap-break-word">{promptText}</div>
- </div>
- </div>
- ) : null}
-
- {/* Sub-agent side: avatar label + its turns. */}
- <div className="flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wide text-content-faint">
- <span aria-hidden>🤖</span>
- {subagent.agentId}
- </div>
-
- {transcript.length === 0 ? (
- <p className="text-xs italic text-content-faint">
- {isRunning
- ? t('conversations.subagent.working')
- : t('conversations.subagent.noOutputYet')}
- </p>
- ) : (
- <ol className="space-y-2">
- {transcript.map((item, idx) => {
- // Insert a "Turn N" divider when the iteration advances.
- const prevIteration = idx > 0 ? transcript[idx - 1].iteration : undefined;
- const showTurn = item.iteration != null && item.iteration !== prevIteration;
- const turnDivider = showTurn ? (
- <li
- aria-hidden
- className="flex items-center gap-2 pt-1 text-[10px] font-medium uppercase tracking-wide text-content-faint"
- data-testid="subagent-turn-divider">
- <span className="h-px flex-1 bg-surface-strong" />
- {t('conversations.toolTimeline.turn')} {item.iteration}
- <span className="h-px flex-1 bg-surface-strong" />
- </li>
- ) : null;
-
- if (item.kind === 'thinking') {
- const thought = stripToolCallEnvelopes(item.text).trim();
- return (
- <ItemWrapper key={`th-${idx}`} divider={turnDivider}>
- <ReasoningTraceText
- text={thought}
- streaming={isRunning && idx === transcript.length - 1}
- collapsible={false}
- data-testid="subagent-transcript-thinking"
- />
- </ItemWrapper>
- );
- }
-
- if (item.kind === 'text') {
- return (
- <ItemWrapper key={`tx-${idx}`} divider={turnDivider}>
- <div data-testid="subagent-transcript-text">
- <BubbleMarkdown content={stripToolCallEnvelopes(item.text)} />
- {isRunning && idx === lastTextIdx ? (
- <span
- aria-hidden
- className="ml-0.5 inline-block h-3 w-1 animate-pulse bg-primary-400 align-middle"
- />
- ) : null}
- </div>
- </ItemWrapper>
- );
- }
-
- return (
- <ItemWrapper key={`tl-${item.callId}`} divider={turnDivider}>
- <AssistantUiToolCallCard
- toolName={item.toolName}
- args={item.args}
- result={item.result}
- status={item.status}
- displayName={item.displayName}
- detail={item.detail}
- elapsedMs={item.elapsedMs}
- failure={item.failure}
- />
- </ItemWrapper>
- );
- })}
- </ol>
- )}
- </div>
- </SheetContent>
- </SheetRoot>
- );
-}
-
-/** Render a transcript row, prefixed by an optional "Turn N" divider. */
-function ItemWrapper({ divider, children }: { divider: ReactNode; children: ReactNode }) {
- return (
- <>
- {divider}
- <li>{children}</li>
- </>
- );
-}
diff --git a/app/src/features/conversations/components/ToolFailureLines.tsx b/app/src/features/conversations/components/ToolFailureLines.tsx
deleted file mode 100644
index e53740d138..0000000000
--- a/app/src/features/conversations/components/ToolFailureLines.tsx
+++ /dev/null
@@ -1,58 +0,0 @@
-import { useT } from '../../../lib/i18n/I18nContext';
-import type { ToolFailureExplanation } from '../../../store/chatRuntimeSlice';
-
-/**
- * The failure classes the UI has localized copy for (#4254 / #4459), keyed by
- * the camelCase form of the wire's PascalCase `class`. Any class not in this
- * set falls back to the English `causePlain` / `nextAction` on the payload.
- */
-const LOCALIZED_FAILURE_CLASSES: ReadonlySet<string> = new Set([
- 'missingPermission',
- 'missingApp',
- 'serviceUnavailable',
- 'badCredentials',
- 'blockedByPolicy',
- 'modelConnection',
- 'timeout',
- 'denied',
- 'approvalExpired',
- 'notFound',
- 'unsupported',
- 'unknown',
-]);
-
-/** Lowercase the first character: `MissingPermission` → `missingPermission`. */
-function toCamelClass(cls: string): string {
- return cls.length > 0 ? cls[0].toLowerCase() + cls.slice(1) : cls;
-}
-
-/**
- * The "why + what to do next" pair rendered under a failed tool row (#4254 /
- * #4459). Copy resolves by failure class from i18n, falling back to the English
- * `causePlain` / `nextAction` carried on the wire when the class is one the UI
- * hasn't localized. Shared by the parent processing transcript and the
- * sub-agent renderers so a failed child tool shows the same why/next copy.
- */
-export function ToolFailureLines({ failure }: { failure: ToolFailureExplanation }) {
- const { t } = useT();
- const camel = toCamelClass(failure.class);
- const known = LOCALIZED_FAILURE_CLASSES.has(camel);
- const cause = known
- ? t(`conversations.toolFailure.${camel}.cause`, failure.causePlain)
- : failure.causePlain;
- const next = known
- ? t(`conversations.toolFailure.${camel}.next`, failure.nextAction)
- : failure.nextAction;
- return (
- <span
- data-testid="processing-tool-failure"
- className="mt-1 flex flex-col gap-0.5 text-[11px] leading-snug">
- <span className="text-coral-600 dark:text-coral-300">
- <span className="font-semibold">{t('conversations.toolFailure.whyLabel')}:</span> {cause}
- </span>
- <span className="text-content-muted">
- <span className="font-semibold">{t('conversations.toolFailure.nextLabel')}:</span> {next}
- </span>
- </span>
- );
-}
diff --git a/app/src/features/conversations/components/ToolTimelineBlock.tsx b/app/src/features/conversations/components/ToolTimelineBlock.tsx
deleted file mode 100644
index e4ebe5523a..0000000000
--- a/app/src/features/conversations/components/ToolTimelineBlock.tsx
+++ /dev/null
@@ -1,621 +0,0 @@
-import createDebug from 'debug';
-import { useCallback, useEffect, useRef, useState } from 'react';
-
-import {
- CollapsibleContent,
- CollapsibleRoot,
- CollapsibleTrigger,
-} from '../../../components/ui/Collapsible';
-import { useT } from '../../../lib/i18n/I18nContext';
-import type {
- ProcessingTranscriptItem,
- SubagentActivity,
- ToolTimelineEntry,
-} from '../../../store/chatRuntimeSlice';
-import { formatTimelineEntry, stripToolCallEnvelopes } from '../../../utils/toolTimelineFormatting';
-import { parseWorkerThreadRef } from '../utils/workerThreadRef';
-import { agentNameTone, AgentTimelineRail } from './AgentTimelineRail';
-import { AssistantUiSubagentCall, isActiveSubagentStatus } from './AssistantUiSubagentCall';
-import { ProcessingTranscriptView } from './ProcessingTranscriptView';
-import {
- coalesceTimelineEntries,
- normalizeToolBody,
- RepeatCount,
- workerStatusFromEntry,
-} from './toolTimelineRows';
-import { WorkerThreadRefCard } from './WorkerThreadRefCard';
-
-/** Tail of the parent's in-flight response shown in the processing panel. */
-const RESPONSE_PREVIEW_CHARS = 320;
-
-const log = createDebug('app:conversations:tool-timeline');
-
-/**
- * The parent agent's live response, surfaced inside the processing panel while
- * the turn is in flight — its lead-in narration ("Let me check your Notion…")
- * belongs with the work it's narrating, not in a standalone chat bubble. The
- * final answer still lands in the message bubble once the turn settles.
- * Collapsible + accented apart from the stone-toned sub-agent Thoughts so the
- * parent's own voice reads as the primary thread.
- *
- * The disclosure is the shared Radix {@link CollapsibleRoot}, which gives the
- * trigger real `aria-expanded` / `aria-controls` wiring that the hand-rolled
- * `<details>`/`<summary>` pair never had.
- */
-function LiveResponseBlock({ text }: { text: string }) {
- const { t } = useT();
- const clean = stripToolCallEnvelopes(text)
- .replace(/[ \t]+\n/g, '\n')
- .trimEnd();
- const shown = clean.slice(-RESPONSE_PREVIEW_CHARS);
- if (!shown.trim()) return null;
- return (
- <CollapsibleRoot
- defaultOpen
- data-testid="agent-live-response"
- className="group/resp mt-1.5 border-l-2 border-primary-300 pl-2 dark:border-primary-500/50">
- <CollapsibleTrigger
- size="sm"
- className="justify-start gap-1 px-0 py-0 hover:bg-transparent"
- aria-label={t('conversations.agentTaskInsights.response')}>
- <span aria-hidden className="text-[11px] leading-none">
- 💬
- </span>
- <span className="text-[11px] font-semibold tracking-wide text-primary-500 uppercase dark:text-primary-300">
- {t('conversations.agentTaskInsights.response')}
- </span>
- <span
- aria-hidden
- className="text-[10px] text-content-faint transition-transform group-data-[state=open]:rotate-90">
- ▶
- </span>
- </CollapsibleTrigger>
- <CollapsibleContent size="sm" className="px-0 pb-0">
- <p className="mt-0.5 text-[12px] leading-snug wrap-break-word whitespace-pre-wrap text-content-secondary">
- {clean.length > RESPONSE_PREVIEW_CHARS ? (
- <span className="text-content-faint">…</span>
- ) : null}
- {shown}
- <span
- aria-hidden
- className="ml-0.5 inline-block h-3 w-1 animate-pulse bg-primary-400 align-middle"
- />
- </p>
- </CollapsibleContent>
- </CollapsibleRoot>
- );
-}
-
-/**
- * Neutral surface tones for an expanded row's body (worker-thread card,
- * detail bubble, code block). Per the Figma "Agentic task insights"
- * design these read as plain light cards rather than status-coloured
- * panels — the row's *status* is conveyed by the agent name (see
- * {@link agentNameTone}), so the body stays visually quiet.
- */
-const BODY_SURFACE = 'bg-surface-muted';
-
-/**
- * Height of the in-flight timeline viewport. While a turn is active the row
- * list is windowed to this height and auto-follows the newest activity, so a
- * long run (dozens of steps, each able to expand) can no longer grow without
- * bound and shove the composer + message list around mid-turn. Settled turns
- * are untouched — they still collapse to the group summary as before.
- */
-const TIMELINE_VIEWPORT_CLASS = 'max-h-64 overflow-y-auto overscroll-contain';
-
-/** Distance from the bottom (px) still treated as "pinned to the live edge". */
-const STICK_TO_BOTTOM_SLACK_PX = 24;
-
-/**
- * One expandable timeline row's disclosure.
- *
- * Replaces the previous `<details open={autoExpand}>`, whose semantics this
- * reproduces exactly rather than approximately: the row follows `autoExpand`
- * whenever THAT value changes (running → settled collapses it again), but a
- * manual toggle in between sticks until the next such change. A plain
- * `defaultOpen` would have dropped the first half; a fully controlled
- * `open={autoExpand}` would have dropped the second.
- *
- * `forceMount` keeps the body in the DOM while collapsed, which is what
- * `<details>` did — the rows are never "wiped", only hidden.
- */
-function TimelineRowDisclosure({
- autoExpand,
- title,
- titleClassName,
- count,
- children,
-}: {
- autoExpand: boolean;
- title: string;
- titleClassName: string;
- count: number;
- children: React.ReactNode;
-}) {
- const [open, setOpen] = useState(autoExpand);
- // Render-time adjustment (React's documented "reset state on prop change"
- // pattern) rather than an effect, so the corrected frame is the first one
- // painted.
- const [prevAuto, setPrevAuto] = useState(autoExpand);
- if (prevAuto !== autoExpand) {
- setPrevAuto(autoExpand);
- setOpen(autoExpand);
- }
- return (
- <CollapsibleRoot
- open={open}
- onOpenChange={next => {
- log('timeline-row: user toggled open=%s (auto would be %s)', next, autoExpand);
- setOpen(next);
- }}
- className="group/row">
- <CollapsibleTrigger
- size="sm"
- className="justify-start gap-1.5 px-0 py-0 font-normal hover:bg-transparent">
- <span className={`text-[13px] font-medium ${titleClassName}`}>{title}</span>
- <RepeatCount count={count} />
- <span
- aria-hidden
- className="text-[11px] text-content-faint transition-transform group-data-[state=open]:rotate-90">
- ▶
- </span>
- </CollapsibleTrigger>
- <CollapsibleContent forceMount size="sm" className="px-0 pb-0">
- {children}
- </CollapsibleContent>
- </CollapsibleRoot>
- );
-}
-
-/**
- * The agent-run timeline rendered above an assistant answer — the
- * "Agentic task insights" surface from the Figma Chat design.
- *
- * Each {@link ToolTimelineEntry} is a row on a shared vertical timeline
- * rail ({@link AgentTimelineRail}); the agent name carries the run state
- * (pulsing while in flight, solid when done) and expands in place to show
- * its detail/code/sub-agent activity. The whole group sits under a
- * collapsible "Agentic task insights" header so the user can fold the live
- * activity away.
- */
-export function ToolTimelineBlock({
- entries,
- onViewSubagent,
- onViewDetails,
- onViewWholeRun,
- expandAllRows = false,
- liveResponse,
- turnActive,
- transcript,
-}: {
- entries: ToolTimelineEntry[];
- /** Opens the full-transcript drawer for a subagent row. When omitted,
- * subagent cards render without the "view full processing" affordance
- * (e.g. interrupted-snapshot rendering with no live driver). */
- onViewSubagent?: (subagent: SubagentActivity) => void;
- /** Compact chat mode: when set, a finished step renders as a single
- * `label + "View details →"` line (no inline expand) and the link opens the
- * side panel scoped to *that* step via this callback. The panel itself
- * renders without `onViewDetails` to keep the full expanded view. */
- onViewDetails?: (entry: ToolTimelineEntry) => void;
- /** Opens the whole-run "Agent Process Source" panel. When set, a compact
- * "View full agent process Source →" link sits in the group header beside the
- * "Agentic task insights" title (clicking it does NOT toggle the collapse). */
- onViewWholeRun?: () => void;
- /** Expand every row's details by default (used by the "Agent Process
- * Source" panel, where the whole run should be visible at a glance).
- * In the inline chat only the latest running row auto-expands. */
- expandAllRows?: boolean;
- /** The parent agent's in-flight response text. While the turn streams, its
- * narration renders inside this panel (as a "Response" block) instead of a
- * standalone chat bubble, so the lead-in sits with the work it narrates.
- * Omitted/empty once the turn settles — the final answer is the message
- * bubble. */
- liveResponse?: string;
- /** Whether a turn is in flight on this thread's lifecycle
- * (`inferenceTurnLifecycleByThread`), the same signal the chat threads page
- * uses. When provided, the sticky `userOverrideOpen` reset fires on THIS
- * value's true→false edge — once per USER TURN — instead of on `isRunning`'s
- * edge, which flips once PER SUB-AGENT within a single turn (each
- * subagent spawn→settle) and made the panel flicker open/closed as
- * sub-agents ran (regression from #5008). Falls back to `isRunning` when
- * omitted, which is correct for a settled/past-turn render (there is no
- * turn left to track). */
- turnActive?: boolean;
- /** The turn's interleaved processing transcript (narration + thinking + tool
- * pointers, in stream order). When non-empty the rail renders it through
- * {@link ProcessingTranscriptView} — the SAME component the Agent Process
- * Source panel uses — so the agent's prose and its tool steps appear in one
- * surface instead of narration living in the chat stream and thinking in a
- * separate bubble. Omitted/empty falls back to the tool-row list, which is
- * still correct for legacy snapshots that predate the transcript. */
- transcript?: ProcessingTranscriptItem[];
-}) {
- const { t } = useT();
-
- // Sticky override for the outer "Agentic task insights" group: `null` means
- // the user hasn't explicitly toggled it on THIS mount yet, so the group
- // falls back to the auto rule below (open while running, collapsed once
- // settled). Once the user clicks the trigger, this pins their choice —
- // including across later turns that stream onto the SAME mounted block
- // (e.g. the workflow copilot's dedicated thread, whose `ToolTimelineBlock`
- // stays mounted for the life of the conversation while `entries` keeps
- // growing turn over turn) — so a new turn's activity landing no longer
- // involuntarily re-collapses (or re-expands) a choice the user already
- // made ("Agentic task insights keeps collapsing on every new feedback").
- // Deliberately component-local state, not lifted to Redux:
- // the block never remounts mid-conversation in the one place this bug was
- // reported (`WorkflowCopilotPanel` renders it at a stable JSX position
- // with entries accumulating in `toolTimelineByThread`, not reset per
- // turn), so a plain `useState` already survives every turn it needs to.
- const [userOverrideOpen, setUserOverrideOpen] = useState<boolean | null>(null);
-
- // Whether *any* entry is currently running — computed here (ahead of the
- // `entries.length === 0` early return below) purely so the render-time
- // reset adjustment that follows runs every render; order doesn't matter for
- // this existence check, unlike `latestRunningEntryId` further down, which
- // needs the seq-sorted order to pick a specific "latest" row.
- const isRunning = entries.some(entry => entry.status === 'running');
-
- // The signal the reset below watches for a "turn just settled" edge. Prefer
- // the real TURN lifecycle (`turnActive`, sourced from
- // `inferenceTurnLifecycleByThread` — the same signal the chat threads page
- // uses) when the caller supplies it: it flips true→false exactly once per
- // USER TURN. `isRunning` is only a fallback for callers with no turn
- // lifecycle to hand (e.g. a settled/past-turn render, where entries never
- // change again anyway) — used directly it flips once PER SUB-AGENT within a
- // single turn (each subagent spawn→settle), which reset the override (and
- // so auto-collapsed the panel) repeatedly within one turn and made it
- // flicker open/closed as sub-agents ran (#5008 regression).
- const settleSignal = turnActive ?? isRunning;
-
- // Reset the user's manual open/close override on the settleSignal's
- // true→false edge (a turn just finished) so the auto-collapse applies to
- // the just-settled turn. The override only sticks WITHIN a turn —
- // preventing involuntary mid-feedback collapse (#4942) — not permanently
- // across turns.
- //
- // Done as a render-time adjustment (comparing against `prevSettleSignal`
- // state and calling both setters synchronously in the render body), not a
- // `useEffect`, per React's documented pattern for resetting state on a prop
- // transition: it bails out and re-renders with the reset applied before
- // paint, instead of committing a stale (still-collapsed/expanded) frame
- // and only correcting it a tick later once the effect runs.
- const [prevSettleSignal, setPrevSettleSignal] = useState(settleSignal);
- if (prevSettleSignal !== settleSignal) {
- if (prevSettleSignal && !settleSignal) {
- log('agent-task-insights: turn settled (running→done), resetting user override');
- setUserOverrideOpen(null);
- }
- setPrevSettleSignal(settleSignal);
- }
-
- // ── In-flight viewport: fixed height + auto-follow ──────────────────────
- // Windowed ONLY while the turn is in flight, and never under
- // `expandAllRows` (the Agent Process Source panel wants the full list, not
- // a 16rem porthole).
- //
- // Keyed off `turnActive` directly rather than `settleSignal` — the latter
- // falls back to `isRunning`, which flips once per SUB-AGENT inside a single
- // turn and would re-window + re-pin the viewport repeatedly mid-turn (the
- // same failure class as the #5008 collapse flicker). Callers that pass no
- // `turnActive` (settled/past-turn renders) never window at all, so nothing
- // about historical turns changes.
- const windowed = turnActive === true && !expandAllRows;
- const viewportRef = useRef<HTMLDivElement | null>(null);
- // Whether to keep pinning to the newest activity. A plain ref, not state:
- // no render output depends on it, and mutating it from the scroll handler
- // must not trigger a re-render on every wheel tick.
- const followTailRef = useRef(true);
-
- // Re-pin whenever a new turn starts windowing, so a user who scrolled up
- // during the previous turn isn't stuck detached for the next one.
- useEffect(() => {
- if (windowed) followTailRef.current = true;
- }, [windowed]);
-
- // Detach on scroll-up so reading an earlier step doesn't get yanked back
- // down by the next tool event; re-attach when they return to the bottom.
- const handleViewportScroll = () => {
- const el = viewportRef.current;
- if (!el) return;
- followTailRef.current =
- el.scrollHeight - el.scrollTop - el.clientHeight <= STICK_TO_BOTTOM_SLACK_PX;
- };
-
- // Follow the live edge. A ResizeObserver on the row list (rather than an
- // effect keyed on row count) catches every way the content grows: a new row
- // arriving, the running row auto-expanding, and `tool_args_delta` streaming
- // into an already-expanded row — the last of which changes no React key at
- // all and would otherwise silently stop following mid-tool.
- //
- // Attached via a CALLBACK REF, not a `useEffect([windowed])`. The effect
- // version never attached in a real turn: `windowed` flips true at the START
- // of the turn, when there is nothing to show yet, so the component returned
- // null, `viewportRef.current` was null, and the effect bailed. Rows arriving
- // afterwards re-rendered the viewport but did not change `windowed`, so the
- // effect never re-ran and no observer was ever created. A callback ref fires
- // whenever the node itself mounts or changes, which is exactly the event we
- // care about, and is immune to that ordering entirely.
- const observerRef = useRef<ResizeObserver | null>(null);
- const windowedRef = useRef(windowed);
- windowedRef.current = windowed;
- const attachViewport = useCallback((node: HTMLDivElement | null) => {
- observerRef.current?.disconnect();
- observerRef.current = null;
- viewportRef.current = node;
- if (!node || typeof ResizeObserver === 'undefined') return;
- // Children are in the DOM by the time a parent's ref callback runs.
- const inner = node.firstElementChild;
- if (!inner) return;
- const observer = new ResizeObserver(() => {
- // Read the live values through refs so the observer survives a settle →
- // re-arm without being torn down and rebuilt.
- if (!windowedRef.current || !followTailRef.current) return;
- // `auto`, not `smooth`: streaming deltas fire these back-to-back, and
- // queued smooth scrolls visibly lag behind the content.
- node.scrollTop = node.scrollHeight;
- });
- observer.observe(inner);
- observerRef.current = observer;
- }, []);
- useEffect(() => () => observerRef.current?.disconnect(), []);
-
- // Render whenever there is EITHER a tool row or transcript prose. Gating on
- // `entries` alone blanked the rail for the opening stretch of every turn —
- // narration streams before the first tool call — and hid a tool-less turn
- // (pure reasoning/narration) completely.
- if (entries.length === 0 && !(transcript && transcript.length > 0)) return null;
-
- // The rows + the parent's streaming response — shared by both the collapsible
- // (in-flight) and static (settled) header layouts below.
- // Sort by issue order (`seq`), not arrival order: a `tool_args_delta` for a
- // later parallel call can reach the store before an earlier call's own
- // event, which would otherwise create rows in the wrong order.
- // Sort a copy — `entries` may be a state slice other callers still rely on.
- const ordered = [...entries].sort((a, b) => a.seq - b.seq);
- // "Latest running" must be derived from the same seq-ordered list the rows
- // render from — not raw arrival order — or a running row that arrived late
- // but sorts earlier (e.g. seq [2, 0, 1]) gets treated as "latest" and the
- // wrong step stays expanded/linked in compact chat mode.
- const latestRunningEntryId = [...ordered].reverse().find(entry => entry.status === 'running')?.id;
-
- // Whole-run "View full agent process Source →" link — a SIBLING of the
- // disclosure trigger, not a child of it. Nesting one button inside another
- // is invalid HTML; as siblings the link needs no `stopPropagation` to avoid
- // toggling the group, and it stays outside the collapsible body so it is
- // reachable while the group is collapsed.
- const wholeRunLink = onViewWholeRun ? (
- <button
- type="button"
- onClick={() => {
- log('agent-task-insights: opening whole-run process source');
- onViewWholeRun();
- }}
- data-testid="view-process-source"
- className="shrink-0 text-[11px] font-medium text-primary-600 hover:underline dark:text-primary-300">
- {t('conversations.agentTaskInsights.viewProcessSource')} →
- </button>
- ) : null;
-
- // Coalesce runs of identical, body-less rows (e.g. a retry loop that spawns
- // the same integrations step 25×) into single `×N` rows before rendering.
- const rows = coalesceTimelineEntries(ordered);
-
- const body = (
- <>
- {/* Viewport wrapper. Stays in the tree in both modes so the row list is
- never remounted (and its disclosure state never reset) when a turn
- settles — only the height/scroll classes toggle. */}
- <div
- ref={attachViewport}
- onScroll={windowed ? handleViewportScroll : undefined}
- data-testid="tool-timeline-viewport"
- data-windowed={windowed ? 'true' : 'false'}
- className={windowed ? TIMELINE_VIEWPORT_CLASS : undefined}>
- {transcript && transcript.length > 0 ? (
- <ProcessingTranscriptView
- transcript={transcript}
- entries={ordered}
- // Keep the trailing thought expanded while the turn runs, so a
- // model that is still reasoning after its last tool step shows
- // progress instead of a collapsed 💭 row.
- live={turnActive ?? isRunning}
- renderSubagent={subagent => (
- <AssistantUiSubagentCall
- activity={subagent}
- running={isActiveSubagentStatus(subagent.status)}
- onView={onViewSubagent ? () => onViewSubagent(subagent) : undefined}
- />
- )}
- />
- ) : (
- <div className="text-sm text-content-faint">
- {rows.map(({ entry, count }, index) => {
- const formatted = formatTimelineEntry(entry, t);
- const detailContent =
- normalizeToolBody(formatted.detail) ?? normalizeToolBody(entry.argsBuffer);
- const workerRef = parseWorkerThreadRef(formatted.detail ?? entry.detail);
- const subagent = entry.subagent;
- const resultContent = normalizeToolBody(entry.result);
- // A subagent row should always render the expandable details so
- // its live activity is visible — even when there is no prompt
- // detail to show. Mirrors the rule that a non-subagent row only
- // expands when it has detail content (or a result to show).
- const expandable = detailContent != null || subagent != null || resultContent != null;
- const isLatestRunning =
- latestRunningEntryId != null && latestRunningEntryId === entry.id;
- const shouldAutoExpand = expandAllRows || isLatestRunning;
- const nameTone = agentNameTone(entry.status);
- // Chat mode: the currently-running step stays expanded inline in the
- // main UI; finished steps collapse to a compact "View details →" link
- // (their full activity lives in the side panel).
- const compact = onViewDetails != null && !isLatestRunning;
-
- return (
- <AgentTimelineRail
- key={entry.id}
- isFirst={index === 0}
- isLast={index === rows.length - 1}>
- {compact ? (
- // Collapsed step: the whole label is the link — "Run Code →"
- // opens the full-run panel scoped to this step. A collapsed row
- // is backgrounded, so it never pulses — only the single active
- // (expanded) step blinks. Strip `animate-pulse` from the tone.
- <div className="space-y-1">
- <button
- type="button"
- onClick={() => onViewDetails(entry)}
- data-testid="view-details"
- className="group/details flex items-center gap-1.5 text-left">
- <span
- className={`text-[13px] font-medium ${nameTone.replace('animate-pulse ', '')} group-hover/details:underline`}>
- {formatted.title}
- </span>
- <RepeatCount count={count} />
- <span className="text-[13px] font-medium text-primary-600 dark:text-primary-300">
- →
- </span>
- </button>
- {/* Output stays inline for FAILED steps only. On a success
- the agent's final answer is already the compression of
- what the tool returned, so repeating the raw result here
- just duplicates it — and a multi-tool turn stacked a
- scrollable <pre> per step above the answer. A failure is
- the case where the answer is least trustworthy (or may
- not mention the failure at all), so the evidence earns
- its space. Successful output is still one click away via
- this row's "→" and "View full agent process Source", and
- expanded rows / the process panel are unchanged. */}
- {resultContent && entry.status === 'error' ? (
- <pre
- data-testid="tool-result-output"
- className={`max-h-40 overflow-y-auto rounded px-2 py-1 font-mono text-[12px] whitespace-pre-wrap break-all text-content-secondary ${BODY_SURFACE}`}>
- {resultContent}
- </pre>
- ) : null}
- </div>
- ) : expandable ? (
- <TimelineRowDisclosure
- autoExpand={shouldAutoExpand}
- title={formatted.title}
- titleClassName={nameTone}
- count={count}>
- {workerRef ? (
- <div
- className={`mt-1 rounded-xl rounded-tl-md px-2.5 py-2 text-[13px] whitespace-pre-wrap wrap-break-word text-content-secondary ${BODY_SURFACE}`}>
- {workerRef.before}
- <WorkerThreadRefCard
- ref={workerRef.ref}
- status={workerStatusFromEntry(entry.status)}
- />
- {workerRef.after ? <div className="mt-1">{workerRef.after}</div> : null}
- </div>
- ) : formatted.detail ? (
- <div
- className={`mt-1 rounded-xl rounded-tl-md px-2.5 py-2 text-[13px] whitespace-pre-wrap wrap-break-word text-content-secondary ${BODY_SURFACE}`}>
- {formatted.detail}
- </div>
- ) : detailContent ? (
- <pre
- className={`mt-1 max-h-24 overflow-y-auto rounded px-2 py-1 font-mono text-[12px] whitespace-pre-wrap break-all text-content-secondary ${BODY_SURFACE}`}>
- {detailContent}
- </pre>
- ) : null}
- {resultContent ? (
- // What the tool returned (size-capped upstream). Scrolls
- // inside its own box so a long result never floods the
- // timeline.
- <pre
- data-testid="tool-result-output"
- className={`mt-1 max-h-40 overflow-y-auto rounded px-2 py-1 font-mono text-[12px] whitespace-pre-wrap break-all text-content-secondary ${BODY_SURFACE}`}>
- {resultContent}
- </pre>
- ) : null}
- {subagent ? (
- <AssistantUiSubagentCall
- activity={subagent}
- running={entry.status === 'running' || entry.status === 'awaiting_user'}
- onView={onViewSubagent ? () => onViewSubagent(subagent) : undefined}
- />
- ) : null}
- </TimelineRowDisclosure>
- ) : (
- <div className="flex items-center gap-1.5">
- <span className={`text-[13px] font-medium ${nameTone}`}>
- {formatted.title}
- </span>
- <RepeatCount count={count} />
- </div>
- )}
- </AgentTimelineRail>
- );
- })}
- </div>
- )}
- </div>
- {liveResponse ? <LiveResponseBlock text={liveResponse} /> : null}
- </>
- );
-
- // The group header is a static section label — the live "working" state is
- // conveyed by the pulsing agent-name rows, so it never repeats a "Working…"
- // string. Absent a user override, the group is auto-driven: open while the
- // run is in flight so the live activity is visible; collapsed once it
- // settles so a finished run (which can be dozens of steps) never dominates
- // the conversation. The full "Agent Process Source" panel forces every row
- // open via `expandAllRows`. Once the user has explicitly toggled the group,
- // THAT choice wins over the auto rule — otherwise a new turn streaming onto
- // an already-mounted block (settling, or starting a fresh run) would
- // silently flip `open` out from under the user's manual choice on every
- // turn.
- //
- // Driven by `settleSignal` (i.e. `turnActive` when the caller supplies it),
- // NOT by `isRunning`. `isRunning` means "a tool is executing *this instant*",
- // which goes false in every gap BETWEEN tools — while the agent reasons about
- // a result before issuing the next call. Keyed off that, the group snapped
- // shut a beat after each tool result and reopened when the next call started,
- // so a multi-tool turn flickered and a just-delivered result looked like it
- // had been wiped. #5008 already established `turnActive` as the correct
- // whole-turn signal and applied it to the override reset above; `autoOpen`
- // was left behind on `isRunning`. Same signal now drives both, so the group
- // stays open for the WHOLE turn and collapses once, at settle.
- const autoOpen = settleSignal || expandAllRows;
- const open = userOverrideOpen ?? autoOpen;
-
- return (
- // Radix `Collapsible`, fully controlled off `open` above: one source of
- // truth, plus the `aria-expanded`/`aria-controls` wiring the hand-rolled
- // `<details>`/`<summary>` pair never had. `forceMount` on the content keeps
- // the rows in the DOM while collapsed, exactly as `<details>` did — the
- // activity is hidden, never wiped.
- <CollapsibleRoot
- open={open}
- onOpenChange={next => {
- log('agent-task-insights: user toggled open=%s (auto would be %s)', next, autoOpen);
- setUserOverrideOpen(next);
- }}
- className="group/insights mb-2 px-1 py-0"
- data-testid="agent-task-insights">
- <div className="mb-1.5 flex items-center gap-1.5">
- <CollapsibleTrigger
- size="sm"
- className="w-auto justify-start gap-1.5 px-0 py-0 font-normal hover:bg-transparent">
- <span className="text-[13px] font-medium text-content-muted">
- {t('conversations.agentTaskInsights.title')}
- </span>
- <span
- aria-hidden
- className="text-[11px] text-content-faint transition-transform group-data-[state=open]:rotate-90">
- ▶
- </span>
- </CollapsibleTrigger>
- {wholeRunLink}
- </div>
- <CollapsibleContent forceMount size="sm" className="px-0 pb-0">
- {body}
- </CollapsibleContent>
- </CollapsibleRoot>
- );
-}
diff --git a/app/src/features/conversations/components/__tests__/AgentTimelineRail.test.tsx b/app/src/features/conversations/components/__tests__/AgentTimelineRail.test.tsx
deleted file mode 100644
index 0fa36f1e5a..0000000000
--- a/app/src/features/conversations/components/__tests__/AgentTimelineRail.test.tsx
+++ /dev/null
@@ -1,68 +0,0 @@
-import { render, screen } from '@testing-library/react';
-import { describe, expect, it } from 'vitest';
-
-import { agentNameTone, AgentTimelineRail } from '../AgentTimelineRail';
-
-describe('agentNameTone', () => {
- it('pulses + mutes a running agent (in progress)', () => {
- const tone = agentNameTone('running');
- expect(tone).toContain('animate-pulse');
- expect(tone).toContain('text-content-faint');
- });
-
- it('pulses an awaiting-user agent', () => {
- expect(agentNameTone('awaiting_user')).toContain('animate-pulse');
- });
-
- it('renders a done agent solid (no pulse)', () => {
- const tone = agentNameTone('success');
- expect(tone).not.toContain('animate-pulse');
- expect(tone).toContain('text-content-secondary');
- });
-
- it('tints a failed agent with the error token', () => {
- expect(agentNameTone('error')).toContain('coral');
- });
-
- it('treats an unknown status as in-progress', () => {
- expect(agentNameTone(undefined)).toContain('animate-pulse');
- });
-
- it('renders a cancelled agent muted and static (terminal, not pulsing)', () => {
- const tone = agentNameTone('cancelled');
- expect(tone).not.toContain('animate-pulse');
- expect(tone).toContain('text-content-faint');
- });
-});
-
-describe('AgentTimelineRail', () => {
- it('renders the row content and a spark node', () => {
- render(
- <AgentTimelineRail isFirst isLast>
- <span>Research Agent</span>
- </AgentTimelineRail>
- );
- const row = screen.getByTestId('agent-timeline-row');
- expect(row.textContent).toContain('Research Agent');
- expect(row.querySelector('svg')).not.toBeNull();
- });
-
- it('omits the upper connector on the first row and the lower connector on the last', () => {
- const { container } = render(
- <AgentTimelineRail isFirst isLast>
- <span>only</span>
- </AgentTimelineRail>
- );
- // first+last single row → no connector segments at all
- expect(container.querySelectorAll('span[aria-hidden]')).toHaveLength(0);
- });
-
- it('draws both connectors on a middle row', () => {
- const { container } = render(
- <AgentTimelineRail isFirst={false} isLast={false}>
- <span>middle</span>
- </AgentTimelineRail>
- );
- expect(container.querySelectorAll('span[aria-hidden]')).toHaveLength(2);
- });
-});
diff --git a/app/src/features/conversations/components/__tests__/SubagentDrawer.test.tsx b/app/src/features/conversations/components/__tests__/SubagentDrawer.test.tsx
deleted file mode 100644
index 9bcd783001..0000000000
--- a/app/src/features/conversations/components/__tests__/SubagentDrawer.test.tsx
+++ /dev/null
@@ -1,378 +0,0 @@
-import { render, screen, waitFor, within } from '@testing-library/react';
-import userEvent from '@testing-library/user-event';
-import { describe, expect, it, vi } from 'vitest';
-
-import { threadApi } from '../../../../services/api/threadApi';
-import type { SubagentActivity, SubagentTranscriptItem } from '../../../../store/chatRuntimeSlice';
-import { SubagentDrawer } from '../SubagentDrawer';
-
-vi.mock('../../../../services/api/threadApi', () => ({
- threadApi: { getThreadMessages: vi.fn() },
-}));
-
-function activity(overrides: Partial<SubagentActivity> = {}): SubagentActivity {
- return { taskId: 'sub-1', agentId: 'researcher', toolCalls: [], transcript: [], ...overrides };
-}
-
-const INTERLEAVED: SubagentTranscriptItem[] = [
- { kind: 'thinking', iteration: 1, text: 'comparing the two sources' },
- { kind: 'text', iteration: 1, text: 'Let me search for that.' },
- {
- kind: 'tool',
- iteration: 1,
- callId: 'c1',
- toolName: 'web_search',
- status: 'success',
- elapsedMs: 1200,
- },
- { kind: 'text', iteration: 2, text: 'The answer is **42**.' },
-];
-
-describe('SubagentDrawer', () => {
- it('renders nothing when no subagent is selected', () => {
- const { container } = render(<SubagentDrawer subagent={null} onClose={() => {}} />);
- expect(container.firstChild).toBeNull();
- });
-
- it('renders the transcript in chronological order (text where it occurred)', () => {
- render(
- <SubagentDrawer
- subagent={activity({ transcript: INTERLEAVED })}
- status="running"
- onClose={() => {}}
- />
- );
- const drawer = screen.getByTestId('subagent-drawer');
- expect(drawer.textContent).toContain('researcher');
-
- // Walk the rendered transcript items and assert their on-screen order:
- // thinking → text → tool → text — i.e. the tool sits between the two
- // text blocks, not in a separate section.
- const thinking = screen.getByTestId('subagent-transcript-thinking');
- const tool = screen.getByTestId('assistant-ui-tool-call');
- const texts = screen.getAllByTestId('subagent-transcript-text');
- expect(texts).toHaveLength(2);
-
- const order = (el: Element) =>
- Array.prototype.indexOf.call(drawer.querySelectorAll('[data-testid]'), el);
- expect(order(thinking)).toBeLessThan(order(texts[0]));
- expect(order(texts[0])).toBeLessThan(order(tool));
- expect(order(tool)).toBeLessThan(order(texts[1]));
-
- expect(thinking.textContent).toContain('comparing the two sources');
- // Rendered through the shared reasoning panel, inline (no disclosure).
- expect(thinking.getAttribute('data-variant')).toBe('static');
- expect(thinking.querySelector('button')).toBeNull();
- expect(tool.textContent).toContain('Searched the web');
- expect(tool.textContent).toContain('1.2s');
- expect(texts[1].textContent).toContain('The answer is');
- });
-
- it('renders the why/next explanation for a failed child tool call (#4459)', () => {
- render(
- <SubagentDrawer
- subagent={activity({
- transcript: [
- {
- kind: 'tool',
- iteration: 1,
- callId: 'cc-1',
- toolName: 'shell',
- status: 'error',
- // A class not in LOCALIZED_FAILURE_CLASSES so the copy falls back
- // to the verbatim causePlain/nextAction (i18n-independent assert).
- failure: {
- class: 'someUnclassifiedFailure',
- category: 'user_declined',
- recoverable: false,
- causePlain: 'You declined this action.',
- nextAction: 'Ask again if you change your mind.',
- },
- },
- ],
- })}
- onClose={() => {}}
- />
- );
- // Rendered through the vendored `tool-error` element (`ToolFailureCard`)
- // now that this drawer's failed child rows go through `AssistantUiToolCall`
- // instead of the legacy `ToolFailureLines` text.
- const failure = screen.getByTestId('assistant-ui-tool-failure');
- expect(failure).toHaveTextContent('You declined this action.');
- expect(failure).toHaveTextContent('Ask again if you change your mind.');
- });
-
- it('opens with the parent delegation prompt as a chat bubble', () => {
- render(
- <SubagentDrawer
- subagent={activity({
- prompt: 'Research Q3 revenue drivers and summarise.',
- transcript: [{ kind: 'text', iteration: 1, text: 'On it.' }],
- })}
- status="running"
- onClose={() => {}}
- />
- );
- const parent = screen.getByTestId('subagent-parent-prompt');
- expect(parent.textContent).toContain('Research Q3 revenue drivers');
- // The parent bubble renders before the sub-agent's reply.
- const drawer = screen.getByTestId('subagent-drawer');
- const text = screen.getByTestId('subagent-transcript-text');
- const order = (el: Element) =>
- Array.prototype.indexOf.call(drawer.querySelectorAll('[data-testid]'), el);
- expect(order(parent)).toBeLessThan(order(text));
- });
-
- it('inserts a turn divider when the iteration advances', () => {
- render(
- <SubagentDrawer
- subagent={activity({ transcript: INTERLEAVED })}
- status="running"
- onClose={() => {}}
- />
- );
- // Two distinct iterations (1 and 2) → two turn dividers.
- expect(screen.getAllByTestId('subagent-turn-divider')).toHaveLength(2);
- });
-
- it('shows a working placeholder while running with an empty transcript', () => {
- render(<SubagentDrawer subagent={activity()} status="running" onClose={() => {}} />);
- expect(screen.getByTestId('subagent-drawer').textContent).toContain('Working');
- });
-
- it('reopens from memory: fetches the worker thread when there is no live transcript', async () => {
- vi.mocked(threadApi.getThreadMessages).mockResolvedValue({
- count: 3,
- messages: [
- {
- id: 'm0',
- content: 'Research Q3 revenue.',
- type: 'text',
- sender: 'user',
- createdAt: 't0',
- extraMetadata: { scope: 'worker_thread' },
- },
- {
- id: 'm1',
- content: 'Searched the web.',
- type: 'text',
- sender: 'agent',
- createdAt: 't1',
- extraMetadata: { tool_name: 'web_search', iteration: 1 },
- },
- {
- id: 'm2',
- content: 'Revenue grew 18%.',
- type: 'text',
- sender: 'agent',
- createdAt: 't2',
- extraMetadata: { iteration: 2, final: true },
- },
- ],
- });
-
- render(
- <SubagentDrawer
- subagent={activity({ workerThreadId: 'worker-abc', transcript: [] })}
- status="success"
- onClose={() => {}}
- />
- );
-
- await waitFor(() => expect(threadApi.getThreadMessages).toHaveBeenCalledWith('worker-abc'));
- // The persisted conversation renders: parent prompt + a tool call + the text.
- await waitFor(() =>
- expect(screen.getByTestId('subagent-parent-prompt').textContent).toContain('Research Q3')
- );
- expect(screen.getByTestId('assistant-ui-tool-call').textContent).toContain('Searched the web');
- expect(screen.getByTestId('subagent-transcript-text').textContent).toContain(
- 'Revenue grew 18%'
- );
- });
-
- it('does not fetch when a live transcript is present', () => {
- render(
- <SubagentDrawer
- subagent={activity({
- workerThreadId: 'worker-abc',
- transcript: [{ kind: 'text', iteration: 1, text: 'live' }],
- })}
- status="running"
- onClose={() => {}}
- />
- );
- expect(threadApi.getThreadMessages).not.toHaveBeenCalled();
- });
-
- it('invokes onClose from the close button', async () => {
- const onClose = vi.fn();
- render(<SubagentDrawer subagent={activity()} status="success" onClose={onClose} />);
- await userEvent.click(screen.getByText('✕'));
- expect(onClose).toHaveBeenCalledTimes(1);
- });
-
- it('shows the Cancel task CTA only while running and with an onCancel handler', () => {
- // No handler → no CTA.
- const { rerender } = render(
- <SubagentDrawer subagent={activity()} status="running" onClose={() => {}} />
- );
- expect(screen.queryByTestId('subagent-cancel')).toBeNull();
-
- // Handler present but already finished → no CTA.
- rerender(
- <SubagentDrawer
- subagent={activity()}
- status="success"
- onCancel={vi.fn()}
- onClose={() => {}}
- />
- );
- expect(screen.queryByTestId('subagent-cancel')).toBeNull();
-
- // Running + handler → CTA shown.
- rerender(
- <SubagentDrawer
- subagent={activity()}
- status="running"
- onCancel={vi.fn()}
- onClose={() => {}}
- />
- );
- expect(screen.getByTestId('subagent-cancel')).toBeTruthy();
- });
-
- it('cancels via onCancel, then closes on success', async () => {
- const onCancel = vi.fn().mockResolvedValue(undefined);
- const onClose = vi.fn();
- render(
- <SubagentDrawer
- subagent={activity()}
- status="running"
- onCancel={onCancel}
- onClose={onClose}
- />
- );
- await userEvent.click(screen.getByTestId('subagent-cancel'));
- expect(onCancel).toHaveBeenCalledTimes(1);
- await waitFor(() => expect(onClose).toHaveBeenCalledTimes(1));
- expect(screen.queryByTestId('subagent-cancel-error')).toBeNull();
- });
-
- it('surfaces an error and stays open when cancel fails', async () => {
- const onCancel = vi.fn().mockRejectedValue(new Error('boom'));
- const onClose = vi.fn();
- render(
- <SubagentDrawer
- subagent={activity()}
- status="running"
- onCancel={onCancel}
- onClose={onClose}
- />
- );
- await userEvent.click(screen.getByTestId('subagent-cancel'));
- await waitFor(() => expect(screen.getByTestId('subagent-cancel-error')).toBeTruthy());
- expect(onClose).not.toHaveBeenCalled();
- });
-
- it('renders the cancelled status label', () => {
- render(<SubagentDrawer subagent={activity()} status="cancelled" onClose={() => {}} />);
- // Case-robust: the label may be rendered as "Cancelled" or "cancelled".
- expect(screen.getByTestId('subagent-drawer').textContent?.toLowerCase()).toContain('cancelled');
- });
-
- it('expands a tool call to reveal its input args and output', async () => {
- const transcript: SubagentTranscriptItem[] = [
- {
- kind: 'tool',
- iteration: 1,
- callId: 'c1',
- toolName: 'web_search',
- status: 'success',
- elapsedMs: 1200,
- args: { query: 'Q3 revenue drivers' },
- result: 'Found 3 results about revenue.',
- },
- ];
- render(
- <SubagentDrawer subagent={activity({ transcript })} status="success" onClose={() => {}} />
- );
-
- // Collapsed by default — neither input nor output is rendered yet.
- expect(screen.queryByTestId('assistant-ui-tool-input')).toBeNull();
- expect(screen.queryByTestId('assistant-ui-tool-output')).toBeNull();
-
- await userEvent.click(within(screen.getByTestId('assistant-ui-tool-call')).getByRole('button'));
-
- expect(screen.getByTestId('assistant-ui-tool-input').textContent).toContain(
- 'Q3 revenue drivers'
- );
- expect(screen.getByTestId('assistant-ui-tool-output').textContent).toContain(
- 'Found 3 results about revenue.'
- );
- });
-
- it('shows the no-output placeholder when the tool returned an empty result', async () => {
- const transcript: SubagentTranscriptItem[] = [
- { kind: 'tool', iteration: 1, callId: 'c1', toolName: 'noop', status: 'success', result: '' },
- ];
- render(
- <SubagentDrawer subagent={activity({ transcript })} status="success" onClose={() => {}} />
- );
- await userEvent.click(within(screen.getByTestId('assistant-ui-tool-call')).getByRole('button'));
- expect(screen.getByTestId('assistant-ui-tool-output').textContent?.toLowerCase()).toContain(
- 'no output'
- );
- });
-
- it('renders cancelled/awaiting_user tool-call statuses with their own label (not "failed")', () => {
- const transcript: SubagentTranscriptItem[] = [
- { kind: 'tool', iteration: 1, callId: 'c1', toolName: 'web_search', status: 'cancelled' },
- { kind: 'tool', iteration: 1, callId: 'c2', toolName: 'composio', status: 'awaiting_user' },
- ];
- render(
- <SubagentDrawer subagent={activity({ transcript })} status="cancelled" onClose={() => {}} />
- );
- const rows = screen.getAllByTestId('assistant-ui-tool-call');
- expect(rows[0].textContent?.toLowerCase()).toContain('cancelled');
- expect(rows[0].textContent?.toLowerCase()).not.toContain('failed');
- expect(rows[1].textContent?.toLowerCase()).toContain('awaiting');
- });
-
- it('does not offer expansion for a tool call with no captured args or result', () => {
- const transcript: SubagentTranscriptItem[] = [
- { kind: 'tool', iteration: 1, callId: 'c1', toolName: 'web_search', status: 'success' },
- ];
- render(
- <SubagentDrawer subagent={activity({ transcript })} status="success" onClose={() => {}} />
- );
- const toggle = within(screen.getByTestId('assistant-ui-tool-call')).getByRole('button');
- expect(toggle).toHaveAttribute('aria-expanded', 'false');
- expect(screen.queryByTestId('assistant-ui-tool-input')).toBeNull();
- expect(screen.queryByTestId('assistant-ui-tool-output')).toBeNull();
- });
-
- it('keeps a degraded "tool" row readable from its arguments, without guessing a web search', () => {
- // A provider that hands back a generic `tool` name leaves the row with
- // nothing better than "Tool" unless the arguments are there to read. Those
- // arguments only survive a reload because the snapshot now carries them
- // (#5987) — without them this row reads "Tool" again after a refresh.
- const transcript: SubagentTranscriptItem[] = [
- {
- kind: 'tool',
- iteration: 1,
- callId: 'c1',
- toolName: 'tool',
- status: 'success',
- displayName: 'tool',
- args: { query: 'openhuman turn state' },
- },
- ];
- render(
- <SubagentDrawer subagent={activity({ transcript })} status="success" onClose={() => {}} />
- );
- const row = screen.getByTestId('assistant-ui-tool-call');
- expect(row.textContent).toContain('Used tool');
- expect(row.textContent).toContain('openhuman turn state');
- expect(row.textContent).not.toContain('Searched the web');
- });
-});
diff --git a/app/src/features/conversations/components/__tests__/ToolTimelineBlock.test.tsx b/app/src/features/conversations/components/__tests__/ToolTimelineBlock.test.tsx
deleted file mode 100644
index 2c9229442a..0000000000
--- a/app/src/features/conversations/components/__tests__/ToolTimelineBlock.test.tsx
+++ /dev/null
@@ -1,1703 +0,0 @@
-import { fireEvent, render, screen, within } from '@testing-library/react';
-import userEvent from '@testing-library/user-event';
-import { Provider } from 'react-redux';
-import { describe, expect, it, vi } from 'vitest';
-
-import { store } from '../../../../store';
-import type { SubagentActivity, ToolTimelineEntry } from '../../../../store/chatRuntimeSlice';
-import { AssistantUiSubagentCall } from '../AssistantUiSubagentCall';
-import { ToolTimelineBlock } from '../ToolTimelineBlock';
-
-function SubagentActivityBlock({
- subagent,
- onView,
-}: {
- subagent: SubagentActivity;
- onView?: () => void;
-}) {
- return <AssistantUiSubagentCall activity={subagent} onView={onView} defaultOpen />;
-}
-
-// #1122 — guards the parent-thread live subagent rendering. The block
-// always expands subagent rows so the activity stays visible while the
-// run is in flight, even before the subagent emits any prompt detail.
-
-function renderInStore(ui: React.ReactNode) {
- return render(<Provider store={store}>{ui}</Provider>);
-}
-
-describe('SubagentActivityBlock', () => {
- it('derives its lifecycle from the activity when no running prop is passed', () => {
- // Most call sites (AgentProcessSourcePanel, PastTurnInsights, this block)
- // pass no `running` prop at all. The old `running = false` default reported
- // an in-flight delegation as finished, with a success check.
- renderInStore(
- <SubagentActivityBlock
- subagent={{ taskId: 't', agentId: 'researcher', status: 'running', toolCalls: [] }}
- />
- );
-
- expect(screen.getByText('running')).toBeInTheDocument();
- });
-
- it('marks a failed delegation as failed rather than complete', () => {
- renderInStore(
- <SubagentActivityBlock
- subagent={{ taskId: 't', agentId: 'researcher', status: 'failed', toolCalls: [] }}
- />
- );
-
- expect(screen.getByTestId('assistant-ui-subagent-call')).toHaveAttribute(
- 'data-status',
- 'failed'
- );
- expect(screen.getByText('failed')).toBeInTheDocument();
- expect(screen.queryByText('running')).not.toBeInTheDocument();
- });
-
- it('renders mode + dedicated-thread + child-turn pills', () => {
- renderInStore(
- <SubagentActivityBlock
- subagent={{
- taskId: 't',
- agentId: 'researcher',
- mode: 'typed',
- dedicatedThread: true,
- childIteration: 2,
- childMaxIterations: 5,
- toolCalls: [],
- }}
- />
- );
- const block = screen.getByTestId('subagent-activity');
- expect(block.textContent).toContain('typed');
- expect(block.textContent).toContain('worker thread');
- expect(block.textContent).toContain('turn 2/5');
- });
-
- it('renders "step N" when childMaxIterations is null (extended policy)', () => {
- renderInStore(
- <SubagentActivityBlock
- subagent={{ taskId: 't', agentId: 'code_executor', childIteration: 7, toolCalls: [] }}
- />
- );
- const block = screen.getByTestId('subagent-activity');
- expect(block.textContent).toContain('step 7');
- expect(block.textContent).not.toContain('/');
- });
-
- it('renders final-run statistics on a completed sub-agent', () => {
- renderInStore(
- <SubagentActivityBlock
- subagent={{
- taskId: 't',
- agentId: 'researcher',
- iterations: 3,
- elapsedMs: 4200,
- toolCalls: [],
- }}
- />
- );
- const block = screen.getByTestId('subagent-activity');
- expect(block.textContent).toContain('3 turns');
- expect(block.textContent).toContain('4.2s');
- });
-
- it('renders one row per child tool call with formatted names, status + timing', () => {
- renderInStore(
- <SubagentActivityBlock
- subagent={{
- taskId: 't',
- agentId: 'researcher',
- toolCalls: [
- { callId: 'c1', toolName: 'web_search', status: 'success', elapsedMs: 312 },
- { callId: 'c2', toolName: 'composio_execute', status: 'running', iteration: 2 },
- { callId: 'c3', toolName: 'file_read', status: 'error', elapsedMs: 50 },
- ],
- }}
- />
- );
- const calls = screen.getAllByTestId('assistant-ui-tool-call');
- expect(calls).toHaveLength(3);
- // Human labels + timing, with status as a tinted "Done" / "Failed" /
- // "Running" tag instead of a bare ✓/✕ glyph or the raw lowercase word.
- expect(calls[0].textContent).toContain('Searched the web');
- expect(calls[0].textContent?.toLowerCase()).toContain('done');
- expect(calls[0].textContent).toContain('312ms');
- expect(calls[1].textContent).toContain('Running app action');
- expect(calls[1].textContent?.toLowerCase()).toContain('running');
- expect(calls[1].textContent).not.toContain('·t2');
- expect(calls[2].textContent).toContain('Read file');
- expect(calls[2].textContent?.toLowerCase()).toContain('failed');
- expect(calls[2].textContent).toContain('50ms');
- });
-
- it('renders subagent web output as Markdown instead of raw JSON', async () => {
- renderInStore(
- <SubagentActivityBlock
- subagent={{
- taskId: 't',
- agentId: 'researcher',
- toolCalls: [],
- transcript: [
- {
- kind: 'tool',
- callId: 'search-1',
- toolName: 'web_search_tool',
- status: 'success',
- result: JSON.stringify({ content: '**Formal Conjectures**\n\n- OEIS Open' }),
- },
- ],
- }}
- />
- );
-
- expect(screen.getByText('Searched the web')).toBeInTheDocument();
- const call = screen.getByTestId('assistant-ui-tool-call');
- await userEvent.click(within(call).getByRole('button'));
- expect(screen.getByTestId('assistant-ui-tool-output')).toHaveTextContent('Formal Conjectures');
- expect(screen.getByRole('strong')).toHaveTextContent('Formal Conjectures');
- expect(screen.queryByText(/"content"/)).not.toBeInTheDocument();
- });
-
- // A query argument alone no longer makes a call "Searched the web"; that
- // heuristic mislabelled memory, tool and email searches.
- it('labels a degraded subagent tool name honestly, keeping its query visible', () => {
- renderInStore(
- <SubagentActivityBlock
- subagent={{
- taskId: 't',
- agentId: 'researcher',
- toolCalls: [
- {
- callId: 'generic-search',
- toolName: 'tool',
- status: 'success',
- args: { query: 'world news' },
- result: '# Search results\n\n- Headline',
- },
- ],
- }}
- />
- );
-
- const call = screen.getByTestId('assistant-ui-tool-call');
- expect(call).toHaveTextContent('Used tool');
- expect(call).toHaveTextContent('world news');
- expect(call).not.toHaveTextContent('Searched the web');
- });
-
- it('labels cancelled / awaiting-user calls distinctly (not the green "Done" pill)', () => {
- renderInStore(
- <SubagentActivityBlock
- subagent={{
- taskId: 't',
- agentId: 'researcher',
- toolCalls: [
- { callId: 'c1', toolName: 'web_search', status: 'cancelled', elapsedMs: 10 },
- { callId: 'c2', toolName: 'file_read', status: 'awaiting_user' },
- ],
- }}
- />
- );
- const calls = screen.getAllByTestId('assistant-ui-tool-call');
- expect(calls).toHaveLength(2);
- // A cancelled / awaiting-user call must NOT read as a successful "Done" step.
- expect(calls[0].textContent?.toLowerCase()).toContain('cancelled');
- expect(calls[0].textContent?.toLowerCase()).not.toContain('done');
- expect(calls[1].textContent?.toLowerCase()).toContain('awaiting input');
- expect(calls[1].textContent?.toLowerCase()).not.toContain('done');
- });
-
- it('names a connected-app action by its app, with the server detail beside the action', () => {
- renderInStore(
- <SubagentActivityBlock
- subagent={{
- taskId: 't',
- agentId: 'researcher',
- toolCalls: [
- {
- callId: 'c1',
- toolName: 'GMAIL_READ_MESSAGES',
- status: 'success',
- displayName: 'Reading messages',
- detail: '[email protected]',
- },
- ],
- }}
- />
- );
- const row = screen.getByTestId('assistant-ui-tool-call');
- expect(row.textContent).toContain('Used Gmail');
- expect(row.textContent).toContain('Read messages · [email protected]');
- // Never the raw snake_case slug.
- expect(row.textContent).not.toContain('GMAIL_READ_MESSAGES');
- });
-
- it('renders every thought inline as quoted prose (reasoning + narration)', () => {
- renderInStore(
- <SubagentActivityBlock
- subagent={{
- taskId: 't',
- agentId: 'researcher',
- toolCalls: [],
- transcript: [
- { kind: 'thinking', iteration: 1, text: 'pondering the request' },
- { kind: 'text', iteration: 1, text: 'Here is what I found so far about the topic' },
- ],
- }}
- />
- );
- const thoughts = screen.getAllByTestId('subagent-thought');
- // Both reasoning and visible narration surface as their own prose block —
- // shown directly, with no "Thoughts" heading.
- expect(thoughts).toHaveLength(2);
- expect(thoughts[0].textContent).toContain('pondering the request');
- expect(thoughts[0].textContent).not.toContain('Thoughts');
- expect(thoughts[1].textContent).toContain('Here is what I found so far');
- });
-
- it('renders thoughts and tool calls interleaved in transcript order', () => {
- renderInStore(
- <SubagentActivityBlock
- subagent={{
- taskId: 't',
- agentId: 'researcher',
- toolCalls: [],
- transcript: [
- { kind: 'thinking', iteration: 1, text: 'I should search the web first' },
- { kind: 'tool', iteration: 1, callId: 'c1', toolName: 'web_search', status: 'success' },
- { kind: 'text', iteration: 1, text: 'Found three relevant results' },
- ],
- }}
- />
- );
- const rows = screen.getByTestId('subagent-transcript').children;
- // Order is preserved: thought → tool → thought.
- expect(rows[0]).toHaveAttribute('data-testid', 'subagent-thought');
- expect(rows[0].textContent).toContain('I should search the web first');
- expect(rows[1]).toHaveAttribute('data-testid', 'assistant-ui-tool-call');
- expect(rows[1].textContent).toContain('Searched the web');
- expect(rows[2]).toHaveAttribute('data-testid', 'subagent-thought');
- expect(rows[2].textContent).toContain('Found three relevant results');
- });
-
- it('shows a thought directly as prose — no heading, no collapse', () => {
- renderInStore(
- <SubagentActivityBlock
- subagent={{
- taskId: 't',
- agentId: 'researcher',
- toolCalls: [],
- transcript: [{ kind: 'thinking', iteration: 1, text: 'weighing the options' }],
- }}
- />
- );
- const thought = screen.getByTestId('subagent-thought');
- // Not a disclosure at all — the text is shown directly. Asserted against
- // the RADIX observables, because the disclosures in this file moved off
- // `<details>`/`<summary>`: after that move, `tagName !== 'DETAILS'` and
- // `querySelector('summary') === null` became true of every node in the
- // tree, so both passed without being able to fail. `data-state` and an
- // `aria-expanded` trigger are what a collapsed Collapsible would
- // actually emit here.
- expect(thought).not.toHaveAttribute('data-state');
- expect(thought.querySelector('[aria-expanded]')).toBeNull();
- expect(thought.textContent).toContain('weighing the options');
- expect(thought.textContent).not.toContain('Thoughts');
- expect(thought.textContent).not.toContain('💭');
- });
-
- it('strips a leaked <tool_call> envelope from the thought text', () => {
- renderInStore(
- <SubagentActivityBlock
- subagent={{
- taskId: 't',
- agentId: 'researcher',
- toolCalls: [],
- transcript: [
- {
- kind: 'text',
- iteration: 1,
- text: 'I\'ll search your Notion for that. <tool_call> {"name": "NOTION_SEARCH", "arguments": {"query": "audit"}} </tool_call>',
- },
- ],
- }}
- />
- );
- const thought = screen.getByTestId('subagent-thought');
- expect(thought.textContent).toContain("I'll search your Notion for that.");
- // The raw tool-call envelope must not leak into the displayed prose.
- expect(thought.textContent).not.toContain('tool_call');
- expect(thought.textContent).not.toContain('NOTION_SEARCH');
- });
-
- it('skips an all-whitespace thought delta', () => {
- renderInStore(
- <SubagentActivityBlock
- subagent={{
- taskId: 't',
- agentId: 'researcher',
- toolCalls: [],
- transcript: [{ kind: 'thinking', iteration: 1, text: ' \n ' }],
- }}
- />
- );
- expect(screen.queryByTestId('subagent-thought')).toBeNull();
- });
-
- it('renders the view-processing button only when onView is provided', async () => {
- const onView = vi.fn();
- const { rerender } = renderInStore(
- <SubagentActivityBlock subagent={{ taskId: 't', agentId: 'researcher', toolCalls: [] }} />
- );
- expect(screen.queryByTestId('subagent-view-processing')).toBeNull();
-
- rerender(
- <Provider store={store}>
- <SubagentActivityBlock
- subagent={{ taskId: 't', agentId: 'researcher', toolCalls: [] }}
- onView={onView}
- />
- </Provider>
- );
- const btn = screen.getByTestId('subagent-view-processing');
- await userEvent.click(btn);
- expect(onView).toHaveBeenCalledTimes(1);
- });
-
- it('renders the inline worktree block + actions when worktreePath is set (#3376)', () => {
- renderInStore(
- <SubagentActivityBlock
- subagent={{
- taskId: 't',
- agentId: 'coder',
- toolCalls: [],
- worktreePath: '/r/.claude/worktrees/worker-a',
- changedFiles: ['src/lib.rs'],
- isDirty: true,
- }}
- />
- );
- const block = screen.getByTestId('subagent-worktree');
- expect(block).toBeInTheDocument();
- // Compact label shows the basename, not the full path.
- expect(block).toHaveTextContent('worker-a');
- expect(screen.getByTestId('worktree-actions')).toBeInTheDocument();
- expect(screen.getByTestId('worktree-remove')).toBeInTheDocument();
- });
-
- it('omits the worktree block for a non-isolated subagent', () => {
- renderInStore(
- <SubagentActivityBlock subagent={{ taskId: 't', agentId: 'researcher', toolCalls: [] }} />
- );
- expect(screen.queryByTestId('subagent-worktree')).toBeNull();
- });
-});
-
-describe('ToolTimelineBlock — agentic task insights surface', () => {
- it('wraps rows in the "Agentic task insights" group and conveys run state on the name', () => {
- const entries: ToolTimelineEntry[] = [
- {
- id: 'r',
- name: 'web_search',
- round: 1,
- seq: 0,
- status: 'running',
- argsBuffer: '{"query":"f1"}',
- },
- {
- id: 'd',
- name: 'file_read',
- round: 1,
- seq: 0,
- status: 'success',
- argsBuffer: '{"path":"/a/b.txt"}',
- },
- ];
- renderInStore(<ToolTimelineBlock entries={entries} />);
- const group = screen.getByTestId('agent-task-insights');
- expect(group).toBeInTheDocument();
- // Static section label — NOT a duplicate "Working…" string (the live
- // state lives on the pulsing row names, not the header).
- expect(group.textContent).toContain('Agentic task insights');
- expect(group.textContent).not.toContain('Working');
- // Two rows on the timeline rail.
- expect(screen.getAllByTestId('agent-timeline-row')).toHaveLength(2);
- // Running row name pulses; done row name is solid.
- const running = screen.getByText('Searching the web');
- const done = screen.getByText('Read file');
- expect(running.className).toContain('animate-pulse');
- expect(done.className).not.toContain('animate-pulse');
- });
-
- it('renders rows in seq (issue) order, not array (arrival) order', () => {
- // Simulates the out-of-order-arrival bug: a `tool_args_delta` for
- // a later parallel call can land — and create its row — before an
- // earlier call's own event, so the entries array ends up scrambled
- // relative to the order the agent actually issued the calls. `seq` is
- // the source of truth for display order; the array position is not.
- const entries: ToolTimelineEntry[] = [
- { id: 'third', name: 'run_code', round: 1, seq: 2, status: 'success' },
- { id: 'first', name: 'web_search', round: 1, seq: 0, status: 'success' },
- { id: 'second', name: 'file_read', round: 1, seq: 1, status: 'success' },
- ];
- renderInStore(<ToolTimelineBlock entries={entries} />);
- const rows = screen.getAllByTestId('agent-timeline-row');
- expect(rows).toHaveLength(3);
- expect(rows[0].textContent).toContain('Searched the web');
- expect(rows[1].textContent).toContain('Read file');
- expect(rows[2].textContent).toContain('Ran code');
- });
-
- it('renders nothing for an empty timeline', () => {
- const { container } = renderInStore(<ToolTimelineBlock entries={[]} />);
- expect(container.querySelector('[data-testid="agent-task-insights"]')).toBeNull();
- });
-
- it('stays open while running and collapses once settled so a finished run does not dominate', () => {
- const running: ToolTimelineEntry[] = [
- { id: 'r', name: 'web_search', round: 1, seq: 0, status: 'running' },
- ];
- const { rerender } = renderInStore(<ToolTimelineBlock entries={running} />);
- // In flight → the group is open so the live activity is visible.
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'open');
-
- // Settled (no running row) → collapsed by default; the rows stay in the DOM
- // one click away, but no longer flood the conversation.
- const settled: ToolTimelineEntry[] = [
- { id: 'r', name: 'web_search', round: 1, seq: 0, status: 'success' },
- ];
- rerender(
- <Provider store={store}>
- <ToolTimelineBlock entries={settled} />
- </Provider>
- );
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'closed');
-
- // The side panel still forces every row open via expandAllRows.
- rerender(
- <Provider store={store}>
- <ToolTimelineBlock entries={settled} expandAllRows />
- </Provider>
- );
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'open');
- });
-
- // Regression coverage for "Agentic task insights keeps collapsing on every
- // new feedback": the workflow copilot keeps ONE `ToolTimelineBlock` mounted
- // for the life of a thread, appending each new turn's entries onto the same
- // `entries` prop (see `WorkflowCopilotPanel`/`useWorkflowBuilderChat`) — it
- // never remounts the block per turn. Before the fix, the outer group's
- // `open` was driven purely by `isRunning || expandAllRows`, so every time a
- // turn settled (running → not running) the group snapped shut regardless of
- // anything the user had done, discarding a manual expand made moments
- // earlier. These tests simulate that same "new turn's entries land on an
- // already-mounted block" shape via `rerender` rather than remounting.
- describe('agentic task insights — sticky user expand/collapse across turns', () => {
- it('resets a user expand when a new turn settles', () => {
- const turn1Settled: ToolTimelineEntry[] = [
- { id: 't1', name: 'web_search', round: 1, seq: 0, status: 'success' },
- ];
- const { rerender } = renderInStore(<ToolTimelineBlock entries={turn1Settled} />);
- // Default: settled and collapsed (unchanged behaviour).
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'closed');
-
- // The user manually expands it.
- fireEvent.click(screen.getByText('Agentic task insights'));
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'open');
-
- // A new turn/feedback starts streaming onto the SAME mounted block. The
- // override still wins WHILE it runs — the user's choice isn't clobbered
- // mid-turn (#4942).
- const turn2Running: ToolTimelineEntry[] = [
- ...turn1Settled,
- { id: 't2', name: 'file_read', round: 2, seq: 1, status: 'running' },
- ];
- rerender(
- <Provider store={store}>
- <ToolTimelineBlock entries={turn2Running} />
- </Provider>
- );
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'open');
-
- // ...and settles. The override only sticks WITHIN a turn — once this
- // turn finishes, the auto-collapse applies to it, so the panel
- // collapses instead of permanently overriding every future turn.
- const turn2Settled: ToolTimelineEntry[] = [
- ...turn1Settled,
- { id: 't2', name: 'file_read', round: 2, seq: 1, status: 'success' },
- ];
- rerender(
- <Provider store={store}>
- <ToolTimelineBlock entries={turn2Settled} />
- </Provider>
- );
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'closed');
- });
-
- it('leaves the default open-while-running/collapsed-when-settled behaviour unchanged absent any user interaction', () => {
- const running: ToolTimelineEntry[] = [
- { id: 'r', name: 'web_search', round: 1, seq: 0, status: 'running' },
- ];
- const { rerender } = renderInStore(<ToolTimelineBlock entries={running} />);
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'open');
-
- const settled: ToolTimelineEntry[] = [
- { id: 'r', name: 'web_search', round: 1, seq: 0, status: 'success' },
- ];
- rerender(
- <Provider store={store}>
- <ToolTimelineBlock entries={settled} />
- </Provider>
- );
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'closed');
- });
-
- it('also persists an explicit user collapse across a new turn (does not force it back open)', () => {
- const turn1Running: ToolTimelineEntry[] = [
- { id: 't1', name: 'web_search', round: 1, seq: 0, status: 'running' },
- ];
- const { rerender } = renderInStore(<ToolTimelineBlock entries={turn1Running} />);
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'open');
-
- // The user collapses it while a turn is still running.
- fireEvent.click(screen.getByText('Agentic task insights'));
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'closed');
-
- // A new turn starts running — the auto rule alone would force it back
- // open, but the user's explicit collapse must win.
- const turn2Running: ToolTimelineEntry[] = [
- { id: 't1', name: 'web_search', round: 1, seq: 0, status: 'success' },
- { id: 't2', name: 'file_read', round: 2, seq: 1, status: 'running' },
- ];
- rerender(
- <Provider store={store}>
- <ToolTimelineBlock entries={turn2Running} />
- </Provider>
- );
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'closed');
- });
-
- it('auto-collapses when a turn finishes even if the user had expanded it', () => {
- const turn1Settled: ToolTimelineEntry[] = [
- { id: 't1', name: 'web_search', round: 1, seq: 0, status: 'success' },
- ];
- const { rerender } = renderInStore(<ToolTimelineBlock entries={turn1Settled} />);
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'closed');
-
- // User expands the settled turn1 panel.
- fireEvent.click(screen.getByText('Agentic task insights'));
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'open');
-
- // A new turn starts running — stays open (both the override and the
- // auto rule agree here).
- const turn2Running: ToolTimelineEntry[] = [
- ...turn1Settled,
- { id: 't2', name: 'file_read', round: 2, seq: 1, status: 'running' },
- ];
- rerender(
- <Provider store={store}>
- <ToolTimelineBlock entries={turn2Running} />
- </Provider>
- );
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'open');
-
- // It settles — the override is cleared on this running→settled edge,
- // so the panel auto-collapses instead of staying pinned open forever.
- const turn2Settled: ToolTimelineEntry[] = [
- ...turn1Settled,
- { id: 't2', name: 'file_read', round: 2, seq: 1, status: 'success' },
- ];
- rerender(
- <Provider store={store}>
- <ToolTimelineBlock entries={turn2Settled} />
- </Provider>
- );
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'closed');
- });
-
- it('does not collapse mid-stream when new entries arrive on a running turn', () => {
- const turn1Running: ToolTimelineEntry[] = [
- { id: 't1', name: 'web_search', round: 1, seq: 0, status: 'running' },
- ];
- const { rerender } = renderInStore(<ToolTimelineBlock entries={turn1Running} />);
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'open');
-
- // More entries stream in while the turn is still running — the
- // running→settled edge never fires, so the panel must stay open.
- const turn1StillRunning: ToolTimelineEntry[] = [
- ...turn1Running,
- { id: 't1b', name: 'file_read', round: 1, seq: 1, status: 'running' },
- ];
- rerender(
- <Provider store={store}>
- <ToolTimelineBlock entries={turn1StillRunning} />
- </Provider>
- );
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'open');
-
- const turn1MoreRunning: ToolTimelineEntry[] = [
- { id: 't1', name: 'web_search', round: 1, seq: 0, status: 'success' },
- { id: 't1b', name: 'file_read', round: 1, seq: 1, status: 'running' },
- ];
- rerender(
- <Provider store={store}>
- <ToolTimelineBlock entries={turn1MoreRunning} />
- </Provider>
- );
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'open');
- });
-
- it('respects a manual expand during an active turn, resets on settle', () => {
- const turn1Running: ToolTimelineEntry[] = [
- { id: 't1', name: 'web_search', round: 1, seq: 0, status: 'running' },
- ];
- const { rerender } = renderInStore(<ToolTimelineBlock entries={turn1Running} />);
- // Auto-open while running (no override yet).
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'open');
-
- // User explicitly collapses it mid-run...
- fireEvent.click(screen.getByText('Agentic task insights'));
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'closed');
-
- // ...then explicitly re-expands it — a manual expand during the still-
- // active turn — and it must stick while the turn keeps running.
- fireEvent.click(screen.getByText('Agentic task insights'));
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'open');
-
- // The turn settles — the manual override resets on this edge, and
- // since the run is done the auto rule collapses the panel.
- const turn1Settled: ToolTimelineEntry[] = [
- { id: 't1', name: 'web_search', round: 1, seq: 0, status: 'success' },
- ];
- rerender(
- <Provider store={store}>
- <ToolTimelineBlock entries={turn1Settled} />
- </Provider>
- );
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'closed');
- });
- });
-
- // #5008 shipped the reset-on-settle fix using the `isRunning` true→false
- // edge, but that edge fires once PER SUB-AGENT within a single turn (each
- // subagent_spawned/subagent_completed pair toggles `isRunning`), not once
- // per turn — so on a multi-sub-agent turn the panel's override reset (and
- // its auto-collapse) fired repeatedly, flickering the panel open/closed
- // as each sub-agent came and went. `turnActive` — sourced from
- // `inferenceTurnLifecycleByThread`, the same lifecycle the chat threads
- // page uses for `isSending` — transitions exactly once per USER TURN, so
- // passing it in makes the reset track the turn instead of any single
- // sub-agent.
- describe('with turnActive prop', () => {
- it('does not reset the user override while turnActive stays true across multiple isRunning toggles, only resetting (and auto-collapsing) when turnActive itself goes false', () => {
- const subagentARunning: ToolTimelineEntry[] = [
- { id: 'a', name: 'subagent:researcher', round: 1, seq: 0, status: 'running' },
- ];
- const { rerender } = renderInStore(
- <ToolTimelineBlock entries={subagentARunning} turnActive />
- );
- // Sub-agent A running, turn active → auto-open (no override yet).
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'open');
-
- // Sub-agent A settles: `isRunning` flips true→false, but the whole
- // TURN is still active, so the group STAYS OPEN.
- //
- // This expectation was inverted deliberately. #5008 moved the override
- // reset onto `turnActive` but left `autoOpen` on `isRunning`, so the
- // group still auto-collapsed in every gap between tools/sub-agents —
- // a just-delivered tool result appeared to be wiped a beat later, and a
- // multi-tool turn flickered. `autoOpen` now tracks the same whole-turn
- // signal as the reset, so the group collapses exactly once, at settle.
- const subagentASettled: ToolTimelineEntry[] = [
- { id: 'a', name: 'subagent:researcher', round: 1, seq: 0, status: 'success' },
- ];
- rerender(
- <Provider store={store}>
- <ToolTimelineBlock entries={subagentASettled} turnActive />
- </Provider>
- );
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'open');
-
- // The user manually COLLAPSES it while the turn is still in flight.
- // (Pre-change the auto rule had already closed it here, so this click
- // was an expand; the override mechanic under test is identical either
- // way — what matters is that the explicit choice survives the toggles
- // below.)
- fireEvent.click(screen.getByText('Agentic task insights'));
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'closed');
-
- // Sub-agent B spawns: `isRunning` flips false→true again. Still one
- // turn (`turnActive` unchanged) — the user's override must hold, so the
- // group stays COLLAPSED despite the auto rule wanting it open.
- const subagentBRunning: ToolTimelineEntry[] = [
- ...subagentASettled,
- { id: 'b', name: 'subagent:coder', round: 1, seq: 1, status: 'running' },
- ];
- rerender(
- <Provider store={store}>
- <ToolTimelineBlock entries={subagentBRunning} turnActive />
- </Provider>
- );
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'closed');
-
- // Sub-agent B settles: `isRunning` flips true→false a second time
- // within the SAME turn. This is exactly the edge that used to reset
- // the override and cause the flicker (#5008 regression) — with
- // `turnActive` supplied it must NOT reset; the user's collapse sticks.
- const subagentBSettled: ToolTimelineEntry[] = [
- ...subagentASettled,
- { id: 'b', name: 'subagent:coder', round: 1, seq: 1, status: 'success' },
- ];
- rerender(
- <Provider store={store}>
- <ToolTimelineBlock entries={subagentBSettled} turnActive />
- </Provider>
- );
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'closed');
-
- // Only when the TURN itself ends (`turnActive` true→false) does the
- // override reset — the panel then auto-collapses since the run is done.
- rerender(
- <Provider store={store}>
- <ToolTimelineBlock entries={subagentBSettled} turnActive={false} />
- </Provider>
- );
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'closed');
- });
-
- it('keeps a mid-turn manual collapse intact across a sub-agent settling, only reopening per the auto rule once turnActive ends', () => {
- const subagentARunning: ToolTimelineEntry[] = [
- { id: 'a', name: 'subagent:researcher', round: 1, seq: 0, status: 'running' },
- ];
- const { rerender } = renderInStore(
- <ToolTimelineBlock entries={subagentARunning} turnActive />
- );
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'open');
-
- // The user explicitly collapses it while sub-agent A is still running.
- fireEvent.click(screen.getByText('Agentic task insights'));
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'closed');
-
- // Sub-agent A settles, sub-agent B spawns and settles too — all within
- // the same turn (`turnActive` stays true throughout). None of these
- // `isRunning` toggles may reopen the panel against the user's choice.
- const afterSubagentB: ToolTimelineEntry[] = [
- { id: 'a', name: 'subagent:researcher', round: 1, seq: 0, status: 'success' },
- { id: 'b', name: 'subagent:coder', round: 1, seq: 1, status: 'running' },
- ];
- rerender(
- <Provider store={store}>
- <ToolTimelineBlock entries={afterSubagentB} turnActive />
- </Provider>
- );
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'closed');
-
- const bothSettled: ToolTimelineEntry[] = [
- { id: 'a', name: 'subagent:researcher', round: 1, seq: 0, status: 'success' },
- { id: 'b', name: 'subagent:coder', round: 1, seq: 1, status: 'success' },
- ];
- rerender(
- <Provider store={store}>
- <ToolTimelineBlock entries={bothSettled} turnActive />
- </Provider>
- );
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'closed');
-
- // The turn ends — override resets; auto rule (settled, not running)
- // keeps it collapsed, same outcome but for the right reason now.
- rerender(
- <Provider store={store}>
- <ToolTimelineBlock entries={bothSettled} turnActive={false} />
- </Provider>
- );
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'closed');
-
- // Both sides of that transition read "collapsed", which a STALE `false`
- // override would also produce — prove the override actually reset (not
- // just that it happened to still agree with the auto rule) by starting
- // a brand-new turn: the auto rule alone (isRunning) should now govern,
- // reopening the panel with no further user interaction.
- const newTurnRunning: ToolTimelineEntry[] = [
- { id: 'c', name: 'subagent:researcher', round: 2, seq: 0, status: 'running' },
- ];
- rerender(
- <Provider store={store}>
- <ToolTimelineBlock entries={newTurnRunning} turnActive />
- </Provider>
- );
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'open');
- });
- });
-
- it('renders the tool result output inside the expanded row', () => {
- const entries: ToolTimelineEntry[] = [
- {
- id: 'd',
- name: 'web_search',
- round: 1,
- seq: 0,
- status: 'success',
- argsBuffer: '{"query":"f1"}',
- result: 'Top result: https://openhuman.dev',
- },
- ];
- renderInStore(<ToolTimelineBlock entries={entries} expandAllRows />);
- const output = screen.getByTestId('tool-result-output');
- expect(output.textContent).toContain('Top result: https://openhuman.dev');
- });
-
- it('makes a row expandable on a result alone and omits the block without one', () => {
- const entries: ToolTimelineEntry[] = [
- // No argsBuffer / detail / subagent — the result is the only body.
- { id: 'a', name: 'run_code', round: 1, seq: 0, status: 'success', result: 'exit 0' },
- { id: 'b', name: 'run_code', round: 2, seq: 0, status: 'success' },
- ];
- renderInStore(<ToolTimelineBlock entries={entries} expandAllRows />);
- const outputs = screen.getAllByTestId('tool-result-output');
- expect(outputs).toHaveLength(1);
- expect(outputs[0].textContent).toBe('exit 0');
- });
-
- it('renders the parent live response inside the panel under a Response heading', () => {
- const entries: ToolTimelineEntry[] = [
- {
- id: 'r',
- name: 'web_search',
- round: 1,
- seq: 0,
- status: 'running',
- argsBuffer: '{"query":"f1"}',
- },
- ];
- renderInStore(
- <ToolTimelineBlock
- entries={entries}
- liveResponse="Let me check your Notion for that audit file."
- />
- );
- const resp = screen.getByTestId('agent-live-response');
- expect(resp.textContent).toContain('Response');
- expect(resp.textContent).toContain('Let me check your Notion for that audit file.');
- });
-
- it('omits the Response block when there is no live response', () => {
- const entries: ToolTimelineEntry[] = [
- { id: 'r', name: 'web_search', round: 1, seq: 0, status: 'running' },
- ];
- renderInStore(<ToolTimelineBlock entries={entries} />);
- expect(screen.queryByTestId('agent-live-response')).toBeNull();
- });
-
- it('strips a leaked <tool_call> envelope from the live response', () => {
- const entries: ToolTimelineEntry[] = [
- { id: 'r', name: 'web_search', round: 1, seq: 0, status: 'running' },
- ];
- renderInStore(
- <ToolTimelineBlock
- entries={entries}
- liveResponse={'Searching now. <tool_call> {"name":"X"} </tool_call>'}
- />
- );
- const resp = screen.getByTestId('agent-live-response');
- expect(resp.textContent).toContain('Searching now.');
- expect(resp.textContent).not.toContain('tool_call');
- });
-});
-
-describe('ToolTimelineBlock — coalescing repeated rows', () => {
- it('collapses consecutive identical body-less rows into one ×N row', () => {
- // A retry loop that spawns the same integrations step five times, each
- // surfacing the generic "Checking your connected app" label with no
- // distinguishing detail/result/subagent.
- const entries: ToolTimelineEntry[] = Array.from({ length: 5 }, (_, i) => ({
- id: `dup-${i}`,
- name: 'integrations_agent',
- round: 1,
- seq: 0,
- status: 'success' as const,
- }));
- renderInStore(<ToolTimelineBlock entries={entries} />);
- // Five entries render as a single rail row carrying an ×5 badge.
- expect(screen.getAllByTestId('agent-timeline-row')).toHaveLength(1);
- expect(screen.getByTestId('timeline-repeat-count').textContent).toBe('×5');
- });
-
- it('does not merge across differing status or the live running row', () => {
- const entries: ToolTimelineEntry[] = [
- { id: 'a', name: 'integrations_agent', round: 1, seq: 0, status: 'success' },
- { id: 'b', name: 'integrations_agent', round: 1, seq: 0, status: 'success' },
- // Different status breaks the run.
- { id: 'c', name: 'integrations_agent', round: 1, seq: 0, status: 'error' },
- // The live running row is never folded away.
- { id: 'd', name: 'integrations_agent', round: 1, seq: 0, status: 'running' },
- ];
- renderInStore(<ToolTimelineBlock entries={entries} />);
- // success×2 (merged) + error (single) + running (single) = 3 rows.
- expect(screen.getAllByTestId('agent-timeline-row')).toHaveLength(3);
- const counts = screen.getAllByTestId('timeline-repeat-count');
- expect(counts).toHaveLength(1);
- expect(counts[0].textContent).toBe('×2');
- });
-
- it('never merges rows that carry a unique result body', () => {
- const entries: ToolTimelineEntry[] = [
- { id: 'a', name: 'run_code', round: 1, seq: 0, status: 'success', result: 'exit 0' },
- { id: 'b', name: 'run_code', round: 1, seq: 0, status: 'success', result: 'exit 1' },
- ];
- renderInStore(<ToolTimelineBlock entries={entries} expandAllRows />);
- // Both keep their own row — distinct results are never coalesced.
- expect(screen.getAllByTestId('agent-timeline-row')).toHaveLength(2);
- expect(screen.queryByTestId('timeline-repeat-count')).toBeNull();
- });
-});
-
-describe('ToolTimelineBlock — subagent rendering', () => {
- it('shows child tool calls after the collapsed subagent row is opened', () => {
- const entry: ToolTimelineEntry = {
- id: 'tid:subagent:sub-1:researcher',
- name: 'subagent:researcher',
- round: 1,
- seq: 0,
- status: 'running',
- subagent: {
- taskId: 'sub-1',
- agentId: 'researcher',
- mode: 'typed',
- childIteration: 1,
- childMaxIterations: 5,
- toolCalls: [{ callId: 'cc-1', toolName: 'web_search', status: 'running', iteration: 1 }],
- },
- };
- renderInStore(<ToolTimelineBlock entries={[entry]} />);
-
- const subagent = screen.getByTestId('assistant-ui-subagent-call');
- const trigger = within(subagent).getByRole('button');
- expect(trigger).toHaveAttribute('aria-expanded', 'false');
- fireEvent.click(trigger);
- const calls = screen.getAllByTestId('assistant-ui-tool-call');
- expect(calls).toHaveLength(1);
- expect(calls[0].textContent).toContain('Searching the web');
- expect(screen.getByTestId('subagent-activity').textContent).toContain('turn 1/5');
- });
-
- it('renders a non-subagent row without crashing when there is no detail', () => {
- const entry: ToolTimelineEntry = {
- id: 'plain',
- name: 'list_threads',
- round: 0,
- seq: 0,
- status: 'success',
- };
- renderInStore(<ToolTimelineBlock entries={[entry]} />);
- // Plain rows with no detail collapse to a flat label + status pill.
- expect(screen.queryByTestId('subagent-activity')).toBeNull();
- });
-});
-
-// Issue #1624: when a parent timeline entry contains a worker_thread_ref
-// envelope, ToolTimelineBlock must propagate the entry's status to the
-// rendered WorkerThreadRefCard so the card's badge stays in lockstep
-// with the surrounding `<details>` status pill — both are mutated by
-// the same subagent_spawned / subagent_completed / subagent_failed
-// socket events.
-describe('ToolTimelineBlock — worker thread ref status propagation', () => {
- const WORKER_REF_DETAIL = `summary text\n[worker_thread_ref]\n${JSON.stringify({
- thread_id: 't-worker-1',
- label: 'researcher',
- agent_id: 'researcher',
- task_id: 'task-42',
- })}\n[/worker_thread_ref]`;
-
- function entryWithStatus(status: ToolTimelineEntry['status']): ToolTimelineEntry {
- return {
- id: `tid:subagent:task-42:researcher:${status}`,
- name: 'subagent:researcher',
- round: 1,
- seq: 0,
- status,
- detail: WORKER_REF_DETAIL,
- };
- }
-
- it('passes `running` to the card when the parent entry is in flight', () => {
- renderInStore(<ToolTimelineBlock entries={[entryWithStatus('running')]} />);
- const badge = screen.getByTestId('worker-thread-status-badge');
- expect(badge.getAttribute('data-status')).toBe('running');
- });
-
- it('passes `completed` to the card when the parent entry succeeds', () => {
- renderInStore(<ToolTimelineBlock entries={[entryWithStatus('success')]} />);
- const badge = screen.getByTestId('worker-thread-status-badge');
- expect(badge.getAttribute('data-status')).toBe('completed');
- });
-
- it('passes `failed` to the card when the parent entry errors', () => {
- renderInStore(<ToolTimelineBlock entries={[entryWithStatus('error')]} />);
- const badge = screen.getByTestId('worker-thread-status-badge');
- expect(badge.getAttribute('data-status')).toBe('failed');
- });
-
- // Defensive fallback: if the entry arrives with an unrecognised status
- // (e.g. the union grows in the future, or a malformed payload slips
- // through), the card is rendered as label-only so it can never display a
- // misleading lifecycle state. The status badge must be absent in that case.
- it('omits the status badge when the parent entry has an unknown status', () => {
- const malformed = {
- ...entryWithStatus('success'),
- status: 'queued' as unknown as ToolTimelineEntry['status'],
- };
- renderInStore(<ToolTimelineBlock entries={[malformed]} />);
- expect(screen.queryByTestId('worker-thread-status-badge')).toBeNull();
- });
-});
-
-describe('ToolTimelineBlock — compact chat mode (onViewDetails)', () => {
- const entries: ToolTimelineEntry[] = [
- // A finished step.
- {
- id: 'tl-1',
- name: 'agent_prepare_context',
- round: 1,
- seq: 0,
- status: 'success',
- detail: 'fetch X',
- result: 'Prepared context from 3 sources.',
- },
- // The currently-running sub-agent (latest running).
- {
- id: 'sa-1',
- name: 'subagent:researcher',
- round: 1,
- seq: 0,
- status: 'running',
- subagent: {
- taskId: 'task-1',
- agentId: 'researcher',
- toolCalls: [],
- transcript: [{ kind: 'thinking', iteration: 1, text: 'pondering' }],
- },
- },
- ];
-
- it('collapses finished steps to a link and keeps the running delegation card inline', () => {
- const onViewDetails = vi.fn();
- renderInStore(<ToolTimelineBlock entries={entries} onViewDetails={onViewDetails} />);
-
- // Only the finished step collapses to a "View details →" link.
- const links = screen.getAllByTestId('view-details');
- expect(links).toHaveLength(1);
-
- // The running delegation remains inline but its assistant-ui disclosure is
- // collapsed by default like every other delegation card.
- const subagent = screen.getByTestId('assistant-ui-subagent-call');
- const trigger = within(subagent).getByRole('button');
- expect(trigger).toHaveAttribute('aria-expanded', 'false');
- fireEvent.click(trigger);
- const activity = screen.getByTestId('subagent-activity');
- expect(activity.textContent).toContain('pondering');
- // The finished step SUCCEEDED, so its raw output is no longer duplicated
- // inline — the final answer already compresses it, and it stays reachable
- // through this row's "→". (Previously asserted present; see the
- // failure-only rule in the compact branch of ToolTimelineBlock.)
- expect(screen.queryByTestId('tool-result-output')).toBeNull();
-
- // Clicking the finished step's link opens the full-run panel.
- fireEvent.click(links[0]);
- expect(onViewDetails).toHaveBeenCalledTimes(1);
- });
-
- it('collapses an already-finished sub-agent (no longer running) to a "View details" link', () => {
- const onViewDetails = vi.fn();
- renderInStore(
- <ToolTimelineBlock
- entries={[
- {
- id: 'sa-done',
- name: 'subagent:researcher',
- round: 1,
- seq: 0,
- status: 'success',
- subagent: {
- taskId: 'task-2',
- agentId: 'researcher',
- toolCalls: [],
- transcript: [{ kind: 'thinking', iteration: 1, text: 'done thinking' }],
- },
- },
- ]}
- onViewDetails={onViewDetails}
- />
- );
- // No running step → the finished sub-agent collapses (no inline activity).
- expect(screen.getByTestId('view-details')).toBeInTheDocument();
- expect(screen.queryByTestId('subagent-activity')).toBeNull();
- });
-
- it('still expands inline (no compact link) when onViewDetails is omitted (panel mode)', () => {
- renderInStore(<ToolTimelineBlock entries={entries} expandAllRows />);
- const subagent = screen.getByTestId('assistant-ui-subagent-call');
- fireEvent.click(within(subagent).getByRole('button'));
- // Panel path uses the same delegation card, with no compact details link.
- expect(screen.getByTestId('subagent-activity')).toBeInTheDocument();
- expect(screen.queryByTestId('view-details')).toBeNull();
- });
-});
-
-// The in-flight viewport: while a turn is active the row list is windowed to
-// a fixed height and auto-follows the newest activity, so a long run can't
-// grow without bound and shove the composer around mid-turn. Settled turns
-// keep their previous full-height behaviour.
-describe('ToolTimelineBlock — in-flight viewport windowing', () => {
- const runningEntries: ToolTimelineEntry[] = [
- { id: 'w-1', name: 'read_file', round: 1, seq: 0, status: 'success', detail: 'a.ts' },
- { id: 'w-2', name: 'code_executor', round: 1, seq: 1, status: 'running', detail: 'run' },
- ];
-
- it('windows the row list while the turn is active', () => {
- renderInStore(<ToolTimelineBlock entries={runningEntries} turnActive />);
- const viewport = screen.getByTestId('tool-timeline-viewport');
- expect(viewport.getAttribute('data-windowed')).toBe('true');
- expect(viewport.className).toContain('overflow-y-auto');
- });
-
- it('does not window once the turn has settled', () => {
- renderInStore(<ToolTimelineBlock entries={runningEntries} turnActive={false} />);
- const viewport = screen.getByTestId('tool-timeline-viewport');
- expect(viewport.getAttribute('data-windowed')).toBe('false');
- expect(viewport.className).not.toContain('overflow-y-auto');
- });
-
- // Callers with no turn lifecycle to hand (settled / past-turn renders) must
- // be completely unaffected — windowing is opt-in via `turnActive`.
- it('does not window when the caller passes no turnActive', () => {
- renderInStore(<ToolTimelineBlock entries={runningEntries} />);
- expect(screen.getByTestId('tool-timeline-viewport').getAttribute('data-windowed')).toBe(
- 'false'
- );
- });
-
- // The Agent Process Source panel wants the whole list, not a porthole.
- it('never windows under expandAllRows, even mid-turn', () => {
- renderInStore(<ToolTimelineBlock entries={runningEntries} turnActive expandAllRows />);
- expect(screen.getByTestId('tool-timeline-viewport').getAttribute('data-windowed')).toBe(
- 'false'
- );
- });
-
- // Scrolling up detaches the auto-follow so reading an earlier step isn't
- // interrupted; returning to the bottom re-attaches it.
- it('detaches and re-attaches tail-following as the user scrolls', () => {
- renderInStore(<ToolTimelineBlock entries={runningEntries} turnActive />);
- const viewport = screen.getByTestId('tool-timeline-viewport');
- // jsdom reports 0 for all layout metrics, so drive them explicitly.
- Object.defineProperty(viewport, 'scrollHeight', { value: 500, configurable: true });
- Object.defineProperty(viewport, 'clientHeight', { value: 100, configurable: true });
-
- viewport.scrollTop = 0; // scrolled to the top — detached
- expect(() => fireEvent.scroll(viewport)).not.toThrow();
-
- viewport.scrollTop = 400; // back at the bottom — re-attached
- expect(() => fireEvent.scroll(viewport)).not.toThrow();
- });
-
- // The row list must not remount when a turn settles, or every <details>
- // the user opened mid-turn would snap shut.
- it('keeps the row list mounted across the settle transition', () => {
- const { rerender } = renderInStore(<ToolTimelineBlock entries={runningEntries} turnActive />);
- const before = screen.getByTestId('tool-timeline-viewport').firstElementChild;
- rerender(
- <Provider store={store}>
- <ToolTimelineBlock entries={runningEntries} turnActive={false} />
- </Provider>
- );
- const after = screen.getByTestId('tool-timeline-viewport').firstElementChild;
- expect(after).toBe(before);
- });
-});
-
-// Regression: the group used to auto-collapse in the GAP BETWEEN tools —
-// `autoOpen` keyed off `isRunning` ("a tool is executing right now"), which
-// goes false while the agent reasons about a result before issuing the next
-// call. A just-delivered tool result appeared to be wiped a beat later, and a
-// multi-tool turn flickered open/closed. The whole-turn signal (`turnActive`)
-// now drives it, so the group collapses exactly once, at settle.
-describe('ToolTimelineBlock — stays open between tools within a turn', () => {
- const settledRows: ToolTimelineEntry[] = [
- { id: 'g-1', name: 'read_file', round: 1, seq: 0, status: 'success', detail: 'a.ts' },
- {
- id: 'g-2',
- name: 'code_executor',
- round: 1,
- seq: 1,
- status: 'success',
- detail: 'run',
- result: 'exit 0',
- },
- ];
-
- it('stays open between tool calls while the turn is still active', () => {
- // No entry is `running` — the agent is reasoning before its next call.
- renderInStore(<ToolTimelineBlock entries={settledRows} turnActive />);
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'open');
- });
-
- it('collapses once the turn itself settles', () => {
- renderInStore(<ToolTimelineBlock entries={settledRows} turnActive={false} />);
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'closed');
- });
-
- // Callers with no turn lifecycle fall back to `isRunning`, unchanged.
- it('falls back to isRunning when the caller passes no turnActive', () => {
- const running: ToolTimelineEntry[] = [
- { id: 'g-3', name: 'code_executor', round: 1, seq: 0, status: 'running' },
- ];
- renderInStore(<ToolTimelineBlock entries={running} />);
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'open');
- renderInStore(<ToolTimelineBlock entries={settledRows} />);
- expect(screen.getAllByTestId('agent-task-insights')[1]).toHaveAttribute('data-state', 'closed');
- });
-
- // The rows were never deleted — the group was merely shut. Prove the content
- // is still mounted so "wiped" can be ruled out for good.
- it('keeps the rows mounted even while collapsed', () => {
- renderInStore(<ToolTimelineBlock entries={settledRows} turnActive={false} />);
- const group = screen.getByTestId('agent-task-insights');
- expect(group).toHaveAttribute('data-state', 'closed');
- expect(within(group).getByTestId('tool-timeline-viewport')).toBeInTheDocument();
- });
-});
-
-// The settled-turn contract: once the final result has landed the timeline
-// folds itself away so a long run never dominates the conversation, but the
-// escape hatch stays reachable — "View full agent process Source →" lives in
-// the always-visible <summary>, not in the collapsed body. Collapsing is only
-// acceptable BECAUSE that link survives, so both halves are asserted together.
-describe('ToolTimelineBlock — settled turn keeps the process-source escape hatch', () => {
- const settled: ToolTimelineEntry[] = [
- { id: 's-1', name: 'read_file', round: 1, seq: 0, status: 'success', detail: 'a.ts' },
- { id: 's-2', name: 'code_executor', round: 1, seq: 1, status: 'success', result: 'exit 0' },
- ];
-
- it('collapses after the final result but still exposes the process-source link', () => {
- const onViewWholeRun = vi.fn();
- renderInStore(
- <ToolTimelineBlock entries={settled} turnActive={false} onViewWholeRun={onViewWholeRun} />
- );
-
- const group = screen.getByTestId('agent-task-insights');
- expect(group).toHaveAttribute('data-state', 'closed');
-
- // Link is in the <summary>, so it is reachable while collapsed.
- const link = screen.getByTestId('view-process-source');
- expect(link).toBeInTheDocument();
-
- // Clicking it opens the full-run panel and must NOT toggle the disclosure
- // (the handler stops propagation to the summary's own click).
- fireEvent.click(link);
- expect(onViewWholeRun).toHaveBeenCalledTimes(1);
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'closed');
- });
-
- it('still exposes the link while the turn is in flight', () => {
- const onViewWholeRun = vi.fn();
- renderInStore(
- <ToolTimelineBlock entries={settled} turnActive onViewWholeRun={onViewWholeRun} />
- );
- expect(screen.getByTestId('agent-task-insights')).toHaveAttribute('data-state', 'open');
- expect(screen.getByTestId('view-process-source')).toBeInTheDocument();
- });
-});
-
-// Compact chat rows show raw tool output for FAILED steps only. A successful
-// step's output is already compressed into the agent's final answer, so
-// repeating it inline duplicated the answer and stacked one scrollable <pre>
-// per tool above it. A failure is where the answer is least trustworthy (it may
-// not mention the failure at all), so that evidence stays inline.
-describe('ToolTimelineBlock — compact rows show output only on failure', () => {
- const succeeded: ToolTimelineEntry = {
- id: 'r-ok',
- name: 'code_executor',
- round: 1,
- seq: 0,
- status: 'success',
- result: 'exit 0 — 42 passed',
- };
- const failed: ToolTimelineEntry = {
- id: 'r-err',
- name: 'code_executor',
- round: 1,
- seq: 1,
- status: 'error',
- result: 'exit 1 — 3 failed',
- };
-
- it('omits the output blob for a successful compact row', () => {
- renderInStore(<ToolTimelineBlock entries={[succeeded]} onViewDetails={vi.fn()} />);
- // Still collapsed to its link — the output is reachable, just not inline.
- expect(screen.getByTestId('view-details')).toBeInTheDocument();
- expect(screen.queryByTestId('tool-result-output')).toBeNull();
- });
-
- it('keeps the output blob for a failed compact row', () => {
- renderInStore(<ToolTimelineBlock entries={[failed]} onViewDetails={vi.fn()} />);
- expect(screen.getByTestId('tool-result-output').textContent).toContain('exit 1 — 3 failed');
- });
-
- it('shows only the failure when a turn mixes successful and failed steps', () => {
- renderInStore(<ToolTimelineBlock entries={[succeeded, failed]} onViewDetails={vi.fn()} />);
- const outputs = screen.getAllByTestId('tool-result-output');
- expect(outputs).toHaveLength(1);
- expect(outputs[0].textContent).toContain('exit 1 — 3 failed');
- });
-
- // The panel/expanded path is the full record and must be unaffected — a
- // successful result is still shown there.
- it('still shows successful output in the expanded/panel path', () => {
- renderInStore(<ToolTimelineBlock entries={[succeeded]} expandAllRows />);
- expect(screen.getByTestId('tool-result-output').textContent).toContain('exit 0 — 42 passed');
- });
-});
-
-// The rail renders the turn's interleaved processing transcript — narration,
-// reasoning and tool steps in stream order — through the SAME
-// `ProcessingTranscriptView` the Agent Process Source panel uses, so the rail
-// is a windowed view of the panel rather than a second, divergent rendering.
-// Narration no longer lives in the chat stream and reasoning no longer has its
-// own bubble; both surface here.
-describe('ToolTimelineBlock — renders the processing transcript inline', () => {
- const entries: ToolTimelineEntry[] = [
- { id: 'tx-1', name: 'web_fetch', round: 1, seq: 0, status: 'success', detail: 'example.com' },
- ];
-
- it('renders narration and tool steps from the transcript', () => {
- renderInStore(
- <ToolTimelineBlock
- entries={entries}
- turnActive
- transcript={[
- { kind: 'narration', round: 1, seq: 0, text: 'Let me get the data for both.' },
- { kind: 'toolCall', round: 1, seq: 1, callId: 'tx-1' },
- ]}
- />
- );
- const view = screen.getByTestId('processing-transcript');
- expect(view).toBeInTheDocument();
- expect(screen.getByTestId('processing-narration').textContent).toContain(
- 'Let me get the data for both.'
- );
- });
-
- it('keeps the transcript inside the windowed viewport during a turn', () => {
- renderInStore(
- <ToolTimelineBlock
- entries={entries}
- turnActive
- transcript={[{ kind: 'narration', round: 1, seq: 0, text: 'Working…' }]}
- />
- );
- const viewport = screen.getByTestId('tool-timeline-viewport');
- expect(viewport.getAttribute('data-windowed')).toBe('true');
- expect(within(viewport).getByTestId('processing-transcript')).toBeInTheDocument();
- });
-
- // Legacy snapshots predate the transcript — those turns must still render.
- it('falls back to the tool-row list when no transcript is present', () => {
- renderInStore(<ToolTimelineBlock entries={entries} turnActive />);
- expect(screen.queryByTestId('processing-transcript')).toBeNull();
- expect(screen.getByTestId('agent-task-insights')).toBeInTheDocument();
- });
-
- it('falls back when the transcript is present but empty', () => {
- renderInStore(<ToolTimelineBlock entries={entries} turnActive transcript={[]} />);
- expect(screen.queryByTestId('processing-transcript')).toBeNull();
- });
-});
-
-// Regression: swapping the rail's body to `ProcessingTranscriptView` dropped
-// nested sub-agent activity, because its `ToolRow` renders only title/detail/
-// failure and never reads `entry.subagent`. A delegated run collapsed to one
-// line and every child tool call it made became invisible — visible as the
-// process-source panel (which fell back to the row list) showing more tool
-// calls than the inline rail. `renderSubagent` injects the block back in;
-// injected rather than imported because ToolTimelineBlock already imports
-// ProcessingTranscriptView, so importing back would be a cycle.
-describe('ToolTimelineBlock — sub-agent activity survives the transcript path', () => {
- const subagentEntry: ToolTimelineEntry = {
- id: 'sa-tx',
- name: 'subagent:researcher',
- round: 1,
- seq: 0,
- status: 'running',
- subagent: {
- taskId: 'task-9',
- agentId: 'researcher',
- toolCalls: [
- { callId: 'c1', toolName: 'web_search', status: 'success', elapsedMs: 120 },
- { callId: 'c2', toolName: 'web_fetch', status: 'running' },
- ],
- },
- };
-
- it('renders the sub-agent child tool calls inside the transcript rail', () => {
- renderInStore(
- <ToolTimelineBlock
- entries={[subagentEntry]}
- turnActive
- transcript={[{ kind: 'toolCall', round: 1, seq: 0, callId: 'sa-tx' }]}
- />
- );
- // Rendering through the transcript path…
- expect(screen.getByTestId('processing-transcript')).toBeInTheDocument();
- // …and the nested child run is present, not collapsed to one line.
- expect(screen.getByTestId('processing-subagent')).toBeInTheDocument();
- const subagent = screen.getByTestId('assistant-ui-subagent-call');
- fireEvent.click(within(subagent).getByRole('button'));
- const calls = screen.getAllByTestId('assistant-ui-tool-call');
- expect(calls).toHaveLength(2);
- expect(calls[0].textContent).toContain('Searched the web');
- expect(calls[0].textContent?.toLowerCase()).toContain('done');
- // Human label, not the raw `web_fetch` slug.
- expect(calls[1].textContent).toContain('Reading webpage');
- expect(calls[1].textContent?.toLowerCase()).toContain('running');
- });
-
- it('still renders child tool calls on the legacy row path (no transcript)', () => {
- renderInStore(<ToolTimelineBlock entries={[subagentEntry]} turnActive />);
- expect(screen.queryByTestId('processing-transcript')).toBeNull();
- const subagent = screen.getByTestId('assistant-ui-subagent-call');
- fireEvent.click(within(subagent).getByRole('button'));
- expect(screen.getAllByTestId('assistant-ui-tool-call')).toHaveLength(2);
- });
-
- // The nested child run must live INSIDE the windowed viewport, and must not
- // introduce a scroll container of its own. A nested scroller would clamp its
- // own height, so a streaming child run would stop changing the outer content
- // height — the ResizeObserver would never fire and auto-follow would silently
- // stall mid-subagent, with the window pinned to stale content.
- it('nests the sub-agent inside the sliding window with no scroller of its own', () => {
- renderInStore(
- <ToolTimelineBlock
- entries={[subagentEntry]}
- turnActive
- transcript={[{ kind: 'toolCall', round: 1, seq: 0, callId: 'sa-tx' }]}
- />
- );
- const viewport = screen.getByTestId('tool-timeline-viewport');
- expect(viewport.getAttribute('data-windowed')).toBe('true');
-
- const subagent = within(viewport).getByTestId('processing-subagent');
- expect(subagent).toBeInTheDocument();
-
- // Walk from the sub-agent up to the viewport: nothing between them may
- // scroll, or the outer window stops seeing the child run grow.
- for (let node = subagent; node && node !== viewport; node = node.parentElement!) {
- expect(node.className).not.toMatch(/overflow-(y-)?auto|overflow-(y-)?scroll/);
- }
- });
-});
-
-// Auto-follow: the window pins to the newest activity as the turn streams.
-// jsdom ships no ResizeObserver, so the effect early-returns and this behaviour
-// is invisible to every other test in this file — stub one and drive it
-// directly, otherwise the single most user-visible property of the windowed
-// rail has no coverage at all.
-describe('ToolTimelineBlock — auto-follows the live edge', () => {
- const entries: ToolTimelineEntry[] = [
- { id: 'af-1', name: 'web_fetch', round: 1, seq: 0, status: 'running', detail: 'example.com' },
- ];
- const transcript = [
- { kind: 'narration' as const, round: 1, seq: 0, text: 'Let me get the data.' },
- { kind: 'toolCall' as const, round: 1, seq: 1, callId: 'af-1' },
- ];
-
- /** Installs a fake ResizeObserver and returns a trigger for its callback. */
- function stubResizeObserver() {
- const callbacks: Array<() => void> = [];
- class FakeResizeObserver {
- constructor(cb: () => void) {
- callbacks.push(cb);
- }
- observe() {}
- disconnect() {}
- unobserve() {}
- }
- (globalThis as unknown as { ResizeObserver: unknown }).ResizeObserver = FakeResizeObserver;
- return {
- fire: () => callbacks.forEach(cb => cb()),
- restore: () => {
- delete (globalThis as unknown as { ResizeObserver?: unknown }).ResizeObserver;
- },
- };
- }
-
- /** jsdom reports 0 for all layout metrics — drive them explicitly. */
- function sizeViewport(el: HTMLElement, { scrollHeight = 600, clientHeight = 200 } = {}) {
- Object.defineProperty(el, 'scrollHeight', { value: scrollHeight, configurable: true });
- Object.defineProperty(el, 'clientHeight', { value: clientHeight, configurable: true });
- }
-
- it('scrolls to the newest content when the transcript grows', () => {
- const ro = stubResizeObserver();
- try {
- renderInStore(<ToolTimelineBlock entries={entries} turnActive transcript={transcript} />);
- const viewport = screen.getByTestId('tool-timeline-viewport');
- sizeViewport(viewport);
- viewport.scrollTop = 0;
-
- ro.fire();
-
- // Pinned to the live edge.
- expect(viewport.scrollTop).toBe(600);
- } finally {
- ro.restore();
- }
- });
-
- it('stops following once the user scrolls away from the bottom', () => {
- const ro = stubResizeObserver();
- try {
- renderInStore(<ToolTimelineBlock entries={entries} turnActive transcript={transcript} />);
- const viewport = screen.getByTestId('tool-timeline-viewport');
- sizeViewport(viewport);
-
- // User scrolls up to read an earlier step (well outside the 24px slack).
- viewport.scrollTop = 100;
- fireEvent.scroll(viewport);
-
- ro.fire();
-
- // Left where the user put it — not yanked back down.
- expect(viewport.scrollTop).toBe(100);
- } finally {
- ro.restore();
- }
- });
-
- it('resumes following when the user scrolls back to the bottom', () => {
- const ro = stubResizeObserver();
- try {
- renderInStore(<ToolTimelineBlock entries={entries} turnActive transcript={transcript} />);
- const viewport = screen.getByTestId('tool-timeline-viewport');
- sizeViewport(viewport);
-
- viewport.scrollTop = 100; // detach
- fireEvent.scroll(viewport);
- viewport.scrollTop = 400; // back at the bottom (600 - 200 = 400)
- fireEvent.scroll(viewport);
-
- ro.fire();
-
- expect(viewport.scrollTop).toBe(600);
- } finally {
- ro.restore();
- }
- });
-
- it('does not follow when the turn has settled (not windowed)', () => {
- const ro = stubResizeObserver();
- try {
- renderInStore(
- <ToolTimelineBlock entries={entries} turnActive={false} transcript={transcript} />
- );
- const viewport = screen.getByTestId('tool-timeline-viewport');
- sizeViewport(viewport);
- viewport.scrollTop = 0;
-
- ro.fire();
-
- expect(viewport.scrollTop).toBe(0);
- } finally {
- ro.restore();
- }
- });
-});
-
-// Regression: auto-follow silently never armed in a real turn.
-//
-// The observer used to attach in `useEffect(..., [windowed])`. `windowed` flips
-// true at the START of a turn — when there is no content yet, so the component
-// returned null, the ref was null, and the effect bailed. Content arriving
-// afterwards re-rendered the viewport but did not change `windowed`, so the
-// effect never re-ran and no observer was ever created. Every earlier test
-// passed because it rendered with content already present at mount, which is
-// precisely the case that never happens live.
-describe('ToolTimelineBlock — auto-follow arms when content arrives after mount', () => {
- function stubResizeObserver() {
- const callbacks: Array<() => void> = [];
- class FakeResizeObserver {
- constructor(cb: () => void) {
- callbacks.push(cb);
- }
- observe() {}
- disconnect() {}
- unobserve() {}
- }
- (globalThis as unknown as { ResizeObserver: unknown }).ResizeObserver = FakeResizeObserver;
- return {
- fire: () => callbacks.forEach(cb => cb()),
- count: () => callbacks.length,
- restore: () => {
- delete (globalThis as unknown as { ResizeObserver?: unknown }).ResizeObserver;
- },
- };
- }
-
- it('follows content that only appears on a later render', () => {
- const ro = stubResizeObserver();
- try {
- // Turn starts: windowed, but nothing to show yet → renders nothing.
- const { rerender } = renderInStore(
- <ToolTimelineBlock entries={[]} turnActive transcript={[]} />
- );
- expect(screen.queryByTestId('tool-timeline-viewport')).toBeNull();
- expect(ro.count()).toBe(0);
-
- // …then the first tool row lands.
- rerender(
- <Provider store={store}>
- <ToolTimelineBlock
- entries={[{ id: 'late-1', name: 'web_fetch', round: 1, seq: 0, status: 'running' }]}
- turnActive
- transcript={[]}
- />
- </Provider>
- );
-
- const viewport = screen.getByTestId('tool-timeline-viewport');
- Object.defineProperty(viewport, 'scrollHeight', { value: 500, configurable: true });
- Object.defineProperty(viewport, 'clientHeight', { value: 200, configurable: true });
- viewport.scrollTop = 0;
-
- // The observer must have been created for the node that appeared late.
- expect(ro.count()).toBeGreaterThan(0);
- ro.fire();
- expect(viewport.scrollTop).toBe(500);
- } finally {
- ro.restore();
- }
- });
-
- // Narration streams before the first tool call, so gating the render on
- // `entries` alone blanked the rail for the opening stretch of every turn and
- // hid tool-less turns entirely.
- it('renders on transcript alone, with no tool rows yet', () => {
- renderInStore(
- <ToolTimelineBlock
- entries={[]}
- turnActive
- transcript={[{ kind: 'narration', round: 1, seq: 0, text: 'Let me get the data.' }]}
- />
- );
- expect(screen.getByTestId('tool-timeline-viewport')).toBeInTheDocument();
- expect(screen.getByTestId('processing-narration').textContent).toContain(
- 'Let me get the data.'
- );
- });
-
- it('still renders nothing when there is neither a row nor transcript prose', () => {
- renderInStore(<ToolTimelineBlock entries={[]} turnActive transcript={[]} />);
- expect(screen.queryByTestId('agent-task-insights')).toBeNull();
- });
-});
diff --git a/app/src/features/conversations/components/aui/subagentDrawerHost.tsx b/app/src/features/conversations/components/aui/subagentDrawerHost.tsx
deleted file mode 100644
index b770195a18..0000000000
--- a/app/src/features/conversations/components/aui/subagentDrawerHost.tsx
+++ /dev/null
@@ -1,55 +0,0 @@
-import { createContext, type ReactNode, useContext, useMemo } from 'react';
-
-export interface SubagentDrawerHostValue {
- /** Opens the host's `SubagentDrawer` on a delegation, by spawn `taskId`. */
- open: (taskId: string) => void;
- /**
- * Whether the drawer can actually show that delegation.
- *
- * The host resolves a `taskId` against the thread's live tool timeline and
- * renders nothing when it is absent, so a delegation replayed from the
- * settled core transcript would otherwise get a button that opens an empty
- * sheet. Asking the host keeps that knowledge where it already lives, and
- * keeps this seam's consumers - which are tool parts, rendered by
- * assistant-ui in contexts that do not all have a Redux store - free of a
- * store subscription of their own.
- */
- canOpen: (taskId: string) => boolean;
-}
-
-/**
- * The host that owns the sub-agent drawer's disclosure state.
- *
- * A context rather than a prop because the consumer is a *tool part*: the
- * delegation card is rendered by assistant-ui from inside the transcript, many
- * layers below anything the host passes props to, while the drawer belongs to
- * `Conversations`. `null` outside a provider, which is what every read-only
- * mount of the card (the drawer itself, past-turn insights) wants: no host, no
- * "View full processing" affordance.
- */
-const SubagentDrawerHostContext = createContext<SubagentDrawerHostValue | null>(null);
-
-export function SubagentDrawerHost({
- onOpenSubagent,
- canOpenSubagent,
- children,
-}: {
- onOpenSubagent?: ((taskId: string) => void) | undefined;
- canOpenSubagent?: ((taskId: string) => boolean) | undefined;
- children: ReactNode;
-}) {
- const value = useMemo<SubagentDrawerHostValue | null>(
- () =>
- onOpenSubagent ? { open: onOpenSubagent, canOpen: canOpenSubagent ?? (() => true) } : null,
- [onOpenSubagent, canOpenSubagent]
- );
- return (
- <SubagentDrawerHostContext.Provider value={value}>
- {children}
- </SubagentDrawerHostContext.Provider>
- );
-}
-
-export function useSubagentDrawerHost(): SubagentDrawerHostValue | null {
- return useContext(SubagentDrawerHostContext);
-}
diff --git a/app/src/features/conversations/components/toolTimelineRows.tsx b/app/src/features/conversations/components/toolTimelineRows.tsx
deleted file mode 100644
index 69b6cc7a09..0000000000
--- a/app/src/features/conversations/components/toolTimelineRows.tsx
+++ /dev/null
@@ -1,99 +0,0 @@
-import Badge from '../../../components/ui/Badge';
-import type { ToolTimelineEntry } from '../../../store/chatRuntimeSlice';
-import { formatTimelineEntry } from '../../../utils/toolTimelineFormatting';
-import type { WorkerThreadStatus } from './WorkerThreadRefCard';
-
-/**
- * Map a parent timeline entry's status to the worker-thread lifecycle
- * phase rendered on `WorkerThreadRefCard`. The parent entry is what the
- * subagent_spawned / subagent_completed / subagent_failed socket events
- * mutate, so reading from it keeps the badge and the surrounding
- * disclosure's status pill in lockstep without a second source of truth.
- *
- * Returns `undefined` for the rare ambiguous case so the card stays
- * label-only rather than render a misleading state.
- */
-export function workerStatusFromEntry(
- status: ToolTimelineEntry['status']
-): WorkerThreadStatus | undefined {
- if (status === 'running') return 'running';
- if (status === 'success') return 'completed';
- if (status === 'error') return 'failed';
- return undefined;
-}
-
-/** Treat empty / structurally-empty tool bodies as absent. */
-export function normalizeToolBody(value?: string): string | undefined {
- if (!value) return undefined;
- const trimmed = value.trim();
- if (trimmed.length === 0) return undefined;
- if (trimmed === '{}' || trimmed === '[]' || trimmed === 'null') return undefined;
- return value;
-}
-
-/**
- * Whether a timeline entry carries any unique body worth its own row — a
- * sub-agent's live activity, a returned result, a prompt/detail bubble, or a
- * structured failure. A row with none of these renders as a bare label + status
- * and is therefore indistinguishable from any sibling with the same title, so it
- * is safe to coalesce (see {@link coalesceTimelineEntries}). Mirrors the
- * `expandable` predicate in the row renderer so the two never disagree.
- */
-export function entryHasUniqueBody(entry: ToolTimelineEntry): boolean {
- const formatted = formatTimelineEntry(entry);
- const detailContent = normalizeToolBody(formatted.detail) ?? normalizeToolBody(entry.argsBuffer);
- const resultContent = normalizeToolBody(entry.result);
- return (
- detailContent != null ||
- resultContent != null ||
- entry.subagent != null ||
- entry.failure != null
- );
-}
-
-/** A rendered timeline row: a representative entry plus how many identical,
- * body-less entries it stands in for (`count === 1` for an ordinary row). */
-export interface CoalescedRow {
- entry: ToolTimelineEntry;
- count: number;
-}
-
-/**
- * Collapse runs of consecutive, identical, body-less rows into a single row
- * carrying an `×N` count. A retry loop (e.g. the orchestrator re-spawning the
- * integrations agent 25×, each surfacing the same "Checking your connected app"
- * label with no distinguishing detail) would otherwise flood the timeline with
- * indistinguishable nodes. Only truly interchangeable rows merge: same title,
- * same status, no unique body (result/detail/sub-agent/failure), and never the
- * live `running` row — so no information is lost, only duplication.
- */
-export function coalesceTimelineEntries(entries: ToolTimelineEntry[]): CoalescedRow[] {
- const rows: CoalescedRow[] = [];
- for (const entry of entries) {
- const mergeable = entry.status !== 'running' && !entryHasUniqueBody(entry);
- const previous = rows[rows.length - 1];
- if (
- mergeable &&
- previous != null &&
- previous.entry.status === entry.status &&
- !entryHasUniqueBody(previous.entry) &&
- previous.entry.status !== 'running' &&
- formatTimelineEntry(previous.entry).title === formatTimelineEntry(entry).title
- ) {
- previous.count += 1;
- continue;
- }
- rows.push({ entry, count: 1 });
- }
- return rows;
-}
-
-/** Compact "×N" badge appended to a coalesced row's label. */
-export function RepeatCount({ count }: { count: number }) {
- if (count <= 1) return null;
- return (
- <Badge className="shrink-0 rounded-full text-[10px]" data-testid="timeline-repeat-count">
- ×{count}
- </Badge>
- );
-}