Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

32.9 KB
Raw Blame
/**
 * @vitest-environment happy-dom
 */
import { cleanup, render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
import { afterEach, describe, expect, it, vi } from 'vitest';

import { LOADING_FLAT } from '@/const/message';
import type { AssistantContentBlock } from '@/types/index';

import Group from './Group';

let mockIsCollapsed = false;
let mockIsGenerating = false;
let mockCreatingIds = new Set<string>();
let mockDbMessages: {
  createdAt?: Date | number | string | null;
  id: string;
  metadata?: { finishType?: string };
}[] = [];
let mockOperations: { metadata: Record<string, unknown>; status: string }[] = [];

vi.mock('@/store/chat', () => ({
  useChatStore: (selector: (state: unknown) => unknown) => selector({}),
}));

vi.mock('@/store/chat/slices/operation/selectors', () => ({
  operationSelectors: {
    getOperationsByMessage: () => () => mockOperations,
  },
}));

// The `mcp_apps` flag's default: these cases cover the layout without MCP App views.
vi.mock('@/store/serverConfig', () => ({
  serverConfigSelectors: { enableMcpApps: () => false },
  useServerConfigStore: (selector: (s: unknown) => unknown) => selector({}),
}));

// Mock the council list so importing Group doesn't pull in the AgentCouncil
// render chain (→ shared-tool-ui inspectors → `@lobehub/ui` `keyframes`), which is
// out of scope for this unit test.
vi.mock('../../AgentCouncil/components/CouncilList', () => ({
  default: ({ members }: { members?: unknown[] }) => <div>council:{members?.length ?? 0}</div>,
}));

vi.mock('../../../store', () => ({
  messageStateSelectors: {
    isAssistantGroupItemGenerating: () => () => mockIsGenerating,
    isMessageCollapsed: () => () => mockIsCollapsed,
    isMessageCreating: (id: string) => () => mockCreatingIds.has(id),
    isMessageGenerating: () => () => mockIsGenerating,
  },
  useConversationStore: (selector: (state: unknown) => unknown) =>
    selector({ dbMessages: mockDbMessages }),
}));

vi.mock('./SteerMessage', () => ({
  default: ({ id }: { id: string }) => <div data-id={id} data-testid="steer-message" />,
}));

vi.mock('./CollapsedMessage', () => ({
  CollapsedMessage: ({ content }: { content?: string }) => <div>{content}</div>,
}));

vi.mock('./WorkflowCollapse', () => ({
  default: ({
    blocks,
    workflowChromeComplete,
  }: {
    blocks: Array<{
      content: string;
      contentOverride?: string;
      disableMarkdownStreaming?: boolean;
      domId?: string;
      error?: unknown;
      hasToolsOverride?: boolean;
      tools?: unknown[];
    }>;
    workflowChromeComplete?: boolean;
  }) => (
    <div
      data-chrome-complete={String(!!workflowChromeComplete)}
      data-testid="workflow-segment"
      data-blocks={JSON.stringify(
        blocks.map(
          ({
            content,
            contentOverride,
            disableMarkdownStreaming,
            domId,
            error,
            hasToolsOverride,
            tools,
          }) => ({
            content,
            contentOverride,
            disableMarkdownStreaming: !!disableMarkdownStreaming,
            domId,
            hasError: !!error,
            hasToolsOverride,
            toolCount: tools?.length ?? 0,
          }),
        ),
      )}
    />
  ),
}));

vi.mock('./ProcessFold', () => ({
  default: ({
    children,
    stepCount,
  }: {
    children?: ReactNode;
    durationText?: string;
    stepCount: number;
  }) => (
    <div data-step-count={stepCount} data-testid="process-fold">
      {children}
    </div>
  ),
}));

vi.mock('./GroupItem', () => ({
  default: ({
    content,
    contentOverride,
    disableMarkdownStreaming,
    domId,
    error,
    hasToolsOverride,
    id,
    isFirstBlock,
    tools,
  }: {
    content: string;
    contentOverride?: string;
    disableMarkdownStreaming?: boolean;
    domId?: string;
    error?: unknown;
    hasToolsOverride?: boolean;
    id: string;
    isFirstBlock?: boolean;
    tools?: unknown[];
  }) => (
    <div
      data-testid="answer-segment"
      data-block={JSON.stringify({
        content,
        contentOverride,
        disableMarkdownStreaming: !!disableMarkdownStreaming,
        domId,
        hasError: !!error,
        hasToolsOverride,
        id,
        isFirstBlock: !!isFirstBlock,
        toolCount: tools?.length ?? 0,
      })}
    />
  ),
}));

vi.mock('@/features/Conversation/Messages/components/ContentLoading', () => ({
  default: ({ id, startTime }: { id: string; startTime?: number }) => (
    <div data-id={id} data-start-time={startTime} data-testid="tail-running" />
  ),
}));

const blk = (p: Partial<AssistantContentBlock> & { id: string }): AssistantContentBlock =>
  ({ content: '', ...p }) as AssistantContentBlock;

const parseAnswerSegment = () =>
  JSON.parse(screen.getByTestId('answer-segment').getAttribute('data-block') || '{}');

const parseAnswerSegments = () =>
  screen
    .queryAllByTestId('answer-segment')
    .map((node) => JSON.parse(node.getAttribute('data-block') || '{}'));

const parseWorkflowSegment = () =>
  JSON.parse(screen.getByTestId('workflow-segment').getAttribute('data-blocks') || '[]');

const runningChecksInput = (): Parameters<typeof blk>[0] => ({
  content: 'Running the checks.',
  id: 'block-1',
  tools: [
    { apiName: 'bash', id: 'tool-1', result: { content: 'ok' } } as any,
    { apiName: 'bash', id: 'tool-2', result: { content: 'ok' } } as any,
  ],
});

const completedToolInput = (): Parameters<typeof blk>[0] => ({
  content: '',
  id: 'block-1',
  tools: [{ apiName: 'bash', id: 'tool-1', result: { content: 'done' } } as any],
});

describe('Group', () => {
  afterEach(() => {
    cleanup();
    mockIsCollapsed = false;
    mockIsGenerating = false;
    mockCreatingIds = new Set();
    mockDbMessages = [];
    mockOperations = [];
  });

  it('keeps an empty terminal block when only the persisted message has its finish type', () => {
    mockDbMessages = [{ id: 'block-1', metadata: { finishType: 'RECITATION' } }];

    render(
      <Group isLatestItem blocks={[blk({ id: 'block-1' })]} id="assistant-1" messageIndex={0} />,
    );

    expect(parseAnswerSegment()).toMatchObject({ content: '', id: 'block-1' });
  });

  it('keeps a long mixed single-tool block inline in its natural order', () => {
    // No promotion/relocation: a block carrying both a tool call and long prose
    // renders as ONE inline unit (content above its tool inside ContentBlock),
    // never split into a tool-first / text-after layout.
    const longContent =
      'State management in real projects is an interesting topic!\n\nWhat specific problem are you running into right now? For example:\n- Not sure when to use useState vs Context\n- State passing between components gets messy\n- Performance issues from unnecessary re-renders';

    render(
      <Group
        isLatestItem
        id="assistant-1"
        messageIndex={0}
        blocks={[
          blk({
            content: longContent,
            id: 'block-1',
            tools: [{ apiName: 'search', id: 'tool-1' } as any],
          }),
        ]}
      />,
    );

    expect(screen.queryByTestId('workflow-segment')).not.toBeInTheDocument();
    expect(parseAnswerSegments()).toEqual([
      {
        content: longContent,
        contentOverride: undefined,
        disableMarkdownStreaming: false,
        domId: undefined,
        hasError: false,
        hasToolsOverride: undefined,
        id: 'block-1',
        isFirstBlock: false,
        toolCount: 1,
      },
    ]);
  });

  it('keeps a short mixed status block inline when there is only one tool call', () => {
    render(
      <Group
        isLatestItem
        id="assistant-1"
        messageIndex={0}
        blocks={[
          blk({
            content: '现在我来搜索资料。',
            id: 'block-1',
            tools: [{ apiName: 'search', id: 'tool-1' } as any],
          }),
        ]}
      />,
    );

    expect(screen.queryByTestId('workflow-segment')).not.toBeInTheDocument();
    expect(parseAnswerSegments()).toEqual([
      {
        content: '现在我来搜索资料。',
        disableMarkdownStreaming: false,
        domId: undefined,
        hasError: false,
        id: 'block-1',
        isFirstBlock: false,
        toolCount: 1,
      },
    ]);
  });

  it('keeps answer-like mixed prose visible above a folded multi-tool workflow', () => {
    const answerLikePreamble =
      'I found the likely rendering issue and need to verify the grouped workflow behavior.\n\n- The assistant prose should remain above the fold when it explains the result.\n- The tools still belong in the collapsed workflow.\n- Short progress lines should not split the workflow.';

    const { container } = render(
      <Group
        isLatestItem
        id="assistant-1"
        messageIndex={0}
        blocks={[
          blk({
            content: answerLikePreamble,
            id: 'block-1',
            tools: [{ apiName: 'search', id: 'tool-1' } as any],
          }),
          blk({
            content: '',
            id: 'block-2',
            tools: [{ apiName: 'readFile', id: 'tool-2' } as any],
          }),
        ]}
      />,
    );

    const sequence = Array.from(container.querySelectorAll('[data-testid]')).map((node) =>
      node.getAttribute('data-testid'),
    );

    expect(sequence).toEqual(['answer-segment', 'workflow-segment']);
    expect(parseAnswerSegment()).toEqual({
      content: answerLikePreamble,
      contentOverride: answerLikePreamble,
      disableMarkdownStreaming: true,
      domId: 'block-1__answer',
      hasError: false,
      hasToolsOverride: false,
      id: 'block-1',
      isFirstBlock: false,
      toolCount: 0,
    });
    expect(parseWorkflowSegment()).toEqual([
      {
        content: '',
        contentOverride: '',
        disableMarkdownStreaming: true,
        domId: 'block-1__workflow',
        hasError: false,
        hasToolsOverride: true,
        toolCount: 1,
      },
      {
        content: '',
        disableMarkdownStreaming: false,
        domId: undefined,
        hasError: false,
        toolCount: 1,
      },
    ]);
  });

  it('shows short narration between consecutive single-tool workflow steps', () => {
    const { container } = render(
      <Group
        isLatestItem
        id="assistant-1"
        messageIndex={0}
        blocks={[
          blk({
            content: 'Let me inspect the package scripts.',
            id: 'block-1',
            tools: [{ apiName: 'command_execution', id: 'tool-1' } as any],
          }),
          blk({
            content: 'Now let me read the source file.',
            id: 'block-2',
            tools: [{ apiName: 'readFile', id: 'tool-2' } as any],
          }),
        ]}
      />,
    );

    const sequence = Array.from(container.querySelectorAll('[data-testid]')).map((node) =>
      node.getAttribute('data-testid'),
    );

    expect(sequence).toEqual([
      'answer-segment',
      'answer-segment',
      'answer-segment',
      'answer-segment',
    ]);
    expect(screen.queryByTestId('workflow-segment')).not.toBeInTheDocument();
    const rendered = screen
      .getAllByTestId('answer-segment')
      .map((node) => JSON.parse(node.getAttribute('data-block') || '{}'));
    expect(rendered).toEqual([
      expect.objectContaining({
        content: 'Let me inspect the package scripts.',
        id: 'block-1',
        domId: 'block-1__answer',
        toolCount: 0,
        hasToolsOverride: false,
        disableMarkdownStreaming: true,
        hasError: false,
      }),
      expect.objectContaining({
        content: '',
        id: 'block-1',
        domId: 'block-1__workflow',
        toolCount: 1,
        hasToolsOverride: true,
        disableMarkdownStreaming: true,
        hasError: false,
      }),
      expect.objectContaining({
        content: 'Now let me read the source file.',
        id: 'block-2',
        domId: 'block-2__answer',
        toolCount: 0,
        hasToolsOverride: false,
        disableMarkdownStreaming: false,
        hasError: false,
      }),
      expect.objectContaining({
        content: '',
        id: 'block-2',
        domId: 'block-2__workflow',
        toolCount: 1,
        hasToolsOverride: true,
        disableMarkdownStreaming: false,
        hasError: false,
      }),
    ]);
  });

  it('breaks an image-bearing tool out and shows narration between workflow runs', () => {
    const { container } = render(
      <Group
        isLatestItem
        id="assistant-1"
        messageIndex={0}
        blocks={[
          blk({
            content: 'Inspecting.',
            id: 'block-1',
            tools: [
              { apiName: 'Bash', id: 'tool-0', identifier: 'claude-code' } as any,
              { apiName: 'Bash', id: 'tool-1', identifier: 'claude-code' } as any,
              {
                apiName: 'Read',
                id: 'tool-2',
                identifier: 'claude-code',
                result: {
                  content: 'ok',
                  id: 'r2',
                  state: { images: [{ url: 'https://x/a.png' }] },
                },
              } as any,
              { apiName: 'Bash', id: 'tool-3', identifier: 'claude-code' } as any,
            ],
          }),
          blk({
            content: 'Continuing.',
            id: 'block-2',
            tools: [{ apiName: 'Bash', id: 'tool-4', identifier: 'claude-code' } as any],
          }),
        ]}
      />,
    );

    const sequence = Array.from(container.querySelectorAll('[data-testid]')).map((node) =>
      node.getAttribute('data-testid'),
    );
    expect(sequence).toEqual([
      'answer-segment',
      'workflow-segment',
      'answer-segment',
      'answer-segment',
      'answer-segment',
      'answer-segment',
    ]);
    expect(parseWorkflowSegment()).toEqual([
      expect.objectContaining({
        contentOverride: '',
        domId: 'block-1__tool-0__workflow',
        toolCount: 2,
      }),
    ]);
    const answers = screen
      .getAllByTestId('answer-segment')
      .map((node) => JSON.parse(node.getAttribute('data-block') || '{}'));
    expect(answers).toEqual([
      expect.objectContaining({ content: 'Inspecting.', domId: 'block-1__answer', toolCount: 0 }),
      expect.objectContaining({ domId: 'block-1__tool-2__workflow', id: 'block-1', toolCount: 1 }),
      expect.objectContaining({ content: '', domId: 'block-1__tool-3__workflow', toolCount: 1 }),
      expect.objectContaining({ content: 'Continuing.', domId: 'block-2__answer', toolCount: 0 }),
      expect.objectContaining({ content: '', domId: 'block-2__workflow', toolCount: 1 }),
    ]);
  });

  it('does not fold the latest process behind a non-renderable final answer placeholder', () => {
    render(
      <Group
        enableProcessFold
        isLatestItem
        id="assistant-1"
        messageIndex={0}
        blocks={[
          blk({
            content: 'I will run the checks.',
            id: 'block-1',
            tools: [
              { apiName: 'bash', id: 'tool-1', result: { content: 'ok' } } as any,
              { apiName: 'bash', id: 'tool-2', result: { content: 'ok' } } as any,
            ],
          }),
          blk({ content: LOADING_FLAT, id: 'block-2' }),
        ]}
      />,
    );

    expect(screen.queryByTestId('process-fold')).not.toBeInTheDocument();
    expect(screen.getByTestId('workflow-segment')).toBeInTheDocument();
    expect(parseAnswerSegment()).toEqual(
      expect.objectContaining({ content: 'I will run the checks.', toolCount: 0 }),
    );
  });

  it('keeps a non-latest finished turn’s final answer visible outside the fold', () => {
    render(
      <Group
        enableProcessFold
        id="assistant-1"
        isLatestItem={false}
        messageIndex={0}
        blocks={[
          blk(runningChecksInput()),
          blk({ content: 'Here is the final answer.', id: 'block-2' }),
        ]}
      />,
    );

    const fold = screen.getByTestId('process-fold');
    const [narration, answer] = screen.getAllByTestId('answer-segment');
    expect(fold.contains(narration)).toBe(true);
    expect(JSON.parse(answer.getAttribute('data-block') || '{}').content).toBe(
      'Here is the final answer.',
    );
    // Folding only ever collapses the process; the final answer stays a visible
    // sibling for every turn, latest or not — never swallowed into the fold.
    expect(fold.contains(answer)).toBe(false);
    expect(fold.contains(screen.getByTestId('workflow-segment'))).toBe(true);
    expect(fold).toHaveAttribute('data-step-count', '2');
  });

  it('folds as soon as the operation’s visible output ends, before terminal completion', () => {
    // After `visible_output_end` the op stays `running` for seconds of terminal
    // bookkeeping (persistence, agent_runtime_end, completeRun). Folding must
    // key off the visible end, not the terminal status flip.
    mockOperations = [{ metadata: { visibleLoadingDone: true }, status: 'running' }];

    render(
      <Group
        enableProcessFold
        isLatestItem
        id="assistant-1"
        messageIndex={0}
        blocks={[
          blk(runningChecksInput()),
          blk({ content: 'Here is the final answer.', id: 'block-2' }),
        ]}
      />,
    );

    expect(screen.getByTestId('process-fold')).toBeInTheDocument();
  });

  it('does not fold while the operation is still visibly running', () => {
    mockOperations = [{ metadata: {}, status: 'running' }];

    render(
      <Group
        enableProcessFold
        isLatestItem
        id="assistant-1"
        messageIndex={0}
        blocks={[
          blk(runningChecksInput()),
          blk({ content: 'Here is the final answer.', id: 'block-2' }),
        ]}
      />,
    );

    expect(screen.queryByTestId('process-fold')).not.toBeInTheDocument();
  });

  it('keeps the latest finished turn’s final answer visible outside the fold', () => {
    render(
      <Group
        enableProcessFold
        isLatestItem
        id="assistant-1"
        messageIndex={0}
        blocks={[
          blk(runningChecksInput()),
          blk({ content: 'Here is the final answer.', id: 'block-2' }),
        ]}
      />,
    );

    const fold = screen.getByTestId('process-fold');
    const [narration, answer] = screen.getAllByTestId('answer-segment');
    expect(fold.contains(narration)).toBe(true);
    expect(JSON.parse(answer.getAttribute('data-block') || '{}').content).toBe(
      'Here is the final answer.',
    );
    // Latest turn: the answer stays out of the fold so it reads without expanding.
    expect(fold.contains(answer)).toBe(false);
    expect(fold.contains(screen.getByTestId('workflow-segment'))).toBe(true);
  });

  it('keeps assistant runtime errors outside the workflow collapse', () => {
    const { container } = render(
      <Group
        isLatestItem
        id="assistant-1"
        messageIndex={0}
        blocks={[
          blk({
            content: '',
            error: {
              body: { code: 'rate_limit' },
              message: 'rate limit',
              type: 'ProviderBizError',
            } as any,
            id: 'block-1',
            tools: [
              { apiName: 'bash', id: 'tool-1' } as any,
              { apiName: 'bash', id: 'tool-2' } as any,
            ],
          }),
        ]}
      />,
    );

    const sequence = Array.from(container.querySelectorAll('[data-testid]')).map((node) =>
      node.getAttribute('data-testid'),
    );

    expect(sequence).toEqual(['workflow-segment', 'answer-segment']);
    expect(parseWorkflowSegment()).toEqual([
      {
        content: '',
        contentOverride: '',
        disableMarkdownStreaming: false,
        domId: 'block-1__workflow',
        hasError: false,
        hasToolsOverride: true,
        toolCount: 2,
      },
    ]);
    expect(parseAnswerSegment()).toEqual({
      content: '',
      contentOverride: '',
      disableMarkdownStreaming: false,
      domId: 'block-1__answer',
      hasError: true,
      hasToolsOverride: false,
      id: 'block-1',
      isFirstBlock: false,
      toolCount: 0,
    });
  });

  it('renders a single tool call inline instead of folding it', () => {
    render(
      <Group
        isLatestItem
        id="assistant-1"
        messageIndex={0}
        blocks={[
          blk({
            content: '',
            id: 'block-1',
            tools: [{ apiName: 'search', id: 'tool-1' } as any],
          }),
        ]}
      />,
    );

    expect(screen.queryByTestId('workflow-segment')).not.toBeInTheDocument();
    expect(parseAnswerSegments()).toEqual([
      {
        content: '',
        disableMarkdownStreaming: false,
        domId: undefined,
        hasError: false,
        id: 'block-1',
        isFirstBlock: false,
        toolCount: 1,
      },
    ]);
  });

  it('shows a running indicator below a settled single inline tool while still generating', () => {
    mockIsGenerating = true;
    render(
      <Group isLatestItem blocks={[blk(completedToolInput())]} id="assistant-1" messageIndex={0} />,
    );

    expect(screen.getByTestId('tail-running')).toHaveAttribute('data-id', 'assistant-1');
  });

  it('does not add a tail indicator when the inline segment ends on a LOADING_FLAT placeholder', () => {
    // The settled tool is followed by a LOADING_FLAT placeholder that stays
    // inside the inline segment; that block mounts MessageContent and renders
    // its OWN running line, so the tail must NOT stack a second identical one.
    mockIsGenerating = true;
    render(
      <Group
        isLatestItem
        blocks={[blk(completedToolInput()), blk({ content: LOADING_FLAT, id: 'block-2' })]}
        id="assistant-1"
        messageIndex={0}
      />,
    );

    expect(screen.queryByTestId('tail-running')).not.toBeInTheDocument();
  });

  it('keeps the tail indicator when the trailing block is a blank content:"" shell', () => {
    // The gateway emits an empty `content: ''` assistant shell on stream_start.
    // ContentBlock does NOT mount MessageContent for it (no text/LOADING_FLAT/
    // tools), so it renders no running line of its own — the tail must stay to
    // fill the gap after the settled tool until the first content chunk lands.
    mockIsGenerating = true;
    render(
      <Group
        isLatestItem
        blocks={[blk(completedToolInput()), blk({ content: '', id: 'block-2' })]}
        id="assistant-1"
        messageIndex={0}
      />,
    );

    expect(screen.getByTestId('tail-running')).toHaveAttribute('data-id', 'assistant-1');
  });

  it('anchors the running indicator to the tool RESULT createdAt, not the tool-call block', () => {
    mockIsGenerating = true;
    // The tool result lands after the tool-call block; the tail timer must start
    // from the result row so a long tool runtime is not folded back into elapsed.
    mockDbMessages = [
      { createdAt: 1000, id: 'block-1' },
      { createdAt: 5000, id: 'tool-result-1' },
    ];
    render(
      <Group
        isLatestItem
        id="assistant-1"
        messageIndex={0}
        blocks={[
          blk({
            content: '',
            id: 'block-1',
            tools: [
              {
                apiName: 'bash',
                id: 'tool-1',
                result: { content: 'done' },
                result_msg_id: 'tool-result-1',
              } as any,
            ],
          }),
        ]}
      />,
    );

    expect(screen.getByTestId('tail-running')).toHaveAttribute('data-start-time', '5000');
  });

  it('hides the running indicator while the inline tool is still executing', () => {
    mockIsGenerating = true;
    render(
      <Group
        isLatestItem
        id="assistant-1"
        messageIndex={0}
        blocks={[
          blk({
            content: '',
            id: 'block-1',
            tools: [{ apiName: 'bash', id: 'tool-1' } as any],
          }),
        ]}
      />,
    );

    expect(screen.queryByTestId('tail-running')).not.toBeInTheDocument();
  });

  it('hides the running indicator once generation has finished', () => {
    mockIsGenerating = false;
    render(
      <Group isLatestItem blocks={[blk(completedToolInput())]} id="assistant-1" messageIndex={0} />,
    );

    expect(screen.queryByTestId('tail-running')).not.toBeInTheDocument();
  });

  it('only animates the last block in a multi-block group', () => {
    const { container } = render(
      <Group
        isLatestItem
        id="assistant-1"
        messageIndex={0}
        blocks={[
          blk({ content: 'first paragraph', id: 'block-1' }),
          blk({ content: 'middle paragraph', id: 'block-2' }),
          blk({ content: 'last paragraph', id: 'block-3' }),
        ]}
      />,
    );

    const sequence = Array.from(container.querySelectorAll('[data-testid]')).map((node) =>
      node.getAttribute('data-testid'),
    );

    expect(sequence).toEqual(['answer-segment', 'answer-segment', 'answer-segment']);
    expect(
      parseAnswerSegments().map((seg: { disableMarkdownStreaming: boolean; id: string }) => ({
        disableMarkdownStreaming: seg.disableMarkdownStreaming,
        id: seg.id,
      })),
    ).toEqual([
      { disableMarkdownStreaming: true, id: 'block-1' },
      { disableMarkdownStreaming: true, id: 'block-2' },
      { disableMarkdownStreaming: false, id: 'block-3' },
    ]);
  });

  it('marks the workflow chrome complete once content renders below a settled fold while generating', () => {
    // An errored multi-tool block splits into a folded workflow (the tools) plus
    // a trailing answer segment (the error text). While still generating, the
    // collapse must not keep showing its streaming "working" header now that the
    // model has moved past it and content renders below.
    mockIsGenerating = true;

    const { container } = render(
      <Group
        isLatestItem
        id="assistant-1"
        messageIndex={0}
        blocks={[
          blk({
            content: 'Something failed while running the commands.',
            error: { message: 'boom' } as any,
            id: 'block-1',
            tools: [
              { apiName: 'command_execution', id: 'tool-1', result: { content: 'ok' } } as any,
              { apiName: 'command_execution', id: 'tool-2', result: { content: 'ok' } } as any,
            ],
          }),
        ]}
      />,
    );

    const sequence = Array.from(container.querySelectorAll('[data-testid]')).map((node) =>
      node.getAttribute('data-testid'),
    );

    expect(sequence).toEqual(['workflow-segment', 'answer-segment']);
    expect(screen.getByTestId('workflow-segment').getAttribute('data-chrome-complete')).toBe(
      'true',
    );
  });

  it('keeps the fold streaming when it still holds a pending intervention, even with content below', () => {
    // Same shape as above, but one tool awaits user confirmation. The completion
    // shortcut must be suppressed so the "awaiting confirmation" chrome survives —
    // areWorkflowToolsComplete ignores pending tools, so we cannot rely on it.
    mockIsGenerating = true;

    const { container } = render(
      <Group
        isLatestItem
        id="assistant-1"
        messageIndex={0}
        blocks={[
          blk({
            content: 'Partial output before the failure.',
            error: { message: 'boom' } as any,
            id: 'block-1',
            tools: [
              { apiName: 'command_execution', id: 'tool-1', result: { content: 'ok' } } as any,
              {
                apiName: 'command_execution',
                id: 'tool-2',
                intervention: { status: 'pending' },
              } as any,
            ],
          }),
        ]}
      />,
    );

    const sequence = Array.from(container.querySelectorAll('[data-testid]')).map((node) =>
      node.getAttribute('data-testid'),
    );

    expect(sequence).toEqual(['workflow-segment', 'answer-segment']);
    expect(screen.getByTestId('workflow-segment').getAttribute('data-chrome-complete')).toBe(
      'false',
    );
  });

  describe('steered continuations', () => {
    const chain1 = [
      blk({
        content: 'Looking into it.',
        id: 'a1',
        tools: [{ apiName: 'search', id: 't1' } as any],
      }),
      blk({ content: 'Turn one answer.', id: 'a2' }),
    ];
    const chain2 = [
      blk({ content: '', id: 'b1', tools: [{ apiName: 'readFile', id: 't2' } as any] }),
      blk({ content: 'Final answer.', id: 'b2' }),
    ];

    it('renders steer bubbles inline between chains while streaming', () => {
      mockIsGenerating = true;

      const { container } = render(
        <Group
          isLatestItem
          blocks={chain1}
          continuations={[{ blocks: chain2, id: 'group-2', steerUserId: 'steer-1' }]}
          id="group-1"
          messageIndex={0}
        />,
      );

      const sequence = Array.from(container.querySelectorAll('[data-testid]')).map((node) =>
        node.getAttribute('data-testid'),
      );
      expect(sequence).toEqual([
        'answer-segment',
        'answer-segment',
        'steer-message',
        'answer-segment',
        'answer-segment',
      ]);
      expect(screen.getByTestId('steer-message').getAttribute('data-id')).toBe('steer-1');
      expect(screen.queryByTestId('process-fold')).not.toBeInTheDocument();
    });

    it('folds each turn separately and keeps every turn’s final answer outside its fold', () => {
      mockOperations = [];

      const { container } = render(
        <Group
          enableProcessFold
          isLatestItem
          blocks={chain1}
          continuations={[{ blocks: chain2, id: 'group-2', steerUserId: 'steer-1' }]}
          id="group-1"
          messageIndex={0}
        />,
      );

      const folds = screen.getAllByTestId('process-fold');
      expect(folds.map((fold) => fold.getAttribute('data-step-count'))).toEqual(['2', '2']);

      const steer = screen.getByTestId('steer-message');
      expect(
        folds[0]!.compareDocumentPosition(steer) & Node.DOCUMENT_POSITION_FOLLOWING,
      ).toBeTruthy();
      expect(
        steer.compareDocumentPosition(folds[1]!) & Node.DOCUMENT_POSITION_FOLLOWING,
      ).toBeTruthy();
      expect(folds.some((fold) => fold.contains(steer))).toBe(false);

      const idsIn = (root: Element) =>
        Array.from(root.querySelectorAll('[data-testid="answer-segment"]')).map(
          (node) => JSON.parse(node.getAttribute('data-block') || '{}').id,
        );
      expect(idsIn(folds[0]!)).toEqual(['a1']);
      expect(idsIn(folds[1]!)).toEqual(['b1']);

      // A queued follow-up is only sent after the turn it follows has finished,
      // so that turn's answer is a real reply and must stay readable, sitting
      // between its own fold and the steer bubble.
      const sequence = Array.from(container.querySelectorAll('[data-testid]'))
        .filter((node) => !folds.some((fold) => fold !== node && fold.contains(node)))
        .map((node) =>
          node.getAttribute('data-testid') === 'answer-segment'
            ? JSON.parse(node.getAttribute('data-block') || '{}').id
            : node.getAttribute('data-testid'),
        );
      expect(sequence).toEqual(['process-fold', 'a2', 'steer-message', 'process-fold', 'b2']);
    });

    it('folds the whole of an earlier turn that stopped on a tool call', () => {
      mockOperations = [];

      render(
        <Group
          enableProcessFold
          isLatestItem
          blocks={[chain1[0]!]}
          continuations={[{ blocks: chain2, id: 'group-2', steerUserId: 'steer-1' }]}
          id="group-1"
          messageIndex={0}
        />,
      );

      const folds = screen.getAllByTestId('process-fold');
      expect(folds).toHaveLength(2);
      expect(
        Array.from(folds[0]!.querySelectorAll('[data-testid="answer-segment"]')).map(
          (node) => JSON.parse(node.getAttribute('data-block') || '{}').id,
        ),
      ).toEqual(['a1']);
    });

    it('keeps the loading placeholder of a continuation that is still being created', () => {
      mockCreatingIds = new Set(['pending-assistant']);

      const { container } = render(
        <Group
          enableProcessFold
          isLatestItem
          blocks={chain1}
          id="group-1"
          messageIndex={0}
          continuations={[
            {
              blocks: [blk({ content: LOADING_FLAT, id: 'pending-assistant' })],
              id: 'pending-assistant',
              steerUserId: 'steer-1',
            },
          ]}
        />,
      );

      const ids = Array.from(container.querySelectorAll('[data-testid="answer-segment"]')).map(
        (node) => JSON.parse(node.getAttribute('data-block') || '{}').id,
      );
      expect(ids).toContain('pending-assistant');
      expect(screen.queryByTestId('process-fold')).not.toBeInTheDocument();
    });

    it('skips the fold for a continuation whose whole output is the final answer', () => {
      mockOperations = [];

      render(
        <Group
          enableProcessFold
          isLatestItem
          blocks={chain1}
          id="group-1"
          messageIndex={0}
          continuations={[
            {
              blocks: [blk({ content: 'Final answer.', id: 'b2' })],
              id: 'group-2',
              steerUserId: 'steer-1',
            },
          ]}
        />,
      );

      const folds = screen.getAllByTestId('process-fold');
      expect(folds).toHaveLength(1);
      expect(folds[0]!.getAttribute('data-step-count')).toBe('2');
      expect(screen.getByTestId('steer-message')).toBeInTheDocument();
    });
  });
});