Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(dictation): bound Windows clipboard reads before paste (#336)

Ruben Lütkeca75badebff4
diff --git a/docs/os-parity.md b/docs/os-parity.md
index 976ca59b7f..2e10952fec 100644
--- a/docs/os-parity.md
+++ b/docs/os-parity.md
@@ -149,6 +149,23 @@ Protocol references: [AsyncSSH port forwarding](https://asyncssh.readthedocs.io/
[Kimi MCP configuration](https://github.com/MoonshotAI/kimi-cli/blob/main/README.md),
[Cursor MCP](https://docs.cursor.com/en/cli/mcp).
+||||||| parent of 1e445fa61 (fix(dictation): bound Windows clipboard reads before paste)
+## Windows clipboard read deadline (2026-10-02, T2)
+
+Windows clipboard reads now run in a disposable helper with a one-second
+communication timeout. This prevents a stalled delayed-rendering owner from
+holding dictation before the paste for Windows' 30-second render timeout.
+Timeout kills and reaps the reader before returning `None`, releasing its
+clipboard lock. Dictation then skips restoring unreadable previous content
+and keeps the new transcript available. Text travels only through a pipe.
+The private helper supports source and windowed/frozen entry points.
+
+Linux and macOS retain their existing clipboard commands and five-second
+timeouts; headless hosts still return unavailable without starting a helper.
+Tests cover helper termination, Unicode, empty/unavailable data, concurrent
+reads, private dispatch and the Windows windowed stdout pipe. A packaged
+installer and a live third-party stalled clipboard owner remain unverified.
+
## Connected computers on Linux, macOS and Windows (2026-10-01, T3)
This one is about the REMOTE side: the machine Jarvis connects to under
diff --git a/jarvis/__main__.py b/jarvis/__main__.py
index 4c60c4a3f0..668b54125d 100644
--- a/jarvis/__main__.py
+++ b/jarvis/__main__.py
@@ -22,6 +22,12 @@ import signal
import sys
from typing import TYPE_CHECKING, NoReturn
+if sys.argv[1:] == ["--clipboard-read"]:
+ # Private read helper, including windowed/frozen builds. Never boot the app.
+ from jarvis.platform.clipboard_reader import main as _clipboard_read_main
+
+ raise SystemExit(_clipboard_read_main())
+
# A frozen GUI executable cannot be relaunched with ``python -m`` and has no
# reliable stdout. Dispatch this private, file-backed sidecar mode before the
# normal desktop imports so Settings can safely enumerate newly hot-plugged
diff --git a/jarvis/platform/clipboard.py b/jarvis/platform/clipboard.py
index 20502dbcde..21dbdda15b 100644
--- a/jarvis/platform/clipboard.py
+++ b/jarvis/platform/clipboard.py
@@ -123,6 +123,15 @@ def _read_linux() -> str | None:
def _read_windows() -> str | None:
+ # GetClipboardData can wait 30 seconds for another application's delayed
+ # renderer. A timed-out thread still owns the clipboard lock, blocking the
+ # dictation write that follows. Isolate the read so timeout releases it.
+ from jarvis.platform.clipboard_reader import read_with_deadline
+
+ return read_with_deadline()
+
+
+def _read_windows_native() -> str | None:
"""Read Unicode text with the Win32 clipboard API.
The clipboard is a shared, singly-owned resource: brief retries handle
diff --git a/jarvis/platform/clipboard_reader.py b/jarvis/platform/clipboard_reader.py
new file mode 100644
index 0000000000..888a853a09
--- /dev/null
+++ b/jarvis/platform/clipboard_reader.py
@@ -0,0 +1,105 @@
+"""Bound Windows clipboard reads without leaving a thread holding it open.
+
+Windows may spend 30 seconds asking a clipboard owner to render text. The
+reader is disposable: subprocess.run kills and reaps it on timeout, releasing
+the clipboard before dictation writes its transcript. No clipboard content is
+written to disk, command arguments or logs. Native reads remain in clipboard.py.
+"""
+from __future__ import annotations
+
+import json
+import logging
+import subprocess
+import sys
+import threading
+from pathlib import Path
+
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+
+log = logging.getLogger(__name__)
+READ_TIMEOUT_S = 1.0
+_READ_LOCK = threading.Lock()
+
+
+def _reader_command() -> list[str]:
+ if getattr(sys, "frozen", False):
+ return [sys.executable, "--clipboard-read"]
+ executable = Path(sys.executable)
+ if executable.name.lower() == "pythonw.exe":
+ executable = executable.with_name("python.exe")
+ return [str(executable), "-m", "jarvis.platform.clipboard_reader"]
+
+
+def read_with_deadline() -> str | None:
+ """Return text, or None on a busy/unresponsive clipboard; never queue reads."""
+ if not _READ_LOCK.acquire(blocking=False):
+ log.debug("clipboard: another bounded read is in progress")
+ return None
+ try:
+ result = subprocess.run(
+ _reader_command(),
+ stdin=subprocess.DEVNULL,
+ stdout=subprocess.PIPE,
+ stderr=subprocess.DEVNULL,
+ encoding="utf-8",
+ errors="replace",
+ timeout=READ_TIMEOUT_S,
+ check=False,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ # A desktop shortcut may start in another directory. Source installs
+ # must import the same checkout as their parent (also in tests).
+ cwd=None if getattr(sys, "frozen", False) else str(Path(__file__).resolve().parents[2]),
+ )
+ if result.returncode:
+ log.warning("clipboard: read helper exited with code %d", result.returncode)
+ return None
+ value = json.loads(result.stdout)
+ return value if isinstance(value, str) else None
+ except subprocess.TimeoutExpired:
+ log.warning("clipboard: read exceeded %.1fs; reader stopped", READ_TIMEOUT_S)
+ except (OSError, subprocess.SubprocessError, ValueError):
+ # Do not log stdout, exception payloads or clipboard contents.
+ log.warning("clipboard: read helper unavailable or returned invalid data")
+ finally:
+ _READ_LOCK.release()
+ return None
+
+
+def _write_response(value: str | None) -> None:
+ payload = json.dumps(value, ensure_ascii=True).encode("utf-8")
+ if sys.stdout is not None:
+ sys.stdout.write(payload.decode("utf-8"))
+ sys.stdout.flush()
+ return
+
+ # A windowed PyInstaller executable sets sys.stdout to None even when the
+ # parent supplied a pipe. Write only to that inherited pipe, never a file.
+ import ctypes
+ from ctypes import wintypes
+
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ kernel32.GetStdHandle.argtypes = [wintypes.DWORD]
+ kernel32.GetStdHandle.restype = wintypes.HANDLE
+ kernel32.WriteFile.argtypes = [
+ wintypes.HANDLE, ctypes.c_void_p, wintypes.DWORD,
+ ctypes.POINTER(wintypes.DWORD), ctypes.c_void_p,
+ ]
+ kernel32.WriteFile.restype = wintypes.BOOL
+ handle = kernel32.GetStdHandle(-11) # STD_OUTPUT_HANDLE
+ buffer = ctypes.create_string_buffer(payload)
+ written = wintypes.DWORD()
+ if not kernel32.WriteFile(handle, buffer, len(payload), ctypes.byref(written), None):
+ raise OSError("clipboard response pipe is unavailable")
+ if written.value != len(payload):
+ raise OSError("clipboard response was incomplete")
+
+
+def main() -> int:
+ from jarvis.platform.clipboard import _read_windows_native
+
+ _write_response(_read_windows_native())
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/unit/platform/test_clipboard_reader.py b/tests/unit/platform/test_clipboard_reader.py
new file mode 100644
index 0000000000..6d24b1cd06
--- /dev/null
+++ b/tests/unit/platform/test_clipboard_reader.py
@@ -0,0 +1,115 @@
+"""A stalled clipboard owner must not hold up dictation or leak its text."""
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+import psutil
+import pytest
+
+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+from jarvis.platform import clipboard
+from jarvis.platform import clipboard_reader as reader
+
+
[email protected]("value", ["", "line one\nUnicode: café 🦊", None])
+def test_reads_preserve_empty_unicode_and_unavailable(monkeypatch, value):
+ def run(command, **kwargs):
+ assert kwargs["timeout"] == reader.READ_TIMEOUT_S
+ assert kwargs["creationflags"] == NO_WINDOW_CREATIONFLAGS
+ assert kwargs["encoding"] == "utf-8"
+ assert kwargs["stderr"] == subprocess.DEVNULL
+ return subprocess.CompletedProcess(command, 0, stdout=json.dumps(value))
+
+ monkeypatch.setattr(reader.subprocess, "run", run)
+ assert clipboard._read_windows() == value
+
+
+def test_timeout_releases_reader_before_the_next_request(monkeypatch, caplog):
+ calls = 0
+
+ def run(command, **kwargs):
+ nonlocal calls
+ calls += 1
+ if calls == 1:
+ raise subprocess.TimeoutExpired(command, 1, output="private clipboard text")
+ return subprocess.CompletedProcess(command, 0, stdout='"next clipboard"')
+
+ monkeypatch.setattr(reader.subprocess, "run", run)
+ assert reader.read_with_deadline() is None
+ assert reader.read_with_deadline() == "next clipboard"
+ assert "private clipboard text" not in caplog.text
+
+
+def test_concurrent_read_is_not_queued(monkeypatch):
+ def unexpected(*args, **kwargs):
+ pytest.fail("a second clipboard reader was started")
+
+ monkeypatch.setattr(reader.subprocess, "run", unexpected)
+ with reader._READ_LOCK:
+ assert reader.read_with_deadline() is None
+
+
+def test_invalid_response_does_not_log_contents(monkeypatch, caplog):
+ monkeypatch.setattr(reader.subprocess, "run", lambda *a, **k:
+ subprocess.CompletedProcess(a[0], 0, stdout="private clipboard text"))
+ assert reader.read_with_deadline() is None
+ assert "private clipboard text" not in caplog.text
+
+
+def test_frozen_reader_reenters_private_mode(monkeypatch):
+ monkeypatch.setattr(sys, "frozen", True, raising=False)
+ assert reader._reader_command() == [sys.executable, "--clipboard-read"]
+
+
+def test_stalled_reader_process_is_reaped(monkeypatch, tmp_path):
+ """Exercise the real kill/wait path without accessing the user's clipboard."""
+ pid_file = tmp_path / "reader.pid"
+ script = (
+ "import os,sys,time; from pathlib import Path; "
+ "Path(sys.argv[1]).write_text(str(os.getpid())); time.sleep(30)"
+ )
+ monkeypatch.setattr(reader, "_reader_command", lambda:
+ [sys.executable, "-c", script, str(pid_file)])
+ started = time.monotonic()
+ assert reader.read_with_deadline() is None
+ assert time.monotonic() - started < 5
+ assert pid_file.exists(), "the helper must have started for this test to prove cleanup"
+ assert not psutil.pid_exists(int(pid_file.read_text()))
+
+
[email protected](sys.platform != "win32", reason="windowed Windows pipe contract")
+def test_windowed_helper_writes_to_inherited_pipe():
+ pythonw = Path(sys.executable).with_name("pythonw.exe")
+ if not pythonw.exists():
+ pytest.skip("windowed interpreter unavailable")
+ script = (
+ "from jarvis.platform.clipboard_reader import _write_response; "
+ "_write_response('sample\\nUnicode: café 🦊')"
+ )
+ result = subprocess.run(
+ [str(pythonw), "-c", script],
+ stdin=subprocess.DEVNULL, capture_output=True,
+ encoding="utf-8", timeout=5, creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ assert result.returncode == 0
+ assert json.loads(result.stdout) == "sample\nUnicode: café 🦊"
+
+
+def test_private_entrypoint_does_not_boot_desktop():
+ script = (
+ "import sys,runpy; import jarvis.platform.clipboard as c; "
+ "c._read_windows_native=lambda: 'sample'; "
+ "sys.argv=['jarvis','--clipboard-read']; "
+ "runpy.run_module('jarvis',run_name='__main__')"
+ )
+ result = subprocess.run(
+ [sys.executable, "-c", script],
+ stdin=subprocess.DEVNULL, capture_output=True,
+ encoding="utf-8", timeout=5, creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ assert result.returncode == 0
+ assert json.loads(result.stdout) == "sample"