Skip to content

Your lightweight open-source personal agent.

56.0 KB
Raw Blame
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { beforeAll, describe, expect, it, vi } from "vitest";

import { MessageBlockMenuActions, MessageBubble } from "@/components/MessageBubble";
import { preloadMarkdownText } from "@/components/MarkdownText";
import { ThreadMessages } from "@/components/thread/ThreadMessages";
import { setAppLanguage } from "@/i18n";
import { parseWebuiThreadPayload } from "@/lib/api";
import * as clipboard from "@/lib/clipboard";
import { formatMessageEndTime } from "@/lib/format-time";
import { projectWebuiThreadMessages } from "@/lib/thread-display-projection";
import { projectThreadEvents } from "@/lib/thread-event-projection";
import { ThreadTranscript } from "@/lib/thread-transcript";
import type {
  CliAppInfo,
  McpPresetInfo,
  SlashCommand,
  ThreadProjectionEvent,
  UIMessage,
} from "@/lib/types";
import { createStreamClient } from "./stream-client";

const CLI_APPS: CliAppInfo[] = [
  {
    name: "zoom",
    display_name: "Zoom",
    category: "productivity",
    description: "Meetings",
    requires: "",
    source: "harness",
    entry_point: "cli-anything-zoom",
    install_supported: true,
    installed: true,
    available: true,
    status: "installed",
    logo_url: "https://example.invalid/zoom.svg",
    brand_color: "#0B5CFF",
    skill_installed: true,
  },
  {
    name: "krita",
    display_name: "Krita",
    category: "image",
    description: "Painting",
    requires: "",
    source: "harness",
    entry_point: "cli-anything-krita",
    install_supported: true,
    installed: false,
    available: false,
    status: "not_installed",
    logo_url: null,
    brand_color: "#3BABFF",
    skill_installed: false,
  },
];

const MCP_PRESETS: McpPresetInfo[] = [
  {
    name: "browserbase",
    display_name: "Browserbase",
    category: "browser",
    description: "Cloud browser automation",
    docs_url: "https://docs.browserbase.com",
    transport: "streamableHttp",
    requires: "Browserbase API key",
    note: "",
    install_supported: true,
    installed: true,
    configured: true,
    available: true,
    status: "configured",
    logo_url: "https://example.invalid/browserbase.svg",
    brand_color: "#111827",
    required_fields: [],
    connection_summary: "https://mcp.browserbase.com/mcp",
  },
];

const SLASH_COMMANDS: SlashCommand[] = [
  {
    command: "/model",
    title: "Show or switch model",
    description: "Show the active model or switch to another configuration.",
    icon: "brain",
    lifecycle: "agent_turn_with_args",
    acceptsArgs: true,
  },
  {
    command: "/goal",
    title: "Start a goal",
    description: "Start a sustained goal.",
    icon: "activity",
    lifecycle: "agent_turn_with_args",
    acceptsArgs: true,
  },
  {
    command: "/new",
    title: "New chat",
    description: "Start a new chat.",
    icon: "square-pen",
    lifecycle: "finalize_active_turn",
    acceptsArgs: false,
  },
];

function menuActions(root: ParentNode = document): HTMLElement {
  const actions = root.querySelector<HTMLElement>("[data-message-block-menu-actions]");
  expect(actions).not.toBeNull();
  return actions!;
}

describe("MessageBubble", () => {
  beforeAll(preloadMarkdownText);

  it.each(["live", "paged history"] as const)("renders and copies literal output unchanged through %s, alongside ordinary Markdown", async (source) => {
    const raw = [
      "  Switched model preset to `raw`.",
      "__pycache__ <script>alert(\"raw\")</script>",
      "![capture](https://example.invalid/output.png)",
      "```mermaid",
      "graph TD; A-->B",
      "```",
      "$$x^2$$",
      "\x1b[31mred\x1b[0m",
      "[Subagent task completed]",
      "Task: print this",
      "Result:",
      "  literal result\t",
      "Summarize this naturally",
      "",
      "",
    ].join("\n");
    const shellEvents: ThreadProjectionEvent[] = [
      { event: "user_message", chat_id: "literal-chat", turn_id: "shell", turn_seq: 1, starts_turn: false, text: "!printf output" },
      { event: "message", chat_id: "literal-chat", turn_id: "shell", turn_seq: 2, render_as: "text", text: raw },
    ];
    const normalEvents: ThreadProjectionEvent[] = [
      { event: "user_message", chat_id: "literal-chat", turn_id: "normal", turn_seq: 1, starts_turn: true, text: "Explain the output" },
      { event: "message", chat_id: "literal-chat", turn_id: "normal", turn_seq: 2, text: "**Normal reply** [docs](https://example.invalid/docs)" },
      { event: "turn_end", chat_id: "literal-chat", turn_id: "normal", turn_seq: 3 },
    ];
    const transcript = new ThreadTranscript();
    if (source === "live") {
      const { client, receive } = createStreamClient();
      const unsubscribe = client.onTranscript("literal-chat", (event) => {
        if (event.event === "user_message" || event.event === "message" || event.event === "turn_end") {
          transcript.project(event, { createId: () => crypto.randomUUID(), now: 1_800_000_000_000 });
        }
      });
      try {
        [...shellEvents, ...normalEvents].forEach(receive);
      } finally {
        unsubscribe();
        client.close();
      }
    } else {
      expect(transcript.accept(parseWebuiThreadPayload({
        schemaVersion: 3, projection: "events", events: normalEvents, completed_turn_ids: ["normal"],
        page: { before_cursor: "before-normal", has_more_before: true, user_message_offset: 1 },
      }), transcript.begin("initial"))).toBe(true);
      expect(transcript.accept(parseWebuiThreadPayload({
        schemaVersion: 3, projection: "events", events: shellEvents,
        page: { before_cursor: null, has_more_before: false, user_message_offset: 0 },
      }), transcript.begin("older"))).toBe(true);
    }
    const writeText = vi.spyOn(clipboard, "copyTextToClipboard").mockResolvedValue(true);
    try {
      const { container } = render(<ThreadMessages messages={projectWebuiThreadMessages(transcript.messages)} />);
      const output = screen.getByTestId("plain-code-fallback");
      expect(output.textContent).toBe(raw);
      expect(output).toHaveClass("whitespace-pre-wrap");
      expect(output.querySelector("code")!.childNodes).toHaveLength(1);
      expect(output.querySelector("code")!.firstChild!.nodeType).toBe(Node.TEXT_NODE);
      expect((await screen.findByText("Normal reply")).tagName).toBe("STRONG");
      expect(container.querySelector("img, script, .katex, [data-testid='mermaid-block']")).toBeNull();
      expect(screen.getByRole("link", { name: "docs" })).toHaveAttribute("href", "https://example.invalid/docs");
      fireEvent.click(screen.getByRole("button", { name: "Copy code" }));
      await waitFor(() => expect(writeText).toHaveBeenNthCalledWith(1, raw));
      fireEvent.click(within(output.closest<HTMLElement>("[data-thread-display-unit]")!).getByRole("button", { name: "Message actions" }));
      fireEvent.click(screen.getByRole("button", { name: "Copy" }));
      await waitFor(() => expect(writeText).toHaveBeenNthCalledWith(2, raw));
    } finally {
      writeText.mockRestore();
    }
  });

  it.each([undefined, "TEXT"])("keeps Markdown after bang input unless render_as is literally text (%s)", async (render_as) => {
    const payload = parseWebuiThreadPayload({
      schemaVersion: 3, projection: "events", events: [
        { event: "user_message", chat_id: "chat", text: "!echo **ordinary output**", starts_turn: true, turn_id: "bang" },
        { event: "message", chat_id: "chat", text: "**ordinary output**", render_as, turn_id: "bang" },
      ],
    });
    const { container } = render(<ThreadMessages messages={projectWebuiThreadMessages(projectThreadEvents(payload.events))} />);
    await waitFor(() => expect(container.querySelector("[data-assistant-message] strong")?.textContent).toBe("ordinary output"));
    expect(screen.queryByTestId("plain-code-fallback")).not.toBeInTheDocument();
  });

  it.each([false, undefined])("keeps normal sources out of the block menu (fallback: %s)", (fallback) => {
    const message: UIMessage = { id: "primary", role: "assistant", content: "Hello", createdAt: 0,
      responseSources: [{ provider: "openai_codex", model: "gpt", preset: "codex", fallback }] };
    render(<MessageBlockMenuActions message={message} />);
    expect(screen.getByRole("button", { name: "Copy" })).toBeVisible();
    expect(screen.queryByRole("button", { name: /fallback/i })).not.toBeInTheDocument();
  });

  it("keeps fallback sources visible live and moves them into the completed block menu", () => {
    const message: UIMessage = { id: "actual", role: "assistant", content: "Hello", createdAt: 0,
      isStreaming: true, responseSources: [
        { provider: "openai_codex", model: "gpt", preset: "codex", fallback: false },
        { provider: "xai", model: "grok-4.5", preset: "grok", fallback: true },
      ] };
    const { container, rerender } = render(<ThreadMessages messages={[message]} isStreaming />);
    expect(screen.getByText("grok")).toBeVisible();
    expect(screen.queryByText("codex")).not.toBeInTheDocument();
    expect(screen.queryByText("grok-4.5")).not.toBeInTheDocument();
    expect(container.querySelector("img")).toHaveAttribute("alt", "");
    fireEvent.error(container.querySelector("img")!);
    expect(screen.getByText("grok")).toBeVisible();
    rerender(<ThreadMessages messages={[{ ...message, isStreaming: false }]} />);
    fireEvent.click(screen.getByRole("button", { name: "Message actions" }));
    expect(menuActions()).toContainElement(screen.getByText("grok"));
    expect(screen.getAllByText("grok")).toHaveLength(1);
    rerender(<ThreadMessages messages={[{ ...message, isStreaming: false, responseSources: undefined }]} />);
    expect(screen.queryByText("grok")).not.toBeInTheDocument();
  });

  it("explains fallback on focus and click, with the source above static metadata", async () => {
    await setAppLanguage("zh-CN");
    const description = "本条回复已切换至备用模型,由 grok 回答。";
    const { container } = render(<MessageBlockMenuActions message={{
      id: "fallback-info", role: "assistant", content: "你好", createdAt: 1,
      responseSources: [{ provider: "xai", model: "grok", preset: "grok", fallback: true }],
    }} />);
    const trigger = screen.getByRole("button", { name: description });
    const actions = menuActions(container);
    const metadata = actions.querySelector("[data-message-block-metadata]")!;
    expect(trigger.compareDocumentPosition(metadata) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
    fireEvent.focus(trigger);
    expect(await screen.findByRole("tooltip")).toHaveTextContent(description);
    fireEvent.blur(trigger);
    fireEvent.click(trigger);
    const popover = await screen.findByRole("dialog", { name: description });
    expect(popover).toHaveTextContent(description);
    expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();
    fireEvent.keyDown(popover, { key: "Escape" });
    await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
  });

  it("copies the localized compact reply instead of the stored English text", async () => {
    await setAppLanguage("zh-CN");
    const writeText = vi.fn().mockResolvedValue(undefined);
    Object.defineProperty(navigator, "clipboard", {
      configurable: true,
      value: { writeText },
    });
    const { container } = render(<ThreadMessages messages={[{
      id: "compact-empty", role: "assistant", content: "Nothing to compact.",
      compactReply: "empty", createdAt: 1,
    }]} />);
    expect(screen.getByText("无需压缩上下文")).toBeInTheDocument();
    fireEvent.click(screen.getByRole("button", { name: "消息操作" }));
    expect(container).toHaveTextContent("无需压缩上下文");
    fireEvent.click(screen.getByRole("button", { name: "复制" }));
    await waitFor(() => expect(writeText).toHaveBeenCalledWith("无需压缩上下文"));
  });

  it("renders a compacted context notice", () => {
    const message: UIMessage = {
      id: "compaction-1",
      role: "assistant",
      content: "",
      kind: "compaction",
      createdAt: Date.now(),
      compaction: {
        id: "compact-1",
        phase: "succeeded",
        announce: true,
      },
    };

    const { container } = render(<MessageBubble message={message} />);

    const notice = container.querySelector("[data-context-compaction='succeeded']");
    expect(notice).toHaveAttribute("role", "status");
    expect(notice).toHaveAttribute("aria-live", "polite");
    expect(screen.getByText("Context compacted")).toBeInTheDocument();
    expect(notice).toHaveTextContent(/^Context compacted$/);
  });

  it("renders user messages as right-aligned pills", () => {
    const message: UIMessage = {
      id: "u1",
      role: "user",
      content: "hello",
      createdAt: Date.now(),
    };

    const { container } = render(<MessageBubble message={message} />);
    const row = container.firstElementChild;
    const pill = screen.getByText("hello");

    expect(row).toHaveClass("ml-auto", "flex");
    expect(pill.parentElement).toHaveAttribute("data-user-text-bubble", "true");
    expect(pill).toHaveClass("ml-auto", "w-fit", "rounded-floating");
    expect(pill).toHaveTextContent("hello");
  });

  it("anchors the context trigger to the text even below an image or quote", () => {
    const message: UIMessage = {
      id: "u-alignment", role: "user", content: "first line\nsecond line", createdAt: 0,
    };
    const contextMenu = <button data-message-block-menu-trigger>Message actions</button>;
    const { container, rerender } = render(
      <MessageBubble message={message} contextMenu={contextMenu} />,
    );
    const anchor = container.querySelector("[data-user-text-bubble]")!;
    expect(anchor).toHaveClass("relative");
    expect(screen.getByRole("button", { name: "Message actions" }).parentElement).toBe(anchor);

    rerender(<MessageBubble message={{ ...message, images: [{ name: "image.png" }] }} contextMenu={contextMenu} />);
    expect(screen.getByRole("button", { name: "Message actions" }).parentElement)
      .toBe(container.querySelector("[data-user-text-bubble]"));

    rerender(<MessageBubble message={{ ...message, content: "> [!QUOTE]\n> excerpt\n\nreply" }} contextMenu={contextMenu} />);
    expect(screen.getByRole("button", { name: "Message actions" }).parentElement)
      .toBe(screen.getByText("reply").parentElement);
  });

  it("renders cross-session input with its public handle above a left-aligned bubble", () => {
    const message: UIMessage = {
      id: "session-message:message-1",
      role: "user",
      content: "Please review this.",
      createdAt: 1_700_000_000_123,
      sessionMessage: {
        message_id: "message-1",
        session: {
          id: "handle_0123456789abcdef0123456789abcdef",
          name: "mira-0123456789",
        },
      },
    };

    const contextMenu = <button data-message-block-menu-trigger>Message actions</button>;
    const { container } = render(<MessageBubble message={message} contextMenu={contextMenu} />);

    const row = container.querySelector("[data-session-message]")!;
    const handle = screen.getByText("@mira-0123456789");
    const bubble = row.querySelector("[data-assistant-selectable]")!.parentElement!;
    expect(row).toHaveClass("mr-auto", "w-fit", "max-w-[min(85%,36rem)]");
    expect(handle.parentElement!.parentElement).toBe(row);
    expect(bubble).toHaveClass("relative", "rounded-floating", "bg-secondary/70", "px-4", "py-2");
    expect(bubble).toContainElement(screen.getByText("Please review this."));
    expect(screen.getByRole("button", { name: "Message actions" }).parentElement).toBe(bubble);
  });

  it("outlines temporary-chat user messages with a short dashed border", () => {
    const message: UIMessage = {
      id: "u-temporary",
      role: "user",
      content: "private question",
      createdAt: Date.now(),
    };

    const { rerender } = render(<MessageBubble message={message} temporary />);
    const bubble = screen.getByText("private question");

    expect(bubble).toHaveAttribute("data-temporary-message", "true");
    expect(bubble).toHaveClass("border-dashed", "border-muted-foreground/40", "bg-transparent");

    rerender(<MessageBubble message={message} />);
    expect(bubble).not.toHaveClass("border-dashed");
    expect(bubble).toHaveClass("user-message-surface", "bg-secondary/70");
  });

  it("renders completed message branches with static wrapper classes", async () => {
    const messages: UIMessage[] = [
      {
        id: "u-persisted",
        role: "user",
        content: "Earlier question",
        createdAt: 1_700_000_000_000,
      },
      {
        id: "a-persisted",
        role: "assistant",
        content: "Earlier answer",
        createdAt: 1_700_000_001_000,
      },
      {
        id: "t-persisted",
        role: "tool",
        kind: "trace",
        content: "Earlier tool call",
        createdAt: 1_700_000_002_000,
      },
    ];

    for (const message of messages) {
      const { container, unmount } = render(<MessageBubble message={message} />);
      if (message.kind === "trace") {
        const disclosure = screen.getByRole("button", { expanded: false });
        fireEvent.click(disclosure);
        expect(disclosure).toHaveAttribute("aria-expanded", "true");
      }
      expect(await screen.findByText(message.content)).toBeVisible();
      for (const className of ["animate-in", "fade-in-0", "slide-in-from-bottom-1"]) {
        expect(container.firstElementChild).not.toHaveClass(className);
      }
      unmount();
    }
  });

  it("renders failed delivery details on focus without persistent accepted chrome", async () => {
    const message: UIMessage = {
      id: "u-delivery",
      role: "user",
      content: "hello",
      createdAt: Date.now(),
      deliveryStatus: "sending",
    };

    const { rerender } = render(<MessageBubble message={message} />);

    expect(screen.getByRole("status")).toHaveTextContent("Sending");

    rerender(<MessageBubble message={{ ...message, deliveryStatus: "accepted" }} />);
    expect(screen.queryByRole("status")).not.toBeInTheDocument();

    rerender(
      <MessageBubble
        message={{
          ...message,
          deliveryStatus: "failed",
          deliveryErrorKind: "message_too_big",
        }}
      />,
    );
    expect(screen.queryByRole("status")).not.toBeInTheDocument();
    const failedStatus = screen.getByRole("button", {
      name: "Not sent: Message too large",
    });
    expect(failedStatus).toHaveClass(
      "text-destructive/80",
      "dark:text-red-400/80",
    );
    expect(screen.getByText("hello")).not.toHaveClass("ring-1");
    expect(screen.getByText("hello")).not.toHaveClass("ring-destructive/30");
    expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();

    fireEvent.focus(failedStatus);

    const tooltip = await screen.findByRole("tooltip");
    expect(tooltip).toHaveTextContent("Message too large");
    expect(tooltip).toHaveTextContent(
      "The server rejected your last message because it exceeded the size limit.",
    );
    expect(screen.getByRole("alert")).toHaveClass("sr-only");
  });

  it("styles only generated quoted context in user messages", () => {
    const message: UIMessage = {
      id: "u-quote",
      role: "user",
      content: "> [!QUOTE]\n> selected assistant excerpt\n\nWhat about this?",
      createdAt: Date.now(),
    };

    const { rerender } = render(<MessageBubble message={message} />);

    const quote = screen.getByLabelText("Quoted context");
    expect(quote).toHaveTextContent("selected assistant excerpt");
    expect(quote).not.toHaveAttribute("title");
    expect(screen.queryByText("Quoted context")).not.toBeInTheDocument();
    expect(screen.getByText("What about this?")).toBeInTheDocument();

    rerender(
      <MessageBubble
        message={{
          ...message,
          content: "> manually typed quote\n\nWhat about this?",
        }}
      />,
    );
    expect(screen.queryByLabelText("Quoted context")).not.toBeInTheDocument();
  });

  it("copies user messages from the shared message action", async () => {
    const writeText = vi.fn().mockResolvedValue(undefined);
    Object.defineProperty(navigator, "clipboard", {
      configurable: true,
      value: { writeText },
    });
    const message: UIMessage = {
      id: "u-copy",
      role: "user",
      content: "Copy this user prompt.",
      createdAt: Date.now(),
    };

    try {
      render(<MessageBlockMenuActions message={message} />);

      fireEvent.click(screen.getByRole("button", { name: "Copy" }));

      expect(writeText).toHaveBeenCalledWith("Copy this user prompt.");
      await waitFor(() =>
        expect(screen.getByRole("button", { name: "Copied" })).toBeInTheDocument(),
      );
    } finally {
      Reflect.deleteProperty(navigator, "clipboard");
    }
  });

  it("highlights recognized slash command names without adding container chrome", () => {
    const message: UIMessage = {
      id: "u-command",
      role: "user",
      content: "/model gpt-5",
      createdAt: Date.now(),
    };

    render(<MessageBubble message={message} slashCommands={SLASH_COMMANDS} />);

    const command = screen.getByTestId("message-slash-command");
    expect(command).toHaveTextContent("/model");
    expect(command).toHaveClass(
      "font-normal",
      "transition-colors",
      "duration-150",
    );
    expect(command).not.toHaveClass("font-mono");
    expect(command.getAttribute("style")).not.toContain("text-shadow");
    expect(command.getAttribute("style")).toContain("var(--inline-reference-highlight)");
    expect(command.firstElementChild).toHaveTextContent(/^\/$/);
    expect(command.firstElementChild).toHaveClass("opacity-90");
    expect(command.className).not.toMatch(/(?:^|\s)(?:bg-|border|ring|rounded)/);
    expect(command.parentElement).toHaveTextContent("/model gpt-5");
    expect(command.parentElement).toHaveClass("rounded-floating", "user-message-surface", "bg-secondary/70");
  });

  it("keeps unknown and invalid slash commands as plain message text", () => {
    const unknown: UIMessage = {
      id: "u-unknown-command",
      role: "user",
      content: "/unknown value",
      createdAt: Date.now(),
    };
    const invalidExactCommand: UIMessage = {
      id: "u-invalid-command",
      role: "user",
      content: "/new with-arguments",
      createdAt: Date.now(),
    };

    const { rerender } = render(
      <MessageBubble message={unknown} slashCommands={SLASH_COMMANDS} />,
    );
    expect(screen.queryByTestId("message-slash-command")).not.toBeInTheDocument();
    expect(screen.getByText("/unknown value")).toBeInTheDocument();

    rerender(<MessageBubble message={invalidExactCommand} slashCommands={SLASH_COMMANDS} />);
    expect(screen.queryByTestId("message-slash-command")).not.toBeInTheDocument();
    expect(screen.getByText("/new with-arguments")).toBeInTheDocument();
  });

  it("preserves installed capability mentions in slash command arguments", () => {
    const message: UIMessage = {
      id: "u-command-mention",
      role: "user",
      content: "/goal ask $github and @zoom to schedule the review",
      createdAt: Date.now(),
    };

    render(
      <MessageBubble
        message={message}
        slashCommands={SLASH_COMMANDS}
        cliApps={CLI_APPS}
      />,
    );

    const command = screen.getByTestId("message-slash-command");
    const skill = screen.getByTestId("message-skill-reference-github");
    expect(command).toHaveTextContent("/goal");
    expect(skill).toHaveTextContent("$github");
    expect(command.className).toBe(skill.className);
    expect(command.getAttribute("style")).toBe(skill.getAttribute("style"));
    expect(screen.getByTestId("message-cli-mention-zoom")).toHaveTextContent("@Zoom");
  });

  it.each(["! ls", "  !pwd", '!echo "$github" @zoom\nWrite-Output "hello!"'])("highlights a sent bang prefix while preserving the command literally: %s", (content) => {
    const message: UIMessage = { id: "u-shell", role: "user", content, createdAt: Date.now() };
    const { container, rerender } = render(<MessageBubble message={message} cliApps={CLI_APPS} />);
    const prefix = screen.getByTestId("message-shell-prefix");
    expect(prefix).toHaveTextContent(/^!$/);
    expect(prefix).toHaveClass("font-normal");
    expect(prefix.style.color).toBe("var(--inline-reference-highlight)");
    expect(container.querySelector("[data-user-text-bubble] p")?.textContent).toBe(content);

    rerender(<MessageBubble message={{ ...message, content: "Explain !pwd, please!" }} />);
    expect(screen.queryByTestId("message-shell-prefix")).not.toBeInTheDocument();
    expect(container.querySelector("[data-user-text-bubble] p")?.textContent).toBe("Explain !pwd, please!");
  });

  it("highlights skill references without a live skill catalog", () => {
    const message: UIMessage = {
      id: "u-skill-reference",
      role: "user",
      content: "Ask $github to review this with @zoom",
      createdAt: Date.now(),
    };

    render(
      <MessageBubble
        message={message}
        cliApps={CLI_APPS}
      />,
    );

    const skill = screen.getByTestId("message-skill-reference-github");
    expect(skill).toHaveTextContent(/^\$github$/);
    expect(skill).toHaveClass(
      "font-normal",
      "transition-colors",
      "duration-150",
    );
    expect(skill.getAttribute("style")).not.toContain("text-shadow");
    expect(skill.getAttribute("style")).toContain("var(--inline-reference-highlight)");
    expect(skill.className).not.toMatch(/(?:^|\s)(?:bg-|border|ring|rounded)/);
    expect(skill).not.toHaveAttribute("title");
    expect(screen.getByTestId("message-cli-mention-zoom")).toHaveTextContent("@Zoom");
    expect(skill.parentElement).toHaveTextContent("Ask $github to review this with @Zoom");
  });

  it("highlights well-formed skill references and leaves a bare marker plain", () => {
    const message: UIMessage = {
      id: "u-plain-skill-reference",
      role: "user",
      content: "Try $unknown or $blocked-skill and $",
      createdAt: Date.now(),
    };

    render(<MessageBubble message={message} />);

    expect(screen.getByTestId("message-skill-reference-unknown")).toHaveTextContent(/^\$unknown$/);
    expect(screen.getByTestId("message-skill-reference-blocked-skill"))
      .toHaveTextContent(/^\$blocked-skill$/);
    const references = screen.getAllByTestId(/^message-skill-reference-/);
    expect(references).toHaveLength(2);
    expect(references[0].parentElement)
      .toHaveTextContent("Try $unknown or $blocked-skill and $");
  });

  it("renders fork as a contextual assistant action", () => {
    const onForkFromHere = vi.fn();
    const message: UIMessage = {
      id: "a-fork",
      role: "assistant",
      content: "branch after this answer",
      latencyMs: 1_200,
      createdAt: Date.now(),
    };

    const { container } = render(
      <MessageBlockMenuActions message={message} onForkFromHere={onForkFromHere} />,
    );

    menuActions(container);
    fireEvent.click(screen.getByRole("button", { name: "New chat from here" }));
    expect(onForkFromHere).toHaveBeenCalledTimes(1);
  });

  it("keeps assistant completion time in the block menu metadata", () => {
    const completedAt = Date.UTC(2026, 6, 25, 12, 34, 56);
    const { container } = render(
      <MessageBlockMenuActions
        message={{
          id: "a-completed-at",
          role: "assistant",
          content: "Finished answer",
          latencyMs: 13_000,
          completedAt,
          createdAt: Date.now(),
        }}
      />,
    );

    menuActions(container);
    const time = document.querySelector("[data-assistant-completed-at]");
    expect(time).toHaveTextContent(formatMessageEndTime(completedAt));
    expect(time).toHaveAttribute("dateTime", new Date(completedAt).toISOString());
    expect(time).toHaveClass("tabular-nums");
  });

  it("groups actions above static timestamp metadata", () => {
    const completedAt = Date.UTC(2026, 6, 25, 12, 34, 56);
    const { container } = render(<MessageBlockMenuActions
      message={{ id: "a-actions", role: "assistant", content: "Finished answer",
        completedAt, createdAt: completedAt - 1_000 }}
      onForkFromHere={vi.fn()}
    />);
    const actions = menuActions(container);
    const copy = screen.getByRole("button", { name: "Copy" });
    const fork = screen.getByRole("button", { name: "New chat from here" });
    const metadata = actions.querySelector("[data-message-block-metadata]")!;
    expect(actions.querySelector("[data-message-block-toolbar]")).toContainElement(copy);
    expect(actions.querySelector("[data-message-block-toolbar]")).toContainElement(fork);
    expect(metadata).toHaveTextContent(formatMessageEndTime(completedAt));
    expect(copy.compareDocumentPosition(fork) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
    expect(fork.compareDocumentPosition(metadata) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
  });

  it("falls back to the assistant creation time when replay has no completion time", () => {
    const createdAt = Date.UTC(2026, 6, 25, 12, 34, 56);
    const { container } = render(
      <MessageBlockMenuActions
        message={{
          id: "a-created-at",
          role: "assistant",
          content: "Proactive answer",
          createdAt,
        }}
      />,
    );

    menuActions(container);
    const time = document.querySelector("[data-message-timestamp]");
    expect(time).toHaveTextContent(formatMessageEndTime(createdAt));
    expect(time).toHaveAttribute("dateTime", new Date(createdAt).toISOString());
    expect(time).not.toHaveAttribute("data-assistant-completed-at");
  });

  it("renders the creation time for user messages", () => {
    const createdAt = Date.UTC(2026, 6, 25, 12, 34, 56);
    const { container } = render(
      <MessageBlockMenuActions
        message={{
          id: "u-created-at",
          role: "user",
          content: "A user message",
          createdAt,
        }}
      />,
    );

    const time = container.querySelector("[data-message-created-at]");
    expect(time).toHaveTextContent(formatMessageEndTime(createdAt));
    expect(time).toHaveAttribute("dateTime", new Date(createdAt).toISOString());
    expect(time).not.toHaveAttribute("title");
    expect(time).toHaveProperty("tabIndex", -1);
    expect(time?.parentElement).toHaveAttribute("data-message-block-metadata");
  });

  it("does not infer completion time from the assistant creation timestamp", () => {
    const createdAt = Date.UTC(2026, 6, 25, 12, 34, 0);
    const latencyMs = 13_000;
    const { container } = render(
      <MessageBlockMenuActions
        message={{
          id: "a-replayed-completion",
          role: "assistant",
          content: "Replayed answer",
          latencyMs,
          createdAt,
        }}
      />,
    );

    menuActions(container);
    expect(document.querySelector("[data-assistant-completed-at]")).not.toBeInTheDocument();
    expect(document.querySelector("[data-message-timestamp]")).toHaveTextContent(
      formatMessageEndTime(createdAt),
    );
  });

  it("preserves punctuation-separated session links and capability mentions in sent messages", () => {
    const message: UIMessage = {
      id: "u-punctuation-mentions",
      role: "user",
      content: "@bime、@luma,@luma;@zoom:@browserbase。",
      sessionMentions: [
        { id: "handle_00000000000000000000000000000001", name: "bime", session_key: "websocket:pricing", title: "Pricing" },
        { id: "handle_00000000000000000000000000000002", name: "luma", session_key: "websocket:notes", title: "Notes" },
      ],
      createdAt: Date.now(),
    };

    render(<MessageBubble message={message} cliApps={CLI_APPS} mcpPresets={MCP_PRESETS} />);

    expect(screen.getByTestId("message-session-mention-bime").closest("a"))
      .toHaveAttribute("href", "#/chat/websocket%3Apricing");
    const repeated = screen.getAllByTestId("message-session-mention-luma");
    expect(repeated).toHaveLength(2);
    for (const token of repeated) {
      expect(token.closest("a")).toHaveAttribute("href", "#/chat/websocket%3Anotes");
    }
    expect(screen.getByTestId("message-cli-mention-zoom")).toHaveTextContent("@Zoom");
    expect(screen.getByTestId("message-mcp-mention-browserbase")).toHaveTextContent("@Browserbase");
  });

  it("renders installed CLI app mentions inside sent user messages", () => {
    const message: UIMessage = {
      id: "u-cli",
      role: "user",
      content: "Hi nano, please use @zoom to book a meeting, not @krita",
      createdAt: Date.now(),
    };

    render(<MessageBubble message={message} cliApps={CLI_APPS} />);

    const token = screen.getByTestId("message-cli-mention-zoom");
    expect(token).toHaveTextContent("@Zoom");
    expect(token).toHaveAttribute("title", "CLI app: Zoom (@zoom)");
    expect(token).toHaveClass("font-[550]");
    expect(token.className).not.toContain("rounded");
    expect(token.className).not.toContain("px-");
    expect(token).toHaveClass("text-foreground");
    expect(token.style.textShadow).toBe("");
    const logo = screen.getByTestId("message-cli-mention-logo-zoom");
    expect(logo).toHaveClass("h-[1.1em]", "w-[1.1em]", "rounded-[0.25em]", "top-1/2", "-translate-y-1/2");
    expect(logo.parentElement).toHaveClass("mr-1", "w-[1.1em]");
    expect(screen.queryByTestId("message-cli-mention-krita")).not.toBeInTheDocument();
    expect(screen.getByText(/not @krita/)).toBeInTheDocument();
  });

  it("places automation metadata after the timestamp with its source visible", () => {
    const completedAt = Date.UTC(2026, 6, 25, 12, 34, 56);
    const message: UIMessage = {
      id: "a-cron",
      role: "assistant",
      content: "Time to drink water.",
      source: { kind: "cron", label: "drink water" },
      completedAt,
      createdAt: completedAt - 1_000,
    };

    const { container } = render(<MessageBlockMenuActions message={message} />);

    menuActions(container);

    const timestamp = document.querySelector("[data-message-timestamp]")!;
    const automation = document.querySelector("[data-automation-trigger]")!;
    expect(timestamp).toHaveTextContent(formatMessageEndTime(completedAt));
    expect(automation).toHaveTextContent("Triggered automatically drink water");
    expect(timestamp.compareDocumentPosition(automation) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
  });

  it("renders structured CLI app attachments even without the installed catalog", () => {
    const message: UIMessage = {
      id: "u-cli-attached",
      role: "user",
      content: "Please use @drawio for the diagram",
      createdAt: Date.now(),
      cliApps: [{
        name: "drawio",
        display_name: "Draw.io",
        category: "diagram",
        entry_point: "cli-anything-drawio",
        logo_url: "https://example.invalid/drawio.svg",
        brand_color: "#F08705",
      }],
    };

    render(<MessageBubble message={message} cliApps={[]} />);

    const token = screen.getByTestId("message-cli-mention-drawio");
    expect(token).toHaveTextContent("@Draw.io");
    expect(token.className).not.toContain("rounded");
    expect(token.className).not.toContain("px-");
    expect(token).toHaveClass("text-foreground");
    expect(screen.getByTestId("message-cli-mention-logo-drawio")).toBeInTheDocument();
  });

  it("renders MCP preset mentions inside sent user messages", () => {
    const message: UIMessage = {
      id: "u-mcp",
      role: "user",
      content: "Use @browserbase to inspect the checkout flow",
      createdAt: Date.now(),
    };

    render(<MessageBubble message={message} mcpPresets={MCP_PRESETS} />);

    const token = screen.getByTestId("message-mcp-mention-browserbase");
    expect(token).toHaveTextContent("@Browserbase");
    expect(token).toHaveAttribute("title", "MCP server: Browserbase (@browserbase)");
    expect(token).toHaveClass("text-foreground");
    const logo = screen.getByTestId("message-mcp-mention-logo-browserbase");
    expect(logo).toHaveClass("h-[1.1em]", "w-[1.1em]", "rounded-[0.25em]", "top-1/2", "-translate-y-1/2");
    expect(logo.parentElement).toHaveClass("mr-1", "w-[1.1em]");
  });

  it.each((["cli", "mcp"] as const).flatMap((kind) => [
    ["linear", "Linear", "Linear"],
    ["iterm2", "iTerm2", "iTerm2"],
    ["drawio", "Draw.io", "Draw.io"],
    ["gimp", "GIMP", "GIMP"],
    ["google-drive", "Google Drive", "Google Drive"],
    ["1password-cli", "1Password CLI", "1Password CLI"],
    ["feishu-cli", "Feishu/Lark CLI", "Feishu/Lark CLI"],
    ["local-app", "  本地应用  ", "本地应用"],
    ["fallback-app", "   ", "fallback-app"],
  ].map(([name, displayName, expected]) => ({ kind, name, displayName, expected }))))(
    "uses the saved display name for $kind $name without rewriting its identifier",
    ({ kind, name, displayName, expected }) => {
      const message: UIMessage = {
        id: "saved-app-name",
        role: "user",
        content: `Use @${name} please`,
        createdAt: 1,
        ...(kind === "cli" ? {
          cliApps: [{ name, display_name: displayName, category: "test", entry_point: name }],
        } : {
          mcpPresets: [{ name, display_name: displayName, category: "test", transport: "stdio" }],
        }),
      };
      render(<MessageBubble message={message} />);
      const token = screen.getByTestId(`message-${kind}-mention-${name}`);
      expect(token.textContent).toBe(`@${expected}`);
      expect(token).toHaveAttribute("title", `${kind === "cli" ? "CLI app" : "MCP server"}: ${expected} (@${name})`);
      expect(token).toHaveClass("inline-flex", "items-baseline", "max-w-full", "[overflow-wrap:anywhere]");
      expect(token.firstElementChild).toHaveClass("shrink-0");
      expect(token.lastElementChild).toHaveClass("min-w-0", "font-semibold");
      expect(message.content).toBe(`Use @${name} please`);
    },
  );

  it("copies the original mention identifiers rather than display names", async () => {
    const copy = vi.spyOn(clipboard, "copyTextToClipboard").mockResolvedValue(true);
    try {
      render(<ThreadMessages messages={[{
        id: "copy-display-name", role: "user", content: "Please use @drawio", createdAt: 1,
        cliApps: [{ name: "drawio", display_name: "Draw.io", category: "diagram", entry_point: "drawio" }],
      }]} />);
      expect(screen.getByTestId("message-cli-mention-drawio")).toHaveTextContent("@Draw.io");
      fireEvent.click(screen.getByRole("button", { name: "Message actions" }));
      fireEvent.click(screen.getByRole("button", { name: "Copy" }));
      await waitFor(() => expect(copy).toHaveBeenCalledWith("Please use @drawio"));
    } finally {
      copy.mockRestore();
    }
  });

  it("renders persisted session mentions inside sent user messages", () => {
    const message: UIMessage = {
      id: "u-session",
      role: "user",
      content: "Use @收费设计 as context",
      createdAt: Date.now(),
      sessionMentions: [{
        name: "收费设计",
        session_key: "websocket:pricing",
        title: "收费设计",
      }],
    };

    render(<MessageBubble message={message} />);

    const token = screen.getByTestId("message-session-mention-收费设计");
    expect(token).toHaveTextContent("@收费设计");
    expect(token).toHaveAttribute("title", "Session: 收费设计");
    expect(token.closest("a")).toHaveAttribute("href", "#/chat/websocket%3Apricing");
    expect(token.closest("a")?.getAttribute("style")).toContain(
      "text-decoration-color: var(--inline-token-highlight)",
    );
  });

  it("copies completed assistant replies from the action row", async () => {
    const writeText = vi.fn().mockResolvedValue(undefined);
    Object.defineProperty(navigator, "clipboard", {
      configurable: true,
      value: { writeText },
    });
    const message: UIMessage = {
      id: "a-copy",
      role: "assistant",
      content: "I can help with the next step.",
      createdAt: Date.now(),
    };

    const { container } = render(<MessageBlockMenuActions message={message} />);

    menuActions(container);
    fireEvent.click(screen.getByRole("button", { name: "Copy" }));

    expect(writeText).toHaveBeenCalledWith("I can help with the next step.");
    await waitFor(() =>
      expect(screen.getByRole("button", { name: "Copied" })).toBeInTheDocument(),
    );
  });

  it("copies completed assistant replies with the textarea fallback", async () => {
    Object.defineProperty(navigator, "clipboard", {
      configurable: true,
      value: undefined,
    });
    const execCommand = vi.fn().mockReturnValue(true);
    Object.defineProperty(document, "execCommand", {
      configurable: true,
      value: execCommand,
    });
    const message: UIMessage = {
      id: "a-copy-fallback",
      role: "assistant",
      content: "Fallback copy reply.",
      createdAt: Date.now(),
    };

    try {
      const { container } = render(<MessageBlockMenuActions message={message} />);

      menuActions(container);
      fireEvent.click(screen.getByRole("button", { name: "Copy" }));

      await waitFor(() => expect(execCommand).toHaveBeenCalledWith("copy"));
    } finally {
      Reflect.deleteProperty(navigator, "clipboard");
      Reflect.deleteProperty(document, "execCommand");
    }
  });

  it("falls back when the Clipboard API rejects assistant reply copy", async () => {
    const writeText = vi.fn().mockRejectedValue(new Error("not allowed"));
    Object.defineProperty(navigator, "clipboard", {
      configurable: true,
      value: { writeText },
    });
    const execCommand = vi.fn().mockReturnValue(true);
    Object.defineProperty(document, "execCommand", {
      configurable: true,
      value: execCommand,
    });
    const message: UIMessage = {
      id: "a-copy-reject",
      role: "assistant",
      content: "Rejected clipboard copy.",
      createdAt: Date.now(),
    };

    try {
      const { container } = render(<MessageBlockMenuActions message={message} />);

      menuActions(container);
      fireEvent.click(screen.getByRole("button", { name: "Copy" }));

      expect(writeText).toHaveBeenCalledWith("Rejected clipboard copy.");
      await waitFor(() => expect(execCommand).toHaveBeenCalledWith("copy"));
    } finally {
      Reflect.deleteProperty(navigator, "clipboard");
      Reflect.deleteProperty(document, "execCommand");
    }
  });

  it("does not show copy actions for streaming placeholders", () => {
    const message: UIMessage = {
      id: "a-streaming",
      role: "assistant",
      content: "",
      isStreaming: true,
      createdAt: Date.now(),
    };

    render(<MessageBubble message={message} />);

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

  it("keeps the assistant body mounted when its completed block menu becomes available", () => {
    const message: UIMessage = { id: "a-stable", role: "assistant", content: "Stable answer",
      isStreaming: true, createdAt: Date.now() };
    const { container, rerender } = render(<ThreadMessages messages={[message]} isStreaming />);
    const body = container.querySelector("[data-assistant-message]");
    expect(body).toHaveClass("relative", "w-full");
    rerender(<ThreadMessages messages={[{ ...message, isStreaming: false }]} />);
    expect(container.querySelector("[data-assistant-message]")).toBe(body);
    fireEvent.click(screen.getByRole("button", { name: "Message actions" }));
    expect(screen.getByRole("button", { name: "Copy" })).toBeVisible();
  });

  it("makes answer actions available after the containing turn completes", () => {
    const message: UIMessage = { id: "a-intermediate", role: "assistant",
      content: "I will keep working.", createdAt: Date.now() };
    const { rerender } = render(<ThreadMessages messages={[message]} isStreaming />);
    expect(screen.getByText(message.content)).toBeVisible();
    expect(screen.queryByRole("button", { name: "Message actions" })).not.toBeInTheDocument();
    rerender(<ThreadMessages messages={[message]} />);
    expect(screen.getByRole("button", { name: "Message actions" })).toBeInTheDocument();
  });

  it("keeps timestamp metadata available for a media-only message", () => {
    const createdAt = Date.UTC(2026, 6, 25, 12, 34, 56);
    const { container } = render(<MessageBlockMenuActions
      message={{ id: "a-file", role: "assistant", content: "", createdAt,
        media: [{ kind: "file", name: "report.csv", url: "/api/media/report.csv" }] }}
    />);
    expect(container.querySelector("time")).toHaveTextContent(formatMessageEndTime(createdAt));
    expect(container.querySelector("time")).toHaveAttribute("dateTime", new Date(createdAt).toISOString());
  });

  it("renders trace messages as collapsible tool groups", () => {
    const message: UIMessage = {
      id: "t1",
      role: "tool",
      kind: "trace",
      content: 'search "hk weather"',
      traces: ['weather("get")', 'search "hk weather"'],
      createdAt: Date.now(),
    };

    render(<MessageBubble message={message} />);
    const toggle = screen.getByRole("button", { name: /used 2 tools/i });

    const content = document.getElementById(toggle.getAttribute("aria-controls")!)!;
    expect(content).toHaveAttribute("data-state", "closed");
    expect(content).toHaveAttribute("inert");
    expect(screen.queryByRole("list")).not.toBeInTheDocument();

    fireEvent.click(toggle);
    expect(screen.getByText('weather("get")')).toBeInTheDocument();
    expect(screen.getByText('search "hk weather"')).toBeInTheDocument();
    expect(content).toHaveAttribute("data-state", "open");
    fireEvent.click(toggle);
    expect(content).toHaveAttribute("data-state", "closed");
    expect(content).toHaveAttribute("aria-hidden", "true");
    expect(screen.queryByText('weather("get")')).not.toBeInTheDocument();
  });

  it("lazily mounts large trace groups and releases them only after an uninterrupted exit", async () => {
    const traces = Array.from({ length: 1000 }, (_, index) => `tool call ${index}`);
    render(<MessageBubble message={{
      id: "large-trace", role: "tool", kind: "trace",
      content: traces[0], traces, createdAt: Date.now(),
    }} />);
    const toggle = screen.getByRole("button", { name: /used 1000 tools/i });
    const content = document.getElementById(toggle.getAttribute("aria-controls")!)!;
    // Hidden content must not allocate a DOM node for every historical trace.
    expect(content.querySelectorAll("li")).toHaveLength(0);
    fireEvent.click(toggle);
    expect(content.querySelectorAll("li")).toHaveLength(1000);

    let finishExit!: () => void;
    const getAnimations = vi.fn(() => [{
      finished: new Promise<void>((resolve) => { finishExit = resolve; }),
    }]);
    Object.defineProperty(content, "getAnimations", { value: getAnimations });
    fireEvent.click(toggle);
    expect(content.querySelectorAll("li")).toHaveLength(1000);
    expect(content).toHaveAttribute("inert");

    // Reopening cancels cleanup of the previous exit, even if it finishes later.
    fireEvent.click(toggle);
    await act(async () => { finishExit(); });
    expect(content.querySelectorAll("li")).toHaveLength(1000);
    expect(content).not.toHaveAttribute("inert");

    fireEvent.click(toggle);
    expect(getAnimations).toHaveBeenCalledTimes(2);
    await act(async () => { finishExit(); });
    expect(content.querySelectorAll("li")).toHaveLength(0);
    fireEvent.click(toggle);
    expect(content.querySelectorAll("li")).toHaveLength(1000);
  });

  it("retries a failed video locally without replacing a healthy player on history updates", () => {
    const message: UIMessage = { id: "retry-video", role: "user", content: "watch", createdAt: 0,
      media: [{ kind: "video", name: "clip.webm", url: "/api/media/sig/clip" }] };
    const { container, rerender } = render(<MessageBubble message={message} />);
    const original = container.querySelector("video")!;
    fireEvent.error(original);
    expect(container.querySelector("video")).not.toBeInTheDocument();
    fireEvent.click(screen.getByRole("button", { name: "Retry" }));
    const retried = container.querySelector("video")!;
    expect(retried).toHaveAttribute("src", "/api/media/sig/clip");
    expect(retried).not.toBe(original);
    rerender(<MessageBubble message={{ ...message, media: [...message.media!] }} />);
    expect(container.querySelector("video")).toBe(retried);
    fireEvent.error(retried);
    expect(screen.getByRole("button", { name: "Retry" })).toBeVisible();
  });

  it("renders video media as an inline player", () => {
    const message: UIMessage = {
      id: "a1",
      role: "assistant",
      content: "here is the clip",
      createdAt: Date.now(),
      media: [
        {
          kind: "video",
          url: "/api/media/sig/payload",
          name: "demo.mp4",
        },
      ],
    };

    const { container } = render(<MessageBubble message={message} />);

    expect(screen.getByText("here is the clip")).toBeInTheDocument();
    const video = screen.getByLabelText(/video attachment/i);
    expect(video.tagName).toBe("VIDEO");
    expect(video).toHaveAttribute("src", "/api/media/sig/payload");
    expect(video).toHaveAttribute("preload", "metadata");
    expect(container.querySelector("video[controls]")).toBeInTheDocument();
    expect(screen.queryByText("Preview")).not.toBeInTheDocument();
    expect(screen.queryByText("Code")).not.toBeInTheDocument();
  });

  it("starts an uploaded player from its accepted URL and preserves it through hydration", () => {
    const message: UIMessage = {
      id: "optimistic-user", role: "user", content: "Watch this", createdAt: 1,
      turnId: "video-turn", turnPhase: "user", deliveryStatus: "sending",
      media: [{ kind: "video", name: "clip.webm" }],
    };
    const accepted: UIMessage = {
      ...message, deliveryStatus: "accepted",
      media: [{ kind: "video", name: "clip.webm", url: "/api/media/sig/clip" }],
    };
    const { rerender, unmount } = render(<ThreadMessages messages={[message]} />);
    expect(screen.queryByLabelText(/video attachment/i)?.tagName).not.toBe("VIDEO");
    expect(screen.queryByText(/attachment unavailable/i)).not.toBeInTheDocument();
    rerender(<ThreadMessages messages={[accepted]} />);
    const video = screen.getByLabelText(/video attachment/i);
    rerender(<ThreadMessages messages={[{ ...accepted, id: "history-user" }]} />);
    expect(screen.getByLabelText(/video attachment/i)).toBe(video);
    expect(video).toHaveAttribute("src", "/api/media/sig/clip");
    unmount();
    render(<ThreadMessages messages={[accepted]} />);
    expect(screen.getByLabelText(/video attachment/i)).toHaveAttribute("src", "/api/media/sig/clip");
  });

  it("renders streaming reasoning as one compact activity line", () => {
    const message: UIMessage = {
      id: "a-reasoning-streaming",
      role: "assistant",
      content: "",
      createdAt: Date.now(),
      reasoning: "Step 1: parse intent. Step 2: compute.",
      reasoningStreaming: true,
    };

    const { container } = render(<MessageBubble message={message} />);

    const preview = screen.getByText("Step 1: parse intent. Step 2: compute.");
    expect(preview).toBeInTheDocument();
    expect(container.querySelector(".reasoning-sheen-stripe")).not.toBeInTheDocument();
    expect(preview).toHaveClass("streaming-text-sheen");
    expect(preview).toHaveAttribute(
      "data-sheen-text",
      "Step 1: parse intent. Step 2: compute.",
    );
    expect(screen.queryByText("Thinking…")).not.toBeInTheDocument();
    expect(screen.queryByRole("button", { name: /thinking/i })).not.toBeInTheDocument();
  });

  it("keeps completed reasoning on one line above the answer", () => {
    const message: UIMessage = {
      id: "a-reasoning-done",
      role: "assistant",
      content: "The answer is 42.",
      createdAt: Date.now(),
      reasoning: "hidden until expanded",
      reasoningStreaming: false,
    };

    render(<MessageBubble message={message} />);

    const preview = screen.getByText("hidden until expanded");
    expect(preview).toBeInTheDocument();
    expect(screen.getByText("The answer is 42.")).toBeInTheDocument();
    expect(preview.closest('[data-testid="activity-step"]')).toHaveClass("mb-2");
    expect(screen.queryByText("Thinking")).not.toBeInTheDocument();
    expect(screen.queryByRole("button", { name: /thinking/i })).not.toBeInTheDocument();
  });

  it("compacts reasoning markdown into plain single-line text", () => {
    const message: UIMessage = {
      id: "a-reasoning-md",
      role: "assistant",
      content: "",
      createdAt: Date.now(),
      reasoning: "### Section title\n\nBody line.",
      reasoningStreaming: false,
    };

    const { container } = render(<MessageBubble message={message} />);

    expect(screen.getByText("Section title Body line.")).toBeInTheDocument();
    expect(container.textContent).not.toContain("###");
    expect(container.querySelector("h3")).not.toBeInTheDocument();
  });

  it("renders inline file paths as compact file references", async () => {
    await import("@/components/MarkdownTextRenderer");
    const message: UIMessage = {
      id: "a-file-path",
      role: "assistant",
      content:
        "改动在 `webui/src/components/MarkdownTextRenderer.tsx` 和 `/Users/renxubin/.nanobot/workspace/minecraft-fps/index.html`。",
      createdAt: Date.now(),
    };

    try {
      render(<MessageBubble message={message} />);

      const references = await screen.findAllByTestId("inline-file-path");
      expect(references).toHaveLength(2);
      expect(references[0].parentElement).not.toHaveClass("translate-y-[0.08em]");
      expect(references[0].parentElement).toHaveClass("align-baseline");
      expect(references[0].parentElement).toHaveClass("leading-[inherit]");
      expect(references[0]).toHaveClass("items-baseline");
      expect(references[0]).toHaveTextContent("MarkdownTextRenderer.tsx");
      expect(references[0]).not.toHaveTextContent("webui/src/components");
      expect(screen.getByText("index.html")).toBeInTheDocument();
      expect(references[1]).not.toHaveTextContent("/Users/renxubin");
      expect(references[1]).not.toHaveAttribute("title");
      expect(references[1]).toHaveAttribute(
        "aria-label",
        "/Users/renxubin/.nanobot/workspace/minecraft-fps/index.html",
      );

      vi.useFakeTimers();
      fireEvent.pointerMove(references[1].parentElement!);
      await act(async () => {
        vi.advanceTimersByTime(500);
      });
      const tooltip = screen.getByRole("tooltip");
      expect(tooltip).toHaveTextContent(
        "/Users/renxubin/.nanobot/workspace/minecraft-fps/index.html",
      );
    } finally {
      vi.useRealTimers();
    }
  });

  it("renders assistant image media as a larger generated result", () => {
    const message: UIMessage = {
      id: "a-image",
      role: "assistant",
      content: "done",
      createdAt: Date.now(),
      media: [
        {
          kind: "image",
          url: "/api/media/sig/image",
          name: "generated.png",
        },
      ],
    };

    const { container } = render(<MessageBubble message={message} />);

    const image = container.querySelector("img")!;
    Object.defineProperties(image, { naturalWidth: { value: 1600 }, naturalHeight: { value: 900 } });
    fireEvent.load(image);
    const imageButton = screen.getByRole("button", { name: /view image/i });
    expect(imageButton).toHaveClass("rounded-control", "focus-visible:ring-2");
    expect(imageButton.style.width).toBe("448px");
    expect(imageButton.style.height).toBe("252px");
    expect(imageButton).not.toHaveAttribute("title");
    expect(image).toHaveClass("object-contain");
  });

  it("renders mislabeled html assistant media as a file attachment", () => {
    const message: UIMessage = {
      id: "a-html",
      role: "assistant",
      content: "file ready",
      createdAt: Date.now(),
      media: [
        {
          kind: "image",
          url: "/api/media/sig/html",
          name: "index.html",
        },
      ],
    };

    const { container } = render(<MessageBubble message={message} />);

    expect(screen.getByRole("link", { name: "Download index.html" })).toHaveAttribute("download", "index.html");
    expect(screen.getByRole("button", { name: "index.html" })).toBeVisible();
    expect(container.querySelector("img")).not.toBeInTheDocument();
  });

  it("renders assistant svg media as an image preview", () => {
    const message: UIMessage = {
      id: "a-svg",
      role: "assistant",
      content: "chart ready",
      createdAt: Date.now(),
      media: [
        {
          kind: "file",
          url: "/api/media/sig/svg",
          name: "growth.svg",
        },
      ],
    };

    const { container } = render(<MessageBubble message={message} />);

    expect(screen.getByRole("button", { name: /view image: growth.svg/i })).toBeInTheDocument();
    expect(container.querySelector('img[src="/api/media/sig/svg"]')).toBeInTheDocument();
    expect(screen.queryByRole("link", { name: "Download growth.svg" })).not.toBeInTheDocument();
  });

});