You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The #207 viewer runs noVNC in a Chromium app window through x11vnc and a loopback bridge. It can only watch, it depends on VNC, and it costs a browser process per window.
Acceptance criteria
A new Rust binary, pickforge-viewer, shows one lab session in a native window on Wayland and X11 hosts. It reads the session's own Xvfb display directly, with no VNC server, bridge or browser.
Frames come from shared-memory capture and update on damage, so an idle session costs close to no CPU. Capture pauses while the window is hidden or minimized.
The image scales to the window and keeps its aspect ratio. The session's cursor is visible.
The window opens as a thumbnail, 384 logical pixels wide, pinned in the bottom-right corner on Hyprland, without taking focus. A click expands it to the session size, capped to the screen. A slim bar offers Fullscreen and Collapse. Status text shows connecting and session ended.
This part is watch only. The viewer sends no input to the session.
pickforge-lab watch and viewer.mode: "auto" use the native viewer when it is installed, and fall back to the noVNC viewer otherwise.
CPU use is measured against the noVNC viewer for idle, scrolling and animation, and recorded in the PR.
The candidate artifacts build the binary into the Linux x86_64 release asset, and the installer installs it. The release config change waits for owner approval at merge.
Checklist
Crate, X11 capture and window rendering
Thumbnail, expand, fullscreen and collapse, with the Hyprland adapter
CLI integration and fallback
Benchmarks
Release asset and installer
Tests, README, SECURITY.md and docs/releases/UNRELEASED.md
Technical plan for #340 and #341, written by the planning pass on 542d3ee. #341 stacks on #340.
One addition beyond the owner decisions: a small close button in the viewer bar, because a frameless window on compositors without server-side decorations has no other close control. Closing still returns control, per decision 5.
Implementation plan: #340 native PiP viewer (watch only) and #341 take control + request_takeover
Repo: /home/dev/Projects/Pickforge/pickforge at 542d3ee. Host facts gathered read-only: Rust 1.96, Hyprland 0.56.2 with configProvider: "lua" (so the existing Lua-rule adapter applies), notify-send, Xvfb, x11vnc, xdotool on PATH, no pickforge-viewer yet. Cargo.lock has no winit/x11rb/egui today.
0. Where the current code contradicts the settled owner decisions (must change, not reopen)
1: viewer injects input itself, no second writable x11vnc
startHumanTakeover in packages/desktop-linux/src/takeover.ts always stops the view-only x11vnc and restarts it writable, and records vncPid/vncPort on the lease; endHumanTakeover always reverts VNC. recoverStaleTakeoverLocked in session.ts only knows how to stop a writable VNC.
#341 adds an input transport to the orchestration (transport: "x11vnc" | "viewer"); the VNC switch becomes the fallback path only. The core lease primitives in packages/core/src/takeover.ts are transport-agnostic and stay as they are.
3: MCP may open the viewer with viewer.mode: "auto"
sessionStatusEntry in packages/mcp-server/src/tools/session.ts:212 hard-codes hostGuiLaunchSupported = false; README line 871 ("MCP never launches host GUI" lineage from #207).
Becomes true only when mode is auto, the native binary is on PATH and a graphical session exists.
7: screenshot and wait busy during control
README line 601: "desktop_screenshot is the only desktop tool left ungated"; registerScreenshotTool/registerWaitTool in packages/mcp-server/src/tools/desktop.ts have no lease check.
Add the gate (section 4) and rewrite that README paragraph.
2: request_takeover is how an agent asks
SECRET_GUIDANCE in packages/mcp-server/src/tools/user.ts:16 and the takeover_status description in tools/takeover.ts:20 tell the agent to ask the human to run watch --control.
Point both at request_takeover / takeover_wait.
5: Esc goes to the session during control
noVNC page uses Escape to collapse.
Native viewer: Esc collapses only in watch mode; during control every key is forwarded.
1 (continued): native viewer needs no VNC
watchWithBrowser in packages/cli/src/commands/watch.ts calls ensureSessionVnc and ensureViewerBridge before it even checks for a graphical session.
Native path must be chosen before any x11vnc/bridge is started; VNC stays untouched, so other noVNC watchers keep working during control (the #207 "thumbnail stays live" property is preserved for free).
Nothing in the lease state machine itself contradicts the decisions; the owner pid of the lease is process.pid of the acquirer (buildHumanLease), which fits the "TypeScript supervisor holds the lease" design below.
pickforge-lab watch / session create --viewer / MCP (auto only)
└─ ensureNativeViewerHost(sessionId) (TS, packages/cli/src/viewer/native-host.ts)
└─ startDaemon(node, [cliEntry, "internal", "viewer-host", "--session", id, ...])
viewer host (TS, detached, pattern copied from bridge-daemon.ts)
├─ spawns pickforge-viewer with stdio pipes (same process group, NOT detached)
├─ stdin/stdout: newline-delimited JSON commands/events
├─ Unix socket <sessionDataDir>/viewer/host.sock (0700 dir) for CLI/MCP ops
├─ readiness file <viewer dir>/host.json {pid,startTicks,socket,launchId}
└─ #341: owns the human lease, heartbeat, watchdog, notification
Why a host even in #340: #341 needs a long-lived lab-core-capable process that outlives the CLI (auto mode returns immediately) and that teardown can find by identity. Introducing it in #340 keeps #341 purely additive (new ops, no relaunch rewrite). It replaces the bridge daemon process on the native path, so process count does not grow versus today.
Who launches: watchDesktopSession in packages/cli/src/commands/watch.ts gains a first branch: detectNativeViewer() (findOnPath("pickforge-viewer"), then --version must equal the CLI version, else treat as absent and log why) and hasGraphicalSession(); if both, watchWithNative, else the existing watchWithBrowser (unchanged). runSessionCreate in commands/session.ts already routes through watchDesktopSession, so viewer.mode: "auto" gets the preference for free.
How the viewer learns the display: argv only. The host resolves the session record, validates the display with the existing verifyOwnedDisplayTarget (packages/desktop-linux/src/x11-target.ts, which checks Xvfb argv, -nolisten tcp, no -auth, lock pid, socket inode, uid) and passes --display :N --xvfb-pid P --xvfb-start-ticks T --width W --height H --class pickforge-viewer-<launchId> --thumbnail-width 384. The viewer must refuse --display equal to its own host DISPLAY.
X authority: Xvfb is started by buildXvfbArgs with -nolisten tcp and no -auth, so local connections need no cookie. The viewer connects by opening /tmp/.X11-unix/XN as a UnixStream and calling x11rb::rust_connection::RustConnection::connect_to_stream_with_auth_info(stream, 0, empty, empty); it never reads ~/.Xauthority (mirrors the TS X11Wire "empty-auth setup" and the XAUTHORITY: /dev/null discipline in x11-prebind.ts). The viewer's own window uses the untouched host env (WAYLAND_DISPLAY/DISPLAY); the host must spawn it with the caller env, never with createIsolatedDesktopEnvironment (that would poison WAYLAND_DISPLAY and map the window on the Xvfb).
Session end detection: three signals, any one suffices: (a) X connection EOF/IO error on the capture thread (Xvfb exited), (b) viewer polls /proc/P/stat start ticks every 5 s against --xvfb-start-ticks, (c) host watches the record like sessionEnded() in watch.ts (read under withSessionVncLock) and sends {"cmd":"sessionEnded"}. Viewer shows "session ended", keeps the last frame, stops capture. Teardown: stopSessionViewer in viewer-state.ts gets a kind: "native" launch record (fields: hostPid/hostStartTicks, viewerPid/viewerStartTicks) and stops host then viewer by verified identity, as it does for browsers.
1.2 Window stack
Evaluated:
Option
Verdict
winit 0.30 + softbuffer 0.4 + fontdue + one embedded OFL font
Chosen. Pure-Rust Wayland backend (wayland-backend rust impl; libxkbcommon dlopen'ed at runtime, present on every Wayland desktop), X11 backend via x11rb, CPU presentation through wl_shm/XPutImage. No GL/EGL, no system GTK, builds on a bare ubuntu-latest runner with no apt packages. Stripped binary roughly 3–5 MB. Cost: we draw the bar ourselves (three flat buttons, one status label, one banner) — a few hundred lines; antialiased text from fontdue gives the "polished minimal" look.
egui/eframe
Rejected: needs glow (EGL/GL context, fails in containers without llvmpipe) or wgpu (very large), binary 12–20 MB, a GPU driver dependency for a thumbnail, and per-frame texture upload is no cheaper than a CPU blit at 384 px.
iced
Rejected: same weight class; tiny-skia backend still drags the framework.
Rejected: two window implementations for one window.
Window attributes: with_decorations(false), with_transparent(false), with_resizable(true), Wayland WindowAttributesExtWayland::with_name(class, class) and X11 with_name(class, class) so the compositor sees app_id = pickforge-viewer-<launchId> deterministically (no Chromium URL-derived id games). viewerClassPattern in packages/cli/src/viewer/hyprland.ts gets a native variant ^pickforge-viewer-<launchId>$; hyprlandRuleName, buildRuleInstallLua, installViewerRule, disableViewerRule, waitForViewerWindow, applyHyprlandWindowMode, placeViewerWindow are reused unchanged (pid = viewer pid).
Modes and placement: thumbnail (384 logical px wide, no controls, click expands and is consumed), expanded (session size capped to 90 % work area via placeViewerWindow), fullscreen (set_fullscreen(Borderless(None))). Wayland cannot position windows, so expand/collapse is a round trip exactly like today's bridge window API: viewer emits expandRequested → host runs applyHyprlandWindowMode (resize+move by address) → host replies setMode{mode,size} → viewer request_inner_size. On non-Hyprland the viewer resizes itself and the compositor places it. Bar: 32 logical px, top of the expanded window, buttons Fullscreen and Collapse (#340), Take/Return control (#341); status text bottom-left overlay ("connecting", "session ended", "viewer stopped"). Esc collapses in watch mode only. Note for the owner: non-Hyprland hosts without SSD get a frameless window with no close affordance; I suggest a small "×" in the bar (closing = return control in #341). This is an addition, not a reopened decision.
HiDPI: softbuffer buffers are physical pixels; bar metrics and font size multiply by window.scale_factor() (Hyprland fractional scale is handled by winit). Thumbnail/expanded sizes stay logical, matching viewerWindowSizes and the Lua rule.
1.3 Capture
Crate feature set: x11rb = { features = ["shm", "damage", "xfixes", "xinput", "xtest"] } (xtest in #341).
One capture thread owns the session RustConnection. Frames: shm::create_segment via memfd_create + shm::attach_fd (MIT-SHM 1.2, supported by Xvfb); fallback to plain GetImage when attach fails (e.g. restricted containers). ShmGetImage(root, x, y, w, h) of the damage bounding box only, blitted into a CPU Frame (BGRX, session size, two buffers).
DAMAGE: damage::create(root, ReportLevel::BOUNDING_BOX); on DamageNotify accumulate the rect, damage::subtract, fetch, coalesce to at most one fetch per 16 ms. An idle session yields zero events, so idle CPU is the Wayland frame callback only (none while not redrawing).
Cursor: xfixes::select_cursor_input(root, DISPLAY_CURSOR) + get_cursor_image on CursorNotify; position via XInput2 RawMotion selected on root (no polling, no grab); fallback: query_pointer at 20 Hz while visible if XI2 is absent. Cursor is composited client-side onto the scaled frame (this is what the x11vnc -nocursorshape note in watch: picture-in-picture live view with bundled noVNC and separate take-control #207 did server-side).
Frames reach the UI thread as Arc<Frame> + dirty rect through EventLoopProxy::send_event; the UI thread rescales only dirty output rows and present_with_damage.
Pause: on WindowEvent::Occluded(true) or minimized the viewer stops fetching (DAMAGE stays subscribed, events are discarded cheaply); on unhide it does one full fetch. ControlFlow::Wait everywhere.
Scaling: integer-weight area averaging for downscale (3.33× at thumbnail) with precomputed span tables; identity at 1:1; bilinear for upscale in fullscreen/HiDPI. Keep aspect, letterbox with the bar colour. Only dirty rows are recomputed.
The TS viewer host. It calls startHumanTakeover(id, { transport: "viewer" }) (new option in packages/desktop-linux/src/takeover.ts): acquireHumanLease (drain of agent permits unchanged, owner pid = host pid), no VNC switch, renewHumanLease patch records inputTransport: "viewer" and viewerPid/viewerStartTicks (new optional HumanLease fields in core takeover.ts, parsed in parseHumanLease), evidence takeover_start. The heartbeat/hard-deadline/watchdog triple in runControlledViewer (watch.ts) is extracted into holdHumanLease(handle, { onLost }) in a new packages/cli/src/commands/takeover-hold.ts and used by both the VNC fallback and the host; defaultSpawnWatchdog keeps spawning internal takeover-watchdog, which already works on any lease. endHumanTakeover with transport: "viewer" skips the VNC revert, runs releaseStuckInput(display) (section 3), captures the resume screenshot, releases. recoverStaleTakeoverLocked in session.ts: when the stale lease says inputTransport: "viewer", stopProcessGroupVerified on the owner pid (host + viewer share a group, so a hung host loses its child) then releaseStuckInput.
2.2 Request flow
Viewer ⇄ host (stdio JSON lines, viewer is a child): events ready, mode, expandRequested, collapseRequested, closed, sessionEnded, takeRequested, returnRequested, controlAck{leaseId,state}; commands setMode, status, sessionEnded, shutdown, attention{message}, clearAttention, control{state:"granted",leaseId,grantMs} | {state:"revoked",reason}. Protocol documented in crates/pickforge-viewer/PROTOCOL.md and typed on the TS side in packages/desktop-linux/src/viewer-host-protocol.ts (desktop-linux, not cli, because the MCP server must import it; cli depends on mcp-server, not the reverse).
CLI/MCP → host (Unix socket in the 0700 viewer dir, path verified through withViewerDir): ops status, expand, collapse, requestTakeover{message,timeoutMs}, cancelRequest{requestId}, subscribe (events controlTaken, controlReturned{reason}, viewerClosed). The socket has no op that grants control or injects input; only the child viewer over stdio can emit takeRequested, and only the host calls acquireHumanLease. Message: ≤ 500 chars, control characters rejected, never logged.
Take control: viewer takeRequested → host startHumanTakeover(viewer) → on success host sends control granted with grantMs = heartbeatMs * 2 → viewer enables injection until now + grantMs; every successful renewal re-sends granted. Lease lost (renew undefined, deadline timer, SIGTERM) → host sends revoked, waits ≤ 1 s for controlAck, else SIGKILLs the viewer (dead viewer cannot inject; stuck keys handled by the host backstop). Return control / window close → viewer returnRequested (after its own release-all) → host endHumanTakeover.
request_takeover (MCP): resolve session → if lease active, behave as takeover_wait; else find an open host (host.json identity alive + socket status); none open: with viewer.mode: "auto" and binary and graphical env, launch via an injected launcher (see 2.4); otherwise return { outcome: "viewer_not_open", command: "pickforge-lab watch --session <id>" } and launch nothing. With a host: requestTakeover{message} → host expands through the compositor (never focuswindow), sends attention{message} to the viewer (banner + highlighted Take control button), runs notify-send via argv array (["--app-name=Pickforge", "--urgency=normal", title, body], silently skipped when absent — D-Bus directly would add zbus or a Node D-Bus dependency for no gain on this host) → MCP waits for controlTaken then controlReturned, or timeout, or MCP cancellation (reuse the abort plumbing already proven by packages/mcp-server/test/session-destroy-cancel.test.ts; on cancel send cancelRequest, viewer clears the banner and collapses unless control was taken). Returns { outcome: "returned" | "timeout" | "cancelled" | "viewer_closed", heldMs, screenshot }; the screenshot is taken after the lease is released through the existing captureDesktopScreenshot (export it from tools/desktop.ts), so it goes through the normal observation gate and evidence.
takeover_wait: poll checkHumanLeaseBusy (25–250 ms backoff) until undefined, bounded by timeoutMs (default 10 min, max 1 h), cancellable, returns the same shape with a fresh screenshot.
2.3 Fail-closed invariants and the tests that prove them
Invariant
Proof
I1 Input is injected only while the host's lease is live and the viewer's grant is unexpired
Rust unit: injector with a fake clock refuses after grantMs; Rust Xvfb test: after revoked (or stdin EOF) a listener window receives no further KeyPress; TS host test with the fake viewer: first failed renewal → revoked sent within one heartbeat, SIGKILL after no ack within 1 s
I2 No writable network server ever exists
static scan of crates/ for TcpListener/bind(/listen(; TS test: the x11vnc argv recorder (as in desktop-linux/test/takeover.test.ts) never sees a non--viewonly start on the viewer transport; socket lives under a 0700 dir checked by assertPrivate
I3 The socket cannot grant control
protocol op table test: takeControl/key/pointer ops are rejected as unknown; only stdio takeRequested triggers startHumanTakeover
I4 No stuck keys or buttons after any end reason
Rust Xvfb test: hold Shift + button 1, revoke → query_keymap all zero and query_pointer.mask has no buttons; TS test for releaseStuckInput after xdotool keydown shift
I5 MCP never opens a host window unless mode is auto
MCP test with manual mode: fake binary on PATH, assert no spawn and the exact command returned; auto mode: fake viewer spawned
viewer-state test with a fake viewer that ignores SIGTERM (as viewer-fakes.ts already supports)
2.4 Dependency direction for MCP launching
packages/mcp-server cannot import packages/cli. The host daemon start (startDaemon(process.execPath, [cliEntry, "internal", "viewer-host", ...])) therefore moves into desktop-linux as startNativeViewerHost({ cliEntry, ... }), and createMcpServer in packages/mcp-server/src/index.ts takes an optional viewerLauncher that packages/cli/src/pickforge-mcp.ts injects with its sibling pickforge-lab.js entry. Without a launcher (library use), request_takeover always returns the command.
Keyboard, the text path: use winit's composed KeyEvent.text (Wayland and X11 backends both run xkbcommon compose, so ABNT2 ´+a arrives as "á"; Key::Dead presses are swallowed on the host) and Ime::Commit strings (set_ime_allowed(true), covers fcitx5/CJK). Codepoints → keysyms via a port of codepointToKeysym/keysymToCodepoint (packages/desktop-linux/src/x11-keysyms.ts + x11-legacy-keysyms.ts, generate the legacy table into keysyms.rs). Keymap: port parseModifiers, parseCoreMap, parseXkbMap, usableCodepoints, translatedLevel from x11-keymap.ts and planBindings from x11-prebind.ts to crates/pickforge-viewer/src/keymap.rs, reading via x11rb get_modifier_mapping, get_keyboard_mapping, xkb::get_map; refresh on MappingNotify. Missing symbols are bound with change_keyboard_mapping to spare keycodes (highest empty non-modifier first, min reserved for desktop_key, never restored — same ledger rules as docs/desktop-typing.md); allocation is impossible to race with agent typing because the lease excludes it.
Modifier reconciliation: forward Shift/Control/Alt/Super/ISO_Level3_Shift presses as real keys so drags and Ctrl+click work; do not forward Caps_Lock/Num_Lock (host compose already applied them; keeps the session Lock state off and lookup deterministic). Before each text key: read current state (query_pointer.mask), compute the level needed via the XKB type entries, press missing modifiers, temporarily release conflicting ones, press/release the keycode, restore.
Named keys and chords: logical_key Named → keysym table (Return, Escape, arrows, F-keys, Tab, BackSpace, Delete, Home/End/Page). Ctrl+letter has text None → use logical_key Character with the current modifier state. Repeats (repeat: true) are forwarded as release+press.
Stuck key/button release: viewer keeps down_keycodes/down_buttons; releases all on revoke, Focused(false), close, session end, panic (catch_unwind + Drop guard on the XTEST connection). Backstop in TS: releaseStuckInput(display) in desktop-linux = raw-wire QueryKeymap (32-byte bitmask) + xdotool keyup <code> per down code and xdotool mouseup 1..7, argv arrays only; called by endHumanTakeover(viewer) and recoverStaleTakeoverLocked. XTEST state does not clear on client disconnect, which is why the backstop exists.
4. MCP tools, busy rule, timeouts, notification
tools/desktop.ts: new assertNoHumanLease(ctx, id) (uses checkHumanLeaseBusy, throws HumanControlActiveError) before captureDesktopScreenshot and inside the wait loop. Gate desktopWait per sample through a new opts.busyCheck?: () => Promise<void> in packages/desktop-linux/src/wait.ts (not a permit: a permit would make acquireHumanLease drain-time out against a 300 s wait). The screenshot() primitive itself stays ungated because endHumanTakeover captures the resume shot while the lease is still held. Apply the same gate to CLI desktop screenshot/wait for parity.
tools/takeover.ts: add request_takeover{session?, message, timeoutMs?} and takeover_wait{session?, timeoutMs?}; update the takeover_status description. Evidence actions takeover_requested and takeover_wait via withMcpEvidence.
tools/user.ts: SECRET_GUIDANCE says "call request_takeover with a short message".
Timeouts: request_takeover default 10 min, cap 1 h; the lease itself stays heartbeat-bounded (30 s TTL / 5 s renew) and unbounded in duration; on timeout the tool returns timeout, control may still be taken later and input stays busy.
Notification: notify-send from the host via runCommand argv array; body = first 120 chars of the message after control-char stripping; absent binary → no error.
5. Release, installer, CI
Touches release config (owner approval at merge):
.github/workflows/candidate-artifacts.ymlrust-binaries: Linux matrix entry additionally runs cargo build --release --locked --target x86_64-unknown-linux-gnu -p pickforge-viewer, copies to release-assets/pickforge-viewer-linux-x86_64, strips, writes .sha256. Same artifact name pickforge-linux-x86_64, so release.yml's pattern: pickforge-* upload and gh release upload release-assets/* need no change. macOS entry unchanged (viewer is Linux-only).
docs/releases/CHECKLIST.md "asset list must be exactly" gains the two viewer files and a --version check.
scripts/install.sh: install_viewer_binary after install_rust_binary, Linux x86_64 only, same download/checksum/--version (pickforge-viewer <version>) pattern, installs ${bin_dir}/pickforge-viewer. packages/cli/test/installer.test.ts fixtures gain the asset.
scripts/candidate-smoke.sh: verify and install the viewer asset on Linux, run pickforge-viewer --version and --self-test (headless: keymap fixture parse, scaler golden) inside the Flutter container.
Crate: crates/pickforge-viewer/Cargo.toml with version.workspace = true (so check-release-versions.mjs needs no change), [[bin]] name = "pickforge-viewer", Linux-only deps under [target.'cfg(target_os = "linux")'.dependencies] and a non-Linux main stub, because ci.yml runs cargo clippy --workspace --all-targets -- -D warnings and cargo test --workspace on Windows too. Add crates/ to scanRoots() in test/security/security-x-display.test.ts (Xvfb spawns in Rust tests must use the explicit-display form).
ci.ymlrust job: on ubuntu install xvfb xdotool and set PICKFORGE_REQUIRE_XVFB=1 so the Rust Xvfb tests run instead of skip; test job: add the Rust toolchain and cargo build -p pickforge-viewer --release so the TS live viewer test runs with PICKFORGE_REQUIRE_VIEWER=1. candidate-smokes-pr.yml already filters on crates/**.
npm-only installs: detectNativeViewer() returns null → watch uses noVNC (watch only), watch --control keeps the external-VNC-client path, request_takeover returns the watch --control command plus an install hint. Documented in README and UNRELEASED.
6. Test and QA strategy (never the live desktop, except one check)
Rust unit (cargo test, no display): keymap parser against byte fixtures captured from a real Xvfb (tests/fixtures/*.bin), binding planner cases ported from x11-prebind.test.ts (case pairs, capacity exhausted, min reserved), scaler goldens, pointer mapping, protocol framing, grant-expiry injector.
Rust Xvfb integration (tests/xvfb.rs): start Xvfb :<n> -screen 0 640x480x24 -nolisten tcp -noreset with an explicit display chosen like test-resources.ts (random 10000–50000, lock-file probe); the capture and inject modules are separate from the window code so they run headless: draw with an x11rb window, assert the captured frame; assert DAMAGE delivery; type "ção ÁÉ ñ ß € Ctrl+c" and decode the KeyPress events in a listener window through the session keymap; stuck-key assertions (I4).
TS unit/integration with a fake viewer (packages/cli/test/viewer-fakes.ts gains installViewer(): a Node script speaking the stdio protocol, recording commands, emitting events from a cue file) and the existing fake hyprctl: host lifecycle, launch record, teardown, fallback when the binary is absent or version-mismatched, Hyprland rule with the native class, socket ops, notify-send argv recorder, lease fail-closed timing, MCP tool behaviours (I5, I6), security scans.
QA journey in CI and locally (packages/cli/test/native-viewer-live.test.ts): two Pickforge desktop sessions A (watched) and B (host); run the real pickforge-viewer with WINIT_UNIX_BACKEND=x11 DISPLAY=:B watching :A; drive the viewer window on B with xdotool (click to expand, click Take control, type, click Return control) and assert pixels/keys on A. This exercises the full winit X11 path with no compositor and never touches the host desktop. Both displays are explicit, satisfying AGENTS.md.
Unavoidable live Hyprland check (dev machine, Hyprland 0.56.2 Lua): one throwaway desktop session, pickforge-lab watch, confirm via hyprctl -j clients that the window maps floating, pinned, bottom-right, focusHistoryID != 0 (no focus); expand/collapse/fullscreen resize; request_takeover grows the window without focus and mako shows the notification; close returns control. Why: Hyprland's treatment of winit app_id, pinned-floating size changes and no_initial_focus cannot be emulated by the fake hyprctl. The CPU benchmarks also must run live (the Wayland present path differs from X11): scripts/lab/viewer-bench.mjs samples /proc/<pid>/stat utime+stime for the viewer+host versus chromium tree+bridge+x11vnc over idle 60 s, xdotool scroll loop in an xterm, and a text-animation xterm; results go in the watch: native Rust picture-in-picture viewer #340 PR.
Order: (1) lease transport + stuck release + recovery (TS, testable with fake x11vnc as today); (2) keymap port + injector + Xvfb tests (Rust); (3) host control grants + fail-closed tests; (4) viewer buttons/banner; (5) MCP tools + gates + launcher injection; (6) live Hyprland check; (7) docs/security tests.
Risks
Keymap spare-keycode budget is shared with agent desktop_type; a long human session typing exotic characters could exhaust it. Mitigate: viewer reuses its own bindings and caps new ones; document.
Lock-state and layout edge cases (Caps on host, titlecase) — covered by not forwarding lock keys and by the reconciliation tests; still the riskiest module.
winit Wayland behaviour on compositors other than Hyprland (no SSD, no placement) is "ordinary window" by decision, but a frameless window with no close button is a usability gap (the "×" suggestion).
The host is a detached Node process; a hung host is reclaimed by the watchdog and the viewer's grant expiry (≤ 10 s), well inside the 30 s TTL.
Rust cargo test --workspace on Windows must stay green with the Linux-only crate (stub main + cfg deps).
Cargo.lock grows by roughly 150 crates (winit stack); osv-scanner in CI scans it, so pin to current versions and expect review of the new tree.
Parallel split without overlapping writes
Each PR splits cleanly along the language boundary once PROTOCOL.md is fixed: worker 1 owns crates/ only (viewer, tests, fixtures); worker 2 owns packages/, scripts/, .github/, docs, with the fake viewer standing in for the binary. The only shared file is Cargo.lock/Cargo.toml (worker 1) versus ci.yml's cargo steps (worker 2), which do not conflict textually. In PR B the same split holds: keymap/injector (worker 1) versus lease transport, host ops, MCP tools and gates (worker 2).
packages/desktop-linux/src/takeover.ts (viewer transport without the x11vnc switch; stuck-input backstop; end/recovery paths)
packages/cli/src/viewer/bridge-daemon.ts (the daemon/readiness/identity pattern the viewer host copies) together with packages/desktop-linux/src/viewer-state.ts (launch records, teardown)
packages/desktop-linux/src/x11-keymap.ts plus x11-prebind.ts/x11-keysyms.ts (the keymap and binding logic to port into crates/pickforge-viewer/src/keymap.rs)
packages/mcp-server/src/tools/takeover.ts with tools/desktop.ts (new request_takeover/takeover_wait, screenshot and wait busy gate) and .github/workflows/candidate-artifacts.yml with scripts/install.sh (release asset and installer, owner-approved)
Activity
ElbertePlinio commentedon Oct 28, 2026
Technical plan for #340 and #341, written by the planning pass on 542d3ee. #341 stacks on #340.
One addition beyond the owner decisions: a small close button in the viewer bar, because a frameless window on compositors without server-side decorations has no other close control. Closing still returns control, per decision 5.
Implementation plan: #340 native PiP viewer (watch only) and #341 take control +
request_takeoverRepo:
/home/dev/Projects/Pickforge/pickforgeat542d3ee. Host facts gathered read-only: Rust 1.96, Hyprland 0.56.2 withconfigProvider: "lua"(so the existing Lua-rule adapter applies),notify-send,Xvfb,x11vnc,xdotoolon PATH, nopickforge-vieweryet.Cargo.lockhas no winit/x11rb/egui today.0. Where the current code contradicts the settled owner decisions (must change, not reopen)
startHumanTakeoverinpackages/desktop-linux/src/takeover.tsalways stops the view-only x11vnc and restarts it writable, and recordsvncPid/vncPorton the lease;endHumanTakeoveralways reverts VNC.recoverStaleTakeoverLockedinsession.tsonly knows how to stop a writable VNC.transport: "x11vnc" | "viewer"); the VNC switch becomes the fallback path only. The core lease primitives inpackages/core/src/takeover.tsare transport-agnostic and stay as they are.viewer.mode: "auto"sessionStatusEntryinpackages/mcp-server/src/tools/session.ts:212hard-codeshostGuiLaunchSupported = false; README line 871 ("MCP never launches host GUI" lineage from #207).trueonly when mode isauto, the native binary is on PATH and a graphical session exists.desktop_screenshotis the only desktop tool left ungated";registerScreenshotTool/registerWaitToolinpackages/mcp-server/src/tools/desktop.tshave no lease check.request_takeoveris how an agent asksSECRET_GUIDANCEinpackages/mcp-server/src/tools/user.ts:16and thetakeover_statusdescription intools/takeover.ts:20tell the agent to ask the human to runwatch --control.request_takeover/takeover_wait.watchWithBrowserinpackages/cli/src/commands/watch.tscallsensureSessionVncandensureViewerBridgebefore it even checks for a graphical session.Nothing in the lease state machine itself contradicts the decisions; the owner pid of the lease is
process.pidof the acquirer (buildHumanLease), which fits the "TypeScript supervisor holds the lease" design below.1. Architecture of the viewer (#340)
1.1 Process model
Three processes, one language boundary:
Why a host even in #340: #341 needs a long-lived lab-core-capable process that outlives the CLI (auto mode returns immediately) and that teardown can find by identity. Introducing it in #340 keeps #341 purely additive (new ops, no relaunch rewrite). It replaces the bridge daemon process on the native path, so process count does not grow versus today.
watchDesktopSessioninpackages/cli/src/commands/watch.tsgains a first branch:detectNativeViewer()(findOnPath("pickforge-viewer"), then--versionmust equal the CLI version, else treat as absent and log why) andhasGraphicalSession(); if both,watchWithNative, else the existingwatchWithBrowser(unchanged).runSessionCreateincommands/session.tsalready routes throughwatchDesktopSession, soviewer.mode: "auto"gets the preference for free.verifyOwnedDisplayTarget(packages/desktop-linux/src/x11-target.ts, which checksXvfbargv,-nolisten tcp, no-auth, lock pid, socket inode, uid) and passes--display :N --xvfb-pid P --xvfb-start-ticks T --width W --height H --class pickforge-viewer-<launchId> --thumbnail-width 384. The viewer must refuse--displayequal to its own hostDISPLAY.buildXvfbArgswith-nolisten tcpand no-auth, so local connections need no cookie. The viewer connects by opening/tmp/.X11-unix/XNas aUnixStreamand callingx11rb::rust_connection::RustConnection::connect_to_stream_with_auth_info(stream, 0, empty, empty); it never reads~/.Xauthority(mirrors the TSX11Wire"empty-auth setup" and theXAUTHORITY: /dev/nulldiscipline inx11-prebind.ts). The viewer's own window uses the untouched host env (WAYLAND_DISPLAY/DISPLAY); the host must spawn it with the caller env, never withcreateIsolatedDesktopEnvironment(that would poisonWAYLAND_DISPLAYand map the window on the Xvfb)./proc/P/statstart ticks every 5 s against--xvfb-start-ticks, (c) host watches the record likesessionEnded()in watch.ts (read underwithSessionVncLock) and sends{"cmd":"sessionEnded"}. Viewer shows "session ended", keeps the last frame, stops capture. Teardown:stopSessionViewerinviewer-state.tsgets akind: "native"launch record (fields:hostPid/hostStartTicks,viewerPid/viewerStartTicks) and stops host then viewer by verified identity, as it does for browsers.1.2 Window stack
Evaluated:
wl_shm/XPutImage. No GL/EGL, no system GTK, builds on a bareubuntu-latestrunner with no apt packages. Stripped binary roughly 3–5 MB. Cost: we draw the bar ourselves (three flat buttons, one status label, one banner) — a few hundred lines; antialiased text from fontdue gives the "polished minimal" look.Window attributes:
with_decorations(false),with_transparent(false),with_resizable(true), WaylandWindowAttributesExtWayland::with_name(class, class)and X11with_name(class, class)so the compositor seesapp_id=pickforge-viewer-<launchId>deterministically (no Chromium URL-derived id games).viewerClassPatterninpackages/cli/src/viewer/hyprland.tsgets a native variant^pickforge-viewer-<launchId>$;hyprlandRuleName,buildRuleInstallLua,installViewerRule,disableViewerRule,waitForViewerWindow,applyHyprlandWindowMode,placeViewerWindoware reused unchanged (pid = viewer pid).Modes and placement: thumbnail (384 logical px wide, no controls, click expands and is consumed), expanded (session size capped to 90 % work area via
placeViewerWindow), fullscreen (set_fullscreen(Borderless(None))). Wayland cannot position windows, so expand/collapse is a round trip exactly like today's bridge window API: viewer emitsexpandRequested→ host runsapplyHyprlandWindowMode(resize+move by address) → host repliessetMode{mode,size}→ viewerrequest_inner_size. On non-Hyprland the viewer resizes itself and the compositor places it. Bar: 32 logical px, top of the expanded window, buttons Fullscreen and Collapse (#340), Take/Return control (#341); status text bottom-left overlay ("connecting", "session ended", "viewer stopped"). Esc collapses in watch mode only. Note for the owner: non-Hyprland hosts without SSD get a frameless window with no close affordance; I suggest a small "×" in the bar (closing = return control in #341). This is an addition, not a reopened decision.HiDPI: softbuffer buffers are physical pixels; bar metrics and font size multiply by
window.scale_factor()(Hyprland fractional scale is handled by winit). Thumbnail/expanded sizes stay logical, matchingviewerWindowSizesand the Lua rule.1.3 Capture
Crate feature set:
x11rb = { features = ["shm", "damage", "xfixes", "xinput", "xtest"] }(xtest in #341).RustConnection. Frames:shm::create_segmentviamemfd_create+shm::attach_fd(MIT-SHM 1.2, supported by Xvfb); fallback to plainGetImagewhen attach fails (e.g. restricted containers).ShmGetImage(root, x, y, w, h)of the damage bounding box only, blitted into a CPUFrame(BGRX, session size, two buffers).damage::create(root, ReportLevel::BOUNDING_BOX); onDamageNotifyaccumulate the rect,damage::subtract, fetch, coalesce to at most one fetch per 16 ms. An idle session yields zero events, so idle CPU is the Wayland frame callback only (none while not redrawing).xfixes::select_cursor_input(root, DISPLAY_CURSOR)+get_cursor_imageonCursorNotify; position via XInput2RawMotionselected on root (no polling, no grab); fallback:query_pointerat 20 Hz while visible if XI2 is absent. Cursor is composited client-side onto the scaled frame (this is what the x11vnc-nocursorshapenote in watch: picture-in-picture live view with bundled noVNC and separate take-control #207 did server-side).Arc<Frame>+ dirty rect throughEventLoopProxy::send_event; the UI thread rescales only dirty output rows andpresent_with_damage.WindowEvent::Occluded(true)or minimized the viewer stops fetching (DAMAGE stays subscribed, events are discarded cheaply); on unhide it does one full fetch.ControlFlow::Waiteverywhere.Scaling: integer-weight area averaging for downscale (3.33× at thumbnail) with precomputed span tables; identity at 1:1; bilinear for upscale in fullscreen/HiDPI. Keep aspect, letterbox with the bar colour. Only dirty rows are recomputed.
2. Control channel (#341)
2.1 Who holds the lease
The TS viewer host. It calls
startHumanTakeover(id, { transport: "viewer" })(new option inpackages/desktop-linux/src/takeover.ts):acquireHumanLease(drain of agent permits unchanged, owner pid = host pid), no VNC switch,renewHumanLeasepatch recordsinputTransport: "viewer"andviewerPid/viewerStartTicks(new optionalHumanLeasefields in coretakeover.ts, parsed inparseHumanLease), evidencetakeover_start. The heartbeat/hard-deadline/watchdog triple inrunControlledViewer(watch.ts) is extracted intoholdHumanLease(handle, { onLost })in a newpackages/cli/src/commands/takeover-hold.tsand used by both the VNC fallback and the host;defaultSpawnWatchdogkeeps spawninginternal takeover-watchdog, which already works on any lease.endHumanTakeoverwithtransport: "viewer"skips the VNC revert, runsreleaseStuckInput(display)(section 3), captures the resume screenshot, releases.recoverStaleTakeoverLockedinsession.ts: when the stale lease saysinputTransport: "viewer",stopProcessGroupVerifiedon the owner pid (host + viewer share a group, so a hung host loses its child) thenreleaseStuckInput.2.2 Request flow
ready, mode, expandRequested, collapseRequested, closed, sessionEnded, takeRequested, returnRequested, controlAck{leaseId,state}; commandssetMode, status, sessionEnded, shutdown, attention{message}, clearAttention, control{state:"granted",leaseId,grantMs} | {state:"revoked",reason}. Protocol documented incrates/pickforge-viewer/PROTOCOL.mdand typed on the TS side inpackages/desktop-linux/src/viewer-host-protocol.ts(desktop-linux, not cli, because the MCP server must import it; cli depends on mcp-server, not the reverse).withViewerDir): opsstatus, expand, collapse, requestTakeover{message,timeoutMs}, cancelRequest{requestId}, subscribe(eventscontrolTaken, controlReturned{reason}, viewerClosed). The socket has no op that grants control or injects input; only the child viewer over stdio can emittakeRequested, and only the host callsacquireHumanLease. Message: ≤ 500 chars, control characters rejected, never logged.takeRequested→ hoststartHumanTakeover(viewer)→ on success host sendscontrol grantedwithgrantMs = heartbeatMs * 2→ viewer enables injection untilnow + grantMs; every successful renewal re-sendsgranted. Lease lost (renewundefined, deadline timer, SIGTERM) → host sendsrevoked, waits ≤ 1 s forcontrolAck, else SIGKILLs the viewer (dead viewer cannot inject; stuck keys handled by the host backstop). Return control / window close → viewerreturnRequested(after its own release-all) → hostendHumanTakeover.request_takeover(MCP): resolve session → if lease active, behave astakeover_wait; else find an open host (host.jsonidentity alive + socketstatus); none open: withviewer.mode: "auto"and binary and graphical env, launch via an injected launcher (see 2.4); otherwise return{ outcome: "viewer_not_open", command: "pickforge-lab watch --session <id>" }and launch nothing. With a host:requestTakeover{message}→ host expands through the compositor (neverfocuswindow), sendsattention{message}to the viewer (banner + highlighted Take control button), runsnotify-sendvia argv array (["--app-name=Pickforge", "--urgency=normal", title, body], silently skipped when absent — D-Bus directly would add zbus or a Node D-Bus dependency for no gain on this host) → MCP waits forcontrolTakenthencontrolReturned, or timeout, or MCP cancellation (reuse the abort plumbing already proven bypackages/mcp-server/test/session-destroy-cancel.test.ts; on cancel sendcancelRequest, viewer clears the banner and collapses unless control was taken). Returns{ outcome: "returned" | "timeout" | "cancelled" | "viewer_closed", heldMs, screenshot }; the screenshot is taken after the lease is released through the existingcaptureDesktopScreenshot(export it fromtools/desktop.ts), so it goes through the normal observation gate and evidence.takeover_wait: pollcheckHumanLeaseBusy(25–250 ms backoff) until undefined, bounded bytimeoutMs(default 10 min, max 1 h), cancellable, returns the same shape with a fresh screenshot.2.3 Fail-closed invariants and the tests that prove them
grantMs; Rust Xvfb test: afterrevoked(or stdin EOF) a listener window receives no furtherKeyPress; TS host test with the fake viewer: first failed renewal →revokedsent within one heartbeat, SIGKILL after no ack within 1 scrates/forTcpListener/bind(/listen(; TS test: the x11vnc argv recorder (as indesktop-linux/test/takeover.test.ts) never sees a non--viewonlystart on the viewer transport; socket lives under a 0700 dir checked byassertPrivatetakeControl/key/pointerops are rejected as unknown; only stdiotakeRequestedtriggersstartHumanTakeoverquery_keymapall zero andquery_pointer.maskhas no buttons; TS test forreleaseStuckInputafterxdotool keydown shiftautotakeover.test.ts(acquire lease, call tools, expecthuman_control_active)viewer-fakes.tsalready supports)2.4 Dependency direction for MCP launching
packages/mcp-servercannot importpackages/cli. The host daemon start (startDaemon(process.execPath, [cliEntry, "internal", "viewer-host", ...])) therefore moves into desktop-linux asstartNativeViewerHost({ cliEntry, ... }), andcreateMcpServerinpackages/mcp-server/src/index.tstakes an optionalviewerLauncherthatpackages/cli/src/pickforge-mcp.tsinjects with its siblingpickforge-lab.jsentry. Without a launcher (library use),request_takeoveralways returns the command.3. Input forwarding (#341)
fake_inputon the session connection:MotionNotifywith root coordinates,ButtonPress/Release(winit Left/Middle/Right/Back/Forward → 1/2/3/8/9), scrollLineDelta→ buttons 4/5/6/7 per step,PixelDelta(Wayland touchpads) accumulated and emitted every 20 px.KeyEvent.text(Wayland and X11 backends both run xkbcommon compose, so ABNT2´+aarrives as"á";Key::Deadpresses are swallowed on the host) andIme::Commitstrings (set_ime_allowed(true), covers fcitx5/CJK). Codepoints → keysyms via a port ofcodepointToKeysym/keysymToCodepoint(packages/desktop-linux/src/x11-keysyms.ts+x11-legacy-keysyms.ts, generate the legacy table intokeysyms.rs). Keymap: portparseModifiers,parseCoreMap,parseXkbMap,usableCodepoints,translatedLevelfromx11-keymap.tsandplanBindingsfromx11-prebind.tstocrates/pickforge-viewer/src/keymap.rs, reading via x11rbget_modifier_mapping,get_keyboard_mapping,xkb::get_map; refresh onMappingNotify. Missing symbols are bound withchange_keyboard_mappingto spare keycodes (highest empty non-modifier first,minreserved fordesktop_key, never restored — same ledger rules asdocs/desktop-typing.md); allocation is impossible to race with agent typing because the lease excludes it.query_pointer.mask), compute the level needed via the XKB type entries, press missing modifiers, temporarily release conflicting ones, press/release the keycode, restore.logical_keyNamed → keysym table (Return, Escape, arrows, F-keys, Tab, BackSpace, Delete, Home/End/Page). Ctrl+letter hastextNone → uselogical_keyCharacter with the current modifier state. Repeats (repeat: true) are forwarded as release+press.down_keycodes/down_buttons; releases all on revoke,Focused(false), close, session end, panic (catch_unwind+Dropguard on the XTEST connection). Backstop in TS:releaseStuckInput(display)in desktop-linux = raw-wireQueryKeymap(32-byte bitmask) +xdotool keyup <code>per down code andxdotool mouseup 1..7, argv arrays only; called byendHumanTakeover(viewer)andrecoverStaleTakeoverLocked. XTEST state does not clear on client disconnect, which is why the backstop exists.4. MCP tools, busy rule, timeouts, notification
tools/desktop.ts: newassertNoHumanLease(ctx, id)(usescheckHumanLeaseBusy, throwsHumanControlActiveError) beforecaptureDesktopScreenshotand inside the wait loop. GatedesktopWaitper sample through a newopts.busyCheck?: () => Promise<void>inpackages/desktop-linux/src/wait.ts(not a permit: a permit would makeacquireHumanLeasedrain-time out against a 300 s wait). Thescreenshot()primitive itself stays ungated becauseendHumanTakeovercaptures the resume shot while the lease is still held. Apply the same gate to CLIdesktop screenshot/waitfor parity.tools/takeover.ts: addrequest_takeover{session?, message, timeoutMs?}andtakeover_wait{session?, timeoutMs?}; update thetakeover_statusdescription. Evidence actionstakeover_requestedandtakeover_waitviawithMcpEvidence.tools/user.ts:SECRET_GUIDANCEsays "callrequest_takeoverwith a short message".tools/session.ts:hostGuiLaunchSupportedreflects mode/binary/graphical env.request_takeoverdefault 10 min, cap 1 h; the lease itself stays heartbeat-bounded (30 s TTL / 5 s renew) and unbounded in duration; on timeout the tool returnstimeout, control may still be taken later and input stays busy.notify-sendfrom the host viarunCommandargv array; body = first 120 chars of the message after control-char stripping; absent binary → no error.5. Release, installer, CI
Touches release config (owner approval at merge):
.github/workflows/candidate-artifacts.ymlrust-binaries: Linux matrix entry additionally runscargo build --release --locked --target x86_64-unknown-linux-gnu -p pickforge-viewer, copies torelease-assets/pickforge-viewer-linux-x86_64, strips, writes.sha256. Same artifact namepickforge-linux-x86_64, sorelease.yml'spattern: pickforge-*upload andgh release upload release-assets/*need no change. macOS entry unchanged (viewer is Linux-only).docs/releases/CHECKLIST.md"asset list must be exactly" gains the two viewer files and a--versioncheck.scripts/install.sh:install_viewer_binaryafterinstall_rust_binary, Linux x86_64 only, same download/checksum/--version(pickforge-viewer <version>) pattern, installs${bin_dir}/pickforge-viewer.packages/cli/test/installer.test.tsfixtures gain the asset.scripts/candidate-smoke.sh: verify and install the viewer asset on Linux, runpickforge-viewer --versionand--self-test(headless: keymap fixture parse, scaler golden) inside the Flutter container.crates/pickforge-viewer/Cargo.tomlwithversion.workspace = true(socheck-release-versions.mjsneeds no change),[[bin]] name = "pickforge-viewer", Linux-only deps under[target.'cfg(target_os = "linux")'.dependencies]and a non-Linuxmainstub, becauseci.ymlrunscargo clippy --workspace --all-targets -- -D warningsandcargo test --workspaceon Windows too. Addcrates/toscanRoots()intest/security/security-x-display.test.ts(Xvfb spawns in Rust tests must use the explicit-display form).ci.ymlrustjob: on ubuntu installxvfb xdotooland setPICKFORGE_REQUIRE_XVFB=1so the Rust Xvfb tests run instead of skip;testjob: add the Rust toolchain andcargo build -p pickforge-viewer --releaseso the TS live viewer test runs withPICKFORGE_REQUIRE_VIEWER=1.candidate-smokes-pr.ymlalready filters oncrates/**.detectNativeViewer()returns null →watchuses noVNC (watch only),watch --controlkeeps the external-VNC-client path,request_takeoverreturns thewatch --controlcommand plus an install hint. Documented in README and UNRELEASED.6. Test and QA strategy (never the live desktop, except one check)
cargo test, no display): keymap parser against byte fixtures captured from a real Xvfb (tests/fixtures/*.bin), binding planner cases ported fromx11-prebind.test.ts(case pairs, capacity exhausted, min reserved), scaler goldens, pointer mapping, protocol framing, grant-expiry injector.tests/xvfb.rs): startXvfb :<n> -screen 0 640x480x24 -nolisten tcp -noresetwith an explicit display chosen liketest-resources.ts(random 10000–50000, lock-file probe); the capture and inject modules are separate from the window code so they run headless: draw with an x11rb window, assert the captured frame; assert DAMAGE delivery; type"ção ÁÉ ñ ß € Ctrl+c"and decode theKeyPressevents in a listener window through the session keymap; stuck-key assertions (I4).packages/cli/test/viewer-fakes.tsgainsinstallViewer(): a Node script speaking the stdio protocol, recording commands, emitting events from a cue file) and the existing fakehyprctl: host lifecycle, launch record, teardown, fallback when the binary is absent or version-mismatched, Hyprland rule with the native class, socket ops, notify-send argv recorder, lease fail-closed timing, MCP tool behaviours (I5, I6), security scans.packages/cli/test/native-viewer-live.test.ts): two Pickforge desktop sessions A (watched) and B (host); run the realpickforge-viewerwithWINIT_UNIX_BACKEND=x11 DISPLAY=:Bwatching:A; drive the viewer window on B with xdotool (click to expand, click Take control, type, click Return control) and assert pixels/keys on A. This exercises the full winit X11 path with no compositor and never touches the host desktop. Both displays are explicit, satisfying AGENTS.md.pickforge-lab watch, confirm viahyprctl -j clientsthat the window maps floating, pinned, bottom-right,focusHistoryID != 0(no focus); expand/collapse/fullscreen resize;request_takeovergrows the window without focus and mako shows the notification; close returns control. Why: Hyprland's treatment of winitapp_id, pinned-floating size changes andno_initial_focuscannot be emulated by the fake hyprctl. The CPU benchmarks also must run live (the Wayland present path differs from X11):scripts/lab/viewer-bench.mjssamples/proc/<pid>/statutime+stime for the viewer+host versus chromium tree+bridge+x11vnc over idle 60 s,xdotoolscroll loop in an xterm, and a text-animation xterm; results go in the watch: native Rust picture-in-picture viewer #340 PR.7. File ownership, ordered tasks, risks, parallel split
PR A (#340) files
New:
crates/pickforge-viewer/{Cargo.toml,PROTOCOL.md,src/main.rs,app.rs,capture.rs,scale.rs,ui.rs,protocol.rs,x11.rs,tests/*,assets/font};packages/cli/src/viewer/native.ts,native-host.ts;packages/cli/src/commands/viewer-host.ts;packages/desktop-linux/src/viewer-host-protocol.ts,viewer-host.ts(start/find/stop host);scripts/lab/viewer-bench.mjs;packages/cli/test/native-viewer*.test.ts.Modified:
Cargo.toml,Cargo.lock,packages/cli/src/commands/watch.ts,program.ts,viewer/hyprland.ts,packages/desktop-linux/src/viewer-state.ts,index.ts,.github/workflows/{candidate-artifacts,ci}.yml,scripts/{install.sh,candidate-smoke.sh},docs/releases/{CHECKLIST,UNRELEASED}.md,README.md(watch section 835–900, CLI reference),SECURITY.md,test/security/security-x-display.test.ts,packages/cli/test/installer.test.ts.Order: (1) agree PROTOCOL.md; (2) crate skeleton +
--version/--self-test+ CI/clippy on both OSes; (3) capture + scale + Xvfb tests; (4) winit window, modes, bar; (5) TS host daemon + launcher + fake viewer tests; (6) watch/session preference and fallback; (7) Hyprland class + live check; (8) release/installer/smoke; (9) benchmarks + docs.PR B (#341) files
Rust:
src/input.rs,src/keymap.rs,src/keysyms.rs(generated), ui control state,tests/inject_xvfb.rs.TS:
packages/core/src/takeover.ts(lease fields),packages/desktop-linux/src/takeover.ts(transport),session.ts(recovery), newstuck-input.ts,wait.ts(busy check),packages/cli/src/commands/takeover-hold.ts,viewer-host.ts(lease ops),watch.ts(--controlwith native),packages/mcp-server/src/tools/{takeover,user,desktop,session}.ts,index.ts(launcher injection),packages/cli/src/pickforge-mcp.ts, tests inpackages/mcp-server/test/takeover.test.ts,desktop.test.ts,test/security/security-native-viewer.test.ts, README takeover section 581–612, SECURITY.md SEC-01 paragraph, UNRELEASED.md.Order: (1) lease transport + stuck release + recovery (TS, testable with fake x11vnc as today); (2) keymap port + injector + Xvfb tests (Rust); (3) host control grants + fail-closed tests; (4) viewer buttons/banner; (5) MCP tools + gates + launcher injection; (6) live Hyprland check; (7) docs/security tests.
Risks
desktop_type; a long human session typing exotic characters could exhaust it. Mitigate: viewer reuses its own bindings and caps new ones; document.cargo test --workspaceon Windows must stay green with the Linux-only crate (stub main + cfg deps).Cargo.lockgrows by roughly 150 crates (winit stack);osv-scannerin CI scans it, so pin to current versions and expect review of the new tree.Parallel split without overlapping writes
Each PR splits cleanly along the language boundary once PROTOCOL.md is fixed: worker 1 owns
crates/only (viewer, tests, fixtures); worker 2 ownspackages/,scripts/,.github/, docs, with the fake viewer standing in for the binary. The only shared file isCargo.lock/Cargo.toml(worker 1) versusci.yml's cargo steps (worker 2), which do not conflict textually. In PR B the same split holds: keymap/injector (worker 1) versus lease transport, host ops, MCP tools and gates (worker 2).Critical Files for Implementation
packages/cli/src/commands/watch.ts(native-first preference, fallback,--controlrouting, lease-hold extraction)packages/desktop-linux/src/takeover.ts(viewer transport without the x11vnc switch; stuck-input backstop; end/recovery paths)packages/cli/src/viewer/bridge-daemon.ts(the daemon/readiness/identity pattern the viewer host copies) together withpackages/desktop-linux/src/viewer-state.ts(launch records, teardown)packages/desktop-linux/src/x11-keymap.tsplusx11-prebind.ts/x11-keysyms.ts(the keymap and binding logic to port intocrates/pickforge-viewer/src/keymap.rs)packages/mcp-server/src/tools/takeover.tswithtools/desktop.ts(newrequest_takeover/takeover_wait, screenshot and wait busy gate) and.github/workflows/candidate-artifacts.ymlwithscripts/install.sh(release asset and installer, owner-approved)