Skip to main content

agentmux_srv_core/backend/blockcontroller/
agent_lock.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! In-memory registry of PtyShell agent leases — the authoritative, hot-path
5//! answer to "is a human's keystroke for this block currently locked out?".
6//!
7//! # Why this exists as its own thing rather than a meta read
8//!
9//! The lease (`term:agentlockuntil`,
10//! `docs/specs/SPEC_AGENT_INTERACTIVE_PTY_SHELL_API_2026_09_10.md` §10.3) is
11//! enforced in `controllerinput` (`server/websocket.rs`). That handler
12//! serves the Stop button's `SIGINT` (`useAgentCommands.ts`) and the
13//! debounced PTY-width resizes `usePtyWidth.ts` sends — the latter in bursts
14//! while a pane is actively being dragged, which is precisely when the UI is
15//! most latency-sensitive. (It is NOT the keystroke path: terminal
16//! keystrokes go through the `blockinput` WS command instead —
17//! `termViewModel.ts`, `AgentShellSubblock.tsx` — see the gap note at the
18//! bottom of this comment.) The first implementation answered the
19//! is-it-leased question by reading the block out of `Store`:
20//!
21//! ```ignore
22//! mstore.get::<Block>(&cmd.blockid)  // synchronous SQLite, on every keystroke
23//! ```
24//!
25//! `Store` is one process-wide SQLite connection behind one `Mutex<Connection>`
26//! (`storage/store.rs`'s own doc comment: "matching Go's `MaxOpenConns(1)`"),
27//! and `Store::get` is a plain blocking call — so that read put a real disk
28//! query, serialized against every other `Store` user in the process, inside
29//! an async WS handler, inline on a Tokio worker thread with no
30//! `block_in_place`/`spawn_blocking`. That is the same failure class the
31//! sysinfo incident already cost this repo once (commit `0f34704a8`, #1782).
32//! See `docs/analysis/ANALYSIS_CROSS_PANE_INPUT_DELAY_REGRESSION_2026_09_15.md`.
33//!
34//! The lease is short-lived (`AGENT_LOCK_WINDOW_MS`, 4s), process-local, and
35//! recreated on every agent write. None of that needs durability — so it
36//! lives here instead: a `HashMap` behind an uncontended `Mutex`, held for
37//! nanoseconds with no I/O inside it. For the overwhelmingly common case
38//! (no agent is driving any shell) the map is empty and the check is a hash
39//! lookup that misses.
40//!
41//! # Formerly a known gap, closed 2026-09-16
42//!
43//! `controllerinput` is not the path a human's keystrokes actually take.
44//! Both the Terminal pane (`termViewModel.ts`) and the agent pane's drawer
45//! shell (`AgentShellSubblock.tsx`) send keystrokes via the `blockinput` WS
46//! command, which called `blockcontroller::send_input` directly with no
47//! lease check at all — so the server-side enforcement added in #3194 did
48//! not in fact cover the human-vs-agent write collision it was added for.
49//! The only thing standing in the way there was `AgentShellSubblock`'s own
50//! `agentLocked()` gate, i.e. exactly the eventually-consistent frontend
51//! check that enforcement was meant to backstop. This surfaced for real
52//! during a live vim investigation on 2026-09-16: an agent driving `vim`
53//! through `PtyShellInput` on its own composer-drawer shell (the same PTY
54//! a human's `blockinput` keystrokes reach) had its writes interleave with
55//! other input on that pane, corrupting vim's cursor-addressed
56//! alternate-screen redraw into a visibly garbled pane — not a hang, byte
57//! interleaving mid-escape-sequence. `dispatch_blockinput`
58//! (`server/websocket.rs`) now calls `is_locked` too, mirroring
59//! `controllerinput`'s check — see
60//! `blockinput_is_dropped_while_an_agent_lock_is_active` there for the
61//! regression test.
62//!
63//! # Relationship to `term:agentlockuntil` meta
64//!
65//! The meta key is still written, and is still what `AgentShellSubblock.tsx`
66//! renders its "Agent is using this shell" badge from — but it is now the UX
67//! layer only, exactly as that handler's own comment already described it
68//! ("the frontend gate is the UX layer that keeps it from happening in the
69//! first place, not the correctness boundary"). This registry is the
70//! correctness boundary. They're written together (`lock_shell_for_agent`)
71//! and cleared together (`handle_pty_shell_stop`, and shell exit — below).
72//!
73//! # Fail-open on restart, deliberately
74//!
75//! A restarted srv starts with an empty registry, so no lease survives it.
76//! That is the right direction to fail for a lock whose entire purpose is a
77//! UX-level write-collision guard, not a security boundary: the failure mode
78//! of a stale lease is *a human who cannot type in their own terminal* — at
79//! worst, cannot type `exit` to close the pane — which is strictly worse than
80//! an agent's write interleaving with a human's. Persisted meta could
81//! previously outlive the process that set it; memory cannot.
82
83use std::collections::HashMap;
84use std::sync::{Mutex, OnceLock};
85
86/// The block meta key holding the lease's expiry (ms since the epoch). `server::http_shell`
87/// re-exports it: `server::websocket`'s `controllerinput` handler also reads it.
88pub const META_KEY_AGENT_LOCK_UNTIL: &str = "term:agentlockuntil";
89
90/// block_id → absolute unix-ms timestamp the lease expires at.
91static LEASES: OnceLock<Mutex<HashMap<String, i64>>> = OnceLock::new();
92
93fn leases() -> &'static Mutex<HashMap<String, i64>> {
94    LEASES.get_or_init(|| Mutex::new(HashMap::new()))
95}
96
97/// Lease `block_id` against human input until `until_ms` (absolute unix ms).
98///
99/// Called before every agent write (`PtyShellInput`/`PtyShellResize`), which
100/// is what makes the lease self-renewing while an agent is actively working
101/// and self-releasing ~`AGENT_LOCK_WINDOW_MS` after it stops. A lease that is
102/// already in the past is not stored (and clears any existing one) — there is
103/// no such thing as a lease that is expired the moment it's taken, and
104/// keeping it would only leave an entry for `is_locked` to prune later.
105pub fn lock_until(block_id: &str, until_ms: i64) {
106    let mut map = leases().lock().unwrap();
107    if until_ms <= agentmux_common::time::now_ms() {
108        map.remove(block_id);
109        return;
110    }
111    map.insert(block_id.to_string(), until_ms);
112}
113
114/// Is a human's input for `block_id` currently locked out by an agent lease?
115///
116/// The hot path — see the module doc. Prunes the entry when it finds an
117/// expired one, so the map stays bounded by the number of *currently* leased
118/// blocks (in practice: the number of agents driving a shell right now,
119/// normally zero) rather than by every block ever leased.
120pub fn is_locked(block_id: &str) -> bool {
121    let mut map = leases().lock().unwrap();
122    match map.get(block_id) {
123        None => false,
124        Some(&until_ms) => {
125            if until_ms > agentmux_common::time::now_ms() {
126                true
127            } else {
128                map.remove(block_id);
129                false
130            }
131        }
132    }
133}
134
135/// Release `block_id`'s lease immediately. Returns whether it was actually
136/// held (and unexpired) at the moment of the call — `PtyShellStop` reports
137/// that back to the agent as `released`.
138///
139/// Called from `PtyShellStop` (the explicit release) and from a shell's
140/// exit path (`shell/lifecycle.rs`) — an exited shell must never keep a
141/// lease alive, or the pane it belongs to would refuse the human's keystrokes
142/// for up to the rest of the window for a PTY that isn't there any more.
143pub fn release(block_id: &str) -> bool {
144    let mut map = leases().lock().unwrap();
145    match map.remove(block_id) {
146        Some(until_ms) => until_ms > agentmux_common::time::now_ms(),
147        None => false,
148    }
149}
150
151/// Release the lease AND clear the `term:agentlockuntil` meta copy the
152/// frontend gates on, broadcasting the update so it takes effect now.
153///
154/// Releasing only the in-memory copy is not enough on any path where the
155/// point is to give the human their keyboard back. Codex P1 / ReAgent P1 on
156/// PR #3249, and they're right: `AgentShellSubblock.tsx`'s `agentLocked()`
157/// derives its gate purely from that meta value. `blockinput` now also has
158/// its own server-side lease check (see the module doc's "Formerly a known
159/// gap" section), so a stale meta value no longer risks a swallowed
160/// keystroke reaching a live controller — but the frontend still reads
161/// meta for its own badge/gate, and clearing memory alone would leave that
162/// badge (and the client-side keystroke suppression) stuck for the rest of
163/// the 4s window, which is precisely the "typed `exit`, nothing visibly
164/// happened" case this is meant to fix.
165///
166/// Best-effort on the meta half (logs and continues), authoritative on the
167/// memory half. Mirrors `core::persist_session_id`'s established
168/// update-then-broadcast shape; no-ops on the meta half when `mstore` is
169/// `None`, as unit tests that don't wire a store expect.
170pub fn release_and_clear_meta(
171    block_id: &str,
172    mstore: &Option<std::sync::Arc<crate::backend::storage::store::Store>>,
173    event_bus: &Option<std::sync::Arc<crate::backend::eventbus::EventBus>>,
174) -> bool {
175    let was_locked = release(block_id);
176
177    let Some(store) = mstore else { return was_locked };
178    let oref_str = format!("block:{block_id}");
179    let mut meta_update = crate::backend::obj::MetaMapType::new();
180    meta_update.insert(
181        META_KEY_AGENT_LOCK_UNTIL.to_string(),
182        serde_json::Value::Null,
183    );
184    if let Err(e) = crate::backend::wcore::object_meta::update_object_meta(store, &oref_str, &meta_update) {
185        tracing::warn!(block_id = %block_id, error = %e, "agent_lock: failed to clear lease meta");
186        return was_locked;
187    }
188    let Some(event_bus) = event_bus else { return was_locked };
189    super::core::broadcast_block_update(store, event_bus, block_id);
190    was_locked
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196
197    /// Global state shared across the whole test binary — every test here
198    /// uses its own block ids so parallel tests can't observe each other.
199    fn id(suffix: &str) -> String {
200        format!("agent-lock-test-{suffix}")
201    }
202
203    fn entry_count(block_id: &str) -> usize {
204        leases().lock().unwrap().keys().filter(|k| *k == block_id).count()
205    }
206
207    #[test]
208    fn an_unleased_block_is_never_locked() {
209        assert!(!is_locked(&id("never-leased")));
210    }
211
212    #[test]
213    fn a_future_lease_locks_and_an_expired_one_does_not() {
214        let b = id("future-then-expired");
215        lock_until(&b, agentmux_common::time::now_ms() + 60_000);
216        assert!(is_locked(&b), "a lease ending in the future must lock");
217
218        lock_until(&b, agentmux_common::time::now_ms() - 1);
219        assert!(!is_locked(&b), "a lease ending in the past must not lock");
220    }
221
222    /// The expiry must be evaluated at read time, not stored as a boolean —
223    /// otherwise a lease taken while an agent worked would still read as
224    /// locked minutes later, which is exactly the "human can't type `exit`"
225    /// failure this whole mechanism has to avoid.
226    #[test]
227    fn a_lease_that_lapses_stops_locking_without_anyone_releasing_it() {
228        let b = id("lapses-on-its-own");
229        let now = agentmux_common::time::now_ms();
230        lock_until(&b, now + 40);
231        assert!(is_locked(&b));
232        std::thread::sleep(std::time::Duration::from_millis(60));
233        assert!(!is_locked(&b), "a lapsed lease must stop locking on its own");
234    }
235
236    #[test]
237    fn reading_a_lapsed_lease_prunes_it() {
238        let b = id("pruned-on-read");
239        lock_until(&b, agentmux_common::time::now_ms() + 20);
240        assert_eq!(entry_count(&b), 1);
241        std::thread::sleep(std::time::Duration::from_millis(40));
242        assert!(!is_locked(&b));
243        assert_eq!(entry_count(&b), 0, "a lapsed lease must not be retained after it's read");
244    }
245
246    /// `lock_until` with an already-past timestamp is a caller bug, but it
247    /// must not leave an entry behind for `is_locked` to trip over later.
248    #[test]
249    fn locking_into_the_past_stores_nothing() {
250        let b = id("past-lease");
251        lock_until(&b, agentmux_common::time::now_ms() - 5_000);
252        assert_eq!(entry_count(&b), 0);
253        assert!(!is_locked(&b));
254    }
255
256    #[test]
257    fn release_reports_whether_a_live_lease_was_held() {
258        let b = id("release-reporting");
259        assert!(!release(&b), "releasing an unleased block reports nothing was held");
260
261        lock_until(&b, agentmux_common::time::now_ms() + 60_000);
262        assert!(release(&b), "releasing a live lease reports it was held");
263        assert!(!is_locked(&b), "release must take effect immediately");
264        assert_eq!(entry_count(&b), 0);
265
266        lock_until(&b, agentmux_common::time::now_ms() + 30);
267        std::thread::sleep(std::time::Duration::from_millis(50));
268        assert!(!release(&b), "releasing an already-lapsed lease reports nothing was held");
269    }
270
271    /// One agent leasing its own pane's shell must not lock anyone else out —
272    /// the lease is per-block, and the registry is shared.
273    #[test]
274    fn leases_are_independent_per_block() {
275        let leased = id("independent-leased");
276        let other = id("independent-other");
277        lock_until(&leased, agentmux_common::time::now_ms() + 60_000);
278        assert!(is_locked(&leased));
279        assert!(!is_locked(&other));
280        release(&leased);
281    }
282
283    /// `release` alone clears only the copy `controllerinput` reads. The
284    /// copy that actually gates a human's keystrokes is the
285    /// `term:agentlockuntil` meta `AgentShellSubblock.tsx` reads — keystrokes
286    /// travel on `blockinput`, which has no server-side check — so releasing
287    /// without clearing meta leaves the human's input swallowed client-side
288    /// for the rest of the window. Codex P1 / ReAgent P1 on PR #3249.
289    #[test]
290    fn release_and_clear_meta_clears_the_copy_the_frontend_gates_on() {
291        use crate::backend::obj::Block;
292
293        let store = std::sync::Arc::new(
294            crate::backend::storage::store::Store::open_in_memory().expect("store"),
295        );
296        // A real UUID, not a readable label: `update_object_meta` parses the
297        // oref and rejects a non-UUID oid outright ("invalid object id"). A
298        // label would make this test pass for the wrong reason — the meta
299        // write would fail, `release_and_clear_meta` would log and move on,
300        // and the assertion below would be measuring nothing.
301        let block_id = uuid::Uuid::new_v4().to_string();
302        let mut block = Block {
303            oid: block_id.clone(),
304            meta: {
305                let mut m = crate::backend::obj::MetaMapType::new();
306                m.insert(
307                    META_KEY_AGENT_LOCK_UNTIL.to_string(),
308                    serde_json::json!(agentmux_common::time::now_ms() + 60_000),
309                );
310                m
311            },
312            ..Default::default()
313        };
314        store.insert(&mut block).expect("insert");
315        lock_until(&block_id, agentmux_common::time::now_ms() + 60_000);
316
317        assert!(release_and_clear_meta(&block_id, &Some(store.clone()), &None));
318
319        assert!(!is_locked(&block_id), "the in-memory copy must be released");
320        let after: Block = store.must_get(&block_id).expect("block still exists");
321        let meta_val = after.meta.get(META_KEY_AGENT_LOCK_UNTIL);
322        assert!(
323            meta_val.is_none() || meta_val == Some(&serde_json::Value::Null),
324            "the meta copy the frontend gates on must be cleared, got {meta_val:?}"
325        );
326    }
327
328    /// Re-leasing while a lease is live extends it rather than stacking —
329    /// this is what makes "refreshed on every agent write" work.
330    #[test]
331    fn relocking_extends_the_same_entry() {
332        let b = id("extend");
333        lock_until(&b, agentmux_common::time::now_ms() + 30);
334        lock_until(&b, agentmux_common::time::now_ms() + 60_000);
335        assert_eq!(entry_count(&b), 1);
336        std::thread::sleep(std::time::Duration::from_millis(50));
337        assert!(is_locked(&b), "the later lease must win, not the earlier expiry");
338        release(&b);
339    }
340}