Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

feat(clipboard): bridge native clipboard image paste for WebKitGTK

hairyfebd47f607c43
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 7f3b969a..a78bd83a 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -816,7 +816,9 @@ dependencies = [
name = "deepseek-harness-desktop"
version = "0.7.2"
dependencies = [
+ "arboard",
"async-trait",
+ "base64 0.22.1",
"flate2",
"futures-util",
"image",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 564cd2ec..a155ad26 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -32,6 +32,8 @@ tauri-plugin-store = "2"
tauri-plugin-clipboard-manager = "2"
tauri-plugin-notification = "2"
image = { version = "0.25", default-features = false, features = [ "png" ] }
+arboard = { version = "3", features = [ "wayland-data-control" ] }
+base64 = "0.22"
serde = { version = "1", features = [ "derive" ] }
serde_json = "1"
serde_yaml = "0.9"
diff --git a/src-tauri/src/bridge/clipboard.rs b/src-tauri/src/bridge/clipboard.rs
new file mode 100644
index 00000000..bdb64859
--- /dev/null
+++ b/src-tauri/src/bridge/clipboard.rs
@@ -0,0 +1,79 @@
+//! 原生剪贴板图片读取(Linux/WebKitGTK 贴图回退)。
+//!
+//! WebKitGTK 不通过 Web API(`ClipboardEvent.clipboardData.items/files`)暴露
+//! `image/*` 剪贴板条目,导致桌面端内嵌的 dsh iframe 中输入框「贴图」无效
+//! (浏览器里却正常)。本命令在 Rust 侧用 `arboard` 读取系统剪贴板图片、编码为
+//! PNG data URL 返回;注入到 iframe 的桥脚本(`desktop::paste::PASTE_SHIM_JS`)
+//! 拿到该 data URL 后重新派发 `paste` 事件,让 dsh 聊天框按正常贴图路径处理。
+
+use base64::{engine::general_purpose::STANDARD, Engine};
+
+/// 剪贴板图片读取结果:自包含的 PNG data URL(可直接作为 Blob/File 来源)。
+#[derive(serde::Serialize)]
+pub struct ClipboardImageResponse {
+ /// 形如 `data:image/png;base64,...`
+ pub data_url: String,
+ pub mime: String,
+ pub filename: String,
+}
+
+/// 从系统剪贴板读取图片并编码为 PNG data URL。
+///
+/// 剪贴板无图片时返回 `Ok(None)`;读取/编码失败返回 `Err`(前缀 `CLIPBOARD_IMAGE_`)。
+#[tauri::command]
+pub async fn read_clipboard_image(
+ _app: tauri::AppHandle,
+) -> Result<Option<ClipboardImageResponse>, String> {
+ // arboard 的 Clipboard::new()/get_image() 是阻塞调用(Linux 上需连接显示服务器),
+ // 放到 blocking 线程避免阻塞异步运行时与 UI。
+ let result =
+ tokio::task::spawn_blocking(move || -> Result<Option<ClipboardImageResponse>, String> {
+ // 超过约 50MP 的剪贴板图片(≈200MB RGBA)直接拒绝,避免撑爆内存
+ const MAX_PIXELS: u64 = 50_000_000;
+
+ let mut clipboard =
+ arboard::Clipboard::new().map_err(|e| format!("CLIPBOARD_IMAGE_ACCESS: {e}"))?;
+
+ let image_data = match clipboard.get_image() {
+ Ok(data) => data,
+ // 剪贴板里没有图片(普通文本/文件等),不是错误
+ Err(arboard::Error::ContentNotAvailable) => return Ok(None),
+ Err(e) => return Err(format!("CLIPBOARD_IMAGE_READ: {e}")),
+ };
+
+ if image_data.width == 0 || image_data.height == 0 {
+ return Ok(None);
+ }
+ let pixel_count = image_data.width as u64 * image_data.height as u64;
+ if pixel_count > MAX_PIXELS {
+ return Err(format!(
+ "CLIPBOARD_IMAGE_TOO_LARGE: {}x{} ({} px)",
+ image_data.width, image_data.height, pixel_count
+ ));
+ }
+
+ // arboard 返回 RGBA8 像素,直接包装为 RgbaImage 后用 image 编码成 PNG
+ let rgba = image::RgbaImage::from_raw(
+ image_data.width as u32,
+ image_data.height as u32,
+ image_data.bytes.into_owned(),
+ )
+ .ok_or_else(|| "CLIPBOARD_IMAGE_DECODE: invalid rgba buffer".to_string())?;
+
+ let mut cursor = std::io::Cursor::new(Vec::new());
+ image::DynamicImage::ImageRgba8(rgba)
+ .write_to(&mut cursor, image::ImageFormat::Png)
+ .map_err(|e| format!("CLIPBOARD_IMAGE_ENCODE: {e}"))?;
+
+ let b64 = STANDARD.encode(cursor.into_inner());
+ Ok(Some(ClipboardImageResponse {
+ data_url: format!("data:image/png;base64,{b64}"),
+ mime: "image/png".to_string(),
+ filename: "clipboard-image.png".to_string(),
+ }))
+ })
+ .await
+ .map_err(|e| format!("CLIPBOARD_IMAGE_TASK: {e}"))??;
+
+ Ok(result)
+}
diff --git a/src-tauri/src/bridge/mod.rs b/src-tauri/src/bridge/mod.rs
index 93bcedd2..5cf7a2bf 100644
--- a/src-tauri/src/bridge/mod.rs
+++ b/src-tauri/src/bridge/mod.rs
@@ -5,6 +5,7 @@
//! 以 `crate::bridge::<cmd>` 形式注册。
pub mod app_config;
+pub mod clipboard;
pub mod core;
pub mod lifecycle;
pub mod plugin;
@@ -13,6 +14,7 @@ pub mod system_os;
pub mod updater;
pub use app_config::*;
+pub use clipboard::*;
pub use core::*;
pub use lifecycle::*;
pub use plugin::*;
diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rs
index 540de996..cccf3abb 100644
--- a/src-tauri/src/desktop/builder.rs
+++ b/src-tauri/src/desktop/builder.rs
@@ -158,7 +158,8 @@ pub fn build_main_window(app: &tauri::AppHandle<Wry>) -> tauri::Result<tauri::We
let webview_builder = webview_builder
.initialization_script_for_all_frames(crate::desktop::notification::NOTIFICATION_SHIM_JS)
.initialization_script_for_all_frames(crate::desktop::nav::NAV_SHIM_JS)
- .initialization_script_for_all_frames(crate::desktop::style::IFRAME_STYLES_JS);
+ .initialization_script_for_all_frames(crate::desktop::style::IFRAME_STYLES_JS)
+ .initialization_script_for_all_frames(crate::desktop::paste::PASTE_SHIM_JS);
let webview_window = webview_builder.build()?;
@@ -239,6 +240,7 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {
crate::bridge::open_desktop_installer,
crate::bridge::get_desktop_about,
crate::bridge::open_external_url,
+ crate::bridge::read_clipboard_image,
crate::desktop::notification::show_native_notification,
crate::bridge::log_frontend,
]
diff --git a/src-tauri/src/desktop/mod.rs b/src-tauri/src/desktop/mod.rs
index 825532f6..2b99824f 100644
--- a/src-tauri/src/desktop/mod.rs
+++ b/src-tauri/src/desktop/mod.rs
@@ -1,6 +1,7 @@
pub mod builder;
pub mod nav;
pub mod notification;
+pub mod paste;
pub mod payload;
pub mod style;
pub mod window;
diff --git a/src-tauri/src/desktop/notification.rs b/src-tauri/src/desktop/notification.rs
index 1a48ca2d..dacda21e 100644
--- a/src-tauri/src/desktop/notification.rs
+++ b/src-tauri/src/desktop/notification.rs
@@ -271,11 +271,12 @@ pub fn enable_notification_permissions(
let _ = frame3.add_ContentLoading(
&FrameContentLoadingEventHandler::create(Box::new(move |_, _| {
- // 通知桥 + 导航桥 + 样式桥(壳层导航栏左侧控制需要 iframe 上下文执行)
+ // 通知桥 + 导航桥 + 样式桥 + 剪贴板图片桥(壳层导航栏左侧控制需要 iframe 上下文执行)
for script in [
crate::desktop::notification::NOTIFICATION_SHIM_JS,
crate::desktop::nav::NAV_SHIM_JS,
crate::desktop::style::IFRAME_STYLES_JS,
+ crate::desktop::paste::PASTE_SHIM_JS,
] {
let script = HSTRING::from(script);
let _ = frame_for_injection.ExecuteScript(
diff --git a/src-tauri/src/desktop/paste.rs b/src-tauri/src/desktop/paste.rs
new file mode 100644
index 00000000..fcbb2451
--- /dev/null
+++ b/src-tauri/src/desktop/paste.rs
@@ -0,0 +1,148 @@
+//! 剪贴板图片回退桥:让 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 聊天框按普通
+//! 贴图路径处理,从而与浏览器行为一致。
+//!
+//! 与 [`crate::desktop::notification::NOTIFICATION_SHIM_JS`] / [`crate::desktop::nav::NAV_SHIM_JS`]
+//! 走同一套注入通道(Windows 在 FrameCreated → ContentLoading 时 ExecuteScript,
+//! 其余平台 `initialization_script_for_all_frames`)。脚本带 `__dsh_clipboard_image_bridge__`
+//! 幂等守卫,重复注入安全;只处理「直接 iframe」发来的剪贴板请求,避免多层 iframe 误转发。
+
+pub(crate) const PASTE_SHIM_JS: &str = r#"(function () {
+ if (window.__dsh_clipboard_image_bridge__) return;
+ window.__dsh_clipboard_image_bridge__ = true;
+
+ // 请求方向:iframe → 宿主;响应方向:宿主 → iframe
+ var REQ_SRC = 'dsh-clipboard-image-bridge';
+ var RES_SRC = 'dsh-desktop-clipboard';
+ var REQ_TYPE = 'dsh://clipboard-image:read';
+
+ var reqSeq = 0;
+ var pending = {}; // id -> { resolve, target }
+
+ function requestClipboardImage(target) {
+ return new Promise(function (resolve) {
+ reqSeq += 1;
+ var id = 'req-' + reqSeq;
+ pending[id] = { resolve: resolve, target: target };
+ try {
+ window.parent.postMessage({ source: REQ_SRC, type: REQ_TYPE, id: id }, '*');
+ } catch (_) {
+ delete pending[id];
+ resolve(null);
+ }
+ });
+ }
+
+ // 宿主回包
+ window.addEventListener('message', function (event) {
+ var data = event.data;
+ if (!data || typeof data !== 'object' || data.source !== RES_SRC) return;
+ var item = pending[data.id];
+ if (!item) return;
+ delete pending[data.id];
+ item.resolve(data.data_url || null);
+ });
+
+ // 剪贴板事件里是否已带图片(非 WebKitGTK 场景):不介入,交 dsh 自身处理
+ function hasImageData(dt) {
+ if (!dt) return false;
+ try {
+ if (dt.items) {
+ for (var i = 0; i < dt.items.length; i++) {
+ var it = dt.items[i];
+ if (it && it.type && it.type.indexOf('image/') === 0) return true;
+ }
+ }
+ if (dt.files && dt.files.length > 0) return true;
+ var types = dt.types || [];
+ for (var j = 0; j < types.length; j++) {
+ if (types[j] === 'Files') return true;
+ }
+ } catch (_) {}
+ return false;
+ }
+
+ // 剪贴板事件里是否带文本/HTML(普通文本复制):不介入,让 dsh 正常粘贴文本
+ function hasTextData(dt) {
+ if (!dt) return false;
+ try {
+ if (dt.getData('text/plain')) return true;
+ if (dt.getData('text/html')) return true;
+ var types = dt.types || [];
+ return types.indexOf('text/plain') !== -1 || types.indexOf('text/html') !== -1;
+ } catch (_) {
+ return false;
+ }
+ }
+
+ function isPasteTarget(target) {
+ return !!(target && (target.isContentEditable || /^(textarea|INPUT)$/i.test(target.tagName)));
+ }
+
+ function dataUrlToBlob(dataUrl) {
+ var comma = dataUrl.indexOf(',');
+ if (comma === -1) return null;
+ var header = dataUrl.slice(0, comma);
+ var mime = (header.match(/:(.*?);/) || [])[1] || 'image/png';
+ var b64 = dataUrl.slice(comma + 1);
+ try {
+ var bin = atob(b64);
+ var bytes = new Uint8Array(bin.length);
+ for (var i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
+ return new Blob([bytes], { type: mime });
+ } catch (_) {
+ return null;
+ }
+ }
+
+ // 把图片作为 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' });
+ try {
+ var dt = new DataTransfer();
+ dt.items.add(file);
+ var ev;
+ try {
+ ev = new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true });
+ } catch (_) {
+ // 个别 WebKit 版本 ClipboardEvent 构造器不支持 clipboardData:用普通事件补属性
+ ev = new Event('paste', { bubbles: true, cancelable: true });
+ Object.defineProperty(ev, 'clipboardData', { value: dt });
+ }
+ if (target.isConnected) {
+ target.dispatchEvent(ev);
+ } else {
+ var active = document.activeElement;
+ if (active && isPasteTarget(active)) active.dispatchEvent(ev);
+ }
+ } catch (_) {}
+ }
+
+ // 捕获阶段先于 dsh 应用自身监听:空剪贴板时接管并走原生读取。
+ // 仅当本窗口是子 frame(dsh iframe)时才接管;顶层壳层文档里没有聊天框,
+ // 且 `window.parent` 指向自身,postMessage 不会命中宿主(见 handleClipboardImage),
+ // 这里直接把拦截限定在子 frame,避免对壳层输入产生任何干扰。
+ if (window !== window.parent) {
+ document.addEventListener('paste', function (event) {
+ var dt = event.clipboardData;
+ if (hasImageData(dt)) return;
+ if (hasTextData(dt)) return;
+
+ var target = document.activeElement || event.target;
+ if (!isPasteTarget(target)) return;
+
+ event.preventDefault();
+ requestClipboardImage(target).then(function (dataUrl) {
+ if (dataUrl) dispatchImagePaste(target, dataUrl);
+ });
+ }, true);
+ }
+})();"#;
diff --git a/src/hooks/use-iframe-shim.ts b/src/hooks/use-iframe-shim.ts
index 0c17449d..e59c2cfd 100644
--- a/src/hooks/use-iframe-shim.ts
+++ b/src/hooks/use-iframe-shim.ts
@@ -29,6 +29,17 @@ interface PluginErrorMessage {
action?: string
}
+/**
+ * iframe 剪贴板图片回退请求(desktop/paste::PASTE_SHIM_JS 发来)。
+ * Linux/WebKitGTK 下 dsh iframe 的 paste 事件拿不到图片,宿主侧据此调用
+ * `read_clipboard_image` 读系统剪贴板,再把 PNG data URL 回传给 iframe 重新贴图。
+ */
+interface ClipboardImageRequest {
+ source?: 'dsh-clipboard-image-bridge'
+ type?: 'dsh://clipboard-image:read'
+ id?: string
+}
+
export function useIframeShim(iframeRef: RefObject<HTMLIFrameElement | null>) {
const isMounted = useMountedState()
@@ -91,8 +102,44 @@ export function useIframeShim(iframeRef: RefObject<HTMLIFrameElement | null>) {
.catch(error => console.error('[plugin-error] report_plugin_error failed:', error))
}
+ // 接收 iframe 的「剪贴板图片回退」请求:读取系统剪贴板图片并把 PNG data URL 回传,
+ // 使 Linux/WebKitGTK 下 dsh iframe 的贴图(paste 事件拿不到图片)能走原生剪贴板通路。
+ function handleClipboardImage(event: MessageEvent<ClipboardImageRequest>) {
+ const data = event.data
+ if (!data || typeof data !== 'object' || data.source !== 'dsh-clipboard-image-bridge') {
+ return
+ }
+ // 只接受 DSH 直接 iframe 发来的消息;不兼容多层嵌套 iframe。
+ if (event.source !== iframeRef.current?.contentWindow) {
+ return
+ }
+ const iframeOrigin = getIframeOrigin(iframeRef)
+ if (!iframeOrigin || event.origin !== iframeOrigin) {
+ return
+ }
+ if (data.type !== 'dsh://clipboard-image:read' || !data.id) {
+ return
+ }
+ // 在闭包外把收窄后的值固定到局部常量,避免 TS 在闭包内丢失控制流收窄
+ const reqId = data.id
+ const origin = iframeOrigin
+ function reply(dataUrl: string | null) {
+ iframeRef.current?.contentWindow?.postMessage(
+ { source: 'dsh-desktop-clipboard', id: reqId, data_url: dataUrl },
+ origin,
+ )
+ }
+ void invoke<{ data_url?: string } | null>('read_clipboard_image')
+ .then(result => reply(result?.data_url ?? null))
+ .catch((error) => {
+ console.error('[clipboard-image] read_clipboard_image failed:', error)
+ reply(null)
+ })
+ }
+
useEvent('message', handleMessage)
useEvent('message', handlePluginError)
+ useEvent('message', handleClipboardImage)
// 系统通知点击 → 通知 iframe 聚焦对应会话
useEffect(() => {