feat(composer): fold large pastes into text attachments (#11442)

This commit is contained in:
Chris Deeming authored and GitHub committed 2026-09-12 17:28:28 -07:00
1 parent 36caf200c2
commit 68c2277f50
77 files changed
+3278 -465

No files matched your search

+4
View File
@@ -103,6 +103,10 @@
"types": "./src/state/attachments.ts",
"default": "./src/state/attachments.ts"
},
"./text-paste": {
"types": "./src/textPaste.ts",
"default": "./src/textPaste.ts"
},
"./state/connections": {
"types": "./src/state/connections.ts",
"default": "./src/state/connections.ts"
@@ -0,0 +1,156 @@
import { describe, expect, it } from "vite-plus/test";
import {
nextPastedTextFileName,
PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES,
isPasteAsTextShortcut,
pastedTextDisposition,
replaceTextSelection,
wouldTextPasteExceedLimit,
} from "./textPaste.ts";
describe("pasted text disposition", () => {
it("keeps ordinary text inline and folds at the 32 KiB boundary", () => {
expect(
pastedTextDisposition({
text: "x".repeat(PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES - 1),
canAttach: true,
}),
).toBe("inline");
expect(
pastedTextDisposition({
text: "x".repeat(PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES),
canAttach: true,
}),
).toBe("attachment");
});
it("measures UTF-8 bytes instead of UTF-16 characters", () => {
const text = "🙂".repeat(PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES / 4);
expect(text.length).toBeLessThan(PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES);
expect(pastedTextDisposition({ text, canAttach: true })).toBe("attachment");
});
it("keeps text inline for the explicit bypass or without attachment support", () => {
const text = "x".repeat(PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES);
expect(pastedTextDisposition({ text, canAttach: true, bypassAutoAttachment: true })).toBe(
"inline",
);
expect(pastedTextDisposition({ text, canAttach: false })).toBe("inline");
});
it("folds a smaller paste when the resulting prompt would exceed the input limit", () => {
expect(
pastedTextDisposition({
text: "small paste",
canAttach: true,
wouldExceedInputLimit: true,
}),
).toBe("attachment");
});
});
describe("pasted text attachment names", () => {
it("uses the first available readable sequence", () => {
expect(nextPastedTextFileName([])).toBe("pasted-text.txt");
expect(nextPastedTextFileName(["PASTED-TEXT.TXT", "pasted-text-2.txt"])).toBe(
"pasted-text-3.txt",
);
});
});
describe("paste-as-text shortcut", () => {
it.each([
{ metaKey: true, ctrlKey: false, macPlatform: true },
{ metaKey: false, ctrlKey: true, macPlatform: false },
])("accepts the platform modifier with Shift", ({ metaKey, ctrlKey, macPlatform }) => {
expect(
isPasteAsTextShortcut(
{
key: "V",
metaKey,
ctrlKey,
shiftKey: true,
altKey: false,
},
macPlatform,
),
).toBe(true);
});
it("does not claim ordinary or alternate paste chords", () => {
expect(
isPasteAsTextShortcut(
{
key: "v",
metaKey: true,
ctrlKey: false,
shiftKey: false,
altKey: false,
},
true,
),
).toBe(false);
expect(
isPasteAsTextShortcut(
{
key: "v",
metaKey: true,
ctrlKey: false,
shiftKey: true,
altKey: true,
},
true,
),
).toBe(false);
});
it("rejects the other platform's modifier", () => {
const event = {
key: "v",
metaKey: false,
ctrlKey: true,
shiftKey: true,
altKey: false,
};
expect(isPasteAsTextShortcut(event, true)).toBe(false);
expect(isPasteAsTextShortcut({ ...event, metaKey: true, ctrlKey: false }, false)).toBe(false);
});
});
describe("text paste insertion", () => {
it("replaces the selected range and returns the collapsed cursor", () => {
expect(
replaceTextSelection({
value: "before old after",
selection: { start: 7, end: 10 },
text: "new",
}),
).toEqual({ value: "before new after", cursor: 10 });
});
it("clamps stale native selections", () => {
expect(
replaceTextSelection({ value: "abc", selection: { start: 20, end: 30 }, text: "!" }),
).toEqual({ value: "abc!", cursor: 4 });
});
it("measures the replacement value after removing the selected range", () => {
expect(
wouldTextPasteExceedLimit({
valueLength: 100,
selection: { start: 40, end: 80 },
textLength: 30,
maxLength: 100,
}),
).toBe(false);
expect(
wouldTextPasteExceedLimit({
valueLength: 100,
selection: { start: 40, end: 80 },
textLength: 41,
maxLength: 100,
}),
).toBe(true);
});
});
+76
View File
@@ -0,0 +1,76 @@
export const PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES = 32 * 1024;
const textEncoder = new TextEncoder();
export type PastedTextDisposition = "attachment" | "inline";
export function isPasteAsTextShortcut(
event: Pick<KeyboardEvent, "key" | "metaKey" | "ctrlKey" | "altKey" | "shiftKey">,
macPlatform: boolean,
): boolean {
return (
event.key.toLowerCase() === "v" &&
event.shiftKey &&
!event.altKey &&
(macPlatform ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey)
);
}
/**
* Large clipboard text becomes a file so an agent can inspect it selectively.
* The threshold is byte-based: character counts substantially understate the
* context cost of some Unicode-heavy clipboard contents.
*/
export function pastedTextDisposition(input: {
readonly text: string;
readonly canAttach: boolean;
readonly bypassAutoAttachment?: boolean;
readonly wouldExceedInputLimit?: boolean;
}): PastedTextDisposition {
if (input.bypassAutoAttachment || !input.canAttach || input.text.length === 0) {
return "inline";
}
return input.wouldExceedInputLimit ||
input.text.length >= PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES ||
textEncoder.encode(input.text).byteLength >= PASTED_TEXT_ATTACHMENT_THRESHOLD_BYTES
? "attachment"
: "inline";
}
/** Stable, human-readable names when a draft contains several folded pastes. */
export function nextPastedTextFileName(existingNames: ReadonlyArray<string>): string {
const names = new Set(existingNames.map((name) => name.toLowerCase()));
if (!names.has("pasted-text.txt")) {
return "pasted-text.txt";
}
for (let sequence = 2; ; sequence += 1) {
const candidate = `pasted-text-${sequence}.txt`;
if (!names.has(candidate)) {
return candidate;
}
}
}
export function replaceTextSelection(input: {
readonly value: string;
readonly selection: { readonly start: number; readonly end: number };
readonly text: string;
}): { readonly value: string; readonly cursor: number } {
const start = Math.max(0, Math.min(input.value.length, input.selection.start));
const end = Math.max(start, Math.min(input.value.length, input.selection.end));
return {
value: `${input.value.slice(0, start)}${input.text}${input.value.slice(end)}`,
cursor: start + input.text.length,
};
}
export function wouldTextPasteExceedLimit(input: {
readonly valueLength: number;
readonly selection: { readonly start: number; readonly end: number };
readonly textLength: number;
readonly maxLength: number;
}): boolean {
const start = Math.max(0, Math.min(input.valueLength, input.selection.start));
const end = Math.max(start, Math.min(input.valueLength, input.selection.end));
return input.valueLength - (end - start) + input.textLength > input.maxLength;
}
+2
View File
@@ -1308,6 +1308,8 @@ export interface DesktopBridge {
* builds lack it; callers fall back to VS Code only.
*/
probeRemoteEditors?: () => Promise<readonly EditorId[]>;
/** Present when the desktop shell can perform an ordered plain-text paste. */
pasteAsText?: () => Promise<void>;
onMenuAction: (listener: (action: string) => void) => () => void;
onSnapShotEvent?: (listener: (event: DesktopSnapShotEvent) => void) => () => void;
/**
+7
View File
@@ -310,6 +310,9 @@ export const ChatImageAttachment = Schema.Struct({
});
export type ChatImageAttachment = typeof ChatImageAttachment.Type;
export const PastedTextAttachmentSource = Schema.TaggedStruct("pasted-text", {});
export type PastedTextAttachmentSource = typeof PastedTextAttachmentSource.Type;
export const ChatFileAttachment = Schema.Struct({
type: Schema.Literal("file"),
id: ChatAttachmentId,
@@ -319,6 +322,10 @@ export const ChatFileAttachment = Schema.Struct({
Schema.isGreaterThanOrEqualTo(1),
Schema.isLessThanOrEqualTo(PROVIDER_SEND_TURN_MAX_FILE_BYTES),
),
/** Clipboard text folded by a client. Providers keep these path-only so the
agent can inspect the file selectively instead of eagerly spending the
same context the fold is intended to preserve. */
source: Schema.optional(PastedTextAttachmentSource),
});
export type ChatFileAttachment = typeof ChatFileAttachment.Type;
@@ -582,6 +582,22 @@ describe("upgradeLegacyContextMessage", () => {
]);
});
it("keeps adjacent trailing reviews in place, including their original spacing", () => {
const upgraded = upgradeLegacyContextMessage(`Compare ${review} ${review}`);
expect(upgraded.text).toBe(
"Compare [f.ts line](t3-context://v1/review-comment/legacy_review-comment_1) [f.ts line](t3-context://v1/review-comment/legacy_review-comment_2)",
);
});
it("keeps a trailing review beside a terminal chip whose payload follows it", () => {
const upgraded = upgradeLegacyContextMessage(
`@build:7 ${review}\n\n<terminal_context>\n- Build line 7:\n output\n</terminal_context>`,
);
expect(upgraded.text).toBe(
"[Build line 7](t3-context://v1/terminal/legacy_terminal_1) [f.ts line](t3-context://v1/review-comment/legacy_review-comment_1)",
);
});
it("handles the combined legacy send order: terminal, element, preview, review", () => {
const text = [
"See ",
+13 -6
View File
@@ -339,15 +339,22 @@ export function upgradeLegacyContextMessage(text: string): UpgradedLegacyContext
// Blocks were appended in send order (terminal, element, preview, review), so they peel
// off the end in reverse. Each peel exposes the next block as trailing.
// Only reviews that trailed the original text were appended by the old send path; a
// review that sat before other blocks keeps its place.
// Peel reviews only when they hide another trailing context block. A review at the end
// of ordinary prose can still be inline; keep its original spacing and line breaks.
const trailingReviewTokens: number[] = [];
const tokens = trailingReviewTokenPattern.exec(rest);
if (tokens && tokens[0].length > 0) {
trailingReviewTokens.push(
...Array.from(tokens[0].matchAll(reviewTokenPattern), (m) => Number(m[1])),
);
rest = rest.slice(0, tokens.index).replace(/\n+$/, "");
const preceding = rest.slice(0, tokens.index);
if (
TRAILING_PREVIEW.test(preceding) ||
TRAILING_ELEMENT.test(preceding) ||
TRAILING_TERMINAL.test(preceding)
) {
trailingReviewTokens.push(
...Array.from(tokens[0].matchAll(reviewTokenPattern), (m) => Number(m[1])),
);
rest = preceding;
}
}
for (;;) {
const preview = stripTrailing(rest, TRAILING_PREVIEW);
@@ -99,6 +99,31 @@ describe("serializeLegacyContextMessage", () => {
});
});
it.each([" ", "\n", "\n\n"])(
"preserves the separator between a skill and a trailing PR through an older server: %j",
(separator) => {
const pullRequest = {
...review,
label: "#11440",
sectionId: "pull-request:11440",
sectionTitle: "Pull request",
filePath: "PR #11440",
rangeLabel: "summary",
text: "Audit Mobile Photo Import",
diff: "",
};
const text = `$pr-audit${separator}${formatComposerContextReference(pullRequest)}`;
const upgraded = upgradeLegacyContextMessage(
serializeLegacyContextMessage({ text, records: [pullRequest] }),
);
expect(upgraded.records).toHaveLength(1);
expect(upgraded.text).toBe(
`$pr-audit${separator}${formatComposerContextReference(upgraded.records[0]!)}`,
);
},
);
it("retains picked-element details for preview annotations sent through an older server", () => {
const text = `Update ${formatComposerContextReference(annotation)}`;
const upgraded = upgradeLegacyContextMessage(