feat: paste local files into chat attachments

Copied local files previously required the attachment picker. The chat
composer now imports one or more supported files directly from paste,
sharing parsing progress, limits, and batch rollback with file selection.
Text and screenshot paste remain available, and failures preserve drafts.

Validation: prior 166 focused tests, typecheck, and lint passed; 28 targeted
tests passed again before commit. The prior full suite had 4214 passes,
67 skips, and 6 window-recovery failures; window tests passed 10/10 alone.
Native clipboard behavior was verified on Windows; macOS/Linux remain unverified.

Release note: 现在可在文件管理器中复制一个或多个支持的本地文件,直接粘贴到聊天输入框添加附件;可查看读取和解析进度,失败时保留草稿与已有附件。
This commit is contained in:
mesalogo
2026-09-15 08:05:31 +08:00
parent e1fe1cf10a
commit d4f1668c9b
19 changed files with 344 additions and 29 deletions
+66 -5
View File
@@ -753,6 +753,8 @@ const api: DesktopApi = {
})),
},
context: {
getFilePath: vi.fn(() => ""),
importFiles: vi.fn(async () => []),
selectFiles: vi.fn(async () => []),
onFileSelectionProgress: vi.fn((listener) => {
fileSelectionProgressListener = listener;
@@ -1586,11 +1588,11 @@ describe("App", () => {
).toBeInTheDocument();
expect(screen.getByLabelText("Message GoodBuddy")).toHaveAttribute(
"placeholder",
"Message GoodBuddy…\nEnter to send, Shift+Enter for a new line, Ctrl+V to paste an image or text",
"Message GoodBuddy…\nEnter to send, Shift+Enter for a new line, Ctrl+V to paste files, images, or text",
);
expect(screen.getByLabelText("Message GoodBuddy")).toHaveAttribute(
"title",
"Enter to send, Shift+Enter for a new line, Ctrl+V to paste an image or text",
"Enter to send, Shift+Enter for a new line, Ctrl+V to paste files, images, or text",
);
} finally {
cleanup();
@@ -5776,7 +5778,7 @@ describe("App", () => {
name: "附件读取与解析进度",
}),
).toBeInTheDocument();
expect(screen.getByText("正在选择附件…")).toBeInTheDocument();
expect(screen.getByText("正在添加附件…")).toBeInTheDocument();
act(() => {
fileSelectionProgressListener?.({
@@ -5875,6 +5877,63 @@ describe("App", () => {
);
});
it("imports copied files with progress, prevents duplicate pastes, and sends their context", async () => {
const files = [new File(["notes"], "notes.txt"), new File(["doc"], "report.docx")];
vi.mocked(api.context.getFilePath)
.mockReturnValueOnce("C:\\notes.txt")
.mockReturnValueOnce("C:\\report.docx");
const attachments: ContextAttachment[] = files.map((file, index) => ({
id: `00000000-0000-4000-8000-00000000032${index}`,
name: file.name, kind: "text", size: 4, preview: "parsed content",
}));
let finish: ((attachments: ContextAttachment[]) => void) | undefined;
vi.mocked(api.context.importFiles).mockImplementationOnce(() => new Promise(resolve => { finish = resolve; }));
render(<App />);
const input = await screen.findByLabelText("向 GoodBuddy 提问");
fireEvent.change(input, { target: { value: "Read these files" } });
expect(fireEvent.paste(input, { clipboardData: { files } })).toBe(false);
expect(api.context.importFiles).toHaveBeenCalledExactlyOnceWith(["C:\\notes.txt", "C:\\report.docx"]);
expect(screen.getByLabelText("添加附件")).toBeDisabled();
act(() => fileSelectionProgressListener?.({
phase: "parsing", fileName: "report.docx", fileNumber: 2, fileCount: 2,
}));
expect(screen.getByText("正在解析 report.docx")).toBeInTheDocument();
fireEvent.paste(input, { clipboardData: { files } });
fireEvent.keyDown(input, { key: "Enter" });
expect(api.context.importFiles).toHaveBeenCalledOnce();
expect(run).not.toHaveBeenCalled();
act(() => finish?.(attachments));
expect(await screen.findByText("report.docx")).toBeInTheDocument();
expect(input).toHaveValue("Read these files");
await waitFor(() => expect(screen.getByLabelText("添加附件")).toBeEnabled());
fireEvent.keyDown(input, { key: "Enter" });
await waitFor(() => expect(run).toHaveBeenCalledWith(expect.objectContaining({
prompt: "Read these files", contextIds: attachments.map(item => item.id),
})));
expect(api.context.addPastedImage).not.toHaveBeenCalled();
expect(api.context.selectFiles).not.toHaveBeenCalled();
});
it("shows file paste failures without clearing the draft and rejects oversized batches", async () => {
render(<App />);
const input = await screen.findByLabelText("向 GoodBuddy 提问");
fireEvent.change(input, { target: { value: "Keep this draft" } });
const file = new File(["archive"], "archive.zip");
vi.mocked(api.context.getFilePath).mockReturnValueOnce("C:\\archive.zip");
vi.mocked(api.context.importFiles).mockRejectedValueOnce(new Error("不支持的文件类型:.zip"));
fireEvent.paste(input, { clipboardData: { files: [file] } });
expect(await screen.findByRole("alert", { name: "不支持的文件类型:.zip" })).toBeInTheDocument();
expect(input).toHaveValue("Keep this draft");
await waitFor(() => expect(screen.getByLabelText("添加附件")).toBeEnabled());
fireEvent.paste(input, { clipboardData: { files: Array(9).fill(file) } });
expect(api.context.importFiles).toHaveBeenCalledOnce();
expect(input).toHaveAttribute("aria-invalid", "true");
fireEvent.paste(input, { clipboardData: { files: [file] } });
expect(await screen.findByRole("alert", {
name: "无法读取此剪贴板文件,请保存到本地后通过附件按钮添加",
})).toBeInTheDocument();
});
it("accepts pasted images without intercepting pasted text", async () => {
vi.mocked(api.context.addPastedImage).mockResolvedValueOnce({
id: "00000000-0000-4000-8000-000000000303",
@@ -5895,6 +5954,7 @@ describe("App", () => {
expect(
fireEvent.paste(input, {
clipboardData: {
files: [],
items: [
{
getAsFile: () => null,
@@ -5909,6 +5969,7 @@ describe("App", () => {
fireEvent.paste(input, {
clipboardData: {
files: [pastedImage],
items: [
{
getAsFile: () => pastedImage,
@@ -6685,7 +6746,7 @@ describe("App", () => {
).toHaveTextContent(/^Ask$/u);
expect(screen.getByLabelText("向 GoodBuddy 提问")).toHaveAttribute(
"placeholder",
"给 GoodBuddy 发消息…\nEnter 发送,Shift+Enter 换行,Ctrl+V 粘贴图片或文本",
"给 GoodBuddy 发消息…\nEnter 发送,Shift+Enter 换行,Ctrl+V 粘贴文件、图片或文本",
);
expect(
within(conversationSettings).getByRole("button", {
@@ -10146,7 +10207,7 @@ describe("App", () => {
expect((await screen.findAllByText("生图")).length).toBeGreaterThan(0);
expect(screen.getByLabelText("向 GoodBuddy 提问")).toHaveAttribute(
"placeholder",
"描述你想生成的图片…\nEnter 发送,Shift+Enter 换行,Ctrl+V 粘贴图片或文本",
"描述你想生成的图片…\nEnter 发送,Shift+Enter 换行,Ctrl+V 粘贴文件、图片或文本",
);
await waitFor(() => expect(api.artifacts.list).toHaveBeenCalled());
+36 -11
View File
@@ -7571,7 +7571,7 @@ function App(): React.JSX.Element {
}
};
const selectContextFiles = async (): Promise<void> => {
const selectContextFiles = async (paths?: string[]): Promise<void> => {
if (selectingContextFilesRef.current) {
return;
}
@@ -7579,7 +7579,9 @@ function App(): React.JSX.Element {
setSelectingContextFiles(true);
setFileSelectionProgress(undefined);
try {
await addContext(() => window.goodbuddy.context.selectFiles());
await addContext(() => paths
? window.goodbuddy.context.importFiles(paths)
: window.goodbuddy.context.selectFiles());
} finally {
selectingContextFilesRef.current = false;
setSelectingContextFiles(false);
@@ -9452,17 +9454,40 @@ function App(): React.JSX.Element {
value={input}
onChange={(event) => setInput(event.target.value)}
onPaste={(event) => {
const imageItem = Array.from(
event.clipboardData.items,
).find(
(item) =>
item.kind === "file" &&
item.type.startsWith("image/"),
);
if (!imageItem) {
const files = Array.from(event.clipboardData.files);
if (files.length > 0) {
event.preventDefault();
if (selectingContextFilesRef.current) {
setContextError(t("composer.attachmentProgress.waitBeforeSending"));
return;
}
if (files.length > 8) {
setContextError(t("composer.errors.attachmentLimit"));
return;
}
try {
const paths = files.map((file) => window.goodbuddy.context.getFilePath(file));
if (paths.some(Boolean)) {
if (paths.some((path) => !path)) {
setContextError(t("composer.errors.pasteFilePath"));
return;
}
void selectContextFiles(paths);
return;
}
if (files.some((file) => !file.type.startsWith("image/"))) {
setContextError(t("composer.errors.pasteFilePath"));
return;
}
} catch (reason) {
setContextError(reason instanceof Error ? reason.message : t("composer.errors.addContext"));
return;
}
}
const image = files.find((file) => file.type.startsWith("image/"));
if (!image) {
return;
}
const image = imageItem.getAsFile();
const mimeType =
image?.type === "image/jpeg" ||
image?.type === "image/png" ||
+3 -2
View File
@@ -435,11 +435,11 @@ export const app = {
placeholder: 'Message GoodBuddy…',
imagePlaceholder: 'Describe the image you want to generate…',
keyboardHint:
'Enter to send, Shift+Enter for a new line, Ctrl+V to paste an image or text',
'Enter to send, Shift+Enter for a new line, Ctrl+V to paste files, images, or text',
addContent: 'Add content',
addAttachment: 'Add attachment',
attachmentProgress: {
selecting: 'Selecting attachments…',
selecting: 'Adding attachments…',
reading: 'Reading {{name}}',
parsing: 'Parsing {{name}}',
waiting: 'Files will be read and parsed after selection',
@@ -618,6 +618,7 @@ export const app = {
},
errors: {
pasteImageType: 'Only JPEG, PNG, or WebP images can be pasted',
pasteFilePath: 'Cannot read this clipboard file. Save it locally, then use Add attachment.',
pasteImageSize: 'Pasted images cannot exceed 12 MB',
attachmentLimit: 'A message can include up to 8 attachments',
addContext: 'Failed to add context'
+3 -2
View File
@@ -416,11 +416,11 @@ export const app = {
placeholder: '给 GoodBuddy 发消息…',
imagePlaceholder: '描述你想生成的图片…',
keyboardHint:
'Enter 发送,Shift+Enter 换行,Ctrl+V 粘贴图片或文本',
'Enter 发送,Shift+Enter 换行,Ctrl+V 粘贴文件、图片或文本',
addContent: '添加内容',
addAttachment: '添加附件',
attachmentProgress: {
selecting: '正在选择附件…',
selecting: '正在添加附件…',
reading: '正在读取 {{name}}',
parsing: '正在解析 {{name}}',
waiting: '选择文件后将自动读取并解析',
@@ -578,6 +578,7 @@ export const app = {
},
errors: {
pasteImageType: '仅支持粘贴 JPEG、PNG 或 WebP 图片',
pasteFilePath: '无法读取此剪贴板文件,请保存到本地后通过附件按钮添加',
pasteImageSize: '粘贴图片不能超过 12MB',
attachmentLimit: '单次消息最多添加 8 个附件',
addContext: '添加上下文失败'