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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(ui): restore right-click cut/copy/paste across the whole app
Ruben Lütkee95c5179bbaf
diff --git a/jarvis/platform/clipboard.py b/jarvis/platform/clipboard.pyindex ac6d08bb13..20502dbcde 100644--- a/jarvis/platform/clipboard.py+++ b/jarvis/platform/clipboard.py@@ -1,12 +1,15 @@-"""Cross-platform system clipboard writer for the local desktop shell.+"""Cross-platform system clipboard access for the local desktop shell.The Web UI normally uses the browser Clipboard API. Embedded WebViews can denythat API even after a visible button click (notably WKWebView after an awaitedrequest), so the desktop backend needs a native, capability-gated fallback.+Reading is denied outright: the embedded browser withholds the ``clipboard-read``+permission, so a right-click "Paste" has no browser path at all and depends on+``read_text`` below.Only text is supported here. Clipboard contents are passed through stdin or anative memory buffer, never process arguments or logs. Missing display/tooling-returns ``False`` instead of raising, preserving headless operation.+returns ``False``/``None`` instead of raising, preserving headless operation."""from __future__ import annotations@@ -46,6 +49,141 @@ def write_text(text: str) -> bool:return _write_linux(text)+def read_text() -> str | None:+ """Return the local desktop clipboard's text.++ ``None`` means this host cannot read a clipboard at all (headless, or no+ OS tooling); an empty string means the clipboard is genuinely empty. The+ caller must be able to distinguish those, so an unreachable clipboard is+ never reported as a successful empty paste.++ Line endings are normalised to ``\\n``. Windows hands out ``\\r\\n``, and a+ raw carriage return pasted into a terminal reads as a second Enter — which+ would run every line of a multi-line command twice.+ """+ if not detect_capabilities().display_present:+ log.info("clipboard: no display present; native paste is unavailable")+ return None++ platform = detect_platform()+ if platform == "win32":+ raw = _read_windows()+ elif platform == "darwin":+ raw = _read_command(["/usr/bin/pbpaste"])+ else:+ raw = _read_linux()++ if raw is None:+ return None+ return raw.replace("\r\n", "\n").replace("\r", "\n")+++def _read_command(command: Sequence[str]) -> str | None:+ """Read clipboard text from a fixed OS command's stdout."""+ try:+ completed = subprocess.run( # noqa: S603 - fixed, non-shell OS command+ list(command),+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=_COMMAND_TIMEOUT_S,+ check=False,+ close_fds=True,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ except (OSError, subprocess.SubprocessError) as exc:+ log.warning("clipboard: native paste command unavailable (%s)", exc)+ return None+ if completed.returncode != 0:+ detail = (completed.stderr or "").strip()+ log.warning(+ "clipboard: native paste command failed with exit %d%s",+ completed.returncode,+ f" ({detail[:300]})" if detail else "",+ )+ return None+ return completed.stdout+++def _read_linux() -> str | None:+ """Use the available Wayland/X11 clipboard command, if any."""+ candidates = (+ ("wl-paste", ["wl-paste", "--no-newline"]),+ ("xclip", ["xclip", "-selection", "clipboard", "-out"]),+ ("xsel", ["xsel", "--clipboard", "--output"]),+ )+ for executable, command in candidates:+ resolved = shutil.which(executable)+ if resolved:+ command[0] = resolved+ return _read_command(command)+ log.info("clipboard: no wl-paste, xclip, or xsel command is available")+ return None+++def _read_windows() -> str | None:+ """Read Unicode text with the Win32 clipboard API.++ The clipboard is a shared, singly-owned resource: brief retries handle+ another application holding it open, and the handle is always unlocked and+ the clipboard always closed, even on an unexpected format.+ """+ try:+ from ctypes import wintypes++ user32 = ctypes.WinDLL("user32", use_last_error=True)+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)++ user32.OpenClipboard.argtypes = [wintypes.HWND]+ user32.OpenClipboard.restype = wintypes.BOOL+ user32.IsClipboardFormatAvailable.argtypes = [wintypes.UINT]+ user32.IsClipboardFormatAvailable.restype = wintypes.BOOL+ user32.GetClipboardData.argtypes = [wintypes.UINT]+ user32.GetClipboardData.restype = wintypes.HANDLE+ user32.CloseClipboard.argtypes = []+ user32.CloseClipboard.restype = wintypes.BOOL+ kernel32.GlobalLock.argtypes = [wintypes.HGLOBAL]+ kernel32.GlobalLock.restype = ctypes.c_void_p+ kernel32.GlobalUnlock.argtypes = [wintypes.HGLOBAL]+ kernel32.GlobalUnlock.restype = wintypes.BOOL+ except (AttributeError, OSError) as exc:+ log.warning("clipboard: Win32 API unavailable (%s)", exc)+ return None++ opened = False+ for _attempt in range(_WINDOWS_CLIPBOARD_RETRIES):+ if user32.OpenClipboard(None):+ opened = True+ break+ time.sleep(_WINDOWS_CLIPBOARD_RETRY_S)+ if not opened:+ log.warning("clipboard: Win32 clipboard remained busy")+ return None++ handle = None+ try:+ if not user32.IsClipboardFormatAvailable(13): # CF_UNICODETEXT+ # Something non-textual is on the clipboard (an image, a file+ # list). There is nothing to paste as text, which is not a failure.+ return ""+ handle = user32.GetClipboardData(13)+ if not handle:+ return ""+ pointer = kernel32.GlobalLock(handle)+ if not pointer:+ return None+ try:+ return ctypes.wstring_at(pointer)+ finally:+ kernel32.GlobalUnlock(handle)+ except (AttributeError, OSError, ValueError) as exc:+ log.warning("clipboard: Win32 clipboard read failed (%s)", exc)+ return None+ finally:+ user32.CloseClipboard()++def _run_command(command: Sequence[str], text: str) -> bool:"""Feed clipboard text to a fixed OS command through UTF-8 stdin."""try:@@ -163,4 +301,4 @@ def _write_windows(text: str) -> bool:user32.CloseClipboard()-__all__ = ["write_text"]+__all__ = ["read_text", "write_text"]diff --git a/jarvis/ui/web/clipboard_routes.py b/jarvis/ui/web/clipboard_routes.pyindex 46581b1b47..f439a57f93 100644--- a/jarvis/ui/web/clipboard_routes.py+++ b/jarvis/ui/web/clipboard_routes.py@@ -1,10 +1,10 @@-"""Desktop-only REST fallback for writing text to the system clipboard."""+"""Desktop-only REST fallback for reading and writing the system clipboard."""from __future__ import annotationsfrom fastapi import APIRouter, HTTPException, Requestfrom pydantic import BaseModel, Field-from jarvis.platform.clipboard import write_text+from jarvis.platform.clipboard import read_text, write_textrouter = APIRouter(prefix="/api/clipboard", tags=["clipboard"])@@ -23,6 +23,12 @@ class ClipboardTextResponse(BaseModel):copied: bool+class ClipboardReadResponse(BaseModel):+ """Current text on the local desktop clipboard."""++ text: str++@router.post("/text",response_model=ClipboardTextResponse,@@ -40,4 +46,26 @@ def copy_text_to_system_clipboard(raise HTTPException(status_code=503, detail="native-clipboard-unavailable")return ClipboardTextResponse(copied=True)++ "/text",+ response_model=ClipboardReadResponse,+ summary="Read text from the local desktop clipboard",+)+def read_text_from_system_clipboard(request: Request) -> ClipboardReadResponse:+ """Return the clipboard text so the desktop shell can offer a real Paste.++ The embedded WebView withholds the browser ``clipboard-read`` permission,+ so a right-click "Paste" has no in-page path and reads through here. Gated+ on the same local-desktop capability as the write route: on a browser or a+ remote/headless server this would expose the *server's* clipboard to a+ remote page, so it stays absent there. The text is never logged.+ """+ if not bool(getattr(request.app.state, "native_file_actions", False)):+ raise HTTPException(status_code=404, detail="native-clipboard-disabled")+ text = read_text()+ if text is None:+ raise HTTPException(status_code=503, detail="native-clipboard-unavailable")+ return ClipboardReadResponse(text=text)+__all__ = ["router"]diff --git a/jarvis/ui/web/frontend/src/App.tsx b/jarvis/ui/web/frontend/src/App.tsxindex a41fd8caf5..58d18d1461 100644--- a/jarvis/ui/web/frontend/src/App.tsx+++ b/jarvis/ui/web/frontend/src/App.tsx@@ -11,6 +11,7 @@ import { InputIsolationBanner } from "@/components/layout/InputIsolationBanner";import { VoiceWarmingBanner } from "@/components/layout/VoiceWarmingBanner";import { MainView } from "@/components/layout/MainView";import { ToastLayer } from "@/components/ToastLayer";+import { EditContextMenu } from "@/components/EditContextMenu";import { JarvisDock } from "@/components/JarvisDock";import { CliConnectPoller } from "@/components/CliConnectPoller";import { OnboardingGate } from "@/components/onboarding/OnboardingGate";@@ -73,6 +74,10 @@ export default function App() {</main><ToastLayer />+ {/* Right-click Cut/Copy/Paste. The desktop WebView ships with its own+ context menu disabled, so without this there is no mouse-driven paste+ anywhere in the app — including the IDE terminals. */}+ <EditContextMenu />{/* Always-present "Jarvis presence" drop dock — drag a mission/outputcard here to pull it into the live conversation context. */}<JarvisDock />diff --git a/jarvis/ui/web/frontend/src/components/EditContextMenu.tsx b/jarvis/ui/web/frontend/src/components/EditContextMenu.tsxnew file mode 100644index 0000000000..f29920e929--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/EditContextMenu.tsx@@ -0,0 +1,245 @@+import {+ useCallback,+ useEffect,+ useLayoutEffect,+ useRef,+ useState,+ type KeyboardEvent as ReactKeyboardEvent,+} from "react";+import { Clipboard, Copy, Scissors, TextSelect } from "lucide-react";++import { useT } from "@/i18n";+import { useEventStore } from "@/store/events";+import { robustCopy, robustPaste } from "@/lib/clipboard";+import {+ capabilitiesFor,+ captureEditSnapshot,+ deleteSelection,+ pasteInto,+ selectAll,+ type EditCapabilities,+ type EditSnapshot,+} from "@/lib/editActions";+import { cn } from "@/lib/utils";++/**+ * App-wide right-click menu offering Cut / Copy / Paste / Select all.+ *+ * The desktop shell embeds the UI in a WebView whose own context menu is+ * switched off, so without this component right-clicking does nothing at all —+ * anywhere in the app. That leaves mouse-driven pasting impossible, which is+ * how most people paste. Mounted once in the app shell so it covers every+ * view, including the Agentic IDE terminals.+ *+ * Shift+right-click is deliberately left alone: in a real browser that still+ * opens the native menu, keeping the developer escape hatch intact.+ */++const MENU_WIDTH = 210;+const VIEWPORT_MARGIN = 8;++interface MenuState {+ x: number;+ y: number;+ snapshot: EditSnapshot;+ caps: EditCapabilities;+}++export function EditContextMenu() {+ const t = useT();+ const pushToast = useEventStore((s) => s.pushToast);+ const [menu, setMenu] = useState<MenuState | null>(null);+ const menuRef = useRef<HTMLDivElement | null>(null);++ const close = useCallback(() => setMenu(null), []);++ useEffect(() => {+ const onContextMenu = (event: MouseEvent) => {+ // Escape hatch: let the browser's own menu through.+ if (event.shiftKey) return;+ const snapshot = captureEditSnapshot(event.target);+ const caps = capabilitiesFor(snapshot);+ // Nothing useful to offer (e.g. a right-click on empty chrome with no+ // selection) — stay out of the way rather than show a dead menu.+ if (!caps.canCut && !caps.canCopy && !caps.canPaste && !caps.canSelectAll) {+ return;+ }+ event.preventDefault();+ setMenu({ x: event.clientX, y: event.clientY, snapshot, caps });+ };++ document.addEventListener("contextmenu", onContextMenu);+ return () => document.removeEventListener("contextmenu", onContextMenu);+ }, []);++ useEffect(() => {+ if (!menu) return;+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key === "Escape") {+ event.stopPropagation();+ close();+ }+ };+ const onPointerDown = (event: PointerEvent) => {+ if (!menuRef.current?.contains(event.target as Node)) close();+ };+ // A scroll or a resize moves the anchor out from under the menu.+ window.addEventListener("keydown", onKeyDown, true);+ window.addEventListener("pointerdown", onPointerDown, true);+ window.addEventListener("resize", close);+ window.addEventListener("blur", close);+ document.addEventListener("scroll", close, true);+ return () => {+ window.removeEventListener("keydown", onKeyDown, true);+ window.removeEventListener("pointerdown", onPointerDown, true);+ window.removeEventListener("resize", close);+ window.removeEventListener("blur", close);+ document.removeEventListener("scroll", close, true);+ };+ }, [menu, close]);++ // Keep the menu inside the window: near the right or bottom edge it flips+ // back over the cursor instead of being clipped.+ useLayoutEffect(() => {+ const node = menuRef.current;+ if (!node || !menu) return;+ const { width, height } = node.getBoundingClientRect();+ const maxX = window.innerWidth - width - VIEWPORT_MARGIN;+ const maxY = window.innerHeight - height - VIEWPORT_MARGIN;+ node.style.left = `${Math.max(VIEWPORT_MARGIN, Math.min(menu.x, maxX))}px`;+ node.style.top = `${Math.max(VIEWPORT_MARGIN, Math.min(menu.y, maxY))}px`;+ node.style.visibility = "visible";+ // Focus the menu so Escape and the arrow keys work without a mouse.+ node.querySelector<HTMLButtonElement>("button:not([disabled])")?.focus();+ }, [menu]);++ const run = useCallback(+ async (action: "cut" | "copy" | "paste" | "selectAll") => {+ if (!menu) return;+ const { snapshot } = menu;+ close();++ if (action === "selectAll") {+ selectAll(snapshot);+ return;+ }+ if (action === "copy" || action === "cut") {+ const copied = await robustCopy(snapshot.selectedText);+ if (!copied) {+ pushToast("error", t("edit_menu.copy_failed"));+ return;+ }+ if (action === "cut") deleteSelection(snapshot);+ return;+ }+ // Paste.+ const text = await robustPaste();+ if (text === null) {+ pushToast("error", t("edit_menu.paste_unavailable"));+ return;+ }+ if (!text) return; // nothing on the clipboard — not an error+ if (!pasteInto(snapshot, text)) {+ pushToast("error", t("edit_menu.paste_failed"));+ }+ },+ [menu, close, pushToast, t],+ );++ const onMenuKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {+ if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return;+ event.preventDefault();+ const items = Array.from(+ menuRef.current?.querySelectorAll<HTMLButtonElement>(+ "button:not([disabled])",+ ) ?? [],+ );+ if (!items.length) return;+ const current = items.indexOf(document.activeElement as HTMLButtonElement);+ const step = event.key === "ArrowDown" ? 1 : -1;+ const next = (current + step + items.length) % items.length;+ items[next]?.focus();+ };++ if (!menu) return null;+ const { caps } = menu;++ return (+ <div+ ref={menuRef}+ role="menu"+ aria-label={t("edit_menu.label")}+ onKeyDown={onMenuKeyDown}+ // Positioned in the layout effect above, once its real size is known.+ style={{ width: MENU_WIDTH, visibility: "hidden" }}+ className="fixed z-[100] overflow-hidden rounded-md border border-border bg-background py-1 shadow-lg"+ >+ <MenuItem+ icon={Scissors}+ label={t("edit_menu.cut")}+ shortcut="Ctrl+X"+ disabled={!caps.canCut}+ onSelect={() => void run("cut")}+ />+ <MenuItem+ icon={Copy}+ label={t("edit_menu.copy")}+ shortcut="Ctrl+C"+ disabled={!caps.canCopy}+ onSelect={() => void run("copy")}+ />+ <MenuItem+ icon={Clipboard}+ label={t("edit_menu.paste")}+ shortcut="Ctrl+V"+ disabled={!caps.canPaste}+ onSelect={() => void run("paste")}+ />+ <MenuItem+ icon={TextSelect}+ label={t("edit_menu.select_all")}+ shortcut="Ctrl+A"+ disabled={!caps.canSelectAll}+ onSelect={() => void run("selectAll")}+ />+ </div>+ );+}++function MenuItem({+ icon: Icon,+ label,+ shortcut,+ disabled,+ onSelect,+}: {+ icon: typeof Copy;+ label: string;+ shortcut: string;+ disabled: boolean;+ onSelect: () => void;+}) {+ return (+ <button+ type="button"+ role="menuitem"+ disabled={disabled}+ // Without this the click moves focus off the field before the action+ // runs, and the caret — the place the text has to land — is gone.+ onMouseDown={(e) => e.preventDefault()}+ onClick={onSelect}+ className={cn(+ "flex w-full items-center gap-2 px-3 py-1.5 text-left text-sm",+ disabled+ ? "cursor-default text-muted-foreground/40"+ : "text-foreground hover:bg-primary/10 focus:bg-primary/10 focus:outline-none",+ )}+ >+ <Icon className="h-3.5 w-3.5 shrink-0" aria-hidden />+ <span className="flex-1">{label}</span>+ <span className="text-[10px] tracking-wider text-muted-foreground">+ {shortcut}+ </span>+ </button>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsxindex c06aab35f1..9deb1cf19c 100644--- a/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/AgenticTerminal.tsx@@ -71,6 +71,7 @@ import {type PaneDropPayload,} from "./paneDrop";import { attachToTerminal } from "@/lib/agenticIdeApi";+import { attachTerminalBridge } from "@/lib/editActions";export type PaneStatus = "connecting" | "live" | "exited" | "error";@@ -235,6 +236,15 @@ export function AgenticTerminal({}termRef.current = term;fitRef.current = fit;+ // Let the app-wide right-click menu reach this terminal. It cannot use the+ // browser selection here — the canvas renderer above paints the text, so+ // there is no selectable DOM to read — and it must paste through xterm so+ // the sequence is bracketed rather than typed key by key.+ attachTerminalBridge(container, {+ getSelection: () => term.getSelection(),+ paste: (text) => term.paste(text),+ focus: () => term.focus(),+ });try {fit.fit();} catch {diff --git a/jarvis/ui/web/frontend/src/lib/clipboard.test.ts b/jarvis/ui/web/frontend/src/lib/clipboard.test.tsindex bcf1678698..3494d3ec66 100644--- a/jarvis/ui/web/frontend/src/lib/clipboard.test.ts+++ b/jarvis/ui/web/frontend/src/lib/clipboard.test.ts@@ -1,6 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { robustCopy, saveOrDownload } from "./clipboard";+import { robustCopy, robustPaste, saveOrDownload } from "./clipboard";const originalClipboard = Object.getOwnPropertyDescriptor(navigator, "clipboard");const originalExecCommand = Object.getOwnPropertyDescriptor(document, "execCommand");@@ -168,3 +168,81 @@ describe("saveOrDownload", () => {expect(clickSpy).toHaveBeenCalledTimes(1);});});++describe("robustPaste", () => {+ afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ restoreProperty(navigator, "clipboard", originalClipboard);+ });++ function stubReadText(readText: () => Promise<string>) {+ Object.defineProperty(navigator, "clipboard", {+ configurable: true,+ value: { readText },+ });+ }++ function stubRest(response: { ok: boolean; body?: unknown }) {+ const fetchMock = vi.fn(async () => ({+ ok: response.ok,+ status: response.ok ? 200 : 404,+ json: async () => response.body,+ }));+ vi.stubGlobal("fetch", fetchMock);+ return fetchMock;+ }++ it("reads through the desktop route first", async () => {+ const readText = vi.fn(async () => "from the browser");+ stubReadText(readText);+ stubRest({ ok: true, body: { text: "from the desktop" } });++ await expect(robustPaste()).resolves.toBe("from the desktop");+ expect(readText).not.toHaveBeenCalled();+ });++ it("is not blocked by a clipboard permission prompt that never settles", async () => {+ // The regression this ordering exists for: inside the desktop WebView,+ // navigator.clipboard.readText() stays pending forever — neither resolved+ // nor rejected — so awaiting it first made right-click Paste look dead.+ stubReadText(() => new Promise<string>(() => {}));+ stubRest({ ok: true, body: { text: "pasted anyway" } });++ await expect(robustPaste()).resolves.toBe("pasted anyway");+ });++ it("falls back to the browser when the desktop route is absent", async () => {+ stubReadText(async () => "from the browser");+ stubRest({ ok: false });++ await expect(robustPaste()).resolves.toBe("from the browser");+ });++ it("reports a genuinely empty clipboard as empty, not as a failure", async () => {+ stubReadText(async () => "should not be consulted");+ stubRest({ ok: true, body: { text: "" } });++ await expect(robustPaste()).resolves.toBe("");+ });++ it("gives up on a browser read that never settles", async () => {+ vi.useFakeTimers();+ stubReadText(() => new Promise<string>(() => {}));+ stubRest({ ok: false });++ const pending = robustPaste();+ await vi.advanceTimersByTimeAsync(5000);+ await expect(pending).resolves.toBeNull();+ });++ it("returns null when no path can read the clipboard", async () => {+ stubReadText(async () => {+ throw new Error("NotAllowedError");+ });+ stubRest({ ok: false });++ await expect(robustPaste()).resolves.toBeNull();+ });+});diff --git a/jarvis/ui/web/frontend/src/lib/clipboard.ts b/jarvis/ui/web/frontend/src/lib/clipboard.tsindex 5a91d45b53..6cbed1a46b 100644--- a/jarvis/ui/web/frontend/src/lib/clipboard.ts+++ b/jarvis/ui/web/frontend/src/lib/clipboard.ts@@ -48,6 +48,69 @@ export async function robustCopy(text: string): Promise<boolean> {return nativeBackendCopy(text);}+/** Hard cap on the browser clipboard read (see robustPaste). */+const BROWSER_READ_TIMEOUT_MS = 5000;++/**+ * Robustly reads the system clipboard for an in-app "Paste" command.+ *+ * Returns the text, or null when no path could read it.+ *+ * Order matters, and it is the reverse of robustCopy's. Measured inside the+ * desktop WebView (2026-07-26): the REST route answers in ~60 ms, while+ * `navigator.clipboard.readText()` **never settles at all** — not resolved,+ * not rejected, still pending after 10 s, because the embedded browser+ * withholds the `clipboard-read` permission and nothing ever answers the+ * prompt. Awaiting it first made right-click Paste look dead. So the native+ * route goes first, and the browser API is only a fallback for a real browser+ * — where the desktop route is deliberately absent — and even then it is+ * raced against a timeout so a pending promise can never hang the menu.+ */+export async function robustPaste(): Promise<string | null> {+ // Path A — local desktop backend, reading through the operating system.+ // Intentionally absent on a browser/headless server, where it would expose+ // the server's clipboard rather than the user's.+ const fromBackend = await nativeBackendPaste();+ if (fromBackend !== null) return fromBackend;+ // Path B — modern clipboard API, for a real browser.+ return browserPaste();+}++async function browserPaste(): Promise<string | null> {+ if (+ typeof navigator === "undefined" ||+ !navigator.clipboard ||+ typeof navigator.clipboard.readText !== "function"+ ) {+ return null;+ }+ try {+ const timeout = new Promise<null>((resolve) =>+ setTimeout(() => resolve(null), BROWSER_READ_TIMEOUT_MS),+ );+ return await Promise.race([navigator.clipboard.readText(), timeout]);+ } catch {+ return null;+ }+}++async function nativeBackendPaste(): Promise<string | null> {+ if (typeof fetch !== "function") return null;+ try {+ const response = await fetch("/api/clipboard/text", {+ method: "GET",+ credentials: "same-origin",+ });+ if (!response.ok) return null;+ const result = (await response.json().catch(() => null)) as {+ text?: unknown;+ } | null;+ return typeof result?.text === "string" ? result.text : null;+ } catch {+ return null;+ }+}+async function nativeBackendCopy(text: string): Promise<boolean> {if (typeof fetch !== "function") return false;try {diff --git a/jarvis/ui/web/frontend/src/lib/editActions.test.ts b/jarvis/ui/web/frontend/src/lib/editActions.test.tsnew file mode 100644index 0000000000..6423e9bed0--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/editActions.test.ts@@ -0,0 +1,209 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import {+ attachTerminalBridge,+ capabilitiesFor,+ captureEditSnapshot,+ deleteSelection,+ findTerminalBridge,+ pasteInto,+ selectAll,+} from "./editActions";++/* jsdom implements neither execCommand nor a canvas terminal, which is exactly+ * the situation these helpers are built to survive: every action falls back to+ * a manual path, and terminals arrive through the registered bridge. */++afterEach(() => {+ document.body.replaceChildren();+ vi.restoreAllMocks();+});++function makeTextarea(value: string, start?: number, end?: number) {+ const el = document.createElement("textarea");+ el.value = value;+ document.body.appendChild(el);+ el.focus();+ el.setSelectionRange(start ?? value.length, end ?? start ?? value.length);+ return el;+}++describe("captureEditSnapshot", () => {+ it("treats a writable textarea as an editable field", () => {+ const el = makeTextarea("hello world", 0, 5);+ const snap = captureEditSnapshot(el);++ expect(snap.kind).toBe("field");+ expect(snap.editable).toBe(true);+ expect(snap.selectedText).toBe("hello");+ expect(snap.selectionStart).toBe(0);+ expect(snap.selectionEnd).toBe(5);+ });++ it("marks a read-only field as not editable", () => {+ const el = makeTextarea("locked");+ el.readOnly = true;+ expect(captureEditSnapshot(el).editable).toBe(false);+ });++ it("ignores non-text inputs such as checkboxes", () => {+ const el = document.createElement("input");+ el.type = "checkbox";+ document.body.appendChild(el);+ expect(captureEditSnapshot(el).kind).toBe("plain");+ });++ it("never offers to write into a file input", () => {+ const el = document.createElement("input");+ el.type = "file";+ document.body.appendChild(el);+ expect(capabilitiesFor(captureEditSnapshot(el)).canPaste).toBe(false);+ });++ it("resolves a click inside a terminal to that terminal's bridge", () => {+ const host = document.createElement("div");+ const inner = document.createElement("span");+ host.appendChild(inner);+ document.body.appendChild(host);+ attachTerminalBridge(host, {+ getSelection: () => "selected in terminal",+ paste: () => {},+ focus: () => {},+ });++ const snap = captureEditSnapshot(inner);+ expect(snap.kind).toBe("terminal");+ expect(snap.selectedText).toBe("selected in terminal");+ expect(snap.editable).toBe(true);+ });++ it("returns no bridge for an element outside any terminal", () => {+ const el = document.createElement("div");+ document.body.appendChild(el);+ expect(findTerminalBridge(el)).toBeNull();+ });+});++describe("pasteInto", () => {+ it("inserts at the caret rather than replacing the whole field", () => {+ const el = makeTextarea("ab", 1, 1);+ const snap = captureEditSnapshot(el);++ expect(pasteInto(snap, "XY")).toBe(true);+ expect(el.value).toBe("aXYb");+ });++ it("replaces the selected text", () => {+ const el = makeTextarea("keep DROP keep", 5, 9);+ const snap = captureEditSnapshot(el);++ pasteInto(snap, "NEW");+ expect(el.value).toBe("keep NEW keep");+ });++ it("emits an input event so a React-controlled field updates", () => {+ const el = makeTextarea("", 0, 0);+ const onInput = vi.fn();+ el.addEventListener("input", onInput);++ pasteInto(captureEditSnapshot(el), "typed by menu");+ expect(onInput).toHaveBeenCalledTimes(1);+ });++ it("routes a terminal paste through the bridge", () => {+ const host = document.createElement("div");+ document.body.appendChild(host);+ const paste = vi.fn();+ attachTerminalBridge(host, {+ getSelection: () => "",+ paste,+ focus: () => {},+ });++ expect(pasteInto(captureEditSnapshot(host), "ls -la")).toBe(true);+ expect(paste).toHaveBeenCalledWith("ls -la");+ });++ it("refuses to write into a read-only field", () => {+ const el = makeTextarea("locked");+ el.readOnly = true;+ expect(pasteInto(captureEditSnapshot(el), "nope")).toBe(false);+ expect(el.value).toBe("locked");+ });++ it("does nothing when the clipboard was empty", () => {+ const el = makeTextarea("unchanged");+ expect(pasteInto(captureEditSnapshot(el), "")).toBe(false);+ expect(el.value).toBe("unchanged");+ });+});++describe("deleteSelection", () => {+ it("removes exactly the selected range", () => {+ const el = makeTextarea("keep DROP keep", 5, 10);+ expect(deleteSelection(captureEditSnapshot(el))).toBe(true);+ expect(el.value).toBe("keep keep");+ });++ it("never edits a terminal's scrollback", () => {+ const host = document.createElement("div");+ document.body.appendChild(host);+ attachTerminalBridge(host, {+ getSelection: () => "some output",+ paste: () => {},+ focus: () => {},+ });+ expect(deleteSelection(captureEditSnapshot(host))).toBe(false);+ });+});++describe("selectAll", () => {+ it("selects the whole field", () => {+ const el = makeTextarea("select all of this", 0, 0);+ expect(selectAll(captureEditSnapshot(el))).toBe(true);+ expect(el.selectionStart).toBe(0);+ expect(el.selectionEnd).toBe("select all of this".length);+ });+});++describe("capabilitiesFor", () => {+ it("offers cut and copy only when something is selected", () => {+ const el = makeTextarea("nothing selected", 3, 3);+ const caps = capabilitiesFor(captureEditSnapshot(el));+ expect(caps.canCut).toBe(false);+ expect(caps.canCopy).toBe(false);+ expect(caps.canPaste).toBe(true);+ expect(caps.canSelectAll).toBe(true);+ });++ it("offers copy but not cut for a terminal selection", () => {+ const host = document.createElement("div");+ document.body.appendChild(host);+ attachTerminalBridge(host, {+ getSelection: () => "output text",+ paste: () => {},+ focus: () => {},+ });++ const caps = capabilitiesFor(captureEditSnapshot(host));+ expect(caps.canCopy).toBe(true);+ expect(caps.canCut).toBe(false);+ expect(caps.canPaste).toBe(true);+ expect(caps.canSelectAll).toBe(false);+ });++ it("offers copy on plain page text with a selection", () => {+ const p = document.createElement("p");+ p.textContent = "some prose";+ document.body.appendChild(p);+ const range = document.createRange();+ range.selectNodeContents(p);+ const selection = window.getSelection();+ selection?.removeAllRanges();+ selection?.addRange(range);++ const caps = capabilitiesFor(captureEditSnapshot(p));+ expect(caps.canCopy).toBe(true);+ expect(caps.canPaste).toBe(false);+ });+});diff --git a/jarvis/ui/web/frontend/src/lib/editActions.ts b/jarvis/ui/web/frontend/src/lib/editActions.tsnew file mode 100644index 0000000000..eefa798070--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/editActions.ts@@ -0,0 +1,289 @@+/**+ * Cut / copy / paste / select-all against whatever the user right-clicked.+ *+ * Background: the desktop shell runs the UI inside an embedded WebView whose+ * built-in context menu is switched off, so the browser's own Cut/Copy/Paste+ * entries do not exist anywhere in the app. This module is the replacement's+ * engine — deliberately free of React so it can be tested directly.+ *+ * Two details drive the design:+ *+ * - **The click steals the focus.** Activating a menu item moves focus off the+ * field, taking the caret with it. Every action therefore takes a snapshot+ * captured at right-click time and restores focus + selection first.+ * - **Terminals are not text.** The IDE terminals paint onto a canvas, so the+ * browser selection is empty there and inserting characters does nothing.+ * A terminal registers a small bridge on its container instead.+ */++export interface TerminalBridge {+ /** Text the user has selected inside the terminal ("" when none). */+ getSelection(): string;+ /** Write text into the terminal as a paste (bracketed where supported). */+ paste(text: string): void;+ focus(): void;+}++const BRIDGE_KEY = "__jarvisTerminalBridge";+const TERMINAL_SELECTOR = "[data-jarvis-terminal]";++/** Register a terminal so the context menu can copy from / paste into it. */+export function attachTerminalBridge(+ element: HTMLElement,+ bridge: TerminalBridge,+): void {+ element.setAttribute("data-jarvis-terminal", "");+ (element as unknown as Record<string, unknown>)[BRIDGE_KEY] = bridge;+}++/** Find the bridge of the terminal containing `element`, if any. */+export function findTerminalBridge(+ element: Element | null,+): TerminalBridge | null {+ const host = element?.closest?.(TERMINAL_SELECTOR) ?? null;+ if (!host) return null;+ const bridge = (host as unknown as Record<string, unknown>)[BRIDGE_KEY];+ return (bridge as TerminalBridge) ?? null;+}++export type EditTargetKind = "field" | "terminal" | "plain";++/**+ * Everything an action needs, frozen at right-click time.+ *+ * `selectionStart`/`selectionEnd` are captured here because activating a menu+ * item destroys them.+ */+export interface EditSnapshot {+ kind: EditTargetKind;+ element: HTMLElement | null;+ bridge: TerminalBridge | null;+ /** Text currently selected, wherever the selection lives. */+ selectedText: string;+ /** True when text can be written at the target. */+ editable: boolean;+ selectionStart: number | null;+ selectionEnd: number | null;+ /** Saved DOM range for contenteditable targets. */+ range: Range | null;+}++function isTextInput(+ element: Element | null,+): element is HTMLInputElement | HTMLTextAreaElement {+ if (!element) return false;+ const tag = element.tagName;+ if (tag === "TEXTAREA") return true;+ if (tag !== "INPUT") return false;+ // Only inputs that hold editable text — a checkbox or a colour picker has+ // nothing to cut, and a file input must never be writable from a menu.+ const type = (element as HTMLInputElement).type.toLowerCase();+ return [+ "text",+ "search",+ "url",+ "tel",+ "email",+ "password",+ "number",+ "",+ ].includes(type);+}++function isWritable(element: HTMLInputElement | HTMLTextAreaElement): boolean {+ return !element.disabled && !element.readOnly;+}++/** Capture what was right-clicked, before any focus moves. */+export function captureEditSnapshot(target: EventTarget | null): EditSnapshot {+ const element = target instanceof HTMLElement ? target : null;+ const docSelection =+ typeof window !== "undefined" ? window.getSelection() : null;++ const bridge = findTerminalBridge(element);+ if (bridge) {+ return {+ kind: "terminal",+ element,+ bridge,+ selectedText: bridge.getSelection() || "",+ editable: true,+ selectionStart: null,+ selectionEnd: null,+ range: null,+ };+ }++ if (isTextInput(element)) {+ const start = element.selectionStart;+ const end = element.selectionEnd;+ const selected =+ start !== null && end !== null && end > start+ ? element.value.slice(start, end)+ : "";+ return {+ kind: "field",+ element,+ bridge: null,+ selectedText: selected,+ editable: isWritable(element),+ selectionStart: start,+ selectionEnd: end,+ range: null,+ };+ }++ const editableHost = element?.closest?.<HTMLElement>(+ '[contenteditable="true"]',+ );+ if (editableHost) {+ const range =+ docSelection && docSelection.rangeCount > 0+ ? docSelection.getRangeAt(0).cloneRange()+ : null;+ return {+ kind: "field",+ element: editableHost,+ bridge: null,+ selectedText: docSelection?.toString() ?? "",+ editable: true,+ selectionStart: null,+ selectionEnd: null,+ range,+ };+ }++ return {+ kind: "plain",+ element,+ bridge: null,+ selectedText: docSelection?.toString() ?? "",+ editable: false,+ selectionStart: null,+ selectionEnd: null,+ range: null,+ };+}++/** Put focus and caret back where they were when the menu opened. */+function restore(snapshot: EditSnapshot): void {+ const { element } = snapshot;+ if (!element) return;+ if (snapshot.bridge) {+ snapshot.bridge.focus();+ return;+ }+ element.focus({ preventScroll: true });+ if (+ isTextInput(element) &&+ snapshot.selectionStart !== null &&+ snapshot.selectionEnd !== null+ ) {+ element.setSelectionRange(snapshot.selectionStart, snapshot.selectionEnd);+ return;+ }+ if (snapshot.range && typeof window !== "undefined") {+ const selection = window.getSelection();+ selection?.removeAllRanges();+ selection?.addRange(snapshot.range);+ }+}++/**+ * Insert `text` at the caret.+ *+ * `insertText` is used rather than assigning `.value` because it keeps the+ * caret position, keeps undo history intact, and emits the native `input`+ * event that React's controlled inputs listen for — a direct `.value` write is+ * invisible to React and gets overwritten on the next render.+ */+export function pasteInto(snapshot: EditSnapshot, text: string): boolean {+ if (!text) return false;+ restore(snapshot);++ if (snapshot.bridge) {+ snapshot.bridge.paste(text);+ return true;+ }+ if (!snapshot.editable) return false;++ try {+ if (document.execCommand("insertText", false, text)) return true;+ } catch {+ // Fall through to the manual path below.+ }+ return insertTextManually(snapshot, text);+}++/** Fallback for engines where `insertText` is unavailable or refused. */+function insertTextManually(snapshot: EditSnapshot, text: string): boolean {+ const element = snapshot.element;+ if (!isTextInput(element)) return false;++ const start = snapshot.selectionStart ?? element.value.length;+ const end = snapshot.selectionEnd ?? start;+ const next = element.value.slice(0, start) + text + element.value.slice(end);++ // React tracks the previous value on the DOM node and skips the change event+ // when it looks unchanged; going through the prototype setter defeats that.+ const prototype =+ element.tagName === "TEXTAREA"+ ? HTMLTextAreaElement.prototype+ : HTMLInputElement.prototype;+ const setter = Object.getOwnPropertyDescriptor(prototype, "value")?.set;+ if (setter) setter.call(element, next);+ else element.value = next;++ const caret = start + text.length;+ element.setSelectionRange(caret, caret);+ element.dispatchEvent(new Event("input", { bubbles: true }));+ return true;+}++/** Remove the selected text from an editable target. */+export function deleteSelection(snapshot: EditSnapshot): boolean {+ if (!snapshot.editable || !snapshot.selectedText) return false;+ if (snapshot.bridge) return false; // a terminal's scrollback is not editable+ restore(snapshot);+ try {+ if (document.execCommand("delete")) return true;+ } catch {+ // Fall through.+ }+ return insertTextManually(snapshot, "");+}++/** Select everything at the target. */+export function selectAll(snapshot: EditSnapshot): boolean {+ const element = snapshot.element;+ if (!element) return false;+ if (isTextInput(element)) {+ element.focus({ preventScroll: true });+ element.select();+ return true;+ }+ element.focus?.({ preventScroll: true });+ try {+ return document.execCommand("selectAll");+ } catch {+ return false;+ }+}++/** Which menu entries make sense for this target. */+export interface EditCapabilities {+ canCut: boolean;+ canCopy: boolean;+ canPaste: boolean;+ canSelectAll: boolean;+}++export function capabilitiesFor(snapshot: EditSnapshot): EditCapabilities {+ const hasSelection = snapshot.selectedText.length > 0;+ return {+ canCut: snapshot.editable && hasSelection && snapshot.kind === "field",+ canCopy: hasSelection,+ canPaste: snapshot.editable,+ canSelectAll: snapshot.kind !== "terminal",+ };+}diff --git a/tests/integration/test_clipboard_routes.py b/tests/integration/test_clipboard_routes.pyindex 0402843ed3..552a6daa0b 100644--- a/tests/integration/test_clipboard_routes.py+++ b/tests/integration/test_clipboard_routes.py@@ -66,6 +66,54 @@ def test_unavailable_native_clipboard_returns_503(assert response.json()["detail"] == "native-clipboard-unavailable"+def test_desktop_read_returns_the_clipboard_text(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(clipboard_routes, "read_text", lambda: "first\nsecond")++ response = _client(native=True).get("/api/clipboard/text")++ assert response.status_code == 200, response.text+ assert response.json() == {"text": "first\nsecond"}+++def test_headless_read_is_disabled(monkeypatch: pytest.MonkeyPatch) -> None:+ called = False++ def _unexpected() -> str | None:+ nonlocal called+ called = True+ return "leaked clipboard"++ monkeypatch.setattr(clipboard_routes, "read_text", _unexpected)+ response = _client(native=False).get("/api/clipboard/text")++ assert response.status_code == 404+ assert response.json()["detail"] == "native-clipboard-disabled"+ assert called is False+++def test_unreadable_clipboard_returns_503(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(clipboard_routes, "read_text", lambda: None)++ response = _client(native=True).get("/api/clipboard/text")++ assert response.status_code == 503+ assert response.json()["detail"] == "native-clipboard-unavailable"+++def test_empty_clipboard_is_a_successful_empty_read(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """An empty clipboard is not an error — only an unreachable one is."""+ monkeypatch.setattr(clipboard_routes, "read_text", lambda: "")++ response = _client(native=True).get("/api/clipboard/text")++ assert response.status_code == 200, response.text+ assert response.json() == {"text": ""}++def test_copy_route_declares_danger_metadata() -> None:schema = _client(native=True).app.openapi()operation = schema["paths"]["/api/clipboard/text"]["post"]diff --git a/tests/unit/platform/test_clipboard.py b/tests/unit/platform/test_clipboard.pyindex 04cc6021c1..948a4d262e 100644--- a/tests/unit/platform/test_clipboard.py+++ b/tests/unit/platform/test_clipboard.py@@ -101,3 +101,100 @@ def test_command_writer_passes_text_only_through_stdin(assert captured["command"] == ["pbcopy"]assert captured["input"] == clipboard_textassert clipboard_text not in captured["command"]+++# --- read_text -------------------------------------------------------------+#+# The desktop WebView cannot use ``navigator.clipboard.readText`` (the embedded+# browser withholds that permission), so a right-click "Paste" reads through+# this helper instead. ``None`` means "this host cannot read a clipboard";+# an empty string means "the clipboard is genuinely empty" — the caller must be+# able to tell those apart.+++def test_headless_host_cannot_read(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ clipboard, "detect_capabilities", lambda: _capabilities(False)+ )+ called = False++ def _unexpected() -> str | None:+ nonlocal called+ called = True+ return "leaked"++ monkeypatch.setattr(clipboard, "_read_windows", _unexpected)+ assert clipboard.read_text() is None+ assert called is False+++def test_macos_reads_through_pbpaste(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ clipboard, "detect_capabilities", lambda: _capabilities(True)+ )+ monkeypatch.setattr(clipboard, "detect_platform", lambda: "darwin")+ calls: list[list[str]] = []+ monkeypatch.setattr(+ clipboard,+ "_read_command",+ lambda command: (calls.append(list(command)), "from pbpaste")[1],+ )++ assert clipboard.read_text() == "from pbpaste"+ assert calls == [["/usr/bin/pbpaste"]]+++def test_windows_reads_through_the_native_api(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ clipboard, "detect_capabilities", lambda: _capabilities(True)+ )+ monkeypatch.setattr(clipboard, "detect_platform", lambda: "win32")+ monkeypatch.setattr(clipboard, "_read_windows", lambda: "Unicode: café")++ assert clipboard.read_text() == "Unicode: café"+++def test_linux_prefers_wayland_for_reading(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ clipboard.shutil,+ "which",+ lambda name: "/usr/bin/wl-paste" if name == "wl-paste" else None,+ )+ calls: list[list[str]] = []+ monkeypatch.setattr(+ clipboard,+ "_read_command",+ lambda command: (calls.append(list(command)), "wayland text")[1],+ )++ assert clipboard._read_linux() == "wayland text"+ assert calls == [["/usr/bin/wl-paste", "--no-newline"]]+++def test_linux_without_any_clipboard_tool_reads_nothing(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(clipboard.shutil, "which", lambda _name: None)+ assert clipboard._read_linux() is None+++def test_read_command_failure_is_reported_as_unavailable(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def _run(command: list[str], **_kwargs: object) -> subprocess.CompletedProcess[str]:+ return subprocess.CompletedProcess(command, 1, stdout="", stderr="no display")++ monkeypatch.setattr(clipboard.subprocess, "run", _run)+ assert clipboard._read_command(["xclip", "-o"]) is None+++def test_empty_clipboard_reads_as_empty_string_not_unavailable(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def _run(command: list[str], **_kwargs: object) -> subprocess.CompletedProcess[str]:+ return subprocess.CompletedProcess(command, 0, stdout="", stderr="")++ monkeypatch.setattr(clipboard.subprocess, "run", _run)+ assert clipboard._read_command(["pbpaste"]) == ""