Skip to content

armgit / Handy

Public Imported from GitHub
0

A free, open source, and extensible speech-to-text application that works completely offline.

add more reliable paste (#1812)

CJ Paisa70ac84fd668
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 4e19d72d..fae1ad20 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -2465,6 +2465,9 @@ dependencies = [
"hound",
"log",
"natural",
+ "objc2",
+ "objc2-app-kit",
+ "objc2-foundation",
"once_cell",
"rdev",
"regex",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index d70fdc73..77051b48 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -106,10 +106,14 @@ tauri-plugin-updater = "2.10.0"
windows = { version = "0.61.3", features = [
"Win32_Media_Audio_Endpoints",
"Win32_System_Com_StructuredStorage",
+ "Win32_System_DataExchange",
"Win32_System_LibraryLoader",
+ "Win32_System_Ole",
+ "Win32_System_Memory",
"Win32_System_Threading",
"Win32_System_Variant",
"Win32_Foundation",
+ "Win32_Graphics_Gdi",
"Win32_UI_WindowsAndMessaging",
] }
winreg = "0.55"
@@ -139,6 +143,11 @@ transcribe-cpp = { version = "0.1.3", default-features = false }
[target.'cfg(target_os = "macos")'.dependencies]
tauri-nspanel = { git = "https://github.com/ahkohd/tauri-nspanel", branch = "v2.1" }
transcribe-cpp = { version = "0.1.3", default-features = false, features = ["metal"] }
+# Used by the receipt-sequenced ("reliable") paste path for lazy NSPasteboard
+# promises. Versions track what Tauri already pulls in.
+objc2 = "0.6"
+objc2-foundation = "0.3"
+objc2-app-kit = "0.3"
[target.'cfg(target_os = "linux")'.dependencies]
gtk-layer-shell = { version = "0.8", features = ["v0_6"] }
diff --git a/src-tauri/src/clipboard.rs b/src-tauri/src/clipboard.rs
index c822bc2f..5a181345 100644
--- a/src-tauri/src/clipboard.rs
+++ b/src-tauri/src/clipboard.rs
@@ -63,9 +63,11 @@ fn paste_via_clipboard(
// Fall back to enigo if no native tool handled it
if !key_combo_sent {
match paste_method {
- PasteMethod::CtrlV => input::send_paste_ctrl_v(enigo)?,
- PasteMethod::CtrlShiftV => input::send_paste_ctrl_shift_v(enigo)?,
- PasteMethod::ShiftInsert => input::send_paste_shift_insert(enigo)?,
+ // The legacy path cannot detect a mistimed chord, so it keeps the
+ // conservative 100ms modifier hold.
+ PasteMethod::CtrlV => input::send_paste_ctrl_v(enigo, 100)?,
+ PasteMethod::CtrlShiftV => input::send_paste_ctrl_shift_v(enigo, 100)?,
+ PasteMethod::ShiftInsert => input::send_paste_shift_insert(enigo, 100)?,
_ => return Err("Invalid paste method for clipboard paste".into()),
}
}
@@ -561,7 +563,7 @@ fn paste_direct(
input::paste_text_direct(enigo, text)
}
-fn send_return_key(enigo: &mut Enigo, key_type: AutoSubmitKey) -> Result<(), String> {
+pub(crate) fn send_return_key(enigo: &mut Enigo, key_type: AutoSubmitKey) -> Result<(), String> {
match key_type {
AutoSubmitKey::Enter => {
enigo
@@ -649,6 +651,28 @@ pub fn paste(text: String, app_handle: AppHandle) -> Result<(), String> {
)?;
}
PasteMethod::CtrlV | PasteMethod::CtrlShiftV | PasteMethod::ShiftInsert => {
+ // Debug-gated receipt-sequenced paste (#502): restore the clipboard
+ // after the target actually reads the transcript, not on a timer.
+ // On success it fully handles the paste (including auto-submit and
+ // clipboard handling) asynchronously; on failure fall through to
+ // the legacy path untouched.
+ #[cfg(any(target_os = "macos", target_os = "windows"))]
+ if settings.reliable_paste {
+ match crate::paste_tx::try_reliable_paste(
+ &text,
+ &app_handle,
+ &paste_method,
+ &mut enigo,
+ settings.auto_submit,
+ settings.auto_submit_key,
+ settings.clipboard_handling,
+ ) {
+ Ok(()) => return Ok(()),
+ Err(e) => {
+ log::warn!("Reliable paste unavailable ({e}); falling back to legacy paste")
+ }
+ }
+ }
paste_via_clipboard(
&mut enigo,
&text,
diff --git a/src-tauri/src/input.rs b/src-tauri/src/input.rs
index ee33317b..ef915035 100644
--- a/src-tauri/src/input.rs
+++ b/src-tauri/src/input.rs
@@ -25,7 +25,14 @@ pub fn get_cursor_position(app_handle: &AppHandle) -> Option<(i32, i32)> {
/// Sends a Ctrl+V or Cmd+V paste command using platform-specific virtual key codes.
/// This ensures the paste works regardless of keyboard layout (e.g., Russian, AZERTY, DVORAK).
/// Note: On Wayland, this may not work - callers should check for Wayland and use alternative methods.
-pub fn send_paste_ctrl_v(enigo: &mut Enigo) -> Result<(), String> {
+///
+/// `hold_ms` is how long the modifier stays held after the V click before being
+/// released. Most applications read the modifier from the V event's flags and
+/// need no hold at all, but applications that poll global keyboard state when
+/// handling the key need the modifier to still be down — the hold insures
+/// against those. Callers that can detect a failed chord (e.g. the
+/// receipt-sequenced paste path) may use a much shorter hold.
+pub fn send_paste_ctrl_v(enigo: &mut Enigo, hold_ms: u64) -> Result<(), String> {
// Platform-specific key definitions
#[cfg(target_os = "macos")]
let (modifier_key, v_key_code) = (Key::Meta, Key::Other(9));
@@ -42,7 +49,7 @@ pub fn send_paste_ctrl_v(enigo: &mut Enigo) -> Result<(), String> {
.key(v_key_code, enigo::Direction::Click)
.map_err(|e| format!("Failed to click V key: {}", e))?;
- std::thread::sleep(std::time::Duration::from_millis(100));
+ std::thread::sleep(std::time::Duration::from_millis(hold_ms));
enigo
.key(modifier_key, enigo::Direction::Release)
@@ -54,7 +61,7 @@ pub fn send_paste_ctrl_v(enigo: &mut Enigo) -> Result<(), String> {
/// Sends a Ctrl+Shift+V paste command.
/// This is commonly used in terminal applications on Linux to paste without formatting.
/// Note: On Wayland, this may not work - callers should check for Wayland and use alternative methods.
-pub fn send_paste_ctrl_shift_v(enigo: &mut Enigo) -> Result<(), String> {
+pub fn send_paste_ctrl_shift_v(enigo: &mut Enigo, hold_ms: u64) -> Result<(), String> {
// Platform-specific key definitions
#[cfg(target_os = "macos")]
let (modifier_key, v_key_code) = (Key::Meta, Key::Other(9)); // Cmd+Shift+V on macOS
@@ -74,7 +81,7 @@ pub fn send_paste_ctrl_shift_v(enigo: &mut Enigo) -> Result<(), String> {
.key(v_key_code, enigo::Direction::Click)
.map_err(|e| format!("Failed to click V key: {}", e))?;
- std::thread::sleep(std::time::Duration::from_millis(100));
+ std::thread::sleep(std::time::Duration::from_millis(hold_ms));
enigo
.key(Key::Shift, enigo::Direction::Release)
@@ -89,7 +96,7 @@ pub fn send_paste_ctrl_shift_v(enigo: &mut Enigo) -> Result<(), String> {
/// Sends a Shift+Insert paste command (Windows and Linux only).
/// This is more universal for terminal applications and legacy software.
/// Note: On Wayland, this may not work - callers should check for Wayland and use alternative methods.
-pub fn send_paste_shift_insert(enigo: &mut Enigo) -> Result<(), String> {
+pub fn send_paste_shift_insert(enigo: &mut Enigo, hold_ms: u64) -> Result<(), String> {
#[cfg(target_os = "windows")]
let insert_key_code = Key::Other(0x2D); // VK_INSERT
#[cfg(not(target_os = "windows"))]
@@ -103,7 +110,7 @@ pub fn send_paste_shift_insert(enigo: &mut Enigo) -> Result<(), String> {
.key(insert_key_code, enigo::Direction::Click)
.map_err(|e| format!("Failed to click Insert key: {}", e))?;
- std::thread::sleep(std::time::Duration::from_millis(100));
+ std::thread::sleep(std::time::Duration::from_millis(hold_ms));
enigo
.key(Key::Shift, enigo::Direction::Release)
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 3dec643a..621b6a02 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -12,6 +12,7 @@ mod input;
mod llm_client;
mod managers;
mod overlay;
+mod paste_tx;
pub mod portable;
mod secure_input;
mod settings;
@@ -624,6 +625,7 @@ pub fn run(cli_args: CliArgs) {
shortcut::change_extra_recording_buffer_setting,
shortcut::change_paste_delay_ms_setting,
shortcut::change_paste_delay_after_ms_setting,
+ shortcut::change_reliable_paste_setting,
shortcut::change_paste_method_setting,
shortcut::get_available_typing_tools,
shortcut::change_typing_tool_setting,
diff --git a/src-tauri/src/paste_tx/macos.rs b/src-tauri/src/paste_tx/macos.rs
new file mode 100644
index 00000000..0c4113b6
--- /dev/null
+++ b/src-tauri/src/paste_tx/macos.rs
@@ -0,0 +1,336 @@
+//! macOS reliable paste.
+//!
+//! Publishes the transcript with `declareTypes:owner:`, which puts a *promise*
+//! on the general pasteboard instead of data. When any consumer actually
+//! requests the text, AppKit calls `pasteboard:provideDataForType:` on our
+//! owner object — that callback is the read receipt. The previous clipboard is
+//! restored once receipts go quiet (see `paste_tx::evaluate`), guarded by the
+//! pasteboard `changeCount` so we never clobber a newer user copy.
+//!
+//! Threading: publishing and chord injection happen on the calling (main)
+//! thread, because promised pasteboard data is serviced by AppKit on the main
+//! run loop. The (potentially seconds-long) wait runs on a worker thread; the
+//! guarded restore is dispatched back to the main thread.
+
+use std::sync::{Arc, Mutex};
+use std::thread;
+use std::time::{Duration, Instant};
+
+use log::{error, info};
+use objc2::rc::Retained;
+use objc2::{define_class, msg_send, AnyThread, DefinedClass};
+use objc2_app_kit::{NSPasteboard, NSPasteboardTypeString};
+use objc2_foundation::{NSArray, NSInteger, NSObject, NSString};
+use tauri::{AppHandle, Manager};
+use tauri_plugin_clipboard_manager::ClipboardExt;
+
+use super::{evaluate, send_chord, TxState, WaitDecision};
+use crate::clipboard::send_return_key;
+use crate::input::EnigoState;
+use crate::settings::{AutoSubmitKey, ClipboardHandling, PasteMethod};
+
+/// Concealment marker types declared alongside the text so that well-behaved
+/// third-party clipboard managers (Maccy, Paste, ...) skip the transcript.
+/// Fewer eager readers means a receipt is more likely to be the actual target.
+/// These are conventions; nothing enforces them.
+const CONCEALMENT_TYPES: [&str; 3] = [
+ "org.nspasteboard.TransientType",
+ "org.nspasteboard.ConcealedType",
+ "org.nspasteboard.AutoGeneratedType",
+];
+
+pub struct ProviderIvars {
+ state: Arc<Mutex<TxState>>,
+ text: String,
+}
+
+define_class!(
+ // SAFETY: NSObject has no subclassing requirements and the ivars are
+ // plain Rust values guarded by a Mutex.
+ #[unsafe(super(NSObject))]
+ #[name = "HandyPasteProvider"]
+ #[ivars = ProviderIvars]
+ pub struct HandyPasteProvider;
+
+ impl HandyPasteProvider {
+ // NSPasteboardOwner informal protocol: the pasteboard is asking for the
+ // promised data — our receipt that a consumer read the clipboard.
+ #[unsafe(method(pasteboard:provideDataForType:))]
+ fn pasteboard_provide_data_for_type(&self, pasteboard: &NSPasteboard, data_type: &NSString) {
+ let ivars = self.ivars();
+ // SAFETY: NSPasteboardTypeString is a read-only framework static.
+ let is_text = unsafe { data_type.isEqualToString(NSPasteboardTypeString) };
+ // Only a text read counts as a receipt: a request for one of the
+ // concealment marker types is a clipboard manager inspecting the
+ // markers, not the paste target reading the transcript.
+ if is_text {
+ if let Ok(mut state) = ivars.state.lock() {
+ state.record_receipt(Instant::now());
+ }
+ }
+ let payload = if is_text {
+ NSString::from_str(&ivars.text)
+ } else {
+ // Concealment marker types are never handed out.
+ NSString::from_str("")
+ };
+ let _ = pasteboard.setString_forType(&payload, data_type);
+ }
+
+ #[unsafe(method(pasteboardChangedOwner:))]
+ fn pasteboard_changed_owner(&self, _pasteboard: &NSPasteboard) {
+ if let Ok(mut state) = self.ivars().state.lock() {
+ state.ownership_lost = true;
+ }
+ }
+ }
+);
+
+impl HandyPasteProvider {
+ fn new(state: Arc<Mutex<TxState>>, text: String) -> Retained<Self> {
+ let this = Self::alloc().set_ivars(ProviderIvars { state, text });
+ unsafe { msg_send![super(this), init] }
+ }
+}
+
+struct MacPending {
+ state: Arc<Mutex<TxState>>,
+ saved_text: Option<String>,
+ saved_image: Option<tauri::image::Image<'static>>,
+ change_count: NSInteger,
+ provider: Option<Retained<HandyPasteProvider>>,
+ auto_submit: bool,
+ auto_submit_key: AutoSubmitKey,
+ /// ClipboardHandling::CopyToClipboard — instead of restoring, settle by
+ /// re-writing the transcript as plain text (without the concealment
+ /// markers), so clipboard managers record it and it outlives the promise.
+ preserve_transcript: bool,
+ /// The transcript, for the `preserve_transcript` re-write at settle time.
+ transcript: String,
+ settled: bool,
+}
+
+/// The transaction currently holding the clipboard, if any. A new paste
+/// settles it before snapshotting (see `flush_pending`).
+static PENDING: Mutex<Option<Arc<Mutex<MacPending>>>> = Mutex::new(None);
+
+/// Settles a transaction exactly once: sends the owed auto-submit Enter and
+/// restores the previous clipboard, guarded so we never clobber a newer copy.
+/// Must run on the main thread. Uses the already-locked enigo when called
+/// from within `paste` (which holds the lock), otherwise locks it itself.
+fn settle(
+ pending: &Arc<Mutex<MacPending>>,
+ app_handle: &AppHandle,
+ enigo: Option<&mut enigo::Enigo>,
+) {
+ let mut p = match pending.lock() {
+ Ok(p) => p,
+ Err(_) => return,
+ };
+ if p.settled {
+ return;
+ }
+ p.settled = true;
+
+ let (receipt_seen, ownership_lost) = match p.state.lock() {
+ Ok(st) => (st.any_receipt_after_injection(), st.ownership_lost),
+ Err(_) => (false, true),
+ };
+
+ // Auto-submit only once the target demonstrably read the transcript;
+ // pressing Enter after an unconfirmed paste could submit stale content.
+ if p.auto_submit && receipt_seen {
+ match enigo {
+ Some(e) => {
+ let _ = send_return_key(e, p.auto_submit_key);
+ }
+ None => {
+ if let Some(enigo_state) = app_handle.try_state::<EnigoState>() {
+ if let Ok(mut e) = enigo_state.0.lock() {
+ let _ = send_return_key(&mut e, p.auto_submit_key);
+ }
+ }
+ }
+ }
+ }
+
+ let still_ours =
+ !ownership_lost && NSPasteboard::generalPasteboard().changeCount() == p.change_count;
+ if !still_ours {
+ info!("[reliable-paste] clipboard changed externally; leaving it untouched");
+ } else if p.preserve_transcript {
+ // The user asked for the transcript to stay on the clipboard: replace
+ // the concealed promise with plain text so clipboard managers record
+ // it and it survives this app exiting.
+ let _ = app_handle.clipboard().write_text(&p.transcript);
+ info!("[reliable-paste] left transcript on clipboard as plain text");
+ } else {
+ let clipboard = app_handle.clipboard();
+ if let Some(text) = &p.saved_text {
+ let _ = clipboard.write_text(text);
+ } else if let Some(image) = &p.saved_image {
+ let _ = clipboard.write_image(image);
+ } else {
+ let _ = clipboard.clear();
+ }
+ info!("[reliable-paste] restored previous clipboard");
+ }
+
+ // Release the owner; any outstanding promise dies with the pasteboard
+ // contents we just replaced (or with the external change).
+ p.provider = None;
+}
+
+/// If a previous transaction is still holding the clipboard, settle it now so
+/// the caller's snapshot captures the user's original clipboard content.
+fn flush_pending(app_handle: &AppHandle, enigo: &mut enigo::Enigo) {
+ let previous = match PENDING.lock() {
+ Ok(mut slot) => slot.take(),
+ Err(_) => None,
+ };
+ if let Some(previous) = previous {
+ settle(&previous, app_handle, Some(enigo));
+ }
+}
+
+fn spawn_waiter(pending: Arc<Mutex<MacPending>>, app_handle: AppHandle) {
+ thread::spawn(move || {
+ let outcome = loop {
+ thread::sleep(Duration::from_millis(15));
+ let (decision, state_snapshot) = {
+ let p = match pending.lock() {
+ Ok(p) => p,
+ Err(_) => return,
+ };
+ if p.settled {
+ // A newer paste settled this transaction already.
+ return;
+ }
+ let result = match p.state.lock() {
+ Ok(st) => {
+ let now = Instant::now();
+ let snapshot = (
+ st.any_receipt_after_injection(),
+ st.ownership_lost,
+ st.injection_failed,
+ );
+ (evaluate(&st, now), snapshot)
+ }
+ Err(_) => return,
+ };
+ result
+ };
+ if let WaitDecision::Finish = decision {
+ break state_snapshot;
+ }
+ };
+
+ let (receipt_seen, ownership_lost, injection_failed) = outcome;
+ if ownership_lost {
+ info!("[reliable-paste] settling: clipboard ownership lost");
+ } else if receipt_seen {
+ info!("[reliable-paste] settling: reads went quiet");
+ } else if injection_failed {
+ info!("[reliable-paste] settling: chord injection failed, restoring quickly");
+ } else {
+ info!("[reliable-paste] settling: no read within timeout, restoring anyway");
+ }
+
+ let pending_for_finish = pending.clone();
+ let app_for_finish = app_handle.clone();
+ let _ = app_handle.run_on_main_thread(move || {
+ settle(&pending_for_finish, &app_for_finish, None);
+ if let Ok(mut slot) = PENDING.lock() {
+ let is_us = slot
+ .as_ref()
+ .map(|current| Arc::ptr_eq(current, &pending))
+ .unwrap_or(false);
+ if is_us {
+ *slot = None;
+ }
+ }
+ });
+ });
+}
+
+pub(super) fn run(
+ text: &str,
+ app_handle: &AppHandle,
+ paste_method: &PasteMethod,
+ enigo: &mut enigo::Enigo,
+ auto_submit: bool,
+ auto_submit_key: AutoSubmitKey,
+ clipboard_handling: ClipboardHandling,
+) -> Result<(), String> {
+ // Settle any previous transaction first so the snapshot below captures the
+ // user's original clipboard, not the previous transcript.
+ flush_pending(app_handle, enigo);
+
+ let clipboard = app_handle.clipboard();
+ let saved_text = clipboard.read_text().ok().filter(|t| !t.is_empty());
+ // Only probe for an image when there is no text; reading an image decodes
+ // the full bitmap (mirrors the legacy path).
+ let saved_image = if saved_text.is_none() {
+ clipboard.read_image().ok().map(|image| image.to_owned())
+ } else {
+ None
+ };
+
+ let state = Arc::new(Mutex::new(TxState::new()));
+ let provider = HandyPasteProvider::new(state.clone(), text.to_string());
+ let pasteboard = NSPasteboard::generalPasteboard();
+
+ let mut types: Vec<Retained<NSString>> = Vec::with_capacity(1 + CONCEALMENT_TYPES.len());
+ types.push(NSString::from_str("public.utf8-plain-text"));
+ for t in CONCEALMENT_TYPES {
+ types.push(NSString::from_str(t));
+ }
+ let types = NSArray::from_retained_slice(&types);
+
+ // declareTypes:owner: clears the pasteboard and puts our promise on it;
+ // the return value is the new changeCount.
+ let change_count: NSInteger =
+ unsafe { msg_send![&*pasteboard, declareTypes: &*types, owner: &*provider] };
+ if change_count <= 0 {
+ return Err("declareTypes:owner: failed".to_string());
+ }
+ info!("[reliable-paste] published transcript as lazy promise (changeCount {change_count})");
+
+ // Mark injection *before* sending: enigo holds the chord for ~100ms and a
+ // fast target may legitimately read while the chord is still held.
+ if let Ok(mut st) = state.lock() {
+ st.injected_at = Some(Instant::now());
+ }
+ match send_chord(enigo, paste_method) {
+ Ok(()) => {
+ info!("[reliable-paste] paste chord sent ({paste_method:?})");
+ }
+ Err(e) => {
+ // Keep the transaction alive: the waiter restores the clipboard
+ // after the short failed-injection timeout.
+ if let Ok(mut st) = state.lock() {
+ st.injection_failed = true;
+ }
+ error!("[reliable-paste] failed to send paste chord: {e}");
+ }
+ }
+
+ let pending = Arc::new(Mutex::new(MacPending {
+ state,
+ saved_text,
+ saved_image,
+ change_count,
+ provider: Some(provider),
+ auto_submit,
+ auto_submit_key,
+ preserve_transcript: clipboard_handling == ClipboardHandling::CopyToClipboard,
+ transcript: text.to_string(),
+ settled: false,
+ }));
+ if let Ok(mut slot) = PENDING.lock() {
+ *slot = Some(pending.clone());
+ }
+ spawn_waiter(pending, app_handle.clone());
+
+ Ok(())
+}
diff --git a/src-tauri/src/paste_tx/mod.rs b/src-tauri/src/paste_tx/mod.rs
new file mode 100644
index 00000000..71fdc552
--- /dev/null
+++ b/src-tauri/src/paste_tx/mod.rs
@@ -0,0 +1,283 @@
+//! Receipt-sequenced clipboard paste ("reliable paste", debug-gated).
+//!
+//! The legacy clipboard paste (`clipboard::paste_via_clipboard`) restores the
+//! previous clipboard after a fixed delay. The paste keystroke is only
+//! *enqueued* at that point — the target application reads the clipboard
+//! whenever its event loop gets to it, so any fixed delay can lose the race
+//! and the user gets their old clipboard pasted back (#502).
+//!
+//! This module instead publishes the transcript as a *lazy promise* and waits
+//! for the operating system to tell us that a consumer actually read the
+//! clipboard — a "receipt" — before restoring:
+//!
+//! - Windows: delayed rendering (`SetClipboardData(CF_UNICODETEXT, NULL)`),
+//! the owner window receives `WM_RENDERFORMAT` on read.
+//! - macOS: `declareTypes:owner:` with an owner object, the pasteboard calls
+//! `pasteboard:provideDataForType:` on read.
+//!
+//! Two rules make the receipt trustworthy:
+//!
+//! 1. Only receipts observed *after* the paste chord was injected count. A
+//! read before that is an eager third party (clipboard manager, antivirus)
+//! reacting to the clipboard change itself.
+//! 2. Restoration only happens while we still own the clipboard
+//! (sequence number / changeCount unchanged, no ownership-lost event). If
+//! the user copied something else in the meantime, their action wins.
+//!
+//! The restore is additionally gated on a short quiet period after the *last*
+//! receipt, because some applications read the clipboard several times per
+//! paste (Chromium probes, then reads). A bounded timeout caps how long the
+//! transcript may occupy the clipboard; the failure mode is always "the
+//! transcript stays on the clipboard a bit longer", never "stale content gets
+//! pasted".
+
+// The shared transaction state is compiled on all platforms (for the unit
+// tests), but only the macOS/Windows platform modules consume all of it.
+#![cfg_attr(not(any(target_os = "macos", target_os = "windows")), allow(dead_code))]
+
+use std::time::{Duration, Instant};
+
+#[cfg(target_os = "macos")]
+mod macos;
+#[cfg(target_os = "windows")]
+mod windows;
+
+#[cfg(target_os = "macos")]
+use macos as platform;
+#[cfg(target_os = "windows")]
+use windows as platform;
+
+/// How long after the *last* observed read the transcript stays on the
+/// clipboard before restoring. Covers applications that read the clipboard
+/// several times per paste (e.g. Chromium probe-then-read).
+pub(crate) const QUIET_PERIOD: Duration = Duration::from_millis(200);
+
+/// Upper bound on how long the transcript may occupy the clipboard before we
+/// restore regardless of receipts. Long enough that a realistically loaded
+/// target always gets to read first; short enough that a lost keystroke does
+/// not strand the transcript on the clipboard for long.
+pub(crate) const RESTORE_TIMEOUT: Duration = Duration::from_secs(8);
+
+/// When the chord could not be injected at all, no legitimate receipt can
+/// arrive, so restore quickly instead of waiting out the full timeout.
+pub(crate) const FAILED_INJECTION_TIMEOUT: Duration = Duration::from_millis(500);
+
+/// Shared, cross-thread record of one paste transaction.
+#[derive(Debug)]
+pub(crate) struct TxState {
+ /// When the transcript was published to the clipboard.
+ pub published_at: Instant,
+ /// When the paste chord was injected. Only receipts *after* this count as
+ /// evidence the target read the transcript — earlier reads are eager third
+ /// parties reacting to the clipboard change itself.
+ pub injected_at: Option<Instant>,
+ /// The chord could not be sent; short-circuit the wait.
+ pub injection_failed: bool,
+ /// Times at which a consumer requested the clipboard data.
+ pub receipts: Vec<Instant>,
+ /// Someone else took clipboard ownership (user copied elsewhere, ...).
+ pub ownership_lost: bool,
+ /// A newer paste transaction settled this one early (see flush logic in
+ /// the platform modules).
+ pub cancelled: bool,
+ /// The post-paste Enter (auto-submit) has been sent for this transaction.
+ /// (Read on Windows; the macOS path settles via `MacPending::settled`.)
+ #[allow(dead_code)]
+ pub auto_submit_sent: bool,
+ /// First post-injection receipt has been logged.
+ pub logged_receipt: bool,
+}
+
+impl TxState {
+ pub fn new() -> Self {
+ Self {
+ published_at: Instant::now(),
+ injected_at: None,
+ injection_failed: false,
+ receipts: Vec::new(),
+ ownership_lost: false,
+ cancelled: false,
+ auto_submit_sent: false,
+ logged_receipt: false,
+ }
+ }
+
+ /// Records a read receipt, logging the first one that counts as evidence.
+ pub fn record_receipt(&mut self, at: Instant) {
+ self.receipts.push(at);
+ if !self.logged_receipt {
+ if let Some(injected) = self.injected_at {
+ if at >= injected {
+ self.logged_receipt = true;
+ log::info!(
+ "[reliable-paste] clipboard read {}ms after chord",
+ at.duration_since(injected).as_millis()
+ );
+ }
+ }
+ }
+ }
+
+ pub fn last_receipt_after_injection(&self) -> Option<Instant> {
+ let injected = self.injected_at?;
+ self.receipts.iter().copied().rev().find(|t| *t >= injected)
+ }
+
+ pub fn any_receipt_after_injection(&self) -> bool {
+ self.last_receipt_after_injection().is_some()
+ }
+}
+
+pub(crate) enum WaitDecision {
+ KeepWaiting,
+ /// Stop waiting; settle the transaction (auto-submit + guarded restore).
+ Finish,
+}
+
+/// Pure decision: given the current transaction state, keep waiting for the
+/// target to read, or finish now. Both platform event loops call this.
+pub(crate) fn evaluate(state: &TxState, now: Instant) -> WaitDecision {
+ if state.ownership_lost || state.cancelled {
+ return WaitDecision::Finish;
+ }
+ if let Some(last) = state.last_receipt_after_injection() {
+ if now.duration_since(last) >= QUIET_PERIOD {
+ return WaitDecision::Finish;
+ }
+ }
+ let deadline = if state.injection_failed {
+ FAILED_INJECTION_TIMEOUT
+ } else {
+ RESTORE_TIMEOUT
+ };
+ if now.duration_since(state.published_at) >= deadline {
+ return WaitDecision::Finish;
+ }
+ WaitDecision::KeepWaiting
+}
+
+/// Modifier hold for the receipt-sequenced chord, kept at parity with the
+/// legacy path (100ms) for the beta: that hold was added in #165 because real
+/// users' systems dropped chords released too quickly, and the beta should
+/// validate the receipt mechanism without changing a second variable.
+///
+/// Once receipts are proven in the field this becomes a safe tuning knob — a
+/// chord the target never recognizes produces no receipt and is logged ("no
+/// read within timeout") rather than failing silently, so a shorter hold
+/// (measured working at 10ms on a fast machine, cutting visible latency from
+/// ~110ms to ~20ms) can be tried as its own experiment later.
+const CHORD_HOLD_MS: u64 = 100;
+
+/// Sends the platform paste chord for the configured method.
+pub(crate) fn send_chord(
+ enigo: &mut enigo::Enigo,
+ paste_method: &crate::settings::PasteMethod,
+) -> Result<(), String> {
+ use crate::settings::PasteMethod;
+ match paste_method {
+ PasteMethod::CtrlV => crate::input::send_paste_ctrl_v(enigo, CHORD_HOLD_MS),
+ PasteMethod::CtrlShiftV => crate::input::send_paste_ctrl_shift_v(enigo, CHORD_HOLD_MS),
+ PasteMethod::ShiftInsert => crate::input::send_paste_shift_insert(enigo, CHORD_HOLD_MS),
+ other => Err(format!(
+ "Invalid paste method for clipboard paste: {:?}",
+ other
+ )),
+ }
+}
+
+/// Attempts the receipt-sequenced paste. Returns `Err` before anything has
+/// been published when the platform transaction cannot start, in which case
+/// the caller should fall back to the legacy paste path. On `Ok`, publishing
+/// and chord injection have completed and the guarded restore (plus
+/// auto-submit) finishes asynchronously.
+#[cfg(any(target_os = "macos", target_os = "windows"))]
+pub(crate) fn try_reliable_paste(
+ text: &str,
+ app_handle: &tauri::AppHandle,
+ paste_method: &crate::settings::PasteMethod,
+ enigo: &mut enigo::Enigo,
+ auto_submit: bool,
+ auto_submit_key: crate::settings::AutoSubmitKey,
+ clipboard_handling: crate::settings::ClipboardHandling,
+) -> Result<(), String> {
+ platform::run(
+ text,
+ app_handle,
+ paste_method,
+ enigo,
+ auto_submit,
+ auto_submit_key,
+ clipboard_handling,
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn state_after_publish(published_ago: Duration) -> TxState {
+ let mut s = TxState::new();
+ s.published_at = Instant::now() - published_ago;
+ s
+ }
+
+ #[test]
+ fn keeps_waiting_without_receipt_within_timeout() {
+ let s = state_after_publish(Duration::from_millis(100));
+ assert!(matches!(
+ evaluate(&s, Instant::now()),
+ WaitDecision::KeepWaiting
+ ));
+ }
+
+ #[test]
+ fn finishes_after_quiet_period_once_read() {
+ let mut s = state_after_publish(Duration::from_millis(300));
+ s.injected_at = Some(Instant::now() - Duration::from_millis(250));
+ s.receipts.push(Instant::now() - QUIET_PERIOD);
+ assert!(matches!(evaluate(&s, Instant::now()), WaitDecision::Finish));
+ }
+
+ #[test]
+ fn waits_through_quiet_period_after_recent_read() {
+ let mut s = state_after_publish(Duration::from_millis(300));
+ s.injected_at = Some(Instant::now() - Duration::from_millis(100));
+ s.receipts.push(Instant::now() - Duration::from_millis(50));
+ assert!(matches!(
+ evaluate(&s, Instant::now()),
+ WaitDecision::KeepWaiting
+ ));
+ }
+
+ #[test]
+ fn pre_injection_receipt_does_not_count() {
+ let mut s = state_after_publish(Duration::from_millis(300));
+ s.receipts.push(Instant::now() - Duration::from_millis(200));
+ s.injected_at = Some(Instant::now() - Duration::from_millis(100));
+ assert!(!s.any_receipt_after_injection());
+ assert!(matches!(
+ evaluate(&s, Instant::now()),
+ WaitDecision::KeepWaiting
+ ));
+ }
+
+ #[test]
+ fn finishes_on_timeout_without_receipt() {
+ let s = state_after_publish(RESTORE_TIMEOUT);
+ assert!(matches!(evaluate(&s, Instant::now()), WaitDecision::Finish));
+ }
+
+ #[test]
+ fn failed_injection_uses_short_timeout() {
+ let mut s = state_after_publish(FAILED_INJECTION_TIMEOUT);
+ s.injection_failed = true;
+ assert!(matches!(evaluate(&s, Instant::now()), WaitDecision::Finish));
+ }
+
+ #[test]
+ fn ownership_loss_finishes_immediately() {
+ let mut s = state_after_publish(Duration::from_millis(10));
+ s.ownership_lost = true;
+ assert!(matches!(evaluate(&s, Instant::now()), WaitDecision::Finish));
+ }
+}
diff --git a/src-tauri/src/paste_tx/windows.rs b/src-tauri/src/paste_tx/windows.rs
new file mode 100644
index 00000000..4c090919
--- /dev/null
+++ b/src-tauri/src/paste_tx/windows.rs
@@ -0,0 +1,613 @@
+//! Windows reliable paste.
+//!
+//! Publishes the transcript as a *delayed-render* clipboard format
+//! (`SetClipboardData(CF_UNICODETEXT, NULL)`) owned by a hidden message-only
+//! window. Windows sends the owner `WM_RENDERFORMAT` when a consumer actually
+//! requests the data — that message is the read receipt. The previous
+//! clipboard contents (snapshotted with full format fidelity) are restored
+//! once receipts go quiet (see `paste_tx::evaluate`), guarded by the clipboard
+//! sequence number so we never clobber a newer user copy.
+//!
+//! Threading: clipboard ownership and delayed rendering are per-thread and
+//! need a message pump, so the whole transaction lives on a dedicated worker
+//! thread. The calling thread only sends the paste chord once the worker
+//! signals the transcript is published, then returns; the wait, guarded
+//! restore and auto-submit all finish on the worker.
+
+use std::sync::{mpsc::Sender, Arc, Mutex, Once};
+use std::thread;
+use std::time::Instant;
+
+use log::{error, info, warn};
+use tauri::Manager;
+use windows::core::{w, PCWSTR};
+use windows::Win32::Foundation::{HANDLE, HGLOBAL, HINSTANCE, HWND, LPARAM, LRESULT, WPARAM};
+
+use super::{evaluate, send_chord, TxState, WaitDecision};
+use crate::clipboard::send_return_key;
+use crate::input::EnigoState;
+use crate::settings::{AutoSubmitKey, ClipboardHandling, PasteMethod};
+use windows::Win32::Foundation::GlobalFree;
+use windows::Win32::System::DataExchange::{
+ CloseClipboard, EmptyClipboard, EnumClipboardFormats, GetClipboardData, GetClipboardOwner,
+ GetClipboardSequenceNumber, OpenClipboard, RegisterClipboardFormatW, SetClipboardData,
+};
+use windows::Win32::System::LibraryLoader::GetModuleHandleW;
+use windows::Win32::System::Memory::{
+ GlobalAlloc, GlobalLock, GlobalSize, GlobalUnlock, GMEM_MOVEABLE,
+};
+use windows::Win32::System::Ole::{
+ CF_BITMAP, CF_DSPBITMAP, CF_DSPENHMETAFILE, CF_DSPMETAFILEPICT, CF_DSPTEXT, CF_ENHMETAFILE,
+ CF_OWNERDISPLAY, CF_PALETTE, CF_UNICODETEXT,
+};
+use windows::Win32::UI::WindowsAndMessaging::{
+ CopyImage, CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW, GetMessageW,
+ GetWindowLongPtrW, KillTimer, PostQuitMessage, RegisterClassW, SetTimer, SetWindowLongPtrW,
+ GDI_IMAGE_TYPE, GWLP_USERDATA, HWND_MESSAGE, IMAGE_FLAGS, MSG, WINDOW_EX_STYLE, WINDOW_STYLE,
+ WM_DESTROYCLIPBOARD, WM_RENDERALLFORMATS, WM_RENDERFORMAT, WM_TIMER, WNDCLASSW,
+};
+
+const CLASS_NAME: PCWSTR = w!("HandyPasteTxWindow");
+const TIMER_ID: usize = 1;
+const TIMER_INTERVAL_MS: u32 = 25;
+/// Skip clipboard formats larger than this when snapshotting.
+const MAX_FORMAT_BYTES: usize = 64 * 1024 * 1024;
+
+const IMAGE_BITMAP_TYPE: GDI_IMAGE_TYPE = GDI_IMAGE_TYPE(0);
+const LR_CREATEDIBSECTION_FLAG: IMAGE_FLAGS = IMAGE_FLAGS(0x2000);
+
+struct SavedFormat {
+ format: u32,
+ data: Vec<u8>,
+}
+
+pub(super) struct WinTxShared {
+ state: Mutex<TxState>,
+ text: String,
+ snapshot: Mutex<Vec<SavedFormat>>,
+ /// Copied HBITMAP (as raw usize), restored via SetClipboardData.
+ saved_bitmap: Mutex<Option<usize>>,
+ sequence: Mutex<u32>,
+ app_handle: tauri::AppHandle,
+ auto_submit: bool,
+ auto_submit_key: AutoSubmitKey,
+ /// ClipboardHandling::CopyToClipboard — settle by leaving the transcript
+ /// on the clipboard as plain text instead of restoring the snapshot.
+ preserve_transcript: bool,
+}
+
+/// The transaction currently holding the clipboard, if any. A new
+/// transaction settles it before snapshotting (see `flush_pending`).
+static PENDING: Mutex<Option<Arc<WinTxShared>>> = Mutex::new(None);
+
+fn wide(s: &str) -> Vec<u16> {
+ s.encode_utf16().chain(std::iter::once(0)).collect()
+}
+
+unsafe fn shared_ptr(hwnd: HWND) -> *const WinTxShared {
+ GetWindowLongPtrW(hwnd, GWLP_USERDATA) as *const WinTxShared
+}
+
+/// Sends the auto-submit Enter. Uses `try_lock` because the paste caller may
+/// currently hold the enigo lock while waiting for this worker.
+fn send_auto_submit(shared: &WinTxShared) {
+ {
+ let mut st = match shared.state.lock() {
+ Ok(st) => st,
+ Err(_) => return,
+ };
+ if st.auto_submit_sent {
+ return;
+ }
+ st.auto_submit_sent = true;
+ }
+ if let Some(enigo_state) = shared.app_handle.try_state::<EnigoState>() {
+ match enigo_state.0.try_lock() {
+ Ok(mut enigo) => {
+ let _ = send_return_key(&mut enigo, shared.auto_submit_key);
+ }
+ Err(_) => warn!("[reliable-paste] skipping auto-submit: input state busy"),
+ }
+ }
+}
+
+/// Renders the promised transcript into the clipboard, which must already be
+/// open: the system opens it on our behalf for WM_RENDERFORMAT; every other
+/// caller has to wrap this in OpenClipboard/CloseClipboard itself.
+unsafe fn render_text(shared: &WinTxShared) {
+ let wide_text: Vec<u16> = shared
+ .text
+ .encode_utf16()
+ .chain(std::iter::once(0))
+ .collect();
+ let Ok(hg) = GlobalAlloc(GMEM_MOVEABLE, wide_text.len() * 2) else {
+ return;
+ };
+ let ptr = GlobalLock(hg) as *mut u16;
+ if ptr.is_null() {
+ let _ = GlobalFree(Some(hg));
+ return;
+ }
+ std::ptr::copy_nonoverlapping(wide_text.as_ptr(), ptr, wide_text.len());
+ let _ = GlobalUnlock(hg);
+ if SetClipboardData(CF_UNICODETEXT.0 as u32, Some(HANDLE(hg.0))).is_err() {
+ let _ = GlobalFree(Some(hg));
+ }
+}
+
+unsafe extern "system" fn paste_wnd_proc(
+ hwnd: HWND,
+ msg: u32,
+ wparam: WPARAM,
+ lparam: LPARAM,
+) -> LRESULT {
+ let shared = shared_ptr(hwnd);
+ match msg {
+ WM_RENDERFORMAT => {
+ if !shared.is_null() {
+ let shared = &*shared;
+ if let Ok(mut st) = shared.state.lock() {
+ st.record_receipt(Instant::now());
+ }
+ if wparam.0 as u32 == CF_UNICODETEXT.0 as u32 {
+ render_text(shared);
+ }
+ }
+ LRESULT(0)
+ }
+ WM_RENDERALLFORMATS => {
+ // Sent when the window is destroyed while an unrendered promise is
+ // still on the clipboard — not a consumer read, so no receipt.
+ // Unlike WM_RENDERFORMAT the system does not open the clipboard on
+ // our behalf here: open it and confirm we still own it first.
+ if !shared.is_null() {
+ let shared = &*shared;
+ if OpenClipboard(Some(hwnd)).is_ok() {
+ if GetClipboardOwner()
+ .map(|owner| owner == hwnd)
+ .unwrap_or(false)
+ {
+ render_text(shared);
+ }
+ let _ = CloseClipboard();
+ }
+ }
+ LRESULT(0)
+ }
+ WM_DESTROYCLIPBOARD => {
+ if !shared.is_null() {
+ if let Ok(mut st) = (&*shared).state.lock() {
+ st.ownership_lost = true;
+ }
+ }
+ LRESULT(0)
+ }
+ WM_TIMER => {
+ if !shared.is_null() {
+ on_timer(hwnd, &*shared);
+ }
+ LRESULT(0)
+ }
+ _ => DefWindowProcW(hwnd, msg, wparam, lparam),
+ }
+}
+
+fn ensure_window_class(hinstance: HINSTANCE) {
+ static ONCE: Once = Once::new();
+ ONCE.call_once(|| {
+ let wc = WNDCLASSW {
+ lpfnWndProc: Some(paste_wnd_proc),
+ hInstance: hinstance,
+ lpszClassName: CLASS_NAME,
+ ..Default::default()
+ };
+ unsafe {
+ RegisterClassW(&wc);
+ }
+ });
+}
+
+/// If a previous transaction is still holding the clipboard, settle it now so
+/// the snapshot below captures the user's original clipboard content. The
+/// previous worker observes `cancelled` on its next timer tick and tears down
+/// without restoring.
+fn flush_pending() {
+ let previous = match PENDING.lock() {
+ Ok(mut slot) => slot.take(),
+ Err(_) => None,
+ };
+ let Some(previous) = previous else {
+ return;
+ };
+ let receipt = {
+ let mut st = match previous.state.lock() {
+ Ok(st) => st,
+ Err(_) => return,
+ };
+ st.cancelled = true;
+ st.any_receipt_after_injection()
+ };
+ if previous.auto_submit && receipt {
+ send_auto_submit(&previous);
+ }
+ let sequence = *previous.sequence.lock().unwrap();
+ let still_ours = unsafe { GetClipboardSequenceNumber() } == sequence;
+ if still_ours {
+ unsafe { settle_clipboard(&previous) };
+ }
+}
+
+/// Settle-time clipboard handling once we know we still own the clipboard:
+/// restore the snapshot, or — for ClipboardHandling::CopyToClipboard — replace
+/// the concealed promise with plain transcript text, so clipboard history and
+/// managers record it and it survives this transaction's window going away.
+unsafe fn settle_clipboard(shared: &WinTxShared) {
+ if !shared.preserve_transcript {
+ restore_snapshot(shared);
+ return;
+ }
+ if OpenClipboard(None).is_err() {
+ warn!("[reliable-paste] could not open clipboard to leave transcript");
+ return;
+ }
+ let _ = EmptyClipboard();
+ render_text(shared);
+ let _ = CloseClipboard();
+ info!("[reliable-paste] left transcript on clipboard as plain text");
+}
+
+/// Restores the snapshotted clipboard contents. Safe to call from any thread.
+unsafe fn restore_snapshot(shared: &WinTxShared) {
+ if OpenClipboard(None).is_err() {
+ warn!("[reliable-paste] could not open clipboard to restore");
+ return;
+ }
+ let _ = EmptyClipboard();
+ if let Ok(formats) = shared.snapshot.lock() {
+ for saved in formats.iter() {
+ if saved.data.is_empty() {
+ continue;
+ }
+ let Ok(hg) = GlobalAlloc(GMEM_MOVEABLE, saved.data.len()) else {
+ continue;
+ };
+ let ptr = GlobalLock(hg) as *mut u8;
+ if ptr.is_null() {
+ let _ = GlobalFree(Some(hg));
+ continue;
+ }
+ std::ptr::copy_nonoverlapping(saved.data.as_ptr(), ptr, saved.data.len());
+ let _ = GlobalUnlock(hg);
+ // SetClipboardData takes ownership of the handle on success.
+ if SetClipboardData(saved.format, Some(HANDLE(hg.0))).is_err() {
+ let _ = GlobalFree(Some(hg));
+ }
+ }
+ }
+ if let Ok(mut bitmap) = shared.saved_bitmap.lock() {
+ if let Some(raw) = bitmap.take() {
+ let _ = SetClipboardData(CF_BITMAP.0 as u32, Some(HANDLE(raw as *mut _)));
+ }
+ }
+ let _ = CloseClipboard();
+ info!("[reliable-paste] restored previous clipboard");
+}
+
+unsafe fn snapshot_clipboard(hwnd: HWND, shared: &WinTxShared) -> Result<(), String> {
+ OpenClipboard(Some(hwnd)).map_err(|e| format!("OpenClipboard failed: {e}"))?;
+ let mut formats = Vec::new();
+ let mut format = 0u32;
+ loop {
+ format = EnumClipboardFormats(format);
+ if format == 0 {
+ break;
+ }
+ if format == CF_BITMAP.0 as u32 {
+ // GDI object, not global memory: duplicate the handle instead.
+ if let Ok(handle) = GetClipboardData(CF_BITMAP.0 as u32) {
+ if let Ok(copy) =
+ CopyImage(handle, IMAGE_BITMAP_TYPE, 0, 0, LR_CREATEDIBSECTION_FLAG)
+ {
+ if let Ok(mut slot) = shared.saved_bitmap.lock() {
+ *slot = Some(copy.0 as usize);
+ }
+ }
+ }
+ continue;
+ }
+ // Formats whose handles are not plain global memory cannot be
+ // byte-copied; skipping them matches what the legacy path restored.
+ if format == CF_ENHMETAFILE.0 as u32
+ || format == CF_DSPENHMETAFILE.0 as u32
+ || format == CF_DSPBITMAP.0 as u32
+ || format == CF_DSPMETAFILEPICT.0 as u32
+ || format == CF_DSPTEXT.0 as u32
+ || format == CF_OWNERDISPLAY.0 as u32
+ || format == CF_PALETTE.0 as u32
+ {
+ continue;
+ }
+ if let Ok(handle) = GetClipboardData(format) {
+ let hg = HGLOBAL(handle.0);
+ let size = GlobalSize(hg);
+ if size == 0 || size > MAX_FORMAT_BYTES {
+ continue;
+ }
+ let ptr = GlobalLock(hg) as *const u8;
+ if ptr.is_null() {
+ continue;
+ }
+ let data = std::slice::from_raw_parts(ptr, size).to_vec();
+ let _ = GlobalUnlock(hg);
+ formats.push(SavedFormat { format, data });
+ }
+ }
+ let _ = CloseClipboard();
+ if let Ok(mut slot) = shared.snapshot.lock() {
+ *slot = formats;
+ }
+ Ok(())
+}
+
+/// Publishes the transcript as a delayed-render promise plus clipboard
+/// history / cloud / monitoring opt-out markers (the same formats Chrome uses
+/// for Incognito copies). Returns the new clipboard sequence number.
+unsafe fn publish(hwnd: HWND) -> Result<u32, String> {
+ OpenClipboard(Some(hwnd)).map_err(|e| format!("OpenClipboard failed: {e}"))?;
+ let published = publish_formats();
+ let closed = CloseClipboard();
+ published?;
+ closed.map_err(|e| format!("CloseClipboard failed: {e}"))?;
+ Ok(GetClipboardSequenceNumber())
+}
+
+/// Everything `publish` does while the clipboard is open, split out so
+/// `publish` closes the clipboard on every path — bailing out while holding it
+/// open (and possibly already emptied) would strand the clipboard and leave
+/// the legacy fallback snapshotting nothing.
+unsafe fn publish_formats() -> Result<(), String> {
+ EmptyClipboard().map_err(|e| format!("EmptyClipboard failed: {e}"))?;
+
+ for (name, value) in [
+ ("ExcludeClipboardContentFromMonitorProcessing", 1u32),
+ ("CanIncludeInClipboardHistory", 0u32),
+ ("CanUploadToCloudClipboard", 0u32),
+ ] {
+ let name_wide = wide(name);
+ let format = RegisterClipboardFormatW(PCWSTR(name_wide.as_ptr()));
+ if format == 0 {
+ continue;
+ }
+ if let Ok(hg) = GlobalAlloc(GMEM_MOVEABLE, std::mem::size_of::<u32>()) {
+ let ptr = GlobalLock(hg) as *mut u32;
+ if !ptr.is_null() {
+ *ptr = value;
+ let _ = GlobalUnlock(hg);
+ if SetClipboardData(format, Some(HANDLE(hg.0))).is_err() {
+ let _ = GlobalFree(Some(hg));
+ }
+ } else {
+ let _ = GlobalFree(Some(hg));
+ }
+ }
+ }
+
+ // NULL handle = delayed rendering: we are only asked for the data (via
+ // WM_RENDERFORMAT) when a consumer actually reads it.
+ SetClipboardData(CF_UNICODETEXT.0 as u32, None)
+ .map_err(|e| format!("SetClipboardData failed: {e}"))?;
+ Ok(())
+}
+
+fn on_timer(_hwnd: HWND, shared: &WinTxShared) {
+ let now = Instant::now();
+ let finish = {
+ let mut st = match shared.state.lock() {
+ Ok(st) => st,
+ Err(_) => return,
+ };
+ if st.cancelled {
+ true
+ } else {
+ match evaluate(&st, now) {
+ WaitDecision::KeepWaiting => false,
+ WaitDecision::Finish => {
+ st.cancelled = true;
+ true
+ }
+ }
+ }
+ };
+ if !finish {
+ return;
+ }
+
+ let (receipt, ownership_lost, injection_failed) = {
+ let st = match shared.state.lock() {
+ Ok(st) => st,
+ Err(_) => return,
+ };
+ (
+ st.any_receipt_after_injection(),
+ st.ownership_lost,
+ st.injection_failed,
+ )
+ };
+ if ownership_lost {
+ info!("[reliable-paste] settling: clipboard ownership lost");
+ } else if receipt {
+ info!("[reliable-paste] settling: reads went quiet");
+ } else if injection_failed {
+ info!("[reliable-paste] settling: chord injection failed, restoring quickly");
+ } else {
+ info!("[reliable-paste] settling: no read within timeout, restoring anyway");
+ }
+
+ // Auto-submit only once the target demonstrably read the transcript;
+ // pressing Enter after an unconfirmed paste could submit stale content.
+ if shared.auto_submit && receipt {
+ send_auto_submit(shared);
+ }
+
+ let sequence = *shared.sequence.lock().unwrap();
+ let still_ours = !ownership_lost && unsafe { GetClipboardSequenceNumber() } == sequence;
+ if still_ours {
+ unsafe { settle_clipboard(shared) };
+ } else {
+ info!("[reliable-paste] clipboard changed externally; leaving it untouched");
+ }
+
+ if let Ok(mut slot) = PENDING.lock() {
+ let is_us = slot
+ .as_ref()
+ .map(|pending| Arc::as_ptr(pending) as *const WinTxShared == shared as *const _)
+ .unwrap_or(false);
+ if is_us {
+ *slot = None;
+ }
+ }
+
+ unsafe {
+ PostQuitMessage(0);
+ }
+}
+
+unsafe fn destroy_window_and_shared(hwnd: HWND) {
+ let ptr = shared_ptr(hwnd);
+ let _ = DestroyWindow(hwnd);
+ if !ptr.is_null() {
+ drop(Arc::from_raw(ptr));
+ }
+}
+
+fn pump_thread(shared: Arc<WinTxShared>, ready: Sender<Result<(), String>>) {
+ unsafe {
+ // Settle any previous transaction first so the snapshot captures the
+ // user's original clipboard, not the previous transcript.
+ flush_pending();
+
+ let hinstance = match GetModuleHandleW(PCWSTR::null()) {
+ Ok(hmodule) => HINSTANCE(hmodule.0),
+ Err(e) => {
+ let _ = ready.send(Err(format!("GetModuleHandle failed: {e}")));
+ return;
+ }
+ };
+ ensure_window_class(hinstance);
+
+ let hwnd = match CreateWindowExW(
+ WINDOW_EX_STYLE::default(),
+ CLASS_NAME,
+ w!("HandyPasteTx"),
+ WINDOW_STYLE::default(),
+ 0,
+ 0,
+ 0,
+ 0,
+ Some(HWND_MESSAGE),
+ None,
+ Some(hinstance),
+ None,
+ ) {
+ Ok(hwnd) => hwnd,
+ Err(e) => {
+ let _ = ready.send(Err(format!("CreateWindowEx failed: {e}")));
+ return;
+ }
+ };
+ SetWindowLongPtrW(
+ hwnd,
+ GWLP_USERDATA,
+ Arc::into_raw(shared.clone()) as *const _ as isize,
+ );
+
+ let published = match snapshot_clipboard(hwnd, &shared) {
+ Ok(()) => match publish(hwnd) {
+ Ok(sequence) => Ok(sequence),
+ Err(e) => {
+ // publish may have emptied the clipboard before failing;
+ // put the snapshot back so the legacy fallback's own
+ // snapshot captures the user's clipboard, not an empty one.
+ restore_snapshot(&shared);
+ Err(e)
+ }
+ },
+ Err(e) => Err(e),
+ };
+ let sequence = match published {
+ Ok(sequence) => sequence,
+ Err(e) => {
+ destroy_window_and_shared(hwnd);
+ let _ = ready.send(Err(e));
+ return;
+ }
+ };
+ *shared.sequence.lock().unwrap() = sequence;
+ shared.state.lock().unwrap().published_at = Instant::now();
+ if let Ok(mut slot) = PENDING.lock() {
+ *slot = Some(shared.clone());
+ }
+ let _ = SetTimer(Some(hwnd), TIMER_ID, TIMER_INTERVAL_MS, None);
+ let _ = ready.send(Ok(()));
+
+ let mut msg = MSG::default();
+ while GetMessageW(&mut msg, None, 0, 0).as_bool() {
+ let _ = DispatchMessageW(&msg);
+ }
+
+ let _ = KillTimer(Some(hwnd), TIMER_ID);
+ destroy_window_and_shared(hwnd);
+ }
+}
+
+pub(super) fn run(
+ text: &str,
+ app_handle: &tauri::AppHandle,
+ paste_method: &PasteMethod,
+ enigo: &mut enigo::Enigo,
+ auto_submit: bool,
+ auto_submit_key: AutoSubmitKey,
+ clipboard_handling: ClipboardHandling,
+) -> Result<(), String> {
+ let shared = Arc::new(WinTxShared {
+ state: Mutex::new(TxState::new()),
+ text: text.to_string(),
+ snapshot: Mutex::new(Vec::new()),
+ saved_bitmap: Mutex::new(None),
+ sequence: Mutex::new(0),
+ app_handle: app_handle.clone(),
+ auto_submit,
+ auto_submit_key,
+ preserve_transcript: clipboard_handling == ClipboardHandling::CopyToClipboard,
+ });
+
+ let (ready_tx, ready_rx) = std::sync::mpsc::channel();
+ let shared_for_pump = shared.clone();
+ thread::spawn(move || pump_thread(shared_for_pump, ready_tx));
+
+ // Wait until the transcript is actually published (or the worker reports
+ // why it could not) before injecting the chord.
+ match ready_rx.recv() {
+ Ok(Ok(())) => {}
+ Ok(Err(e)) => return Err(e),
+ Err(_) => return Err("reliable paste worker died before publishing".to_string()),
+ }
+ info!("[reliable-paste] published transcript (delayed render)");
+
+ // Mark injection *before* sending: enigo holds the chord for ~100ms and a
+ // fast target may legitimately read while the chord is still held.
+ shared.state.lock().unwrap().injected_at = Some(Instant::now());
+ match send_chord(enigo, paste_method) {
+ Ok(()) => {
+ info!("[reliable-paste] paste chord sent ({paste_method:?})");
+ }
+ Err(e) => {
+ // Keep the transaction alive: the worker restores the clipboard
+ // after the short failed-injection timeout.
+ shared.state.lock().unwrap().injection_failed = true;
+ error!("[reliable-paste] failed to send paste chord: {e}");
+ }
+ }
+
+ Ok(())
+}
diff --git a/src-tauri/src/settings.rs b/src-tauri/src/settings.rs
index 5fa6279f..7cf32fec 100644
--- a/src-tauri/src/settings.rs
+++ b/src-tauri/src/settings.rs
@@ -443,6 +443,11 @@ pub struct AppSettings {
pub paste_delay_ms: u64,
#[serde(default = "default_paste_delay_after_ms")]
pub paste_delay_after_ms: u64,
+ /// Debug-gated ("beta") receipt-sequenced paste: restore the clipboard only
+ /// after the target app actually reads the transcript, instead of after a
+ /// fixed delay. See `paste_tx`. macOS and Windows only.
+ #[serde(default)]
+ pub reliable_paste: bool,
#[serde(default = "default_typing_tool")]
pub typing_tool: TypingTool,
#[serde(default)]
@@ -885,6 +890,7 @@ pub fn get_default_settings() -> AppSettings {
show_tray_icon: default_show_tray_icon(),
paste_delay_ms: default_paste_delay_ms(),
paste_delay_after_ms: default_paste_delay_after_ms(),
+ reliable_paste: false,
typing_tool: default_typing_tool(),
external_script_path: None,
custom_filler_words: None,
diff --git a/src-tauri/src/shortcut/mod.rs b/src-tauri/src/shortcut/mod.rs
index 8fb2bb40..d69bc0ea 100644
--- a/src-tauri/src/shortcut/mod.rs
+++ b/src-tauri/src/shortcut/mod.rs
@@ -855,6 +855,15 @@ pub fn change_paste_delay_after_ms_setting(app: AppHandle, ms: u64) -> Result<()
Ok(())
}
+#[tauri::command]
+#[specta::specta]
+pub fn change_reliable_paste_setting(app: AppHandle, enabled: bool) -> Result<(), String> {
+ let mut settings = settings::get_settings(&app);
+ settings.reliable_paste = enabled;
+ settings::write_settings(&app, settings);
+ Ok(())
+}
+
#[tauri::command]
#[specta::specta]
pub fn change_paste_method_setting(app: AppHandle, method: String) -> Result<(), String> {
diff --git a/src/bindings.ts b/src/bindings.ts
index e7ef242e..e850f733 100644
--- a/src/bindings.ts
+++ b/src/bindings.ts
@@ -149,6 +149,14 @@ async changePasteDelayAfterMsSetting(ms: number) : Promise<Result<null, string>>
else return { status: "error", error: e as any };
}
},
+async changeReliablePasteSetting(enabled: boolean) : Promise<Result<null, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("change_reliable_paste_setting", { enabled }) };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
async changePasteMethodSetting(method: string) : Promise<Result<null, string>> {
try {
return { status: "ok", data: await TAURI_INVOKE("change_paste_method_setting", { method }) };
@@ -916,7 +924,13 @@ bindings?: Partial<{ [key in string]: ShortcutBinding }>; push_to_talk?: boolean
* upgrading from before this key existed are blanked by the migration so they
* see the current release's notes — see `apply_settings_migrations`.
*/
-whats_new_last_seen_version?: string; selected_model?: string; onboarding_completed?: boolean; always_on_microphone?: boolean; selected_microphone?: string | null; clamshell_microphone?: string | null; selected_output_device?: string | null; translate_to_english?: boolean; selected_language?: string; overlay_position?: OverlayPosition; debug_mode?: boolean; log_level?: LogLevel; custom_words?: string[]; model_unload_timeout?: ModelUnloadTimeout; word_correction_threshold?: number; history_limit?: number; recording_retention_period?: RecordingRetentionPeriod; paste_method?: PasteMethod; clipboard_handling?: ClipboardHandling; auto_submit?: boolean; auto_submit_key?: AutoSubmitKey; post_process_enabled?: boolean; post_process_provider_id?: string; post_process_providers?: PostProcessProvider[]; post_process_api_keys?: SecretMap; post_process_models?: Partial<{ [key in string]: string }>; post_process_prompts?: LLMPrompt[]; post_process_selected_prompt_id?: string | null; mute_while_recording?: boolean; append_trailing_space?: boolean; app_language?: string; theme?: Theme; experimental_enabled?: boolean; lazy_stream_close?: boolean; keyboard_implementation?: KeyboardImplementation; show_tray_icon?: boolean; paste_delay_ms?: number; paste_delay_after_ms?: number; typing_tool?: TypingTool; external_script_path?: string | null; custom_filler_words?: string[] | null; transcribe_accelerator?: TranscribeAcceleratorSetting; ort_accelerator?: OrtAcceleratorSetting; transcribe_gpu_device?: number; extra_recording_buffer_ms?: number; vad_enabled?: boolean;
+whats_new_last_seen_version?: string; selected_model?: string; onboarding_completed?: boolean; always_on_microphone?: boolean; selected_microphone?: string | null; clamshell_microphone?: string | null; selected_output_device?: string | null; translate_to_english?: boolean; selected_language?: string; overlay_position?: OverlayPosition; debug_mode?: boolean; log_level?: LogLevel; custom_words?: string[]; model_unload_timeout?: ModelUnloadTimeout; word_correction_threshold?: number; history_limit?: number; recording_retention_period?: RecordingRetentionPeriod; paste_method?: PasteMethod; clipboard_handling?: ClipboardHandling; auto_submit?: boolean; auto_submit_key?: AutoSubmitKey; post_process_enabled?: boolean; post_process_provider_id?: string; post_process_providers?: PostProcessProvider[]; post_process_api_keys?: SecretMap; post_process_models?: Partial<{ [key in string]: string }>; post_process_prompts?: LLMPrompt[]; post_process_selected_prompt_id?: string | null; mute_while_recording?: boolean; append_trailing_space?: boolean; app_language?: string; theme?: Theme; experimental_enabled?: boolean; lazy_stream_close?: boolean; keyboard_implementation?: KeyboardImplementation; show_tray_icon?: boolean; paste_delay_ms?: number; paste_delay_after_ms?: number;
+/**
+ * Debug-gated ("beta") receipt-sequenced paste: restore the clipboard only
+ * after the target app actually reads the transcript, instead of after a
+ * fixed delay. See `paste_tx`. macOS and Windows only.
+ */
+reliable_paste?: boolean; typing_tool?: TypingTool; external_script_path?: string | null; custom_filler_words?: string[] | null; transcribe_accelerator?: TranscribeAcceleratorSetting; ort_accelerator?: OrtAcceleratorSetting; transcribe_gpu_device?: number; extra_recording_buffer_ms?: number; vad_enabled?: boolean;
/**
* Which recording overlay to show: None / Minimal / Live. Streaming mode is
* not gated on this — that follows model capability. Migrated from the old
diff --git a/src/components/settings/debug/DebugSettings.tsx b/src/components/settings/debug/DebugSettings.tsx
index c3e1b339..dd65ae57 100644
--- a/src/components/settings/debug/DebugSettings.tsx
+++ b/src/components/settings/debug/DebugSettings.tsx
@@ -4,6 +4,7 @@ import { WordCorrectionThreshold } from "./WordCorrectionThreshold";
import { LogLevelSelector } from "./LogLevelSelector";
import { LiveLogViewer } from "./LiveLogViewer";
import { PasteDelay } from "./PasteDelay";
+import { ReliablePasteToggle } from "./ReliablePaste";
import { RecordingBuffer } from "./RecordingBuffer";
import { SettingsGroup } from "../../ui/SettingsGroup";
import { AlwaysOnMicrophone } from "../AlwaysOnMicrophone";
@@ -35,6 +36,7 @@ export const DebugSettings: React.FC = () => {
labelKey="settings.debug.pasteDelayAfter.title"
descriptionKey="settings.debug.pasteDelayAfter.description"
/>
+ <ReliablePasteToggle descriptionMode="tooltip" grouped={true} />
<RecordingBuffer descriptionMode="tooltip" grouped={true} />
<AlwaysOnMicrophone descriptionMode="tooltip" grouped={true} />
<ClamshellMicrophoneSelector descriptionMode="tooltip" grouped={true} />
diff --git a/src/components/settings/debug/ReliablePaste.tsx b/src/components/settings/debug/ReliablePaste.tsx
new file mode 100644
index 00000000..7dc9b0d8
--- /dev/null
+++ b/src/components/settings/debug/ReliablePaste.tsx
@@ -0,0 +1,36 @@
+import React from "react";
+import { useTranslation } from "react-i18next";
+import { ToggleSwitch } from "../../ui/ToggleSwitch";
+import { useSettings } from "../../../hooks/useSettings";
+import { useOsType } from "../../../hooks/useOsType";
+
+interface ReliablePasteToggleProps {
+ descriptionMode?: "inline" | "tooltip";
+ grouped?: boolean;
+}
+
+export const ReliablePasteToggle: React.FC<ReliablePasteToggleProps> = ({
+ descriptionMode = "tooltip",
+ grouped = false,
+}) => {
+ const { t } = useTranslation();
+ const { getSetting, updateSetting, isUpdating } = useSettings();
+ const osType = useOsType();
+
+ // The receipt-sequenced paste path is implemented for macOS and Windows.
+ if (osType !== "macos" && osType !== "windows") {
+ return null;
+ }
+
+ return (
+ <ToggleSwitch
+ checked={getSetting("reliable_paste") ?? false}
+ onChange={(enabled) => updateSetting("reliable_paste", enabled)}
+ isUpdating={isUpdating("reliable_paste")}
+ label={t("settings.debug.reliablePaste.title")}
+ description={t("settings.debug.reliablePaste.description")}
+ descriptionMode={descriptionMode}
+ grouped={grouped}
+ />
+ );
+};
diff --git a/src/i18n/locales/ar/translation.json b/src/i18n/locales/ar/translation.json
index 95597112..30c95c2e 100644
--- a/src/i18n/locales/ar/translation.json
+++ b/src/i18n/locales/ar/translation.json
@@ -504,6 +504,10 @@
"title": "تأخير اللصق (بعد)",
"description": "التأخير (بالمللي ثانية) بعد ضغطة مفتاح اللصق وقبل استعادة محتوى الحافظة السابق. قم بزيادته إذا تم لصق محتوى الحافظة القديم بدلاً من النص المُفرَّغ."
},
+ "reliablePaste": {
+ "title": "لصق موثوق (Beta)",
+ "description": "استعادة الحافظة فقط بعد أن يقرأ التطبيق المستهدف النص المُفرَّغ فعلياً، بدلاً من الاعتماد على تأخير ثابت. يهدف إلى إصلاح لصق محتوى الحافظة القديم عند وجود حمل على النظام. يتطلب طريقة لصق تعتمد على الحافظة؛ على macOS وWindows فقط."
+ },
"recordingBuffer": {
"title": "مخزن التسجيل الإضافي",
"description": "وقت إضافي (بالمللي ثانية) للاستمرار في التسجيل بعد تحرير المفتاح، لالتقاط الصوت المتبقي. 0 = لا مخزن إضافي."
diff --git a/src/i18n/locales/bg/translation.json b/src/i18n/locales/bg/translation.json
index 5b73ae81..c676b3d9 100644
--- a/src/i18n/locales/bg/translation.json
+++ b/src/i18n/locales/bg/translation.json
@@ -525,6 +525,10 @@
"title": "Забавяне при поставяне (след)",
"description": "Забавяне (в милисекунди) след клавиша за поставяне, преди възстановяване на предишния клипборд. Увеличете, ако вместо транскрипцията се поставя старото съдържание на клипборда."
},
+ "reliablePaste": {
+ "title": "Надеждно поставяне (Beta)",
+ "description": "Възстановява клипборда само след като целевото приложение действително прочете транскрипцията, вместо след фиксирано забавяне. Предназначено да отстрани поставянето на старото съдържание на клипборда при натоварване на системата. Изисква начин на поставяне през клипборда; само за macOS и Windows."
+ },
"recordingBuffer": {
"title": "Допълнителен буфер на записа",
"description": "Допълнително време (в милисекунди) за запис след пускане на клавиша, за да се улови краят на аудиото. 0 = без допълнителен буфер."
diff --git a/src/i18n/locales/cs/translation.json b/src/i18n/locales/cs/translation.json
index 0b7771fa..34205dea 100644
--- a/src/i18n/locales/cs/translation.json
+++ b/src/i18n/locales/cs/translation.json
@@ -525,6 +525,10 @@
"title": "Zpoždění vložení (po)",
"description": "Zpoždění (v milisekundách) po klávese pro vložení, před obnovením předchozí schránky. Zvyšte, pokud se místo přepisu vkládá starý obsah schránky."
},
+ "reliablePaste": {
+ "title": "Spolehlivé vložení (Beta)",
+ "description": "Obnoví schránku teprve poté, co cílová aplikace skutečně přečte přepis, místo po pevně daném zpoždění. Má odstranit vkládání starého obsahu schránky při zatížení systému. Vyžaduje způsob vložení přes schránku; pouze macOS a Windows."
+ },
"recordingBuffer": {
"title": "Extra vyrovnávací paměť nahrávání",
"description": "Extra čas (v milisekundách) pro pokračování nahrávání po uvolnění klávesy, pro zachycení zbývajícího zvuku. 0 = žádná extra vyrovnávací paměť."
diff --git a/src/i18n/locales/da/translation.json b/src/i18n/locales/da/translation.json
index 0f62ca4c..e32fc566 100644
--- a/src/i18n/locales/da/translation.json
+++ b/src/i18n/locales/da/translation.json
@@ -532,6 +532,10 @@
"title": "Forsinkelse af indsættelse (efter)",
"description": "Forsinkelse (i millisekunder) efter tastetrykket for indsætning, før din tidligere udklipsholder gendannes. Øg, hvis dit gamle udklipsholderindhold bliver indsat i stedet for transskriptionen."
},
+ "reliablePaste": {
+ "title": "Pålidelig indsættelse (Beta)",
+ "description": "Gendan først din udklipsholder, når målappen faktisk har læst transskriptionen, i stedet for efter en fast forsinkelse. Skal afhjælpe, at gammelt udklipsholderindhold indsættes, når systemet er belastet. Kræver en indsætningsmetode via udklipsholderen; kun macOS og Windows."
+ },
"recordingBuffer": {
"title": "Ekstra optagelsesbuffer",
"description": "Ekstra tid (i millisekunder) til at fortsætte optagelsen, efter du slipper tasten, for at fange efterfølgende lyd. 0 = ingen ekstra buffer."
diff --git a/src/i18n/locales/de/translation.json b/src/i18n/locales/de/translation.json
index 3b5c59fb..b5d4e56b 100644
--- a/src/i18n/locales/de/translation.json
+++ b/src/i18n/locales/de/translation.json
@@ -525,6 +525,10 @@
"title": "Einfügeverzögerung (nachher)",
"description": "Verzögerung (in Millisekunden) nach dem Einfüge-Tastendruck, bevor deine vorherige Zwischenablage wiederhergestellt wird. Erhöhe den Wert, wenn der alte Inhalt der Zwischenablage statt der Transkription eingefügt wird."
},
+ "reliablePaste": {
+ "title": "Zuverlässiges Einfügen (Beta)",
+ "description": "Die Zwischenablage erst wiederherstellen, wenn die Ziel-App die Transkription tatsächlich gelesen hat, statt nach einer festen Verzögerung. Soll verhindern, dass bei Systemlast der alte Inhalt der Zwischenablage eingefügt wird. Erfordert eine Einfügemethode über die Zwischenablage; nur macOS und Windows."
+ },
"recordingBuffer": {
"title": "Zusätzlicher Aufnahmepuffer",
"description": "Zusätzliche Zeit (in Millisekunden), um nach dem Loslassen der Taste weiter aufzunehmen, um nachlaufendes Audio zu erfassen. 0 = kein zusätzlicher Puffer."
diff --git a/src/i18n/locales/en/translation.json b/src/i18n/locales/en/translation.json
index 1c23046b..0b12d869 100644
--- a/src/i18n/locales/en/translation.json
+++ b/src/i18n/locales/en/translation.json
@@ -532,6 +532,10 @@
"title": "Paste Delay (After)",
"description": "Delay (in milliseconds) after the paste keystroke, before restoring your previous clipboard. Increase if your old clipboard content is being pasted instead of the transcription."
},
+ "reliablePaste": {
+ "title": "Reliable Paste (Beta)",
+ "description": "Restore the clipboard only after the target app actually reads the transcription, instead of after a fixed delay. Intended to fix old clipboard content being pasted under system load. Requires a clipboard paste method; macOS and Windows only."
+ },
"recordingBuffer": {
"title": "Extra Recording Buffer",
"description": "Extra time (in milliseconds) to keep recording after you release the key, to capture trailing audio. 0 = no extra buffer."
diff --git a/src/i18n/locales/es/translation.json b/src/i18n/locales/es/translation.json
index 58f215b6..dc132b41 100644
--- a/src/i18n/locales/es/translation.json
+++ b/src/i18n/locales/es/translation.json
@@ -525,6 +525,10 @@
"title": "Retraso de pegado (después)",
"description": "Retraso (en milisegundos) después de la pulsación de tecla de pegar, antes de restaurar el portapapeles anterior. Auméntelo si se pega el contenido antiguo del portapapeles en lugar de la transcripción."
},
+ "reliablePaste": {
+ "title": "Pegado fiable (Beta)",
+ "description": "Restaura el portapapeles solo después de que la aplicación de destino lea realmente la transcripción, en lugar de tras un retraso fijo. Pensado para corregir que se pegue el contenido antiguo del portapapeles cuando el sistema está cargado. Requiere un método de pegado por portapapeles; solo macOS y Windows."
+ },
"recordingBuffer": {
"title": "Búfer de grabación adicional",
"description": "Tiempo adicional (en milisegundos) para seguir grabando después de soltar la tecla, para capturar el audio restante. 0 = sin búfer adicional."
diff --git a/src/i18n/locales/fr/translation.json b/src/i18n/locales/fr/translation.json
index 55aa4672..cc16c5a4 100644
--- a/src/i18n/locales/fr/translation.json
+++ b/src/i18n/locales/fr/translation.json
@@ -525,6 +525,10 @@
"title": "Délai de collage (après)",
"description": "Délai (en millisecondes) après la touche de collage, avant la restauration de votre presse-papiers précédent. Augmentez si l'ancien contenu du presse-papiers est collé à la place de la transcription."
},
+ "reliablePaste": {
+ "title": "Collage fiable (Beta)",
+ "description": "Restaure le presse-papiers uniquement après que l'application cible a réellement lu la transcription, au lieu d'attendre un délai fixe. Vise à corriger le collage de l'ancien contenu du presse-papiers lorsque le système est chargé. Nécessite une méthode de collage par presse-papiers ; macOS et Windows uniquement."
+ },
"recordingBuffer": {
"title": "Tampon d'enregistrement supplémentaire",
"description": "Temps supplémentaire (en millisecondes) pour continuer l'enregistrement après avoir relâché la touche, pour capturer l'audio restant. 0 = pas de tampon supplémentaire."
diff --git a/src/i18n/locales/he/translation.json b/src/i18n/locales/he/translation.json
index 335b4e37..3acaee7a 100644
--- a/src/i18n/locales/he/translation.json
+++ b/src/i18n/locales/he/translation.json
@@ -525,6 +525,10 @@
"title": "השהיית הדבקה (אחרי)",
"description": "השהיה (במילישניות) לאחר צירוף ההדבקה, לפני שחזור הלוח הקודם. הגדל אם התוכן הישן של הלוח מודבק במקום התמלול."
},
+ "reliablePaste": {
+ "title": "הדבקה אמינה (Beta)",
+ "description": "שחזור הלוח רק אחרי שאפליקציית היעד קוראת בפועל את התמלול, במקום אחרי השהיה קבועה. נועד לתקן הדבקה של תוכן לוח ישן כשהמערכת עמוסה. דורש שיטת הדבקה דרך הלוח; ב-macOS וב-Windows בלבד."
+ },
"recordingBuffer": {
"title": "באפר הקלטה נוסף",
"description": "זמן נוסף (במילישניות) להמשך הקלטה אחרי שחרור המקש, כדי ללכוד סוף דיבור. 0 = בלי באפר נוסף."
diff --git a/src/i18n/locales/hi/translation.json b/src/i18n/locales/hi/translation.json
index b63c058e..23b871e9 100644
--- a/src/i18n/locales/hi/translation.json
+++ b/src/i18n/locales/hi/translation.json
@@ -532,6 +532,10 @@
"title": "पेस्ट में देरी (बाद में)",
"description": "पेस्ट कीस्ट्रोक के बाद और आपका पिछला क्लिपबोर्ड वापस लाने से पहले की देरी (मिलीसेकंड में). अगर ट्रांसक्रिप्शन की जगह आपके क्लिपबोर्ड का पुराना कॉन्टेंट पेस्ट हो रहा हो, तो इसे बढ़ाएं."
},
+ "reliablePaste": {
+ "title": "भरोसेमंद पेस्ट (Beta)",
+ "description": "क्लिपबोर्ड को तय देरी के बाद नहीं, बल्कि टारगेट ऐप असल में ट्रांसक्रिप्शन पढ़ लेने के बाद ही वापस लाएं. यह सिस्टम पर लोड होने के दौरान पुराना क्लिपबोर्ड कॉन्टेंट पेस्ट होने की समस्या ठीक करने के लिए है. इसके लिए क्लिपबोर्ड वाला पेस्ट तरीका ज़रूरी है; सिर्फ़ macOS और Windows पर."
+ },
"recordingBuffer": {
"title": "अतिरिक्त रिकॉर्डिंग बफ़र",
"description": "बटन छोड़ने के बाद भी रिकॉर्डिंग जारी रखने का अतिरिक्त समय (मिलीसेकंड में), ताकि आखिरी हिस्से का ऑडियो कैप्चर हो सके. 0 = कोई अतिरिक्त बफ़र नहीं."
diff --git a/src/i18n/locales/it/translation.json b/src/i18n/locales/it/translation.json
index ba261368..bf03bf63 100644
--- a/src/i18n/locales/it/translation.json
+++ b/src/i18n/locales/it/translation.json
@@ -525,6 +525,10 @@
"title": "Ritardo incolla (dopo)",
"description": "Ritardo (in millisecondi) dopo il tasto incolla, prima di ripristinare gli appunti precedenti. Aumentare se viene incollato il vecchio contenuto degli appunti invece della trascrizione."
},
+ "reliablePaste": {
+ "title": "Incolla affidabile (Beta)",
+ "description": "Ripristina gli appunti solo dopo che l'app di destinazione ha effettivamente letto la trascrizione, anziché dopo un ritardo fisso. Serve a risolvere l'incollaggio del vecchio contenuto degli appunti quando il sistema è sotto carico. Richiede un metodo di incollaggio tramite appunti; solo macOS e Windows."
+ },
"recordingBuffer": {
"title": "Buffer di registrazione extra",
"description": "Tempo extra (in millisecondi) per continuare a registrare dopo aver rilasciato il tasto, per catturare l'audio finale. 0 = nessun buffer extra."
diff --git a/src/i18n/locales/ja/translation.json b/src/i18n/locales/ja/translation.json
index b43b07f1..869681e8 100644
--- a/src/i18n/locales/ja/translation.json
+++ b/src/i18n/locales/ja/translation.json
@@ -525,6 +525,10 @@
"title": "貼り付け遅延(後)",
"description": "貼り付けキーを送信した後、以前のクリップボードを復元する前の遅延(ミリ秒)。文字起こしではなく古いクリップボードの内容が貼り付けられる場合は増やしてください。"
},
+ "reliablePaste": {
+ "title": "確実な貼り付け(Beta)",
+ "description": "固定の遅延ではなく、対象アプリが実際に文字起こしを読み取った後にのみクリップボードを復元します。システム負荷が高いときに古いクリップボードの内容が貼り付けられる問題を解決するための設定です。クリップボードを使う貼り付け方法が必要です。macOS と Windows のみ。"
+ },
"recordingBuffer": {
"title": "追加録音バッファ",
"description": "キーを離した後に録音を続ける追加時間(ミリ秒)。末尾の音声を捕捉するため。0 = 追加バッファなし。"
diff --git a/src/i18n/locales/ko/translation.json b/src/i18n/locales/ko/translation.json
index a41fa088..1851283b 100644
--- a/src/i18n/locales/ko/translation.json
+++ b/src/i18n/locales/ko/translation.json
@@ -520,6 +520,10 @@
"title": "붙여넣기 지연 (이후)",
"description": "붙여넣기 키 입력을 보낸 후 이전 클립보드를 복원하기 전의 지연 시간(밀리초). 전사된 텍스트 대신 이전 클립보드 내용이 붙여넣어지면 늘리세요."
},
+ "reliablePaste": {
+ "title": "안정적인 붙여넣기 (Beta)",
+ "description": "고정된 지연 시간이 아니라 대상 앱이 실제로 전사된 텍스트를 읽은 뒤에만 클립보드를 복원합니다. 시스템 부하가 높을 때 이전 클립보드 내용이 붙여넣어지는 문제를 해결하기 위한 옵션입니다. 클립보드를 사용하는 붙여넣기 방법이 필요하며 macOS와 Windows에서만 지원됩니다."
+ },
"recordingBuffer": {
"title": "추가 녹음 버퍼",
"description": "키를 놓은 후 추가로 녹음을 계속하는 시간(밀리초). 후행 오디오를 캡처하기 위함. 0 = 추가 버퍼 없음."
diff --git a/src/i18n/locales/ne/translation.json b/src/i18n/locales/ne/translation.json
index be89c29a..02711d8d 100644
--- a/src/i18n/locales/ne/translation.json
+++ b/src/i18n/locales/ne/translation.json
@@ -532,6 +532,10 @@
"title": "पेस्ट ढिलाइ (पछि)",
"description": "पेस्ट किस्ट्रोकपछि, तपाईंको अघिल्लो क्लिपबोर्ड पुनर्स्थापना गर्नुअघिको ढिलाइ (मिलिसेकेन्डमा)। ट्रान्सक्रिप्सनको सट्टा पुरानो क्लिपबोर्ड सामग्री पेस्ट भइरहेको छ भने बढाउनुहोस्।"
},
+ "reliablePaste": {
+ "title": "भरपर्दो पेस्ट (Beta)",
+ "description": "निश्चित ढिलाइपछि नभई, लक्षित एपले ट्रान्सक्रिप्सन साँच्चै पढेपछि मात्र क्लिपबोर्ड पुनर्स्थापना गर्नुहोस्। प्रणालीमा भार बढ्दा पुरानो क्लिपबोर्ड सामग्री पेस्ट हुने समस्या समाधान गर्न बनाइएको। क्लिपबोर्ड प्रयोग गर्ने पेस्ट विधि आवश्यक; macOS र Windows मा मात्र।"
+ },
"recordingBuffer": {
"title": "अतिरिक्त रेकर्डिङ बफर",
"description": "कि छोडेपछि अन्तिम अडियो समात्न रेकर्डिङ जारी राख्ने अतिरिक्त समय (मिलिसेकेन्डमा)। 0 = कुनै अतिरिक्त बफर छैन।"
diff --git a/src/i18n/locales/nl/translation.json b/src/i18n/locales/nl/translation.json
index 68f89f12..0f644a31 100644
--- a/src/i18n/locales/nl/translation.json
+++ b/src/i18n/locales/nl/translation.json
@@ -532,6 +532,10 @@
"title": "Plakvertraging (na)",
"description": "Vertraging (in milliseconden) na de plak-toetsaanslag, voordat je vorige klembord wordt hersteld. Verhoog dit als de oude klembordinhoud wordt geplakt in plaats van de transcriptie."
},
+ "reliablePaste": {
+ "title": "Betrouwbaar plakken (Beta)",
+ "description": "Herstel het klembord pas nadat de doelapp de transcriptie daadwerkelijk heeft gelezen, in plaats van na een vaste vertraging. Bedoeld om te verhelpen dat bij systeembelasting de oude klembordinhoud wordt geplakt. Vereist een plakmethode via het klembord; alleen macOS en Windows."
+ },
"recordingBuffer": {
"title": "Extra opnamebuffer",
"description": "Extra tijd (in milliseconden) om te blijven opnemen nadat je de toets loslaat, om naloopaudio op te vangen. 0 = geen extra buffer."
diff --git a/src/i18n/locales/pl/translation.json b/src/i18n/locales/pl/translation.json
index a3e0f9e6..4bcd7655 100644
--- a/src/i18n/locales/pl/translation.json
+++ b/src/i18n/locales/pl/translation.json
@@ -525,6 +525,10 @@
"title": "Opóźnienie wklejania (po)",
"description": "Opóźnienie (w milisekundach) po klawiszu wklejania, przed przywróceniem poprzedniego schowka. Zwiększ, jeśli zamiast transkrypcji wklejana jest stara zawartość schowka."
},
+ "reliablePaste": {
+ "title": "Niezawodne wklejanie (Beta)",
+ "description": "Przywracaj schowek dopiero po tym, jak docelowa aplikacja faktycznie odczyta transkrypcję, a nie po ustalonym opóźnieniu. Ma naprawić wklejanie starej zawartości schowka przy obciążeniu systemu. Wymaga metody wklejania przez schowek; tylko macOS i Windows."
+ },
"recordingBuffer": {
"title": "Dodatkowy bufor nagrywania",
"description": "Dodatkowy czas (w milisekundach) na kontynuowanie nagrywania po zwolnieniu klawisza, aby przechwycić końcowy dźwięk. 0 = brak dodatkowego bufora."
diff --git a/src/i18n/locales/pt/translation.json b/src/i18n/locales/pt/translation.json
index 1f2aca38..68de5028 100644
--- a/src/i18n/locales/pt/translation.json
+++ b/src/i18n/locales/pt/translation.json
@@ -525,6 +525,10 @@
"title": "Atraso de colagem (depois)",
"description": "Atraso (em milissegundos) após a tecla de colar, antes de restaurar a área de transferência anterior. Aumente se o conteúdo antigo da área de transferência estiver sendo colado em vez da transcrição."
},
+ "reliablePaste": {
+ "title": "Colagem confiável (Beta)",
+ "description": "Restaura a área de transferência somente depois que o aplicativo de destino realmente lê a transcrição, em vez de após um atraso fixo. Serve para corrigir a colagem do conteúdo antigo da área de transferência quando o sistema está sobrecarregado. Requer um método de colar via área de transferência; apenas macOS e Windows."
+ },
"recordingBuffer": {
"title": "Buffer de gravação extra",
"description": "Tempo extra (em milissegundos) para continuar gravando após soltar a tecla, para capturar áudio restante. 0 = sem buffer extra."
diff --git a/src/i18n/locales/ru/translation.json b/src/i18n/locales/ru/translation.json
index e5f5a3e9..6a05b781 100644
--- a/src/i18n/locales/ru/translation.json
+++ b/src/i18n/locales/ru/translation.json
@@ -525,6 +525,10 @@
"title": "Задержка вставки (после)",
"description": "Задержка (в миллисекундах) после нажатия клавиши вставки, перед восстановлением предыдущего буфера обмена. Увеличьте, если вместо транскрипции вставляется старое содержимое буфера обмена."
},
+ "reliablePaste": {
+ "title": "Надёжная вставка (Beta)",
+ "description": "Восстанавливать буфер обмена только после того, как целевое приложение действительно прочитает транскрипцию, а не по фиксированной задержке. Предназначено для устранения вставки старого содержимого буфера обмена при нагрузке на систему. Требуется метод вставки через буфер обмена; только macOS и Windows."
+ },
"recordingBuffer": {
"title": "Дополнительный буфер записи",
"description": "Дополнительное время (в миллисекундах) для продолжения записи после отпускания клавиши, чтобы захватить завершающий звук. 0 = без дополнительного буфера."
diff --git a/src/i18n/locales/sv/translation.json b/src/i18n/locales/sv/translation.json
index 0774ef2c..83fb39b1 100644
--- a/src/i18n/locales/sv/translation.json
+++ b/src/i18n/locales/sv/translation.json
@@ -525,6 +525,10 @@
"title": "Fördröjning vid klistra in (efter)",
"description": "Fördröjning (i millisekunder) efter tangenttryckningen för att klistra in, innan ditt tidigare urklipp återställs. Öka om det gamla urklippsinnehållet klistras in i stället för transkriptionen."
},
+ "reliablePaste": {
+ "title": "Tillförlitlig inklistring (Beta)",
+ "description": "Återställ urklipp först när målappen faktiskt har läst transkriptionen, i stället för efter en fast fördröjning. Avsett att åtgärda att det gamla urklippsinnehållet klistras in när systemet är belastat. Kräver en klistra-in-metod via urklipp; endast macOS och Windows."
+ },
"recordingBuffer": {
"title": "Extra inspelningsbuffert",
"description": "Extra tid (i millisekunder) för att fortsätta spela in efter att du släppt tangenten, för att fånga upp avslutande ljud. 0 = ingen extra buffert."
diff --git a/src/i18n/locales/tr/translation.json b/src/i18n/locales/tr/translation.json
index cbf3eae6..5865cd28 100644
--- a/src/i18n/locales/tr/translation.json
+++ b/src/i18n/locales/tr/translation.json
@@ -525,6 +525,10 @@
"title": "Yapıştırma gecikmesi (sonra)",
"description": "Yapıştırma tuşundan sonra, önceki panonuz geri yüklenmeden önceki gecikme (milisaniye cinsinden). Yazıya dökülen metin yerine eski pano içeriği yapıştırılıyorsa artırın."
},
+ "reliablePaste": {
+ "title": "Güvenilir yapıştırma (Beta)",
+ "description": "Panoyu sabit bir gecikmenin ardından değil, hedef uygulama yazıya dökülen metni gerçekten okuduktan sonra geri yükler. Sistem yükü altında eski pano içeriğinin yapıştırılması sorununu gidermeyi amaçlar. Pano üzerinden çalışan bir yapıştırma yöntemi gerektirir; yalnızca macOS ve Windows."
+ },
"recordingBuffer": {
"title": "Ekstra kayıt tamponu",
"description": "Tuşu bıraktıktan sonra arka plandaki sesi yakalamak için kaydı sürdürme süresi (milisaniye). 0 = ekstra tampon yok."
diff --git a/src/i18n/locales/uk/translation.json b/src/i18n/locales/uk/translation.json
index e33e73f1..da057f12 100644
--- a/src/i18n/locales/uk/translation.json
+++ b/src/i18n/locales/uk/translation.json
@@ -525,6 +525,10 @@
"title": "Затримка вставки (після)",
"description": "Затримка (у мілісекундах) після натискання клавіші вставки, перед відновленням попереднього буфера обміну. Збільшіть, якщо замість транскрипції вставляється старий вміст буфера обміну."
},
+ "reliablePaste": {
+ "title": "Надійна вставка (Beta)",
+ "description": "Відновлювати буфер обміну лише після того, як цільова програма справді прочитає транскрипцію, а не через фіксовану затримку. Призначено для усунення вставки старого вмісту буфера обміну під навантаженням на систему. Потрібен метод вставки через буфер обміну; лише macOS і Windows."
+ },
"recordingBuffer": {
"title": "Додатковий буфер запису",
"description": "Додатковий час (у мілісекундах) для продовження запису після відпускання клавіші, щоб захопити завершальний звук. 0 = без додаткового буфера."
diff --git a/src/i18n/locales/vi/translation.json b/src/i18n/locales/vi/translation.json
index a3943664..d1d2ce2f 100644
--- a/src/i18n/locales/vi/translation.json
+++ b/src/i18n/locales/vi/translation.json
@@ -525,6 +525,10 @@
"title": "Độ trễ dán (sau)",
"description": "Độ trễ (tính bằng mili giây) sau khi gửi phím dán, trước khi khôi phục bảng nhớ tạm trước đó. Tăng nếu nội dung bảng nhớ tạm cũ được dán thay vì bản chép lời."
},
+ "reliablePaste": {
+ "title": "Dán đáng tin cậy (Beta)",
+ "description": "Chỉ khôi phục bảng nhớ tạm sau khi ứng dụng đích thực sự đọc bản chép lời, thay vì sau một độ trễ cố định. Nhằm khắc phục việc nội dung bảng nhớ tạm cũ bị dán khi hệ thống bị tải nặng. Cần một phương thức dán qua bảng nhớ tạm; chỉ dành cho macOS và Windows."
+ },
"recordingBuffer": {
"title": "Bộ đệm ghi âm thêm",
"description": "Thời gian thêm (tính bằng mili giây) để tiếp tục ghi âm sau khi nhả phím, để thu âm thanh cuối. 0 = không có bộ đệm thêm."
diff --git a/src/i18n/locales/zh-TW/translation.json b/src/i18n/locales/zh-TW/translation.json
index 1dcf6799..092844cd 100644
--- a/src/i18n/locales/zh-TW/translation.json
+++ b/src/i18n/locales/zh-TW/translation.json
@@ -525,6 +525,10 @@
"title": "貼上延遲(後)",
"description": "發送貼上按鍵後、還原先前剪貼簿前的延遲(毫秒)。如果貼上的是舊的剪貼簿內容而非轉錄文字,請增加此值。"
},
+ "reliablePaste": {
+ "title": "可靠貼上(Beta)",
+ "description": "在目標應用程式真正讀取轉錄文字之後才還原剪貼簿,而不是等待固定延遲。用於解決系統負載較高時貼上舊剪貼簿內容的問題。需要使用剪貼簿類的貼上方式;僅支援 macOS 與 Windows。"
+ },
"recordingBuffer": {
"title": "額外錄音緩衝",
"description": "放開按鍵後繼續錄音的額外時間(毫秒),以捕捉尾音。0 = 無額外緩衝。"
diff --git a/src/i18n/locales/zh/translation.json b/src/i18n/locales/zh/translation.json
index 34976ba8..5f170e0c 100644
--- a/src/i18n/locales/zh/translation.json
+++ b/src/i18n/locales/zh/translation.json
@@ -525,6 +525,10 @@
"title": "粘贴延迟(后)",
"description": "发送粘贴按键后、恢复先前剪贴板前的延迟(毫秒)。如果粘贴的是旧的剪贴板内容而非转录文本,请增加此值。"
},
+ "reliablePaste": {
+ "title": "可靠粘贴(Beta)",
+ "description": "在目标应用程序真正读取转录文本之后再恢复剪贴板,而不是等待固定延迟。用于解决系统负载较高时粘贴旧剪贴板内容的问题。需要使用剪贴板类的粘贴方式;仅支持 macOS 和 Windows。"
+ },
"recordingBuffer": {
"title": "额外录音缓冲",
"description": "放开按键后继续录音的额外时间(毫秒),以捕捉尾音。0 = 无额外缓冲。"
diff --git a/src/stores/settingsStore.ts b/src/stores/settingsStore.ts
index b4e04282..50f9b2c5 100644
--- a/src/stores/settingsStore.ts
+++ b/src/stores/settingsStore.ts
@@ -125,6 +125,8 @@ const settingUpdaters: {
commands.changePasteDelayMsSetting(value as number),
paste_delay_after_ms: (value) =>
commands.changePasteDelayAfterMsSetting(value as number),
+ reliable_paste: (value) =>
+ commands.changeReliablePasteSetting(value as boolean),
paste_method: (value) => commands.changePasteMethodSetting(value as string),
typing_tool: (value) => commands.changeTypingToolSetting(value as string),
external_script_path: (value) =>