Skip to content
Draft
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
148 changes: 148 additions & 0 deletions crates/agent-gateway/test/webui/paste-newline-pipeline.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
import assert from "node:assert/strict";
import test from "node:test";
import { createWebModuleLoader } from "../helpers/load-web-module.mjs";

const loader = createWebModuleLoader();
const composer = loader.loadModule("src/components/chat/MentionComposer.tsx");
const composerText = loader.loadModule("src/lib/chat/composerText.ts");
const draftText = loader.loadModule("src/app/chatDraft.ts");
const uploadedFiles = loader.loadModule("src/lib/chat/uploadedFiles.ts");

const originalNode = globalThis.Node;
globalThis.Node = { TEXT_NODE: 3, ELEMENT_NODE: 1 };

test.after(() => {
if (originalNode === undefined) delete globalThis.Node;
else globalThis.Node = originalNode;
});

function textNode(text) {
return { nodeType: Node.TEXT_NODE, textContent: text };
}

function elementNode(tagName, childNodes = [], attributes = {}) {
return {
nodeType: Node.ELEMENT_NODE,
tagName,
childNodes,
getAttribute(name) {
return attributes[name] ?? null;
},
hasAttribute(name) {
return Object.hasOwn(attributes, name);
},
};
}

function chromiumPasteDom(clipboardText) {
const normalized = clipboardText.replace(/\r\n?/g, "\n");
const lines = normalized.split("\n");
const children = [];
if (lines[0]) children.push(textNode(lines[0]));
else if (lines.length > 1) children.push(elementNode("DIV", [elementNode("BR")]));
for (const line of lines.slice(1)) {
children.push(elementNode("DIV", line ? [textNode(line)] : [elementNode("BR")]));
}
return elementNode("DIV", children);
}

function draftFromSegments(segments) {
const text = segments.map((segment) => segment.text ?? "").join("");
return {
segments,
text,
textWithoutLargePastes: text,
largePastes: [],
skillMentions: [],
commitMentions: [],
gitFileMentions: [],
codeMentions: [],
isEmpty: text.trim().length === 0,
};
}

const cases = [
["LF no blank line", "alpha\nbeta"],
["LF one blank line", "alpha\n\nbeta"],
["CRLF one blank line", "alpha\r\n\r\nbeta"],
["CR one blank line", "alpha\r\rbeta"],
["multiple blank lines", "alpha\n\n\nbeta"],
["leading newline", "\nalpha"],
["trailing newline", "alpha\n"],
["Markdown paragraphs", "first paragraph\n\nsecond paragraph"],
["Markdown list", "- one\n- two"],
["Markdown quote", "> quote\n> continued"],
["Markdown code block", "```ts\nconst value = 1;\n```"],
["Markdown table", "| a | b |\n| - | - |\n| 1 | 2 |"],
["Unicode and emoji", "你好🙂\n\nκαλημέρα"],
["long text", `${"x".repeat(20_000)}\n\n${"y".repeat(20_000)}`],
];

test("clipboard DOM -> composer draft -> outbound -> history preserves logical newlines", () => {
for (const [name, clipboardText] of cases) {
const expected = clipboardText.replace(/\r\n?/g, "\n");
const segments = composer.serializeChildrenToSegments(chromiumPasteDom(clipboardText), new Map());
const draft = draftFromSegments(segments);
const outbound = draftText.buildTextFromComposerDraft(draft);
const message = uploadedFiles.createUserMessageWithUploads(outbound, [], 1);
const history = JSON.parse(JSON.stringify(message));

assert.equal(draft.text, expected, `${name}: composer draft`);
assert.equal(outbound, expected, `${name}: outbound payload`);
assert.equal(history.content, expected, `${name}: history/replay`);
assert.equal(
uploadedFiles.getUserMessageDisplayText(history),
expected,
`${name}: transcript user bubble text`,
);
}
});

test("pure whitespace remains structurally intact in the draft but is not sendable", () => {
const clipboardText = " \r\n\r\n ";
const expected = " \n\n ";
const segments = composer.serializeChildrenToSegments(chromiumPasteDom(clipboardText), new Map());
const draft = draftFromSegments(segments);
assert.equal(draft.text, expected);
assert.equal(draftText.buildTextFromComposerDraft(draft), expected);
assert.equal(uploadedFiles.createUserMessageWithUploads(expected, [], 1), null);
});

test("message creation normalizes line endings without trimming logical edge newlines", () => {
const input = "\r\nalpha\r\nbeta\r";
const expected = "\nalpha\nbeta\n";
const message = uploadedFiles.createUserMessageWithUploads(input, [], 1);
assert.equal(message.content, expected);
assert.equal(uploadedFiles.getUserMessageDisplayText(message), expected);
});

test("plaintext HTML escaping preserves literal content and logical newlines", () => {
assert.equal(
composerText.plainTextToContentEditableHtml("<tag>& value\r\nnext"),
"&lt;tag&gt;&amp; value\nnext",
);
});

test("composer serialization preserves newlines around mention chips", () => {
const root = elementNode("DIV", [
textNode("first\n"),
elementNode("SPAN", [], {
"data-mention-path": "src/App.tsx",
"data-mention-kind": "file",
}),
textNode("\nsecond"),
]);
const segments = composer.serializeChildrenToSegments(root, new Map());
assert.deepEqual(
segments.map((segment) =>
segment.type === "text"
? { type: "text", text: segment.text }
: { type: segment.type, path: segment.reference?.path },
),
[
{ type: "text", text: "first\n" },
{ type: "fileMention", path: "src/App.tsx" },
{ type: "text", text: "\nsecond" },
],
);
});
9 changes: 5 additions & 4 deletions crates/agent-gateway/web/src/app/GatewayApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import { registerAskUserQuestionAnswerHandler } from "@/lib/chat/askUserQuestion
import type { ChatFileLink } from "@/lib/chat/chatFileLinks";
import type { ChatHistorySummary } from "@/lib/chat/chatHistory";
import { buildModelOptions } from "@/lib/chat/chatPageHelpers";
import { normalizeLogicalLineEndings } from "@/lib/chat/composerText";
import type { HistoryMessageRef } from "@/lib/chat/conversationState";
import {
adoptHistoryWindowState,
Expand Down Expand Up @@ -2392,11 +2393,11 @@ export default function GatewayApp() {
files: PendingUploadedFile[],
workdir: string,
) {
let text = (
let text = normalizeLogicalLineEndings(
isAgentMode && draft.largePastes.length > 0
? draft.textWithoutLargePastes
: buildTextFromComposerDraft(draft)
).trim();
: buildTextFromComposerDraft(draft),
);
let uploadedFiles = files;

if (isAgentMode && draft.largePastes.length > 0) {
Expand All @@ -2414,7 +2415,7 @@ export default function GatewayApp() {
if (apiRef.current?.getActiveAgent().trim() !== agentID) {
throw new Error("Agent 已切换,已取消发送本次大段粘贴内容。");
}
text = buildTextFromComposerDraft(draft, imported.fileByPasteId).trim();
text = buildTextFromComposerDraft(draft, imported.fileByPasteId);
uploadedFiles = mergePendingUploadedFiles(files, imported.files);
} finally {
isImportingPastedTextRef.current = false;
Expand Down
53 changes: 28 additions & 25 deletions crates/agent-gateway/web/src/app/chatDraft.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type {
MentionComposerGitFileMention,
MentionComposerLargePaste,
} from "@/components/chat/MentionComposer";
import { normalizeLogicalLineEndings } from "@/lib/chat/composerText";
import { formatCodeMentionToken, formatFileMentionToken } from "@/lib/chat/mentionReferences";
import type { PendingUploadedFile } from "@/lib/chat/uploadedFiles";
import { withPastedTextDisplayMetadata } from "@/lib/chat/uploadedFiles";
Expand Down Expand Up @@ -53,31 +54,33 @@ export function buildTextFromComposerDraft(
draft: MentionComposerDraft,
pastedFileById?: Map<string, PendingUploadedFile>,
) {
return draft.segments
.map((segment) => {
if (segment.type === "text") {
return segment.text;
}
if (segment.type === "fileMention") {
return formatFileMentionToken(segment.reference);
}
if (segment.type === "skillMention") {
return `$${segment.skill.name}`;
}
if (segment.type === "commitMention") {
return formatComposerCommitMention(segment.commit);
}
if (segment.type === "gitFileMention") {
return formatComposerGitFileMention(segment.file);
}
if (segment.type === "codeMention") {
return formatCodeMentionToken(segment.reference);
}
const file = pastedFileById?.get(segment.paste.id);
return file ? `[${segment.paste.label}: ${file.relativePath}]` : segment.paste.text;
})
.join("")
.replace(/\u00A0/g, " ");
return normalizeLogicalLineEndings(
draft.segments
.map((segment) => {
if (segment.type === "text") {
return segment.text;
}
if (segment.type === "fileMention") {
return formatFileMentionToken(segment.reference);
}
if (segment.type === "skillMention") {
return `$${segment.skill.name}`;
}
if (segment.type === "commitMention") {
return formatComposerCommitMention(segment.commit);
}
if (segment.type === "gitFileMention") {
return formatComposerGitFileMention(segment.file);
}
if (segment.type === "codeMention") {
return formatCodeMentionToken(segment.reference);
}
const file = pastedFileById?.get(segment.paste.id);
return file ? `[${segment.paste.label}: ${file.relativePath}]` : segment.paste.text;
})
.join("")
.replace(/\u00A0/g, " "),
);
}

export async function importPastedTextsAsFiles(params: {
Expand Down
Loading
Loading