Skip to content

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

fix(conversations): restore missing turn content after streaming

Steven Enamakelfdf90c241d2a
diff --git a/app/src/features/conversations/components/ChatThreadView.assistantUiRuntime.test.tsx b/app/src/features/conversations/components/ChatThreadView.assistantUiRuntime.test.tsx
deleted file mode 100644
index a82d0f970d..0000000000
--- a/app/src/features/conversations/components/ChatThreadView.assistantUiRuntime.test.tsx
+++ /dev/null
@@ -1,187 +0,0 @@
-/**
- * Guards the assistant-ui adoption against the one regression that would make
- * it not worth having.
- *
- * `ChatThreadView.renderPerf.test.tsx` pins the transcript's render cost, but
- * it mounts the transcript under a bare Redux `Provider` — the assistant-ui
- * runtime is not in that tree, so it cannot see a cost the runtime introduces.
- * `App.tsx` mounts the runtime ABOVE every chat surface, and a runtime that
- * re-rendered or re-converted the transcript per streamed token would undo the
- * memoized-`TranscriptRow` optimisation without failing a single existing test.
- *
- * So this file re-states the same property with the runtime in place. The
- * bound and the instrument are deliberately the same ones the sibling
- * benchmark uses; only the tree differs. Measured at adoption time, the counts
- * are identical with and without the runtime mounted (0 unwraps per streamed
- * token, 0 settled-bubble re-renders).
- */
-import { combineReducers, configureStore } from '@reduxjs/toolkit';
-import { act, render } from '@testing-library/react';
-import { Provider } from 'react-redux';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { AssistantUiRuntimeProvider } from '../../../providers/AssistantUiRuntimeProvider';
-import chatRuntimeReducer, { streamDeltaReceived } from '../../../store/chatRuntimeSlice';
-import themeReducer from '../../../store/themeSlice';
-import threadReducer from '../../../store/threadSlice';
-import type { ThreadMessage } from '../../../types/thread';
-import { ChatThreadView } from './ChatThreadView';
-
-const unwrapSpy = vi.hoisted(() => vi.fn());
-const bubbleRenderSpy = vi.hoisted(() => vi.fn<(content: string) => void>());
-
-vi.mock('../../../lib/chat/toolCallEnvelope', async orig => {
- const actual = await orig<typeof import('../../../lib/chat/toolCallEnvelope')>();
- return {
- ...actual,
- unwrapToolCallEnvelope: (raw: string) => {
- unwrapSpy(raw);
- return actual.unwrapToolCallEnvelope(raw);
- },
- };
-});
-
-// Pass-through, deliberately unmemoized: the contract is that the PARENT stops
-// re-rendering settled rows, so the instrument must not supply memoization.
-vi.mock('./AgentMessageBubble', async orig => {
- const actual = await orig<typeof import('./AgentMessageBubble')>();
- return {
- ...actual,
- AgentMessageText: (props: Parameters<typeof actual.AgentMessageText>[0]) => {
- bubbleRenderSpy(props.content);
- return actual.AgentMessageText(props);
- },
- AgentMessageBubble: (props: Parameters<typeof actual.AgentMessageBubble>[0]) => {
- bubbleRenderSpy(props.content);
- return actual.AgentMessageBubble(props);
- },
- };
-});
-
-vi.mock('../../../hooks/useStickToBottom', () => ({
- useStickToBottom: vi.fn(() => ({ containerRef: { current: null }, endRef: { current: null } })),
-}));
-
-const THREAD_ID = 't-aui-perf';
-const MESSAGE_COUNT = 40;
-const MAX_WORK_PER_TAIL_TOKEN = 4;
-
-function buildTranscript(): ThreadMessage[] {
- const messages: ThreadMessage[] = [];
- for (let i = 0; i < MESSAGE_COUNT - 1; i += 1) {
- const isAgent = i % 2 === 1;
- messages.push({
- id: `m-${i}`,
- sender: isAgent ? 'agent' : 'user',
- type: 'text',
- content: isAgent ? `Settled agent prose MARK${i}_ not JSON` : `User question ${i}?`,
- extraMetadata: {},
- createdAt: new Date(Date.UTC(2026, 0, 1, 0, i)).toISOString(),
- });
- }
- messages.push({
- id: 'm-tail',
- sender: 'agent',
- type: 'text',
- content: 'Starting the answer',
- extraMetadata: {},
- createdAt: new Date(Date.UTC(2026, 0, 1, 1, 0)).toISOString(),
- });
- return messages;
-}
-
-function buildStore() {
- return configureStore({
- reducer: combineReducers({
- thread: threadReducer,
- chatRuntime: chatRuntimeReducer,
- theme: themeReducer,
- }),
- preloadedState: {
- thread: {
- threads: [
- {
- id: THREAD_ID,
- title: 'Perf thread',
- chatId: null,
- isActive: true,
- messageCount: MESSAGE_COUNT,
- lastMessageAt: '2026-01-01T00:00:00.000Z',
- createdAt: '2026-01-01T00:00:00.000Z',
- labels: ['general'],
- },
- ],
- selectedThreadId: THREAD_ID,
- activeThreadIds: {},
- welcomeThreadId: null,
- messagesByThreadId: { [THREAD_ID]: buildTranscript() },
- messages: [],
- isLoadingThreads: false,
- isLoadingMessages: false,
- messagesError: null,
- },
- } as never,
- });
-}
-
-function renderUnderRuntime(store: ReturnType<typeof buildStore>) {
- return render(
- <Provider store={store}>
- <AssistantUiRuntimeProvider>
- <ChatThreadView threadId={THREAD_ID} />
- </AssistantUiRuntimeProvider>
- </Provider>
- );
-}
-
-function streamTokens(store: ReturnType<typeof buildStore>, count: number) {
- for (let i = 0; i < count; i += 1) {
- act(() => {
- store.dispatch(
- streamDeltaReceived({
- threadId: THREAD_ID,
- requestId: 'req-1',
- round: 0,
- delta: ` tok${i}`,
- channel: 'content',
- })
- );
- });
- }
-}
-
-describe('transcript render cost with the assistant-ui runtime mounted', () => {
- beforeEach(() => {
- unwrapSpy.mockClear();
- bubbleRenderSpy.mockClear();
- });
-
- it('does not re-unwrap the settled transcript on every streamed token', () => {
- const store = buildStore();
- renderUnderRuntime(store);
- expect(unwrapSpy.mock.calls.length).toBeGreaterThan(0);
- unwrapSpy.mockClear();
-
- const TOKENS = 5;
- streamTokens(store, TOKENS);
-
- expect(unwrapSpy.mock.calls.length).toBeLessThanOrEqual(MAX_WORK_PER_TAIL_TOKEN * TOKENS);
- });
-
- it('does not re-render a settled message bubble when only the tail changes', () => {
- const store = buildStore();
- renderUnderRuntime(store);
-
- const STABLE_MARKER = 'MARK1_';
- const rendersOfStable = () =>
- bubbleRenderSpy.mock.calls.filter(([c]) => c.includes(STABLE_MARKER)).length;
-
- // Guards the instrument: a vacuous pass would measure nothing.
- expect(rendersOfStable()).toBe(1);
- bubbleRenderSpy.mockClear();
-
- streamTokens(store, 5);
-
- expect(rendersOfStable()).toBe(0);
- });
-});
diff --git a/app/src/features/conversations/components/ChatThreadView.memoIdentity.test.tsx b/app/src/features/conversations/components/ChatThreadView.memoIdentity.test.tsx
deleted file mode 100644
index f68846bf72..0000000000
--- a/app/src/features/conversations/components/ChatThreadView.memoIdentity.test.tsx
+++ /dev/null
@@ -1,123 +0,0 @@
-/**
- * Identity-stability regression tests for the transcript's live tool-timeline
- * and processing-transcript fallbacks (#5162).
- *
- * `selectedThreadToolTimeline` / `selectedThreadProcessing` used to fall back to
- * a freshly-allocated `[]` on every render. That gave the value a new identity
- * each pass, so the `backgroundProcesses` `useMemo` keyed on it was invalidated
- * every render and `selectBackgroundProcesses` re-ran for no reason — avoidable
- * churn on the chat's hot path, and the same identity mistake that fed the
- * render loop this change set fixes. Both now fall back to module-level
- * `EMPTY_*` constants, matching the convention the surrounding code already
- * used for the past-turn maps.
- *
- * The contract is "the memo is not invalidated by a re-render", so these tests
- * count `selectBackgroundProcesses` invocations across re-renders. The mock
- * delegates to the real selector, so behaviour is unchanged.
- */
-import { combineReducers, configureStore } from '@reduxjs/toolkit';
-import { render } from '@testing-library/react';
-import { Provider } from 'react-redux';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import chatRuntimeReducer from '../../../store/chatRuntimeSlice';
-import themeReducer from '../../../store/themeSlice';
-import threadReducer from '../../../store/threadSlice';
-import { ChatThreadView } from './ChatThreadView';
-
-const selectSpy = vi.hoisted(() => vi.fn());
-
-vi.mock('./BackgroundProcessesPanel', async orig => {
- const actual = await orig<typeof import('./BackgroundProcessesPanel')>();
- return {
- ...actual,
- // Delegate to the real selector; we only need the call count.
- selectBackgroundProcesses: (...args: Parameters<typeof actual.selectBackgroundProcesses>) => {
- selectSpy();
- return actual.selectBackgroundProcesses(...args);
- },
- };
-});
-
-// Layout effects are meaningless in jsdom — same stub the sibling suites use.
-vi.mock('../../../hooks/useStickToBottom', () => ({
- useStickToBottom: vi.fn(() => ({ containerRef: { current: null }, endRef: { current: null } })),
-}));
-
-const emptyThreadState = {
- threads: [],
- selectedThreadId: null,
- activeThreadIds: {},
- welcomeThreadId: null,
- messagesByThreadId: {},
- messages: [],
- isLoadingThreads: false,
- isLoadingMessages: false,
- messagesError: null,
-};
-
-function buildStore() {
- return configureStore({
- reducer: combineReducers({
- thread: threadReducer,
- chatRuntime: chatRuntimeReducer,
- theme: themeReducer,
- }),
- preloadedState: { thread: emptyThreadState } as never,
- });
-}
-
-describe('ChatThreadView empty-fallback identity (#5162)', () => {
- beforeEach(() => {
- selectSpy.mockClear();
- });
-
- it('does not re-derive background processes across re-renders with no thread', () => {
- const store = buildStore();
- const { rerender } = render(
- <Provider store={store}>
- <ChatThreadView threadId={null} />
- </Provider>
- );
-
- expect(selectSpy).toHaveBeenCalledTimes(1);
-
- // Nothing about the timeline changed, so the memo must hold. Pre-fix the
- // `?? []` fallback handed it a new array identity on each pass and this
- // climbed with every render.
- rerender(
- <Provider store={store}>
- <ChatThreadView threadId={null} />
- </Provider>
- );
- rerender(
- <Provider store={store}>
- <ChatThreadView threadId={null} />
- </Provider>
- );
-
- expect(selectSpy).toHaveBeenCalledTimes(1);
- });
-
- it('does not re-derive background processes for a thread with no timeline yet', () => {
- const store = buildStore();
- const props = { threadId: 't-1' };
- const { rerender } = render(
- <Provider store={store}>
- <ChatThreadView {...props} />
- </Provider>
- );
-
- expect(selectSpy).toHaveBeenCalledTimes(1);
-
- // The `toolTimelineByThread[threadId] ?? EMPTY_TOOL_TIMELINE` miss is the
- // common case for a fresh thread — it must be identity-stable too.
- rerender(
- <Provider store={store}>
- <ChatThreadView {...props} />
- </Provider>
- );
-
- expect(selectSpy).toHaveBeenCalledTimes(1);
- });
-});
diff --git a/app/src/features/conversations/components/ChatThreadView.renderPerf.test.tsx b/app/src/features/conversations/components/ChatThreadView.renderPerf.test.tsx
deleted file mode 100644
index ed5d9b1e19..0000000000
--- a/app/src/features/conversations/components/ChatThreadView.renderPerf.test.tsx
+++ /dev/null
@@ -1,296 +0,0 @@
-/**
- * Render-cost regression benchmark for the chat transcript.
- *
- * The defect this pins (verified before any fix existed):
- *
- * `ChatThreadView` calls `unwrapToolCallEnvelope(msg.content)` inside the
- * `timelineMessages.map()` in the RENDER BODY — unmemoized, once per agent
- * message, on every single render. `unwrapToolCallEnvelope` does a
- * `JSON.parse` in a `try/catch`, and for ordinary assistant prose (the common
- * case, by far) that parse THROWS and is caught. Nothing below the transcript
- * is memoized either: `React.memo` appears zero times in `ChatThreadView.tsx`,
- * `AgentMessageBubble.tsx` and `ToolTimelineBlock.tsx`.
- *
- * `ChatThreadView` re-renders on every streamed token (the live preview reads
- * `state.chatRuntime.streamingAssistantByThread`). So each token re-parses
- * every agent message already settled in the transcript: O(N) throwaway work
- * per token, N = transcript length.
- *
- * The contract asserted here is the one that must hold AFTER the fix:
- *
- * 1. Appending a token to the live tail must not re-unwrap the ~39 settled
- * messages above it. Expressed as a small constant bound, not an exact
- * count, so it does not rot on unrelated transcript changes.
- * 2. A settled (non-tail) message's bubble must not re-render when only the
- * tail changes.
- *
- * Both are stated as bounds on work per tail update, and both fail on the
- * pre-fix code. Store/provider harness is deliberately the same one
- * `ChatThreadView.test.tsx` and `ChatThreadView.memoIdentity.test.tsx`
- * already use — no new fixtures.
- *
- * This file measures work, not markup: it must not be "fixed" by changing
- * what the transcript renders. Rendered output is unchanged by design.
- */
-import { combineReducers, configureStore } from '@reduxjs/toolkit';
-import { act, render } from '@testing-library/react';
-import { Provider } from 'react-redux';
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-import chatRuntimeReducer, { streamDeltaReceived } from '../../../store/chatRuntimeSlice';
-import themeReducer from '../../../store/themeSlice';
-import threadReducer from '../../../store/threadSlice';
-import type { Thread, ThreadMessage } from '../../../types/thread';
-import { ChatThreadView } from './ChatThreadView';
-
-/** Counts every `unwrapToolCallEnvelope` call, wherever in the tree it happens. */
-const unwrapSpy = vi.hoisted(() => vi.fn());
-/** Records the `content` of every agent message body React actually renders. */
-const bubbleRenderSpy = vi.hoisted(() => vi.fn<(content: string) => void>());
-
-// Spy at the module boundary rather than on `JSON.parse` directly: the count
-// then stays correct if the fix MOVES the unwrap (e.g. down into a memoized
-// per-message component) instead of caching it in place. Delegates to the real
-// implementation, so behaviour is untouched.
-vi.mock('../../../lib/chat/toolCallEnvelope', async orig => {
- const actual = await orig<typeof import('../../../lib/chat/toolCallEnvelope')>();
- return {
- ...actual,
- unwrapToolCallEnvelope: (raw: string) => {
- unwrapSpy(raw);
- return actual.unwrapToolCallEnvelope(raw);
- },
- };
-});
-
-// Transparent pass-through, deliberately NOT wrapped in `memo`: the contract is
-// that the PARENT stops re-rendering settled message rows, so the instrument
-// must not supply memoization of its own and mask that.
-vi.mock('./AgentMessageBubble', async orig => {
- const actual = await orig<typeof import('./AgentMessageBubble')>();
- return {
- ...actual,
- // Both agent-body renderers are instrumented: `themeSlice` defaults
- // `agentMessageViewMode` to `'text'`, so `AgentMessageText` is the one the
- // default transcript actually mounts — but a host that flips the mode to
- // `'bubbles'` must hold the same contract.
- AgentMessageText: (props: Parameters<typeof actual.AgentMessageText>[0]) => {
- bubbleRenderSpy(props.content);
- return actual.AgentMessageText(props);
- },
- AgentMessageBubble: (props: Parameters<typeof actual.AgentMessageBubble>[0]) => {
- bubbleRenderSpy(props.content);
- return actual.AgentMessageBubble(props);
- },
- };
-});
-
-// Layout effects are meaningless in jsdom — same stub the sibling suites use.
-vi.mock('../../../hooks/useStickToBottom', () => ({
- useStickToBottom: vi.fn(() => ({ containerRef: { current: null }, endRef: { current: null } })),
-}));
-
-const THREAD_ID = 't-perf';
-const MESSAGE_COUNT = 40;
-
-const emptyThreadState = {
- threads: [],
- selectedThreadId: null,
- activeThreadIds: {},
- welcomeThreadId: null,
- messagesByThreadId: {},
- messages: [],
- isLoadingThreads: false,
- isLoadingMessages: false,
- messagesError: null,
-};
-
-function makeThread(): Thread {
- return {
- id: THREAD_ID,
- title: 'Perf thread',
- chatId: null,
- isActive: true,
- messageCount: MESSAGE_COUNT,
- lastMessageAt: '2026-01-01T00:00:00.000Z',
- createdAt: '2026-01-01T00:00:00.000Z',
- labels: ['general'],
- };
-}
-
-/**
- * ~40 messages alternating user/agent. Every agent message is ordinary PROSE —
- * that is the common case, and the one where `JSON.parse` throws and is caught
- * on each call. One agent message carries a real tool-call envelope so the
- * benchmark also covers the branch that legitimately parses.
- */
-function buildTranscript(tailContent: string): ThreadMessage[] {
- const messages: ThreadMessage[] = [];
- for (let i = 0; i < MESSAGE_COUNT - 1; i += 1) {
- const isAgent = i % 2 === 1;
- const envelope = i === 21;
- messages.push({
- id: `m-${i}`,
- sender: isAgent ? 'agent' : 'user',
- type: 'text',
- content: envelope
- ? JSON.stringify({
- content: 'Pulling that up now.',
- tool_calls: [{ id: 'call_1', name: 'memory_search', arguments: '{}' }],
- })
- : isAgent
- ? `Settled agent prose MARK${i}_ nothing JSON about it at all`
- : `User question ${i}?`,
- extraMetadata: {},
- createdAt: new Date(Date.UTC(2026, 0, 1, 0, i)).toISOString(),
- });
- }
- // The tail: the agent message a socket is streaming into.
- messages.push({
- id: 'm-tail',
- sender: 'agent',
- type: 'text',
- content: tailContent,
- extraMetadata: {},
- createdAt: new Date(Date.UTC(2026, 0, 1, 1, 0)).toISOString(),
- });
- return messages;
-}
-
-function buildStore(messages: ThreadMessage[]) {
- return configureStore({
- reducer: combineReducers({
- thread: threadReducer,
- chatRuntime: chatRuntimeReducer,
- theme: themeReducer,
- }),
- preloadedState: {
- thread: {
- ...emptyThreadState,
- threads: [makeThread()],
- selectedThreadId: THREAD_ID,
- messagesByThreadId: { [THREAD_ID]: messages },
- },
- } as never,
- });
-}
-
-/**
- * Work permitted for a single appended token. Generous on purpose: the fix
- * only has to stop the transcript-wide sweep, so anything on the order of the
- * live tail (and its immediate neighbours) is fine. It is the ~40-per-token
- * sweep that must go. A bound, not an exact number, so incidental transcript
- * changes do not rot the test.
- */
-const MAX_WORK_PER_TAIL_TOKEN = 4;
-
-describe('ChatThreadView transcript render cost under streaming', () => {
- beforeEach(() => {
- unwrapSpy.mockClear();
- bubbleRenderSpy.mockClear();
- });
-
- it('does not re-unwrap the settled transcript on every streamed token', () => {
- const store = buildStore(buildTranscript('Starting the answer'));
- render(
- <Provider store={store}>
- <ChatThreadView threadId={THREAD_ID} />
- </Provider>
- );
-
- // Baseline mount is allowed to unwrap every agent message once.
- expect(unwrapSpy.mock.calls.length).toBeGreaterThan(0);
- unwrapSpy.mockClear();
-
- // Stream, as the socket does: `streamDeltaReceived` per token. Nothing in
- // `state.thread` changes — the settled transcript is byte-for-byte the same
- // array — so re-unwrapping any of it is pure waste.
- const TOKENS = 5;
- for (let i = 0; i < TOKENS; i += 1) {
- act(() => {
- store.dispatch(
- streamDeltaReceived({
- threadId: THREAD_ID,
- requestId: 'req-1',
- round: 0,
- delta: ` tok${i}`,
- channel: 'content',
- })
- );
- });
- }
-
- expect(unwrapSpy.mock.calls.length).toBeLessThanOrEqual(MAX_WORK_PER_TAIL_TOKEN * TOKENS);
- });
-
- it('does not re-unwrap settled messages when only the tail message grows', () => {
- // The other shape of the same event: the tail ThreadMessage itself grows as
- // the answer lands. Everything above it is unchanged and must not be
- // touched again.
- const { rerender } = (() => {
- const store = buildStore(buildTranscript('Tok'));
- const utils = render(
- <Provider store={store}>
- <ChatThreadView threadId={THREAD_ID} />
- </Provider>
- );
- return utils;
- })();
-
- unwrapSpy.mockClear();
-
- const GROWTHS = 5;
- let tail = 'Tok';
- for (let i = 0; i < GROWTHS; i += 1) {
- tail = `${tail} tok${i}`;
- const nextStore = buildStore(buildTranscript(tail));
- rerender(
- <Provider store={nextStore}>
- <ChatThreadView threadId={THREAD_ID} />
- </Provider>
- );
- }
-
- expect(unwrapSpy.mock.calls.length).toBeLessThanOrEqual(MAX_WORK_PER_TAIL_TOKEN * GROWTHS);
- });
-
- it('does not re-render a settled message bubble when only the tail changes', () => {
- const store = buildStore(buildTranscript('Starting the answer'));
- render(
- <Provider store={store}>
- <ChatThreadView threadId={THREAD_ID} />
- </Provider>
- );
-
- // Pick one stable, non-tail agent message and watch only that bubble.
- // Matched by its unique marker rather than by whole-string equality:
- // `splitAgentMessageIntoBubbles` may hand the bubble a segment rather than
- // the full message, and that split is not what is under test here.
- const STABLE_MARKER = 'MARK1_';
- const rendersOfStable = () =>
- bubbleRenderSpy.mock.calls.filter(([c]) => c.includes(STABLE_MARKER)).length;
-
- // Sanity check on the instrument itself: if the mount never rendered this
- // bubble, the assertion below would pass vacuously and measure nothing.
- expect(rendersOfStable()).toBe(1);
- bubbleRenderSpy.mockClear();
-
- for (let i = 0; i < 5; i += 1) {
- act(() => {
- store.dispatch(
- streamDeltaReceived({
- threadId: THREAD_ID,
- requestId: 'req-1',
- round: 0,
- delta: ` tok${i}`,
- channel: 'content',
- })
- );
- });
- }
-
- // A message nobody touched must not be re-rendered by a token landing on
- // the live tail.
- expect(rendersOfStable()).toBe(0);
- });
-});
diff --git a/app/src/features/conversations/components/ChatThreadView.test.tsx b/app/src/features/conversations/components/ChatThreadView.test.tsx
deleted file mode 100644
index e2bffd5c7c..0000000000
--- a/app/src/features/conversations/components/ChatThreadView.test.tsx
+++ /dev/null
@@ -1,233 +0,0 @@
-/**
- * Focused behavior tests for the extracted transcript scroll body. Mirrors
- * the store-mounting conventions used by
- * `src/pages/__tests__/Conversations.render.test.tsx` (the home chat's own
- * smoke suite), but scoped to `ChatThreadView` in isolation so a second host
- * (e.g. the Workflow Copilot) can be confident the component works when
- * driven purely by its `threadId` prop rather than the global
- * `state.thread.selectedThreadId`.
- */
-import { combineReducers, configureStore } from '@reduxjs/toolkit';
-import { render, screen } from '@testing-library/react';
-import type { ComponentProps } from 'react';
-import { Provider } from 'react-redux';
-import { describe, expect, it, vi } from 'vitest';
-
-import chatRuntimeReducer from '../../../store/chatRuntimeSlice';
-import themeReducer from '../../../store/themeSlice';
-import threadReducer from '../../../store/threadSlice';
-import type { Thread, ThreadMessage } from '../../../types/thread';
-import { ChatThreadView } from './ChatThreadView';
-
-// useStickToBottom returns refs; mock it so layout-effects don't fire in
-// jsdom (same stub the home-chat render suite uses).
-vi.mock('../../../hooks/useStickToBottom', () => ({
- useStickToBottom: vi.fn(() => ({ containerRef: { current: null }, endRef: { current: null } })),
-}));
-
-function makeThread(overrides: Partial<Thread> = {}): Thread {
- return {
- id: 't-1',
- title: 'Test thread',
- chatId: null,
- isActive: false,
- messageCount: 0,
- lastMessageAt: '2026-01-01T00:00:00.000Z',
- createdAt: '2026-01-01T00:00:00.000Z',
- labels: ['general'],
- ...overrides,
- };
-}
-
-function buildStore(preload: Record<string, unknown> = {}) {
- return configureStore({
- reducer: combineReducers({
- thread: threadReducer,
- chatRuntime: chatRuntimeReducer,
- theme: themeReducer,
- }),
- preloadedState: preload as never,
- });
-}
-
-const emptyThreadState = {
- threads: [],
- selectedThreadId: null,
- activeThreadIds: {},
- welcomeThreadId: null,
- messagesByThreadId: {},
- messages: [],
- isLoadingThreads: false,
- isLoadingMessages: false,
- messagesError: null,
-};
-
-function renderThreadView(
- props: Partial<ComponentProps<typeof ChatThreadView>> & { threadId: string | null },
- preload: Record<string, unknown> = {}
-) {
- const store = buildStore(preload);
- render(
- <Provider store={store}>
- <ChatThreadView {...props} />
- </Provider>
- );
- return store;
-}
-
-describe('ChatThreadView', () => {
- it('renders the chat-messages-scroll container', () => {
- renderThreadView({ threadId: null }, { thread: emptyThreadState });
-
- expect(screen.getByTestId('chat-messages-scroll')).toBeInTheDocument();
- });
-
- it('shows emptyContent when the thread has no messages, footer content, or live activity', () => {
- const thread = makeThread({ id: 't-empty' });
- renderThreadView(
- { threadId: thread.id, emptyContent: <p>Nothing here yet</p> },
- {
- thread: {
- ...emptyThreadState,
- threads: [thread],
- selectedThreadId: thread.id,
- messagesByThreadId: { [thread.id]: [] },
- },
- }
- );
-
- expect(screen.getByText('Nothing here yet')).toBeInTheDocument();
- expect(screen.queryByTestId('chat-message-list')).not.toBeInTheDocument();
- });
-
- it('renders a user and an agent message for the given threadId', () => {
- const thread = makeThread({ id: 't-msgs' });
- const messages: ThreadMessage[] = [
- {
- id: 'm-user',
- sender: 'user',
- type: 'text',
- content: 'Hello there',
- extraMetadata: {},
- createdAt: '2026-01-01T00:00:00.000Z',
- },
- {
- id: 'm-agent',
- sender: 'agent',
- type: 'text',
- content: 'General Kenobi',
- extraMetadata: {},
- createdAt: '2026-01-01T00:01:00.000Z',
- },
- ];
-
- renderThreadView(
- { threadId: thread.id },
- {
- thread: {
- ...emptyThreadState,
- threads: [thread],
- selectedThreadId: thread.id,
- messagesByThreadId: { [thread.id]: messages },
- },
- }
- );
-
- expect(screen.getByTestId('chat-message-list')).toBeInTheDocument();
- expect(screen.getByText('Hello there')).toBeInTheDocument();
- expect(screen.getByText('General Kenobi')).toBeInTheDocument();
- });
-
- it('reads messages by the threadId prop, not a global selected thread', () => {
- // Two threads hydrated in the store; only the prop-driven thread's
- // messages should render — proving the component doesn't fall back to
- // `state.thread.selectedThreadId`.
- const threadA = makeThread({ id: 't-a' });
- const threadB = makeThread({ id: 't-b' });
- const messagesA: ThreadMessage[] = [
- {
- id: 'a-1',
- sender: 'user',
- type: 'text',
- content: 'Message in thread A',
- extraMetadata: {},
- createdAt: '2026-01-01T00:00:00.000Z',
- },
- ];
- const messagesB: ThreadMessage[] = [
- {
- id: 'b-1',
- sender: 'user',
- type: 'text',
- content: 'Message in thread B',
- extraMetadata: {},
- createdAt: '2026-01-01T00:00:00.000Z',
- },
- ];
-
- renderThreadView(
- { threadId: threadB.id },
- {
- thread: {
- ...emptyThreadState,
- threads: [threadA, threadB],
- // Deliberately select A globally — the component must still
- // render B's messages because it reads `threadId` prop, not
- // `selectedThreadId`.
- selectedThreadId: threadA.id,
- messagesByThreadId: { [threadA.id]: messagesA, [threadB.id]: messagesB },
- },
- }
- );
-
- expect(screen.getByText('Message in thread B')).toBeInTheDocument();
- expect(screen.queryByText('Message in thread A')).not.toBeInTheDocument();
- });
-
- it('B25: unwraps a raw tool-call envelope agent message to clean text, never raw JSON', () => {
- // A `workflow_builder` turn that both talks AND calls a tool can land in
- // the transcript as the provider wire-format `{ content, tool_calls }`
- // envelope. The shared renderer (used by both the home chat and the
- // workflow copilot) must show only the human text — never the raw JSON.
- const thread = makeThread({ id: 't-envelope' });
- const messages: ThreadMessage[] = [
- {
- id: 'm-user',
- sender: 'user',
- type: 'text',
- content: 'build me a Slack digest',
- extraMetadata: {},
- createdAt: '2026-01-01T00:00:00.000Z',
- },
- {
- id: 'm-agent',
- sender: 'agent',
- type: 'text',
- content: JSON.stringify({
- content: "Here's the workflow I propose.",
- tool_calls: [{ id: 'call_1', name: 'propose_workflow', arguments: '{"nodes":[]}' }],
- }),
- extraMetadata: {},
- createdAt: '2026-01-01T00:01:00.000Z',
- },
- ];
-
- renderThreadView(
- { threadId: thread.id },
- {
- thread: {
- ...emptyThreadState,
- threads: [thread],
- selectedThreadId: thread.id,
- messagesByThreadId: { [thread.id]: messages },
- },
- }
- );
-
- const list = screen.getByTestId('chat-message-list');
- expect(list).toHaveTextContent("Here's the workflow I propose.");
- // The raw envelope must never reach the DOM as text.
- expect(list).not.toHaveTextContent('tool_calls');
- expect(list).not.toHaveTextContent('"nodes":[]');
- });
-});
diff --git a/app/src/features/conversations/components/ChatThreadView.tsx b/app/src/features/conversations/components/ChatThreadView.tsx
deleted file mode 100644
index 1ec5e515d9..0000000000
--- a/app/src/features/conversations/components/ChatThreadView.tsx
+++ /dev/null
@@ -1,601 +0,0 @@
-import { MessageByIndexProvider } from '@assistant-ui/core/react';
-import { type AssistantState, MessagePrimitive, useAuiState } from '@assistant-ui/react';
-import {
- forwardRef,
- Fragment,
- type ReactNode,
- useCallback,
- useImperativeHandle,
- useMemo,
- useRef,
- useState,
-} from 'react';
-
-import { Conversation, ConversationContent } from '../../../components/ai-elements';
-import { useStickToBottom } from '../../../hooks/useStickToBottom';
-import { useCoreTranscriptProjection } from '../../../providers/useOpenHumanExternalStore';
-import type { ProcessingTranscriptItem, ToolTimelineEntry } from '../../../store/chatRuntimeSlice';
-import { useAppDispatch, useAppSelector } from '../../../store/hooks';
-import { persistReaction } from '../../../store/threadSlice';
-import type { ThreadMessage } from '../../../types/thread';
-import { buildThreadTimeline } from '../timeline/selectors';
-import { supersededInterimIndexes } from '../utils/interimNarration';
-import { AgentInsightsSlot } from './aui/AgentInsightsSlot';
-import { useAuiThreadRunning } from './aui/auiThreadState';
-import { InferenceStatusLine } from './aui/InferenceStatusLine';
-import {
- ParallelBranchPreviews,
- StreamingAssistantPreview,
- TypingIndicator,
-} from './aui/StreamingPreview';
-import { TranscriptOverlays } from './aui/TranscriptOverlays';
-import { TranscriptLoadError, TranscriptSkeleton } from './aui/TranscriptStates';
-import { selectBackgroundProcesses } from './BackgroundProcessesPanel';
-import { InterruptedAnswer } from './InterruptedAnswer';
-import { type PastTurnAnchor, TranscriptRow } from './TranscriptRow';
-
-// Stable empty reference for a thread with no persisted messages yet, so the
-// selector below keeps the same identity when the slice field is absent
-// (narrow test stores) or the thread hasn't hydrated any messages.
-const EMPTY_MESSAGES: ThreadMessage[] = [];
-
-// Stable empty reference so the per-thread past-turn timelines map keeps the
-// same identity when the slice field is absent (narrow test stores).
-const EMPTY_TURN_TIMELINES: Record<string, ToolTimelineEntry[]> = {};
-// Sibling stable empty for the per-thread past-turn processing transcripts map
-// (restore-fidelity fix 1).
-const EMPTY_TURN_TRANSCRIPTS: Record<string, ProcessingTranscriptItem[]> = {};
-// Stable empty transcript for a past turn that has tool rows but no persisted
-// reasoning/narration trail (legacy snapshot), so `PastTurnInsights` falls back
-// to the tool-only view without allocating a fresh array each render.
-const EMPTY_TRANSCRIPT: ProcessingTranscriptItem[] = [];
-// Stable empty tool-row list for a transcript-only past turn (agent thought /
-// narrated but ran no tools).
-const EMPTY_TRANSCRIPT_ENTRIES: ToolTimelineEntry[] = [];
-// Stable empty live tool-timeline / processing-transcript for the selected
-// thread. Allocating a fresh `[]` here gave the value a new identity on every
-// render, which invalidated the `backgroundProcesses` memo below every time and
-// added avoidable re-render churn to the chat's hot path (#5162).
-const EMPTY_TOOL_TIMELINE: ToolTimelineEntry[] = [];
-const EMPTY_PROCESSING: ProcessingTranscriptItem[] = [];
-
-/**
- * Establishes assistant-ui's message context around an OpenHuman transcript
- * row. The row itself remains responsible for the richer interleaved tool and
- * agent-process content, while the core primitive supplies native message
- * state for action bars and future editing/branching affordances.
- */
-function AssistantMessageScope({
- messageId,
- children,
-}: {
- messageId: string;
- children: ReactNode;
-}) {
- const runtimeIndex = useAuiState(
- useCallback(
- (state: AssistantState) =>
- state.optional.thread?.messages.findIndex(message => message.id === messageId) ?? -1,
- [messageId]
- )
- );
-
- // ChatThreadView is also rendered in isolated tests and in non-chat previews
- // without an assistant-ui runtime. Preserve that legitimate fallback.
- if (runtimeIndex < 0) return <>{children}</>;
-
- return (
- <MessageByIndexProvider index={runtimeIndex}>
- <MessagePrimitive.Root className="contents">{children}</MessagePrimitive.Root>
- </MessageByIndexProvider>
- );
-}
-
-export interface ChatThreadViewHandle {
- /** Opens the detached background sub-agents panel — called from the host
- * header's background-processes badge (`Conversations`' own copy of the
- * badge, which needs to stay in the header so it renders regardless of
- * scroll position). */
- openBackgroundProcesses(): void;
-}
-
-interface ChatThreadViewProps {
- /** Thread whose transcript is rendered. `null` renders the empty state
- * (no thread selected). */
- threadId: string | null;
- /** `page` (default) is the home chat's floating-composer layout. `sidebar`
- * drops the bottom-padding-reservation trick (the composer is in normal
- * flow) and always applies a flat `pb-4`. */
- variant?: 'page' | 'sidebar';
- /** Page variant floats its footer over the scroll area; the host passes
- * its measured `composerFooterHeight + 16` so the message list reserves
- * matching bottom padding. Sidebar variant omits this (undefined — the
- * message list falls back to a flat `pb-4`). */
- bottomPadding?: number;
- /** The host's footer has pinned content (e.g. a pending review card) that
- * should keep the scroll container in "has content" layout even when
- * there are no visible messages and no live agent activity yet. */
- hasFooterContent?: boolean;
- /** The host's thread-load state, so the loading skeleton renders while a
- * thread's messages are being fetched. Omit for hosts that hydrate
- * synchronously (no skeleton). */
- isLoading?: boolean;
- loadError?: string | null;
- /** Rendered in place of the transcript when the thread has no visible
- * messages, no footer content, and no live agent activity. */
- emptyContent?: ReactNode;
- /** Agent display name threaded into the assistant message's share button. */
- shareAgentName?: string;
- /** Reset key for the auto-stick-to-bottom scroll behavior (see
- * `useStickToBottom`). Pass a value that changes when the surrounding
- * layout/route changes shape (home passes `location.pathname`). */
- scrollResetKey?: string;
- /** ORed into the in-flight check alongside the persisted inference-turn
- * lifecycle — hosts that track their own "send dispatched, not yet
- * accepted" window (home's `pendingSendingThreadIds`) pass it here so a
- * send appears in-flight immediately, before the first socket event
- * lands. */
- pendingSendActive?: boolean;
-}
-
-/**
- * The chat transcript scroll body: message list (with reactions, citations,
- * copy/share affordances, past-turn insight trails, live streaming preview,
- * inference status line, and the "Agentic task insights" panel), plus the
- * background-processes / sub-agent-drawer / agent-process-source modals that
- * are driven entirely by transcript-local state.
- *
- * Extracted from `Conversations.tsx` (the home chat) so a second surface
- * (the Workflow Copilot, on its own dedicated thread) can reuse the exact
- * same rich rendering. Everything here is keyed off the `threadId` prop
- * rather than the global `state.thread.selectedThreadId` — all state reads
- * are per-thread Redux slices already keyed by thread id.
- *
- * ## assistant-ui
- *
- * The presentation leaves under `./aui/` are built on assistant-ui's HEADLESS
- * primitives and styled with OpenHuman semantic tokens; `@assistant-ui/react-ui`
- * and `@assistant-ui/styles` are deliberately NOT used (compiled Tailwind v4,
- * which this repo's `safari15` CSS target cannot downlevel, and a second theming
- * system competing with Theme Studio).
- *
- * Render ORDER, however, still comes from Redux via `buildThreadTimeline`, not
- * from `ThreadPrimitive.Messages`. That is not laziness: this transcript
- * interleaves things the runtime's message list has no concept of — superseded
- * interim narration is filtered out, each past turn's restored process trail is
- * anchored above its answer, and the live insights slot is anchored after the
- * latest USER message. Handing ordering to the runtime would drop all three.
- * The two views stay in agreement because `assistantUiMessages.ts` projects the
- * same Redux state the rows read.
- *
- * The runtime is read from CONTEXT (`./aui/auiThreadState`), never from
- * `state.thread.selectedThreadId` — `AssistantUiRuntimeProvider` is
- * thread-parameterized and `WorkflowCopilotPanel` mounts its own instance on a
- * dedicated builder thread.
- */
-export const ChatThreadView = forwardRef<ChatThreadViewHandle, ChatThreadViewProps>(
- (
- {
- threadId,
- variant = 'page',
- bottomPadding,
- hasFooterContent = false,
- isLoading = false,
- loadError = null,
- emptyContent = null,
- shareAgentName = 'OpenHuman',
- scrollResetKey = 'chat-thread-view',
- pendingSendActive = false,
- },
- ref
- ) => {
- const dispatch = useAppDispatch();
-
- const isSidebar = variant === 'sidebar';
-
- const messages = useAppSelector(state =>
- threadId ? (state.thread.messagesByThreadId[threadId] ?? EMPTY_MESSAGES) : EMPTY_MESSAGES
- );
- const toolTimelineByThread = useAppSelector(state => state.chatRuntime.toolTimelineByThread);
- const interruptedAssistantByThread = useAppSelector(
- state => state.chatRuntime.interruptedAssistantByThread
- );
- const processingByThread = useAppSelector(state => state.chatRuntime.processingByThread);
- const inferenceStatusByThread = useAppSelector(
- state => state.chatRuntime.inferenceStatusByThread
- );
- const streamingAssistantByThread = useAppSelector(
- state => state.chatRuntime.streamingAssistantByThread
- );
- const parallelStreamsByThread = useAppSelector(
- state => state.chatRuntime.parallelStreamsByThread
- );
- const inferenceTurnLifecycleByThread = useAppSelector(
- state => state.chatRuntime.inferenceTurnLifecycleByThread
- );
- const agentMessageViewMode = useAppSelector(
- state => state.theme?.agentMessageViewMode ?? 'text'
- );
- // When ON, the verbose per-agent "Agentic task insights" timeline is hidden
- // from chat; a compact blinking "Processing" link (and the existing message
- // bubble loading) stand in for it, with the full run one click away in the
- // Agent Process Source side panel. See themeSlice.hideAgentInsights.
- const hideAgentInsights = useAppSelector(state => state.theme?.hideAgentInsights ?? false);
-
- // The assistant-ui runtime's own view of "a turn is running", read from
- // context so the copilot's nested runtime answers for the copilot's thread.
- // `undefined` when no runtime is mounted above this transcript (several unit
- // tests, and any future host that skips the provider) — ORed rather than
- // substituted, so those hosts keep the exact Redux-only behaviour.
- const auiRunning = useAuiThreadRunning();
-
- const [copiedMessageId, setCopiedMessageId] = useState<string | null>(null);
- // Sub-agent whose full live transcript is open in the drawer, keyed by the
- // owning timeline row's spawn `taskId`. Null when the drawer is closed.
- const [openSubagentTaskId, setOpenSubagentTaskId] = useState<string | null>(null);
- // Detached background sub-agents (spawn_async_subagent) panel visibility.
- const [showBackgroundProcesses, setShowBackgroundProcesses] = useState(false);
- // Whether the consolidated "Agent Process Source" panel is open (the full
- // agent-run timeline + visited sources for the current thread).
- const [showProcessSource, setShowProcessSource] = useState(false);
- // When the user clicks a step's "View details →", the Agent Process Source
- // panel is scoped to that single step. `null` = the whole-run overview
- // (opened by the bottom "View full agent process Source" link).
- const [scopedDetailEntryId, setScopedDetailEntryId] = useState<string | null>(null);
- const [reactionPickerMsgId, setReactionPickerMsgId] = useState<string | null>(null);
-
- useImperativeHandle(ref, () => ({
- openBackgroundProcesses: () => setShowBackgroundProcesses(true),
- }));
-
- const { containerRef: messagesContainerRef, endRef: messagesEndRef } = useStickToBottom(
- messages,
- threadId,
- scrollResetKey
- );
-
- // Every callback handed to a `TranscriptRow` has to keep the same identity
- // for the row's `memo` to bail out, and `dispatch` / `threadId` both change
- // out from under a long-lived transcript (a new store in a test harness, a
- // thread switch). So the changing values are read through refs and the
- // callbacks themselves have empty dependency lists.
- const dispatchRef = useRef(dispatch);
- dispatchRef.current = dispatch;
- const threadIdRef = useRef(threadId);
- threadIdRef.current = threadId;
-
- const handleCopyMessage = useCallback((messageId: string, content: string) => {
- void (async () => {
- try {
- await navigator.clipboard.writeText(content);
- setCopiedMessageId(messageId);
- setTimeout(() => setCopiedMessageId(null), 1500);
- } catch {
- // Clipboard API not available — silently fail
- }
- })();
- }, []);
-
- const handleReact = useCallback((messageId: string, emoji: string) => {
- const activeThreadId = threadIdRef.current;
- if (!activeThreadId) return;
- void dispatchRef.current(persistReaction({ threadId: activeThreadId, messageId, emoji }));
- }, []);
-
- const selectedThreadToolTimeline = threadId
- ? (toolTimelineByThread[threadId] ?? EMPTY_TOOL_TIMELINE)
- : EMPTY_TOOL_TIMELINE;
- const selectedThreadProcessing = threadId
- ? (processingByThread[threadId] ?? EMPTY_PROCESSING)
- : EMPTY_PROCESSING;
- // Detached background sub-agents (mode === 'async') spawned in this thread.
- const backgroundProcesses = useMemo(
- () => selectBackgroundProcesses(selectedThreadToolTimeline),
- [selectedThreadToolTimeline]
- );
- // Interim narration bubbles ("Let me get the data for both.", "The HTML is
- // hard to parse. Let me search for a clean table.") are live progress, not
- // content: once the turn delivers its real answer they are superseded, and
- // because they were never filtered they piled up permanently between the
- // question and the answer. Hidden once their own turn produced a final,
- // non-interim agent message — so a turn in flight keeps them visible, an
- // answered turn drops them, and a turn that died before answering keeps
- // them (they are its only record). They remain reachable via "View full
- // agent process Source"; the Flows copilot drops them outright.
- const supersededInterim = useMemo(() => supersededInterimIndexes(messages), [messages]);
- // Memoized: a fresh array here would give `timelineMessages` (and through it
- // `pastTurnAnchors`) a new identity on every render, re-running the whole
- // projection for each streamed token.
- const visibleMessages = useMemo(
- () =>
- messages.filter(
- (msg, index) => !msg.extraMetadata?.hidden && !supersededInterim.has(index)
- ),
- [messages, supersededInterim]
- );
- const hasVisibleMessages = visibleMessages.length > 0;
- const latestVisibleMessage = visibleMessages[visibleMessages.length - 1] ?? null;
- const latestVisibleAgentMessage = [...visibleMessages]
- .reverse()
- .find(msg => msg.sender === 'agent');
- // Message list sourced from the unified timeline projection — the single
- // source of render order (see `docs/plans/conversations-timeline-refactor.md`
- // Phase 2). With the streaming/tool inputs omitted the projection yields
- // exactly the visible messages in order; the tool-timeline block and streaming
- // previews stay anchored inline below, so the rendered DOM is unchanged. This
- // routes the live render loop through the projection ahead of the per-turn
- // grouping in Phase 5.
- const timelineMessages = useMemo(
- () =>
- buildThreadTimeline({
- threadId: threadId ?? '',
- messages: visibleMessages,
- toolTimeline: [],
- streaming: null,
- parallelStreams: [],
- hideAgentInsights: false,
- })
- .map(item => ('message' in item ? item.message : null))
- .filter((message): message is ThreadMessage => message !== null),
- [threadId, visibleMessages]
- );
- // Past-turn tool timelines (Phase 5): map the first assistant message of each
- // older settled turn to that turn's timeline, so each past answer renders its
- // own collapsed process trail above it. The latest turn is excluded upstream
- // (it renders as the live "agent insights" anchor), so there is no double
- // render. Empty for legacy messages without a `requestId`.
- const settledRevision = `${messages.at(-1)?.id ?? ''}:${messages.at(-1)?.content?.length ?? 0}`;
- const coreTranscript = useCoreTranscriptProjection(
- threadId,
- settledRevision,
- threadId ? streamingAssistantByThread[threadId]?.requestId : undefined
- );
- const selectedThreadTurnTimelines = coreTranscript.timelines ?? EMPTY_TURN_TIMELINES;
- // Sibling map: each past turn's persisted reasoning/narration trail, so a
- // reopened turn replays its thoughts, not just its tool cards (fix 1).
- const selectedThreadTurnTranscripts = coreTranscript.transcripts ?? EMPTY_TURN_TRANSCRIPTS;
- const pastTurnAnchors = useMemo(() => {
- const anchors: Record<string, PastTurnAnchor> = {};
- const seen = new Set<string>();
- for (const msg of timelineMessages) {
- if (msg.sender !== 'agent') continue;
- const requestId = msg.extraMetadata?.requestId;
- if (typeof requestId !== 'string' || seen.has(requestId)) continue;
- const entries = selectedThreadTurnTimelines[requestId] ?? EMPTY_TRANSCRIPT_ENTRIES;
- const transcript = selectedThreadTurnTranscripts[requestId] ?? EMPTY_TRANSCRIPT;
- // Anchor the turn when it has EITHER tool rows OR a reasoning/narration
- // trail — a tool-less turn (agent only thought/narrated) must still
- // render its restored thoughts above its answer (fix 1).
- if (entries.length > 0 || transcript.length > 0) {
- anchors[msg.id] = { entries, transcript };
- seen.add(requestId);
- }
- }
- return anchors;
- }, [timelineMessages, selectedThreadTurnTimelines, selectedThreadTurnTranscripts]);
- const activeSubagentTimelineEntry = selectedThreadToolTimeline.find(
- entry => entry.status === 'running' && entry.name.startsWith('subagent:')
- );
- const activeToolTimelineEntry = [...selectedThreadToolTimeline]
- .reverse()
- .find(entry => entry.status === 'running' && !entry.name.startsWith('subagent:'));
- const selectedInferenceStatus = threadId ? (inferenceStatusByThread[threadId] ?? null) : null;
- const selectedStreamingAssistant = threadId
- ? (streamingAssistantByThread[threadId] ?? null)
- : null;
- // The partial reply an interrupted turn left behind (restore-fidelity fix 2):
- // surfaced as a settled, marked-interrupted bubble on restore so a turn that
- // crashed mid-answer keeps its visible work instead of rendering blank.
- const selectedInterruptedAssistant = threadId
- ? (interruptedAssistantByThread[threadId] ?? null)
- : null;
- // Live streams for concurrent parallel (forked) turns on the selected thread,
- // rendered as separate interleaved branch bubbles.
- const selectedParallelStreams = threadId
- ? Object.values(parallelStreamsByThread[threadId] ?? {})
- : [];
-
- const isSending = Boolean(
- threadId &&
- (pendingSendActive ||
- auiRunning === true ||
- inferenceTurnLifecycleByThread[threadId] === 'started' ||
- inferenceTurnLifecycleByThread[threadId] === 'streaming')
- );
- const shouldRenderTimelineBeforeLatestAgentMessage =
- selectedThreadToolTimeline.length > 0 && !isSending && Boolean(latestVisibleAgentMessage);
-
- // Live agent activity that must stay visible even before the thread's
- // message history has loaded: an in-flight turn, recorded tool steps, a
- // processing transcript, or streamed prose. Without this, switching to a
- // thread mid-turn rendered a blank pane (the message list is gated on
- // `hasVisibleMessages`) until `loadThreadMessages` resolved — tool calls and
- // streaming output silently invisible despite landing in Redux.
- const hasLiveAgentActivity =
- isSending ||
- selectedThreadToolTimeline.length > 0 ||
- selectedThreadProcessing.length > 0 ||
- Boolean(selectedStreamingAssistant) ||
- // An interrupted turn's restored partial answer must surface too, even
- // before the durable message history loads (restore-fidelity fix 2).
- Boolean(selectedInterruptedAssistant);
-
- // Anchor the "Agentic task insights" panel right after the latest turn's user
- // message — processing happens *before* the answer, so it reads above the
- // result (for both the live streaming preview and the settled agent bubbles).
- // Anchoring on the user message (not the first/last agent message) avoids the
- // multi-agent-message split from issue #3717.
- const lastUserMessageId = [...visibleMessages].reverse().find(m => m.sender === 'user')?.id;
-
- // Open the Agent Process Source panel scoped to one step, or to the whole run.
- const openScopedDetail = (entry: ToolTimelineEntry) => {
- setScopedDetailEntryId(entry.id);
- setShowProcessSource(true);
- };
- const openWholeRunSource = () => {
- setScopedDetailEntryId(null);
- setShowProcessSource(true);
- };
- const scopedDetailEntry =
- scopedDetailEntryId != null
- ? selectedThreadToolTimeline.find(e => e.id === scopedDetailEntryId)
- : undefined;
-
- // The insights panel (timeline + "View full agent process Source" opener),
- // built once and rendered inline above the latest answer.
- const agentInsights = (
- <AgentInsightsSlot
- entries={selectedThreadToolTimeline}
- transcript={selectedThreadProcessing}
- turnActive={isSending}
- timelineBeforeLatestAnswer={shouldRenderTimelineBeforeLatestAgentMessage}
- hideAgentInsights={hideAgentInsights}
- onViewDetails={openScopedDetail}
- onViewWholeRun={openWholeRunSource}
- />
- );
-
- // Standalone fallback slot (rendered once, below all messages) for the
- // rare thread with no user message at all (e.g. a proactive-only run), so
- // `agentInsights` is never unreachable. This slot sits at a fixed JSX
- // position with no per-thread key of its own, so switching directly
- // between two threads that both hit this fallback (e.g. two proactive-only
- // threads) would otherwise reuse the same `ToolTimelineBlock` instance
- // instead of remounting it — leaking its sticky `userOverrideOpen`
- // disclosure state from the old thread into the new one (flagged in
- // review on #4942). Keying on thread id forces a clean remount on every
- // thread switch, matching the `key={msg.id}` pattern used for the in-flow
- // timeline above.
- const proactiveInsightsFallback = lastUserMessageId ? null : (
- <Fragment key={threadId ?? 'none'}>{agentInsights}</Fragment>
- );
-
- const hasContent = hasVisibleMessages || hasFooterContent || hasLiveAgentActivity;
- // Suppress the legacy 3-dot placeholder once streaming output (visible text
- // or thinking) has started — the streaming preview bubble below takes over
- // as the activity indicator.
- const showTypingIndicator =
- isSending &&
- !(
- (selectedStreamingAssistant?.content.length ?? 0) > 0 ||
- (selectedStreamingAssistant?.thinking.length ?? 0) > 0
- );
-
- return (
- <>
- {/* Full-width scroll (scrollbar hugs the window edge); inner content is
- centered and width-capped per branch below. `Conversation` supplies
- the `flex-1 min-h-0 overflow-y-auto` shell and the `role="log"` that
- makes arriving turns announce; the stick-to-bottom behaviour stays
- this component's, wired through the forwarded ref. */}
- <Conversation ref={messagesContainerRef} data-testid="chat-messages-scroll">
- {isLoading ? (
- <TranscriptSkeleton />
- ) : loadError ? (
- <TranscriptLoadError message={loadError} />
- ) : hasContent ? (
- <ConversationContent
- data-testid="chat-message-list"
- className={`mx-auto max-w-195 space-y-3 px-5 pt-4 ${isSidebar ? 'pb-4' : ''}`}
- // Page variant: reserve room for the absolutely-positioned floating
- // composer footer so its tail stays visible. Tracks the footer's
- // measured height (+16px gap) instead of a static `pb-32`, so the
- // queued-followups panel and other dynamic footer content never
- // overlap the last message (#4268).
- style={bottomPadding !== undefined ? { paddingBottom: bottomPadding } : undefined}>
- {timelineMessages.map(msg => (
- <Fragment key={msg.id}>
- {/* One memoized row per turn. Everything the row needs is
- passed as a primitive or a stable callback so a streamed
- token landing on the live tail cannot re-render — or
- re-parse — the settled transcript above it
- (`ChatThreadView.renderPerf.test.tsx`). `agentInsights` is
- deliberately rendered OUTSIDE the row: it is rebuilt on
- every render, and passing it in would defeat the memo for
- whichever row happened to anchor it. The edit composer and
- `BranchPickerPrimitive` would attach INSIDE the row when
- the adapter grows `onEdit` / `setMessages` — see
- `EDIT_AND_BRANCH_SEAM` in `./aui/auiThreadState`. */}
- <AssistantMessageScope messageId={msg.id}>
- <TranscriptRow
- msg={msg}
- threadId={threadId}
- agentMessageViewMode={agentMessageViewMode}
- isLatestVisible={latestVisibleMessage?.id === msg.id}
- isCopied={copiedMessageId === msg.id}
- isReactionPickerOpen={reactionPickerMsgId === msg.id}
- pastTurn={pastTurnAnchors[msg.id]}
- shareAgentName={shareAgentName}
- onCopy={handleCopyMessage}
- onReact={handleReact}
- onOpenReactionPicker={setReactionPickerMsgId}
- />
- </AssistantMessageScope>
- {msg.id === lastUserMessageId ? agentInsights : null}
- </Fragment>
- ))}
- {showTypingIndicator && <TypingIndicator />}
- {selectedStreamingAssistant && (
- <StreamingAssistantPreview content={selectedStreamingAssistant.content} />
- )}
- {/* Interrupted turn's partial answer (restore-fidelity fix 2):
- a settled, marked-interrupted bubble surfaced on restore. Only
- when NOT streaming live (the buffer is cleared by any live turn
- in the slice; this guard is belt-and-braces). */}
- {!isSending && selectedInterruptedAssistant ? (
- <InterruptedAnswer
- content={selectedInterruptedAssistant.content}
- thinking={selectedInterruptedAssistant.thinking}
- />
- ) : null}
- <ParallelBranchPreviews branches={selectedParallelStreams} />
- {/* Inference status indicator.
- For the tool_use / subagent phases this line just restates the
- active row already shown in the agentic-task-insights timeline,
- so suppress it once that timeline is on screen — keep it only
- for the `thinking` phase (which has no timeline row yet) or when
- there is no timeline to fall back on. */}
- {selectedInferenceStatus &&
- (selectedInferenceStatus.phase === 'thinking' ||
- selectedThreadToolTimeline.length === 0) && (
- <InferenceStatusLine
- status={selectedInferenceStatus}
- activeToolEntry={activeToolTimelineEntry}
- activeSubagentEntry={activeSubagentTimelineEntry}
- />
- )}
- {/* The "Agentic task insights" panel is rendered inline *above* the
- latest answer (right after the latest turn's user message) so
- processing reads before the result. `proactiveInsightsFallback`
- (defined above, near `agentInsights`) covers the rare thread
- with no user message at all — see its doc comment for the
- per-thread keying that fix keeps this remount-safe. */}
- {proactiveInsightsFallback}
- <div ref={messagesEndRef} />
- </ConversationContent>
- ) : (
- emptyContent
- )}
- </Conversation>
- <TranscriptOverlays
- threadId={threadId}
- entries={selectedThreadToolTimeline}
- transcript={selectedThreadProcessing}
- backgroundProcesses={backgroundProcesses}
- showBackgroundProcesses={showBackgroundProcesses}
- onCloseBackgroundProcesses={() => setShowBackgroundProcesses(false)}
- openSubagentTaskId={openSubagentTaskId}
- onOpenSubagent={setOpenSubagentTaskId}
- showProcessSource={showProcessSource}
- scopedEntry={scopedDetailEntry}
- onCloseProcessSource={() => {
- setShowProcessSource(false);
- setScopedDetailEntryId(null);
- }}
- />
- </>
- );
- }
-);
-
-ChatThreadView.displayName = 'ChatThreadView';
diff --git a/app/src/features/conversations/components/CitationChips.tsx b/app/src/features/conversations/components/CitationChips.tsx
deleted file mode 100644
index ee119191e5..0000000000
--- a/app/src/features/conversations/components/CitationChips.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-/**
- * Compact memory citation chips for assistant messages (wired from
- * `extraMetadata.citations` populated on `chat_done` / segment events).
- */
-export type MessageCitation = {
- id: string;
- key: string;
- namespace?: string;
- score?: number;
- timestamp: string;
- snippet: string;
-};
-
-export function CitationChips({ citations }: { citations: MessageCitation[] }) {
- const filteredCitations = citations.filter(c => c.namespace !== 'global');
- if (filteredCitations.length === 0) return null;
- return (
- <div className="mt-1.5 flex flex-wrap gap-1">
- {filteredCitations.map(citation => {
- const scoreLabel =
- typeof citation.score === 'number' ? ` ${Math.round(citation.score * 100)}%` : '';
- const title = `${citation.key}${citation.namespace ? ` (${citation.namespace})` : ''}\n${citation.snippet}`;
- return (
- <details key={citation.id} className="group">
- <summary
- className="list-none cursor-pointer rounded-full border border-line-strong bg-surface-subtle px-2 py-0.5 text-[10px] text-content-secondary hover:bg-surface-strong"
- aria-label={title}
- title={title}>
- {citation.namespace ?? citation.key}
- {scoreLabel}
- </summary>
- <div className="mt-1 max-w-md rounded-md border border-line bg-surface px-2 py-1 text-[11px] text-content-secondary shadow-xs">
- {citation.snippet}
- </div>
- </details>
- );
- })}
- </div>
- );
-}
diff --git a/app/src/features/conversations/components/InterruptedAnswer.test.tsx b/app/src/features/conversations/components/InterruptedAnswer.test.tsx
deleted file mode 100644
index ccd450197a..0000000000
--- a/app/src/features/conversations/components/InterruptedAnswer.test.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-import { render, screen } from '@testing-library/react';
-import { Provider } from 'react-redux';
-import { describe, expect, it } from 'vitest';
-
-import { store } from '../../../store';
-import { InterruptedAnswer } from './InterruptedAnswer';
-
-function renderInStore(ui: React.ReactNode) {
- return render(<Provider store={store}>{ui}</Provider>);
-}
-
-describe('InterruptedAnswer', () => {
- it('surfaces the partial reply with an interrupted marker', () => {
- renderInStore(
- <InterruptedAnswer content="Here is the partial answer" thinking="was reasoning about it" />
- );
-
- const block = screen.getByTestId('interrupted-answer');
- expect(block.textContent).toContain('Here is the partial answer');
- // The reasoning it had streamed is kept in a collapsed block.
- expect(block.textContent).toContain('was reasoning about it');
- // Marked interrupted rather than presented as a finished answer.
- expect(screen.getByTestId('interrupted-answer-marker')).toBeTruthy();
- });
-
- it('renders nothing when neither content nor thinking has any text', () => {
- const { container } = renderInStore(<InterruptedAnswer content=" " thinking="" />);
- expect(container.querySelector('[data-testid="interrupted-answer"]')).toBeNull();
- });
-});
diff --git a/app/src/features/conversations/components/InterruptedAnswer.tsx b/app/src/features/conversations/components/InterruptedAnswer.tsx
deleted file mode 100644
index e306363f79..0000000000
--- a/app/src/features/conversations/components/InterruptedAnswer.tsx
+++ /dev/null
@@ -1,53 +0,0 @@
-import { useT } from '../../../lib/i18n/I18nContext';
-import { BubbleMarkdown } from './AgentMessageBubble';
-
-/**
- * The partial assistant reply left behind by an INTERRUPTED turn — the core
- * process that was streaming it exited before `chat_done`, so no final message
- * was ever committed to the durable thread log (restore-fidelity fix 2).
- *
- * Unlike the live streaming preview, this is a SETTLED buffer: it renders as a
- * static agent bubble (no pulsing cursor, full Markdown like a finished answer)
- * carrying an "Interrupted" marker, plus the hidden reasoning it had streamed in
- * a collapsed block. It is deliberately NOT written into the durable message
- * list — it is a restore-time surfacing of what the agent had produced, so the
- * user sees the partial work instead of a blank turn.
- */
-export function InterruptedAnswer({ content, thinking }: { content: string; thinking: string }) {
- const { t } = useT();
- const trimmedContent = content.trim();
- const trimmedThinking = thinking.trim();
- // Nothing persisted to show — render nothing rather than an empty marked bubble.
- if (!trimmedContent && !trimmedThinking) return null;
-
- return (
- <div className="flex justify-start" data-testid="interrupted-answer">
- <div className="relative w-fit max-w-[75%] space-y-1">
- {trimmedThinking ? (
- <details className="mb-0.5 rounded-lg bg-surface-subtle px-3 py-1.5 text-xs text-content-secondary dark:bg-surface-muted">
- <summary className="flex cursor-pointer items-center gap-1.5 select-none">
- <span aria-hidden className="text-[10px] leading-none">
- 💭
- </span>
- <span>{t('chat.thinking')}</span>
- </summary>
- <pre className="mt-1.5 font-sans text-[11px] wrap-break-word whitespace-pre-wrap text-content-muted">
- {trimmedThinking}
- </pre>
- </details>
- ) : null}
- <div className="rounded-2xl rounded-bl-md border-l-2 border-amber-400/70 bg-surface-strong/80 px-3 py-2 text-content dark:bg-surface-muted">
- <div
- className="mb-1 flex items-center gap-1.5 text-[10px] font-medium tracking-wide text-amber-600 uppercase dark:text-amber-300"
- data-testid="interrupted-answer-marker">
- <span aria-hidden className="text-[11px] leading-none">
- ⚠
- </span>
- <span>{t('intelligence.agentWork.status.interrupted')}</span>
- </div>
- {trimmedContent ? <BubbleMarkdown content={trimmedContent} /> : null}
- </div>
- </div>
- </div>
- );
-}
diff --git a/app/src/features/conversations/components/PastTurnInsights.test.tsx b/app/src/features/conversations/components/PastTurnInsights.test.tsx
deleted file mode 100644
index 31a5bb47cd..0000000000
--- a/app/src/features/conversations/components/PastTurnInsights.test.tsx
+++ /dev/null
@@ -1,71 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import { Provider } from 'react-redux';
-import { describe, expect, it } from 'vitest';
-
-import { store } from '../../../store';
-import type { ProcessingTranscriptItem, ToolTimelineEntry } from '../../../store/chatRuntimeSlice';
-import { PastTurnInsights } from './PastTurnInsights';
-
-function renderInStore(ui: React.ReactNode) {
- return render(<Provider store={store}>{ui}</Provider>);
-}
-
-describe('PastTurnInsights', () => {
- it('replays a restored turn as interleaved thoughts + tool rows, not just tool cards', () => {
- // A reopened past turn carries both its reasoning trail and its tools.
- const entries: ToolTimelineEntry[] = [
- { id: 'c1', name: 'read_file', round: 0, seq: 0, status: 'success' },
- ];
- const transcript: ProcessingTranscriptItem[] = [
- { kind: 'thinking', round: 0, seq: 1, text: 'planning the search' },
- { kind: 'toolCall', round: 0, seq: 2, callId: 'c1' },
- ];
-
- renderInStore(<PastTurnInsights entries={entries} transcript={transcript} />);
-
- // The hidden reasoning replays (fix 1) — a restored turn is no longer
- // tool-cards-only.
- expect(screen.getByTestId('processing-thinking').textContent).toContain('planning the search');
- // And its tool step still renders in the interleaved view.
- expect(screen.getAllByTestId('processing-tool-row').length).toBeGreaterThan(0);
- });
-
- it('renders restored sub-agent transcripts beneath the trail', () => {
- const entries: ToolTimelineEntry[] = [
- {
- id: 'subagent:task-y',
- name: 'subagent:researcher',
- round: 0,
- seq: 0,
- status: 'success',
- subagent: {
- taskId: 'task-y',
- agentId: 'researcher',
- toolCalls: [],
- transcript: [{ kind: 'thinking', iteration: 1, text: 'child reasoning trail' }],
- },
- },
- ];
- const transcript: ProcessingTranscriptItem[] = [
- { kind: 'narration', round: 0, seq: 0, text: 'delegating to a researcher' },
- ];
-
- renderInStore(<PastTurnInsights entries={entries} transcript={transcript} />);
-
- const subagents = screen.getByTestId('past-turn-subagents');
- fireEvent.click(screen.getByTestId('assistant-ui-subagent-call').querySelector('button')!);
- expect(subagents.textContent).toContain('child reasoning trail');
- });
-
- it('falls back to the tool-only timeline for a legacy turn with no transcript', () => {
- const entries: ToolTimelineEntry[] = [
- { id: 'c1', name: 'read_file', round: 0, seq: 0, status: 'success' },
- ];
-
- renderInStore(<PastTurnInsights entries={entries} transcript={[]} />);
-
- // The interleaved transcript view is absent; the tool-only block renders.
- expect(screen.queryByTestId('processing-transcript')).toBeNull();
- expect(screen.getByTestId('agent-task-insights')).toBeTruthy();
- });
-});
diff --git a/app/src/features/conversations/components/PastTurnInsights.tsx b/app/src/features/conversations/components/PastTurnInsights.tsx
deleted file mode 100644
index 6389ed70e5..0000000000
--- a/app/src/features/conversations/components/PastTurnInsights.tsx
+++ /dev/null
@@ -1,61 +0,0 @@
-import type { ProcessingTranscriptItem, ToolTimelineEntry } from '../../../store/chatRuntimeSlice';
-import { formatTimelineEntry } from '../../../utils/toolTimelineFormatting';
-import { AssistantUiSubagentCall } from './AssistantUiSubagentCall';
-import { ProcessingTranscriptView } from './ProcessingTranscriptView';
-import { ToolTimelineBlock } from './ToolTimelineBlock';
-
-/**
- * The collapsed process trail rendered above a PAST (settled) turn's answer on a
- * reopened thread — restore-fidelity fix 1.
- *
- * A restored turn must show the *same* interleaved thoughts + tools view a live
- * turn does, not just its tool cards: the persisted `transcript`
- * (narration/thinking/tool pointers, hydrated into
- * `turnTranscriptsByThread`) drives {@link ProcessingTranscriptView}, so the
- * reasoning and narration replay inline exactly where they streamed. Restored
- * sub-agent transcripts (fix 4) render beneath as their own activity blocks,
- * mirroring the whole-run {@link AgentProcessSourcePanel} body.
- *
- * Legacy turns persisted before the transcript field existed have no
- * `transcript` — they fall back to the tool-only {@link ToolTimelineBlock}, so
- * older threads keep rendering unchanged.
- */
-export function PastTurnInsights({
- entries,
- transcript,
-}: {
- entries: ToolTimelineEntry[];
- transcript: ProcessingTranscriptItem[];
-}) {
- // No reasoning/narration trail persisted (legacy snapshot): render the
- // tool-only timeline, which already nests each sub-agent's activity inline.
- if (transcript.length === 0) {
- return <ToolTimelineBlock entries={entries} />;
- }
-
- const subagentEntries = entries.filter(entry => entry.subagent);
-
- return (
- <div className="space-y-3">
- {/* Interleaved narration + hidden reasoning + grouped tool steps. */}
- <ProcessingTranscriptView transcript={transcript} entries={entries} />
-
- {/* Sub-agents — each delegated agent's restored transcript (thoughts +
- tool rows), so a reopened turn keeps its sub-agent reasoning, not just
- a flat tool row. `ProcessingTranscriptView` shows the spawn as a tool
- row but does not nest the child's activity, so surface it here. */}
- {subagentEntries.length > 0 ? (
- <div className="space-y-3" data-testid="past-turn-subagents">
- {subagentEntries.map(entry => (
- <div key={entry.id}>
- <p className="text-[12px] font-medium text-content-secondary">
- {formatTimelineEntry(entry).title}
- </p>
- <AssistantUiSubagentCall activity={entry.subagent!} />
- </div>
- ))}
- </div>
- ) : null}
- </div>
- );
-}
diff --git a/app/src/features/conversations/components/TranscriptRow.test.tsx b/app/src/features/conversations/components/TranscriptRow.test.tsx
deleted file mode 100644
index 54a4747698..0000000000
--- a/app/src/features/conversations/components/TranscriptRow.test.tsx
+++ /dev/null
@@ -1,154 +0,0 @@
-import { render, screen } from '@testing-library/react';
-import userEvent from '@testing-library/user-event';
-import { describe, expect, it, vi } from 'vitest';
-
-import type { ThreadMessage } from '../../../types/thread';
-import { sameThreadMessage, TranscriptRow, type TranscriptRowProps } from './TranscriptRow';
-
-// The share affordance opens a modal and talks to the backend; the row only
-// has to place it, so stub it down to a marker.
-vi.mock('../../share/ShareMessageButton', () => ({
- ShareMessageButton: ({ content }: { content: string }) => (
- <button type="button" data-testid="share-button" data-content={content} />
- ),
-}));
-
-function makeMessage(overrides: Partial<ThreadMessage> = {}): ThreadMessage {
- return {
- id: 'm-1',
- sender: 'agent',
- type: 'text',
- content: 'Hello there',
- extraMetadata: {},
- createdAt: '2026-01-01T00:00:00.000Z',
- ...overrides,
- } as ThreadMessage;
-}
-
-function renderRow(overrides: Partial<TranscriptRowProps> = {}) {
- const props: TranscriptRowProps = {
- msg: makeMessage(),
- threadId: 't-1',
- agentMessageViewMode: 'text',
- isLatestVisible: false,
- isCopied: false,
- isReactionPickerOpen: false,
- shareAgentName: 'OpenHuman',
- onCopy: vi.fn(),
- onReact: vi.fn(),
- onOpenReactionPicker: vi.fn(),
- ...overrides,
- };
- return { ...render(<TranscriptRow {...props} />), props };
-}
-
-describe('TranscriptRow', () => {
- it('renders an agent turn with the transcript test hooks the E2E specs read', () => {
- renderRow();
-
- const row = screen.getByTestId('chat-message-row');
- expect(row).toHaveAttribute('data-sender', 'agent');
- expect(row).toHaveAttribute('data-from', 'assistant');
- expect(screen.getByTestId('agent-message')).toBeInTheDocument();
- expect(screen.getByText('Hello there')).toBeInTheDocument();
- });
-
- it('renders a user turn on the trailing edge and offers no share affordance', () => {
- renderRow({ msg: makeMessage({ id: 'm-2', sender: 'user', content: 'A question?' }) });
-
- expect(screen.getByTestId('chat-message-row')).toHaveAttribute('data-from', 'user');
- expect(screen.getByText('A question?')).toBeInTheDocument();
- expect(screen.queryByTestId('share-button')).toBeNull();
- });
-
- it('unwraps a raw tool-call envelope to its human text, never raw JSON', () => {
- renderRow({
- msg: makeMessage({
- content: JSON.stringify({
- content: 'Pulling that up now.',
- tool_calls: [{ id: 'call_1', name: 'memory_search', arguments: '{}' }],
- }),
- }),
- });
-
- expect(screen.getByText('Pulling that up now.')).toBeInTheDocument();
- expect(screen.queryByText(/tool_calls/)).toBeNull();
- });
-
- it('copies the turn text through the supplied handler', async () => {
- const user = userEvent.setup();
- const onCopy = vi.fn();
- renderRow({ onCopy });
-
- await user.click(screen.getByRole('button', { name: /copy/i }));
-
- expect(onCopy).toHaveBeenCalledWith('m-1', 'Hello there');
- });
-
- it('shows the reaction affordance only on the latest visible turn', () => {
- const { unmount } = renderRow({ isLatestVisible: false });
- expect(screen.queryByRole('button', { name: /reaction/i })).toBeNull();
- unmount();
-
- renderRow({ isLatestVisible: true });
- expect(screen.getByRole('button', { name: /reaction/i })).toBeInTheDocument();
- });
-
- it('reacts and closes the picker in one click', async () => {
- const user = userEvent.setup();
- const onReact = vi.fn();
- const onOpenReactionPicker = vi.fn();
- renderRow({ isLatestVisible: true, isReactionPickerOpen: true, onReact, onOpenReactionPicker });
-
- await user.click(screen.getByTitle('👍'));
-
- expect(onReact).toHaveBeenCalledWith('m-1', '👍');
- expect(onOpenReactionPicker).toHaveBeenCalledWith(null);
- });
-
- it('marks a turn the user stopped mid-stream', () => {
- renderRow({ msg: makeMessage({ extraMetadata: { stopped: true } }) });
-
- expect(screen.getByTestId('stopped-marker')).toBeInTheDocument();
- });
-
- it('renders a restored past-turn process trail above the answer', () => {
- renderRow({
- pastTurn: {
- entries: [
- { id: 'e-1', name: 'memory_search', round: 0, seq: 0, status: 'success' as const },
- ],
- transcript: [],
- },
- });
-
- expect(screen.getByTestId('past-turn-insights')).toBeInTheDocument();
- });
-});
-
-describe('sameThreadMessage', () => {
- it('treats a structurally identical rehydrated message as unchanged', () => {
- expect(sameThreadMessage(makeMessage(), makeMessage())).toBe(true);
- });
-
- it('separates messages whose rendered content differs', () => {
- expect(sameThreadMessage(makeMessage(), makeMessage({ content: 'Different' }))).toBe(false);
- });
-
- it('separates messages whose metadata differs', () => {
- expect(
- sameThreadMessage(makeMessage(), makeMessage({ extraMetadata: { stopped: true } }))
- ).toBe(false);
- });
-
- it('separates messages whose metadata holds a different array instance', () => {
- // Arrays are compared by identity: Redux keeps the instance stable for an
- // untouched message, so a new instance means something rewrote it.
- expect(
- sameThreadMessage(
- makeMessage({ extraMetadata: { myReactions: ['👍'] } }),
- makeMessage({ extraMetadata: { myReactions: ['👍'] } })
- )
- ).toBe(false);
- });
-});
diff --git a/app/src/features/conversations/components/TranscriptRow.tsx b/app/src/features/conversations/components/TranscriptRow.tsx
deleted file mode 100644
index 4955ebb2c8..0000000000
--- a/app/src/features/conversations/components/TranscriptRow.tsx
+++ /dev/null
@@ -1,372 +0,0 @@
-import { memo } from 'react';
-
-import { Message, MessageAction, MessageContent } from '../../../components/ai-elements';
-import { parseMessageImages } from '../../../lib/attachments';
-import { unwrapToolCallEnvelope } from '../../../lib/chat/toolCallEnvelope';
-import { useT } from '../../../lib/i18n/I18nContext';
-import type { ProcessingTranscriptItem, ToolTimelineEntry } from '../../../store/chatRuntimeSlice';
-import type { ThreadMessage } from '../../../types/thread';
-import { splitAgentMessageIntoBubbles } from '../../../utils/agentMessageBubbles';
-import { ShareMessageButton } from '../../share/ShareMessageButton';
-import { type AgentBubblePosition, formatRelativeTime } from '../utils/format';
-import { AgentMessageBubble, AgentMessageText } from './AgentMessageBubble';
-import { CitationChips, type MessageCitation } from './CitationChips';
-import { PastTurnInsights } from './PastTurnInsights';
-import { UserTurnBody } from './UserTurnBody';
-
-/** Emoji offered by the inline reaction picker. */
-const REACTION_EMOJI = ['👍', '❤️', '😂', '🔥', '👀', '🎯'] as const;
-
-/** The persisted process trail of an older, settled turn. */
-export interface PastTurnAnchor {
- entries: ToolTimelineEntry[];
- transcript: ProcessingTranscriptItem[];
-}
-
-export interface TranscriptRowProps {
- /** The turn this row renders. */
- msg: ThreadMessage;
- /** Thread the turn belongs to — threaded into the share affordance. */
- threadId: string | null;
- /** `'text'` renders one flowing answer; `'bubbles'` splits it into chat bubbles. */
- agentMessageViewMode: 'text' | 'bubbles';
- /** True for the newest visible turn, which alone shows its timestamp and
- * reaction affordance. Passed as a boolean rather than as "the latest
- * message" so a new tail does not invalidate every other row's props. */
- isLatestVisible: boolean;
- /** True while this row's copy affordance is showing its "copied" tick. */
- isCopied: boolean;
- /** True while this row owns the open reaction picker. */
- isReactionPickerOpen: boolean;
- /** This turn's restored process trail, or `undefined` if it has none. */
- pastTurn?: PastTurnAnchor;
- /** Agent display name for the share affordance. */
- shareAgentName: string;
- /** Copy the turn's plain text. Must be referentially stable. */
- onCopy: (messageId: string, content: string) => void;
- /** Toggle a reaction on the turn. Must be referentially stable. */
- onReact: (messageId: string, emoji: string) => void;
- /** Open (`messageId`) or close (`null`) the reaction picker. Must be stable. */
- onOpenReactionPicker: (messageId: string | null) => void;
-}
-
-/** Shallow one-level comparison of a message's metadata bag. */
-function sameMetadata(
- a: ThreadMessage['extraMetadata'],
- b: ThreadMessage['extraMetadata']
-): boolean {
- if (a === b) return true;
- if (!a || !b) return false;
- const keysA = Object.keys(a);
- if (keysA.length !== Object.keys(b).length) return false;
- return keysA.every(key => a[key] === b[key]);
-}
-
-/**
- * Two messages render identically.
- *
- * Deliberately compares FIELDS, not object identity. Redux keeps a settled
- * message's identity stable, but a re-hydrated transcript (a reconnect, a
- * refetch, a test that rebuilds its fixture) hands back structurally identical
- * objects with fresh identities — and identity-only memoization would re-render
- * and re-parse the entire transcript on each of those, which is exactly the
- * cost this row exists to avoid.
- */
-export function sameThreadMessage(a: ThreadMessage, b: ThreadMessage): boolean {
- return (
- a === b ||
- (a.id === b.id &&
- a.sender === b.sender &&
- a.type === b.type &&
- a.content === b.content &&
- a.createdAt === b.createdAt &&
- sameMetadata(a.extraMetadata, b.extraMetadata))
- );
-}
-
-function TranscriptRowImpl({
- msg,
- threadId,
- agentMessageViewMode,
- isLatestVisible,
- isCopied,
- isReactionPickerOpen,
- pastTurn,
- shareAgentName,
- onCopy,
- onReact,
- onOpenReactionPicker,
-}: TranscriptRowProps) {
- const { t } = useT();
-
- const isAgentTextMode = msg.sender === 'agent' && agentMessageViewMode === 'text';
- // B25: an agent turn that both talks AND calls a tool can leak the provider
- // wire-format `{ content, tool_calls }` JSON envelope as its raw `content`
- // (see `unwrapToolCallEnvelope`). Unwrap agent messages to the human text so
- // no surface (home chat OR the workflow copilot, which shares this renderer)
- // ever paints raw JSON. Shape-based + a strict passthrough for ordinary
- // prose, so this is a no-op for every non-envelope message — the tool
- // activity itself renders via the timeline, so the extracted tool names are
- // intentionally dropped here.
- //
- // This call is the reason the row is memoized. `unwrapToolCallEnvelope` runs
- // a `JSON.parse` in a `try/catch`, and for ordinary prose that parse THROWS
- // and is caught. Left in the parent's `.map()` body it re-ran for every
- // settled message on every streamed token — O(N) throwaway work per token.
- // Pinned by `ChatThreadView.renderPerf.test.tsx`.
- const displayContent =
- msg.sender === 'agent' ? unwrapToolCallEnvelope(msg.content ?? '').text : (msg.content ?? '');
- // Parsed once per message: for current messages (extraMetadata present, or
- // agent messages) the content already has no markers, so this is a no-op. For
- // legacy persisted user messages with raw [IMAGE:...]/[FILE:...] markers and
- // no extraMetadata, this is what keeps the marker text out of both the
- // rendered bubble and the copy-to-clipboard action.
- const parsedContent = parseMessageImages(displayContent);
-
- return (
- <>
- {/* Past-turn process trail (Phase 5 + restore-fidelity fix 1):
- each older settled turn's interleaved reasoning/narration +
- tool steps (and restored sub-agent transcripts), collapsed,
- above the answer it produced. Falls back to tool-cards-only
- for legacy snapshots with no persisted transcript. */}
- {pastTurn ? (
- <div data-testid="past-turn-insights">
- <PastTurnInsights entries={pastTurn.entries} transcript={pastTurn.transcript} />
- </div>
- ) : null}
- <div>
- <Message from={msg.sender} data-testid="chat-message-row" data-sender={msg.sender}>
- <MessageContent className={isAgentTextMode ? 'w-full max-w-full' : 'w-fit max-w-[75%]'}>
- {msg.sender === 'agent' ? (
- <div className="space-y-1" data-testid="agent-message">
- <div className="relative space-y-1">
- {agentMessageViewMode === 'text' ? (
- <AgentMessageText content={displayContent} />
- ) : (
- splitAgentMessageIntoBubbles(displayContent).map((segment, index, parts) => {
- const position: AgentBubblePosition =
- parts.length === 1
- ? 'single'
- : index === 0
- ? 'first'
- : index === parts.length - 1
- ? 'last'
- : 'middle';
-
- return (
- <AgentMessageBubble
- key={`${msg.id}:${index}`}
- content={segment}
- position={position}
- />
- );
- })
- )}
- {/* Reaction affordance — the closed "+", the open picker,
- and the resulting reaction chips all live here, tucked
- onto the bubble's bottom-left corner so the control
- never jumps to a separate row below the timestamp. */}
- {isLatestVisible && (
- <ReactionRail
- messageId={msg.id}
- myReactions={(msg.extraMetadata?.myReactions as string[] | undefined) ?? []}
- pickerOpen={isReactionPickerOpen}
- onReact={onReact}
- onOpenReactionPicker={onOpenReactionPicker}
- />
- )}
- </div>
- {/* Stopped marker (#4862): the partial reply that was
- preserved when the user hit Stop / ESC mid-stream. */}
- {msg.extraMetadata?.stopped === true && (
- <p
- data-testid="stopped-marker"
- className="flex items-center gap-1 px-1 text-[10px] font-medium text-content-faint">
- <svg
- className="h-2.5 w-2.5"
- fill="currentColor"
- viewBox="0 0 24 24"
- aria-hidden>
- <rect x="6" y="6" width="12" height="12" rx="1.5" />
- </svg>
- {t('chat.stoppedByUser')}
- </p>
- )}
- <MessageCitations raw={msg.extraMetadata?.citations} />
- {isLatestVisible && (
- <p className="px-1 text-[10px] text-content-faint">
- {formatRelativeTime(msg.createdAt)}
- </p>
- )}
- </div>
- ) : (
- <UserTurnBody
- msg={msg}
- displayText={parsedContent.text}
- fallbackDataUris={parsedContent.dataUris}
- showTime={isLatestVisible}
- />
- )}
- <MessageAction
- analyticsId="chat-message-copy"
- label={t('chat.copyResponse')}
- onClick={() => onCopy(msg.id, parsedContent.text)}
- className={`absolute -top-1 ${
- isAgentTextMode ? 'right-0' : msg.sender === 'user' ? '-left-8' : '-right-8'
- } opacity-0 group-hover/msg:opacity-100 text-content-faint hover:text-content-secondary`}>
- {isCopied ? (
- <svg
- className="w-3.5 h-3.5 text-sage-500"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M5 13l4 4L19 7"
- />
- </svg>
- ) : (
- <svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={2}
- d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"
- />
- </svg>
- )}
- </MessageAction>
- {msg.sender === 'agent' && (
- <ShareMessageButton
- content={parsedContent.text}
- agentName={shareAgentName}
- threadId={threadId ?? undefined}
- className={`absolute top-6 ${isAgentTextMode ? 'right-0' : '-right-8'}`}
- />
- )}
- </MessageContent>
- </Message>
- </div>
- </>
- );
-}
-
-/** Citation chips, when the turn carries well-formed citation metadata. */
-function MessageCitations({ raw }: { raw: unknown }) {
- if (!Array.isArray(raw)) return null;
- const citations = raw.filter(
- (item): item is MessageCitation =>
- typeof item === 'object' &&
- item !== null &&
- typeof (item as MessageCitation).id === 'string' &&
- typeof (item as MessageCitation).key === 'string' &&
- typeof (item as MessageCitation).snippet === 'string' &&
- typeof (item as MessageCitation).timestamp === 'string'
- );
- if (citations.length === 0) return null;
- return <CitationChips citations={citations} />;
-}
-
-interface ReactionRailProps {
- messageId: string;
- myReactions: string[];
- pickerOpen: boolean;
- onReact: (messageId: string, emoji: string) => void;
- onOpenReactionPicker: (messageId: string | null) => void;
-}
-
-function ReactionRail({
- messageId,
- myReactions,
- pickerOpen,
- onReact,
- onOpenReactionPicker,
-}: ReactionRailProps) {
- const { t } = useT();
- return (
- <div className="absolute -bottom-2 left-3 z-10 flex items-center gap-1">
- {myReactions.map(emoji => (
- <button
- key={emoji}
- type="button"
- data-analytics-id="chat-message-reaction-remove"
- onClick={() => onReact(messageId, emoji)}
- className="flex items-center rounded-full border border-primary-200 bg-primary-100 px-1.5 text-xs leading-normal shadow-xs transition-colors hover:bg-primary-200 dark:border-primary-400/40 dark:bg-primary-500/25"
- title={t('chat.removeReaction').replace('{emoji}', emoji)}>
- {emoji}
- </button>
- ))}
- {pickerOpen ? (
- <div className="flex items-center gap-0.5 rounded-full bg-surface px-1 py-0.5 shadow-xs ring-1 ring-line dark:ring-line-strong">
- {REACTION_EMOJI.map(emoji => (
- <button
- key={emoji}
- type="button"
- data-analytics-id="chat-message-reaction-pick"
- onClick={() => {
- onReact(messageId, emoji);
- onOpenReactionPicker(null);
- }}
- className="rounded px-0.5 text-sm transition-transform hover:scale-125"
- title={emoji}>
- {emoji}
- </button>
- ))}
- <button
- type="button"
- data-analytics-id="chat-message-reaction-close"
- onClick={() => onOpenReactionPicker(null)}
- aria-label={t('common.close')}
- className="ml-0.5 px-0.5 text-xs text-content-secondary hover:text-content-faint dark:hover:text-content-faint">
- ✕
- </button>
- </div>
- ) : (
- <button
- type="button"
- data-analytics-id="chat-message-reaction-open"
- onClick={() => onOpenReactionPicker(messageId)}
- className="flex h-[18px] items-center rounded-full bg-surface px-1.5 text-xs leading-none text-content-muted opacity-0 shadow-xs ring-1 ring-line transition-opacity hover:bg-surface-hover hover:text-content-secondary group-hover/msg:opacity-100 dark:ring-line-strong"
- title={t('chat.addReaction')}
- aria-label={t('chat.addReaction')}>
- +
- </button>
- )}
- </div>
- );
-}
-
-/**
- * One transcript row, memoized.
- *
- * The transcript re-renders on every streamed token (the live preview reads
- * `streamingAssistantByThread`), so a settled row must be able to bail out.
- * The comparator is field-wise on `msg` — see `sameThreadMessage` — and
- * identity-wise on everything else, which is why every callback prop the parent
- * passes has to be referentially stable and why the "is this the latest
- * message?" / "is the picker open?" questions are answered as booleans by the
- * parent instead of being handed down as the ids to compare against.
- *
- * This component deliberately consumes NO Redux context: a `useSelector` or
- * `useDispatch` here would subscribe it to the store, and a context change
- * re-renders consumers regardless of `memo`.
- */
-export const TranscriptRow = memo(TranscriptRowImpl, (prev, next) => {
- return (
- prev.threadId === next.threadId &&
- prev.agentMessageViewMode === next.agentMessageViewMode &&
- prev.isLatestVisible === next.isLatestVisible &&
- prev.isCopied === next.isCopied &&
- prev.isReactionPickerOpen === next.isReactionPickerOpen &&
- prev.pastTurn === next.pastTurn &&
- prev.shareAgentName === next.shareAgentName &&
- prev.onCopy === next.onCopy &&
- prev.onReact === next.onReact &&
- prev.onOpenReactionPicker === next.onOpenReactionPicker &&
- sameThreadMessage(prev.msg, next.msg)
- );
-});
-TranscriptRow.displayName = 'TranscriptRow';
diff --git a/app/src/features/conversations/components/UserTurnBody.test.tsx b/app/src/features/conversations/components/UserTurnBody.test.tsx
deleted file mode 100644
index e1684e0eff..0000000000
--- a/app/src/features/conversations/components/UserTurnBody.test.tsx
+++ /dev/null
@@ -1,91 +0,0 @@
-import { render, screen } from '@testing-library/react';
-import { describe, expect, it } from 'vitest';
-
-import type { ThreadMessage } from '../../../types/thread';
-import { SAFE_IMAGE_DATA_URI_RE, UserTurnBody } from './UserTurnBody';
-
-const PNG_DATA_URI =
- 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==';
-
-function makeMessage(extraMetadata: Record<string, unknown> = {}): ThreadMessage {
- return {
- id: 'm-1',
- sender: 'user',
- type: 'text',
- content: 'A question?',
- extraMetadata,
- createdAt: '2026-01-01T00:00:00.000Z',
- } as ThreadMessage;
-}
-
-describe('SAFE_IMAGE_DATA_URI_RE', () => {
- it('accepts a well-formed base64 image data URI', () => {
- expect(SAFE_IMAGE_DATA_URI_RE.test(PNG_DATA_URI)).toBe(true);
- });
-
- it('rejects a non-image or script-bearing URI', () => {
- expect(SAFE_IMAGE_DATA_URI_RE.test('javascript:alert(1)')).toBe(false);
- expect(SAFE_IMAGE_DATA_URI_RE.test('data:text/html;base64,PHNjcmlwdD4=')).toBe(false);
- });
-});
-
-describe('UserTurnBody', () => {
- it('renders the turn text', () => {
- render(
- <UserTurnBody
- msg={makeMessage()}
- displayText="A question?"
- fallbackDataUris={[]}
- showTime={false}
- />
- );
-
- expect(screen.getByText('A question?')).toBeInTheDocument();
- });
-
- it('renders a timestamp only when asked for one', () => {
- const { container, rerender } = render(
- <UserTurnBody msg={makeMessage()} displayText="Hi" fallbackDataUris={[]} showTime={false} />
- );
- const withoutTime = container.textContent ?? '';
-
- rerender(<UserTurnBody msg={makeMessage()} displayText="Hi" fallbackDataUris={[]} showTime />);
-
- expect(withoutTime.trim()).toBe('Hi');
- expect((container.textContent ?? '').length).toBeGreaterThan(withoutTime.length);
- });
-
- it('renders file attachment chips from persisted metadata', () => {
- render(
- <UserTurnBody
- msg={makeMessage({
- attachmentKinds: ['file', 'video'],
- attachmentNames: ['spec.pdf', 'clip.mp4'],
- })}
- displayText=""
- fallbackDataUris={[]}
- showTime={false}
- />
- );
-
- expect(screen.getByText('spec.pdf')).toBeInTheDocument();
- expect(screen.getByText('clip.mp4')).toBeInTheDocument();
- });
-
- it('drops an attachment URI that is not a safe image data URI', () => {
- render(
- <UserTurnBody
- msg={makeMessage({ attachmentDataUris: ['javascript:alert(1)', PNG_DATA_URI] })}
- displayText=""
- fallbackDataUris={[]}
- showTime={false}
- />
- );
-
- // Exactly one image survives the filter, and its `src` is never the
- // rejected value.
- const images = screen.getAllByRole('presentation', { hidden: true });
- expect(images).toHaveLength(1);
- expect(images[0].getAttribute('src')).not.toContain('javascript:');
- });
-});
diff --git a/app/src/features/conversations/components/UserTurnBody.tsx b/app/src/features/conversations/components/UserTurnBody.tsx
deleted file mode 100644
index a06005b7be..0000000000
--- a/app/src/features/conversations/components/UserTurnBody.tsx
+++ /dev/null
@@ -1,175 +0,0 @@
-import { useEffect, useState } from 'react';
-
-import type { ThreadMessage } from '../../../types/thread';
-import { formatRelativeTime } from '../utils/format';
-import { BubbleMarkdown } from './AgentMessageBubble';
-
-// Matches only well-formed base64 image data URIs — guards against an
-// `<img src>` XSS vector if a persisted message ever carried a crafted
-// value in `attachmentDataUris`/legacy `[IMAGE:...]` markers.
-export const SAFE_IMAGE_DATA_URI_RE =
- /^data:(image\/(?:png|jpe?g|gif|webp|bmp));base64,([a-z0-9+/=\s]+)$/i;
-const EMPTY_IMAGE_SRC = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';
-
-function imageDataUriToObjectUrl(src: string): string | null {
- const match = SAFE_IMAGE_DATA_URI_RE.exec(src);
- if (!match) return null;
- try {
- const mime = match[1];
- const binary = atob(match[2].replace(/\s/g, ''));
- const bytes = new Uint8Array(binary.length);
- for (let i = 0; i < binary.length; i += 1) {
- bytes[i] = binary.charCodeAt(i);
- }
- return URL.createObjectURL(new Blob([bytes], { type: mime }));
- } catch {
- return null;
- }
-}
-
-function AttachmentImage({ dataUri }: { dataUri: string }) {
- const [objectUrl, setObjectUrl] = useState<string | null>(null);
-
- useEffect(() => {
- const nextUrl = imageDataUriToObjectUrl(dataUri);
- setObjectUrl(nextUrl);
- return () => {
- if (nextUrl) URL.revokeObjectURL(nextUrl);
- };
- }, [dataUri]);
-
- return (
- <img
- src={objectUrl ?? EMPTY_IMAGE_SRC}
- alt=""
- className="max-w-[200px] max-h-[200px] rounded-2xl object-cover"
- />
- );
-}
-
-export interface UserTurnBodyProps {
- msg: ThreadMessage;
- displayText: string;
- fallbackDataUris: string[];
- showTime: boolean;
-}
-
-/**
- * A user turn: its attachments (images, videos, files) above its bubble.
- *
- * Split out of `TranscriptRow` because the attachment rendering — three kinds
- * of chip, plus the object-URL lifecycle behind `AttachmentImage` — is the bulk
- * of the row's code and none of it is reached on the agent side.
- */
-export function UserTurnBody({ msg, displayText, fallbackDataUris, showTime }: UserTurnBodyProps) {
- const dataUris = (
- Array.isArray(msg.extraMetadata?.attachmentDataUris)
- ? (msg.extraMetadata.attachmentDataUris as string[])
- : fallbackDataUris
- ).filter(src => SAFE_IMAGE_DATA_URI_RE.test(src));
- // Document attachments carry no image data-URI (only images do); surface them
- // as filename chips from the persisted attachmentKinds/attachmentNames metadata.
- const kinds = Array.isArray(msg.extraMetadata?.attachmentKinds)
- ? (msg.extraMetadata.attachmentKinds as string[])
- : [];
- const names = Array.isArray(msg.extraMetadata?.attachmentNames)
- ? (msg.extraMetadata.attachmentNames as string[])
- : [];
- const fileNames = kinds
- .map((k, i) => (k === 'file' ? names[i] : null))
- .filter((n): n is string => Boolean(n));
- const posters = Array.isArray(msg.extraMetadata?.attachmentPosters)
- ? (msg.extraMetadata.attachmentPosters as (string | null)[])
- : [];
- const videoItems = kinds
- .map((k, i) => (k === 'video' ? { name: names[i] ?? '', poster: posters[i] ?? null } : null))
- .filter((v): v is { name: string; poster: string | null } => Boolean(v));
-
- return (
- <div className="flex flex-col items-end gap-1">
- {dataUris.length > 0 && (
- <div className="flex flex-wrap gap-1.5 justify-end">
- {dataUris.map((uri, i) => (
- <AttachmentImage key={i} dataUri={uri} />
- ))}
- </div>
- )}
- {videoItems.length > 0 && (
- <div className="flex flex-wrap gap-1.5 justify-end">
- {videoItems.map((video, i) => (
- <div
- key={i}
- className="relative flex items-center gap-2 rounded-lg border border-line bg-surface-muted px-2.5 py-1.5 text-xs text-content-secondary max-w-[220px]">
- {video.poster ? (
- <div className="relative w-10 h-10 shrink-0">
- <img src={video.poster} alt="" className="w-10 h-10 rounded object-cover" />
- <span className="absolute inset-0 flex items-center justify-center">
- <svg
- className="w-4 h-4 text-content-inverted drop-shadow-sm"
- fill="currentColor"
- viewBox="0 0 24 24">
- <path d="M8 5v14l11-7z" />
- </svg>
- </span>
- </div>
- ) : (
- <svg
- className="w-4 h-4 shrink-0 text-content-muted"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={1.8}
- d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 6h8a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2z"
- />
- </svg>
- )}
- <span className="truncate font-medium">{video.name}</span>
- </div>
- ))}
- </div>
- )}
- {fileNames.length > 0 && (
- <div className="flex flex-wrap gap-1.5 justify-end">
- {fileNames.map((name, i) => (
- <div
- key={i}
- className="flex items-center gap-2 rounded-lg border border-line bg-surface-muted px-2.5 py-1.5 text-xs text-content-secondary max-w-[220px]">
- <svg
- className="w-4 h-4 shrink-0 text-content-muted"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={1.8}
- d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"
- />
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={1.8}
- d="M14 2v6h6"
- />
- </svg>
- <span className="truncate font-medium">{name}</span>
- </div>
- ))}
- </div>
- )}
- {(displayText || showTime) && (
- <div className="rounded-2xl px-4 py-2.5 bg-primary-500 text-content-inverted rounded-br-md wrap-break-word wrap-anywhere overflow-hidden">
- {displayText && <BubbleMarkdown content={displayText} tone="user" />}
- {showTime && (
- <p className={`${displayText ? 'mt-1' : ''} text-[10px] text-content-inverted/60`}>
- {formatRelativeTime(msg.createdAt)}
- </p>
- )}
- </div>
- )}
- </div>
- );
-}
diff --git a/app/src/features/conversations/components/aui/AgentInsightsSlot.test.tsx b/app/src/features/conversations/components/aui/AgentInsightsSlot.test.tsx
deleted file mode 100644
index 8a765ad4f6..0000000000
--- a/app/src/features/conversations/components/aui/AgentInsightsSlot.test.tsx
+++ /dev/null
@@ -1,58 +0,0 @@
-import { render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
-
-import type { ProcessingTranscriptItem } from '../../../../store/chatRuntimeSlice';
-import { AgentInsightsSlot } from './AgentInsightsSlot';
-
-vi.mock('../../../../lib/i18n/I18nContext', () => ({
- useT: () => ({ t: (key: string, fallback?: string) => fallback ?? key, locale: 'en' }),
-}));
-
-const thinking: ProcessingTranscriptItem[] = [
- { kind: 'thinking', round: 1, seq: 0, text: 'Planning a Kashmir itinerary.' },
-];
-
-function renderSlot(props: Partial<Parameters<typeof AgentInsightsSlot>[0]> = {}) {
- return render(
- <AgentInsightsSlot
- entries={[]}
- transcript={thinking}
- turnActive={false}
- timelineBeforeLatestAnswer={false}
- hideAgentInsights={false}
- onViewDetails={() => {}}
- onViewWholeRun={() => {}}
- {...props}
- />
- );
-}
-
-describe('AgentInsightsSlot before the first tool call', () => {
- it('streams the live thought inline while the turn is in flight', () => {
- renderSlot({ turnActive: true });
- expect(screen.getByTestId('agent-insights-live')).toBeTruthy();
- expect(screen.getByTestId('processing-thinking-live').textContent).toContain(
- 'Planning a Kashmir itinerary.'
- );
- // The whole-run opener stays reachable.
- expect(screen.getByTestId('view-process-source')).toBeTruthy();
- });
-
- it('falls back to the static opener once the turn has settled', () => {
- renderSlot({ turnActive: false });
- expect(screen.queryByTestId('agent-insights-live')).toBeNull();
- expect(screen.queryByTestId('processing-thinking-live')).toBeNull();
- expect(screen.getByTestId('view-process-source')).toBeTruthy();
- });
-
- it('respects "hide agent insights" and shows only the processing link', () => {
- renderSlot({ turnActive: true, hideAgentInsights: true });
- expect(screen.queryByTestId('agent-insights-live')).toBeNull();
- expect(screen.getByTestId('agent-processing-link')).toBeTruthy();
- });
-
- it('renders nothing with neither steps nor transcript', () => {
- const { container } = renderSlot({ turnActive: true, transcript: [] });
- expect(container.innerHTML).toBe('');
- });
-});
diff --git a/app/src/features/conversations/components/aui/AgentInsightsSlot.tsx b/app/src/features/conversations/components/aui/AgentInsightsSlot.tsx
deleted file mode 100644
index b226a38c03..0000000000
--- a/app/src/features/conversations/components/aui/AgentInsightsSlot.tsx
+++ /dev/null
@@ -1,143 +0,0 @@
-import { useT } from '../../../../lib/i18n/I18nContext';
-import type {
- ProcessingTranscriptItem,
- ToolTimelineEntry,
-} from '../../../../store/chatRuntimeSlice';
-import { ProcessingTranscriptView } from '../ProcessingTranscriptView';
-import { ToolTimelineBlock } from '../ToolTimelineBlock';
-
-export interface AgentInsightsSlotProps {
- entries: ToolTimelineEntry[];
- transcript: ProcessingTranscriptItem[];
- /** True while a turn is in flight on this thread. */
- turnActive: boolean;
- /** True when the settled timeline renders above the latest agent answer. */
- timelineBeforeLatestAnswer: boolean;
- /** `themeSlice.hideAgentInsights` — suppresses the verbose step rows. */
- hideAgentInsights: boolean;
- onViewDetails: (entry: ToolTimelineEntry) => void;
- onViewWholeRun: () => void;
-}
-
-/**
- * The "Agentic task insights" slot: the inline step timeline plus the openers
- * that reach the full Agent Process Source panel.
- *
- * Extracted from `ChatThreadView` verbatim — every `data-testid` here
- * (`agent-processing-link`, `agent-process-source-fallback`,
- * `view-process-source`) is selected on by WDIO specs and must not move.
- *
- * Returns `null` when the thread has neither tool steps nor a persisted
- * reasoning/narration transcript. The transcript guard is not redundant: a
- * tool-less turn (the agent only thinks or narrates) has an empty timeline but
- * still persists thoughts, and without it those thoughts are unreachable.
- */
-export function AgentInsightsSlot({
- entries,
- transcript,
- turnActive,
- timelineBeforeLatestAnswer,
- hideAgentInsights,
- onViewDetails,
- onViewWholeRun,
-}: AgentInsightsSlotProps) {
- const { t } = useT();
- if (entries.length === 0 && transcript.length === 0) return null;
-
- return (
- <>
- {hideAgentInsights ? (
- // "Hide agent thinking" is ON: suppress the verbose step rows. While in
- // flight, surface a compact blinking "Processing" link; once settled the
- // "View full agent process Source" opener below takes over (so only
- // render this fallback when that opener won't).
- turnActive ? (
- <button
- type="button"
- onClick={onViewWholeRun}
- data-testid="agent-processing-link"
- className="flex items-center gap-1.5 px-1 py-1 text-[11px] font-medium text-primary-600 hover:underline dark:text-primary-300">
- <span className="inline-block w-1.5 h-1.5 rounded-full bg-primary-400 animate-pulse" />
- <span>{t('conversations.agentTaskInsights.processing')} →</span>
- </button>
- ) : !timelineBeforeLatestAnswer ? (
- <button
- type="button"
- onClick={onViewWholeRun}
- data-testid="agent-process-source-fallback"
- className="px-1 text-[11px] font-medium text-primary-600 hover:underline dark:text-primary-300">
- {t('conversations.agentTaskInsights.viewProcessSource')} →
- </button>
- ) : null
- ) : entries.length > 0 ? (
- <ToolTimelineBlock
- entries={entries}
- onViewDetails={onViewDetails}
- onViewWholeRun={onViewWholeRun}
- // `turnActive` is the caller's `isSending`, deliberately NOT a raw
- // `in` membership check on `inferenceTurnLifecycleByThread`: that map
- // also carries `'interrupted'` entries (a turn that crashed mid-flight
- // in a PRIOR core process, written by `hydrateRuntimeFromSnapshot` on
- // cold boot) which have no live driver and must NOT read as an active
- // turn, or stale disclosure state leaks into a later retry.
- turnActive={turnActive}
- // Interleaved narration + thinking + tool steps in stream order.
- // Renders 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 of the turn.
- transcript={transcript}
- />
- ) : turnActive ? (
- // In flight with no tool call yet — the time-to-first-token window,
- // where a reasoning model streams only `thinking_delta`s. Render the
- // live transcript inline (trailing thought expanded) so the user sees
- // the agent working instead of a static opener; the timeline above
- // takes over the moment the first tool call lands.
- <div className="space-y-1.5" data-testid="agent-insights-live">
- <button
- type="button"
- onClick={onViewWholeRun}
- data-testid="view-process-source"
- className="flex items-center gap-1.5 px-1 py-1 text-left">
- <span className="text-[13px] font-medium text-content-muted">
- {t('conversations.agentTaskInsights.title')}
- </span>
- <span className="text-[13px] font-medium text-primary-600 dark:text-primary-300">
- →
- </span>
- </button>
- <div className="px-1">
- <ProcessingTranscriptView transcript={transcript} entries={entries} live />
- </div>
- </div>
- ) : (
- // Transcript-only turn: reasoning/narration was streamed but no tool
- // calls were made, so the inline step timeline is empty. The thoughts
- // are still persisted — surface a standalone opener (matching the
- // settled insights header) so the full-run panel stays reachable.
- <button
- type="button"
- onClick={onViewWholeRun}
- data-testid="view-process-source"
- className="flex items-center gap-1.5 px-1 py-1 text-left">
- <span className="text-[13px] font-medium text-content-muted">
- {t('conversations.agentTaskInsights.title')}
- </span>
- <span className="text-[13px] font-medium text-primary-600 dark:text-primary-300">→</span>
- </button>
- )}
- {/* "View full agent process Source" — only needed in the hidden-insights
- settled state; when the timeline is visible the link lives in its
- header (ToolTimelineBlock onViewWholeRun). */}
- {timelineBeforeLatestAnswer && hideAgentInsights && (
- <button
- type="button"
- onClick={onViewWholeRun}
- data-testid="view-process-source"
- className="px-1 text-[11px] font-medium text-primary-600 hover:underline dark:text-primary-300">
- {t('conversations.agentTaskInsights.viewProcessSource')} →
- </button>
- )}
- </>
- );
-}
diff --git a/app/src/features/conversations/components/aui/AuiPlainText.test.tsx b/app/src/features/conversations/components/aui/AuiPlainText.test.tsx
deleted file mode 100644
index 5ad5e828eb..0000000000
--- a/app/src/features/conversations/components/aui/AuiPlainText.test.tsx
+++ /dev/null
@@ -1,37 +0,0 @@
-/**
- * The headless message-part leaf must behave identically with and without an
- * assistant-ui runtime above it.
- *
- * That is not a nicety: `ChatThreadView` is mounted under a bare Redux
- * `Provider` by several unit tests (including the byte-frozen render-cost
- * benchmark), and assistant-ui's default client throws on a direct scope read.
- * `TextMessagePartProvider` synthesises its own `part` scope, which is why this
- * works — and this file is what stops that from silently regressing.
- */
-import { render, screen } from '@testing-library/react';
-import { describe, expect, it } from 'vitest';
-
-import { AuiPlainText } from './AuiPlainText';
-
-const CARET = <span data-testid="test-caret" />;
-
-describe('AuiPlainText', () => {
- it('renders its text with no runtime mounted', () => {
- render(<AuiPlainText text="hello tail" />);
- expect(screen.getByText('hello tail')).toBeInTheDocument();
- });
-
- it('shows the in-progress affordance only while the part is running', () => {
- const { rerender } = render(<AuiPlainText text="partial" isRunning caret={CARET} />);
- expect(screen.getByTestId('test-caret')).toBeInTheDocument();
-
- rerender(<AuiPlainText text="partial" isRunning={false} caret={CARET} />);
- expect(screen.queryByTestId('test-caret')).not.toBeInTheDocument();
- });
-
- it('omits the in-progress slot entirely when no caret is supplied', () => {
- render(<AuiPlainText text="settled" isRunning />);
- expect(screen.queryByTestId('test-caret')).not.toBeInTheDocument();
- expect(screen.getByText('settled')).toBeInTheDocument();
- });
-});
diff --git a/app/src/features/conversations/components/aui/AuiPlainText.tsx b/app/src/features/conversations/components/aui/AuiPlainText.tsx
deleted file mode 100644
index 0bfddedcb3..0000000000
--- a/app/src/features/conversations/components/aui/AuiPlainText.tsx
+++ /dev/null
@@ -1,45 +0,0 @@
-import { MessagePartPrimitive, TextMessagePartProvider } from '@assistant-ui/react';
-
-export interface AuiPlainTextProps {
- /** The text to render. Plain text — never Markdown. */
- text: string;
- /** True while the text is still growing, which drives the caret below. */
- isRunning?: boolean;
- /** Token classes for the rendered `<span>`. */
- className?: string;
- /** Rendered only while `isRunning`, via `MessagePartPrimitive.InProgress`. */
- caret?: React.ReactNode;
-}
-
-/**
- * Plain text rendered through assistant-ui's HEADLESS message-part primitives.
- *
- * `TextMessagePartProvider` synthesises a `part` scope from a bare string, so
- * `MessagePartPrimitive.Text` and `MessagePartPrimitive.InProgress` work here
- * without a thread runtime, a message index, or a `MessagePrimitive.Root`
- * ancestor. That matters: the transcript is mounted both under a runtime (the
- * app) and without one (several unit tests), and this component must render
- * identically in both.
- *
- * Why the caret is a primitive rather than a `{isRunning && ...}`: the running
- * state now lives in the part scope, so a single source decides both the text
- * and whether it is still arriving. There is no way for the two to disagree.
- *
- * `smooth` is OFF deliberately. assistant-ui's smooth reveal animates text in
- * over `requestAnimationFrame` ticks; on the live streaming tail that would add
- * a render per frame on top of a render per token, in the exact hot path
- * `ChatThreadView.renderPerf.test.tsx` exists to protect.
- *
- * Styling is OpenHuman semantic tokens only — the primitives ship no CSS, which
- * is the whole reason the headless layer was chosen over `@assistant-ui/styles`
- * (compiled Tailwind v4: `color-mix()` / `oklch()` / `@property`, none of which
- * esbuild downlevels for this repo's `safari15` CSS target).
- */
-export function AuiPlainText({ text, isRunning = false, className, caret }: AuiPlainTextProps) {
- return (
- <TextMessagePartProvider text={text} isRunning={isRunning}>
- <MessagePartPrimitive.Text smooth={false} className={className} />
- {caret ? <MessagePartPrimitive.InProgress>{caret}</MessagePartPrimitive.InProgress> : null}
- </TextMessagePartProvider>
- );
-}
diff --git a/app/src/features/conversations/components/aui/StreamingPreview.tsx b/app/src/features/conversations/components/aui/StreamingPreview.tsx
deleted file mode 100644
index 7b792ee130..0000000000
--- a/app/src/features/conversations/components/aui/StreamingPreview.tsx
+++ /dev/null
@@ -1,104 +0,0 @@
-import { useT } from '../../../../lib/i18n/I18nContext';
-import { AuiPlainText } from './AuiPlainText';
-
-/** Maximum trailing characters rendered in a live-streaming preview bubble.
- * The full response is revealed via `addInferenceResponse` on `chat_done` —
- * this is purely a ticker-tape affordance to signal progress without jumping
- * the scroll position as tokens arrive. */
-export const STREAMING_PREVIEW_CHARS = 120;
-
-/** The blinking caret at the tail of an in-flight preview. Rendered by
- * `MessagePartPrimitive.InProgress`, so it disappears the moment the part
- * scope stops reporting `running` — no separate visibility condition. */
-const StreamingCaret = (
- <span className="inline-block w-1 h-3 ml-0.5 align-middle bg-primary-400 animate-pulse" />
-);
-
-function PreviewBubble({ content, bordered }: { content: string; bordered?: boolean }) {
- return (
- <div
- className={`rounded-2xl rounded-bl-md px-3 py-1.5 bg-surface-strong/80 dark:bg-surface-muted text-content ${
- bordered ? 'border-l-2 border-primary-400/60' : ''
- }`}>
- <p className="text-xs text-content-secondary font-mono whitespace-pre-wrap wrap-break-word leading-snug">
- {content.length > STREAMING_PREVIEW_CHARS && <span className="text-content-faint">…</span>}
- <AuiPlainText
- text={content.slice(-STREAMING_PREVIEW_CHARS)}
- isRunning
- caret={StreamingCaret}
- />
- </p>
- </div>
- );
-}
-
-/**
- * The primary in-flight assistant preview.
- *
- * Reasoning is deliberately NOT rendered here — the rail above renders the same
- * reasoning through `ProcessingTranscriptView`, interleaved with the narration
- * and tool steps it happened between. A separate bubble would show it twice
- * with two lifetimes. The in-flight ANSWER preview is what stays: that is the
- * terminal response streaming in.
- */
-export function StreamingAssistantPreview({ content }: { content: string }) {
- if (content.length === 0) return null;
- return (
- <div className="flex justify-start">
- <div className="relative w-fit max-w-[75%]">
- <PreviewBubble content={content} />
- </div>
- </div>
- );
-}
-
-export interface ParallelBranchStream {
- requestId: string;
- content: string;
- thinking: string;
-}
-
-/**
- * Concurrent (forked) turns on the same thread, each in its own labeled bubble
- * so they do not collide with the primary stream above.
- */
-export function ParallelBranchPreviews({ branches }: { branches: ParallelBranchStream[] }) {
- const { t } = useT();
- return (
- <>
- {branches.map(branch =>
- branch.content.length > 0 || branch.thinking.length > 0 ? (
- <div key={branch.requestId} className="flex justify-start">
- <div className="relative w-fit max-w-[75%]">
- <div className="mb-1 flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-wide text-primary-500 dark:text-primary-400">
- <span className="inline-block w-1.5 h-1.5 rounded-full bg-primary-400 animate-pulse" />
- <span>{t('chat.parallelBranchLabel')}</span>
- </div>
- {branch.content.length > 0 && <PreviewBubble content={branch.content} bordered />}
- </div>
- </div>
- ) : null
- )}
- </>
- );
-}
-
-/**
- * The three-dot placeholder shown between "turn accepted" and "first token".
- *
- * Suppressed by the caller once streaming output has started — the preview
- * bubble above takes over as the activity indicator from that point.
- */
-export function TypingIndicator() {
- return (
- <div className="flex justify-start">
- <div className="bg-surface-strong/80 dark:bg-surface-muted rounded-2xl rounded-bl-md px-4 py-3">
- <div className="flex items-center gap-1">
- <span className="w-1.5 h-1.5 rounded-full bg-surface-muted dark:bg-surface-muted/600 animate-bounce [animation-delay:0ms]" />
- <span className="w-1.5 h-1.5 rounded-full bg-surface-muted dark:bg-surface-muted/600 animate-bounce [animation-delay:150ms]" />
- <span className="w-1.5 h-1.5 rounded-full bg-surface-muted dark:bg-surface-muted/600 animate-bounce [animation-delay:300ms]" />
- </div>
- </div>
- </div>
- );
-}
diff --git a/app/src/features/conversations/components/aui/TranscriptStates.tsx b/app/src/features/conversations/components/aui/TranscriptStates.tsx
deleted file mode 100644
index 2e03cc6da3..0000000000
--- a/app/src/features/conversations/components/aui/TranscriptStates.tsx
+++ /dev/null
@@ -1,48 +0,0 @@
-import { useT } from '../../../../lib/i18n/I18nContext';
-
-/** Placeholder bubbles shown while a thread's messages are being fetched. */
-export function TranscriptSkeleton() {
- return (
- <div className="mx-auto w-full max-w-195 space-y-4 px-5 py-4">
- {Array.from({ length: 4 }).map((_, i) => (
- <div key={i} className={`flex ${i % 2 === 0 ? 'justify-start' : 'justify-end'}`}>
- <div
- className={`h-12 rounded-2xl animate-pulse bg-surface-subtle ${
- i % 2 === 0 ? 'w-2/3' : 'w-1/2'
- }`}
- />
- </div>
- ))}
- </div>
- );
-}
-
-/** Terminal state for a thread whose message history failed to load. */
-export function TranscriptLoadError({ message }: { message: string }) {
- const { t } = useT();
- return (
- <div className="flex-1 flex flex-col items-center justify-center h-full">
- <svg
- className="w-8 h-8 text-coral-500/70 mb-3"
- fill="none"
- stroke="currentColor"
- viewBox="0 0 24 24">
- <path
- strokeLinecap="round"
- strokeLinejoin="round"
- strokeWidth={1.5}
- d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
- />
- </svg>
- <p className="text-sm text-content-faint mb-1">{t('chat.failedToLoadMessages')}</p>
- <p className="text-xs text-content-secondary mb-3 text-center">{message}</p>
- <button
- type="button"
- data-analytics-id="chat-messages-reload"
- onClick={() => window.location.reload()}
- className="text-xs text-primary-400 hover:text-primary-300 transition-colors">
- {t('common.reload')}
- </button>
- </div>
- );
-}
diff --git a/app/src/features/conversations/derived/derivedRestore.render.test.tsx b/app/src/features/conversations/derived/derivedRestore.render.test.tsx
deleted file mode 100644
index 1d7a6e1009..0000000000
--- a/app/src/features/conversations/derived/derivedRestore.render.test.tsx
+++ /dev/null
@@ -1,86 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react';
-import { Provider } from 'react-redux';
-import { describe, expect, it } from 'vitest';
-
-import { store } from '../../../store';
-import type { DerivedDisplayItem } from '../../../types/derivedTranscript';
-import { PastTurnInsights } from '../components/PastTurnInsights';
-import { mapDisplayItems } from './mapDisplayItems';
-
-function renderInStore(ui: React.ReactNode) {
- return render(<Provider store={store}>{ui}</Provider>);
-}
-
-/** Newest-first page from chronological items (as the RPC returns). */
-function newestFirst(chronological: DerivedDisplayItem[]): DerivedDisplayItem[] {
- return [...chronological].reverse();
-}
-
-describe('derived transcript restore (mapper → PastTurnInsights)', () => {
- it('renders a restored turn with reasoning, tool rows, and a sub-agent trail', () => {
- // A settled turn's projected display items, exactly as `threads_transcript_get`
- // returns them (newest-first). This is a NON-newest turn so the mapper keeps it.
- const chronological: DerivedDisplayItem[] = [
- { kind: 'turnBoundary', requestId: 'req-1' },
- { kind: 'userMessage', content: 'research this', requestId: 'req-1' },
- { kind: 'reasoning', text: 'planning the research' },
- { kind: 'assistantMessage', content: 'searching now', interim: true, requestId: 'req-1' },
- {
- kind: 'toolCall',
- callId: 'c1',
- name: 'read_file',
- args: { path: 'notes.md' },
- result: 'ok',
- status: 'success',
- },
- {
- kind: 'subagent',
- id: 'researcher',
- items: [
- { kind: 'reasoning', text: 'child reasoning trail' },
- {
- kind: 'toolCall',
- callId: 'child-1',
- name: 'web_search',
- args: { q: 'topic' },
- result: 'hits',
- status: 'success',
- },
- ],
- },
- { kind: 'assistantMessage', content: 'the final answer', requestId: 'req-1' },
- // A later turn so req-1 is not the newest (which the mapper would skip).
- { kind: 'turnBoundary', requestId: 'req-2' },
- { kind: 'reasoning', text: 'newest turn thought' },
- ];
-
- const { timelines, transcripts } = mapDisplayItems(newestFirst(chronological));
-
- renderInStore(
- <PastTurnInsights entries={timelines['req-1']} transcript={transcripts['req-1']} />
- );
-
- // Reasoning replays.
- expect(screen.getByTestId('processing-thinking').textContent).toContain(
- 'planning the research'
- );
- // Interim narration replays (not the final answer — that renders from the message).
- expect(screen.getByTestId('processing-transcript').textContent).toContain('searching now');
- expect(screen.getByTestId('processing-transcript').textContent).not.toContain(
- 'the final answer'
- );
- // Tool rows render.
- expect(screen.getAllByTestId('processing-tool-row').length).toBeGreaterThan(0);
- // The sub-agent's own reasoning trail renders beneath.
- const subagents = screen.getByTestId('past-turn-subagents');
- // Assert the trigger before clicking: a bare `querySelector('button')!`
- // throws an opaque TypeError at the click, pointing the stack at the click
- // rather than at the element that was never rendered.
- const subagentTrigger = screen
- .getByTestId('assistant-ui-subagent-call')
- .querySelector('button');
- expect(subagentTrigger).not.toBeNull();
- fireEvent.click(subagentTrigger as HTMLElement);
- expect(subagents.textContent).toContain('child reasoning trail');
- });
-});
diff --git a/app/src/features/conversations/timeline/selectors.test.ts b/app/src/features/conversations/timeline/selectors.test.ts
deleted file mode 100644
index 64b63b5e84..0000000000
--- a/app/src/features/conversations/timeline/selectors.test.ts
+++ /dev/null
@@ -1,299 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import type { StreamingAssistantState, ToolTimelineEntry } from '../../../store/chatRuntimeSlice';
-import type { RootState } from '../../../store/index';
-import type { ThreadMessage } from '../../../types/thread';
-import { buildThreadTimeline, groupTimelineIntoTurns, selectTimelineForThread } from './selectors';
-import { LEGACY_TURN_ID, type TimelineItem } from './types';
-
-const THREAD = 't1';
-
-function userMsg(
- id: string,
- content = `u-${id}`,
- extra: Record<string, unknown> = {}
-): ThreadMessage {
- return {
- id,
- content,
- type: 'text',
- extraMetadata: extra,
- sender: 'user',
- createdAt: '2026-01-01T00:00:00Z',
- };
-}
-function agentMsg(
- id: string,
- content = `a-${id}`,
- extra: Record<string, unknown> = {}
-): ThreadMessage {
- return {
- id,
- content,
- type: 'text',
- extraMetadata: extra,
- sender: 'agent',
- createdAt: '2026-01-01T00:00:01Z',
- };
-}
-function tool(
- id: string,
- name: string,
- round = 0,
- status: ToolTimelineEntry['status'] = 'success'
-): ToolTimelineEntry {
- return { id, name, round, seq: 0, status };
-}
-function subagentRow(id: string, taskId: string, round = 0): ToolTimelineEntry {
- return {
- id,
- name: 'subagent:researcher',
- round,
- seq: 0,
- status: 'running',
- subagent: { taskId, agentId: 'researcher', toolCalls: [] },
- };
-}
-function stream(requestId: string, content: string, thinking = ''): StreamingAssistantState {
- return { requestId, content, thinking };
-}
-
-function build(partial: Partial<Parameters<typeof buildThreadTimeline>[0]>): TimelineItem[] {
- return buildThreadTimeline({
- threadId: THREAD,
- messages: [],
- toolTimeline: [],
- streaming: null,
- parallelStreams: [],
- hideAgentInsights: false,
- ...partial,
- });
-}
-
-const kinds = (items: TimelineItem[]) => items.map(i => i.kind);
-const ids = (items: TimelineItem[]) => items.map(i => i.id);
-
-describe('buildThreadTimeline — ordering', () => {
- it('emits messages in stored order with monotonic seq, all in the legacy turn', () => {
- const items = build({ messages: [userMsg('u1'), agentMsg('a1')] });
- expect(kinds(items)).toEqual(['userMessage', 'assistantMessage']);
- expect(items.map(i => i.seq)).toEqual([0, 1]);
- expect(items.every(i => i.turnId === LEGACY_TURN_ID)).toBe(true);
- expect(items.every(i => i.threadId === THREAD)).toBe(true);
- });
-
- it('anchors the tool timeline immediately after the last user message', () => {
- // Thread: u1, a1, u2, a2 — anchor is u2, so process rows sit between u2 and a2.
- const items = build({
- messages: [userMsg('u1'), agentMsg('a1'), userMsg('u2'), agentMsg('a2')],
- toolTimeline: [tool('call1', 'read_file', 0), tool('call2', 'write_file', 1)],
- });
- expect(kinds(items)).toEqual([
- 'userMessage', // u1
- 'assistantMessage', // a1
- 'userMessage', // u2 (anchor)
- 'toolCall', // call1
- 'toolCall', // call2
- 'assistantMessage', // a2
- ]);
- expect(ids(items)).toEqual(['u1', 'a1', 'u2', 'call1', 'call2', 'a2']);
- // seq is monotonic across the spliced process block.
- expect(items.map(i => i.seq)).toEqual([0, 1, 2, 3, 4, 5]);
- });
-
- it('preserves tool-timeline array order and maps success→ok', () => {
- const items = build({
- messages: [userMsg('u1')],
- toolTimeline: [
- tool('c1', 'a', 0, 'success'),
- tool('c2', 'b', 0, 'error'),
- tool('c3', 'c', 1, 'running'),
- ],
- });
- const calls = items.filter(i => i.kind === 'toolCall');
- expect(calls.map(c => (c.kind === 'toolCall' ? c.status : null))).toEqual([
- 'ok',
- 'error',
- 'running',
- ]);
- expect(calls.map(c => c.id)).toEqual(['c1', 'c2', 'c3']);
- });
-
- it('classifies subagent:* rows as subagentActivity with the taskId', () => {
- const items = build({
- messages: [userMsg('u1')],
- toolTimeline: [subagentRow('row1', 'sub-42', 0)],
- });
- const sub = items.find(i => i.kind === 'subagentActivity');
- expect(sub).toBeDefined();
- expect(sub && sub.kind === 'subagentActivity' && sub.taskId).toBe('sub-42');
- });
-});
-
-describe('buildThreadTimeline — legacy / proactive fallbacks', () => {
- it('empty thread yields no items', () => {
- expect(build({})).toEqual([]);
- });
-
- it('proactive thread with no user message trails process items after the messages (L2669 fallback)', () => {
- const items = build({
- messages: [agentMsg('a1'), agentMsg('a2')],
- toolTimeline: [tool('c1', 'read_file', 0)],
- });
- expect(kinds(items)).toEqual(['assistantMessage', 'assistantMessage', 'toolCall']);
- expect(ids(items)).toEqual(['a1', 'a2', 'c1']);
- });
-
- it('drops hidden messages before anchoring', () => {
- const items = build({
- messages: [userMsg('u1'), userMsg('u2', 'hidden', { hidden: true }), agentMsg('a1')],
- toolTimeline: [tool('c1', 'x', 0)],
- });
- // u2 is hidden, so the anchor is u1 — process rows sit between u1 and a1.
- expect(ids(items)).toEqual(['u1', 'c1', 'a1']);
- });
-});
-
-describe('buildThreadTimeline — hideAgentInsights', () => {
- it('omits tool/subagent process items when hidden but keeps messages', () => {
- const items = build({
- messages: [userMsg('u1'), agentMsg('a1')],
- toolTimeline: [tool('c1', 'x', 0), subagentRow('row1', 'sub-1', 0)],
- hideAgentInsights: true,
- });
- expect(kinds(items)).toEqual(['userMessage', 'assistantMessage']);
- });
-
- it('keeps the streaming preview (answer) even when insights are hidden', () => {
- const items = build({
- messages: [userMsg('u1')],
- toolTimeline: [tool('c1', 'x', 0)],
- streaming: stream('req1', 'partial answer', 'private thoughts'),
- hideAgentInsights: true,
- });
- expect(kinds(items)).toEqual(['userMessage', 'streamingText']);
- });
-});
-
-describe('buildThreadTimeline — streaming previews', () => {
- it('trails the primary streaming item after durable items, carrying thinking', () => {
- const items = build({
- messages: [userMsg('u1'), agentMsg('a1')],
- streaming: stream('req1', 'hello', 'thinking...'),
- });
- const last = items[items.length - 1];
- expect(last.kind).toBe('streamingText');
- if (last.kind === 'streamingText') {
- expect(last.text).toBe('hello');
- expect(last.thinking).toBe('thinking...');
- expect(last.branch).toBe(false);
- expect(last.streamId).toBe('req1');
- }
- });
-
- it('skips an empty primary stream but renders forked branches (content only)', () => {
- const items = build({
- messages: [userMsg('u1')],
- streaming: stream('req1', '', ''),
- parallelStreams: [stream('b1', 'branch one'), stream('b2', '', '')],
- });
- const streams = items.filter(i => i.kind === 'streamingText');
- expect(streams).toHaveLength(1);
- const branch = streams[0];
- expect(branch.kind === 'streamingText' && branch.branch).toBe(true);
- expect(branch.kind === 'streamingText' && branch.text).toBe('branch one');
- // Branch thinking is not carried (rendered content-only today).
- expect(branch.kind === 'streamingText' && branch.thinking).toBeUndefined();
- });
-});
-
-describe('buildThreadTimeline — requestId grouping (Phase 4 anchoring)', () => {
- it('derives turnId from extraMetadata.requestId when present', () => {
- const items = build({
- messages: [
- userMsg('u1', 'q1', { requestId: 'req-1' }),
- agentMsg('a1', 'ans1', { requestId: 'req-1' }),
- userMsg('u2', 'q2', { requestId: 'req-2' }),
- agentMsg('a2', 'ans2', { requestId: 'req-2' }),
- ],
- });
- expect(items.map(i => i.turnId)).toEqual(['req-1', 'req-1', 'req-2', 'req-2']);
- });
-
- it('falls back to the legacy turn for messages without a requestId', () => {
- const items = build({
- messages: [userMsg('u1'), agentMsg('a1', 'ans', { requestId: 'req-9' })],
- });
- expect(items.map(i => i.turnId)).toEqual([LEGACY_TURN_ID, 'req-9']);
- });
-
- it('groups a mixed thread into per-request turns', () => {
- const items = build({
- messages: [
- userMsg('u1', 'q1', { requestId: 'req-1' }),
- agentMsg('a1', 'ans1', { requestId: 'req-1' }),
- userMsg('u2', 'q2', { requestId: 'req-2' }),
- agentMsg('a2', 'ans2', { requestId: 'req-2' }),
- ],
- });
- const turns = groupTimelineIntoTurns(items);
- expect(turns.map(t => t.turnId)).toEqual(['req-1', 'req-2']);
- expect(turns.map(t => t.items.length)).toEqual([2, 2]);
- });
-});
-
-describe('groupTimelineIntoTurns', () => {
- it('groups a single legacy turn into one group', () => {
- const items = build({
- messages: [userMsg('u1'), agentMsg('a1')],
- toolTimeline: [tool('c1', 'x')],
- });
- const turns = groupTimelineIntoTurns(items);
- expect(turns).toHaveLength(1);
- expect(turns[0].turnId).toBe(LEGACY_TURN_ID);
- expect(turns[0].items).toHaveLength(3);
- });
-
- it('empty input yields no turns', () => {
- expect(groupTimelineIntoTurns([])).toEqual([]);
- });
-});
-
-describe('selectTimelineForThread (memoized)', () => {
- function stateWith(
- over: Partial<RootState['chatRuntime']> = {},
- theme = { hideAgentInsights: false }
- ): RootState {
- return {
- thread: { messagesByThreadId: { [THREAD]: [userMsg('u1'), agentMsg('a1')] } },
- chatRuntime: {
- toolTimelineByThread: { [THREAD]: [tool('c1', 'read_file', 0)] },
- streamingAssistantByThread: {},
- parallelStreamsByThread: {},
- ...over,
- },
- theme,
- } as unknown as RootState;
- }
-
- it('projects from state and anchors the tool row after the user message', () => {
- const items = selectTimelineForThread(stateWith(), THREAD);
- expect(ids(items)).toEqual(['u1', 'c1', 'a1']);
- });
-
- it('returns a referentially stable result for unchanged inputs (memoization)', () => {
- const state = stateWith();
- const a = selectTimelineForThread(state, THREAD);
- const b = selectTimelineForThread(state, THREAD);
- expect(a).toBe(b);
- });
-
- it('honors hideAgentInsights from theme state', () => {
- const items = selectTimelineForThread(stateWith({}, { hideAgentInsights: true }), THREAD);
- expect(kinds(items)).toEqual(['userMessage', 'assistantMessage']);
- });
-
- it('returns an empty projection for an unknown thread', () => {
- expect(selectTimelineForThread(stateWith(), 'nope')).toEqual([]);
- });
-});
diff --git a/app/src/features/conversations/timeline/selectors.ts b/app/src/features/conversations/timeline/selectors.ts
deleted file mode 100644
index d6ae1016d6..0000000000
--- a/app/src/features/conversations/timeline/selectors.ts
+++ /dev/null
@@ -1,224 +0,0 @@
-/**
- * Projection of the durable + live conversation state into one ordered
- * `TimelineItem[]` (see `./types.ts` and
- * `docs/plans/conversations-timeline-refactor.md`).
- *
- * `buildThreadTimeline` is a pure function of its inputs — fully unit-testable
- * without a store. `selectTimelineForThread` is the memoized Redux selector that
- * feeds it from state; reselect's weakMap memoization keys on the input slices
- * so switching threads does not thrash the cache.
- *
- * ## Ordering (reproduces today's single-anchor behavior)
- *
- * Messages render in stored append order, filtered to drop
- * `extraMetadata.hidden`. The single tool timeline is anchored *after the last
- * user message* — matching the current positional hack
- * (`Conversations.tsx` `lastUserMessageId` at ~L1756 / L2533). Threads with no
- * user message (proactive-only) place the process items at the end, matching the
- * L2669 fallback. Ephemeral streaming previews (primary + forked branches)
- * always trail the durable items.
- *
- * Until Phase 4 stamps `requestId` on messages, every item belongs to the
- * `LEGACY_TURN_ID` turn, so the projection is behaviorally identical to today.
- */
-import { createSelector } from '@reduxjs/toolkit';
-
-import type { StreamingAssistantState, ToolTimelineEntry } from '../../../store/chatRuntimeSlice';
-import type { RootState } from '../../../store/index';
-import type { ThreadMessage } from '../../../types/thread';
-import {
- isSubagentEntry,
- LEGACY_TURN_ID,
- type TimelineItem,
- type TimelineTurn,
- toTimelineToolStatus,
-} from './types';
-
-interface BuildThreadTimelineInput {
- threadId: string;
- messages: ThreadMessage[];
- toolTimeline: ToolTimelineEntry[];
- /** Primary streaming preview for the thread, or null. */
- streaming: StreamingAssistantState | null;
- /** Forked/parallel branch streams for the thread. */
- parallelStreams: StreamingAssistantState[];
- /** When true, the process kinds (tool/subagent rows) are omitted. */
- hideAgentInsights: boolean;
-}
-
-function isHidden(message: ThreadMessage): boolean {
- return Boolean(message.extraMetadata?.hidden);
-}
-
-/**
- * The turn a message belongs to. Assistant/user messages produced after the
- * Phase 4 rollout carry `extraMetadata.requestId`; older messages have none and
- * fall back to the single `legacy` turn (today's single-anchor behavior).
- */
-function messageTurnId(message: ThreadMessage): string {
- const requestId = message.extraMetadata?.requestId;
- return typeof requestId === 'string' && requestId.length > 0 ? requestId : LEGACY_TURN_ID;
-}
-
-/** Map one runtime tool-timeline row onto a `toolCall`/`subagentActivity` item. */
-function toProcessItem(entry: ToolTimelineEntry, threadId: string, seq: number): TimelineItem {
- const base = {
- id: entry.id,
- turnId: LEGACY_TURN_ID,
- seq,
- threadId,
- callId: entry.id,
- name: entry.name,
- status: toTimelineToolStatus(entry.status),
- round: entry.round,
- entry,
- } as const;
- if (isSubagentEntry(entry) && entry.subagent) {
- return { ...base, kind: 'subagentActivity', taskId: entry.subagent.taskId };
- }
- return { ...base, kind: 'toolCall' };
-}
-
-/**
- * Pure projection: compose messages + tool timeline + streaming previews into
- * one ordered `TimelineItem[]`. See the module doc for ordering rules.
- */
-export function buildThreadTimeline(input: BuildThreadTimelineInput): TimelineItem[] {
- const { threadId, messages, toolTimeline, streaming, parallelStreams, hideAgentInsights } = input;
-
- const visible = messages.filter(m => !isHidden(m));
- // Anchor id: the *last* user message, mirroring the current positional hack.
- let lastUserMessageId: string | undefined;
- for (let i = visible.length - 1; i >= 0; i -= 1) {
- if (visible[i].sender === 'user') {
- lastUserMessageId = visible[i].id;
- break;
- }
- }
-
- const items: TimelineItem[] = [];
- let seq = 0;
-
- const pushProcessItems = () => {
- if (hideAgentInsights) return;
- for (const entry of toolTimeline) {
- items.push(toProcessItem(entry, threadId, seq));
- seq += 1;
- }
- };
-
- for (const message of visible) {
- if (message.sender === 'user') {
- items.push({
- kind: 'userMessage',
- id: message.id,
- turnId: messageTurnId(message),
- seq,
- threadId,
- message,
- });
- } else {
- items.push({
- kind: 'assistantMessage',
- id: message.id,
- turnId: messageTurnId(message),
- seq,
- threadId,
- message,
- // Durable persisted messages are never interim narration; interim
- // (`chat_interim`) items are live-only and folded in during streaming.
- interim: false,
- });
- }
- seq += 1;
- // Anchor the process block immediately after the last user message so it
- // reads above the agent's answer for that turn.
- if (message.id === lastUserMessageId) {
- pushProcessItems();
- }
- }
-
- // Proactive / no-user-message threads: process items have no anchor above, so
- // they trail the messages (mirrors the L2669 fallback).
- if (!lastUserMessageId) {
- pushProcessItems();
- }
-
- // Ephemeral streaming previews always trail the durable items (they belong to
- // the live turn). `thinking` rides along on the primary stream; forked
- // branches render content only, matching today.
- if (streaming && (streaming.content.length > 0 || streaming.thinking.length > 0)) {
- items.push({
- kind: 'streamingText',
- id: `stream:${streaming.requestId}`,
- turnId: LEGACY_TURN_ID,
- seq,
- threadId,
- text: streaming.content,
- thinking: streaming.thinking.length > 0 ? streaming.thinking : undefined,
- streamId: streaming.requestId,
- branch: false,
- });
- seq += 1;
- }
- for (const branch of parallelStreams) {
- if (branch.content.length === 0 && branch.thinking.length === 0) continue;
- items.push({
- kind: 'streamingText',
- id: `stream:branch:${branch.requestId}`,
- turnId: LEGACY_TURN_ID,
- seq,
- threadId,
- text: branch.content,
- streamId: branch.requestId,
- branch: true,
- });
- seq += 1;
- }
-
- return items;
-}
-
-/** Split a flat, ordered timeline into contiguous per-turn groups. */
-export function groupTimelineIntoTurns(items: TimelineItem[]): TimelineTurn[] {
- const turns: TimelineTurn[] = [];
- for (const item of items) {
- const last = turns[turns.length - 1];
- if (last && last.turnId === item.turnId) {
- last.items.push(item);
- } else {
- turns.push({ turnId: item.turnId, items: [item] });
- }
- }
- return turns;
-}
-
-const EMPTY_MESSAGES: ThreadMessage[] = [];
-const EMPTY_TIMELINE: ToolTimelineEntry[] = [];
-
-/**
- * Memoized projection selector. Pass the thread id as the second arg:
- * `selectTimelineForThread(state, threadId)`.
- */
-export const selectTimelineForThread = createSelector(
- [
- (state: RootState, threadId: string) =>
- state.thread.messagesByThreadId[threadId] ?? EMPTY_MESSAGES,
- (state: RootState, threadId: string) =>
- state.chatRuntime.toolTimelineByThread[threadId] ?? EMPTY_TIMELINE,
- (state: RootState, threadId: string) =>
- state.chatRuntime.streamingAssistantByThread[threadId] ?? null,
- (state: RootState, threadId: string) => state.chatRuntime.parallelStreamsByThread[threadId],
- (state: RootState) => state.theme?.hideAgentInsights ?? false,
- (_state: RootState, threadId: string) => threadId,
- ],
- (messages, toolTimeline, streaming, parallelMap, hideAgentInsights, threadId) =>
- buildThreadTimeline({
- threadId,
- messages,
- toolTimeline,
- streaming,
- parallelStreams: parallelMap ? Object.values(parallelMap) : [],
- hideAgentInsights,
- })
-);
diff --git a/app/src/features/conversations/timeline/types.ts b/app/src/features/conversations/timeline/types.ts
deleted file mode 100644
index b822513340..0000000000
--- a/app/src/features/conversations/timeline/types.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-/**
- * Unified timeline model for the conversations panel.
- *
- * `threadSlice` (durable messages) and `chatRuntimeSlice` (live tool timeline,
- * streaming previews) remain the sources of truth; `selectTimelineForThread`
- * (see `./selectors.ts`) projects them into one ordered `TimelineItem[]`. This
- * is a *projection*, not a new slice — no big-bang migration, and each phase of
- * the refactor can land independently (see
- * `docs/plans/conversations-timeline-refactor.md`).
- *
- * Every item carries a stable `id`, its `turnId` (the request that produced it;
- * `'legacy'` for pre-migration turns whose messages carry no `requestId`), a
- * per-turn ordering `seq`, and its `threadId`. Ordering within a turn is by
- * `seq`; turns order by the position of their first message in the thread.
- */
-import type { ToolTimelineEntry } from '../../../store/chatRuntimeSlice';
-import type { ThreadMessage } from '../../../types/thread';
-
-/**
- * Turn id used for every item on a thread whose messages predate per-turn
- * `requestId` stamping (Phase 4). Until then the whole thread is one turn, which
- * reproduces today's single-anchor timeline behavior.
- */
-export const LEGACY_TURN_ID = 'legacy';
-
-/** Normalised tool status for the timeline (`success` → `ok`). */
-export type TimelineToolStatus = 'running' | 'ok' | 'error' | 'awaiting_user' | 'cancelled';
-
-export interface TimelineItemBase {
- /** Stable id: message id, or the runtime row id (`ToolTimelineEntry.id`). */
- id: string;
- /** Request that produced this item; `LEGACY_TURN_ID` before requestId stamping. */
- turnId: string;
- /** Ordering within the turn. Reducer-assigned now; backend-stamped in Phase 4. */
- seq: number;
- threadId: string;
-}
-
-export type TimelineItem = TimelineItemBase &
- (
- | { kind: 'userMessage'; message: ThreadMessage }
- | { kind: 'assistantMessage'; message: ThreadMessage; interim: boolean }
- | {
- /** Ephemeral live-turn streaming tail (primary or a forked branch). */
- kind: 'streamingText';
- text: string;
- thinking?: string;
- /** `requestId` of the stream; distinguishes the primary from branches. */
- streamId?: string;
- /** True for a `parallelStreamsByThread` forked branch. */
- branch: boolean;
- }
- | {
- kind: 'toolCall';
- /** The underlying runtime row (rendered via `ToolTimelineBlock`). */
- entry: ToolTimelineEntry;
- callId: string;
- name: string;
- status: TimelineToolStatus;
- round: number;
- }
- | {
- /** A `subagent:*` tool row, rendered nested but stored flat. */
- kind: 'subagentActivity';
- entry: ToolTimelineEntry;
- taskId: string;
- callId: string;
- name: string;
- status: TimelineToolStatus;
- round: number;
- }
- );
-
-/** A contiguous group of items sharing a `turnId`, in render order. */
-export interface TimelineTurn {
- turnId: string;
- items: TimelineItem[];
-}
-
-/** Map `ToolTimelineEntry.status` onto the normalised timeline status. */
-export function toTimelineToolStatus(status: ToolTimelineEntry['status']): TimelineToolStatus {
- return status === 'success' ? 'ok' : status;
-}
-
-/** A `subagent:*` row carries live/persisted sub-agent activity. */
-export function isSubagentEntry(entry: ToolTimelineEntry): boolean {
- return entry.name.startsWith('subagent:');
-}
diff --git a/app/src/features/conversations/utils/interimNarration.test.ts b/app/src/features/conversations/utils/interimNarration.test.ts
deleted file mode 100644
index a882891df9..0000000000
--- a/app/src/features/conversations/utils/interimNarration.test.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import { describe, expect, it } from 'vitest';
-
-import type { ThreadMessage } from '../../../types/thread';
-import { supersededInterimIndexes } from './interimNarration';
-
-function msg(
- sender: 'user' | 'agent',
- content: string,
- extraMetadata?: Record<string, unknown>
-): ThreadMessage {
- return {
- id: `${sender}-${content.slice(0, 8)}-${Math.random().toString(36).slice(2, 8)}`,
- sender,
- content,
- createdAt: new Date(0).toISOString(),
- ...(extraMetadata ? { extraMetadata } : {}),
- } as unknown as ThreadMessage;
-}
-
-const interim = (text: string) => msg('agent', text, { isInterim: true, requestId: 'r1' });
-const answer = (text: string) => msg('agent', text, { citations: [] });
-
-describe('supersededInterimIndexes', () => {
- it('hides narration once the turn produced its answer', () => {
- const messages = [
- msg('user', 'how many goals?'),
- interim('Let me get the data for both.'),
- interim('The HTML is hard to parse. Let me search for a clean table.'),
- answer('He scored 11 goals.'),
- ];
- expect([...supersededInterimIndexes(messages)].sort()).toEqual([1, 2]);
- });
-
- it('keeps narration while the turn is still in flight (no answer yet)', () => {
- const messages = [
- msg('user', 'how many goals?'),
- interim('Let me get the data for both.'),
- interim('Let me get a cleaner source.'),
- ];
- expect(supersededInterimIndexes(messages).size).toBe(0);
- });
-
- // A turn that errored before answering: its narration is the only record of
- // what actually ran, so it must survive.
- it('keeps narration for a turn that died before answering', () => {
- const messages = [
- msg('user', 'first question'),
- interim('Let me check.'),
- answer('Here is the answer.'),
- msg('user', 'second question'),
- interim('Let me search.'),
- ];
- // Only the FIRST turn's narration is superseded.
- expect([...supersededInterimIndexes(messages)]).toEqual([1]);
- });
-
- it('scopes per turn across a multi-turn thread', () => {
- const messages = [
- msg('user', 'q1'),
- interim('n1'),
- answer('a1'),
- msg('user', 'q2'),
- interim('n2'),
- interim('n3'),
- answer('a2'),
- ];
- expect([...supersededInterimIndexes(messages)].sort((a, b) => a - b)).toEqual([1, 4, 5]);
- });
-
- it('never hides real answers or user messages', () => {
- const messages = [msg('user', 'q'), interim('n'), answer('a')];
- const hidden = supersededInterimIndexes(messages);
- expect(hidden.has(0)).toBe(false);
- expect(hidden.has(2)).toBe(false);
- });
-
- it('handles an empty thread and an interim-only thread with no user message', () => {
- expect(supersededInterimIndexes([]).size).toBe(0);
- // Proactive-only run: narration with no answer yet stays visible.
- expect(supersededInterimIndexes([interim('working…')]).size).toBe(0);
- // Proactive-only run that did answer: narration is superseded.
- expect([...supersededInterimIndexes([interim('working…'), answer('done')])]).toEqual([0]);
- });
-});
diff --git a/app/src/features/conversations/utils/interimNarration.ts b/app/src/features/conversations/utils/interimNarration.ts
deleted file mode 100644
index 299226ed5f..0000000000
--- a/app/src/features/conversations/utils/interimNarration.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-/**
- * Which interim narration bubbles a finished turn has superseded.
- *
- * The agent emits `extraMetadata.isInterim` messages while it works ("Let me
- * get the data for both.", "The HTML is hard to parse. Let me search for a
- * clean table.") — these are live progress, not content. Once the turn delivers
- * its real answer they are superseded; left unfiltered they pile up
- * permanently, wedging several stale "Let me…" bubbles between the question and
- * the answer on every multi-tool turn.
- *
- * The rule is per TURN, keyed on that turn having produced a final
- * (non-interim) agent message:
- *
- * - turn still in flight → no final message yet → narration stays visible
- * - turn answered → narration hidden, the answer speaks for it
- * - turn died first → narration kept; it is the only record of what ran
- *
- * Deriving this from the answer's existence rather than a turn-active flag is
- * what makes the third case work, and keeps the helper pure (no lifecycle
- * plumbing, trivially testable).
- *
- * Nothing is deleted — callers use this to filter the rendered list only. The
- * messages stay persisted and reachable via "View full agent process Source".
- */
-import type { ThreadMessage } from '../../../types/thread';
-
-/**
- * Indexes into `messages` whose interim narration is superseded and should not
- * render. Returns indexes (not ids) so callers can filter positionally without
- * assuming ids are present or unique.
- */
-export function supersededInterimIndexes(messages: readonly ThreadMessage[]): Set<number> {
- const hidden = new Set<number>();
- let segmentStart = 0;
-
- // A turn spans (previous user message, next user message]. Closing a segment
- // hides its narration only when that segment also produced a real answer.
- const closeSegment = (end: number) => {
- let hasFinalAnswer = false;
- for (let i = segmentStart; i < end; i += 1) {
- const msg = messages[i];
- if (msg.sender === 'agent' && !msg.extraMetadata?.isInterim) {
- hasFinalAnswer = true;
- break;
- }
- }
- if (!hasFinalAnswer) return;
- for (let i = segmentStart; i < end; i += 1) {
- if (messages[i].extraMetadata?.isInterim) hidden.add(i);
- }
- };
-
- messages.forEach((msg, index) => {
- if (msg.sender === 'user') {
- closeSegment(index);
- segmentStart = index + 1;
- }
- });
- closeSegment(messages.length);
-
- return hidden;
-}