Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
44.6 KB
Raw Blame
import { describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { I18nProvider } from "@multica/core/i18n/react";
import { chatKeys } from "@multica/core/chat/queries";
import { TooltipProvider } from "@multica/ui/components/ui/tooltip";
import type { Attachment, TaskMessagePayload } from "@multica/core/types";
import type { ReactElement } from "react";
import enChat from "../../locales/en/chat.json";
import zhHansAgents from "../../locales/zh-Hans/agents.json";
import zhHansChat from "../../locales/zh-Hans/chat.json";

// The live timeline is a real list row rather than Virtuoso chrome (MUL-4922),
// so it shares one identity with the persisted assistant row and keeps its
// Mermaid/HTML blocks mounted across task completion. Real react-virtuoso
// renders its Footer but NO data rows under jsdom's zero-height viewport, so
// these tests must stub it to see rows at all. computeItemKey is still applied
// here — it is what expresses the live -> persisted identity.
vi.mock("react-virtuoso", () => ({
  Virtuoso: ({
    data,
    itemContent,
    computeItemKey,
    components,
    context,
    followOutput,
  }: {
    data: unknown[];
    itemContent: (i: number, item: unknown) => ReactElement;
    computeItemKey: (i: number, item: unknown) => string;
    components?: { Footer?: (p: { context?: unknown }) => ReactElement | null };
    context?: unknown;
    followOutput?: (atBottom: boolean) => "smooth" | "auto" | false;
  }) => {
    const Footer = components?.Footer;
    return (
      <div
        data-follow-at-bottom={String(followOutput?.(true))}
        data-follow-away-from-bottom={String(followOutput?.(false))}
      >
        {data.map((item, i) => (
          <div key={computeItemKey(i, item)} data-row-key={computeItemKey(i, item)}>
            {itemContent(i, item)}
          </div>
        ))}
        {Footer ? <Footer context={context} /> : null}
      </div>
    );
  },
}));

import { ChatMessageList } from "./chat-message-list";

const TEST_RESOURCES = { en: { chat: enChat } };
const TASK_ID = "6af44cbe-80ab-4dfe-b07d-bd3cfd588f4d";

function taskMsg(
  seq: number,
  type: TaskMessagePayload["type"],
  extra: Partial<TaskMessagePayload> = {},
): TaskMessagePayload {
  return { task_id: TASK_ID, seq, type, ...extra } as TaskMessagePayload;
}

function pdfAttachment(id: string): Attachment {
  return {
    id,
    workspace_id: "workspace-1",
    issue_id: null,
    comment_id: null,
    chat_session_id: "session-1",
    chat_message_id: null,
    uploader_type: "member",
    uploader_id: "member-1",
    filename: "report.pdf",
    url: "/uploads/report.pdf",
    download_url: `/api/attachments/${id}/download`,
    markdown_url: `/api/attachments/${id}/download`,
    content_type: "application/pdf",
    size_bytes: 1024,
    created_at: "2026-09-17T00:00:00Z",
  };
}

// A streaming timeline whose middle (tool steps) is non-empty, so the live
// footer renders the "N steps" outer fold.
const INITIAL_MESSAGES: TaskMessagePayload[] = [
  taskMsg(0, "text", { content: "Looking into it. " }),
  taskMsg(1, "tool_use", { tool: "Bash", input: { command: "go test ./..." } }),
  taskMsg(2, "tool_result", { tool: "Bash", output: "ok" }),
];

function renderList(qc: QueryClient) {
  qc.setQueryData(chatKeys.taskMessages(TASK_ID), INITIAL_MESSAGES);
  return render(
    <I18nProvider locale="en" resources={TEST_RESOURCES}>
      <QueryClientProvider client={qc}>
        <ChatMessageList
          messages={[]}
          pendingTask={{ task_id: TASK_ID, status: "running" }}
          availability={undefined}
        />
      </QueryClientProvider>
    </I18nProvider>,
  );
}

function pushTaskMessage(qc: QueryClient, msg: TaskMessagePayload) {
  // Mirrors useRealtimeSync's task:message handler: a new array lands in the
  // shared task-messages cache on every streamed message.
  act(() => {
    qc.setQueryData<TaskMessagePayload[]>(
      chatKeys.taskMessages(TASK_ID),
      (old = []) => [...old, msg],
    );
  });
}

describe("ChatMessageList live follow (#6697)", () => {
  it("follows appended output immediately only while Virtuoso is at the live end", () => {
    const { container } = render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={new QueryClient()}>
          <ChatMessageList
            messages={[]}
            pendingTask={null}
            availability="online"
          />
        </QueryClientProvider>
      </I18nProvider>,
    );

    const list = container.querySelector("[data-follow-at-bottom]");
    expect(list).toHaveAttribute("data-follow-at-bottom", "auto");
    expect(list).toHaveAttribute("data-follow-away-from-bottom", "false");
  });

  it("does not follow while older history is being prepended", () => {
    const { container } = render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={new QueryClient()}>
          <ChatMessageList
            messages={[]}
            pendingTask={null}
            availability="online"
            isFetchingOlderMessages
          />
        </QueryClientProvider>
      </I18nProvider>,
    );

    expect(container.querySelector("[data-follow-at-bottom]")).toHaveAttribute(
      "data-follow-at-bottom",
      "false",
    );
  });
});

describe("ChatMessageList live timeline (MUL-3960 regression)", () => {
  // The live footer is passed to Virtuoso through `components`. If that prop
  // is rebuilt inline on render, every streamed task:message unmounts and
  // remounts the whole footer subtree — re-parsing all Markdown and rebuilding
  // thousands of DOM rows, which froze the renderer during long agent runs.
  it("does not remount the live timeline when a streamed message arrives", async () => {
    const qc = new QueryClient();
    renderList(qc);

    const foldTrigger = await screen.findByText("2 steps");
    const footerBefore = foldTrigger.closest("div");

    pushTaskMessage(
      qc,
      taskMsg(3, "tool_use", { tool: "Read", input: { file_path: "/tmp/x" } }),
    );

    // The fold re-renders in place: same DOM node, updated count.
    const updatedTrigger = await screen.findByText("3 steps");
    expect(updatedTrigger.closest("div")).toBe(footerBefore);
    expect(document.contains(foldTrigger)).toBe(true);
  });

  it("keeps the process fold closed by the user across streamed messages", async () => {
    const qc = new QueryClient();
    renderList(qc);

    // Streaming defaults the fold open; the user closes it.
    const foldTrigger = await screen.findByText("2 steps");
    expect(screen.getByText("Bash")).toBeInTheDocument();
    act(() => {
      foldTrigger.click();
    });
    expect(screen.queryByText("Bash")).not.toBeInTheDocument();

    pushTaskMessage(
      qc,
      taskMsg(3, "tool_use", { tool: "Read", input: { file_path: "/tmp/x" } }),
    );

    // Before the fix the footer remounted, useState re-seeded defaultOpen and
    // the fold sprang back open on every streamed message.
    await screen.findByText("3 steps");
    expect(screen.queryByText("Bash")).not.toBeInTheDocument();
  });

  it("applies an embedded surface content transform to streamed text", async () => {
    const qc = new QueryClient();
    qc.setQueryData(chatKeys.taskMessages(TASK_ID), [
      taskMsg(0, "text", {
        content:
          "Draft ready.\n<agent_draft>{\"name\":\"Hidden protocol\"}</agent_draft>",
      }),
    ]);

    render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={qc}>
          <ChatMessageList
            messages={[]}
            pendingTask={{ task_id: TASK_ID, status: "running" }}
            availability="online"
            transformContent={(content) =>
              content.replace(
                /<agent_draft>[\s\S]*?<\/agent_draft>/g,
                "",
              )
            }
          />
        </QueryClientProvider>
      </I18nProvider>,
    );

    expect(await screen.findByText("Draft ready.")).toBeInTheDocument();
    expect(screen.queryByText(/Hidden protocol/)).not.toBeInTheDocument();
  });

  it("hides a partial quick-actions protocol footer while text streams", async () => {
    const qc = new QueryClient();
    qc.setQueryData(chatKeys.taskMessages(TASK_ID), [
      taskMsg(0, "text", {
        content:
          "Draft ready.\n```quick-actions\n[{\"label\":\"Hidden suggestion\"",
      }),
    ]);

    render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={qc}>
          <ChatMessageList
            messages={[]}
            pendingTask={{ task_id: TASK_ID, status: "running" }}
            availability="online"
          />
        </QueryClientProvider>
      </I18nProvider>,
    );

    expect(await screen.findByText("Draft ready.")).toBeInTheDocument();
    expect(screen.queryByText(/Hidden suggestion/)).not.toBeInTheDocument();
  });

  it("keeps attachments visible when a settled content transform removes their inline reference", async () => {
    const attachmentId = "11111111-2222-3333-4444-555555555555";
    render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={new QueryClient()}>
          <ChatMessageList
            messages={[{
              id: "transformed-attachment",
              chat_session_id: "session-1",
              role: "assistant",
              content:
                `<agent_draft>!file[report.pdf](/api/attachments/${attachmentId}/download)</agent_draft>` +
                "Visible answer",
              task_id: null,
              created_at: "2026-09-17T00:00:00Z",
              attachments: [pdfAttachment(attachmentId)],
            }]}
            pendingTask={null}
            availability="online"
            transformContent={(content) =>
              content.replace(/<agent_draft>[\s\S]*<\/agent_draft>/, "")
            }
          />
        </QueryClientProvider>
      </I18nProvider>,
    );

    expect(await screen.findByText("Visible answer")).toBeInTheDocument();
    expect(screen.getByText("report.pdf")).toBeInTheDocument();
  });

  it("does not offer Copy for an attachment-only reply", async () => {
    render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={new QueryClient()}>
          <ChatMessageList
            messages={[{
              id: "attachment-only",
              chat_session_id: "session-1",
              role: "assistant",
              content: "",
              task_id: null,
              created_at: "2026-09-17T00:00:00Z",
              attachments: [
                pdfAttachment("11111111-2222-3333-4444-555555555555"),
              ],
            }]}
            pendingTask={null}
            availability="online"
          />
        </QueryClientProvider>
      </I18nProvider>,
    );

    expect(await screen.findByText("report.pdf")).toBeInTheDocument();
    expect(screen.queryByRole("button", { name: "Copy" })).not.toBeInTheDocument();
  });

  it("renders the canonical settled answer while retaining process narration", async () => {
    const qc = new QueryClient();
    qc.setQueryData(chatKeys.taskMessages(TASK_ID), [
      taskMsg(0, "text", { content: "first timeline fragment" }),
      taskMsg(1, "thinking", { content: "checking" }),
      taskMsg(2, "text", { content: "second timeline fragment" }),
    ]);

    render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={qc}>
          <ChatMessageList
            messages={[{
              id: "settled-answer",
              chat_session_id: "session-1",
              role: "assistant",
              content: "Complete canonical answer",
              task_id: TASK_ID,
              created_at: "2026-09-17T00:00:00Z",
            }]}
            pendingTask={null}
            availability="online"
          />
        </QueryClientProvider>
      </I18nProvider>,
    );

    expect(await screen.findByText("Complete canonical answer")).toBeInTheDocument();
    expect(screen.getAllByText("Complete canonical answer")).toHaveLength(1);
    const foldTrigger = screen.getByText("1 step");
    expect(screen.queryByText("first timeline fragment")).not.toBeInTheDocument();
    expect(screen.queryByText("second timeline fragment")).not.toBeInTheDocument();

    fireEvent.click(foldTrigger);
    expect(screen.getByText("first timeline fragment")).toBeInTheDocument();
    expect(screen.queryByText("second timeline fragment")).not.toBeInTheDocument();
    expect(screen.getAllByText("Complete canonical answer")).toHaveLength(1);
  });

  it("keeps the answer node mounted across the live-to-settled handoff", async () => {
    const qc = new QueryClient();
    qc.setQueryData(chatKeys.taskMessages(TASK_ID), [
      taskMsg(0, "tool_use", { tool: "Read", input: { path: "/tmp/x" } }),
      taskMsg(1, "text", { content: "Intermediate narration" }),
      taskMsg(2, "thinking", { content: "Checking the result" }),
      taskMsg(3, "text", { content: "Stable final answer" }),
    ]);

    const view = (
      messages: Parameters<typeof ChatMessageList>[0]["messages"],
      pendingTask: Parameters<typeof ChatMessageList>[0]["pendingTask"],
    ) => (
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={qc}>
          <ChatMessageList
            messages={messages}
            pendingTask={pendingTask}
            availability="online"
          />
        </QueryClientProvider>
      </I18nProvider>
    );

    const { rerender } = render(
      view([], { task_id: TASK_ID, status: "running" }),
    );
    const answerBefore = await screen.findByText("Stable final answer");
    expect(screen.getByText("3 steps")).toBeInTheDocument();

    rerender(view([{
      id: "persisted-answer",
      chat_session_id: "session-1",
      role: "assistant",
      content: "Stable final answer",
      task_id: TASK_ID,
      created_at: "2026-09-17T00:00:00Z",
    }], null));

    expect(await screen.findByText("Stable final answer")).toBe(answerBefore);
    expect(screen.getByText("3 steps")).toBeInTheDocument();
    expect(screen.queryByText("Intermediate narration")).not.toBeInTheDocument();
  });

  it("marks only the settled answer as an annotation source, without remounting it", async () => {
    const qc = new QueryClient();
    qc.setQueryData(chatKeys.taskMessages(TASK_ID), [
      taskMsg(0, "tool_use", { tool: "Read", input: { path: "/tmp/x" } }),
      taskMsg(1, "text", { content: "Stable final answer" }),
    ]);
    const revealSourceRef: { current: ((messageId: string) => boolean) | null } = { current: null };
    const annotations = {
      cardRef: () => {},
      captureProps: {
        "data-annotation-thread": "chat:session-1" as const,
        onPointerUp: () => {}, onKeyUp: () => {}, onKeyDown: () => {},
      },
      popup: <></>,
      revealSourceRef,
    };
    const view = (
      messages: Parameters<typeof ChatMessageList>[0]["messages"],
      pendingTask: Parameters<typeof ChatMessageList>[0]["pendingTask"],
    ) => (
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={qc}>
          <ChatMessageList messages={messages} pendingTask={pendingTask} availability="online" annotations={annotations} />
        </QueryClientProvider>
      </I18nProvider>
    );

    const { rerender, container } = render(view([], { task_id: TASK_ID, status: "running" }));
    const answerBefore = await screen.findByText("Stable final answer");
    expect(container.querySelector("[data-comment-content]")).toBeNull();
    expect(revealSourceRef.current?.("persisted-answer")).toBe(false);

    rerender(view([{
      id: "persisted-answer",
      chat_session_id: "session-1",
      role: "assistant",
      content: "Stable final answer",
      task_id: TASK_ID,
      created_at: "2026-09-17T00:00:00Z",
    }], null));

    const answer = await screen.findByText("Stable final answer");
    expect(answer).toBe(answerBefore);
    expect(answer.closest("[data-comment-content]")?.getAttribute("data-comment-content")).toBe("persisted-answer");
    expect(answer.closest("[data-annotation-thread]")).not.toBeNull();
  });
});

describe("ChatMessageList tool rows (#8835 regression)", () => {
  // An HTTP-proxy MCP tool (treg's `call`) passes `query` as an object of URL
  // parameters. The row summary returned it as-is, React threw on an object
  // child, and expanding the settled fold took down the whole chat.
  it("expands a settled fold whose tool input carries non-string summary fields", async () => {
    const qc = new QueryClient();
    qc.setQueryData(chatKeys.taskMessages(TASK_ID), [
      taskMsg(0, "tool_use", {
        tool: "mcp__treg__call",
        input: {
          endpoint_id: "zerobounce.people.email.verify",
          query: { email: "[email protected]" },
        },
      }),
      taskMsg(1, "tool_result", {
        tool: "mcp__treg__call",
        output: "{\"status\": 200, \"body\": {\"email_status\": \"Verified\"}}",
      }),
      taskMsg(2, "tool_use", { tool: "Read", input: { path: { dir: "/tmp" } } }),
    ]);

    render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={qc}>
          <ChatMessageList
            messages={[{
              id: "settled-answer",
              chat_session_id: "session-1",
              role: "assistant",
              content: "The email is verified.",
              task_id: TASK_ID,
              created_at: "2026-09-25T00:00:00Z",
            }]}
            pendingTask={null}
            availability="online"
          />
        </QueryClientProvider>
      </I18nProvider>,
    );

    fireEvent.click(await screen.findByText("3 steps"));

    expect(screen.getByText("mcp__treg__call")).toBeInTheDocument();
    expect(screen.getByText("zerobounce.people.email.verify")).toBeInTheDocument();
    expect(screen.getByText("Read")).toBeInTheDocument();
  });

  it("localizes the multi-file patch summary", async () => {
    const qc = new QueryClient();
    qc.setQueryData(chatKeys.taskMessages(TASK_ID), [
      taskMsg(0, "tool_use", {
        tool: "apply_patch",
        input: {
          changes: [
            { path: "src/a.go", kind: "update", diff: "@@\n+x" },
            { path: "src/b.go", kind: "add", content: "y" },
          ],
        },
      }),
    ]);

    render(
      <I18nProvider
        locale="zh-Hans"
        resources={{ "zh-Hans": { chat: zhHansChat, agents: zhHansAgents } }}
      >
        <QueryClientProvider client={qc}>
          <ChatMessageList
            messages={[]}
            pendingTask={{ task_id: TASK_ID, status: "running" }}
            availability="online"
          />
        </QueryClientProvider>
      </I18nProvider>,
    );

    expect(await screen.findByText("src/a.go,另有 1 个文件")).toBeInTheDocument();
  });
});

describe("ChatMessageList command tool rows", () => {
  it("shows a clipped tool name and summary on focus and keeps the row expandable", async () => {
    const tool = "mcp__company-knowledge-base__search_documents_with_filters";
    const qc = new QueryClient();
    qc.setQueryData(chatKeys.taskMessages(TASK_ID), [
      taskMsg(0, "tool_use", { tool, input: { query: "release checklist" } }),
    ]);
    render(
      <TooltipProvider>
        <I18nProvider locale="en" resources={TEST_RESOURCES}>
          <QueryClientProvider client={qc}>
            <ChatMessageList messages={[]} pendingTask={{ task_id: TASK_ID, status: "running" }} availability="online" />
          </QueryClientProvider>
        </I18nProvider>
      </TooltipProvider>,
    );
    const label = await screen.findByText(tool);
    label.style.overflowX = "hidden";
    Object.defineProperties(label, {
      scrollWidth: { value: 360 },
      clientWidth: { value: 120 },
    });

    const trigger = screen.getByRole("button", { name: /mcp__company-knowledge-base__search_documents_with_filters/ });
    await act(async () => { trigger.focus(); });
    expect(trigger).toHaveFocus();
    expect(document.querySelector("[data-slot='tooltip-content']")).toHaveTextContent(`${tool} · release checklist`);

    fireEvent.click(trigger);
    expect(trigger).toHaveAttribute("aria-expanded", "true");
  });

  it("shows a command line by line, not as escaped JSON", async () => {
    const qc = new QueryClient();
    qc.setQueryData(chatKeys.taskMessages(TASK_ID), [
      taskMsg(0, "tool_use", {
        tool: "Bash",
        input: { command: "pnpm test\npnpm lint", description: "Run checks" },
      }),
    ]);

    render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={qc}>
          <ChatMessageList
            messages={[]}
            pendingTask={{ task_id: TASK_ID, status: "running" }}
            availability="online"
          />
        </QueryClientProvider>
      </I18nProvider>,
    );

    fireEvent.click(await screen.findByText("Bash"));

    // Match the raw text: the default matcher collapses the newline that this
    // test is about.
    const command = Array.from(document.querySelectorAll("pre > div")).find(
      (line) => line.textContent === "pnpm test\npnpm lint",
    );
    expect(command).toHaveClass("text-foreground");
    // Same capped, scrolling box as the panel's other inputs and results.
    expect(command?.parentElement).toHaveClass("max-h-32", "overflow-auto");
    expect(screen.queryByText(/"command":/)).not.toBeInTheDocument();
    expect(command?.nextElementSibling?.textContent).toContain('"description": "Run checks"');
  });
});

describe("ChatMessageList footer spacing", () => {
  it("keeps the bottom inset when no task is pending", () => {
    const { container } = render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={new QueryClient()}>
          <ChatMessageList
            messages={[
              {
                id: "assistant-idle",
                chat_session_id: "session-idle",
                role: "assistant",
                content: "Idle reply",
                task_id: null,
                created_at: "2026-08-12T00:00:00Z",
              },
            ]}
            pendingTask={null}
            availability="online"
          />
        </QueryClientProvider>
      </I18nProvider>,
    );

    const list = container.querySelector("[data-row-key]")?.parentElement;
    expect(list?.lastElementChild).toHaveClass("pb-4");
    expect(screen.queryByText(/working|queued/i)).not.toBeInTheDocument();
  });
});

describe("ChatMessageList quick actions", () => {
  it("renders up to three suggestions and sends the hidden prompt", async () => {
    const qc = new QueryClient();
    const onQuickAction = vi.fn();
    const quickActions = [
      { label: "Draft the brief", prompt: "Draft the complete launch brief", primary: true },
      { label: "Make a checklist", prompt: "Create a two-week launch checklist" },
      { label: "Define success", prompt: "Define the activation success metric" },
    ];

    render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={qc}>
          <ChatMessageList
            messages={[{
              id: "assistant-1",
              chat_session_id: "session-1",
              role: "assistant",
              content: "The plan is ready.",
              task_id: null,
              created_at: "2026-07-22T00:00:00Z",
              quick_actions: quickActions,
            }]}
            pendingTask={null}
            availability="online"
            onQuickAction={onQuickAction}
          />
        </QueryClientProvider>
      </I18nProvider>,
    );

    expect(await screen.findByRole("button", { name: "Draft the brief" })).toBeEnabled();
    expect(screen.getByRole("button", { name: "Make a checklist" })).toBeEnabled();
    expect(screen.getByRole("button", { name: "Define success" })).toBeEnabled();
    fireEvent.click(screen.getByRole("button", { name: "Draft the brief" }));
    expect(onQuickAction).toHaveBeenCalledWith(quickActions[0]);
  });

  it("disables suggestions while another reply is running", async () => {
    const qc = new QueryClient();
    render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={qc}>
          <ChatMessageList
            messages={[{
              id: "assistant-1",
              chat_session_id: "session-1",
              role: "assistant",
              content: "Ready.",
              task_id: null,
              created_at: "2026-07-22T00:00:00Z",
              quick_actions: [{ label: "Continue", prompt: "Continue" }],
            }]}
            pendingTask={null}
            availability="online"
            onQuickAction={vi.fn()}
            quickActionsDisabled
          />
        </QueryClientProvider>
      </I18nProvider>,
    );

    expect(await screen.findByRole("button", { name: "Continue" })).toBeDisabled();
  });
});

describe("ChatMessageList quick actions skeleton", () => {
  const assistantMessage = {
    id: "assistant-1",
    chat_session_id: "session-1",
    role: "assistant" as const,
    content: "The plan is ready.",
    task_id: null,
    created_at: "2026-07-22T00:00:00Z",
  };

  it("renders chip skeletons for the message awaiting its supplement", () => {
    const qc = new QueryClient();
    const { container } = render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={qc}>
          <ChatMessageList
            messages={[assistantMessage]}
            pendingTask={null}
            availability="online"
            onQuickAction={vi.fn()}
            quickActionsPendingMessageId="assistant-1"
          />
        </QueryClientProvider>
      </I18nProvider>,
    );
    expect(container.querySelectorAll('[aria-hidden] [data-slot="skeleton"]').length).toBeGreaterThan(0);
    expect(screen.queryByRole("button", { name: /suggested/i })).toBeNull();
  });

  it("shows no skeleton for other messages or without onQuickAction", () => {
    const qc = new QueryClient();
    const { container } = render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={qc}>
          <ChatMessageList
            messages={[assistantMessage]}
            pendingTask={null}
            availability="online"
            quickActionsPendingMessageId="assistant-1"
          />
        </QueryClientProvider>
      </I18nProvider>,
    );
    expect(container.querySelector('[aria-hidden] [data-slot="skeleton"]')).toBeNull();
  });
});

describe("ChatMessageList reply timing caption", () => {
  // Built from local components so the caption is stable in any host timezone;
  // the matcher tolerates the hour's leading zero differing between Node and
  // browser Intl ("2:32 PM" vs "02:32 PM").
  const now = new Date();
  const todayAt = (h: number, m: number) =>
    new Date(now.getFullYear(), now.getMonth(), now.getDate(), h, m).toISOString();

  it("appends the wall-clock time to the elapsed caption", async () => {
    render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={new QueryClient()}>
          <ChatMessageList
            messages={[{
              id: "timed-reply",
              chat_session_id: "s1",
              role: "assistant",
              content: "Done.",
              task_id: null,
              created_at: todayAt(14, 32),
              elapsed_ms: 38000,
            }]}
            pendingTask={null}
            availability="online"
          />
        </QueryClientProvider>
      </I18nProvider>,
    );

    expect(await screen.findByText(/Replied in 38s · 0?2:32 PM/)).toBeInTheDocument();
  });

  it("shows the time alone for legacy replies without elapsed_ms", async () => {
    render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={new QueryClient()}>
          <ChatMessageList
            messages={[{
              id: "legacy-reply",
              chat_session_id: "s1",
              role: "assistant",
              content: "Done.",
              task_id: null,
              created_at: todayAt(14, 32),
            }]}
            pendingTask={null}
            availability="online"
          />
        </QueryClientProvider>
      </I18nProvider>,
    );

    expect(await screen.findByText(/2:32 PM/)).toBeInTheDocument();
    expect(screen.queryByText(/Replied in/)).not.toBeInTheDocument();
  });

  it("timestamps failed replies", async () => {
    render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={new QueryClient()}>
          <ChatMessageList
            messages={[{
              id: "failed-reply",
              chat_session_id: "s1",
              role: "assistant",
              content: "boom",
              task_id: null,
              created_at: todayAt(14, 32),
              elapsed_ms: 12000,
              failure_reason: "manual",
            }]}
            pendingTask={undefined}
            availability="online"
          />
        </QueryClientProvider>
      </I18nProvider>,
    );

    expect(await screen.findByText(/Failed after 12s · 0?2:32 PM/)).toBeInTheDocument();
  });
});

describe("ChatMessageList onboarding kickoff", () => {
  it("hides the product-authored kickoff while rendering Mika's reply", async () => {
    render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={new QueryClient()}>
          <ChatMessageList
            messages={[
              {
                id: "kickoff",
                chat_session_id: "s1",
                role: "user",
                content: "INTERNAL ONBOARDING PROMPT",
                task_id: TASK_ID,
                created_at: new Date(0).toISOString(),
                message_kind: "onboarding_kickoff",
              },
              {
                id: "reply",
                chat_session_id: "s1",
                role: "assistant",
                content: "Hi, I'm Mika.",
                task_id: TASK_ID,
                created_at: new Date(1).toISOString(),
              },
            ]}
            pendingTask={undefined}
            availability="online"
          />
        </QueryClientProvider>
      </I18nProvider>,
    );

    expect(await screen.findByText("Hi, I'm Mika.")).toBeInTheDocument();
    expect(
      screen.queryByText("INTERNAL ONBOARDING PROMPT"),
    ).not.toBeInTheDocument();
  });
});

describe("ChatMessageList wakeup turns", () => {
  it("renders the wakeup input as a divider and the creating reply's card", async () => {
    const now = Date.now();
    render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={new QueryClient()}>
          <ChatMessageList
            messages={[
              {
                id: "promise",
                chat_session_id: "s1",
                role: "assistant",
                content: "I'll tell you when it merges.",
                task_id: "task-1",
                created_at: new Date(0).toISOString(),
              },
              {
                id: "wake-input",
                chat_session_id: "s1",
                role: "user",
                content: "",
                task_id: "task-2",
                created_at: new Date(1).toISOString(),
                message_kind: "wakeup",
                wakeup_id: "w-1",
              },
              {
                id: "report",
                chat_session_id: "s1",
                role: "assistant",
                content: "It merged.",
                task_id: "task-2",
                created_at: new Date(2).toISOString(),
              },
            ]}
            wakeups={[
              {
                id: "w-1",
                chat_session_id: "s1",
                agent_id: "agent-1",
                title: "PR #42 merged",
                instruction: "Report",
                kind: "condition",
                interval_seconds: null,
                fire_at: null,
                next_eval_at: new Date(now).toISOString(),
                expires_at: new Date(now).toISOString(),
                status: "fired",
                end_reason: "condition",
                ended_at: new Date(now).toISOString(),
                check_count: 0,
                last_check_note: null,
                last_checked_at: null,
                last_task_id: "task-2",
                last_fired_at: new Date(now).toISOString(),
                last_error: null,
                source_message_id: null,
                source_task_id: "task-1",
                created_at: new Date(now).toISOString(),
                updated_at: new Date(now).toISOString(),
              },
            ]}
            pendingTask={undefined}
            availability="online"
          />
        </QueryClientProvider>
      </I18nProvider>,
    );

    expect(await screen.findByText("It merged.")).toBeInTheDocument();
    expect(screen.getByText("Back to report · it happened · PR #42 merged")).toBeInTheDocument();
    expect(screen.getByText("Will report back: PR #42 merged")).toBeInTheDocument();
    expect(screen.getByText("Reported back")).toBeInTheDocument();
    expect(document.querySelectorAll('[data-mc="chat-bubble"]')).toHaveLength(0);
  });
});

describe("ChatMessageList channel quote presentation", () => {
  it("renders channel quote content semantically without exposing protocol metadata", async () => {
    const content =
      "> The image contains a celebration emoji.\n\n" +
      "Can you still see this image?";

    const { container } = render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={new QueryClient()}>
          <ChatMessageList
            messages={[
              {
                id: "channel-user-message",
                chat_session_id: "s1",
                role: "user",
                content,
                task_id: TASK_ID,
                created_at: new Date(0).toISOString(),
              },
            ]}
            pendingTask={undefined}
            availability="online"
          />
        </QueryClientProvider>
      </I18nProvider>,
    );

    const quote = await screen.findByText("The image contains a celebration emoji.");
    expect(quote.closest("blockquote")).not.toBeNull();
    expect(screen.getByText("Can you still see this image?")).toBeInTheDocument();
    expect(container).not.toHaveTextContent("quoted_message");
    expect(container).not.toHaveTextContent("private-message-id");
    expect(container).not.toHaveTextContent("private-platform-id");
  });

  it("renders a structured channel quote as a semantic list", async () => {
    const content =
      "> Any heading:\n>\n" +
      "> - Plain text item\n" +
      "> - Another item\n" +
      "> - [Labeled reference](https://example.com/reference)\n\n" +
      "Verify this information";

    const { container } = render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={new QueryClient()}>
          <ChatMessageList
            messages={[
              {
                id: "channel-source-list",
                chat_session_id: "s1",
                role: "user",
                content,
                task_id: TASK_ID,
                created_at: new Date(0).toISOString(),
              },
            ]}
            pendingTask={undefined}
            availability="online"
          />
        </QueryClientProvider>
      </I18nProvider>,
    );

    const quote = container.querySelector("blockquote");
    expect(quote).not.toBeNull();
    expect(await screen.findByText("Any heading:")).toBeInTheDocument();
    expect(quote?.querySelectorAll("li")).toHaveLength(3);
    expect(quote?.querySelector('a[href="https://example.com/reference"]')).toHaveTextContent(
      "Labeled reference",
    );
    expect(screen.getByText("Verify this information")).toBeInTheDocument();
  });

  it("keeps text around quoted RichText media and separates current RichText", async () => {
    const content =
      "> Quoted rich text before\n>\n" +
      "> ![Quoted image](https://example.com/quoted.png)\n>\n" +
      "> Quoted rich text after\n\n" +
      "Current rich text\n\n" +
      "![Current image](https://example.com/current.png)";

    const { container } = render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={new QueryClient()}>
          <ChatMessageList
            messages={[
              {
                id: "channel-rich-text",
                chat_session_id: "s1",
                role: "user",
                content,
                task_id: TASK_ID,
                created_at: new Date(0).toISOString(),
              },
            ]}
            pendingTask={undefined}
            availability="online"
          />
        </QueryClientProvider>
      </I18nProvider>,
    );

    const quote = container.querySelector("blockquote");
    expect(quote).not.toBeNull();
    expect(quote).toHaveTextContent("Quoted rich text before");
    expect(quote).toHaveTextContent("Quoted rich text after");
    expect(quote?.querySelector('img[alt="Quoted image"]')).not.toBeNull();
    expect(quote?.querySelector('img[alt="Current image"]')).toBeNull();
    expect(screen.getByText("Current rich text")).toBeInTheDocument();
    expect(container.querySelector('img[alt="Current image"]')).not.toBeNull();
  });
});

describe("ChatMessageList failure copy (MUL-5370 regression)", () => {
  // The backend moved to the refined taxonomy (agent_error.*) in MUL-2946 but
  // the copy map stayed on the six coarse values, so an exact-key lookup
  // missed every refined reason and fell through to the generic fallback.
  // A user whose skill bundle download stalled was told only "Something went
  // wrong", and the maintainer debugging it had nothing better to go on.
  function renderFailure(reason: string) {
    return render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={new QueryClient()}>
          <ChatMessageList
            messages={[
              {
                id: "m1",
                chat_session_id: "s1",
                role: "assistant",
                content: "skill bundle unavailable: skill \"x\"",
                task_id: null,
                created_at: new Date(0).toISOString(),
                failure_reason: reason,
              },
            ]}
            pendingTask={undefined}
            availability="online"
          />
        </QueryClientProvider>
      </I18nProvider>,
    );
  }

  const FALLBACK = enChat.message_list.failure.fallback;

  it("explains revoked access with a rebind action rather than a generic retry", async () => {
    renderFailure("runtime_access_revoked");
    expect(await screen.findByText(enChat.message_list.failure.runtime_access_revoked)).toBeInTheDocument();
    expect(screen.queryByText(FALLBACK)).not.toBeInTheDocument();
  });

  it("renders dedicated copy for a stalled skill bundle download", async () => {
    renderFailure("skill_bundle_unavailable");
    expect(
      await screen.findByText(enChat.message_list.failure.skill_bundle_unavailable),
    ).toBeInTheDocument();
    expect(screen.queryByText(FALLBACK)).not.toBeInTheDocument();
  });

  it("renders dedicated copy for a failed environment preparation", async () => {
    // #7913. Without an entry of its own this reason has no agent_error
    // family to degrade into, so it would land on the generic fallback —
    // and the one thing the reader needs to know is that the problem is on
    // the machine running the agent, which the fallback cannot say.
    renderFailure("environment_prepare_failed");
    expect(
      await screen.findByText(
        enChat.message_list.failure.environment_prepare_failed,
      ),
    ).toBeInTheDocument();
    expect(screen.queryByText(FALLBACK)).not.toBeInTheDocument();
  });

  it("tells the reader to restore or relink a deleted project folder", async () => {
    // MUL-9665. The reason has no agent_error family to degrade into, so
    // without an entry it would land on the generic fallback, which cannot
    // say the folder is gone or where to fix it.
    renderFailure("local_directory_missing");
    expect(
      await screen.findByText(enChat.message_list.failure.local_directory_missing),
    ).toBeInTheDocument();
    expect(screen.queryByText(FALLBACK)).not.toBeInTheDocument();
  });

  it("renders dedicated recovery copy for persisted runtime access denial", async () => {
    renderFailure("runtime_access_denied");
    expect(
      await screen.findByText(enChat.message_list.failure.runtime_access_denied),
    ).toBeInTheDocument();
    expect(screen.queryByText(FALLBACK)).not.toBeInTheDocument();
  });

  it("renders dedicated copy for a refined reason the map names", async () => {
    renderFailure("agent_error.provider_network");
    expect(
      await screen.findByText(enChat.message_list.failure.provider_network),
    ).toBeInTheDocument();
  });

  it("degrades an unnamed refined reason to its agent_error family", async () => {
    renderFailure("agent_error.unknown");
    expect(
      await screen.findByText(enChat.message_list.failure.agent_error),
    ).toBeInTheDocument();
    expect(screen.queryByText(FALLBACK)).not.toBeInTheDocument();
  });

  it("degrades a reason newer than this build to its agent_error family", async () => {
    renderFailure("agent_error.some_future_bucket");
    expect(
      await screen.findByText(enChat.message_list.failure.agent_error),
    ).toBeInTheDocument();
  });

  it("still falls back when neither the reason nor its family is known", async () => {
    renderFailure("something_entirely_new");
    expect(await screen.findByText(FALLBACK)).toBeInTheDocument();
  });
});

describe("ChatMessageList onboarding starter cards", () => {
  // The opening self-describes: the completion path stamps Mika's reply to the
  // hidden kickoff with message_kind "onboarding_opening" (the kickoff row
  // itself never reaches clients).
  const opening = {
    id: "opening",
    chat_session_id: "s1",
    role: "assistant" as const,
    content: "Hi, I'm Mika.",
    task_id: null,
    created_at: new Date(1).toISOString(),
    message_kind: "onboarding_opening" as const,
    quick_actions: [{ label: "LLM chip", prompt: "llm prompt" }],
  };

  function renderCards(overrides: Partial<Parameters<typeof ChatMessageList>[0]> = {}) {
    return render(
      <I18nProvider locale="en" resources={TEST_RESOURCES}>
        <QueryClientProvider client={new QueryClient()}>
          <ChatMessageList
            messages={[opening]}
            pendingTask={null}
            availability="online"
            onQuickAction={vi.fn()}
            {...overrides}
          />
        </QueryClientProvider>
      </I18nProvider>,
    );
  }

  it("renders the three cards under the opening and hides that turn's chips", async () => {
    renderCards();
    expect(
      await screen.findByRole("button", { name: "Get a board up in minutes" }),
    ).toBeEnabled();
    expect(screen.getByRole("button", { name: "Hand me one thing first" })).toBeEnabled();
    expect(
      screen.getByRole("button", { name: "Let the daily digest write itself" }),
    ).toBeEnabled();
    // The cards own the opening's suggestion strip — no chip row beside them.
    expect(screen.queryByRole("button", { name: "LLM chip" })).toBeNull();
    expect(screen.queryByText("Follow-up questions")).toBeNull();
  });

  it("sends the card's fixed prompt through the quick-action path", async () => {
    const onQuickAction = vi.fn();
    renderCards({ onQuickAction });
    fireEvent.click(
      await screen.findByRole("button", { name: "Get a board up in minutes" }),
    );
    expect(onQuickAction).toHaveBeenCalledWith({
      label: "Get a board up in minutes",
      prompt: "Turn our current goals into a project board",
    });
  });

  it("follows the chips' disabled rule while a task runs", async () => {
    renderCards({ quickActionsDisabled: true });
    expect(
      await screen.findByRole("button", { name: "Get a board up in minutes" }),
    ).toBeDisabled();
  });

  it("renders ordinary chips, not cards, for an unstamped assistant turn", async () => {
    renderCards({ messages: [{ ...opening, message_kind: "message" as const }] });
    expect(await screen.findByRole("button", { name: "LLM chip" })).toBeEnabled();
    expect(
      screen.queryByRole("button", { name: "Get a board up in minutes" }),
    ).toBeNull();
  });

  it("attaches cards only to the stamped opening; later turns keep chips", async () => {
    const followUp = {
      id: "follow-up",
      chat_session_id: "s1",
      role: "assistant" as const,
      content: "Anything else?",
      task_id: null,
      created_at: new Date(2).toISOString(),
      quick_actions: [{ label: "Later chip", prompt: "later" }],
    };
    renderCards({ messages: [opening, followUp] });
    expect(
      await screen.findByRole("button", { name: "Get a board up in minutes" }),
    ).toBeEnabled();
    expect(screen.getByRole("button", { name: "Later chip" })).toBeEnabled();
  });
});