Skip to main content

agentmux_srv_core/backend/blockcontroller/persistent/
input.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! User-facing input surface: user messages, AskUserQuestion answers/denials,
5//! tool-permission decisions, raw stdin, and inbound control frames.
6
7use super::*;
8
9impl PersistentSubprocessController {
10    /// What a dead-air fallback needs to record its re-delivered line — see
11    /// [`RedeliveryPersister`].
12    pub(super) fn redelivery_persister(&self) -> RedeliveryPersister {
13        RedeliveryPersister {
14            broker: self.broker.clone(),
15            filestore: self.filestore.clone(),
16            mstore: self.mstore.clone(),
17            block_id: self.block_id.clone(),
18        }
19    }
20
21    /// Encode a message as the stream-json stdin line the CLI expects.
22    pub(super) fn encode_user_message(message: &str) -> String {
23        serde_json::json!({
24            "type": "user",
25            "message": {
26                "role": "user",
27                "content": message
28            }
29        })
30        .to_string()
31    }
32
33    /// Write an already-encoded stdin line, given a held `inner` guard.
34    ///
35    /// Callers must hold the lock across the must-wait check, the queue
36    /// update and this write, so no concurrent sender or watchdog tick can
37    /// slip between them.
38    ///
39    /// On success the line is also tracked into the current generation's
40    /// resume retry batch, so every write site (the send path and the
41    /// watchdog) gets it without having to remember to.
42    pub(super) fn try_write_stdin_locked(
43        inner: &mut PersistentInner,
44        line: &str,
45    ) -> Result<(), String> {
46        // reagentx P1 on PR #2360 (sixth review pass, round 7):
47        // `spawn_process` sets `stdin_tx` synchronously, well before the
48        // queued message that triggered the spawn is actually delivered by
49        // the background drain task (`drain_queue_after_successful_spawn`).
50        // Gating purely on `stdin_tx.is_some()` let a message land in that
51        // window and `try_send` straight to the live channel, jumping ahead
52        // of whatever was still queued. Checked in the SAME acquisition as
53        // `stdin_tx`, so nothing slips between two checks.
54        if inner.spawning_in_progress {
55            return Err("persistent process is still starting up — try again shortly".to_string());
56        }
57        // A committed deferred restart leaves `stdin_tx` live until the process
58        // actually exits, and a line written into a process about to be killed
59        // is lost, even though its caller was told it was delivered. The human
60        // path (`decide_send_action`) already refuses DeliverDirect here (codex
61        // P1 on PR #2858); this is the same rule for every write through this
62        // helper (codex P1 on #3562).
63        if inner.restart_pending {
64            return Err("persistent process is restarting for a config change — try again shortly".to_string());
65        }
66        // Likewise once a kill has been requested: the process is going down
67        // and a line written now dies with it (see `stop_pending`). Once it
68        // has exited, "not running" below is the accurate answer.
69        if inner.stop_pending && inner.stdin_tx.is_some() {
70            return Err("persistent process is stopping — try again shortly".to_string());
71        }
72        let tx = inner
73            .stdin_tx
74            .as_ref()
75            .ok_or("persistent process not running")?;
76        tx.try_send(line.to_string())
77            .map_err(|e| format!("stdin send failed: {e}"))?;
78        // codex P1 + reagent P1 on PR #3523, found independently by both:
79        // track this into the CURRENT generation's retry batch, exactly as
80        // `send_message`'s `DeliverDirect` branch does. That fix covered the
81        // typed-in-the-UI path and missed this one — the MuxBus/reactive
82        // injection path (`deliver_agent_message`).
83        //
84        // The gap matters most for eager resume, which spawns with an
85        // unconfirmed `--resume` and NO seed message, so the retry batch
86        // starts empty. An injected prompt written straight to stdin and never
87        // appended leaves it empty, so when the resumed sid turns out to be
88        // stale the retry fires with nothing to redeliver — and the prompt is
89        // gone, even though the caller was told it was delivered and the live
90        // blockfile append already rendered it to the operator.
91        //
92        // Read the generation and apply under the caller's SAME lock
93        // acquisition (already held for `try_send`) — a separate one risks a
94        // concurrent respawn bumping `spawn_generation` in between, making the
95        // event carry a stale generation that `update()`'s catch-all silently
96        // ignores. A no-op when no unconfirmed resume is in flight.
97        let generation = inner.spawn_generation;
98        let seq = inner.take_next_message_seq();
99        inner.apply_resume_event(persistent_resume::ResumeEvent::MessageAppendedToRetryBatch {
100            generation,
101            entry: persistent_resume::QueuedRetryEntry { seq, json: line.to_string() },
102        });
103        Ok(())
104    }
105
106    /// Deliver a user message to the **already-running** persistent process,
107    /// without a spawn config. Unlike `send_message`, this never spawns — it errors
108    /// if the process is not running. Used for controller-aware muxbus/reactive
109    /// delivery (`deliver_agent_message`), where the agent is live (busy or idle)
110    /// and we have no `PersistentSpawnConfig` to hand.
111    ///
112    /// A live process gets the message at once, whatever the agent is doing —
113    /// mid-turn included; the CLI reads it at its next inference step. It is
114    /// queued only while the process cannot take a write yet: a spawn in
115    /// flight, a committed restart, a requested stop, or another writer owning
116    /// stdin (see [`Self::deferred_must_wait_locked`]). Refusing it then used
117    /// to drop the message outright (`SPEC_NO_MIDTURN_DELIVERY_2026_09_23.md`
118    /// §3.2.1). Spec: `SPEC_JEKT_IMMEDIATE_DELIVERY_2026_09_28.md` §2.1.
119    #[cfg(test)]
120    pub fn send_user_message(&self, message: String) -> Result<(), String> {
121        self.send_user_message_outcome(message).map(|_| ())
122    }
123
124    /// [`send_user_message`], reporting whether the message went to the agent
125    /// now or is queued until the process can take it (it is starting up,
126    /// restarting or stopping) — so an automated sender can tell its caller
127    /// the truth (MCP `SendMessage`).
128    #[cfg(test)]
129    pub fn send_user_message_outcome(&self, message: String) -> Result<SendOutcome, String> {
130        self.send_user_message_outcome_from(message, None)
131    }
132
133    /// An explicit error when the deferred queue is full, never a false
134    /// success: the caller treats it like any other transient delivery failure
135    /// and retries.
136    fn deferred_queue_full() -> String {
137        format!(
138            "deferred-delivery queue is full ({MAX_DEFERRED_DELIVERIES} messages \
139             waiting for this agent's process to start up, restart or stop) — retry shortly"
140        )
141    }
142
143    /// [`Self::send_user_message_outcome`], saying who the input is from (turn
144    /// provenance, SPEC_AGENT_SELF_QUIT §6.3) — the Swarm broadcast, which is
145    /// the user's own message (SPEC_SWARM_BROADCAST_AS_USER_MESSAGE §6 q2).
146    /// The label is applied only when this message is the only one written: a
147    /// backlog written with it was queued by automated senders, and a message
148    /// left queued (process starting, restarting or stopping) is written later
149    /// by the drain with whatever else is queued. Both stay unlabelled, as
150    /// every automated delivery is, so the label can never vouch for input
151    /// that isn't the user's.
152    #[cfg(test)]
153    pub fn send_user_message_outcome_from(
154        &self,
155        message: String,
156        origin: Option<crate::backend::blockcontroller::health::TurnInput>,
157    ) -> Result<SendOutcome, String> {
158        let record = RecordOrigin::new(MessageOrigin::user());
159        self.send_user_message_with_images_from(message, origin, Vec::new(), record, None, Vec::new())
160    }
161
162    /// [`Self::send_user_message_outcome_from`] with Claude content blocks
163    /// (images, PDFs) ahead of the text, as the composer sends attachments
164    /// (`prompt::claude_user_line`). The stored copy drops their base64
165    /// (`append_delivered_message`).
166    ///
167    /// `record` says where the message came from and which `[AgentMux]` notes
168    /// went with it; the record written for it carries both
169    /// ([`Self::append_delivered_message`]), also when it waits in the queue.
170    ///
171    /// `expires_at_ms` is the sender's expiry (issue #3894): only a jekt has
172    /// one. It rides the queued entry, so a message that waits out its
173    /// expiry behind a starting, restarting or stopping process is dropped
174    /// at write time instead of written stale.
175    ///
176    /// `notes` are the `[AgentMux]` notes the message carries, with their keys:
177    /// if the queued entry is dropped at that expiry, they are held again for
178    /// the next message instead of going with it.
179    pub fn send_user_message_with_images_from(
180        &self,
181        message: String,
182        origin: Option<crate::backend::blockcontroller::health::TurnInput>,
183        images: Vec<serde_json::Value>,
184        record: RecordOrigin,
185        expires_at_ms: Option<i64>,
186        notes: Vec<(String, String)>,
187    ) -> Result<SendOutcome, String> {
188        // Pre-turn fence — see `send_message`.
189        self.fence_check()?;
190        let json_str = if images.is_empty() {
191            Self::encode_user_message(&message)
192        } else {
193            crate::backend::attachments::prompt::claude_user_line(message, images)
194        };
195
196        // ONE lock acquisition covers the must-wait check, the enqueue and the
197        // write. Because the watchdog takes this same lock, there is no window
198        // in which a message is enqueued against a queue a concurrent drain
199        // has already finished with.
200        //
201        // `publish_status`/`spawn_status_heartbeat` must NOT be called while
202        // this guard is held — `publish_status` takes `inner` itself and would
203        // deadlock. They run after the guard drops, below.
204        let (written, was_active, still_queued, failure) = {
205            let mut inner = self.inner.lock().unwrap();
206
207            if inner.deferred_deliveries.len() >= MAX_DEFERRED_DELIVERIES {
208                return Err(Self::deferred_queue_full());
209            }
210            // Always enqueue first, then write the whole backlog in order.
211            // Writing this message directly while older ones are queued would
212            // reorder it ahead of them.
213            inner.deferred_deliveries.push_back(Deferred { line: json_str, record, expires_at_ms, notes });
214
215            // A spawn in flight counts as "wait" rather than as an error. This
216            // is the startup race that used to drop jekts outright
217            // (`SPEC_NO_MIDTURN_DELIVERY_2026_09_23.md` §3.2.1). Not every spawn
218            // ends in a turn — it can fail, or (eager resume) succeed with
219            // nothing to say — so anything left queued here is the watchdog's
220            // to finish, below.
221            let mut failure = None;
222            let mut written = Vec::new();
223            if !self.deferred_must_wait_locked(&inner) {
224                let (w, err) = Self::flush_deferred_locked(&mut inner, &self.block_id);
225                written = w;
226                if let Some(e) = err {
227                    // This call's own message is the newest entry, so it was
228                    // not written. Take it back: this call reports failure,
229                    // so the caller owns the retry. Anything older stays
230                    // queued — it was already accepted, and whoever queued it
231                    // armed the watchdog, so it keeps its retry.
232                    inner.deferred_deliveries.pop_back();
233                    failure = Some(e);
234                }
235            }
236            // Marked under this same guard, so the turn state a concurrent
237            // caller or the turn-end handler reads is never behind the write.
238            // Only a fully successful write of this message alone: with a
239            // failure, the one entry written is an older queued one and this
240            // message was taken back (#4401).
241            let label = if failure.is_none() && written.len() == 1 { origin } else { None };
242            let was_active = (!written.is_empty()).then(|| self.mark_turn_active_locked_from(label));
243            (written, was_active, !inner.deferred_deliveries.is_empty(), failure)
244        };
245        // Anything still queued needs a guaranteed way out. Called after EVERY
246        // enqueue that leaves the queue non-empty, so it cannot miss a watchdog
247        // that exited just before.
248        if still_queued {
249            self.ensure_deferred_watchdog();
250        }
251
252        if let Some(was_active) = was_active {
253            // Everything below needs the `inner` lock released:
254            // `publish_status` takes it, and `spawn_status_heartbeat`'s task
255            // does too. The heartbeat is re-armed only when resuming from idle
256            // — a mid-turn send already has one running, and re-spawning per
257            // call would leak duplicate heartbeat tasks.
258            if !was_active {
259                self.spawn_status_heartbeat();
260            }
261            self.publish_status();
262            for queued in &written {
263                self.append_delivered_message(&queued.line, &queued.record);
264            }
265        }
266        if let Some(e) = failure {
267            return Err(e);
268        }
269        if still_queued {
270            tracing::info!(
271                block_id = %self.block_id,
272                "delivery queued — the agent's process is starting up, restarting or stopping; \
273                 it will be written once the process can take it"
274            );
275            return Ok(SendOutcome::Deferred);
276        }
277        Ok(SendOutcome::Sent)
278    }
279
280    /// srv's own note `text` into the running turn; with no turn running, or
281    /// a process that can't take a write now, held under `key` for the next
282    /// turn (`reactive::held_notes`) instead. The check and the write share
283    /// one acquisition of `inner`, which the turn-end handler takes too
284    /// ([`Self::turn_boundary_locked`]), so the turn can't end between them
285    /// and the note never starts one. Returns whether it joined the turn.
286    pub fn note_into_turn_or_hold(&self, key: &str, text: &str) -> bool {
287        let line = Self::encode_user_message(text);
288        let joined = {
289            let mut inner = self.inner.lock().unwrap();
290            let can_join = self.health_monitor.is_active_turn()
291                && inner.deferred_deliveries.is_empty()
292                && !self.deferred_must_wait_locked(&inner);
293            let joined = can_join && Self::try_write_stdin_locked(&mut inner, &line).is_ok();
294            if !joined {
295                crate::backend::reactive::held_notes::hold(&self.block_id, key, text);
296            }
297            joined
298        };
299        if joined {
300            self.append_delivered_message(&line, &RecordOrigin::new(MessageOrigin::system()));
301        }
302        joined
303    }
304
305    /// Mark the turn active while the caller already holds `inner`, so the
306    /// flip is never behind the write that caused it. Lock order is `inner` →
307    /// `health_monitor`, matching the turn-end handler in `stdout_reader.rs`;
308    /// `health_monitor` never takes `inner`, so this cannot deadlock. Returns
309    /// the pre-call value.
310    fn mark_turn_active_locked(&self) -> bool {
311        self.health_monitor.mark_turn_active_returning_was_active()
312    }
313
314    /// [`Self::mark_turn_active_locked`] with the input's provenance; `None`
315    /// is exactly the unlabelled mark.
316    fn mark_turn_active_locked_from(
317        &self,
318        origin: Option<crate::backend::blockcontroller::health::TurnInput>,
319    ) -> bool {
320        self.health_monitor.mark_turn_active_from(origin)
321    }
322
323    /// Whether a queued message must keep waiting rather than be written now.
324    /// Only states in which the process cannot take a write: what the agent is
325    /// doing (mid-turn or idle) is not one of them
326    /// (`SPEC_JEKT_IMMEDIATE_DELIVERY_2026_09_28.md` §2.1). Shared by the send
327    /// path and the watchdog, so the two can never disagree.
328    ///
329    /// - Another writer owns stdin — see
330    ///   [`Self::stdin_owned_by_another_writer`]; this includes a spawn in
331    ///   flight, whose write `try_write_stdin_locked` would refuse.
332    /// - A committed config restart (`restart_pending`), but only while the
333    ///   process being restarted still holds `stdin_tx`: it is about to be
334    ///   killed, so writes must wait for the replacement. Once it has exited,
335    ///   the ordinary rules apply. The exit handler's respawn
336    ///   (`respawn_after_config_restart`) holds the spawn claim, so the queue
337    ///   keeps waiting for it (a spawn in flight, below), and if no spawn is in
338    ///   flight, whoever was to start one declined or failed. Waiting on
339    ///   `restart_pending` alone then held jekts forever, since only a
340    ///   successful spawn clears it (Korp, 2026-09-29; ReAgent P1 on #3990: a
341    ///   competing spawn claim that fails leaves it set). The watchdog's grace
342    ///   window covers the moment between the exit and the respawn's claim.
343    /// - A requested kill (`stop_pending`), but only while the dying process
344    ///   still holds `stdin_tx`: writes are refused then, and a refusal must
345    ///   not reach an automated caller as an error (reagent P1 on #3562). Once
346    ///   it exits, the ordinary no-process rules apply. A send fails into the
347    ///   caller's respawn fallback, and the watchdog's grace window runs, so
348    ///   nothing parks unreported behind a stop.
349    pub(super) fn deferred_must_wait_locked(&self, inner: &PersistentInner) -> bool {
350        (inner.restart_pending && inner.stdin_tx.is_some())
351            || (inner.stop_pending && inner.stdin_tx.is_some())
352            || Self::stdin_owned_by_another_writer(inner)
353    }
354
355    /// Another writer is feeding stdin, and messages it carries were accepted
356    /// earlier than anything in the deferred queue, so they must not be
357    /// overtaken:
358    ///
359    /// - a spawn is in flight — its seed message and drain go first;
360    /// - a stale-resume retry batch is being replayed (`drain_claim`), possibly
361    ///   into this same live process by a background task writing to the same
362    ///   channel;
363    /// - human messages are queued behind a spawn.
364    ///
365    /// Queued messages count only while a process exists to drain them. A
366    /// drain's "second stall" (`drain_queue_with_claim`) releases its claim
367    /// with leftovers queued and no process. Nothing owns that backlog, and
368    /// treating it as a writer made a send defer instead of failing into
369    /// the no-process fallback, and kept the watchdog resetting its orphan
370    /// timer forever (codex P1 on #3562).
371    ///
372    /// Also part of [`Self::deferred_must_wait_locked`], which every caller of
373    /// [`Self::flush_deferred_locked`] checks first under the same lock.
374    fn stdin_owned_by_another_writer(inner: &PersistentInner) -> bool {
375        inner.spawning_in_progress
376            || inner.drain_claim
377            || (!inner.pending_send_messages.is_empty() && inner.stdin_tx.is_some())
378    }
379
380    /// Write the queued messages to stdin, oldest first, as far as stdin takes
381    /// them. Returns the lines written, in order, and the error that stopped
382    /// it early, if any: the entry that failed stays at the head of the queue
383    /// with everything behind it, so a failed write never drops a message.
384    ///
385    /// A message whose sender's expiry has passed (issue #3894 — only a jekt
386    /// carries one) is dropped here instead, with one log line: the wait for
387    /// the process to take a write outlived the time the message was worth
388    /// anything, and writing it now would deliver it exactly as stale as the
389    /// durable hold's replay used to.
390    ///
391    /// The whole backlog at once, not one at a time: nothing is held for what
392    /// the agent is doing any more (`SPEC_JEKT_IMMEDIATE_DELIVERY_2026_09_28.md`
393    /// §2.1), only for whether the process can take a write.
394    ///
395    /// The caller holds `inner` across this, has checked
396    /// [`Self::deferred_must_wait_locked`] under that same guard, and marks the
397    /// turn active before dropping it if anything was written.
398    pub(super) fn flush_deferred_locked(
399        inner: &mut PersistentInner,
400        block_id: &str,
401    ) -> (Vec<Deferred>, Option<String>) {
402        let now_ms = agentmux_common::time::now_ms();
403        let mut written = Vec::new();
404        while let Some(head) = inner.deferred_deliveries.front().cloned() {
405            if head.expires_at_ms.is_some_and(|expires| expires <= now_ms) {
406                inner.deferred_deliveries.pop_front();
407                // The message is gone, but the `[AgentMux]` notes it carried
408                // are held again for the next one, under their own keys (#3894).
409                crate::backend::reactive::held_notes::put_back(block_id, head.notes.clone());
410                tracing::info!(
411                    block_id = %block_id,
412                    "deferred jekt expired while waiting for the process — dropped instead of delivered"
413                );
414                continue;
415            }
416            if let Err(e) = Self::try_write_stdin_locked(inner, &head.line) {
417                tracing::warn!(
418                    block_id = %block_id,
419                    error = %e,
420                    queued = inner.deferred_deliveries.len(),
421                    "deferred flush failed; leaving the queue for the watchdog to retry"
422                );
423                return (written, Some(e));
424            }
425            inner.deferred_deliveries.pop_front();
426            written.push(head);
427        }
428        (written, None)
429    }
430
431    /// The turn-boundary decision for a `result` frame, under `inner`: the turn
432    /// is over, and a deferred runtime-config restart may now apply. Returns
433    /// whether it does.
434    ///
435    /// Returns `None`, touching nothing, when `generation` is no longer the
436    /// current one. A fallback respawn can install a new process before the
437    /// old reader drains a buffered `result`. That `result` ends nothing the
438    /// new process is doing, so acting on it would mark the replacement's
439    /// running turn idle, or restart it (codex P1 on #3562).
440    ///
441    /// The deferred restart applies only when nothing is queued. Killing the
442    /// process with an entry still queued would strand it; the flag stays set,
443    /// and the next `result` (the watchdog's write starts a turn) applies it.
444    ///
445    /// `stats`: the `result` frame's figures. They go to the turn the pass
446    /// belonged to in the same step that idles it, so input arriving right
447    /// after (which may open a new turn) can never take them (#4492).
448    pub(super) fn turn_boundary_locked(
449        inner: &mut PersistentInner,
450        health: &TurnActivityTracker,
451        block_id: &str,
452        generation: u64,
453        stats: Option<crate::backend::blockcontroller::health::PassStats>,
454    ) -> Option<bool> {
455        if inner.spawn_generation != generation {
456            tracing::debug!(
457                block_id = %block_id,
458                reader_generation = generation,
459                current_generation = inner.spawn_generation,
460                "result from a replaced process — not a boundary for the current one"
461            );
462            return None;
463        }
464        let apply_deferred_restart = inner.deferred_deliveries.is_empty()
465            && std::mem::replace(&mut inner.restart_when_idle, false);
466        health.end_pass(stats);
467        if apply_deferred_restart {
468            inner.restart_pending = true;
469            // The restart token, set in the acquisition that commits the
470            // restart: nothing later may re-arm it after a Stop cleared it.
471            inner.config_restart_generation = Some(generation);
472        }
473        Some(apply_deferred_restart)
474    }
475
476    /// Asks for the deferred runtime-config restart at the boundary about to end the turn: the replacement is brought up
477    /// at once by the kill arm, which is what `turn_boundary_locked` commits when `restart_when_idle` is set.
478    pub(super) fn restart_at_boundary_locked(inner: &mut PersistentInner) {
479        inner.restart_when_idle = true;
480    }
481
482    /// Make sure a watchdog task is looking after a non-empty deferred queue.
483    ///
484    /// Messages are queued only while the process cannot take a write (see
485    /// [`Self::deferred_must_wait_locked`]), and nothing else writes them once
486    /// it can, so this is how every queued message gets out:
487    ///
488    /// - a message queued behind a spawn — delivered once the process is up,
489    ///   whether or not that spawn starts a turn (eager resume spawns with no
490    ///   seed message);
491    /// - a message queued behind a committed restart or a requested stop —
492    ///   delivered to the replacement process;
493    /// - a write that failed (e.g. the bounded stdin channel was momentarily
494    ///   full) — retried;
495    /// - a message queued behind a spawn that then FAILED, or behind a process
496    ///   that exited and was never replaced — reported stranded after the
497    ///   grace window.
498    ///
499    /// Idempotent: at most one watchdog per controller. A no-op for an
500    /// instance without `set_self_ref` (only tests construct those) or outside
501    /// a Tokio runtime.
502    pub(super) fn ensure_deferred_watchdog(&self) {
503        let Some(ctrl) = self.self_ref.lock().unwrap().as_ref().and_then(|w| w.upgrade()) else {
504            return;
505        };
506        let Ok(runtime) = tokio::runtime::Handle::try_current() else {
507            return;
508        };
509        {
510            let mut inner = self.inner.lock().unwrap();
511            if inner.deferred_watchdog_armed {
512                return;
513            }
514            inner.deferred_watchdog_armed = true;
515        }
516        let weak = Arc::downgrade(&ctrl);
517        drop(ctrl);
518        runtime.spawn(async move {
519            let mut orphaned_ticks = 0u32;
520            loop {
521                tokio::time::sleep(DEFERRED_WATCHDOG_TICK).await;
522                // Hold no strong reference across the sleep, so the watchdog
523                // never keeps a torn-down controller alive.
524                let Some(ctrl) = weak.upgrade() else { return };
525                if ctrl.sweep_deferred_once(&mut orphaned_ticks) == WatchdogStep::Exit {
526                    return;
527                }
528            }
529        });
530    }
531
532    /// One watchdog tick. Split out of the task so tests can drive it
533    /// directly, without a real process or real time.
534    pub(super) fn sweep_deferred_once(&self, orphaned_ticks: &mut u32) -> WatchdogStep {
535        let (released, stranded) = {
536            let mut inner = self.inner.lock().unwrap();
537            if inner.deferred_deliveries.is_empty() {
538                // Disarm under the same lock that guards enqueue: any message
539                // pushed after this point is followed by its own
540                // `ensure_deferred_watchdog`, which will see "disarmed".
541                inner.deferred_watchdog_armed = false;
542                return WatchdogStep::Exit;
543            }
544            if self.deferred_must_wait_locked(&inner) {
545                // Something in flight will bring the process up (or fail into
546                // a state this watchdog sees on a later tick).
547                *orphaned_ticks = 0;
548                return WatchdogStep::Continue;
549            }
550            if inner.stdin_tx.is_none() {
551                // No process and nothing starting one. Give a respawn the
552                // grace window to begin, then stop pretending these will be
553                // delivered.
554                *orphaned_ticks += 1;
555                if *orphaned_ticks < DEFERRED_ORPHAN_GRACE_TICKS {
556                    return WatchdogStep::Continue;
557                }
558                inner.deferred_watchdog_armed = false;
559                (None, inner.deferred_deliveries.drain(..).collect::<Vec<_>>())
560            } else {
561                *orphaned_ticks = 0;
562                // A failed write is transient; whatever is left is retried on
563                // the next tick.
564                let (written, _failed) = Self::flush_deferred_locked(&mut inner, &self.block_id);
565                if written.is_empty() {
566                    return WatchdogStep::Continue;
567                }
568                // Flip inside the lock, exactly as the send path does.
569                (Some((written, self.mark_turn_active_locked())), Vec::new())
570            }
571        };
572
573        if !stranded.is_empty() {
574            Self::log_stranded_deferred(
575                &self.block_id,
576                "no process and no spawn in flight for the whole grace window",
577                &stranded,
578            );
579            return WatchdogStep::Exit;
580        }
581        if let Some((written, was_active)) = released {
582            tracing::info!(
583                block_id = %self.block_id,
584                count = written.len(),
585                "the agent's process can take input again — watchdog delivered the queued messages"
586            );
587            if !was_active {
588                self.spawn_status_heartbeat();
589            }
590            self.publish_status();
591            for queued in &written {
592                self.append_delivered_message(&queued.line, &queued.record);
593            }
594        }
595        WatchdogStep::Continue
596    }
597
598    /// Report every stranded deferred entry, so a message this controller
599    /// accepted is never quietly discarded
600    /// (`SPEC_NO_MIDTURN_DELIVERY_2026_09_23.md` §4.5). Callers drain the
601    /// queue in the same `inner` acquisition that ends delivery (`stop`,
602    /// `shutdown`, the watchdog), so no flush can take an entry first.
603    ///
604    /// **Known gap:** reporting is currently a loud structured log, not a
605    /// failure routed back to the original sender. The queue stores encoded
606    /// stdin lines with no sender identity attached, so there is nothing to
607    /// address a reply to; carrying that identity through is Phase 3. Until
608    /// then a stranded message is visible in the logs rather than in the
609    /// sender's response — better than silence, short of the spec's intent.
610    ///
611    /// Takes `block_id` rather than `&self` so `shutdown`'s `'static` future,
612    /// which holds no controller reference, can report through it too.
613    pub(super) fn log_stranded_deferred(block_id: &str, reason: &str, stranded: &[Deferred]) {
614        if stranded.is_empty() {
615            return;
616        }
617        tracing::warn!(
618            block_id = %block_id,
619            reason = %reason,
620            stranded = stranded.len(),
621            "deferred messages were accepted but never delivered"
622        );
623        for queued in stranded {
624            // The length only: the line is the person's or another agent's message text, which no log carries.
625            tracing::warn!(block_id = %block_id, line_len = queued.line.len(), "stranded deferred message");
626        }
627    }
628
629    /// Persist a delivered injection to the blockfile WITH a live event.
630    ///
631    /// Unlike `send_message` there is no `agent-message-accepted` pending echo
632    /// to pair with (nothing was typed in the UI), so without this the
633    /// injection is invisible to the human operator: a silent injection, which
634    /// SPEC_JEKT_SECURITY_AND_VISIBILITY §3.1/G1 forbids. The live append
635    /// renders it in the open pane; the persisted line lets `parseHistoryLines`
636    /// rebuild the node on reopen.
637    ///
638    /// Called at *delivery* time, not enqueue time, so the transcript shows the
639    /// message where the agent actually received it. A queued message is
640    /// therefore not yet visible — surfacing "N waiting" is a UI question
641    /// tracked as spec §8 Q3.
642    pub(super) fn append_delivered_message(&self, json_str: &str, record: &RecordOrigin) {
643        let Some(ref broker) = self.broker else { return };
644        // A line with inline images is stored without their base64, as
645        // `persist_message_to_blockfile` stores one.
646        let json_str = &*crate::backend::attachments::prompt::persisted_line(json_str);
647        let global_zone =
648            crate::backend::transcript::append::resolve_global_output_zone(&self.mstore, &self.block_id);
649        // A paired device's message is stored with who sent it
650        // (`viewer::origin`); the agent's stdin got it without.
651        let stamped = crate::backend::viewer::origin::stamp(&self.block_id, json_str.as_bytes())
652            .and_then(|l| String::from_utf8(l).ok());
653        // Then where it came from and the notes that went with it.
654        let stored = crate::backend::message_origin::stamp_line(stamped.as_deref().unwrap_or(json_str), record);
655        crate::backend::transcript::append::append_output_line(
656            broker,
657            &self.block_id,
658            &stored,
659            self.filestore.as_ref(),
660            global_zone.as_deref(),
661        );
662    }
663
664    /// Answer a parked AskUserQuestion via the Agent SDK **control protocol**.
665    ///
666    /// The CLI asked us with a `can_use_tool` control_request (parked in
667    /// `pending_questions` by the stdout reader); we reply with a
668    /// `control_response` carrying `updatedInput.answers`. This is the ONLY
669    /// mechanism the CLI accepts — delivering a `tool_result` on stdin does NOT
670    /// work (the CLI auto-rejects AskUserQuestion within the turn). `answers` is
671    /// the JSON object mapping each question's text to the selected label(s) or
672    /// free-text. Process must already be running (agent is mid-turn, blocked on
673    /// this answer). Spec: docs/specs/SPEC_AGENT_CONTROL_PROTOCOL_2026_06_15.md §2.3.
674    /// `pending_questions` is in-memory-only, scoped to THIS controller
675    /// instance — a fresh instance (pane reopen, or any process respawn)
676    /// starts with an empty map even though the persisted transcript can
677    /// still show the question as the tail node (deliberately preserved by
678    /// `scrubOrphanedInProgress` as "may still be answerable"). The frontend
679    /// (`useAgentQuestions.ts`'s `SAFE_TO_RETRY_VIA_FOLLOWUP` allowlist)
680    /// matches on this error's text (the "no pending AskUserQuestion" prefix)
681    /// to redeliver as a follow-up message instead of rolling back — keep
682    /// that exact prefix stable if this message ever changes. See
683    /// docs/reports/REPORT_WORKING_STATE_REGRESSION_AND_STUCK_QUESTION_PANEL_2026_07_27.md §2.7/§2.8.
684    pub fn answer_question(&self, tool_use_id: String, answers: serde_json::Value) -> Result<(), String> {
685        let resume_msg = build_answer_resume_message(&answers);
686        self.reply_to_pending_question(
687            tool_use_id,
688            "persistent process not running (cannot deliver answer)",
689            |questions, tool_use_id| {
690                serde_json::json!({
691                    "behavior": "allow",
692                    "updatedInput": { "questions": questions, "answers": answers },
693                    "toolUseID": tool_use_id,
694                })
695            },
696            resume_msg,
697            &ANSWER_DEAD_AIR_LOGS,
698        )
699    }
700
701    /// Decline a parked AskUserQuestion via the Agent SDK **control protocol**
702    /// — the Cancel button / Escape in `AgentQuestionPanel.tsx`. Structurally a
703    /// mirror of `answer_question` (same `pending_questions` lookup/removal,
704    /// same dead-air safety net — the CLI can abandon a pending tool_use whose
705    /// turn already ended regardless of whether the response was an allow or a
706    /// deny), but sends `behavior: "deny"` with a `message` instead of
707    /// `behavior: "allow"` with `updatedInput`. This is a general, documented
708    /// Agent SDK mechanism (`PermissionResult` deny case for the `canUseTool`
709    /// callback) — AskUserQuestion goes through the exact same callback as
710    /// ordinary tool permission requests, confirmed against the official Agent
711    /// SDK docs (code.claude.com/docs/en/agent-sdk/user-input). Spec:
712    /// docs/specs/SPEC_AGENT_CONTROL_PROTOCOL_2026_06_15.md.
713    ///
714    /// See `answer_question`'s doc comment for the `pending_questions`
715    /// in-memory-only caveat and the exact error-prefix stability requirement
716    /// (`useAgentQuestions.ts`'s `SAFE_TO_RETRY_VIA_FOLLOWUP` allowlist matches
717    /// on this method's error text too, since it shares the identical lookup).
718    pub fn deny_question(&self, tool_use_id: String, message: String) -> Result<(), String> {
719        let resume_msg = build_deny_resume_message(&message);
720        self.reply_to_pending_question(
721            tool_use_id,
722            "persistent process not running (cannot deliver decline)",
723            |_questions, tool_use_id| {
724                serde_json::json!({
725                    "behavior": "deny",
726                    "message": message,
727                    "toolUseID": tool_use_id,
728                })
729            },
730            resume_msg,
731            &DENY_DEAD_AIR_LOGS,
732        )
733    }
734
735    /// Removes the parked AskUserQuestion `tool_use_id` and replies to it with
736    /// `response_body(questions, tool_use_id)` via
737    /// [`Self::send_control_response_with_fallback`]. The "no pending
738    /// AskUserQuestion" error prefix is matched by the frontend.
739    fn reply_to_pending_question(
740        &self,
741        tool_use_id: String,
742        not_running_error: &'static str,
743        response_body: impl FnOnce(serde_json::Value, &str) -> serde_json::Value,
744        resume_msg: String,
745        logs: &'static DeadAirLogs,
746    ) -> Result<(), String> {
747        let (request_id, questions, tx) = {
748            let mut inner = self.inner.lock().unwrap();
749            let (rid, qs) = inner
750                .pending_questions
751                .remove(&tool_use_id)
752                .ok_or_else(|| format!(
753                    "no pending AskUserQuestion for tool_use_id {tool_use_id} — this controller \
754                     instance never recorded it (process likely respawned since the question was \
755                     asked, e.g. a pane close/reopen); the caller should redeliver as a follow-up message"
756                ))?;
757            let tx = inner
758                .stdin_tx
759                .as_ref()
760                .ok_or(not_running_error)?
761                .clone();
762            (rid, qs, tx)
763        };
764        let body = response_body(questions, &tool_use_id);
765        self.send_control_response_with_fallback(tx, request_id, body, tool_use_id, resume_msg, logs)
766    }
767
768    /// Sends the `control_response` for a parked `can_use_tool` request and
769    /// arms the dead-air fallback, which re-delivers `resume_msg` as a
770    /// follow-up user turn if no stdout activity follows the response.
771    fn send_control_response_with_fallback(
772        &self,
773        tx: mpsc::Sender<String>,
774        request_id: String,
775        response_body: serde_json::Value,
776        tool_use_id: String,
777        resume_msg: String,
778        logs: &'static DeadAirLogs,
779    ) -> Result<(), String> {
780        // The wait for the user ends here: the watchdog's idle time counts
781        // from now, not from the agent's last output before it asked.
782        self.health_monitor.note_user_reply();
783        let control_response = serde_json::json!({
784            "type": "control_response",
785            "response": {
786                "subtype": "success",
787                "request_id": request_id,
788                "response": response_body,
789            }
790        });
791        // Snapshot stdout activity BEFORE sending, so a fast resume that emits
792        // between the send and the snapshot can't be mistaken for "no
793        // activity".
794        let stdout_seq = Arc::clone(&self.stdout_seq);
795        let before_seq = stdout_seq.load(Ordering::Relaxed);
796
797        tx.try_send(control_response.to_string())
798            .map_err(|e| format!("control_response send failed: {e}"))?;
799
800        // Dead-air safety net. The CLI *abandons* a pending tool_use if its
801        // turn already ended, silently dropping the control_response above
802        // (allow or deny), and the model stalls on an empty message
803        // (SPEC_ASK_USER_QUESTION_2026_06_15.md §9/§10.1). No stdout activity
804        // shortly after means the turn did not resume, so re-deliver the
805        // choice as a follow-up user turn. Gated on stdout activity (every
806        // frame, incl. control frames), so it never double-delivers.
807        let inner = Arc::clone(&self.inner);
808        let block_id = self.block_id.clone();
809        let persist = self.redelivery_persister();
810        tokio::spawn(async move {
811            tokio::time::sleep(std::time::Duration::from_millis(ANSWER_RESUME_FALLBACK_MS)).await;
812            // Any stdout frame since the snapshot means the turn resumed — nothing to do.
813            if stdout_seq.load(Ordering::Relaxed) != before_seq {
814                return;
815            }
816            let line = serde_json::json!({
817                "type": "user",
818                "message": { "role": "user", "content": resume_msg }
819            })
820            .to_string();
821            // The line is recorded in the transcript (spec §6.9) only if it was
822            // written, and not while a restart or stop is committed (the
823            // process is going down and may never read it; History must not
824            // claim a decision it never got). Recorded under the same `inner`
825            // acquisition as the send, so the fallbacks can't interleave with
826            // each other; ordering against a concurrent ordinary send is the
827            // same as between two ordinary sends (each records after its own
828            // send). `persist.write` never takes `inner`.
829            let guard = inner.lock().unwrap();
830            let stdin_tx = guard.stdin_tx.clone();
831            match stdin_tx {
832                Some(stdin_tx) if stdin_tx.try_send(line.clone()).is_ok() => {
833                    if !guard.restart_pending && !guard.stop_pending {
834                        persist.write(&line);
835                    }
836                    drop(guard);
837                    tracing::warn!(
838                        block_id = %block_id,
839                        tool_use_id = %tool_use_id,
840                        fallback_ms = ANSWER_RESUME_FALLBACK_MS,
841                        "{}",
842                        logs.redelivered
843                    );
844                }
845                Some(_) => tracing::warn!(block_id = %block_id, "{}", logs.send_failed),
846                None => tracing::warn!(block_id = %block_id, "{}", logs.not_running),
847            }
848        });
849        Ok(())
850    }
851
852    /// Decide a parked ordinary tool-permission request via the Agent SDK
853    /// **control protocol** — the eventual `AgentDecisionPanel` Allow/Deny
854    /// buttons, once `should_route_to_decision_panel` is flipped on (Phase 2,
855    /// `SPEC_DECISION_PROMPT_2026_04_24.md` / `SPEC_AGENT_CONTROL_PROTOCOL_2026_06_15.md`
856    /// §5). Mirrors `answer_question`/`deny_question` exactly — same
857    /// `pending_*` map lookup/removal, same dead-air safety net — combined
858    /// into one method because the frontend's `tool:decision` RPC already
859    /// carries `outcome` as a single field rather than two separate
860    /// commands.
861    ///
862    /// `outcome` must be `"allow"` or `"deny"` — validated by the caller
863    /// (`websocket.rs`'s `tooldecision` handler) before this is reached, the
864    /// same division of responsibility as that handler's existing `scope`
865    /// validation. An unrecognized value is treated as `"deny"` (fail
866    /// closed) rather than panicking or silently allowing.
867    ///
868    /// On allow, `updatedInput` echoes the ORIGINAL input verbatim — this
869    /// method does not support editing the call before approving it (no UI
870    /// for that exists; `SPEC_DECISION_PROMPT_2026_04_24.md` never scoped
871    /// one). On deny, `feedback` becomes the CLI-facing `message`
872    /// (`SPEC_DECISION_PROMPT`'s G6: "Denials carry user-typed feedback
873    /// verbatim to the agent"); a caller with no feedback gets a generic
874    /// default so the model still learns the call was refused.
875    ///
876    /// See `answer_question`'s doc comment for the `pending_permissions`
877    /// in-memory-only caveat (a fresh controller instance — pane reopen, any
878    /// process respawn — starts with an empty map) and for why the error
879    /// text names the tool_use_id and the likely cause.
880    pub fn decide_tool_permission(
881        &self,
882        tool_use_id: String,
883        outcome: &str,
884        feedback: Option<String>,
885    ) -> Result<(), String> {
886        let (request_id, tool_name, input, tx) = {
887            let mut inner = self.inner.lock().unwrap();
888            let (rid, tool_name, input) = inner
889                .pending_permissions
890                .remove(&tool_use_id)
891                .ok_or_else(|| format!(
892                    "no pending tool-permission request for tool_use_id {tool_use_id} — this \
893                     controller instance never recorded it (process likely respawned since the \
894                     request was made, e.g. a pane close/reopen); the caller should redeliver \
895                     as a follow-up message"
896                ))?;
897            let tx = inner
898                .stdin_tx
899                .as_ref()
900                .ok_or("persistent process not running (cannot deliver decision)")?
901                .clone();
902            (rid, tool_name, input, tx)
903        };
904
905        let allow = outcome == "allow";
906        let response_body = if allow {
907            serde_json::json!({
908                "behavior": "allow",
909                "updatedInput": input,
910                "toolUseID": tool_use_id,
911            })
912        } else {
913            serde_json::json!({
914                "behavior": "deny",
915                "message": feedback.clone().unwrap_or_else(|| "Denied by user.".to_string()),
916                "toolUseID": tool_use_id,
917            })
918        };
919        let resume_msg = build_tool_decision_resume_message(&tool_name, outcome, feedback.as_deref());
920        self.send_control_response_with_fallback(
921            tx,
922            request_id,
923            response_body,
924            tool_use_id,
925            resume_msg,
926            &TOOL_DECISION_DEAD_AIR_LOGS,
927        )
928    }
929
930    /// Push a raw NDJSON line to the live stdin (used to emit control_responses
931    /// from the stdout-reader task, which only holds an `Arc<Mutex<Inner>>`).
932    pub(super) fn push_stdin(inner: &Arc<Mutex<PersistentInner>>, line: String) {
933        let guard = inner.lock().unwrap();
934        if let Some(tx) = guard.stdin_tx.as_ref() {
935            let _ = tx.try_send(line);
936        }
937    }
938
939    /// Handle a control-protocol frame from the CLI's stdout. `control_request`
940    /// of subtype `can_use_tool`: AskUserQuestion is **parked** (the frontend
941    /// panel — rendered from the assistant stream — answers it via
942    /// `answer_question`); every other tool is routed to
943    /// `should_route_to_decision_panel`, which today always says no, so it is
944    /// **auto-allowed** to preserve the current bypass/yolo UX (Phase 1; see
945    /// that function's own doc comment for why Phase 2, #551, isn't simply
946    /// "flip it to true"). `control_response` frames (replies to requests we
947    /// initiate, none today) are logged and dropped. These frames are NOT
948    /// conversation output and never reach the blockfile.
949    /// Spec: docs/specs/SPEC_AGENT_CONTROL_PROTOCOL_2026_06_15.md §4.2.
950    pub(super) fn handle_control_frame(
951        kind: &str,
952        parsed: &serde_json::Value,
953        block_id: &str,
954        inner: &Arc<Mutex<PersistentInner>>,
955    ) {
956        if kind == "control_response" {
957            return;
958        }
959        // control_request
960        let req = match parsed.get("request") {
961            Some(r) => r,
962            None => return,
963        };
964        let subtype = req.get("subtype").and_then(|v| v.as_str()).unwrap_or("");
965        let request_id = parsed
966            .get("request_id")
967            .and_then(|v| v.as_str())
968            .unwrap_or("")
969            .to_string();
970
971        if subtype != "can_use_tool" {
972            tracing::info!(block_id = %block_id, subtype = %subtype, "persistent control_request: unhandled subtype, ignoring");
973            return;
974        }
975
976        let tool_name = req.get("tool_name").and_then(|v| v.as_str()).unwrap_or("");
977        let tool_use_id = req
978            .get("tool_use_id")
979            .and_then(|v| v.as_str())
980            .unwrap_or("")
981            .to_string();
982        let input = req.get("input").cloned().unwrap_or_else(|| serde_json::json!({}));
983
984        if tool_name == "AskUserQuestion" {
985            // Park; the frontend question panel will answer via answer_question().
986            let questions = input
987                .get("questions")
988                .cloned()
989                .unwrap_or_else(|| serde_json::json!([]));
990            {
991                let mut guard = inner.lock().unwrap();
992                guard
993                    .pending_questions
994                    .insert(tool_use_id.clone(), (request_id, questions));
995            }
996            tracing::info!(block_id = %block_id, tool_use_id = %tool_use_id, "AskUserQuestion parked; awaiting user answer");
997        } else if should_route_to_decision_panel(tool_name) {
998            // PHASE2-GATE: unreachable in production today (see that
999            // function's doc comment). Park exactly like AskUserQuestion
1000            // above; the eventual AgentDecisionPanel Allow/Deny answers via
1001            // `PersistentSubprocessController::decide_tool_permission`.
1002            park_tool_permission_request(inner, tool_use_id.clone(), request_id, tool_name.to_string(), input);
1003            tracing::info!(block_id = %block_id, tool_use_id = %tool_use_id, tool_name = %tool_name, "tool-permission request parked; awaiting user decision");
1004        } else {
1005            // Auto-allow every other tool (preserve today's bypass UX).
1006            let resp = serde_json::json!({
1007                "type": "control_response",
1008                "response": {
1009                    "subtype": "success",
1010                    "request_id": request_id,
1011                    "response": { "behavior": "allow", "updatedInput": input }
1012                }
1013            });
1014            Self::push_stdin(inner, resp.to_string());
1015        }
1016    }
1017}
1018
1019/// The warn-level lines one dead-air fallback logs: re-delivered, stdin send
1020/// failed, and skipped because the process is gone.
1021struct DeadAirLogs {
1022    redelivered: &'static str,
1023    send_failed: &'static str,
1024    not_running: &'static str,
1025}
1026
1027const ANSWER_DEAD_AIR_LOGS: DeadAirLogs = DeadAirLogs {
1028    redelivered: "AskUserQuestion answer did not resume the turn — re-delivered as a follow-up message (dead-air fallback)",
1029    send_failed: "AskUserQuestion dead-air fallback: stdin send failed",
1030    not_running: "AskUserQuestion dead-air fallback skipped: process not running",
1031};
1032
1033const DENY_DEAD_AIR_LOGS: DeadAirLogs = DeadAirLogs {
1034    redelivered: "AskUserQuestion decline did not resume the turn — re-delivered as a follow-up message (dead-air fallback)",
1035    send_failed: "AskUserQuestion deny dead-air fallback: stdin send failed",
1036    not_running: "AskUserQuestion deny dead-air fallback skipped: process not running",
1037};
1038
1039const TOOL_DECISION_DEAD_AIR_LOGS: DeadAirLogs = DeadAirLogs {
1040    redelivered: "tool-permission decision did not resume the turn — re-delivered as a follow-up message (dead-air fallback)",
1041    send_failed: "tool-permission dead-air fallback: stdin send failed",
1042    not_running: "tool-permission dead-air fallback skipped: process not running",
1043};
1044
1045/// Records a dead-air re-delivery in the transcript. The three dead-air
1046/// fallbacks (answer, decline, tool-permission decision) re-send the user's
1047/// choice as a follow-up stdin line when the CLI abandoned the pending tool
1048/// call; the CLI then writes no tool result, so without this the choice is
1049/// gone on reload, absent from History, and lost when the live feed rolls the
1050/// turn off (spec §6.9; Codex review of #3703). Written like every other
1051/// stdin line (`persist_message_to_blockfile`), after the send succeeded.
1052pub(super) struct RedeliveryPersister {
1053    broker: Option<Arc<mps::Broker>>,
1054    filestore: Option<Arc<FileStore>>,
1055    mstore: Option<Arc<Store>>,
1056    block_id: String,
1057}
1058
1059impl RedeliveryPersister {
1060    pub(super) fn write(&self, line: &str) {
1061        let global_zone =
1062            crate::backend::transcript::append::resolve_global_output_zone(&self.mstore, &self.block_id);
1063        let record = format!("{line}\n");
1064        crate::backend::transcript::append::persist_user_line(
1065            self.broker.as_deref(),
1066            &self.block_id,
1067            record.as_bytes(),
1068            self.filestore.as_ref(),
1069            global_zone.as_deref(),
1070            // The human's own choice, sent again.
1071            Some(&RecordOrigin::new(MessageOrigin::user())),
1072        );
1073    }
1074}
1075
1076/// Park an ordinary (non-AskUserQuestion) tool-permission `can_use_tool`
1077/// control_request into `PersistentInner::pending_permissions`, mirroring
1078/// how AskUserQuestion is parked into `pending_questions` two branches up in
1079/// `handle_control_frame` — same in-memory-only, per-controller-instance
1080/// lifetime, and the same "process respawned" failure mode on decide
1081/// (`PersistentSubprocessController::decide_tool_permission`'s error text
1082/// explains it the same way `answer_question`'s does).
1083///
1084/// Currently unreachable in production: `should_route_to_decision_panel`
1085/// always returns `false`, so `handle_control_frame` never calls this. Kept
1086/// as its own function (rather than inlined, unlike the AskUserQuestion
1087/// branch) specifically so it can be unit tested directly, independent of
1088/// that gate.
1089pub(super) fn park_tool_permission_request(
1090    inner: &Arc<Mutex<PersistentInner>>,
1091    tool_use_id: String,
1092    request_id: String,
1093    tool_name: String,
1094    input: serde_json::Value,
1095) {
1096    let mut guard = inner.lock().unwrap();
1097    guard
1098        .pending_permissions
1099        .insert(tool_use_id, (request_id, tool_name, input));
1100}
1101
1102/// A new process is not waiting on what the last one asked: drop the requests parked for the user.
1103pub(super) fn forget_parked_requests(inner: &mut PersistentInner) {
1104    inner.pending_questions.clear();
1105    inner.pending_permissions.clear();
1106}
1107
1108impl PersistentSubprocessController {
1109    /// Whether an AskUserQuestion or a tool-permission request is parked
1110    /// waiting for the user (`Controller::awaiting_user_reply`).
1111    pub(super) fn has_parked_request(&self) -> bool {
1112        let inner = self.inner.lock().unwrap();
1113        !inner.pending_questions.is_empty() || !inner.pending_permissions.is_empty()
1114    }
1115
1116    /// `Controller::pending_for_devices`: a parked AskUserQuestion before a parked tool permission, the first by
1117    /// tool use id, and how many messages wait in `pending_send_messages`.
1118    pub(super) fn parked_for_devices(&self) -> crate::backend::blockcontroller::PendingFacts {
1119        use crate::backend::blockcontroller::{PendingFacts, PendingRequest};
1120        let inner = self.inner.lock().unwrap();
1121        let first = |ids: Vec<&String>, kind| ids.into_iter().min().map(|id| PendingRequest { id: id.clone(), kind });
1122        let open = first(inner.pending_questions.keys().collect(), "question")
1123            .or_else(|| first(inner.pending_permissions.keys().collect(), "approval"));
1124        PendingFacts { open, queued: inner.pending_send_messages.len() }
1125    }
1126}