The best way to control Claude Code, Codex and more from any computer or phone
fix(web): copied literal Markdown sends as shown (#36867)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Wout Stiens committed
Nov 14, 2026 at 19:56 UTC
3c77d3d64b88c283477b7fc2f186ab8ac3624f58
5 files changed
+153
-19
apps/web/src/components/ChatMarkdown.browser.test.tsx
+14
-1
@@ -677,7 +677,7 @@ describe("ChatMarkdown inline code selection", () => {
677
});
678
});
679
680
-describe("ChatMarkdown alert copy", () => {
680
+describe("ChatMarkdown copy", () => {
681
it("copies a fully selected callout as alert Markdown and a partial one as text", async () => {
682
setup();
683
await using screen = await renderText("> [!WARNING]\n> Back up first.");
@@ -699,6 +699,19 @@ describe("ChatMarkdown alert copy", () => {
699
);
700
expect(select(labelText, bodyText, "Back up".length)).toBe("Warning\n\nBack up");
701
});
702
+
703
+ it("copies part of inline code without prose escapes", async () => {
704
+ setup();
705
+ await using screen = await renderText("Read `items[0]*_x` and a*b*c.");
706
+ const code = screen.container.querySelector("p code")!.firstChild!;
707
+ const range = document.createRange();
708
+ range.setStart(code, 0);
709
+ range.setEnd(code, "items[0]*_".length);
710
+ const selection = window.getSelection()!;
711
+ selection.removeAllRanges();
712
+ selection.addRange(range);
713
+ expect(chatMarkdownClipboardPayload(selection)?.text).toBe("items[0]*_");
714
+ });
715
});
716
717
describe("ChatMarkdown file chip tooltips", () => {
apps/web/src/markdown-clipboard.test.ts
+61
-11
@@ -12,6 +12,18 @@ import {
12
} from "@t3tools/shared/assistantCitations";
13
import { markdownMathRanges, parseMarkdownWithMath } from "@t3tools/shared/markdownMath";
14
15
+import { unified } from "unified";
16
+import remarkParse from "remark-parse";
17
+import {
18
+ CHAT_MARKDOWN_REMARK_PLUGINS,
19
+ CHAT_USER_MARKDOWN_REMARK_PLUGINS,
20
+} from "@t3tools/shared/markdownPipeline";
21
+
22
+const userMarkdown = unified()
23
+ .use(remarkParse)
24
+ .use(CHAT_MARKDOWN_REMARK_PLUGINS)
25
+ .use(CHAT_USER_MARKDOWN_REMARK_PLUGINS);
26
+
27
const TEXT_NODE = 3;
28
const ELEMENT_NODE = 1;
29
@@ -216,6 +228,39 @@ describe("serializeRenderedMarkdownFragment", () => {
228
expect(paragraph.children.find((child) => child.type === "inlineCode")?.value).toBe(value);
229
});
230
231
+ it.each([
232
+ String.raw`see C:\me\.t3\shot.png`,
233
+ String.raw`C:\work\_build`,
234
+ "C:/work/_build/out.txt",
235
+ String.raw`C:\work\a-_b.txt`,
236
+ "a*word*b and a_word_b; ~~literal~~ and ~single~",
237
+ String.raw`before\ after\ end`,
238
+ ])("copies prose that parses back unchanged: %s", (value) => {
239
+ const container = new FakeElement("DIV").append(new FakeText(value));
240
+ const paragraph = userMarkdown.parse(serializeRenderedMarkdownFragment(asNode(container)))
241
+ .children[0];
242
+ expect(paragraph).toMatchObject({ type: "paragraph", children: [{ type: "text", value }] });
243
+ });
244
+
245
+ it.each([
246
+ ["*", "EM", "word", "emphasis"],
247
+ ["\\", "CODE", "value", "inlineCode"],
248
+ ])("keeps a text edge %j beside %s", (edge, tag, value, type) => {
249
+ const container = new FakeElement("DIV").append(
250
+ new FakeText(edge),
251
+ new FakeElement(tag).append(new FakeText(value)),
252
+ );
253
+ const paragraph = userMarkdown.parse(serializeRenderedMarkdownFragment(asNode(container)))
254
+ .children[0];
255
+ expect(paragraph).toMatchObject({
256
+ type: "paragraph",
257
+ children: [
258
+ { type: "text", value: edge },
259
+ type === "inlineCode" ? { type, value } : { type, children: [{ type: "text", value }] },
260
+ ],
261
+ });
262
+ });
263
+
264
it("copies email links with their address and drops in-app destinations", () => {
265
const container = new FakeElement("DIV").append(
266
new FakeElement("P").append(
@@ -254,19 +299,24 @@ describe("serializeRenderedMarkdownFragment", () => {
299
});
300
301
it.each([
257
- "support@example.com?subject=Help",
258
- "foo",
259
- "support@example.internal1",
260
- "support@example.com_",
261
- "support@example.com-",
262
- ])("keeps the destination when the email label is not a bare address: %s", (label) => {
263
- const href = `mailto:${label}`;
302
+ ["array[index]", "https://example.com"] as const,
303
+ ...[
304
+ "support@example.com?subject=Help",
305
+ "foo",
306
+ "support@example.internal1",
307
+ "support@example.com_",
308
+ "support@example.com-",
309
+ "first_last@example.com",
310
+ ].map((label) => [label, `mailto:${label}`] as const),
311
+ ])("keeps the link label and destination: %s", (label, href) => {
312
const anchor = new FakeElement("A", [], { href }).append(new FakeText(label));
313
const container = new FakeElement("DIV").append(anchor);
266
- const paragraph = parseMarkdownWithMath(serializeRenderedMarkdownFragment(asNode(container)))
314
+ const paragraph = userMarkdown.parse(serializeRenderedMarkdownFragment(asNode(container)))
315
.children[0];
316
if (paragraph?.type !== "paragraph") throw new Error("Expected a paragraph");
269
- expect(paragraph.children.find((child) => child.type === "link")?.url).toBe(href);
317
+ expect(paragraph.children).toMatchObject([
318
+ { type: "link", url: href, children: [{ type: "text", value: label }] },
319
+ ]);
320
});
321
322
it("copies alert and insight callouts as their Markdown instead of the rendered label", () => {
@@ -415,7 +465,7 @@ describe("copying rendered Markdown tables", () => {
465
it("keeps formula pipes as authored while escaping prose pipes", () => {
466
const table = renderedTable(
467
[new FakeText("Formula"), new FakeText("Note")],
418
- [renderedFormula("|x|"), new FakeText("a | b")],
468
+ [renderedFormula("|x|"), new FakeText("*a* | ~~b~~")],
469
[renderedFormula("\\|x\\|"), new FakeElement("CODE").append(new FakeText("\\(c|d\\)"))],
470
[
471
new FakeElement("A", [], { href: "https://example.com/?q=a|b" }).append(
@@ -444,7 +494,7 @@ describe("copying rendered Markdown tables", () => {
494
"|z|",
495
]);
496
expect(parsed.children[1]?.children[1]?.children).toMatchObject([
447
- { type: "text", value: "a | b" },
497
+ { type: "text", value: "*a* | ~~b~~" },
498
]);
499
expect(parsed.children[4]?.children[1]?.children).toMatchObject([
500
{ type: "text", value: "> c | d" },
apps/web/src/markdown-clipboard.ts
+36
-6
@@ -1,3 +1,5 @@
1
+import { UNFINISHED_DRIVE_PATH } from "@t3tools/shared/markdownWindowsPaths";
2
+
3
const SKIPPED_TAGS = new Set(["BUTTON", "INPUT", "SCRIPT", "STYLE", "TEMPLATE"]);
4
const SKIPPED_CLASS_NAMES = ["select-none", "sr-only"];
5
const SANITIZED_HTML_SELECTOR = [
@@ -202,6 +204,32 @@ function serializeDetails(details: Element): string {
204
return `<details${open}>\n<summary>${summary}</summary>${content ? `\n\n${content}` : ""}\n</details>\n\n`;
205
}
206
207
+// Prose that would read as inline Markdown once pasted back: a backslash before punctuation,
208
+// backticks, brackets, and emphasis or strikethrough runs (user remark-gfm sets singleTilde: false).
209
+const INLINE_MARKDOWN = /\\(?=[!-/:-@[-`{-~\n]|$)|[`[\]]|\*+|_+|~{2,}/g;
210
+const ESCAPED_PUNCTUATION = /\\([!-/:-@[-`{-~])/g;
211
+
212
+/** Escapes rendered prose so it parses back to the same text, leaving runs that cannot open or close. */
213
+function escapeProse(text: string): string {
214
+ return text.replace(/\S+/g, (word, wordOffset: number) => {
215
+ // Check each word once; testing every escape's growing prefix would be quadratic.
216
+ const drive = UNFINISHED_DRIVE_PATH.exec(word);
217
+ const driveStart = drive ? drive.index + drive[0].search(/[A-Za-z]/) + 2 : Infinity;
218
+ return word.replace(INLINE_MARKDOWN, (match: string, offset: number) => {
219
+ if (offset >= driveStart) return match;
220
+ const before = text[wordOffset + offset - 1];
221
+ const after = text[wordOffset + offset + match.length];
222
+ if (match === "\\" && after !== undefined && /[^\S\n]/.test(after)) return match;
223
+ // A text node's edge may touch another node's markers, so it counts as neither.
224
+ const between = (pattern: RegExp) =>
225
+ before !== undefined && after !== undefined && pattern.test(before) && pattern.test(after);
226
+ if (/[*_~]/.test(match[0]!) && between(/\s/)) return match;
227
+ if (match[0] === "_" && between(/[\p{L}\p{N}]/u)) return match;
228
+ return match.replace(/[\s\S]/g, "\\$&");
229
+ });
230
+ });
231
+}
232
+
233
function serializeAnchor(anchor: Element, inTableCell: boolean): string {
234
const markdownCopy = anchor.getAttribute("data-markdown-copy");
235
if (markdownCopy !== null) return escapeTablePipes(markdownCopy, inTableCell);
@@ -210,11 +238,12 @@ function serializeAnchor(anchor: Element, inTableCell: boolean): string {
238
if (!/^(?:https?:\/\/|mailto:)/i.test(href)) return content;
239
const label = content.trim();
240
if (!label) return "";
213
- const cellHref = escapeTablePipes(href, inTableCell);
214
- if (cellHref === label) return label;
241
+ // The label arrives escaped; a bare address goes out as shown, since GFM links it again.
242
+ const shown = label.replace(ESCAPED_PUNCTUATION, "$1");
243
+ if (shown === href) return escapeTablePipes(href, inTableCell);
244
// GFM autolinks a bare address only when it fits this shape.
216
- if (cellHref === `mailto:${label}` && /^[\w.+-]+@[\w-]+(?:\.[\w-]+)+(?<=[a-zA-Z])$/.test(label))
217
- return label;
245
+ if (href === `mailto:${shown}` && /^[\w.+-]+@[\w-]+(?:\.[\w-]+)+(?<=[a-zA-Z])$/.test(shown))
246
+ return shown;
247
const destination = escapeTablePipes(href.replace(/[\\()]/g, "\\$&"), inTableCell);
248
return `[${label}](${destination})`;
249
}
@@ -239,7 +268,7 @@ function serializeNode(node: Node, inTableCell = false): string {
268
if (node.nodeType === Node.TEXT_NODE) {
269
const text = node.textContent ?? "";
270
if (text.includes("\n") && text.trim().length === 0) return "\n";
242
- return escapeTablePipes(text, inTableCell);
271
+ return escapeTablePipes(escapeProse(text), inTableCell);
272
}
273
if (node.nodeType !== Node.ELEMENT_NODE) return "";
274
const element = node as Element;
@@ -499,7 +528,8 @@ export function chatMarkdownClipboardPayload(
528
htmls.push(`<meta charset="utf-8">${mathSourceElement(math).outerHTML}`);
529
continue;
530
}
502
- if (ancestorElement?.closest("pre")) {
531
+ // A range inside one code element clones only its text, which would otherwise be escaped as prose.
532
+ if (ancestorElement?.closest("pre, code")) {
533
const text = range.toString();
534
if (text) {
535
texts.push(text);
packages/shared/src/markdownWindowsPaths.ts
+1
-1
@@ -17,7 +17,7 @@ function keepWindowsPathDestination(this: DestinationCompileContext, token: unkn
17
}
18
19
// A drive path that has not reached whitespace yet: `C:`, `C:\Users\me`, `C:/work`.
20
-const UNFINISHED_DRIVE_PATH = /(?:^|\W)[A-Za-z]:(?:[\\/]\S*)?$/;
20
+export const UNFINISHED_DRIVE_PATH = /(?:^|\W)[A-Za-z]:(?:[\\/]\S*)?$/;
21
22
interface EscapeCompileContext {
23
readonly stack: ReadonlyArray<{
scripts/scenarios/copied-literal-markdown-sends-as-shown.e2e.ts
new
+41
@@ -0,0 +1,41 @@
1
+/// <reference lib="dom" />
2
+// The DOM lib types the function this scenario runs in the page.
3
+import { expect } from "e2e";
4
+
5
+import { test, WEB } from "./t3.ts";
6
+
7
+const MESSAGE = "Type \\*word\\* and \\[label](https://example.com) literally.";
8
+const SHOWN = "Type *word* and [label](https://example.com) literally.";
9
+
10
+test(
11
+ "A copied message with literal Markdown characters sends as it was shown",
12
+ WEB,
13
+ async ({ t3, app, browser, screen }) => {
14
+ const project = await t3.project("demo");
15
+ const thread = await t3.thread({ project, title: "Literal", messages: [MESSAGE] });
16
+ await t3.open(thread);
17
+ // A message sent through the CLI shows collapsed under its sender.
18
+ await screen.getByRole("button", /^Agent Type/).tap();
19
+ await expect(screen.getByText(SHOWN)).toBeVisible();
20
+
21
+ // Select the rendered paragraph as a drag across it would.
22
+ await browser.evaluate(() => {
23
+ const paragraph = document.querySelector("[data-user-message-body] p");
24
+ if (!paragraph) throw new Error("No rendered user message");
25
+ const range = document.createRange();
26
+ range.selectNodeContents(paragraph);
27
+ window.getSelection()?.removeAllRanges();
28
+ window.getSelection()?.addRange(range);
29
+ return null;
30
+ });
31
+ await browser.keyboard.press("ControlOrMeta+C");
32
+
33
+ const composer = screen.getByRole("textbox");
34
+ await composer.tap();
35
+ await browser.keyboard.press("ControlOrMeta+V");
36
+ await browser.keyboard.press("Enter");
37
+ await expect(screen.getByText("second fixture turn complete")).toBeVisible();
38
+ await app.screenshot("sent");
39
+ await expect(screen.getByText(SHOWN)).toHaveCount(2);
40
+ },
41
+);