Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
55baad4
test(web): copying items within one list keeps their list markers
StiensWout Nov 19, 2026
f1aa405
fix(web): copying items within one list keeps their list markers
StiensWout Nov 19, 2026
974c3af
fix(web): type the list cloned for a copy as an element
StiensWout Nov 19, 2026
14ff671
fix(web): skip unselected list items at copy boundaries
StiensWout Nov 19, 2026
bf1bb5b
test(web): check the composer’s rendered list markers after paste
StiensWout Nov 19, 2026
0947937
test(web): verify list starts alongside rendered paste markers
StiensWout Nov 19, 2026
6831e01
fix(web): preserve list markers at selection edges
StiensWout Nov 19, 2026
ef1829c
test(web): assert composer list markers directly
StiensWout Nov 19, 2026
36dac74
test(web): restore the copied-list scenario's original assertion
StiensWout Nov 19, 2026
126889b
test(web): drop the partial-item copy case that passes without the fix
StiensWout Nov 19, 2026
506b8f8
fix(web): preserve verbatim list-item text and trim empty copy bounda…
StiensWout Nov 19, 2026
3122c5d
test(web): verify displayed markers after pasting copied list items
StiensWout Nov 19, 2026
afc832a
fix(web): preserve the first copied task marker
StiensWout Nov 19, 2026
7a35daa
fix(web): preserve numbering in nested task selections
StiensWout Nov 19, 2026
dc4627c
test(web): cover copied task markers alongside list markers
StiensWout Nov 19, 2026
ad193df
Merge origin/main into t3/1196-copying-part-of-a-numbered-list-drops-it
juliusmarminge Nov 19, 2026
619d1b0
test(web): keep only the copy cases that fail without the fix
juliusmarminge Nov 19, 2026
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
180 changes: 165 additions & 15 deletions apps/web/src/components/ChatMarkdown.browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,10 @@ vi.mock(import("../hooks/useSettings"), async (original) => {
});

import ChatMarkdown from "./ChatMarkdown";
import { chatMarkdownClipboardPayload } from "../markdown-clipboard";
import {
chatMarkdownClipboardPayload,
serializeRenderedMarkdownFragment,
} from "../markdown-clipboard";
import { AudioPreview } from "./files/AudioPreview";

it("keeps compact audio playback loaded across signed URL renewals", async () => {
Expand Down Expand Up @@ -857,35 +860,182 @@ describe("ChatMarkdown copy", () => {
from: "Deeper",
text: "2. 2. Deeper\n\nAfter.",
},
{
source: "1. Install\n2. Configure\n3. Deploy",
from: "Configure",
to: "Deploy",
text: "2. Configure\n3. Deploy",
},
{
source: "1. A\n2. B\n7. C\n8. D",
from: "B",
to: "C",
userMessage: true,
text: "2. B\n7. C",
},
{
source: "- Install\n- Configure\n- Deploy",
from: "Configure",
to: "Deploy",
text: "- Configure\n- Deploy",
},
])(
"keeps the shown numbers when a copy starts at $from and ends past the list",
async ({ source, from, userMessage, text }) => {
"copies $text with the markers its list shows",
async ({ source, from, to, userMessage, text }) => {
setup();
await using screen = await renderText(
source,
userMessage ? { extraRemarkPlugins: SOURCE_NUMBER_PLUGINS } : {},
);
const start = [...screen.container.querySelectorAll("li")]
.flatMap((item) => [...item.childNodes])
.find((node) => node.nodeType === Node.TEXT_NODE && node.textContent === from)!;
const after = [...screen.container.querySelectorAll("p")].at(-1)!.firstChild!;
const itemText = (shown: string) =>
[...screen.container.querySelectorAll("li")]
.flatMap((item) => [...item.childNodes])
.find((node) => node.nodeType === Node.TEXT_NODE && node.textContent === shown)!;
const end = to
? itemText(to)
: [...screen.container.querySelectorAll("p")].at(-1)!.firstChild!;
const range = document.createRange();
range.setStart(itemText(from), 0);
range.setEnd(end, end.textContent!.length);
const selection = window.getSelection()!;
selection.removeAllRanges();
selection.addRange(range);
const payload = chatMarkdownClipboardPayload(selection);
expect(payload?.text).toBe(text);
// Rich paste reads back as the same list.
expect(
serializeRenderedMarkdownFragment(
new DOMParser().parseFromString(payload!.html, "text/html").body,
),
).toBe(text);
},
);

it.each([
{
source: "1. [ ] Install\n2. [x] Configure\n3. [ ] Test\n4. [x] Deploy",
from: "Configure",
to: "Deploy",
text: "2. [x] Configure\n3. [ ] Test\n4. [x] Deploy",
htmlText: "2. Configure\n3. Test\n4. Deploy",
},
{
source:
"1. First\n2. [x] Outer\n 1. [ ] Setup\n 2. [ ] Configure\n 3. [x] Deploy\n\nAfter.",
from: "Configure",
text: "2. [x] 2. [ ] Configure\n 3. [x] Deploy\n\nAfter.",
htmlText: "2. 2. Configure\n 3. Deploy\n\nAfter.",
},
])(
"copies task items with the markers its list shows: $text",
async ({ source, from, to, text, htmlText }) => {
setup();
await using screen = await renderText(source);
const itemText = (label: string) =>
[...screen.container.querySelectorAll("li")]
.flatMap((item) => [...item.childNodes])
.find((node) => node.nodeType === Node.TEXT_NODE && node.textContent?.trim() === label)!;
const start = itemText(from);
const end = to ? itemText(to) : screen.container.querySelector("p")!.firstChild!;
const range = document.createRange();
range.setStart(start, 0);
range.setEnd(after, after.textContent!.length);
range.setStart(start, start.textContent!.indexOf(from));
range.setEnd(end, end.textContent!.length);
const selection = window.getSelection()!;
selection.removeAllRanges();
selection.addRange(range);
const payload = chatMarkdownClipboardPayload(selection);
expect(payload?.text).toBe(text);
// Rich paste numbers its list from the same start.
// HTML sanitization strips form controls.
expect(
new DOMParser()
.parseFromString(payload!.html, "text/html")
.querySelector("li")
?.closest("ol")?.start,
).toBe(Number(text.split(".")[0]));
serializeRenderedMarkdownFragment(
new DOMParser().parseFromString(payload!.html, "text/html").body,
),
).toBe(htmlText);
},
);

it.each([
{
source: "1. First\n2. Second\n\nAfter.",
from: "First",
skipFrom: true,
text: "2. Second\n\nAfter.",
items: 1,
},
{
source: "Before.\n\n1. First\n2. Second",
from: "Before.",
to: "Second",
skipTo: true,
text: "Before.\n\n1. First",
items: 1,
},
{
source: "1. Outer\n 1. Inner\n 2. Deeper\n2. Next",
from: "Inner",
to: "Next",
skipFrom: true,
text: "1. 2. Deeper\n2. Next",
items: 3,
},
{
source: "1. Outer\n 1. Inner\n2. Next",
from: "Inner",
to: "Next",
skipFrom: true,
text: "2. Next",
items: 1,
},
])(
"omits edge items outside the selection when copying with the markers its list shows: $text",
async ({ source, from, to, skipFrom, skipTo, text, items }) => {
setup();
await using screen = await renderText(source);
const textNode = (shown: string) => {
const walker = document.createTreeWalker(screen.container, NodeFilter.SHOW_TEXT);
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
if (node.textContent === shown) return node;
}
throw new Error(`Could not find text: ${shown}`);
};
const end = to ? textNode(to) : textNode("After.");
const range = document.createRange();
range.setStart(textNode(from), skipFrom ? from.length : 0);
range.setEnd(end, skipTo ? 0 : end.textContent!.length);
const selection = window.getSelection()!;
selection.removeAllRanges();
selection.addRange(range);

const payload = chatMarkdownClipboardPayload(selection);
expect(payload?.text).toBe(text);
const pasted = new DOMParser().parseFromString(payload!.html, "text/html");
expect(serializeRenderedMarkdownFragment(pasted.body)).toBe(text);
expect(pasted.querySelectorAll("li")).toHaveLength(items);
},
);

it("omits an end item whose selected edge sits inside its link", async () => {
setup();
await using screen = await renderText(
"1. Install\n2. Configure\n3. Deploy\n4. [Verify](https://example.com/verify)",
);
const items = [...screen.container.querySelectorAll("li")];
const start = items.find((item) => item.textContent === "Configure")!.firstChild!;
const end = items.at(-1)!.querySelector("a > span")!.lastChild!;
const range = document.createRange();
range.setStart(start, 0);
range.setEnd(end, 0);
const selection = window.getSelection()!;
selection.removeAllRanges();
selection.addRange(range);

const payload = chatMarkdownClipboardPayload(selection);
expect(payload?.text).toBe("2. Configure\n3. Deploy");
const pasted = new DOMParser().parseFromString(payload!.html, "text/html");
expect(
[...pasted.querySelectorAll('ol[start="2"] > li')].map((item) => item.textContent),
).toEqual(["Configure", "Deploy"]);
});
});

describe("ChatMarkdown file chip tooltips", () => {
Expand Down
95 changes: 80 additions & 15 deletions apps/web/src/markdown-clipboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const SANITIZED_HTML_SELECTOR = [

const ALERT_ATTRIBUTE = "data-markdown-alert";
const ALERT_LABEL = "data-markdown-alert-label";
const LIST_ITEM_CHECKBOX = ':scope > input[type="checkbox"], :scope > p > input[type="checkbox"]';

export interface MarkdownClipboardPayload {
text: string;
Expand Down Expand Up @@ -131,10 +132,8 @@ function serializeListItem(
index: number,
inTableCell: boolean,
): string {
const checkbox = item.querySelector(
':scope > input[type="checkbox"], :scope > p > input[type="checkbox"]',
);
const task = checkbox ? `[${(checkbox as HTMLInputElement).checked ? "x" : " "}] ` : "";
const checkbox = item.querySelector<HTMLInputElement>(LIST_ITEM_CHECKBOX);
const task = checkbox ? `[${checkbox.checked ? "x" : " "}] ` : "";
const bullet = ordered ? `${index}. ` : "- ";
const marker = `${bullet}${task}`;
let content = outsideCode(serializeChildren(item, inTableCell), (prose) =>
Expand Down Expand Up @@ -505,22 +504,89 @@ function sanitizedHtmlFrom(container: Element): string {
return `<meta charset="utf-8">${container.innerHTML}`;
}

/** A list cloned from a later item would renumber from its start; restart it at the shown number. */
function keepStartListNumbers(range: Range, container: Element): void {
// The start's ancestors below the common ancestor clone as the fragment's first-child chain.
function isList(node: Node): node is HTMLOListElement | HTMLUListElement {
return node instanceof Element && (node.tagName === "OL" || node.tagName === "UL");
}

// An endpoint can clone empty item wrappers at any nesting depth.
function emptyListBoundary(
ancestor: Node,
node: Node,
offset: number,
side: "start" | "end",
): Element | null {
const next = (node: Node) => (side === "start" ? node.nextSibling : node.previousSibling);
if (node instanceof Text && offset !== (side === "start" ? node.length : 0)) return null;

let boundary: Element | null = null;
let remaining = node.childNodes[side === "start" ? offset : offset - 1] ?? null;
while (node !== ancestor && node.parentNode) {
for (let sibling = remaining; sibling; sibling = next(sibling)) {
if (sibling instanceof Text && !sibling.data.trim()) continue;
if (
sibling instanceof Element &&
isSkippedElement(sibling) &&
!sibling.hasAttribute("data-markdown-copy") &&
!sibling.hasAttribute("data-markdown-details")
) {
continue;
}
return boundary;
}
if (node instanceof Element && node.tagName === "LI" && isList(node.parentNode)) {
boundary = node;
} else if (boundary && isList(node)) {
boundary = node;
}
remaining = next(node);
node = node.parentNode;
}
return boundary;
}

/** Clones the selection and restores the markers shown for its copied list items. */
function cloneWithListMarkers(range: Range, container: Element): void {
const originalAncestor = range.commonAncestorContainer;
const start = emptyListBoundary(
originalAncestor,
range.startContainer,
range.startOffset,
"start",
);
const end = emptyListBoundary(originalAncestor, range.endContainer, range.endOffset, "end");
if (start || end) {
range = range.cloneRange();
if (start) range.setStartAfter(start);
if (end) range.setEndBefore(end);
}
const ancestor = range.commonAncestorContainer;
const withinList = isList(ancestor);
container.appendChild(range.cloneContents());
if (withinList) {
// Items copied within one list clone without the list around them.
const list = ancestor.cloneNode(false) as Element;
list.append(...container.childNodes);
container.replaceChildren(list);
}
// The start's ancestors below the cloned top clone as the fragment's first-child chain.
const top = withinList ? ancestor.parentNode : ancestor;
const chain: Node[] = [];
for (
let node: Node | null = range.startContainer;
node && node !== range.commonAncestorContainer;
node = node.parentNode
) {
for (let node: Node | null = range.startContainer; node && node !== top; node = node.parentNode) {
chain.unshift(node);
}
let clone: Node | null = container;
for (const [depth, source] of chain.entries()) {
clone = clone?.firstChild ?? null;
if (!(clone instanceof Element) || !(source instanceof Element) || source.tagName !== "OL")
if (!(clone instanceof Element) || !(source instanceof Element)) continue;
if (source.tagName === "LI" && clone.tagName === "LI") {
const checkbox = source.querySelector(LIST_ITEM_CHECKBOX);
if (checkbox && !clone.querySelector(LIST_ITEM_CHECKBOX)) {
// Keep the first-child chain intact for nested items.
clone.append(checkbox.cloneNode(false));
}
continue;
}
if (source.tagName !== "OL") continue;
const firstCopied = chain[depth + 1] ?? source.childNodes[range.startOffset];
if (!firstCopied) continue;
const shown = numberedListItems(source).find(
Expand All @@ -544,8 +610,7 @@ export function chatMarkdownClipboardPayload(
const range = selection.getRangeAt(index);
if (range.collapsed) continue;
const container = document.createElement("div");
container.appendChild(range.cloneContents());
keepStartListNumbers(range, container);
cloneWithListMarkers(range, container);
// The indentation typed at a line start only shows; pasted, it would turn lines into code.
for (const indentation of container.querySelectorAll("[data-leading-whitespace]")) {
indentation.remove();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/// <reference lib="dom" />
import { expect } from "e2e";

import { test, WEB } from "./t3.ts";

test(
"Copying two items within a numbered list keeps their numbers",
WEB,
async ({ t3, app, browser, screen }) => {
const project = await t3.project("demo");
const thread = await t3.thread({
project,
title: "Steps",
messages: ["Steps:\n\n1. Install\n2. Configure\n3. Deploy\n\nThen report back."],
});
await t3.open(thread);
await screen.getByRole("button", /^Agent Steps/).tap();
await screen.getByText("Configure", { exact: true }).waitFor();

await browser.evaluate(() => {
const items = [...document.querySelectorAll("[data-user-message-body] ol > li")];
const start = items.find((item) => item.textContent === "Configure")?.firstChild;
const end = items.find((item) => item.textContent === "Deploy")?.firstChild;
if (!start || !end) throw new Error("Could not find the two list items");
const range = document.createRange();
range.setStart(start, 0);
range.setEnd(end, end.textContent?.length ?? 0);
const selection = window.getSelection();
selection?.removeAllRanges();
selection?.addRange(range);
return null;
});
await browser.keyboard.press("ControlOrMeta+C");
await screen.getByRole("textbox").tap();
await browser.keyboard.press("ControlOrMeta+V");

const numberedItems = await browser.evaluate(() => {
const list = document.querySelector<HTMLOListElement>('[role="textbox"] ol');
if (!list) return null;
return [...list.querySelectorAll(":scope > li")].map(
(item, index) => `${list.start + index}. ${item.textContent?.trim()}`,
);
});
await app.screenshot("pasted-list-items");
expect(numberedItems, "The pasted items keep their displayed list numbers").toEqual([
"2. Configure",
"3. Deploy",
]);

const renderedItems = await browser.evaluate(() =>
[...document.querySelectorAll('[role="textbox"] ol > li')].map(
(item) => `${item.getAttribute("data-marker")} ${item.textContent?.trim()}`,
),
);
expect(renderedItems, "The composer renders both pasted markers").toEqual([
"2. Configure",
"3. Deploy",
]);
},
);
Loading