Skip to main content

agentmux_srv_core/backend/blockcontroller/persistent/
queue.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Message intake and the spawn-claim/queue-drain protocol: `send_message` and
5//! everything that decides whether a message is written to stdin now, queued
6//! behind an in-flight spawn, or replayed after one.
7
8use super::*;
9
10impl PersistentSubprocessController {
11    /// Atomically decides what to do with `json_str`, given the caller
12    /// wants it delivered to the persistent process — see
13    /// `PersistentInner::spawning_in_progress`'s doc comment for the race
14    /// this closes. All three outcomes are decided under ONE lock
15    /// acquisition so nothing can slip through the gaps between them:
16    /// - the process is already running AND nobody is still draining a
17    ///   backlog into it → `DeliverDirect`, no spawn decision at all.
18    /// - someone is currently spawning OR still draining a backlog
19    ///   (`spawning_in_progress`) → `json_str` is enqueued for THAT
20    ///   caller's own drain to deliver, and this call returns `Queued`
21    ///   with nothing further to do. reagentx P1 on PR #2360 (sixth
22    ///   review pass, round 4): `spawn_process` sets `stdin_tx` well
23    ///   before the queued message that triggered the spawn is actually
24    ///   delivered (that happens later, on a background drain task —
25    ///   see `drain_queue_after_successful_spawn`). Gating `DeliverDirect`
26    ///   on `stdin_tx.is_some()` alone let a second, genuinely concurrent
27    ///   `send_message` call land in that exact window and write straight
28    ///   to stdin via `try_send`, racing ahead of the drain's own
29    ///   `Sender::send().await` for the message that actually triggered
30    ///   the spawn — silently reordering user input. Checking
31    ///   `!spawning_in_progress` too routes it into the queue instead,
32    ///   where the SAME already-running drain loop (it stays `true` for
33    ///   its entire lifetime — see the field's own doc comment) picks it
34    ///   up next, in order.
35    /// - nobody is running AND nobody is spawning → this caller claims the
36    ///   exclusive right to (`spawning_in_progress = true`), enqueues
37    ///   `json_str` alongside that claim, and returns `BecomeSpawner` —
38    ///   the caller must then call `spawn_process` and, regardless of
39    ///   outcome, call `release_spawn_claim_and_drain_queue`.
40    ///
41    /// `skip_if_seq_queued` is always `None` for the sole production call
42    /// site (`send_message_with_images_from`, which `send_message` reaches):
43    /// a user legitimately re-sending the exact same text while an
44    /// unrelated spawn is in flight must still queue both, so this must
45    /// never dedup there.
46    ///
47    /// `Some(seq)` is NOT exercised by any production call site (#2360) —
48    /// `retry_after_resume_failure` uses `decide_retry_batch_action`
49    /// instead, a separate function with its own atomic,
50    /// batch-aware dedup/prepend logic (see that function's own doc
51    /// comment). The `Some` path here now only exists for unit tests
52    /// (`tests/send_input.rs`), which document the exact scenario
53    /// `decide_retry_batch_action`'s own dedup check handles for a batch
54    /// instead — a KNOWN re-delivery of
55    /// content that may ALREADY be sitting in `pending_send_messages`,
56    /// pushed by the very spawn attempt whose failure triggered a retry,
57    /// if that spawn's own drain hasn't reached it yet; blindly queueing
58    /// another copy there let a fallback spawn eventually deliver the
59    /// same prompt twice.
60    /// `skip_if_seq_queued`: `Some(seq)` marks this call a KNOWN
61    /// re-delivery of the message originally enqueued under `seq` — skip
62    /// enqueueing if that exact entry is still queued, and preserve the
63    /// original seq (not a fresh one) if it must be re-queued, so the
64    /// message keeps one identity for its whole lifetime (issue #2365:
65    /// the old content-equality check here treated a genuinely
66    /// different, identical-text message as "already queued" and
67    /// silently dropped it).
68    #[cfg(test)]
69    pub(super) fn decide_send_action(&self, json_str: &str, skip_if_seq_queued: Option<u64>) -> SendAction {
70        self.decide_send_action_from(json_str, skip_if_seq_queued, None, RecordOrigin::new(MessageOrigin::user()))
71    }
72
73    /// [`Self::decide_send_action`], saying who the input is from (turn
74    /// provenance, SPEC_AGENT_SELF_QUIT §6.3). A direct delivery reports it
75    /// with the turn mark; a queued one tells the tracker about the turn it
76    /// will start.
77    pub(super) fn decide_send_action_from(
78        &self,
79        json_str: &str,
80        skip_if_seq_queued: Option<u64>,
81        origin: Option<crate::backend::blockcontroller::health::TurnInput>,
82        record: RecordOrigin,
83    ) -> SendAction {
84        let mut inner = self.inner.lock().unwrap();
85        // `!restart_pending`: a committed deferred restart leaves `stdin_tx`
86        // live until the process actually exits, and writing into a process
87        // about to be killed loses the message (codex P1 on PR #2858). Falling
88        // through queues it for the replacement instead. `!stop_pending`: the
89        // same loss for a requested kill; see the `Refused` branch below.
90        if inner.stdin_tx.is_some()
91            && !inner.spawning_in_progress
92            && !inner.drain_claim
93            && !inner.restart_pending
94            && !inner.stop_pending
95        {
96            // Reserve the turn before `inner` is released. Lock order is
97            // `inner` → `health_monitor`, as everywhere else.
98            let was_active = self.health_monitor.mark_turn_active_from(origin);
99            SendAction::DeliverDirect { was_active }
100        } else if inner.spawning_in_progress || inner.drain_claim {
101            let already_queued = skip_if_seq_queued
102                .is_some_and(|seq| inner.pending_send_messages.iter().any(|m| m.seq == seq));
103            if !already_queued {
104                let seq = skip_if_seq_queued.unwrap_or_else(|| inner.take_next_message_seq());
105                inner
106                    .pending_send_messages
107                    .push_back(QueuedMessage::fresh(seq, json_str.to_string(), record));
108            }
109            SendAction::Queued
110        } else if inner.stop_pending && !inner.restart_pending && inner.stdin_tx.is_some() {
111            // A kill is pending and the dying process still holds stdin
112            // (reagent P1 on #3562). Writing loses the message; spawning is
113            // wrong too, since the stop may be a teardown (`delete_controller`,
114            // pane shutdown) and would start a process for a closing pane.
115            // Refuse it explicitly: the window lasts until the exit, after
116            // which a send respawns as usual. A committed restart also sets
117            // `stop_pending`, and keeps its own rule: the message falls
118            // through and queues for the replacement.
119            SendAction::Refused(
120                "this agent is stopping — send the message again once it has stopped".to_string(),
121            )
122        } else {
123            inner.spawning_in_progress = true;
124            let own_seq = skip_if_seq_queued.unwrap_or_else(|| inner.take_next_message_seq());
125            inner
126                .pending_send_messages
127                .push_back(QueuedMessage::fresh(own_seq, json_str.to_string(), record));
128            SendAction::BecomeSpawner { own_seq }
129        }
130    }
131
132    /// The write half of [`SendAction::DeliverDirect`], under a second `inner`
133    /// acquisition. On failure nothing was written, and the turn the decision
134    /// reserved is handed back: left active, it would hold every deferred
135    /// message for a `result` that never comes. Nobody else can have started a
136    /// turn meanwhile, since they all saw it reserved and deferred, and the
137    /// watchdog each armed releases them once it reads idle.
138    ///
139    /// Written through [`Self::try_write_stdin_locked`], like every other
140    /// write site, so the gates are re-checked under THIS acquisition: a stop
141    /// or config restart committed after the decision (heartbeat and status
142    /// publish run in between, with `stdin_tx` still live) refuses the write
143    /// instead of putting the message into the dying process (reagent P1 on
144    /// #3562). The same call tracks it into the current generation's retry
145    /// batch (codex P1 on PR #3513: eager resume can reach `DeliverDirect`
146    /// with its `--resume` unconfirmed and no seed tracked), reading the
147    /// generation in this same acquisition (reagentx P1 on PR #2373).
148    pub(super) fn deliver_direct(&self, json_str: &str, was_active: bool) -> Result<(), String> {
149        let mut inner = self.inner.lock().unwrap();
150        if let Err(e) = Self::try_write_stdin_locked(&mut inner, json_str) {
151            if !was_active {
152                self.health_monitor.set_active_turn(false);
153            }
154            drop(inner);
155            self.publish_status();
156            return Err(e);
157        }
158        Ok(())
159    }
160
161    /// Releases the exclusive spawn claim taken by `decide_send_action`
162    /// returning `BecomeSpawner`. `spawn_succeeded` distinguishes two very
163    /// different situations:
164    ///
165    /// - **Failed spawn**: discards only the entry with `own_seq` — the
166    ///   specific message THIS spawner pushed when it claimed
167    ///   `BecomeSpawner` (`SendAction::BecomeSpawner::own_seq`), found by
168    ///   queue identity rather than assumed to be at the front. codex P2
169    ///   on PR #2360 (round 14, commit 8c2bc99ab): the queue is NOT always
170    ///   empty at the moment a new spawner claims it — the "second stall"
171    ///   path (`drain_queue_after_successful_spawn` with
172    ///   `allow_fallback_respawn: false`) deliberately releases
173    ///   `spawning_in_progress` while leaving genuinely leftover messages
174    ///   queued (see that function's own doc comment). A later
175    ///   `send_message` can then claim `BecomeSpawner` and `push_back` its
176    ///   own message BEHIND those leftovers. Assuming "front == my own
177    ///   message" in that case discarded an OLDER, unrelated, already-
178    ///   accepted prompt instead of the actually-failed one — silent data
179    ///   loss, plus handing the wrong (already-failed) message to the
180    ///   fallback respawn. Originally fixed by matching content instead
181    ///   of position, which still left two GENUINELY DIFFERENT messages
182    ///   sharing identical text (e.g. two "yes" replies) ambiguous; seq
183    ///   matching (issue #2365) closes that residue too. codex P1 on PR
184    ///   #2360 (sixth review pass): leaving this message queued let an
185    ///   unrelated LATER successful spawn silently execute a prompt the
186    ///   caller was already told had failed (`send_message`/
187    ///   `retry_after_resume_failure` already report the failure),
188    ///   sometimes duplicating a message the user had re-sent by hand.
189    ///   Anything else queued (from other callers who got
190    ///   `SendAction::Queued` and were already told "accepted") is left in
191    ///   place for the next successful spawn.
192    /// - **Successful spawn**: hands the drain off to a background task
193    ///   that delivers everything queued, in order, via `Sender::send`
194    ///   (which awaits free capacity) rather than `try_send`. codex P2 on
195    ///   PR #2360 (sixth review pass): a synchronous `try_send` loop
196    ///   popped a message off the queue and then discarded it outright if
197    ///   the bounded stdin channel was momentarily full — losing input
198    ///   despite already having told that caller "accepted". Deferring to
199    ///   a task lets delivery simply wait for capacity instead.
200    ///
201    /// If the background task discovers the process it was meant to drain
202    /// into has ALREADY died (`stdin_tx` gone) with messages still left
203    /// queued, it hands off to `respawn_once_for_leftover_queue` using
204    /// `retry_config` — reagentx/codex P1 on PR #2360 (sixth review pass,
205    /// rounds 3-4): a fast-dying child can let the process-waiter run this
206    /// SAME controller's own `retry_after_resume_failure` (via
207    /// `decide_send_action` returning `Queued`, since this spawn's claim
208    /// hasn't been released yet) BEFORE this caller's own thread even
209    /// reaches this function; that retry's `Queued` branch then does
210    /// nothing further, assuming (wrongly, in this exact race) that this
211    /// drain will deliver it. Without a fallback respawn, NOTHING is ever
212    /// left responsible for the leftover messages or for telling the
213    /// frontend the turn ended — the ORIGINAL exit deliberately suppressed
214    /// its own terminal-status publish expecting the retry to eventually
215    /// publish one.
216    pub(super) fn release_spawn_claim_and_drain_queue(&self, spawn_succeeded: bool, retry_config: PersistentSpawnConfig, own_seq: u64) {
217        if !spawn_succeeded {
218            // Discard only the `own_seq` entry — see this function's own doc
219            // comment above for why position (front) is not a safe
220            // assumption. If anything else is queued (from other callers
221            // already told "accepted"), hand off to a bounded fallback
222            // respawn rather than stranding it with nobody responsible for
223            // delivering it.
224            //
225            // codex P2 on PR #2360 (round 13, commit e9678091f): clearing
226            // `spawning_in_progress` in a SEPARATE, later lock acquisition
227            // left a window between the emptiness check above and that
228            // clear where a concurrent `send_message` could observe
229            // `spawning_in_progress` still `true`, enqueue its message via
230            // `decide_send_action`'s `Queued` branch, and be told
231            // "accepted" — then this function's second lock would clear
232            // the claim without ever rechecking the queue, stranding that
233            // accepted message with no spawner and no drain ever
234            // responsible for it. The emptiness check and the flag clear
235            // must be one atomic decision under a single lock acquisition
236            // (same shape as the round-9 regression this whole PR already
237            // fixed once): only clear the claim here if the queue is STILL
238            // empty at the exact moment we're about to clear it; otherwise
239            // leave the claim held and hand off to the fallback respawn.
240            let leftovers = {
241                let mut inner = self.inner.lock().unwrap();
242                if let Some(idx) = inner.pending_send_messages.iter().position(|m| m.seq == own_seq) {
243                    inner.pending_send_messages.remove(idx);
244                } else {
245                    // Shouldn't normally happen — defensively log rather
246                    // than guess which OTHER entry to discard instead.
247                    tracing::warn!(
248                        block_id = %self.block_id,
249                        "failed spawn's own message was not found in the queue to discard"
250                    );
251                }
252                if inner.pending_send_messages.is_empty() {
253                    inner.spawning_in_progress = false;
254                    false
255                } else {
256                    true
257                }
258            };
259            if leftovers {
260                self.respawn_once_for_leftover_queue(retry_config);
261            }
262            return;
263        }
264        self.drain_queue_after_successful_spawn(retry_config, true);
265    }
266
267    /// Drains the queue via a background task after a successful spawn —
268    /// see `release_spawn_claim_and_drain_queue`'s doc comment for the
269    /// `try_send` → `Sender::send` rationale. `allow_fallback_respawn`
270    /// bounds retry depth to exactly one extra hop: `true` from the public
271    /// entry point, `false` when called from `respawn_once_for_leftover_queue`
272    /// itself, so a SECOND stall just publishes a status update instead of
273    /// cascading indefinitely.
274    pub(super) fn drain_queue_after_successful_spawn(&self, retry_config: PersistentSpawnConfig, allow_fallback_respawn: bool) {
275        self.drain_queue_with_claim(retry_config, allow_fallback_respawn, QueueDrainClaim::SpawnClaim);
276    }
277
278    /// The queue-drain loop itself, parameterized by which exclusivity
279    /// claim it runs under ([`QueueDrainClaim`]) — the post-spawn drain
280    /// (`SpawnClaim`) and issue #2367's retry-batch flush (`RetryFlush`)
281    /// share every delivery invariant (Sender::send backpressure,
282    /// seed-aware retry-batch appends, delivery-order persistence,
283    /// stall handling); the ONLY difference is which flag they release.
284    /// `RetryFlush` callers always pass `allow_fallback_respawn: false`:
285    /// the flush targets an already-running process, so a stall means
286    /// that process died — leftovers stay queued for the next spawn and
287    /// the stalled branch publishes a status update.
288    pub(super) fn drain_queue_with_claim(
289        &self,
290        retry_config: PersistentSpawnConfig,
291        allow_fallback_respawn: bool,
292        claim: QueueDrainClaim,
293    ) {
294        debug_assert!(
295            !(claim == QueueDrainClaim::RetryFlush && allow_fallback_respawn),
296            "a retry flush never respawns — see this function's doc comment"
297        );
298        let inner_arc = Arc::clone(&self.inner);
299        let block_id = self.block_id.clone();
300        let self_ref = self.self_ref.lock().unwrap().clone().unwrap_or_default();
301        tokio::spawn(async move {
302            // The message `spawn_process` already seeded synchronously
303            // into the retry batch in `inner.resume` (before this task even
304            // existed — necessary so a process that dies before this task's
305            // first poll can't lose it, see `ResumeState`'s own doc comment)
306            // must be identified exactly, not by "whatever this drain pops
307            // first" (#2360):
308            // a purely positional flag breaks exactly the way
309            // `release_spawn_claim_and_drain_queue`'s front-popping
310            // assumption did (see that function's own fix history): a
311            // prior "second stall" can leave older leftover messages
312            // queued ahead of a later spawner's own triggering message
313            // (`push_back` appends behind them), so the FIRST thing this
314            // drain pops isn't necessarily the seeded one. Treating it as
315            // if it were: (a) skips recording the OLDER leftover into the
316            // retry-batch tracking at all — silently dropping it forever
317            // if this process ALSO later dies from a stale resume, and
318            // (b) records the ACTUAL seeded/triggering message a SECOND
319            // time (once via `spawn_process`'s synchronous seed, once via
320            // this drain's own append) — a confirmed stale-resume retry
321            // would then redeliver that one message TWICE. Originally
322            // fixed by matching content (with `seed_already_matched` as a
323            // one-shot so an identical-text later delivery wasn't ALSO
324            // skipped); now matched by queue identity
325            // (`QueuedMessage::seq`, issue #2365), which identifies the
326            // seeded entry exactly regardless of position or duplicate
327            // text. The one-shot flag is kept as cheap defense-in-depth —
328            // seqs are never reused, so it can no longer fire twice.
329            let mut seed_already_matched = false;
330            let stalled_with_leftovers = loop {
331                let next = {
332                    let mut inner = inner_arc.lock().unwrap();
333                    match inner.stdin_tx.clone() {
334                        Some(tx) => inner.pending_send_messages.pop_front().map(|m| (m, tx)),
335                        None => None,
336                    }
337                };
338                let Some((queued, tx)) = next else {
339                    // Either the queue is empty, or the process has
340                    // already exited again before we got to it. Release
341                    // the claim ONLY if we're not about to hand off to a
342                    // fallback respawn — reagentx P1 on PR #2360 (sixth
343                    // review pass, round 4): releasing it unconditionally
344                    // here left a window, between this release and
345                    // `respawn_once_for_leftover_queue`'s own
346                    // `spawn_process` call re-establishing state, where a
347                    // concurrent `send_message`/`retry_after_resume_failure`
348                    // could see "not running, not spawning" and
349                    // independently spawn its own child process for the
350                    // same block — reintroducing the exact orphaned/
351                    // duplicate-process race `spawning_in_progress` was
352                    // added in this same PR to close.
353                    let mut inner = inner_arc.lock().unwrap();
354                    // Re-check the queue under THIS lock before releasing:
355                    // the pop above observing "empty" and this release are
356                    // two separate acquisitions, and a concurrent caller
357                    // routed to `Queued` (claim still held) can enqueue in
358                    // that gap. With a live tx, releasing now would strand
359                    // that message — no claim holder ever drains it, and
360                    // every future send takes `DeliverDirect` straight
361                    // past it. Loop back and drain it instead (issue
362                    // #2367's queue-authority guarantee; the same gap
363                    // existed for the spawn-claim drain).
364                    if inner.stdin_tx.is_some() && !inner.pending_send_messages.is_empty() {
365                        drop(inner);
366                        continue;
367                    }
368                    let stalled = inner.stdin_tx.is_none() && !inner.pending_send_messages.is_empty();
369                    if !(stalled && allow_fallback_respawn) {
370                        claim.release(&mut inner);
371                    }
372                    break stalled;
373                };
374                let QueuedMessage { seq, json_str, already_persisted, record } = queued;
375                let delivered_copy = json_str.clone();
376                let is_the_seed = !seed_already_matched && {
377                    let inner = inner_arc.lock().unwrap();
378                    inner.resume.is_seeded_message(inner.spawn_generation, seq)
379                };
380                if is_the_seed {
381                    seed_already_matched = true;
382                }
383                // reagentx P1 on PR #2360 (sixth review pass, round 9):
384                // mark "in flight" for the ENTIRE send-then-append
385                // sequence below, not just the send — see
386                // `PersistentInner::drain_send_in_flight`'s own doc
387                // comment for the race this closes (the process-waiter's
388                // exit-handling can `.take()` the confirmed retry batch
389                // in the gap between a successful send and this task
390                // getting back around to recording it there).
391                inner_arc.lock().unwrap().drain_send_in_flight = true;
392                if let Err(e) = tx.send(json_str).await {
393                    tracing::warn!(
394                        block_id = %block_id,
395                        "failed to deliver a queued message — receiver dropped, process likely exited"
396                    );
397                    // The channel's gone, so no send from here will ever
398                    // succeed again — put the message back (rather than
399                    // silently discarding it) for a future spawn to pick
400                    // up. Same claim-retention rule as above.
401                    let mut inner = inner_arc.lock().unwrap();
402                    inner.drain_send_in_flight = false;
403                    inner.pending_send_messages.push_front(QueuedMessage { seq, json_str: e.0, already_persisted, record });
404                    let stalled = !inner.pending_send_messages.is_empty();
405                    if !(stalled && allow_fallback_respawn) {
406                        claim.release(&mut inner);
407                    }
408                    break stalled;
409                }
410                // codex P1 on PR #2360 (sixth review pass, round 5): track
411                // every message actually handed to this process's stdin
412                // channel beyond the first — not just the one that
413                // triggered the spawn — so a confirmed stale-resume retry
414                // redelivers all of them (see `RetryPayload`'s own doc
415                // comment), since channel acceptance is not proof the CLI
416                // ever read it. `MessageAppendedToRetryBatch` is applied
417                // whether the state is still `AwaitingOutcome` or has
418                // already been promoted to `ConfirmedRetry` — codex P1 on
419                // PR #2360 (sixth review pass, round 6): `poison_resume`
420                // (the stderr-reader task, running concurrently) can
421                // promote at any point, and `persistent_resume::update`
422                // handles the append identically either way (see its own
423                // `MessageAppendedToRetryBatch` match arms), so there's no
424                // window where a message delivered right after that
425                // promotion is silently dropped.
426                if !is_the_seed {
427                    // reagentx P1 on PR #2373: reading `spawn_generation`
428                    // and applying the event were two SEPARATE lock
429                    // acquisitions — a concurrent respawn in between would
430                    // bump `spawn_generation`, making this event carry a
431                    // now-stale generation that `update()`'s catch-all
432                    // silently ignores, losing the message from the retry
433                    // batch. One lock acquisition closes the gap.
434                    let mut inner = inner_arc.lock().unwrap();
435                    let generation = inner.spawn_generation;
436                    inner.apply_resume_event(persistent_resume::ResumeEvent::MessageAppendedToRetryBatch {
437                        generation,
438                        entry: persistent_resume::QueuedRetryEntry { seq, json: delivered_copy.clone() },
439                    });
440                }
441                inner_arc.lock().unwrap().drain_send_in_flight = false;
442                // Persist in actual delivery order — codex P2 on PR #2360
443                // (sixth review pass, round 5): persisting at the
444                // `decide_send_action` call site instead let two callers'
445                // own synchronous code run (and thus persist) in a
446                // different order than their messages are actually
447                // delivered, producing a blockfile transcript that
448                // doesn't match what the agent received. Skipped for a
449                // stale-resume retry's redelivery — codex P2 on PR #2360
450                // (sixth review pass, round 7): that content was already
451                // correctly persisted on its ORIGINAL (failed) attempt;
452                // persisting it again here duplicated every replayed
453                // prompt in the blockfile transcript.
454                if let (false, Some(record)) = (already_persisted, record.as_ref()) {
455                    if let Some(ctrl) = self_ref.upgrade() {
456                        ctrl.persist_message_to_blockfile(&delivered_copy, record);
457                    }
458                }
459            };
460            if stalled_with_leftovers {
461                match self_ref.upgrade() {
462                    Some(ctrl) if allow_fallback_respawn => ctrl.respawn_once_for_leftover_queue(retry_config),
463                    Some(ctrl) => ctrl.publish_status(),
464                    None => {
465                        // Nobody left to call back (e.g. a throwaway
466                        // instance that never called `set_self_ref`) — the
467                        // claim was deliberately kept held above pending
468                        // this hand-off, so it must still be released here
469                        // or no future caller could ever spawn again.
470                        claim.release(&mut inner_arc.lock().unwrap());
471                    }
472                }
473            }
474        });
475    }
476
477    /// Attempts exactly one fallback respawn when either call site above is
478    /// about to release its claim with messages still queued and nobody
479    /// left responsible for delivering them. Forces `session_id` empty so
480    /// this fallback spawn never attempts `--resume` — reusing a
481    /// possibly-still-stale session id here would risk repeating the exact
482    /// failure this whole retry mechanism exists to recover from. If THIS
483    /// spawn also fails, or its own process also dies before its own drain
484    /// completes, gives up and publishes a status update rather than
485    /// cascading indefinitely — the queue itself is never discarded (this
486    /// function never pops anything itself — it isn't tied to a specific
487    /// message the way the original spawn attempt was), so a genuinely
488    /// later, unrelated send will still eventually pick it up.
489    /// Atomically clears the ambient session id AND reserves a fresh
490    /// spawn generation, so every reader task belonging to any EXISTING
491    /// generation is stale from this point on. Used by both fresh-start
492    /// respawn paths (`respawn_once_for_leftover_queue`,
493    /// `retry_after_resume_failure`'s `BecomeSpawner` arm) in place of a
494    /// bare `session_id = None`.
495    ///
496    /// codex P1 on PR #2500 (second round): clearing alone left a window
497    /// — until `spawn_process`'s own generation bump, which happens AFTER
498    /// the `--resume` decision reads `session_id` and after the process
499    /// is spawned — where the dying generation still equaled
500    /// `spawn_generation`, so its stdout reader's stale-sid echo passed
501    /// `try_capture_session_id`'s currency gate (issue #2366) and was
502    /// re-adopted: the supposedly fresh spawn could reattach
503    /// `--resume <stale-sid>` with no retry payload armed to catch the
504    /// repeat failure. Reserving the next generation in the same lock
505    /// acquisition as the clear closes the whole window.
506    ///
507    /// The reserved generation is never itself spawned (`spawn_process`
508    /// bumps again) — see `spawn_generation`'s doc comment for why the
509    /// gap is inert. A `stop_process` racing into the reserve window
510    /// records a `StopRequested` for the never-spawned generation, which
511    /// the resume state machine ignores; both callers only reach this
512    /// point after the prior generation's tracking has already resolved,
513    /// so no stop-intent is lost that wasn't equally lost before.
514    pub(super) fn clear_session_id_for_fresh_spawn(&self) {
515        let mut inner = self.inner.lock().unwrap();
516        inner.spawn_generation += 1;
517        inner.session_id = None;
518    }
519
520    pub(super) fn respawn_once_for_leftover_queue(&self, mut config: PersistentSpawnConfig) {
521        config.session_id = String::new();
522        // reagentx P0 on PR #2360 (sixth review pass, round 11): clearing
523        // `config.session_id` alone does nothing — `spawn_process`'s own
524        // `--resume` decision reads `inner.session_id` directly (see its
525        // own doc comment), never `config.session_id` (that field is only
526        // consulted to HYDRATE `inner.session_id` when it's still `None`,
527        // which is skipped here anyway since it's now empty). If the
528        // doomed process's stderr reader hasn't cleared `inner.session_id`
529        // yet (poison_resume races the drain's own `tx.send()` failure —
530        // exactly the fast-fail case this whole mechanism targets), this
531        // fallback respawn would reattach `--resume <stale-sid>` and
532        // reproduce the identical failure — and since this call passes
533        // `resume_retry_payload: None`, nothing re-arms to catch the
534        // repeat, so the process-waiter finds no confirmed retry and
535        // silently drops the message for good. Mirrors
536        // `retry_after_resume_failure`'s own explicit clear for the exact
537        // same reason.
538        //
539        // A plain clear, deliberately NOT `poison_resume` — reagentx P1
540        // on PR #2360 (sixth review pass, round 13): a prior cut of this
541        // fix called `poison_resume` here to defensively close a narrower
542        // race (a still-racing stdout-reader task from the doomed process
543        // could re-capture the same sid right after a plain clear). That
544        // was a regression: `respawn_once_for_leftover_queue` is reached
545        // from TWO triggers that have nothing to do with a CONFIRMED
546        // stale `--resume` — `release_spawn_claim_and_drain_queue`'s
547        // `!spawn_succeeded` branch (ANY `spawn_process` failure — a
548        // missing binary, an OS error) and
549        // `drain_queue_after_successful_spawn`'s stall branch (ANY
550        // process exit/crash with messages still queued, not
551        // specifically a stale-resume death). In both, `inner.session_id`
552        // could just as easily be a legitimately hydrated-but-unattempted
553        // id, or a genuinely valid, already-captured session from a
554        // process that ran fine and crashed for an unrelated reason.
555        // `poison_resume` is documented as PERMANENT (`resume_poisoned` is
556        // "never reset back to None") — poisoning a sid never actually
557        // confirmed dead by the CLI permanently breaks conversation
558        // continuity for that session, with no disclosure, for the rest
559        // of this controller instance's lifetime. A plain clear only
560        // affects THIS respawn's own `--resume` decision (already forced
561        // empty via `config.session_id` above) and carries no such
562        // permanent, over-broad risk. The narrower race the poisoning was
563        // meant to close — a still-racing reader task from the doomed
564        // process re-capturing the same sid right after a plain clear —
565        // is now closed WITHOUT poisoning: the clear also reserves a
566        // fresh spawn generation, making every existing generation's
567        // capture stale to `try_capture_session_id`'s currency gate (see
568        // `clear_session_id_for_fresh_spawn`'s own doc comment).
569        // An adopted recovery candidate (`leftover_resume_candidate`, set by
570        // `settle_empty_resume_retry` when prompts were queued behind the
571        // eager claim — codex P1 on PR #3551, fifth round) is the ONE case
572        // this respawn does not start fresh: it resumes the candidate,
573        // through the same tracked `--resume` an eager resume gets, so a
574        // stale candidate cascades into the normal retry path rather than
575        // being trusted. The generation is still reserved here, exactly as
576        // the fresh clear does, so a late capture from the doomed process
577        // cannot overwrite the candidate before `spawn_process` reads it.
578        let candidate = {
579            let mut inner = self.inner.lock().unwrap();
580            let candidate = inner.leftover_resume_candidate.take();
581            if let Some(ref sid) = candidate {
582                inner.spawn_generation += 1;
583                inner.session_id = Some(sid.clone());
584            }
585            candidate
586        };
587        match candidate {
588            Some(sid) => config.session_id = sid,
589            None => self.clear_session_id_for_fresh_spawn(),
590        }
591        let retry_config = config.clone();
592        let spawn_result = self.spawn_process(config, None);
593        match &spawn_result {
594            Ok(_) => {
595                self.mark_turn_active_and_publish();
596                self.drain_queue_after_successful_spawn(retry_config, false);
597            }
598            Err(e) => {
599                tracing::error!(
600                    block_id = %self.block_id,
601                    error = %e,
602                    "fallback respawn for a leftover queue failed"
603                );
604                // A candidate respawn can be refused by the duplicate-session
605                // guard (codex P1 on PR #3551, sixth round). Taking the
606                // candidate above consumed the only marker, so leaving the
607                // prompts queued would let the NEXT send's generic failed-
608                // spawn handling call this function again — candidate-less,
609                // clearing to fresh — and deliver them to a blank
610                // conversation after all. Same answer as the eager path's
611                // refusal: release, discard, report which prompts and why.
612                if is_held_elsewhere_error(e) {
613                    self.settle_eager_spawn_failure(e, retry_config);
614                    // Same broadcast as the generic arm below (codex P2 on PR
615                    // #3554): the doomed eager process's exit path hands off
616                    // `FireRetry` and deliberately suppresses `PublishDone`,
617                    // so nothing else tells the pane it is no longer working
618                    // until the 20-second heartbeat does.
619                    self.publish_status();
620                    return;
621                }
622                self.inner.lock().unwrap().spawning_in_progress = false;
623                self.publish_status();
624            }
625        }
626    }
627
628    /// Send a user message to the running CLI process.
629    /// If the process isn't spawned yet, spawns it first.
630    /// Emit `agent-message-accepted` for a given message_id, if set.
631    /// Mirrors the subprocess controller's `emit_message_accepted` — signals the
632    /// frontend to promote the pending entry from queued to in-document.
633    pub(super) fn emit_message_accepted(&self, message_id: Option<&str>) {
634        let Some(id) = message_id else { return };
635        let Some(ref broker) = self.broker else { return };
636        super::super::publish_message_accepted(broker, &self.block_id, id);
637        tracing::info!(
638            block_id = %self.block_id,
639            message_id = %id,
640            "emitted agent-message-accepted"
641        );
642    }
643
644    /// Persists a formatted stdin JSON line to the blockfile + global zone
645    /// so `parseHistoryLines` can reconstruct the `user_message` node on
646    /// the next pane open. Published as an `echo: "stdin"` transcript event
647    /// (Phase 5a-3c): the pane already shows the message through the
648    /// `agent-message-accepted` path (UUID node), so it doesn't add a second
649    /// node, but its stream keeps no gap where this record sits.
650    pub(super) fn persist_message_to_blockfile(&self, json_str: &str, record: &RecordOrigin) {
651        let global_zone = crate::backend::transcript::append::resolve_global_output_zone(&self.mstore, &self.block_id);
652        // A line with inline image attachments is stored without the base64:
653        // its text still lists every image, and every reader of stored user
654        // lines expects string content.
655        let stored = crate::backend::attachments::prompt::persisted_line(json_str);
656        let line_with_newline = format!("{stored}\n");
657        // Two SQLite write transactions (the block's store and the host-global
658        // transcript store every instance writes to), each allowed to wait out
659        // a 5s busy timeout. The async callers (run_agent_turn, agent.send)
660        // reach this on a runtime worker; inline, that worker stops polling
661        // the I/O driver and srv stops answering sockets for the duration.
662        // Synchronous on purpose — messages must persist in delivery order.
663        crate::backend::blocking::off_async_worker(|| {
664            crate::backend::transcript::append::persist_user_line(
665                self.broker.as_deref(),
666                &self.block_id,
667                line_with_newline.as_bytes(),
668                self.filestore.as_ref(),
669                global_zone.as_deref(),
670                Some(record),
671            )
672        });
673    }
674
675    #[cfg(test)]
676    pub fn send_message(&self, message: String, config: PersistentSpawnConfig) -> Result<(), String> {
677        self.send_message_from(message, config, None, RecordOrigin::new(MessageOrigin::user()))
678    }
679
680    /// [`Self::send_message`], saying who the message is from, so the turn it
681    /// starts (or joins) carries that provenance (SPEC_AGENT_SELF_QUIT §6.3).
682    /// `None` = unknown, which never counts as the user.
683    pub fn send_message_from(
684        &self,
685        message: String,
686        config: PersistentSpawnConfig,
687        origin: Option<crate::backend::blockcontroller::health::TurnInput>,
688        record: RecordOrigin,
689    ) -> Result<(), String> {
690        self.send_message_with_images_from(message, Vec::new(), config, origin, record)
691    }
692
693    /// [`Self::send_message_from`] with Anthropic `image` content blocks
694    /// placed before the text (image attachments,
695    /// SPEC_AGENT_PANE_IMAGE_ATTACHMENTS_2026_09_26.md §6.6). With no images
696    /// the line is byte-for-byte what `send_message_from` always wrote.
697    /// Stored copies drop the images again — see
698    /// `persist_message_to_blockfile`.
699    pub fn send_message_with_images_from(
700        &self,
701        message: String,
702        images: Vec<serde_json::Value>,
703        config: PersistentSpawnConfig,
704        origin: Option<crate::backend::blockcontroller::health::TurnInput>,
705        record: RecordOrigin,
706    ) -> Result<(), String> {
707        // Pre-turn fence (SPEC_AGENT_SINGLE_LIVE_INSTANCE_2026_09_24 §4.3):
708        // a process that lost the agent to another instance starts no turn.
709        self.fence_check()?;
710        // Format as stream-json user message.
711        let json_str = crate::backend::attachments::prompt::claude_user_line(message, images);
712
713        let queued_origin = origin.clone();
714        let stored_record = record.clone();
715        let action = self.decide_send_action_from(&json_str, None, origin, record);
716        if matches!(action, SendAction::Queued | SendAction::BecomeSpawner { .. }) {
717            // Delivered when the process spawns: the turn it starts is this one's.
718            match queued_origin {
719                Some(o) => self.health_monitor.hint_next_turn(o),
720                None => self.health_monitor.hint_next_turn_unlabelled(),
721            }
722        }
723        match action {
724            // Nothing was written, queued or persisted, so the caller's own
725            // error handling is the whole story.
726            SendAction::Refused(e) => Err(e),
727            SendAction::Queued => {
728                // Persistence happens later, inside the drain, at the
729                // exact moment this message is actually delivered — see
730                // `drain_queue_after_successful_spawn`. codex P2 on PR
731                // #2360 (sixth review pass, round 5): persisting
732                // immediately here instead let whichever caller's
733                // synchronous code happened to run first persist first,
734                // even when queue position said a DIFFERENT message
735                // (already sitting there, from a caller further along in
736                // its own `BecomeSpawner` spawn_process call) is actually
737                // delivered first — producing a blockfile transcript that
738                // doesn't match delivery order.
739                self.emit_message_accepted(config.message_id.as_deref());
740                Ok(())
741            }
742            SendAction::DeliverDirect { was_active } => {
743                // spawn_process already marks a fresh process's first turn
744                // active (and starts its watchdog); for an already-running
745                // process (the common case — every turn after the first)
746                // this is the only place that re-marks the turn active,
747                // since the persistent process never exits between turns.
748                // Without this, `turn_active` would go stale after turn 1.
749                // The mark itself happened inside `decide_send_action` (see
750                // `SendAction::DeliverDirect`); this publishes it.
751                if !was_active {
752                    self.spawn_status_heartbeat();
753                }
754                self.publish_status();
755                // Persist only AFTER a successful send — reagentx P1 on PR
756                // #2360 (sixth review pass, round 5): `stdin_tx` can have
757                // gone `None` (process died) between `decide_send_action`'s
758                // check and this later lock re-acquisition, or `try_send`
759                // can fail with `Full` under load; persisting beforehand
760                // reproduces, for this path, the exact "persisted a
761                // never-delivered message" bug the immediately prior
762                // commit fixed for `BecomeSpawner`. Matches
763                // `send_user_message`'s existing (correct) ordering.
764                self.deliver_direct(&json_str, was_active)?;
765                self.persist_message_to_blockfile(&json_str, &stored_record);
766                self.emit_message_accepted(config.message_id.as_deref());
767                Ok(())
768            }
769            SendAction::BecomeSpawner { own_seq } => {
770                // `resume_retry_payload` is stashed SYNCHRONOUSLY inside
771                // spawn_process, before any background task exists —
772                // reagentx P1 on PR #2360: stashing it after spawn_process
773                // returned left a window where a process that dies fast
774                // enough lets the already-scheduled process-waiter task
775                // observe the exit and take() this payload as still
776                // `None`, silently losing the retry for the exact case it
777                // exists to catch. This is independent of, and still
778                // needed alongside, the spawn-claim/queue mechanism below:
779                // that mechanism only prevents a SECOND process from being
780                // spawned concurrently — it does nothing once THIS
781                // process is running and later dies from a stale
782                // `--resume`, which is what the retry payload is for.
783                let message_id = config.message_id.clone();
784                let retry_config = config.clone();
785                let spawn_result = self.spawn_process(
786                    config,
787                    Some(persistent_resume::QueuedRetryEntry { seq: own_seq, json: json_str }),
788                );
789                // Only emit "accepted" on success — codex P2 on PR #2360
790                // (sixth review pass, round 4): an earlier cut of this fix
791                // persisted unconditionally here, letting a rejected spawn
792                // (missing executable, bad launch config) leave a
793                // "user_message" line in the blockfile for a prompt that
794                // was NEVER actually delivered. Persistence itself now
795                // happens later, inside the drain, at the exact moment
796                // this message is actually delivered (round 5 — see
797                // `drain_queue_after_successful_spawn`) — which already
798                // only runs on a successful spawn, so the same guarantee
799                // holds without needing a persist call here at all.
800                if spawn_result.is_ok() {
801                    self.mark_turn_active_and_publish();
802                    self.emit_message_accepted(message_id.as_deref());
803                }
804                self.release_spawn_claim_and_drain_queue(spawn_result.is_ok(), retry_config, own_seq);
805                spawn_result
806            }
807        }
808    }
809}