Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions FEATURES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions web/src/components/AgentHistoryChat.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,11 @@ async function withMarkdownDom<T>(render: () => T): Promise<T> {
}
}

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",
Expand All @@ -80,7 +80,7 @@ test("chat renders user text plainly, assistant markdown, and collapsed tool blo
2,
),
);
expect(markup).toContain("<p>**not bold**</p>");
expect(markup).toContain("<p>src/**/*.ts and 2 * 3</p>");
expect(markup).toContain("<strong>bold</strong>");
// Tool blocks start collapsed: a summary row only, no entry list.
expect(markup).toContain('aria-expanded="false"');
Expand Down
26 changes: 22 additions & 4 deletions web/src/components/AgentHistoryChat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import {
} from "./agentHistoryView";
import { formatBytes } from "./agentSession";
import { MarkdownPreview } from "./markdown";
import { looksLikeMarkdown } from "../userMarkdown";
import {
attachedImagePieces,
type MessagePiece,
Expand Down Expand Up @@ -140,7 +141,7 @@ const ChatBubble = memo(function ChatBubble({
imageUrl || images?.length ? (
<UserText text={preview} imageUrl={imageUrl} images={images} />
) : (
<p>{preview}</p>
<UserMessageText text={preview} />
)
) : (
<MarkdownPreview
Expand Down Expand Up @@ -234,7 +235,8 @@ function UserText({
? [{ text: piece.image }]
: [piece],
);
if (!pieces.some((piece) => "image" in piece)) return <p>{text}</p>;
if (!pieces.some((piece) => "image" in piece))
return <UserMessageText text={text} />;
const nameOf = (path: string) => path.split(/[\\/]/).pop() ?? path;
const urlOf = (piece: MessageImage) => piece.url ?? imageUrl!(piece.image);
return (
Expand Down Expand Up @@ -272,7 +274,7 @@ function UserText({
<img src={urlOf(piece)} alt={nameOf(piece.image)} loading="lazy" />
</a>
) : (
<p key={index}>{piece.text}</p>
<UserMessageText key={index} text={piece.text} />
),
)}
{shown ? (
Expand All @@ -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 <p>{text}</p>;
return (
<MarkdownPreview
text={text}
className="agent-history-chat-markdown"
breaks
/>
);
}

// 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.
Expand All @@ -305,7 +323,7 @@ function OutboxBubble({
data-outbox-id={message.id}
>
<div className="agent-history-chat-bubble">
<p>{message.text.slice(0, HISTORY_PREVIEW_CHARS)}</p>
<UserMessageText text={message.text.slice(0, HISTORY_PREVIEW_CHARS)} />
</div>
<div className="agent-history-chat-meta">
{failed ? (
Expand Down
96 changes: 96 additions & 0 deletions web/src/components/UserMessageText.dom.test.ts
Original file line number Diff line number Diff line change
@@ -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(`<p>${text}</p>`);
});

test("no raw HTML gets through", async () => {
const shown = await render(
"- one\n- <img src=x onerror=alert(1)><script>alert(2)</script>",
);
expect(shown.querySelector("li")).not.toBeNull();
expect(shown.querySelector("img[onerror], script")).toBeNull();
});
}
34 changes: 34 additions & 0 deletions web/src/userMarkdown.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
23 changes: 23 additions & 0 deletions web/src/userMarkdown.ts
Original file line number Diff line number Diff line change
@@ -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));
}
Loading