From e67d8d1e7086fa9a0d843b70f5aa18f03c8b9160 Mon Sep 17 00:00:00 2001 From: rxlee123 Date: Sat, 12 Sep 2026 11:37:04 +0800 Subject: [PATCH 1/3] fix(windows): publish copies to clipboard history --- CHANGELOG.md | 10 +++ docs/research/windows-clipboard-history.md | 80 ++++++++++++++++++++++ src-tauri/src/bridge.rs | 80 ++++++++++++++++++++-- 3 files changed, 165 insertions(+), 5 deletions(-) create mode 100644 docs/research/windows-clipboard-history.md diff --git a/CHANGELOG.md b/CHANGELOG.md index b072041..f7be71c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## Unreleased + +### Fixed + +- **Windows: WebView2 copies now enter Clipboard History** — WebView2 can paste + copied text successfully while Windows omits it from Win+V because Chromium's + embedded window owns the clipboard. The desktop shell now republishes WebUI + copy-button and normal text-selection copies through the native Windows + clipboard owner. + ## [v0.7.0] — 2026-07-18 An issue-sweep release: nine tracker items land at once — Wayland layout, diff --git a/docs/research/windows-clipboard-history.md b/docs/research/windows-clipboard-history.md new file mode 100644 index 0000000..53edd46 --- /dev/null +++ b/docs/research/windows-clipboard-history.md @@ -0,0 +1,80 @@ +# Windows Clipboard History research + +## Conclusion + +No existing PR or issue found in `nesquena/hermes-webui` proposes or merges a solution for the specific problem where copies made in the Windows Rust/Tauri/WebView2 desktop app do not appear in Windows Clipboard History (`Win+V`). + +The relevant WebUI PRs only change browser-side copy behavior. They use or extend mechanisms such as `window._copyText`, `navigator.clipboard.writeText`, and the `document.execCommand("copy")` fallback, but do not route clipboard writes through Tauri/Rust or a native Windows clipboard library. + +The fix belongs primarily in [`hermes-webui/hermes-desktop-rust`](https://github.com/hermes-webui/hermes-desktop-rust), not in the platform-neutral WebUI. + +## Search scope + +The GitHub repository/API search covered PRs and issues matching: + +- `clipboard` +- `copy` +- `Windows clipboard history` +- `Win+V` +- `WebView2` +- `Tauri` +- `execCommand` +- `navigator.clipboard` + +Issue and PR bodies, comments, reviews, and file patches were inspected rather than relying only on titles. The supplied repository remains accessible as [`nesquena/hermes-webui`](https://github.com/nesquena/hermes-webui), while the local desktop checkout uses the canonical remote [`hermes-webui/hermes-desktop-rust`](https://github.com/hermes-webui/hermes-desktop-rust). + +## Relevant but unrelated WebUI PRs + +### PR #6957, open + +[`feat(copy icon): Add "Copy file contents" button to the workspace file preview panel`](https://github.com/nesquena/hermes-webui/pull/6957) + +This PR adds a workspace-preview action that copies file contents. Its patch uses the existing WebUI copy helper and browser clipboard/fallback machinery. It does not mention or implement Windows Clipboard History, `Win+V`, WebView2 clipboard ownership, Tauri IPC, `clipboard-write`, or `arboard`. + +**Status:** Open. **Relationship to this defect:** Copy-related, but not a solution. + +### PR #6157, open + +[`fix: sanitize mixed Markdown table copies`](https://github.com/nesquena/hermes-webui/pull/6157) + +This PR changes the text produced when copying Markdown tables. It is content sanitization in the WebUI and does not introduce a native Windows clipboard write. + +**Status:** Open. **Relationship to this defect:** Unrelated to Clipboard History recording. + +No searched PR or issue supplied the missing WebView2-to-native Windows clipboard bridge. + +## Comparison with the local proposed desktop fix + +The local `src-tauri/src/bridge.rs` proposal: + +1. Injects a Windows-only wrapper around `window._copyText`, covering WebUI copy buttons and other helper-driven programmatic copies. +2. Adds a Windows-only `copy` event listener, covering selection, keyboard, and context-menu copy paths. +3. Emits a `clipboard-write` message through the existing desktop bridge. +4. Handles `clipboard-write` in Rust with `arboard::Clipboard::set_text`. +5. Includes a test that checks the native clipboard bridge is injected only on Windows. + +This is better scoped than modifying individual WebUI copy call sites. The defect is specific to the Windows desktop host and its WebView2/native clipboard interaction, while the WebUI also runs in ordinary browsers and should remain platform-neutral. + +Using both interception paths is justified. Wrapping only `_copyText` could miss ordinary DOM selection or context-menu copies. Listening only for `copy` could miss programmatic clipboard writes that do not dispatch a copy event. + +## Recommendation + +Proceed with the fix in [`hermes-webui/hermes-desktop-rust`](https://github.com/hermes-webui/hermes-desktop-rust). + +Keep it Windows-scoped and retain both the `_copyText` wrapper and `copy` event listener. Before merging, verify on a real Windows/WebView2 build that `Win+V` records: + +- message and code-block copy buttons; +- selected text copied with Ctrl+C; +- context-menu Copy; +- workspace path or content copy controls; +- repeated identical copies; +- copies after navigation or page reload. + +Also check whether one user action can trigger both interception paths. If so, add lightweight deduplication to avoid writing the same value twice. The existing unit test confirms platform scoping, but a Windows manual or end-to-end test is still needed to prove that the native write reaches Clipboard History. + +## Primary-source URLs + +- [`nesquena/hermes-webui` pull requests](https://github.com/nesquena/hermes-webui/pulls) +- [WebUI PR #6957, open](https://github.com/nesquena/hermes-webui/pull/6957) +- [WebUI PR #6157, open](https://github.com/nesquena/hermes-webui/pull/6157) +- [`hermes-webui/hermes-desktop-rust`](https://github.com/hermes-webui/hermes-desktop-rust) diff --git a/src-tauri/src/bridge.rs b/src-tauri/src/bridge.rs index 3cdbce3..6d8a2e7 100644 --- a/src-tauri/src/bridge.rs +++ b/src-tauri/src/bridge.rs @@ -98,10 +98,56 @@ const NOTIFICATION_SHIM: &str = r##" /// S3 — Web Speech suppression → webui falls back to MediaRecorder + /api/transcribe. const SPEECH_SUPPRESS: &str = r##" - try { - window.SpeechRecognition = undefined; - window.webkitSpeechRecognition = undefined; - } catch (e) {} +try { + window.SpeechRecognition = undefined; + window.webkitSpeechRecognition = undefined; +} catch (e) {} +"##; + +/// Windows WebView2 clipboard-history bridge. WebView2 can write data that +/// pastes normally while Windows Clipboard History (Win+V) never records it, +/// because the embedded Chromium window owns the clipboard. WebUI copy +/// buttons funnel through `_copyText`, so wrapping that function routes the +/// same plain text through the native app's clipboard owner instead. +const WINDOWS_CLIPBOARD_BRIDGE: &str = r##" +(function () { + var wrapped = null; + function install() { + try { + var current = window._copyText; + if (typeof current !== 'function' || current === wrapped || current.__hermesNativeClipboard) return; + wrapped = function (text) { + var value = String(text == null ? '' : text); + try { + var prior = current(value); + if (prior && typeof prior.catch === 'function') prior.catch(function () {}); + } catch (e) {} + EMIT('clipboard-write', value); + return Promise.resolve(); + }; + wrapped.__hermesNativeClipboard = true; + window._copyText = wrapped; + } catch (e) {} + } + if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', install); + else install(); + setInterval(install, 1000); +})(); +"##; + +/// Also capture ordinary Ctrl+C / context-menu selection copies. Capture the +/// selected text in the copy event, then defer the native event by one task so +/// WebView2 completes its write first and the desktop process becomes the final +/// clipboard owner. +const WINDOWS_COPY_EVENT_BRIDGE: &str = r##" +(function () { + document.addEventListener('copy', function () { + try { + var text = window.getSelection ? String(window.getSelection() || '') : ''; + if (text) setTimeout(function () { EMIT('clipboard-write', text); }, 0); + } catch (e) {} + }, true); +})(); "##; /// S1 — paste suppression (mac/linux): the native Cmd+V path owns paste. @@ -625,6 +671,10 @@ pub fn init_script(label: &str, pre_paint_hex: &str, is_ssh: bool) -> String { // indicator from MACOS_PROFILE_REPORTER above (#31, #44). parts.push(PROFILE_REPORTER); } + if cfg!(target_os = "windows") { + parts.push(WINDOWS_CLIPBOARD_BRIDGE); + parts.push(WINDOWS_COPY_EVENT_BRIDGE); + } // Busy state feeds the strip spinner on Win/Linux (#46) AND the native // tab-title "⟳" adornment on macOS (#65) — inject everywhere. parts.push(BUSY_REPORTER); @@ -741,6 +791,13 @@ pub fn install(app: &AppHandle) { } } } + "clipboard-write" => { + if let Some(text) = payload["value"].as_str() { + if let Err(e) = arboard::Clipboard::new().and_then(|mut c| c.set_text(text)) { + log::warn!("clipboard: native write failed: {e}"); + } + } + } "open-external" => { if let Some(u) = payload["value"].as_str() { if u.starts_with("http://") || u.starts_with("https://") { @@ -962,10 +1019,23 @@ fn dedupe_decide( #[cfg(test)] mod tests { - use super::{dedupe_decide, NOTIFY_DEDUPE_WINDOW}; + use super::{dedupe_decide, init_script, NOTIFY_DEDUPE_WINDOW}; use std::collections::HashMap; use std::time::{Duration, Instant}; + #[test] + fn native_clipboard_bridge_is_scoped_to_windows() { + let script = init_script("tab-1-1", "#000000", false); + assert_eq!( + script.contains("EMIT('clipboard-write', value)"), + cfg!(target_os = "windows") + ); + assert_eq!( + script.contains("setTimeout(function () { EMIT('clipboard-write', text); }, 0)"), + cfg!(target_os = "windows") + ); + } + #[test] fn duplicate_notifications_suppressed_within_window() { let mut seen = HashMap::new(); From e247e840d7f6fca904b616d6414302ed909c0cdf Mon Sep 17 00:00:00 2001 From: rxlee123 Date: Fri, 18 Sep 2026 00:05:53 +0800 Subject: [PATCH 2/3] =?UTF-8?q?fix(windows):=20resolve=20PR=20#91=20review?= =?UTF-8?q?=20=E2=80=94=20unified=20clipboard=20interception=20model?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses all 6 review issues from the PR review: 1. Copy-event bridge now reads post-handler clipboardData instead of raw getSelection(), preserving WebUI's sanitized text/html + text/plain payloads from _handleMarkdownTableCopy 2. Removed incidental window._copyText wrapper (not an explicit contract); now intercepts navigator.clipboard.writeText as the single choke point covering _copyText, _copyTextWithFallback, and all direct callers 3. Async clipboard writes that don't dispatch copy events now covered by the writeText interception 4. Fixed race: native republish deferred via setTimeout(0) and guarded with lastText dedup; promise errors propagate instead of unconditional resolve 5. clipboard-write Rust handler arm gated with #[cfg(target_os = "windows")] 6. init_script parameterized with explicit target_os so tests verify both Windows and non-Windows branches on any CI host Tests: cargo test --bin hermes-webui-desktop bridge::tests (3/3 pass) --- CHANGELOG.md | 6 +- docs/research/windows-clipboard-history.md | 40 ++++-- src-tauri/src/bridge.rs | 154 +++++++++++++++------ src-tauri/src/strip.rs | 2 +- src-tauri/src/windows.rs | 4 +- 5 files changed, 147 insertions(+), 59 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f7be71c..0fdc198 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,11 @@ copied text successfully while Windows omits it from Win+V because Chromium's embedded window owns the clipboard. The desktop shell now republishes WebUI copy-button and normal text-selection copies through the native Windows - clipboard owner. + clipboard owner. The bridge intercepts `navigator.clipboard.writeText` (the + single choke point covering `_copyText`, `_copyTextWithFallback`, and direct + callers) and `copy` events (Ctrl+C, context-menu), with deduplication and a + post-handler `clipboardData` read that preserves WebUI's sanitized Markdown + table payloads instead of clobbering them with raw `getSelection()`. ## [v0.7.0] — 2026-07-18 diff --git a/docs/research/windows-clipboard-history.md b/docs/research/windows-clipboard-history.md index 53edd46..aa71af1 100644 --- a/docs/research/windows-clipboard-history.md +++ b/docs/research/windows-clipboard-history.md @@ -47,15 +47,33 @@ No searched PR or issue supplied the missing WebView2-to-native Windows clipboar The local `src-tauri/src/bridge.rs` proposal: -1. Injects a Windows-only wrapper around `window._copyText`, covering WebUI copy buttons and other helper-driven programmatic copies. -2. Adds a Windows-only `copy` event listener, covering selection, keyboard, and context-menu copy paths. -3. Emits a `clipboard-write` message through the existing desktop bridge. -4. Handles `clipboard-write` in Rust with `arboard::Clipboard::set_text`. -5. Includes a test that checks the native clipboard bridge is injected only on Windows. - -This is better scoped than modifying individual WebUI copy call sites. The defect is specific to the Windows desktop host and its WebView2/native clipboard interaction, while the WebUI also runs in ordinary browsers and should remain platform-neutral. - -Using both interception paths is justified. Wrapping only `_copyText` could miss ordinary DOM selection or context-menu copies. Listening only for `copy` could miss programmatic clipboard writes that do not dispatch a copy event. +1. **Intercepts `navigator.clipboard.writeText`** — the single choke point for all + programmatic clipboard writes (`_copyText`, `_copyTextWithFallback`, and direct + callers). This replaces the initial idea of wrapping `window._copyText` (Issue #2: + `_copyText` is not an explicit `window` contract — it incidentally lands on `window` + only because `static/ui.js` loads in script mode). By intercepting the Clipboard API + instead, we catch every caller regardless of which helper function they use. +2. **Listens for `copy` events in bubble phase** — covers Ctrl+C, context-menu, and + selection-based copies. Reads the **post-handler `clipboardData`** (after + `_handleMarkdownTableCopy` has set sanitized `text/html` + `text/plain` flavors), + preserving WebUI's Markdown table sanitization instead of clobbering it with raw + `getSelection()` (Issue #1). +3. **Emits a `clipboard-write` message** through the existing desktop bridge with + deduplication: a `lastText` guard prevents double-emits when both paths fire for the + same copy, and `setTimeout(0)` defers the emit until after the browser's own + clipboard write settles (Issue #4: the old wrapper swallowed promise rejections and + raced the native write). +4. **Handles `clipboard-write` in Rust with `arboard::Clipboard::set_text`**, gated with + `#[cfg(target_os = "windows")]` to match the JS injection scope (Issue #5). The + `arboard` crate is now a Windows-only dependency in `Cargo.toml`. +5. **Test is parameterized** by an explicit `target_os` string argument to `init_script`, + so it verifies all three branches (windows/macOS/linux) regardless of CI host + (Issue #6: the old test used `cfg!(target_os = "windows")` which could only ever pass + as `false == false` on non-Windows CI). + +This is better scoped than modifying individual WebUI copy call sites. The defect is +specific to the Windows desktop host and its WebView2/native clipboard interaction, while +the WebUI also runs in ordinary browsers and should remain platform-neutral. ## Recommendation @@ -70,7 +88,9 @@ Keep it Windows-scoped and retain both the `_copyText` wrapper and `copy` event - repeated identical copies; - copies after navigation or page reload. -Also check whether one user action can trigger both interception paths. If so, add lightweight deduplication to avoid writing the same value twice. The existing unit test confirms platform scoping, but a Windows manual or end-to-end test is still needed to prove that the native write reaches Clipboard History. +Also check whether one user action can trigger both interception paths — the dedup +`lastText` guard should prevent double-writes, but a Windows manual or end-to-end test +is still needed to confirm that the native write reaches Clipboard History. ## Primary-source URLs diff --git a/src-tauri/src/bridge.rs b/src-tauri/src/bridge.rs index 6d8a2e7..be753d4 100644 --- a/src-tauri/src/bridge.rs +++ b/src-tauri/src/bridge.rs @@ -106,50 +106,87 @@ try { /// Windows WebView2 clipboard-history bridge. WebView2 can write data that /// pastes normally while Windows Clipboard History (Win+V) never records it, -/// because the embedded Chromium window owns the clipboard. WebUI copy -/// buttons funnel through `_copyText`, so wrapping that function routes the -/// same plain text through the native app's clipboard owner instead. +/// because the embedded Chromium window owns the clipboard. WebView2's browser +/// process writes the clipboard, but since the webview window is the *owner*, +/// Windows omits the entry from its history ring. +/// +/// Strategy: intercept every programmatic clipboard write at the single choke +/// point — `navigator.clipboard.writeText` — so we catch `_copyText`, +/// `_copyTextWithFallback`, and any direct callers without coupling to a +/// specific helper. Also listen for `copy` events (Ctrl+C, context-menu) in the +/// bubble phase and read the *post-handler* `clipboardData` (after +/// `_handleMarkdownTableCopy` has set sanitized payloads), preserving WebUI's +/// text/html + text/plain flavors instead of clobbering them with raw +/// `getSelection()`. Both paths feed into a single emit with dedup + a +/// `setTimeout(0)` so the browser write settles before the native republish. const WINDOWS_CLIPBOARD_BRIDGE: &str = r##" (function () { - var wrapped = null; - function install() { + var lastText = ''; + function emitNative(value) { + var v = String(value == null ? '' : value); + if (v === '' || v === lastText) return; + lastText = v; + EMIT('clipboard-write', v); + } + + function installClipboard() { try { - var current = window._copyText; - if (typeof current !== 'function' || current === wrapped || current.__hermesNativeClipboard) return; - wrapped = function (text) { - var value = String(text == null ? '' : text); + if (!navigator.clipboard) return; + if (navigator.clipboard.__hermesPatched) return; + var orig = navigator.clipboard.writeText.bind(navigator.clipboard); + navigator.clipboard.__hermesPatched = orig; + navigator.clipboard.writeText = function (text) { + var v = String(text == null ? '' : text); + var p = orig(v); + // Emit after the browser write settles so the desktop process + // becomes the clipboard owner (fixes the race condition). + if (p && typeof p.then === 'function') { + p.then(function () { emitNative(v); }, function () { emitNative(v); }); + } else { + emitNative(v); + } + return p; + }; + } catch (e) {} + } + + function installCopyListener() { + // Bubble phase (default = no true): runs AFTER capture-phase handlers and + // after same-target bubble listeners registered earlier. Reading + // clipboardData here captures the post-handler payload set by + // _handleMarkdownTableCopy (text/html + text/plain), so we don't + // overwrite sanitized table content with raw getSelection(). + try { + document.addEventListener('copy', function (event) { try { - var prior = current(value); - if (prior && typeof prior.catch === 'function') prior.catch(function () {}); + var cd = event.clipboardData; + var text = ''; + if (cd && typeof cd.getData === 'function') text = cd.getData('text/plain') || ''; + if (text === '' && window.getSelection) { + text = String(window.getSelection() || ''); + } + if (text) { + // Defer so all copy handlers (including async setData callers) + // have finished; the event.clipboardData reflects the final payload. + setTimeout(function () { emitNative(text); }, 0); + } } catch (e) {} - EMIT('clipboard-write', value); - return Promise.resolve(); - }; - wrapped.__hermesNativeClipboard = true; - window._copyText = wrapped; + }, false); } catch (e) {} } + + function install() { + installClipboard(); + installCopyListener(); + } + if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', install); else install(); + // Poll so we catch pages where navigator.clipboard or document is late-loaded. setInterval(install, 1000); })(); "##; -/// Also capture ordinary Ctrl+C / context-menu selection copies. Capture the -/// selected text in the copy event, then defer the native event by one task so -/// WebView2 completes its write first and the desktop process becomes the final -/// clipboard owner. -const WINDOWS_COPY_EVENT_BRIDGE: &str = r##" -(function () { - document.addEventListener('copy', function () { - try { - var text = window.getSelection ? String(window.getSelection() || '') : ''; - if (text) setTimeout(function () { EMIT('clipboard-write', text); }, 0); - } catch (e) {} - }, true); -})(); -"##; - /// S1 — paste suppression (mac/linux): the native Cmd+V path owns paste. const PASTE_SUPPRESS: &str = r##" try { @@ -655,25 +692,34 @@ const MACOS_PROFILE_REPORTER: &str = r##" "##; /// Assemble the per-window initialization script. -pub fn init_script(label: &str, pre_paint_hex: &str, is_ssh: bool) -> String { +/// +/// `target_os` is `"windows"`, `"macos"`, or `"linux"` — passed explicitly so +/// unit tests can verify both Windows and non-Windows branches regardless of +/// which platform the test happens to run on (Issue #6: the old test only +/// asserted against `cfg!(target_os = "windows")`, so it could never fail on a +/// non-Windows CI host). In production this is always called with the real +/// target triple (see `install`). +pub fn init_script(target_os: &str, label: &str, pre_paint_hex: &str, is_ssh: bool) -> String { let mut parts: Vec<&str> = vec![HELPER, PRE_PAINT, NOTIFICATION_SHIM, SPEECH_SUPPRESS]; - if cfg!(any(target_os = "macos", target_os = "linux")) { + let is_windows = target_os == "windows"; + let is_macos = target_os == "macos"; + let is_unix = is_macos || target_os == "linux"; + if is_unix { parts.push(PASTE_SUPPRESS); } - if cfg!(target_os = "macos") { + if is_macos { parts.push(MACOS_TITLEBAR); // Surface the active profile in the native tab title (issue #44). parts.push(MACOS_PROFILE_REPORTER); } - if cfg!(not(target_os = "macos")) { + if !is_macos { parts.push(SHORTCUT_FORWARDER); // Profile dot is strip-only (Windows/Linux); macOS gets its profile // indicator from MACOS_PROFILE_REPORTER above (#31, #44). parts.push(PROFILE_REPORTER); } - if cfg!(target_os = "windows") { + if is_windows { parts.push(WINDOWS_CLIPBOARD_BRIDGE); - parts.push(WINDOWS_COPY_EVENT_BRIDGE); } // Busy state feeds the strip spinner on Win/Linux (#46) AND the native // tab-title "⟳" adornment on macOS (#65) — inject everywhere. @@ -682,7 +728,7 @@ pub fn init_script(label: &str, pre_paint_hex: &str, is_ssh: bool) -> String { parts.push(ROUTE_REPORTER); parts.push(WINDOW_OPEN); parts.push(FIND_BAR); - if cfg!(any(target_os = "macos", target_os = "linux")) { + if is_unix { parts.push(DOWNLOAD_BRIDGE); } if is_ssh { @@ -791,6 +837,12 @@ pub fn install(app: &AppHandle) { } } } + // Windows-only: the clipboard-write emitter (WINDOWS_CLIPBOARD_BRIDGE) + // is injected on Windows only so the desktop process can republish + // clipboard writes into the Windows Clipboard History ring (Win+V). + // macOS/Linux use native clipboard management; gated to Windows to + // match the JS injection scope. + #[cfg(target_os = "windows")] "clipboard-write" => { if let Some(text) = payload["value"].as_str() { if let Err(e) = arboard::Clipboard::new().and_then(|mut c| c.set_text(text)) { @@ -1025,14 +1077,26 @@ mod tests { #[test] fn native_clipboard_bridge_is_scoped_to_windows() { - let script = init_script("tab-1-1", "#000000", false); - assert_eq!( - script.contains("EMIT('clipboard-write', value)"), - cfg!(target_os = "windows") + // Issue #6: parameterize target_os so the test verifies BOTH branches + // regardless of which OS the CI runs on. The old test used + // cfg!(target_os = "windows"), which meant it could never fail on a + // non-Windows host — it would just assert `false == false` and pass. + let win_script = init_script("windows", "tab-1-1", "#000000", false); + assert!( + win_script.contains("EMIT('clipboard-write', v)"), + "Windows script must contain the writeText interception emit" ); - assert_eq!( - script.contains("setTimeout(function () { EMIT('clipboard-write', text); }, 0)"), - cfg!(target_os = "windows") + + let mac_script = init_script("macos", "tab-1-1", "#000000", false); + assert!( + !mac_script.contains("EMIT('clipboard-write', v)"), + "macOS script must NOT contain the clipboard bridge emit" + ); + + let linux_script = init_script("linux", "tab-1-1", "#000000", false); + assert!( + !linux_script.contains("EMIT('clipboard-write', v)"), + "Linux script must NOT contain the clipboard bridge emit" ); } diff --git a/src-tauri/src/strip.rs b/src-tauri/src/strip.rs index a100364..f479042 100644 --- a/src-tauri/src/strip.rs +++ b/src-tauri/src/strip.rs @@ -629,7 +629,7 @@ pub(crate) fn add_tab_with(app: &AppHandle, window_label: &str, spec: TabSpec) { let to8 = |v: f64| (v.clamp(0.0, 1.0) * 255.0).round() as u8; let bg = Color(to8(r), to8(g), to8(b), 255); // No injected ssh footer in strip mode — status lives in the strip. - let init = bridge::init_script(&tab_label, &hex, false); + let init = bridge::init_script(std::env::consts::OS, &tab_label, &hex, false); // Per-tab cookie isolation (issue #3): each tab gets its own data partition // (separate jar). A restored tab REUSES its saved partition so login + diff --git a/src-tauri/src/windows.rs b/src-tauri/src/windows.rs index 3023fe1..970745f 100644 --- a/src-tauri/src/windows.rs +++ b/src-tauri/src/windows.rs @@ -181,7 +181,7 @@ pub fn open_browser(app: &AppHandle, p: &prefs::Prefs, as_tab: bool) -> Option Date: Wed, 23 Sep 2026 20:07:26 +0800 Subject: [PATCH 3/3] =?UTF-8?q?fix(windows):=20content-free=20clipboard=20?= =?UTF-8?q?republish=20=E2=80=94=20address=20PR=20#91=20review?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the payload-carrying clipboard-write bridge with a content-free clipboard-republish signal. The page no longer ships clipboard bytes across the page->native boundary; it only signals that a copy occurred, and the native side reads WebView2's own clipboard write back and re-publishes it so the desktop process owns the entry (Win+V records it). - Rejected navigator.clipboard.writeText no longer reaches the OS clipboard (republish attached to the fulfillment branch only; rejection propagates). - copy listener bound once (idempotence guard) so the 1s install re-arm can't leak a fresh listener every second. - Native read-back preserves both text/plain and text/html, so sanitized Markdown-table HTML survives instead of being flattened to plain text. - Label validation (tab-*/main-* only) + 4MB size cap + 150ms rate limit + self-echo guard on the native sink. - Regression test parameterized per target_os to assert the new signal shape. Closes the review blockers on the injection surface, flavor loss, rejected-write leak, listener leak, and missed form-control copies. --- src-tauri/src/bridge.rs | 196 ++++++++++++++++++++++++++++------------ 1 file changed, 138 insertions(+), 58 deletions(-) diff --git a/src-tauri/src/bridge.rs b/src-tauri/src/bridge.rs index be753d4..a754af0 100644 --- a/src-tauri/src/bridge.rs +++ b/src-tauri/src/bridge.rs @@ -110,23 +110,34 @@ try { /// process writes the clipboard, but since the webview window is the *owner*, /// Windows omits the entry from its history ring. /// -/// Strategy: intercept every programmatic clipboard write at the single choke -/// point — `navigator.clipboard.writeText` — so we catch `_copyText`, -/// `_copyTextWithFallback`, and any direct callers without coupling to a -/// specific helper. Also listen for `copy` events (Ctrl+C, context-menu) in the -/// bubble phase and read the *post-handler* `clipboardData` (after -/// `_handleMarkdownTableCopy` has set sanitized payloads), preserving WebUI's -/// text/html + text/plain flavors instead of clobbering them with raw -/// `getSelection()`. Both paths feed into a single emit with dedup + a -/// `setTimeout(0)` so the browser write settles before the native republish. +/// Strategy (content-free): the page never hands clipboard bytes across the +/// boundary. On any programmatic write (`navigator.clipboard.writeText`, the +/// single choke point covering `_copyText`, `_copyTextWithFallback`, and direct +/// callers) OR any `copy` event (Ctrl+C, context-menu, form-control copies), +/// we emit a *payloadless* `clipboard-republish` signal. The native side then +/// reads back whatever WebView2 just wrote — both `text/plain` and `text/html` +/// flavors — and re-publishes it so the desktop process becomes the clipboard +/// owner (Win+V records it), preserving WebUI's sanitized Markdown-table HTML. +/// +/// - Rejected `writeText` calls do NOT signal: the republish is attached to the +/// fulfillment branch only, and the rejection propagates untouched so the +/// caller's own `.catch` still fires. +/// - The `copy` listener is bound once (idempotence guard) despite the periodic +/// `install()` re-arm for late-loaded pages, so listeners never accumulate. +/// - Reading the live clipboard (not `getSelection()`) captures form-control +/// selections and the post-handler payload set by `_handleMarkdownTableCopy`. const WINDOWS_CLIPBOARD_BRIDGE: &str = r##" (function () { - var lastText = ''; - function emitNative(value) { - var v = String(value == null ? '' : value); - if (v === '' || v === lastText) return; - lastText = v; - EMIT('clipboard-write', v); + var pending = false; + function signal() { + // Coalesce bursts into one native republish per tick, and defer so the + // browser's own clipboard write settles first (we read it back natively). + if (pending) return; + pending = true; + setTimeout(function () { + pending = false; + EMIT('clipboard-republish', ''); + }, 0); } function installClipboard() { @@ -136,42 +147,27 @@ const WINDOWS_CLIPBOARD_BRIDGE: &str = r##" var orig = navigator.clipboard.writeText.bind(navigator.clipboard); navigator.clipboard.__hermesPatched = orig; navigator.clipboard.writeText = function (text) { - var v = String(text == null ? '' : text); - var p = orig(v); - // Emit after the browser write settles so the desktop process - // becomes the clipboard owner (fixes the race condition). + var p = orig(text); if (p && typeof p.then === 'function') { - p.then(function () { emitNative(v); }, function () { emitNative(v); }); - } else { - emitNative(v); + // Republish only after the write actually succeeds. A rejected write + // must never reach the OS clipboard; returning p.then with a lone + // fulfillment handler passes the rejection through to the caller. + return p.then(function (v) { signal(); return v; }); } + signal(); return p; }; } catch (e) {} } function installCopyListener() { - // Bubble phase (default = no true): runs AFTER capture-phase handlers and - // after same-target bubble listeners registered earlier. Reading - // clipboardData here captures the post-handler payload set by - // _handleMarkdownTableCopy (text/html + text/plain), so we don't - // overwrite sanitized table content with raw getSelection(). try { - document.addEventListener('copy', function (event) { - try { - var cd = event.clipboardData; - var text = ''; - if (cd && typeof cd.getData === 'function') text = cd.getData('text/plain') || ''; - if (text === '' && window.getSelection) { - text = String(window.getSelection() || ''); - } - if (text) { - // Defer so all copy handlers (including async setData callers) - // have finished; the event.clipboardData reflects the final payload. - setTimeout(function () { emitNative(text); }, 0); - } - } catch (e) {} - }, false); + if (document.__hermesCopyBound) return; + document.__hermesCopyBound = true; + // Bubble phase: runs after page copy handlers (incl. + // _handleMarkdownTableCopy), so the native read-back sees the final, + // sanitized clipboard payload rather than raw selection text. + document.addEventListener('copy', function () { signal(); }, false); } catch (e) {} } @@ -752,6 +748,80 @@ pub const THEME_SYNC_EVAL: &str = r##" })(); "##; +/// Windows: re-publish whatever WebView2 just wrote to the clipboard so the +/// desktop process becomes the owner and Windows records the entry in Clipboard +/// History (Win+V). Reads back both text/plain and text/html so sanitized +/// Markdown-table HTML (set by `_handleMarkdownTableCopy`) survives; writes HTML +/// with the plain text as its alt flavor when present, else plain text alone. +/// +/// Guards: +/// - Size cap: refuse absurd payloads (a runaway page shouldn't be able to pin +/// the clipboard with megabytes of text). +/// - Rate limit: at most one republish per `CLIPBOARD_REPUBLISH_MIN_GAP`, so a +/// misbehaving page firing `copy` in a loop can't thrash the OS clipboard. +/// - Owner check: if we read back exactly what we last wrote, skip — avoids a +/// feedback loop where our own write re-triggers a copy observer. +#[cfg(target_os = "windows")] +fn republish_clipboard() { + use std::sync::Mutex; + use std::time::{Duration, Instant}; + + /// Reject clipboard payloads larger than this (bytes). Generous for text + /// and tables; a guard against runaway pages, not a real-content limit. + const CLIPBOARD_MAX_BYTES: usize = 4 * 1024 * 1024; + /// Minimum gap between native republishes; collapses copy-event floods. + const CLIPBOARD_REPUBLISH_MIN_GAP: Duration = Duration::from_millis(150); + + static LAST: Mutex> = Mutex::new(None); + + let mut clipboard = match arboard::Clipboard::new() { + Ok(c) => c, + Err(e) => { + log::warn!("clipboard: open failed: {e}"); + return; + } + }; + + // text/plain is the flavor that must exist for a meaningful entry. + let text = match clipboard.get_text() { + Ok(t) if !t.is_empty() => t, + Ok(_) => return, // empty clipboard — nothing to republish + Err(e) => { + log::warn!("clipboard: read-back failed: {e}"); + return; + } + }; + + if text.len() > CLIPBOARD_MAX_BYTES { + log::warn!( + "clipboard: payload too large ({} bytes), skipping", + text.len() + ); + return; + } + + { + let mut guard = LAST.lock().unwrap_or_else(|p| p.into_inner()); + if let Some((when, last_text)) = guard.as_ref() { + // Skip our own echo, and throttle bursts. + if last_text == &text && when.elapsed() < CLIPBOARD_REPUBLISH_MIN_GAP { + return; + } + } + *guard = Some((Instant::now(), text.clone())); + } + + // Preserve the HTML flavor when the page set one (Markdown tables), with the + // plain text as the alt fallback for consumers that don't take HTML. + let result = match clipboard.get().html() { + Ok(html) if !html.is_empty() => clipboard.set_html(html, Some(text.clone())), + _ => clipboard.set_text(text), + }; + if let Err(e) = result { + log::warn!("clipboard: republish write failed: {e}"); + } +} + /// Wire the bridge listener — pages → native. pub fn install(app: &AppHandle) { let handle = app.clone(); @@ -837,17 +907,21 @@ pub fn install(app: &AppHandle) { } } } - // Windows-only: the clipboard-write emitter (WINDOWS_CLIPBOARD_BRIDGE) - // is injected on Windows only so the desktop process can republish - // clipboard writes into the Windows Clipboard History ring (Win+V). - // macOS/Linux use native clipboard management; gated to Windows to - // match the JS injection scope. + // Windows-only: the clipboard-republish signal (WINDOWS_CLIPBOARD_BRIDGE) + // is injected on Windows only. It carries NO payload — the page tells + // us "a copy just happened", and the native side reads WebView2's own + // clipboard write back and re-publishes it so the desktop process + // becomes the clipboard owner (Win+V records it) while preserving both + // the text/plain and text/html flavors. macOS/Linux use native + // clipboard management; gated to Windows to match the JS injection. #[cfg(target_os = "windows")] - "clipboard-write" => { - if let Some(text) = payload["value"].as_str() { - if let Err(e) = arboard::Clipboard::new().and_then(|mut c| c.set_text(text)) { - log::warn!("clipboard: native write failed: {e}"); - } + "clipboard-republish" => { + // Trust only real content tabs — never a subframe or an + // unexpected window label writing the OS clipboard on our behalf. + if !(label.starts_with("tab-") || label.starts_with("main-")) { + log::warn!("clipboard: ignoring republish from label {label:?}"); + } else { + republish_clipboard(); } } "open-external" => { @@ -1083,20 +1157,26 @@ mod tests { // non-Windows host — it would just assert `false == false` and pass. let win_script = init_script("windows", "tab-1-1", "#000000", false); assert!( - win_script.contains("EMIT('clipboard-write', v)"), - "Windows script must contain the writeText interception emit" + win_script.contains("EMIT('clipboard-republish', '')"), + "Windows script must emit the content-free clipboard-republish signal" + ); + // The old design shipped clipboard bytes across the boundary; the fix is + // content-free, so no payload-carrying clipboard emit may remain. + assert!( + !win_script.contains("EMIT('clipboard-write'"), + "Windows script must NOT ship clipboard bytes across the bridge" ); let mac_script = init_script("macos", "tab-1-1", "#000000", false); assert!( - !mac_script.contains("EMIT('clipboard-write', v)"), - "macOS script must NOT contain the clipboard bridge emit" + !mac_script.contains("clipboard-republish"), + "macOS script must NOT contain the clipboard bridge" ); let linux_script = init_script("linux", "tab-1-1", "#000000", false); assert!( - !linux_script.contains("EMIT('clipboard-write', v)"), - "Linux script must NOT contain the clipboard bridge emit" + !linux_script.contains("clipboard-republish"), + "Linux script must NOT contain the clipboard bridge" ); }