From fe1b5e47d4f6ed1a87e3df5ff667d2bff4b23f97 Mon Sep 17 00:00:00 2001 From: Thibault Saunier Date: Tue, 17 Nov 2026 21:34:13 -0300 Subject: [PATCH] Render the user's own Markdown messages in the chat A message the user wrote in Markdown (a code fence, inline code, a list, a link, emphasis) now renders in the chat as the agent's replies do, sanitised the same way, instead of showing its raw syntax. Plain text, and text that only holds Markdown's characters (an `_` or a `*` in a path, a word or a sum), still shows as typed. --- FEATURES.md | 13 ++- web/src/components/AgentHistoryChat.test.ts | 6 +- web/src/components/AgentHistoryChat.tsx | 26 ++++- .../components/UserMessageText.dom.test.ts | 96 +++++++++++++++++++ web/src/userMarkdown.test.ts | 34 +++++++ web/src/userMarkdown.ts | 23 +++++ 6 files changed, 186 insertions(+), 12 deletions(-) create mode 100644 web/src/components/UserMessageText.dom.test.ts create mode 100644 web/src/userMarkdown.test.ts create mode 100644 web/src/userMarkdown.ts diff --git a/FEATURES.md b/FEATURES.md index 300d50f1f..7aa2f07a6 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -160,11 +160,14 @@ Inspector state is scoped to each checkout; see pane's host through the file download, instead of its path; a click shows it over the app fitted to the window (a click on it gives its own size; Esc, the backdrop or the close button put it away), and Cmd, Ctrl or a - middle click opens it in a tab. In a Claude session, typing `/` lists the - commands that match what follows (Claude Code's own, then the session's - skills and custom commands, read from its transcript); a click, or the - arrows and Tab or Enter, fill in `/name`, Enter on a whole name sends it, - and Esc closes the list. **Vim keys in agent chats** in Configuration > + middle click opens it in a tab. Your own messages written in Markdown (a + code fence, inline code, a list, a link, emphasis) render as the agent's + replies do; plain text, and text that only holds Markdown's characters (an + `_` or a `*` in a path), shows as typed. In a Claude session, typing `/` + lists the commands that match what follows (Claude Code's own, then the + session's skills and custom commands, read from its transcript); a click, + or the arrows and Tab or Enter, fill in `/name`, Enter on a whole name + sends it, and Esc closes the list. **Vim keys in agent chats** in Configuration > Behavior (off by default) makes chat message boxes Vim editors: insert mode first, `:w` sends, PageUp/PageDown scroll the conversation, and on touch screens an **Esc** button stands in for the missing key. Enter sends and Shift+Enter adds a line; on diff --git a/web/src/components/AgentHistoryChat.test.ts b/web/src/components/AgentHistoryChat.test.ts index eb456489b..2c5b89191 100644 --- a/web/src/components/AgentHistoryChat.test.ts +++ b/web/src/components/AgentHistoryChat.test.ts @@ -63,11 +63,11 @@ async function withMarkdownDom(render: () => T): Promise { } } -test("chat renders user text plainly, assistant markdown, and collapsed tool blocks", async () => { +test("chat renders plain user text as typed, assistant markdown, and collapsed tool blocks", async () => { const markup = await withMarkdownDom(() => renderChat( [ - entry("1", "user", { text: "**not bold**" }), + entry("1", "user", { text: "src/**/*.ts and 2 * 3" }), entry("2", "tool", { tool_name: "bash", text: "", text_bytes: 12 }), entry("3", "tool", { kind: "tool_result", @@ -80,7 +80,7 @@ test("chat renders user text plainly, assistant markdown, and collapsed tool blo 2, ), ); - expect(markup).toContain("

**not bold**

"); + expect(markup).toContain("

src/**/*.ts and 2 * 3

"); expect(markup).toContain("bold"); // Tool blocks start collapsed: a summary row only, no entry list. expect(markup).toContain('aria-expanded="false"'); diff --git a/web/src/components/AgentHistoryChat.tsx b/web/src/components/AgentHistoryChat.tsx index d5f3614e4..74d8c8d7a 100644 --- a/web/src/components/AgentHistoryChat.tsx +++ b/web/src/components/AgentHistoryChat.tsx @@ -43,6 +43,7 @@ import { } from "./agentHistoryView"; import { formatBytes } from "./agentSession"; import { MarkdownPreview } from "./markdown"; +import { looksLikeMarkdown } from "../userMarkdown"; import { attachedImagePieces, type MessagePiece, @@ -140,7 +141,7 @@ const ChatBubble = memo(function ChatBubble({ imageUrl || images?.length ? ( ) : ( -

{preview}

+ ) ) : ( "image" in piece)) return

{text}

; + if (!pieces.some((piece) => "image" in piece)) + return ; const nameOf = (path: string) => path.split(/[\\/]/).pop() ?? path; const urlOf = (piece: MessageImage) => piece.url ?? imageUrl!(piece.image); return ( @@ -272,7 +274,7 @@ function UserText({ {nameOf(piece.image)} ) : ( -

{piece.text}

+ ), )} {shown ? ( @@ -286,6 +288,22 @@ function UserText({ ); } +/** + * What the user typed: as typed, unless written in Markdown (a code fence, + * inline code, a list, a link), which renders as the agent's replies do, + * sanitised the same way. + */ +export function UserMessageText({ text }: { text: string }) { + if (!looksLikeMarkdown(text)) return

{text}

; + return ( + + ); +} + // A message sent from the chat that the transcript does not show yet: on its // way (dashed and dimmed, like a queued one) until its entry replaces it, or // not delivered, with the ways out. @@ -305,7 +323,7 @@ function OutboxBubble({ data-outbox-id={message.id} >
-

{message.text.slice(0, HISTORY_PREVIEW_CHARS)}

+
{failed ? ( diff --git a/web/src/components/UserMessageText.dom.test.ts b/web/src/components/UserMessageText.dom.test.ts new file mode 100644 index 000000000..be76e0559 --- /dev/null +++ b/web/src/components/UserMessageText.dom.test.ts @@ -0,0 +1,96 @@ +import { afterAll, afterEach, expect, test } from "bun:test"; +import { Window } from "happy-dom"; +import type { Root } from "react-dom/client"; + +if (process.env.ROAMGATE_USER_TEXT_DOM_TEST !== "1") { + test("user message text in an isolated DOM runtime", async () => { + const child = Bun.spawn([process.execPath, "test", import.meta.path], { + env: { ...process.env, ROAMGATE_USER_TEXT_DOM_TEST: "1" }, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, code] = await Promise.all([ + new Response(child.stdout).text(), + new Response(child.stderr).text(), + child.exited, + ]); + if (code !== 0) throw new Error(`${stdout}\n${stderr}`); + expect(code).toBe(0); + }, 15_000); +} else { + await registerTests(); +} + +async function registerTests() { + const browser = new Window({ url: "http://localhost" }); + for (const key of [ + "window", + "document", + "navigator", + "HTMLElement", + "Element", + "Node", + "Event", + "MouseEvent", + "DOMParser", + "NodeFilter", + ] as const) { + Object.defineProperty(globalThis, key, { + value: key === "window" ? browser : browser[key], + writable: true, + configurable: true, + }); + } + Object.assign(globalThis, { + getComputedStyle: browser.getComputedStyle.bind(browser), + requestAnimationFrame: browser.requestAnimationFrame.bind(browser), + cancelAnimationFrame: browser.cancelAnimationFrame.bind(browser), + IS_REACT_ACT_ENVIRONMENT: true, + }); + const { act, createElement: h } = await import("react"); + const { createRoot } = await import("react-dom/client"); + const { UserMessageText } = await import("./AgentHistoryChat"); + + let root: Root | null = null; + afterEach(async () => { + if (root) await act(async () => root?.unmount()); + root = null; + document.body.replaceChildren(); + }); + afterAll(async () => browser.happyDOM.close()); + + async function render(text: string) { + const container = document.createElement("div"); + document.body.append(container); + root = createRoot(container); + await act(async () => root!.render(h(UserMessageText, { text }))); + return container; + } + + test("a code fence renders as code", async () => { + const shown = await render( + "Why does this fail?\n```ts\nconst a: number = `x`;\n```\nand `b` too", + ); + const code = shown.querySelector("pre code"); + expect(code?.textContent).toContain("const a: number = `x`;"); + expect(shown.textContent).not.toContain("```"); + expect( + [...shown.querySelectorAll("code")].some((c) => c.textContent === "b"), + ).toBe(true); + expect(shown.querySelector(".agent-history-chat-markdown")).not.toBeNull(); + }); + + test("plain text stays as typed: one paragraph, newlines and all", async () => { + const text = "fix server/src/my_module.ts\nthen run 2 * 3 * 4"; + const shown = await render(text); + expect(shown.innerHTML).toBe(`

${text}

`); + }); + + test("no raw HTML gets through", async () => { + const shown = await render( + "- one\n- ", + ); + expect(shown.querySelector("li")).not.toBeNull(); + expect(shown.querySelector("img[onerror], script")).toBeNull(); + }); +} diff --git a/web/src/userMarkdown.test.ts b/web/src/userMarkdown.test.ts new file mode 100644 index 000000000..87bd99253 --- /dev/null +++ b/web/src/userMarkdown.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, test } from "bun:test"; +import { looksLikeMarkdown } from "./userMarkdown"; + +describe("looksLikeMarkdown", () => { + test("Markdown the user wrote", () => { + for (const text of [ + "look:\n```\nconst a = 1;\n```", + "~~~ts\nx\n~~~", + "run `bun test` again", + "see [the docs](https://example.com)", + "todo:\n- one\n- two", + "steps:\n1. build\n2. test", + "this is **important**", + "this is *really* it", + "an _emphasised_ word", + ]) + expect(looksLikeMarkdown(text)).toBe(true); + }); + + test("plain text, and text that only has Markdown's characters", () => { + for (const text of [ + "hello\nworld", + "fix server/src/my_module_name.ts please", + "the file a_b_c and d_e", + "compute 2 * 3 * 4", + "glob src/**/*.ts", + "snake_case_name", + "rm -rf build", + "2026. A year", + "", + ]) + expect(looksLikeMarkdown(text)).toBe(false); + }); +}); diff --git a/web/src/userMarkdown.ts b/web/src/userMarkdown.ts new file mode 100644 index 000000000..4a422b912 --- /dev/null +++ b/web/src/userMarkdown.ts @@ -0,0 +1,23 @@ +/** + * Whether a message the user typed is written in Markdown: a code fence, + * inline code, a link, a list, or emphasis set off by spaces. Plain text, + * and text that only happens to hold Markdown's characters (an `_` or a + * `*` in a path, a word or a sum), shows as typed. + */ +const SIGNS = [ + // A code fence. + /^ {0,3}(?:```|~~~)/m, + // Inline code. + /`[^`\n]+`/, + // A link. + /\[[^\]\n]+\]\([^)\s]+\)/, + // A list item. + /^ {0,3}(?:[-*+]|\d{1,3}[.)]) +\S/m, + // Strong emphasis, or emphasis between spaces (not inside a word or path). + /(?:^|[\s([{])(\*\*|__)(?=\S)[^\n]*?\S\1(?=$|[\s)\]}.,;:!?])/m, + /(?:^|[\s([{])([*_])(?=[^\s*_])[^\n*_]*[^\s*_]\1(?=$|[\s)\]}.,;:!?])/m, +]; + +export function looksLikeMarkdown(text: string): boolean { + return SIGNS.some((sign) => sign.test(text)); +}