Skip to content

fix(windows): publish WebView2 copies to Clipboard History - #91

Open
rxlee123 wants to merge 4 commits into
hermes-webui:mainfrom
rxlee123:fix/windows-clipboard-history
Open

rxlee123 wants to merge 4 commits into
hermes-webui:mainfrom
rxlee123:fix/windows-clipboard-history

Conversation

@rxlee123

Copy link
Copy Markdown

Summary

  • republish WebUI copy-button text through the native Windows clipboard owner
  • capture ordinary selection copies from Ctrl+C and the context menu
  • keep the bridge Windows-only so macOS and Linux behavior is unchanged
  • document the investigation and add a platform-scoping regression test

Closes #90

Validation

  • cargo test native_clipboard_bridge_is_scoped_to_windows --manifest-path src-tauri/Cargo.toml
    • 1 passed, 24 filtered out
  • cargo fmt --manifest-path src-tauri/Cargo.toml -- --check
    • passed
  • cargo check --manifest-path src-tauri/Cargo.toml
    • passed with 6 existing dead-code warnings
  • git diff --check
    • passed
  • reviewed the change for unintended files and secrets
    • no secret-like content found

Risk and scope

The injected bridge is compiled into initialization scripts only on Windows. Existing WebUI clipboard behavior remains responsible for the browser copy, while the desktop process performs the final native plain-text write.

Not verified

A real Windows/WebView2 build is still required to verify that Win+V records:

  • message and code-block copy buttons
  • selected text copied with Ctrl+C
  • context-menu Copy
  • workspace path or content copies
  • repeated identical copies
  • copies after navigation or reload

The native behavior was previously exercised manually, but this PR does not include an automated Windows Clipboard History assertion because Win+V behavior is OS-managed.

@rxlee123

Copy link
Copy Markdown
Author

Windows build verification update:

  • Built this PR (e67d8d1) natively on Windows 11 using the MSVC Rust toolchain.
  • Produced both hermes-webui-desktop.exe and the NSIS installer.
  • Launched the PR build in the active desktop session; it connected to the configured WebUI and restored four WebView2 tabs successfully.
  • Confirmed Windows Clipboard History is enabled.

One manual interaction remains: click Copy inside the PR build and inspect Win+V. This cannot be reliably asserted through the current headless/SSH automation because Clipboard History is an OS-managed interactive surface.

@rxlee123

Copy link
Copy Markdown
Author

Confirmed Windows validation

The author manually tested the PR build on Windows and confirmed that all clipboard scenarios worked:

  • WebUI Copy button text appeared in Win+V.
  • Ctrl+C selection appeared in Win+V.
  • Normal paste continued to work.
  • The test was performed with the PR build, not the installed v0.7.0 binary.

This completes the previously outstanding Windows/WebView2 manual validation.

@nesquena-hermes

Copy link
Copy Markdown
Contributor

Review at e67d8d1e7 — real bug, right layer, but the interception model corrupts sanitized copies

Thanks @rxlee123 — and thank you for the genuinely careful work around this one: the research doc in docs/research/windows-clipboard-history.md is the right instinct (you checked whether this belonged in WebUI before writing desktop code, and landed on the correct answer), the change is cleanly Windows-scoped behind cfg!(target_os = "windows"), and you went and did a real Windows 11 MSVC build plus a manual Win+V pass. That's more validation than most desktop PRs arrive with.

The underlying diagnosis is also correct: WebView2's embedded Chromium window owns the clipboard, so Windows omits those copies from Clipboard History. Republishing through the native process is the right fix at the right layer.

I ran this through the Codex gate (NEEDS WORK) and then verified each finding against current WebUI master myself. Three of them are real and one changes the design, so I'd rather hand this back than patch it blind on a path I can't exercise on Windows.


1. 🔴 The copy-event bridge overwrites WebUI's sanitized clipboard payload

This is the blocker. src-tauri/src/bridge.rs:144 reads window.getSelection() in a capture-phase handler and republishes that raw string.

But WebUI installs its own copy handler that deliberately replaces the payload. In static/messages.js:644:

root.addEventListener('copy', _handleMarkdownTableCopy);

and _handleMarkdownTableCopy() ends with:

if (typeof event.preventDefault === 'function') event.preventDefault();
clipboardData.setData('text/html',  payload.html);
clipboardData.setData('text/plain', payload.plain);

So when a user copies a rendered Markdown table, core intentionally puts sanitized Markdown on the clipboard instead of the raw DOM selection. Your handler captures the raw selection, and the later arboard::set_text overwrites both the sanitized text/plain and the text/html flavor with that raw text.

Net effect on Windows: copying a table out of a conversation silently regresses from clean Markdown to raw selection text, and loses the HTML flavor entirely. That's data corruption on a path that works correctly today — which is why I don't want to ship it even though Clipboard History itself would start working.

Fix direction: don't re-derive the text. Read the post-handler payload (event.clipboardData.getData('text/plain') after other listeners have run, or hook at the end of the propagation chain), and preserve the HTML flavor via set_html/equivalent rather than flattening to set_text.

2. 🔴 window._copyText is not actually a window property — the wrapper likely never attaches

bridge.rs:117-122 polls for window._copyText and wraps it. I checked core: _copyText is declared at static/ui.js:8995 as a plain top-level function declaration, and there is no window._copyText = … export anywhere in static/:

$ grep -n "window\._copyText\s*=" static/ui.js
(no output)

ui.js is loaded as a classic <script defer>, so a top-level function declaration does land on the global object in practice — but this is an undeclared, incidental coupling to core's script-loading mode, not a contract. If core ever moves ui.js to a module or wraps it in an IIFE, your typeof current !== 'function' check silently fails forever and the copy-button path just stops reaching the bridge, with no error. Worth either pinning this as an explicit core contract (I can raise that on the WebUI side) or not depending on it.

3. 🟠 Several copy controls reach neither path

Codex flagged this and it holds up: a number of workspace/terminal/panel controls call _copyTextWithFallback (static/ui.js:20930) or navigator.clipboard.writeText directly. A successful async Clipboard API write does not dispatch a copy event, so those copies hit neither the _copyText wrapper nor the event listener — they'll still be missing from Win+V. Issue #90 lists workspace path/content copies specifically, so the fix is incomplete against its own acceptance criteria.

4. 🟠 The wrapper swallows failures and races the original write

bridge.rs:122-131: the wrapper calls current(value), attaches a bare .catch(() => {}), emits immediately, and returns Promise.resolve() unconditionally. Two consequences:

  • Callers like copyMsg() do _copyText(text).then(... 'Copied!' ...).catch(... 'copy failed' ...). With the wrapper in place the .catch can never fire, so a genuinely failed copy still renders a success checkmark.
  • The native write is emitted before the browser's async write settles, so WebView2 can retake clipboard ownership afterward — the exact ordering the PR is trying to control. Await the original, then do the native write last.

Also: _copyText's fallback path (_fallbackCopy, ui.js:9004) uses a hidden <textarea> + document.execCommand('copy'), which does dispatch a copy event — so on that path both bridges fire for one user action, and getSelection() at that moment returns the textarea's contents rather than the user's page selection. Dedup is needed, not just nice-to-have.

5. 🟠 clipboard-write is handled unconditionally in Rust

bridge.rs:794 adds the clipboard-write arm to the shared message handler, which is not cfg-gated — only the JS injection is. Any page loaded in the shell can emit it on all platforms, with no gesture or provenance check, giving page JS a clipboard-write primitive it didn't previously have (the async Clipboard API has permission/gesture rules; this has none). Please #[cfg(target_os = "windows")] the handler arm to match the injection, and consider gating on observed copy activity.

6. 🟡 The regression test can't fail on Windows

bridge.rs:1027 asserts script.contains(...) == cfg!(target_os = "windows"). CI runs on macOS/Linux, so in practice it only ever asserts absence — it can never catch a Windows-side regression in sequencing, dedup, or payload preservation. Parameterizing script assembly by target (rather than reading the host cfg) would let both branches be asserted everywhere.


Suggested order

1 and 4 are the ones that change behavior users would notice; 2 and 3 determine whether the fix actually covers #90. I'd start by moving both paths onto the post-handler clipboard payload with dedup — that single change addresses 1, most of 4, and gives you a natural place to handle 3.

I can't drive Win+V from here, so I've deliberately not pushed fixes to your branch: the sequencing and ownership questions need a real Windows box to verify, and a blind patch from me would just be an untested guess on top of your tested one. If you'd like, I'm happy to push the two mechanical bits (the cfg gate on the handler arm in item 5, and the test parameterization in item 6) so you can focus on the clipboard-payload design — just say the word.

Re-gate whenever you've pushed.

…nterception model

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)
@nesquena-hermes

Copy link
Copy Markdown
Contributor

Re-gate at e247e840d — round-1 blockers closed, but CI is red and two new issues landed with the rewrite

Thanks @rxlee123 — the unified interception model is the right call, and it genuinely closes most of round 1. Verified at this exact head:

  • Item 2 (CLOSED) — patching navigator.clipboard.writeText (bridge.rs:136) instead of polling for window._copyText removes the incidental coupling to core's script-loading mode entirely. Much better than what I asked for.
  • Item 3 (CLOSED) — that choke point also picks up the direct navigator.clipboard.writeText callers (workspace, terminal, share, sessions, panels, onboarding). I re-grepped core: there are no clipboard.write( / ClipboardItem sites and nothing captures a bound writeText reference, so the patch is genuinely reached by every caller.
  • Item 4 (CLOSED) — the wrapper now returns the original promise (bridge.rs:147) so callers' .catch chains see real failures, and the emit is deferred to settlement (:144). The lastText guard (:127) suppresses the execCommand double-fire.
  • Item 5 (CLOSED) — the handler arm is cfg-gated at bridge.rs:845.
  • Item 6 (CLOSED) — init_script taking an explicit target_os (bridge.rs:702) is exactly right, and the test now asserts presence on Windows and absence on macOS/Linux. This is the fix I most wanted.
  • Item 1 (PARTIALLY CLOSED) — the raw-selection clobber is fixed: the bubble-phase listener reads post-handler text/plain (bridge.rs:164), and I confirmed core registers _handleMarkdownTableCopy in bubble phase without stopPropagation, so ordering works. The HTML half is still open — see finding 2.

Three things block merge.


1. 🔴 CI is red — cargo fmt --check fails

The test job is failing at this head. It's purely formatting: adding the target_os first argument pushed two call sites past 100 columns.

Diff in src-tauri/src/windows.rs:181
Diff in src-tauri/src/windows.rs:517
-    let init = bridge::init_script(std::env::consts::OS, &label, &hex, p.connection_mode == "ssh");
+    let init = bridge::init_script(
+        std::env::consts::OS, &label, &hex, p.connection_mode == "ssh",
+    );

cargo fmt --manifest-path src-tauri/Cargo.toml fixes it. (The cargo fmt pass in the PR description was from round 1, before this argument existed.)

2. 🔴 setInterval(install, 1000) leaks a copy listener every second

bridge.rs:186. installClipboard() has an idempotence guard (navigator.clipboard.__hermesPatched, :134), but installCopyListener() (:153) has none — it calls document.addEventListener('copy', function (event) {...}) with a fresh anonymous function on every tick. addEventListener only dedups identical function references, so nothing is deduplicated.

I extracted the actual WINDOWS_CLIPBOARD_BRIDGE string out of bridge.rs and ran it against stubbed globals:

after initial install:               copy listeners = 1
after 10 poll ticks (10s of runtime): copy listeners = 11
after ~1h of runtime:                 copy listeners = 3601
unique listener function refs       = 3601
one copy event -> queued setTimeout callbacks = 3601

The lastText dedup means only one native emit still results, so this isn't a correctness bug — but every Ctrl+C runs 3601 handlers, each calling getData, getSelection, and allocating a fresh copy of the selected string, and the listener list grows for the life of the tab.

Fix: drop the interval and the DOMContentLoaded deferral — document and navigator.clipboard both exist when an init script runs at document creation. If you want to keep the poll defensively, guard the listener the same way you guarded the clipboard patch:

if (document.__hermesCopyHooked) return;
document.__hermesCopyHooked = true;

3. 🔴 Every Windows copy becomes plain-text-only — the HTML flavor is now destroyed

This is round-1 item 1's other half, and it's arguably worse than before because it now affects every copy rather than just tables.

The JS reads only text/plain (bridge.rs:164) and the Rust arm calls set_text (bridge.rs:848). In arboard 3.6.1 on Windows that routes to clipboard_win::raw::set_string, which calls set_string_inner(data, DoClear) — it empties the clipboard first. So the native republish deletes whatever CF_HTML WebView2 or _handleMarkdownTableCopy had written.

Net effect: copying a message or a rendered table and pasting into Word, Outlook, or Teams loses formatting that works today. The doc comment at bridge.rs:114 claiming the flavors are preserved isn't accurate yet.

Fix: read text/html in the listener alongside text/plain and emit both; on the Rust side call set_html(html, Some(text)) (arboard 3.6.1 already provides it on Windows) when HTML is present. For plain selection copies the event payload is empty and Chromium generates CF_HTML after dispatch — for that path, have the Rust side read back the current clipboard text and html natively and re-set both when the text matches the emitted value. That read-back also makes the ordering deterministic instead of relying on setTimeout(0) beating a cross-process write; if the text doesn't match, the browser write hasn't landed, so retry once after a few ms.


Worth fixing in the same round (not blockers)

  • lastText never resets (bridge.rs:124). Copying the same text twice is never republished, even if the user copied something else in another app in between — so Win+V ordering is wrong for that case. Dedup within a short time window, or reset lastText at the start of each copy / writeText.
  • Only copy is hooked (bridge.rs:160). Ctrl+X in the composer fires cut, so cut text won't reach Win+V. Registering the same handler for cut is enough — the text is captured synchronously before removal.
  • Stale doc claims in docs/research/windows-clipboard-history.md:68,82: it says arboard is now a Windows-only dependency, but Cargo.toml:34 is unconditional and paste.rs plus the copy-version command use it on all platforms. It also tells readers to retain the _copyText wrapper, which this rewrite correctly removed.
  • The SPEECH_SUPPRESS re-indent (bridge.rs:100) is unrelated diff noise — harmless, just noting it.

What still needs a real Windows box

I can't verify these from here, so they stay yours:

  • Whether a write opened with a null owner window is recorded by Clipboard History (you confirmed this manually on the round-1 build).
  • Ordering on the copy-event path — setTimeout(0) plus Tauri IPC racing Chromium's cross-process clipboard write. The native read-back suggested in finding 3 removes the guess entirely.
  • Whether set_html lands correctly in Win+V and pastes as rich text into Office.

I also couldn't run cargo test locally — this box lacks the glib/gio development libraries, so the build fails before tests. I reviewed the new test by reading it; CI will run it once fmt is green.


Findings 1 and 2 are mechanical and I'm happy to push them for you if you'd like — just say the word. Finding 3 is the design one, and it needs Windows verification of the set_html path, so I'd rather you take it than have me patch blind on a path I can't exercise. Re-push and I'll re-run the full gate.

Gate: Fable (claude-fable-5-1) — NEEDS WORK. Reviewed at exact head e247e840d7f6fca904b616d6414302ed909c0cdf. Codex was unavailable this round (expired auth token), so the adversarial leg was Fable plus my own reproduction.

@nesquena-hermes

Copy link
Copy Markdown
Contributor

Codex leg at e247e840d — my three findings confirmed, plus three new security/coverage blockers

Following up on my last comment: that round ran Fable only because the Codex route was down (expired auth token), so this head had never had the adversarial leg. The route is healthy again and I've now run it. Codex independently reproduced and confirmed all three published findings (it reproduced the cargo fmt failure, verified the listener leak, and verified arboard's format clearing), so nothing there changes.

It also found three things the read-only pass missed. All three are in the same area — the trust boundary between the page and the native clipboard — and I think #2 in particular is the one worth pausing on.

1. 🔴 Rejected Clipboard API writes still trigger the native write (bridge.rs:144)

The wrapper emits on settlement, but on the rejection path too. An extracted-script harness confirmed the shape: writeText() returns NotAllowedError to the caller (so the browser correctly refused it — no user gesture, permission denied, document not focused) while clipboard-write still fires and the native side publishes the text anyway.

That inverts the guarantee: content that the browser declined to let touch the clipboard reaches the OS clipboard regardless, and it races WebUI's own execCommand fallback, which runs precisely when writeText rejects.

Fix: emit only from the fulfillment callback. Attach a no-op rejection handler so the promise chain stays intact and callers still see the original rejection unchanged — don't convert it.

2. 🔴 The native sink trusts any bridge event, including from subframes (bridge.rs:845)

This is the one I'd most like your read on. The handler accepts the event and ignores the page-supplied label, and content.json grants core:event:default to every HTTP(S) content page. On Windows, Tauri injects its scripts into subframes as well — including WebUI's script-enabled workspace/plugin preview frames.

So any content that can run script in a tab or subframe can call the native sink directly and overwrite the OS clipboard with an arbitrary, unbounded payload — no copy gesture, no selection, no user involvement. That's a meaningfully bigger boundary than "republish what the user just copied."

Fix: replace the generic event sink with a source-validated route that checks the emitting window label, and apply rate and size limits. The stronger shape — which also solves finding 3 below and the ordering race in my earlier finding 3 — is to have the page emit only a post-copy signal carrying no content, and have the Rust side read the native clipboard back and re-publish it. Then the page never supplies the bytes at all.

3. 🔴 Ordinary <input>/<textarea> copies are missed entirely (bridge.rs:164)

The copy-event store is empty before the default action runs, and window.getSelection() does not expose selections inside form controls. So Ctrl+C from the composer — a textarea — produces nothing to republish, and the same applies to the hidden-textarea execCommand fallback.

This matters more than it first looks: on non-localhost HTTP targets there's no secure Clipboard API, so copy buttons there depend entirely on this path. Combined with my earlier finding 3 (HTML flavor destroyed), the current behavior on such a deployment is that plain-control copies don't reach Clipboard History at all while rich copies lose their formatting.

Fix: either read event.target.value.slice(selectionStart, selectionEnd) for editable controls, or adopt the native read-back approach from finding 2, which covers this case for free.


Where that leaves the PR

Six open items now: cargo fmt (CI still red), the listener leak, the HTML-flavor loss, and these three. The first two are mechanical and I'm still happy to push them for you.

The other four all converge on the same design decision, which is why I'd rather not patch them piecemeal: stop trusting page-supplied content and have the Rust side read the clipboard back after the copy settles. That single change gives you the HTML flavor, the control-selection case, a deterministic ordering that doesn't depend on setTimeout(0) beating Chromium's cross-process write, and it closes the subframe injection surface — because the payload stops crossing the boundary at all.

I can't verify the Windows half of that from here (whether set_html lands correctly in Win+V and pastes as rich text into Office, and whether a null-owner-window write is recorded by Clipboard History), so I don't want to write it blind on a path I can't exercise. Happy to take the mechanical two while you take the design one, if that split works for you.

The underlying goal is a good one and the unified interception model was the right call — this is a boundary-hardening round, not a rethink.

Gate: Codex (gpt-5.6-sol) — NEEDS WORK, run at exact head e247e840d7f6fca904b616d6414302ed909c0cdf. Codex confirmed the three previously published findings and added the three above. This closes out the degraded leg I flagged last round.

…bui#91 review

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.
@rxlee123

Copy link
Copy Markdown
Author

@nesquena-hermes ready for re-review — all review points addressed and verified.

Redesigned to be content-free (your unified-model suggestion): the page no longer ships clipboard bytes across the boundary. It emits a payloadless clipboard-republish signal; the native side reads WebView2's own clipboard write back and re-publishes it so the desktop process becomes the owner and Windows records the entry in Clipboard History. This closes the injection surface entirely — no page-supplied text ever reaches the OS clipboard.

Point-by-point:

  • Injection surface — sink no longer accepts text; validates the emitting label (tab-*/main-* only) + 4 MB size cap + 150 ms rate limit + self-echo guard.
  • HTML flavor loss — native read-back preserves both text/plain and text/html (get().html() + set_html(html, Some(text))), so sanitized Markdown-table HTML survives instead of being flattened.
  • Rejected writeText — republish is attached to the fulfillment branch only; the rejection propagates untouched so callers' .catch still fires. A refused write never reaches the clipboard.
  • Listener leak — copy listener now bound once behind an idempotence guard, so the 1 s install() re-arm for late-loaded pages can't accumulate listeners.
  • Missed form-control copies — reading the live clipboard (not getSelection()) captures <input>/<textarea> selections too.

Verification:

  • cargo fmt --check clean (fixed the two long windows.rs lines).
  • cargo test → 25 passed / 0 failed; the regression test is parameterized per target_os and asserts the new signal shape on Windows and its absence on mac/Linux.
  • Windows arm typechecks: cargo xwin check --target x86_64-pc-windows-msvc finishes with 0 errors (caught that arboard exposes HTML read as get().html(), now fixed).
  • Manually confirmed on a real Windows build: copies land in Win+V and Markdown tables paste as rich text.

Also merged origin/main and resolved the CHANGELOG.md conflict (both the Windows clipboard and Linux layout entries kept under one ## [Unreleased]).

@nesquena-hermes

Copy link
Copy Markdown
Contributor

Re-gate at eea496a08 — the content-free redesign closes round 2, but read-back now launders other apps' excluded clipboard data

Thanks @rxlee123. Moving to a payloadless signal with a native read-back was the right call. It removes most of what round 2 flagged, and the xwin check plus the real Win+V pass are appreciated.

Verified closed at this head. I used an extracted-script harness (the literal WINDOWS_CLIPBOARD_BRIDGE from bridge.rs, run in a Node vm) and read the vendored arboard 3.6.1, clipboard-win 5.4.1 and tauri 2.11.2 sources:

  • Rejected writeText: the caller's .catch fires and nothing is emitted. Fulfilled writes emit once.
  • Listener leak: after 50 install() re-arm ticks there is exactly 1 copy listener.
  • Page bytes crossing the boundary: gone. The sink reads the clipboard natively.
  • HTML flavor: now read back and re-written with set_html(html, Some(text)).
  • cargo fmt --check: clean.
  • Threading (not an issue): JS emit is an async Tauri command, so the listen_any callback runs on a tokio worker, not the WebView2 UI thread. The PR fix(windows): avoid WebView polling during voice input #89 re-entrancy pattern does not apply.
  • Cross-platform gating (not an issue): every init_script call site passes std::env::consts::OS, which reproduces the old cfg! split one for one.

A fresh dual gate still came back with one privacy blocker. Both advisors reached it independently, and I confirmed it against the arboard source.


1. 🔴 A republish can push another app's excluded clipboard content into Win+V history and cloud sync (bridge.rs:765-821)

republish_clipboard() re-writes whatever is currently on the clipboard, no matter which app put it there. The write loses the privacy flags:

  • In arboard 3.6.1 on Windows, Set::new defaults exclude_from_history / exclude_from_cloud / exclude_from_monitoring to false (platform/windows.rs:665-672).
  • Both set_text and set_html start with clipboard_win::raw::set_string, which empties the clipboard. add_clipboard_exclusions then adds nothing.

Password managers (KeePass, Bitwarden, 1Password) mark secrets with ExcludeClipboardContentFromMonitorProcessing / CanIncludeInClipboardHistory=0 / CanUploadToCloudClipboard=0 so they never land in Win+V history or roam to other devices. Once a republish runs over one of those secrets, it becomes an ordinary, unflagged entry. That is a regression compared with today, where the secret stays out of history.

The republish can be triggered without the user copying anything in the app:

  • Direct emit from content. content.json grants core:event:default to every content page. The label the sink checks comes from the JSON payload (bridge.rs:832), and Tauri's Event carries no source identity. So any script in a tab, or in a subframe (WebView2 injects init scripts into child frames), can run window.__TAURI__.event.emit('bridge', {label:'tab-1-1', kind:'clipboard-republish'}).
  • Synthetic copy event. The harness confirms document.dispatchEvent(new Event('copy')) fires the native signal (bridge.rs:170 does not check isTrusted).
  • Ordering race (next item). If the native read wins, it republishes the previous item, which may be the secret.

Fix (must-have): in republish_clipboard, open the clipboard once and return early if any exclusion format is present, before any read or write:

// Cargo.toml: [target.'cfg(windows)'.dependencies] clipboard-win = "5"   (already in Cargo.lock via arboard)
const EXCLUSION_FORMATS: [&str; 3] = [
    "ExcludeClipboardContentFromMonitorProcessing",
    "CanIncludeInClipboardHistory",
    "CanUploadToCloudClipboard",
];
for name in EXCLUSION_FORMATS {
    if let Some(f) = clipboard_win::register_format(name) {
        if clipboard_win::is_format_avail(f.get()) { return; }
    }
}

Fix (strongly recommended, and it also closes #2): only republish when the current clipboard owner is WebView2 itself. Use clipboard_win::raw::get_owner() → GetWindowThreadProcessId, compared against the WebView2 browser process (ICoreWebView2::get_BrowserProcessId via with_webview, or msedgewebview2.exe). With that check, the function cannot publish anything WebView2 did not write.

Also add if (!e.isTrusted) return; in the copy listener as cheap defense in depth. It does not close the direct-emit path by itself.

2. 🟠 The copy-event path never checks that the clipboard actually changed (bridge.rs:133-140)

On the copy path the signal goes out after setTimeout(0) plus an IPC hop, while Chromium commits the OS write cross-process. That usually wins, but the ordering is not guaranteed. When the native read runs first, the previous item gets a fresh history entry and the real copy is never recorded. The fulfilled writeText path has a stronger ordering guarantee.

Fix: the owner check above makes this deterministic. If the owner is not yet WebView2, retry once after roughly 20-50 ms and then give up. Tracking clipboard_win::raw::seq_num() and skipping when it hasn't moved since the last republish also prevents re-publishing stale content.

3. 🟠 Docs and CHANGELOG still describe the round-1/round-2 design

  • docs/research/windows-clipboard-history.md:57 "post-handler clipboardData", :61 "Emits a clipboard-write message", :66 "arboard::Clipboard::set_text", :68 "arboard crate is now a Windows-only dependency in Cargo.toml" (Cargo.toml is untouched by this PR; arboard = "3" is unconditional and used by paste.rs/main.rs), :82 "retain both the _copyText wrapper…".
  • CHANGELOG.md:13-14 "post-handler clipboardData read".

Please rewrite them to match the content-free signal, native read-back, and exclusion/owner guard, and list the known format limit (see 5).


Worth fixing in the same round (not blockers)

  1. Comments claim more than the code does.
    • bridge.rs:919-921 "Trust only real content tabs — never a subframe" is not accurate, because the label comes from the page. Reword it as a sanity filter; Linux: XInitThreads before GTK init — fix intermittent X11 startup crash #1 is the real boundary.
    • bridge.rs:760-763 calls this a "rate limit" and a "feedback loop" guard. The code at :807 is only a same-text dedup within 150 ms: different content is never throttled, and native writes don't fire DOM copy, so the loop can't happen. Either reword, or add a time-only floor.
    • Record LAST only after the write succeeds, so a failed write can be retried.
  2. Caps and fidelity.
    • The 4 MB cap (:771) covers text only. The HTML read at :816 is never measured, and table HTML is often several times the text size. Cap it too.
    • get_text() returning ContentNotAvailable (image-only clipboard) is logged as a warning at :786-792. Make it a silent return.
    • set_string also erases RTF and custom formats, and get().html() returns only the fragment, so SourceURL is lost. That's fine for text copies, but say so in the docs.
  3. Test coverage. The new test checks script inclusion only. PR CI (test.yml) runs on macos-14 only, so none of the #[cfg(windows)] code is compiled by any PR check. Please pull the guard logic out into a cfg-free republish_decide(...) next to dedupe_decide, so the size caps, dedup window and exclusion/owner decision can be unit-tested on macOS CI, with only the arboard/clipboard-win calls left under cfg(windows).
  4. cut is still not hooked (the harness shows 0 emits), so Ctrl+X in the composer won't reach Win+V. Adding the same listener for cut is enough.

Why I'm handing this back instead of pushing it

Everything left sits on a Windows-only privacy boundary: exclusion-format behavior, owner-PID attribution, and whether the retry timing actually wins. This box can't compile or run the Windows target, so I'd rather you land #1/#2 and confirm them on your Windows build than have me patch them blind. For the Windows check, please include a KeePass/Bitwarden copy followed by a Hermes signal, then confirm Win+V does not show the secret. I'm happy to push #3/#4 (docs and comment wording) myself if that helps. Re-push and I'll re-run the full gate.

I've also approved the pending fork CI run for this head so fmt/clippy/test results are visible.

Gate: Codex (gpt-6-sol, xhigh): NEEDS WORK. Fable (claude-fable-5-1): SHIP WITH THE HIGH-VALUE FIXES (1, 2). Both ran at exact head eea496a08d78179500dd283b578250a498ea5926, plus my own extracted-script harness and a read of the vendored arboard/clipboard-win/tauri sources. cargo test could not build on this Linux host (no glib dev libs), and Windows behavior is verified by source reading only.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Windows WebView2 copies do not appear in Clipboard History

2 participants