DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.
fix(clipboard): Linux 桌面端对话框支持粘贴剪贴板文件 (#1160) (#1169)
北巷249a6df70e16
diff --git a/src-tauri/src/bridge/clipboard.rs b/src-tauri/src/bridge/clipboard.rsindex 309d4a48..d460ef73 100644--- a/src-tauri/src/bridge/clipboard.rs+++ b/src-tauri/src/bridge/clipboard.rs@@ -1,4 +1,4 @@-//! 原生剪贴板读写(Linux/WebKitGTK 贴图回退 + Wayland 安全文本写入)。+//! 原生剪贴板读写(Linux/WebKitGTK 贴图/贴文件回退 + Wayland 安全文本写入)。//!//! ## 读取(图片)//! WebKitGTK 不通过 Web API(`ClipboardEvent.clipboardData.items/files`)暴露@@ -7,6 +7,15 @@//! PNG data URL 返回;注入到 iframe 的桥脚本(`desktop::paste::PASTE_SHIM_JS`)//! 拿到该 data URL 后重新派发 `paste` 事件,让 dsh 聊天框按正常贴图路径处理。//!+//! ## 读取(文件列表,issue #1160)+//! 同一族限制:文件管理器复制文件时,剪贴板里是 `text/uri-list` /+//! `x-special/gnome-copied-files`,WebKitGTK 同样不把它映射成 `clipboardData`+//! 的文件条目;而图片回退桥「无图无文本即吞事件」的行为(issue #610 修复引入)+//! 让贴文件比不修更沉默——事件被 `preventDefault`,图片读取又拿不到图。+//! `read_clipboard_files` 在 Rust 侧用 `arboard` 的 `clipboard.get().file_list()`+//! 读出绝对路径,逐个读成带 MIME 的 data URL 回传;桥脚本把结果全部塞进同一个+//! `DataTransfer` 重发合成 `paste`,dsh 输入框的 `intakeFiles` 原样命中。+//!//! ## 写入(文本)//! 前端的「复制日志 / 复制服务地址」等操作统一走本模块的写入命令,而不是//! `tauri-plugin-clipboard-manager`:后者在**应用启动时**就在主线程上创建并持有@@ -20,6 +29,8 @@//! - 不复用跨操作的长生命周期句柄,规避 Wayland 回退后的挂死 / 崩溃;//! - Wayland 不支持时 `arboard` 自动回退 X11,仍是尽力而为,不抛出。+use std::path::{Path, PathBuf};+use base64::{engine::general_purpose::STANDARD, Engine};/// 剪贴板图片读取结果:自包含的 PNG data URL(可直接作为 Blob/File 来源)。@@ -132,3 +143,274 @@ pub async fn write_clipboard_text(text: String) -> Result<(), String> {.await.map_err(|e| format!("CLIPBOARD_TEXT_TASK: {e}"))?}++/// 单个剪贴板附件的字节上限:超过则拒绝(提示降级),避免整份大文件 base64+/// 后经 `postMessage` 塞爆 WebView(≈27MB 文本,与贴图 50MP 上限同量级)。+const MAX_CLIPBOARD_FILE_BYTES: u64 = 20 * 1024 * 1024;++/// 单次粘贴最多读取的附件数:防御剪贴板里成百上千个文件的极端场景。+const MAX_CLIPBOARD_FILES: usize = 32;++/// 单次粘贴累计读取的字节上限:单文件上限挡不住「多个刚好不超限」的极端组合+/// (32×20MB=640MB 仍会撑爆 WebView),累计越线即整批拒绝,提示用户改用引用路径。+const MAX_CLIPBOARD_TOTAL_BYTES: u64 = 64 * 1024 * 1024;++/// 剪贴板文件读取结果:成功附件 + 被拒条目(前端据此提示降级,不静默丢弃)。+#[derive(Debug, serde::Serialize)]+pub struct ClipboardFileEntry {+ /// 形如 `data:<mime>;base64,...`+ pub data_url: String,+ pub mime: String,+ pub filename: String,+ pub size: u64,+}++/// 被拒绝条目的原因码:`too_large` / `unreadable` / `not_a_file` / `total_exceeded`。+#[derive(Debug, serde::Serialize)]+pub struct ClipboardFileRejection {+ pub filename: String,+ pub reason: String,+}++#[derive(Debug, serde::Serialize)]+pub struct ClipboardFilesResponse {+ pub files: Vec<ClipboardFileEntry>,+ pub rejected: Vec<ClipboardFileRejection>,+}++/// 按扩展名推断 MIME,未知统一 `application/octet-stream`。+///+/// 只覆盖聊天框常见附件类型;其余按通用二进制,输入框据此走普通文件上传路径。+fn guess_mime_by_extension(path: &Path) -> String {+ let ext = path+ .extension()+ .and_then(|e| e.to_str())+ .unwrap_or_default()+ .to_ascii_lowercase();+ match ext.as_str() {+ "png" => "image/png",+ "jpg" | "jpeg" => "image/jpeg",+ "gif" => "image/gif",+ "webp" => "image/webp",+ "bmp" => "image/bmp",+ "svg" => "image/svg+xml",+ "txt" | "md" | "log" => "text/plain",+ "csv" => "text/csv",+ "json" => "application/json",+ "pdf" => "application/pdf",+ "zip" => "application/zip",+ _ => "application/octet-stream",+ }+ .to_string()+}++/// 剪贴板文件的展示名:取路径末段,异常(空/非 UTF-8)落回通用名。+fn clipboard_filename(path: &Path) -> String {+ path.file_name()+ .and_then(|n| n.to_str())+ .unwrap_or("clipboard-file")+ .to_string()+}++/// 读取单个剪贴板文件并编码为 data URL;不可粘时返回拒绝原因。+///+/// `remaining` 是本次粘贴剩余的总量配额。**所有判定都在 `metadata` 阶段完成**+/// (目录 / 单文件超限 / 总量不足都在读文件内容之前拒绝),避免「整份读进内存+/// 再丢弃」的峰值;成功时从 `remaining` 扣掉本文件字节数。+fn read_one_clipboard_file(+ path: &Path,+ remaining: &mut u64,+) -> Result<ClipboardFileEntry, ClipboardFileRejection> {+ // 闭包只捕获 `path` 引用(各分支现场提取文件名),不在别处持有 String 借用+ let reject = |reason: &str| ClipboardFileRejection {+ filename: clipboard_filename(path),+ reason: reason.to_string(),+ };++ let metadata = match std::fs::metadata(path) {+ Ok(metadata) => metadata,+ Err(_) => return Err(reject("unreadable")),+ };+ // 目录 / 符号链接指向的非普通文件:聊天框没有目录附件语义,拒绝而非吞掉+ if !metadata.is_file() {+ return Err(reject("not_a_file"));+ }+ if metadata.len() > MAX_CLIPBOARD_FILE_BYTES {+ return Err(reject("too_large"));+ }+ if metadata.len() > *remaining {+ return Err(reject("total_exceeded"));+ }++ let bytes = match std::fs::read(path) {+ Ok(bytes) => bytes,+ Err(_) => return Err(reject("unreadable")),+ };+ *remaining -= metadata.len();++ let mime = guess_mime_by_extension(path);+ let b64 = STANDARD.encode(bytes);+ Ok(ClipboardFileEntry {+ data_url: format!("data:{mime};base64,{b64}"),+ mime,+ size: metadata.len(),+ filename: clipboard_filename(path),+ })+}++/// 把剪贴板路径列表读成附件响应(纯同步、可单测;由 `read_clipboard_files` 在+/// `spawn_blocking` 内调用)。+///+/// 三级防御:条数(`take`,最多 32)、单文件(20MB)、累计总量(64MB)。后两级+/// 判定都在读内容之前(见 [`read_one_clipboard_file`]),被拒条目随响应回传,+/// 由宿主提示降级,不静默丢弃。+fn collect_clipboard_files(paths: Vec<PathBuf>) -> ClipboardFilesResponse {+ let mut files = Vec::new();+ let mut rejected = Vec::new();+ let mut remaining = MAX_CLIPBOARD_TOTAL_BYTES;+ for path in paths.into_iter().take(MAX_CLIPBOARD_FILES) {+ match read_one_clipboard_file(&path, &mut remaining) {+ Ok(entry) => files.push(entry),+ Err(deny) => rejected.push(deny),+ }+ }+ ClipboardFilesResponse { files, rejected }+}++/// 从系统剪贴板读取文件列表并逐个编码为 data URL(issue #1160,贴文件回退)。+///+/// 路径完全来自**系统剪贴板**(本命令读取),不接受 iframe 传入的路径——iframe+/// 无法借这座桥读取本机任意文件。剪贴板无文件时返回空列表(不是错误)。+///+/// Linux 两个后端(X11 `URI_LIST`/`GNOME_COPIED_FILES`、Wayland `text/uri-list`)+/// arboard 3.6.1 均已实现;Wayland 合成器不支持 data-control 时 arboard 自行回退+/// X11,读不到则返回 `ContentNotAvailable` / `ClipboardNotSupported`,一律降级为+/// 空列表(行为与修复前一致,不抛出)。+///+/// 与 [`read_clipboard_image`] 一致:`spawn_blocking` 内惰性新建短期+/// `arboard::Clipboard`,用完即弃。失败返回 `Err`(前缀 `CLIPBOARD_FILES_`)。+#[tauri::command]+pub async fn read_clipboard_files() -> Result<ClipboardFilesResponse, String> {+ tokio::task::spawn_blocking(|| -> Result<ClipboardFilesResponse, String> {+ let mut clipboard =+ arboard::Clipboard::new().map_err(|e| format!("CLIPBOARD_FILES_ACCESS: {e}"))?;++ let paths = match clipboard.get().file_list() {+ Ok(paths) => paths,+ // 剪贴板里没有文件(普通文本 / 图片等),不是错误+ Err(arboard::Error::ContentNotAvailable) => Vec::new(),+ // 后端不支持 / 无法访问文件列表(如 Wayland 无 data-control 且 X11 回退失败):+ // 优雅降级为空,与修复前行为一致+ Err(arboard::Error::ClipboardNotSupported) => Vec::new(),+ Err(e) => return Err(format!("CLIPBOARD_FILES_READ: {e}")),+ };++ Ok(collect_clipboard_files(paths))+ })+ .await+ .map_err(|e| format!("CLIPBOARD_FILES_TASK: {e}"))?+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn read_one_clipboard_file_encodes_with_guessed_mime() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("photo.jpg");+ // JPEG magic + 占位内容:长度一律由 PAYLOAD 推导,避免手数字节数漂移+ const PAYLOAD: &[u8] = b"\xff\xd8\xff\xe0 fake jpeg";+ std::fs::write(&path, PAYLOAD).unwrap();++ let mut remaining = MAX_CLIPBOARD_TOTAL_BYTES;+ let entry = read_one_clipboard_file(&path, &mut remaining).unwrap();+ assert_eq!(entry.filename, "photo.jpg");+ assert_eq!(entry.mime, "image/jpeg");+ assert!(entry.data_url.starts_with("data:image/jpeg;base64,"));+ assert_eq!(entry.size, PAYLOAD.len() as u64);+ assert_eq!(remaining, MAX_CLIPBOARD_TOTAL_BYTES - PAYLOAD.len() as u64);+ }++ #[test]+ fn read_one_clipboard_file_rejects_directory_as_not_a_file() {+ let dir = tempfile::tempdir().unwrap();+ let mut remaining = MAX_CLIPBOARD_TOTAL_BYTES;+ let deny = read_one_clipboard_file(dir.path(), &mut remaining).unwrap_err();+ assert_eq!(deny.reason, "not_a_file");+ }++ #[test]+ fn read_one_clipboard_file_rejects_missing_path_as_unreadable() {+ let dir = tempfile::tempdir().unwrap();+ let missing = dir.path().join("gone.bin");+ let mut remaining = MAX_CLIPBOARD_TOTAL_BYTES;+ let deny = read_one_clipboard_file(&missing, &mut remaining).unwrap_err();+ assert_eq!(deny.reason, "unreadable");+ }++ #[test]+ fn read_one_clipboard_file_rejects_oversize_without_reading_body() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("big.bin");+ // 稀疏文件:只记长度,不落真实磁盘块,测试仍快速+ let file = std::fs::File::create(&path).unwrap();+ file.set_len(MAX_CLIPBOARD_FILE_BYTES + 1).unwrap();++ let mut remaining = MAX_CLIPBOARD_TOTAL_BYTES;+ let deny = read_one_clipboard_file(&path, &mut remaining).unwrap_err();+ assert_eq!(deny.reason, "too_large");+ assert_eq!(deny.filename, "big.bin");+ // 拒绝发生在 metadata 阶段:配额未消耗+ assert_eq!(remaining, MAX_CLIPBOARD_TOTAL_BYTES);+ }++ #[test]+ fn read_one_clipboard_file_rejects_when_total_quota_exhausted() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("ok.txt");+ std::fs::write(&path, b"content").unwrap();++ // 文件本身没超单文件上限,但剩余配额为 0 → total_exceeded,且不消耗、不读取+ let mut remaining = 0;+ let deny = read_one_clipboard_file(&path, &mut remaining).unwrap_err();+ assert_eq!(deny.reason, "total_exceeded");+ assert_eq!(deny.filename, "ok.txt");+ assert_eq!(remaining, 0);+ }++ #[test]+ fn collect_clipboard_files_keeps_order_and_quotas_across_batch() {+ let dir = tempfile::tempdir().unwrap();+ let small = dir.path().join("a.txt");+ std::fs::write(&small, b"12345").unwrap();+ let missing = dir.path().join("gone.txt");++ let response = collect_clipboard_files(vec![small.clone(), missing.clone(), small]);+ assert_eq!(response.files.len(), 2);+ assert_eq!(response.files[0].filename, "a.txt");+ assert_eq!(response.rejected.len(), 1);+ assert_eq!(response.rejected[0].reason, "unreadable");+ }++ #[test]+ fn collect_clipboard_files_caps_entry_count() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("x.txt");+ std::fs::write(&path, b"x").unwrap();+ let paths = vec![path; MAX_CLIPBOARD_FILES + 10];++ let response = collect_clipboard_files(paths);+ assert_eq!(response.files.len(), MAX_CLIPBOARD_FILES);+ assert!(response.rejected.is_empty());+ }++ #[test]+ fn guess_mime_covers_common_types_and_falls_back() {+ assert_eq!(guess_mime_by_extension(Path::new("a.PNG")), "image/png");+ assert_eq!(guess_mime_by_extension(Path::new("b.md")), "text/plain");+ assert_eq!(guess_mime_by_extension(Path::new("c.pdf")), "application/pdf");+ assert_eq!(guess_mime_by_extension(Path::new("d.unknownext")), "application/octet-stream");+ assert_eq!(guess_mime_by_extension(Path::new("noext")), "application/octet-stream");+ }+}diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rsindex 9d1c0816..4fadb827 100644--- a/src-tauri/src/desktop/builder.rs+++ b/src-tauri/src/desktop/builder.rs@@ -1655,6 +1655,7 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {crate::bridge::get_desktop_about,crate::bridge::open_external_url,crate::bridge::read_clipboard_image,+ crate::bridge::read_clipboard_files,crate::bridge::read_clipboard_text,crate::bridge::write_clipboard_text,crate::desktop::window::create_app_window,diff --git a/src-tauri/src/desktop/paste.rs b/src-tauri/src/desktop/paste.rsindex 5d182a87..bc028550 100644--- a/src-tauri/src/desktop/paste.rs+++ b/src-tauri/src/desktop/paste.rs@@ -1,17 +1,22 @@-//! 剪贴板图片回退桥:让 Linux/WebKitGTK 下 iframe 的「贴图」走原生剪贴板。+//! 剪贴板回退桥:让 Linux/WebKitGTK 下 iframe 的「贴图 / 贴文件」走原生剪贴板。//!-//! WebKitGTK 不通过 Web API 暴露 `image/*` 剪贴板条目,因此截图复制到系统剪贴板后,-//! 在桌面端内嵌的 dsh iframe 中输入框按 Ctrl+V 时,`paste` 事件的-//! `clipboardData` 里既没有图片也没有文本。本脚本在**捕获阶段**监听 `paste`,-//! 检测到「无图片且无文本」时:preventDefault → 向宿主 postMessage 请求读取系统-//! 剪贴板图片(宿主调用 `bridge::read_clipboard_image`)→ 拿到 PNG data URL →-//! 构造 File 并重发一次合成 `paste` 事件给当前焦点元素,让 dsh 聊天框按普通-//! 贴图路径处理,从而与浏览器行为一致。+//! WebKitGTK 不通过 Web API 暴露 `image/*` 与文件(`text/uri-list` /+//! `x-special/gnome-copied-files`)剪贴板条目,因此截图或从文件管理器复制文件后,+//! 在桌面端内嵌的 dsh iframe 中输入框按 Ctrl+V 时,`paste` 事件的 `clipboardData`+//! 里既没有图片、没有文件、往往也没有文本。本脚本在**捕获阶段**监听 `paste`,+//! 检测到「无图片且无文本」时:preventDefault → 先向宿主请求读取系统剪贴板文件+//! (宿主调用 `bridge::read_clipboard_files`)→ 有文件则把全部条目塞进同一个+//! `DataTransfer` 构造 `File` 并重发一次合成 `paste`;无文件再回退读取剪贴板图片+//! (宿主调用 `bridge::read_clipboard_image`)→ 拿到 PNG data URL → 构造 `File`+//! 重发合成 `paste`。两条路径都让 dsh 聊天框按普通附件处理,与浏览器行为一致。//!//! 与 [`crate::desktop::notification::NOTIFICATION_SHIM_JS`] / [`crate::desktop::compat::ABORT_SIGNAL_ANY_SHIM_JS`]//! 走同一套注入通道(Windows 在 FrameCreated → ContentLoading 时 ExecuteScript,//! 其余平台 `initialization_script_for_all_frames`)。脚本带 `__dsh_clipboard_image_bridge__`//! 幂等守卫,重复注入安全;只处理「直接 iframe」发来的剪贴板请求,避免多层 iframe 误转发。+//!+//! 安全:文件路径完全来自**系统剪贴板**(宿主侧读取并回传),iframe 只能请求+//! 「读剪贴板」而不能指定路径,因此不能借本桥读取本机任意文件(issue #1160)。pub(crate) const PASTE_SHIM_JS: &str = r#"(function () {if (window.__dsh_clipboard_image_bridge__) return;@@ -23,17 +28,19 @@ pub(crate) const PASTE_SHIM_JS: &str = r#"(function () {var REQ_SRC = 'dsh-clipboard-image-bridge';var REQ_TYPE = 'dsh://clipboard-image:read';var RES_TYPE = 'dsh://clipboard-image:reply';+ var REQ_FILES_TYPE = 'dsh://clipboard-files:read';+ var RES_FILES_TYPE = 'dsh://clipboard-files:reply';var reqSeq = 0;- var pending = {}; // id -> { resolve, target }+ var pending = {}; // id -> resolve(宿主回包按 type 分发,携带原始 data 调用)- function requestClipboardImage(target) {+ function request(reqType) {return new Promise(function (resolve) {reqSeq += 1;var id = 'req-' + reqSeq;- pending[id] = { resolve: resolve, target: target };+ pending[id] = resolve;try {- window.parent.postMessage({ source: REQ_SRC, type: REQ_TYPE, id: id }, '*');+ window.parent.postMessage({ source: REQ_SRC, type: reqType, id: id }, '*');} catch (_) {delete pending[id];resolve(null);@@ -45,14 +52,15 @@ pub(crate) const PASTE_SHIM_JS: &str = r#"(function () {window.addEventListener('message', function (event) {if (event.source !== window.parent) return;var data = event.data;- if (!data || typeof data !== 'object' || data.type !== RES_TYPE) return;- var item = pending[data.id];- if (!item) return;+ if (!data || typeof data !== 'object') return;+ if (data.type !== RES_TYPE && data.type !== RES_FILES_TYPE) return;+ var resolve = pending[data.id];+ if (!resolve) return;delete pending[data.id];- item.resolve(data.data_url || null);+ resolve(data);});- // 剪贴板事件里是否已带图片(非 WebKitGTK 场景):不介入,交 dsh 自身处理+ // 剪贴板事件里是否已带图片 / 文件(非 WebKitGTK 场景):不介入,交 dsh 自身处理function hasImageData(dt) {if (!dt) return false;try {@@ -104,14 +112,11 @@ pub(crate) const PASTE_SHIM_JS: &str = r#"(function () {}}- // 把图片作为 File 塞进新的 DataTransfer,再派发合成 paste 给焦点元素- function dispatchImagePaste(target, dataUrl) {- var blob = dataUrlToBlob(dataUrl);- if (!blob) return;- var file = new File([blob], 'clipboard-image.png', { type: blob.type || 'image/png' });+ // 把若干 File 塞进同一个 DataTransfer,派发一次合成 paste 给焦点元素+ function dispatchPasteWithFiles(target, files) {try {var dt = new DataTransfer();- dt.items.add(file);+ for (var i = 0; i < files.length; i++) dt.items.add(files[i]);var ev;try {ev = new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true });@@ -129,6 +134,29 @@ pub(crate) const PASTE_SHIM_JS: &str = r#"(function () {} catch (_) {}}+ // 把图片作为 File 塞进新的 DataTransfer,再派发合成 paste 给焦点元素+ function dispatchImagePaste(target, dataUrl) {+ var blob = dataUrlToBlob(dataUrl);+ if (!blob) return;+ var file = new File([blob], 'clipboard-image.png', { type: blob.type || 'image/png' });+ dispatchPasteWithFiles(target, [file]);+ }++ // 把宿主回传的文件条目(data_url + 真实文件名/MIME)还原成 File 后一次性派发。+ // 返回成功构造的数量,0 表示宿主没给到可用文件(调用方据此回退图片路径)。+ function dispatchFilesPaste(target, entries) {+ var files = [];+ for (var i = 0; i < entries.length; i++) {+ var entry = entries[i];+ if (!entry || typeof entry.data_url !== 'string') continue;+ var blob = dataUrlToBlob(entry.data_url);+ if (!blob) continue;+ files.push(new File([blob], entry.filename || 'clipboard-file', { type: entry.mime || blob.type || 'application/octet-stream' }));+ }+ if (files.length > 0) dispatchPasteWithFiles(target, files);+ return files.length;+ }+// 捕获阶段先于 dsh 应用自身监听:空剪贴板时接管并走原生读取。// 仅当本窗口是子 frame(dsh iframe)时才接管;顶层壳层文档里没有聊天框,// 且 `window.parent` 指向自身,postMessage 不会命中宿主(见 handleClipboardImage),@@ -143,8 +171,16 @@ pub(crate) const PASTE_SHIM_JS: &str = r#"(function () {if (!isPasteTarget(target)) return;event.preventDefault();- requestClipboardImage(target).then(function (dataUrl) {- if (dataUrl) dispatchImagePaste(target, dataUrl);+ // 先问文件:从文件管理器复制文件时剪贴板只有 uri-list(对 WebKit 表现为+ // 无图无文本),命中即贴文件(issue #1160);复制截图时文件列表为空,+ // 落回原有图片通路(issue #610),两条路互不干扰。+ request(REQ_FILES_TYPE).then(function (fileData) {+ var entries = (fileData && fileData.files) || [];+ if (entries.length > 0 && dispatchFilesPaste(target, entries) > 0) return;+ return request(REQ_TYPE).then(function (imageData) {+ var dataUrl = imageData && imageData.data_url;+ if (dataUrl) dispatchImagePaste(target, dataUrl);+ });});}, true);}diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.jsonindex 65bac584..d6058a69 100644--- a/src/i18n/locales/en-US.json+++ b/src/i18n/locales/en-US.json@@ -180,6 +180,7 @@"messages.clipboard_copied": "Copied to clipboard","messages.environment_copied": "Environment info copied to clipboard","messages.clipboard_failed": "Copy failed",+ "messages.clipboard_files_partial": "Could not paste {{total}} clipboard file(s): {{names}} (over 20MB or unreadable)","messages.copy_success": "URL copied to clipboard","messages.log_copied": "Logs copied to clipboard","messages.copy_failed": "Failed to copy URL",diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.jsonindex c3815c19..41eaa696 100644--- a/src/i18n/locales/zh-CN.json+++ b/src/i18n/locales/zh-CN.json@@ -180,6 +180,7 @@"messages.clipboard_copied": "已复制到剪贴板","messages.environment_copied": "环境信息已复制到剪贴板","messages.clipboard_failed": "复制失败",+ "messages.clipboard_files_partial": "{{total}} 个剪贴板文件未能粘贴:{{names}}(超过 20MB 或不可读)","messages.copy_success": "地址已复制到剪贴板","messages.log_copied": "日志已复制到剪贴板","messages.copy_failed": "复制地址失败",diff --git a/src/layout/components/iframe.tsx b/src/layout/components/iframe.tsxindex 92ee3fcb..ae692ab9 100644--- a/src/layout/components/iframe.tsx+++ b/src/layout/components/iframe.tsx@@ -39,9 +39,25 @@ const APPEARANCE_HANDSHAKE_TIMEOUT = 4000/** 可见性兜底轮询间隔:主路径是窗口 focus/resize 事件,5s 足以覆盖任务栏切换等场景 */+/**+ * `read_clipboard_files` 的返回载荷(与 Rust `ClipboardFileEntry` / `ClipboardFileRejection` 对齐)。+ * 前端只消费 `data_url / mime / filename` 重建 File,被拒条目用于降级提示(issue #1160)。+ */+interface ClipboardFileEntry {+ data_url: string+ mime: string+ filename: string+ size: number+}++interface ClipboardFileRejection {+ filename: string+ reason: string+}+/*** iframe → 宿主 的桥消息(宿主侧按 `type` 分发,不比对 `source`)。- * 只列 iframe 自身关心的桥:通知 / 插件异常 / 剪贴板图片 / 插件 boot / 帧内日志+ * 只列 iframe 自身关心的桥:通知 / 插件异常 / 剪贴板图片 / 剪贴板文件 / 插件 boot / 帧内日志* (导航桥的 `dsh://sidebar:collapsed` 由 `webview.tsx` 处理)。*/interface IframeBridgeMessage {@@ -405,6 +421,11 @@ export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: Ifrcase 'dsh://clipboard-image:read':handleClipboardImageRead(data)break+ // 剪贴板文件回退:读系统剪贴板文件列表并把附件 data URL 回传+ // (Linux/WebKitGTK 下 dsh iframe 的 paste 事件拿不到 text/uri-list 文件条目,issue #1160)+ case 'dsh://clipboard-files:read':+ handleClipboardFilesRead(data)+ break// 插件 boot 状态:failed 携带官方失败页文本(如 web boot: 1 entry did not activate)case 'dsh://plugin-boot:ready':store.harness.markIframeBootReady()@@ -546,6 +567,26 @@ export function Iframe({ iframeRef, srcOverride = null, borderTint = null }: Ifr})}+ function handleClipboardFilesRead(data: IframeBridgeMessage) {+ if (!data.id)+ return+ const reqId = data.id+ function reply(files: ClipboardFileEntry[], rejected: ClipboardFileRejection[]) {+ post({ type: 'dsh://clipboard-files:reply', id: reqId, files, rejected })+ // 宿主读取侧的降级(超限/不可读/目录)dsh 聊天框无从感知,由执行方提示(issue #1160)+ if (rejected.length > 0) {+ const names = rejected.slice(0, 3).map(entry => entry.filename).join(', ')+ toast(t('messages.clipboard_files_partial', { total: rejected.length, names }), { variant: 'warning' })+ }+ }+ void invoke<{ files?: ClipboardFileEntry[], rejected?: ClipboardFileRejection[] } | null>('read_clipboard_files')+ .then(result => reply(result?.files ?? [], result?.rejected ?? []))+ .catch((error) => {+ console.error('[clipboard-files] read_clipboard_files failed:', error)+ reply([], [])+ })+ }+function handleZoomShortcut(data: IframeBridgeMessage) {const action = zoomActionFromBridgeMessage(data)if (action)diff --git a/test/clipboard-files-bridge.test.ts b/test/clipboard-files-bridge.test.tsnew file mode 100644index 00000000..7bd9b0ff--- /dev/null+++ b/test/clipboard-files-bridge.test.ts@@ -0,0 +1,81 @@+// @vitest-environment node+import { describe, expect, it } from 'vitest'+import { readLocale, readSource } from './setup/read-source'++/**+ * 剪贴板文件回退桥的协议契约(issue #1160)。+ *+ * Linux/WebKitGTK 下 iframe 的 paste 事件拿不到 `text/uri-list` 文件条目,由注入脚本+ * (`src-tauri/src/desktop/paste.rs` 的 `PASTE_SHIM_JS`)向宿主请求原生读取,+ * 宿主(`src/layout/components/iframe.tsx` → `bridge::read_clipboard_files`)回包后+ * 重新合成一次带全部附件的 paste。+ *+ * 与图片桥(#610)同源:两端只按 `type` 字面量互相识别,任何一侧改名都会让贴图/贴文件+ * 静默失败。这些用例把 shim、宿主、命令注册与 Rust 实现的字面量锁在一起。+ */+const REQ_TYPE = 'dsh://clipboard-files:read'+const REPLY_TYPE = 'dsh://clipboard-files:reply'++describe('clipboard files bridge protocol', () => {+ const shim = readSource('src-tauri/src/desktop/paste.rs')+ const iframe = readSource('src/layout/components/iframe.tsx')+ const builder = readSource('src-tauri/src/desktop/builder.rs')+ const clipboard = readSource('src-tauri/src/bridge/clipboard.rs')++ it('shim and host negotiate the same request/reply types', () => {+ expect(shim).toContain(`var REQ_FILES_TYPE = '${REQ_TYPE}'`)+ expect(shim).toContain(`var RES_FILES_TYPE = '${REPLY_TYPE}'`)+ expect(iframe).toContain(`case '${REQ_TYPE}':`)+ expect(iframe).toContain(`type: '${REPLY_TYPE}'`)+ })++ it('identifies host replies by type only, for both image and files', () => {+ expect(shim).toContain('data.type !== RES_TYPE && data.type !== RES_FILES_TYPE')+ expect(shim).toContain('event.source !== window.parent')+ expect(iframe).not.toContain(`source: '${REPLY_TYPE}'`)+ })++ it('asks the host for files first, then falls back to the image read', () => {+ const filesFirst = shim.indexOf(`request(REQ_FILES_TYPE)`)+ const imageAfter = shim.indexOf(`request(REQ_TYPE)`)+ expect(filesFirst).toBeGreaterThan(-1)+ expect(imageAfter).toBeGreaterThan(filesFirst)+ })++ it('dispatches every accepted file in one synthetic paste', () => {+ // dsh 输入框按 `clipboardData.items` 采集附件:多文件必须进同一个 DataTransfer+ expect(shim).toContain('dt.items.add(files[i])')+ expect(shim).toContain('dispatchFilesPaste(target, entries)')+ })++ it('host replies with the files/rejected payload shape the shim reads', () => {+ expect(shim).toContain('fileData && fileData.files')+ expect(iframe).toContain('files, rejected')+ expect(clipboard).toContain('pub struct ClipboardFilesResponse')+ // Rust 序列化为 snake_case,两端字段名一致+ expect(clipboard).toContain('pub files: Vec<ClipboardFileEntry>')+ expect(clipboard).toContain('pub rejected: Vec<ClipboardFileRejection>')+ })++ it('command is implemented and registered', () => {+ expect(clipboard).toContain('pub async fn read_clipboard_files')+ // arboard 3.6.1 的公开读取 API(不存在 get_file_list/Unavailable,用错会编译失败)+ expect(clipboard).toContain('clipboard.get().file_list()')+ expect(clipboard).not.toContain('Error::Unavailable')+ expect(clipboard).toContain('arboard::Error::ClipboardNotSupported')+ expect(builder).toContain('crate::bridge::read_clipboard_files,')+ })++ it('rejection notice is localized in both locales', () => {+ for (const locale of ['zh-CN', 'en-US']) {+ const messages = readLocale(locale)+ expect(messages['messages.clipboard_files_partial']).toContain('{{total}}')+ expect(messages['messages.clipboard_files_partial']).toContain('{{names}}')+ }+ })++ it('keeps the image bridge untouched (regression guard for #610)', () => {+ expect(shim).toContain(`var RES_TYPE = 'dsh://clipboard-image:reply'`)+ expect(iframe).toContain('read_clipboard_image')+ })+})