From c0bd29f18405358cbb7c7ad4f7711ce96e96e593 Mon Sep 17 00:00:00 2001 From: Mo Rajabi Date: Mon, 23 Nov 2026 11:25:01 +0000 Subject: [PATCH 1/3] cli: hold input for harnesses that can't take it mid-turn acp agents advertise no steering and no native queue, yet v2 sent every message typed during a turn as a steer, so it failed with "could not take this". such input is now held in order, the sender is told it's queued, the run state counts it as queued, and each held message starts its own turn when the one before ends, whether it completed, failed or was stopped. pause keeps it until resume; a release or a lost session keeps it pending and offers it next time. /queue without a native queue does the same. steering harnesses are unchanged. --- cli/src/bridge/v2/faults.rs | 332 +++++++++++++++++++++++++++++++++++- cli/src/bridge/v2/work.rs | 164 +++++++++++++++++- 2 files changed, 487 insertions(+), 9 deletions(-) diff --git a/cli/src/bridge/v2/faults.rs b/cli/src/bridge/v2/faults.rs index 3bc659961..0d3e915d8 100644 --- a/cli/src/bridge/v2/faults.rs +++ b/cli/src/bridge/v2/faults.rs @@ -75,6 +75,50 @@ struct FakeSession { unknown_first: bool, /// Modes the work switched the session to, in order. modes: Mutex>, + /// A started turn stays live until the test ends it with [`finish`]. + turns: bool, + /// With `turns`: whether input can join a running turn. Without, the + /// session is scripted like ACP: no steering and no native queue. + steers: bool, + live: Mutex>, +} + +impl FakeSession { + /// A turn-tracking send, shaped like the ACP harness's. + fn send_turns(&self, n: usize, input: Input) -> Result { + let mut live = self.live.lock().unwrap(); + let disposition = match (&input.delivery, live.clone()) { + (Delivery::Turn, Some(active)) => return Err(SendError::Busy { active }), + (Delivery::Turn, None) => { + let turn = TurnId::new(format!("turn-{n}")).unwrap(); + *live = Some(turn.clone()); + InputDisposition::Started { turn } + } + (_, _) if !self.steers => { + return Err(SendError::Unavailable(Availability::unavailable( + "this agent cannot be steered mid-turn", + ))); + } + (Delivery::Steer { expected_turn, .. }, active) + if active.as_ref() != Some(expected_turn) => + { + return Err(SendError::TurnMismatch { active }); + } + (Delivery::Steer { expected_turn, .. }, _) => InputDisposition::Steered { + turn: expected_turn.clone(), + }, + (Delivery::Queue, _) => InputDisposition::Queued { entry: None }, + (Delivery::Passive, _) => InputDisposition::Absorbed, + }; + drop(live); + self.received.lock().unwrap().push(input.clone()); + Ok(InputReceipt { + input: input.id, + disposition, + native: serde_json::Value::Null, + acceptance: Default::default(), + }) + } } impl Session for FakeSession { @@ -86,7 +130,16 @@ impl Session for FakeSession { DeliveryKind::ALL .into_iter() .fold(AvailabilityMatrix::default(), |matrix, kind| { - matrix.with_delivery(kind, Availability::Supported) + let supported = + self.steers || matches!(kind, DeliveryKind::Turn | DeliveryKind::Passive); + matrix.with_delivery( + kind, + if supported { + Availability::Supported + } else { + Availability::unavailable("this agent cannot be steered mid-turn") + }, + ) }) } @@ -100,6 +153,9 @@ impl Session for FakeSession { if self.unknown_first && n == 0 { return Err(SendError::Unknown("the reply was lost".into())); } + if self.turns { + return self.send_turns(n, input); + } self.received.lock().unwrap().push(input.clone()); Ok(InputReceipt { input: input.id, @@ -120,7 +176,10 @@ impl Session for FakeSession { } fn live_work(&self) -> LiveWork { - LiveWork::default() + LiveWork { + turn: self.live.lock().unwrap().clone(), + ..LiveWork::default() + } } fn release<'a>(&'a self) -> HarnessFuture<'a, Released, OpError> { @@ -239,6 +298,14 @@ fn runtime(cleanup: &mut Cleanup, harness: Arc) -> Runtime { } fn fixture(unknown_first: bool) -> (Runtime, Arc, Cleanup) { + session_fixture(unknown_first, false, true) +} + +fn session_fixture( + unknown_first: bool, + turns: bool, + steers: bool, +) -> (Runtime, Arc, Cleanup) { let dir = std::env::temp_dir().join(format!("inline-v2-faults-{}", uuid::Uuid::new_v4())); std::fs::create_dir(&dir).unwrap(); let mut cleanup = Cleanup { dir, tasks: vec![] }; @@ -253,6 +320,9 @@ fn fixture(unknown_first: bool) -> (Runtime, Arc, Cleanup) { received: Mutex::new(Vec::new()), unknown_first, modes: Mutex::new(Vec::new()), + turns, + steers, + live: Mutex::new(None), }); let harness = Arc::new(FakeHarness { session, @@ -2324,3 +2394,261 @@ fn widget_call_text_is_bounded_and_single_line() { "This widget isn't connected to the agent here." ); } + +// --------------------------------------------------------------- +// Input held for a harness without mid-turn input (ACP) +// --------------------------------------------------------------- + +fn received_ids(harness: &FakeHarness) -> Vec { + harness + .session + .received + .lock() + .unwrap() + .iter() + .map(|input| input.id.to_string()) + .collect() +} + +/// Ends the running turn the way a harness reports it, consuming the input +/// that started it. +fn finish(harness: &FakeHarness, outcome: inline_agent_bridge::TurnOutcome) { + let turn = harness + .session + .live + .lock() + .unwrap() + .take() + .expect("a turn runs"); + let started = harness + .session + .received + .lock() + .unwrap() + .last() + .map(|input| input.id.clone()) + .expect("an input started it"); + harness.session.hub.emit(Event::Turn { + turn, + phase: inline_agent_bridge::harness::TurnPhase::Completed { + outcome, + inputs_consumed: vec![started], + error: None, + duration_ms: None, + }, + }); +} + +fn live(harness: &FakeHarness) -> bool { + harness.session.live.lock().unwrap().is_some() +} + +/// Without steering a message sent during a turn neither fails nor steers: +/// it waits, and starts the next turn once this one ends, however it ended. +#[tokio::test] +async fn without_steering_a_message_waits_for_the_turn_whatever_its_end() { + use inline_agent_bridge::TurnOutcome; + for outcome in [ + TurnOutcome::Completed, + TurnOutcome::Failed, + TurnOutcome::Interrupted, + TurnOutcome::ConnectionLost, + ] { + let (runtime, harness, mut cleanup) = session_fixture(false, true, false); + let tx = spawn_work(&runtime, &mut cleanup); + let (first, command) = input(&runtime, 200); + tx.send(command).await.unwrap(); + until(|| live(&harness)).await; + let (second, command) = input(&runtime, 201); + tx.send(command).await.unwrap(); + until(|| state(&runtime, &second) == Some(InputState::Pending)).await; + tokio::time::sleep(Duration::from_millis(50)).await; + assert_eq!( + received_ids(&harness), + std::slice::from_ref(&first), + "{outcome:?}: held" + ); + assert_eq!( + state(&runtime, &second), + Some(InputState::Pending), + "{outcome:?}: not failed" + ); + + finish(&harness, outcome); + until(|| received_ids(&harness).len() == 2).await; + assert_eq!( + received_ids(&harness), + [first, second.clone()], + "{outcome:?}" + ); + let delivered = harness.session.received.lock().unwrap()[1].clone(); + assert_eq!( + delivered.delivery, + Delivery::Turn, + "{outcome:?}: a turn of its own" + ); + assert_eq!(state(&runtime, &second), Some(InputState::Accepted)); + } +} + +/// Held messages go out one per turn, in the order they were sent, each +/// exactly once. +#[tokio::test] +async fn held_messages_run_one_turn_each_in_order() { + let (runtime, harness, mut cleanup) = session_fixture(false, true, false); + let tx = spawn_work(&runtime, &mut cleanup); + let mut ids = Vec::new(); + for message in 210..214 { + let (id, command) = input(&runtime, message); + tx.send(command).await.unwrap(); + if message == 210 { + until(|| live(&harness)).await; + } else { + until(|| state(&runtime, &id) == Some(InputState::Pending)).await; + } + ids.push(id); + } + assert_eq!(received_ids(&harness), ids[..1]); + for turn in 1..ids.len() { + finish(&harness, inline_agent_bridge::TurnOutcome::Completed); + until(|| received_ids(&harness).len() == turn + 1).await; + tokio::time::sleep(Duration::from_millis(30)).await; + assert_eq!(received_ids(&harness), ids[..=turn], "one turn at a time"); + } + finish(&harness, inline_agent_bridge::TurnOutcome::Completed); + tokio::time::sleep(Duration::from_millis(50)).await; + assert_eq!(received_ids(&harness), ids, "nothing runs twice"); + assert!(!live(&harness)); +} + +/// Pause keeps held input; resume runs it, still in order. +#[tokio::test] +async fn pause_keeps_held_input_until_resume() { + let (runtime, harness, mut cleanup) = session_fixture(false, true, false); + let tx = spawn_work(&runtime, &mut cleanup); + let (first, command) = input(&runtime, 220); + tx.send(command).await.unwrap(); + until(|| live(&harness)).await; + let (second, command) = input(&runtime, 221); + tx.send(command).await.unwrap(); + until(|| state(&runtime, &second) == Some(InputState::Pending)).await; + let (reply, toast) = oneshot::channel(); + tx.send(Command::Control { + control: Control::Pause, + actor: 1, + reply, + }) + .await + .unwrap(); + let _ = toast.await; + finish(&harness, inline_agent_bridge::TurnOutcome::Interrupted); + tokio::time::sleep(Duration::from_millis(80)).await; + assert_eq!( + received_ids(&harness), + std::slice::from_ref(&first), + "paused" + ); + let (reply, toast) = oneshot::channel(); + tx.send(Command::Control { + control: Control::Resume, + actor: 1, + reply, + }) + .await + .unwrap(); + let _ = toast.await; + until(|| received_ids(&harness).len() == 2).await; + assert_eq!(received_ids(&harness), [first, second]); +} + +/// `/queue` without a native queue waits like any other message, and +/// starts a turn of its own. +#[tokio::test] +async fn queue_without_a_native_queue_runs_after_the_turn() { + let (runtime, harness, mut cleanup) = session_fixture(false, true, false); + let tx = spawn_work(&runtime, &mut cleanup); + let (first, command) = input(&runtime, 230); + tx.send(command).await.unwrap(); + until(|| live(&harness)).await; + let (second, mut command) = input(&runtime, 231); + if let Command::Input { input, .. } = &mut command { + input.delivery = Delivery::Queue; + } + tx.send(command).await.unwrap(); + until(|| state(&runtime, &second) == Some(InputState::Pending)).await; + finish(&harness, inline_agent_bridge::TurnOutcome::Completed); + until(|| received_ids(&harness).len() == 2).await; + assert_eq!(received_ids(&harness), [first, second]); + assert_eq!( + harness.session.received.lock().unwrap()[1].delivery, + Delivery::Turn + ); +} + +/// A harness that steers still takes a message into the running turn. +#[tokio::test] +async fn a_steering_harness_still_steers_the_running_turn() { + let (runtime, harness, mut cleanup) = session_fixture(false, true, true); + let tx = spawn_work(&runtime, &mut cleanup); + let (_, command) = input(&runtime, 240); + tx.send(command).await.unwrap(); + until(|| live(&harness)).await; + let (second, command) = input(&runtime, 241); + tx.send(command).await.unwrap(); + until(|| received_ids(&harness).len() == 2).await; + let steered = harness.session.received.lock().unwrap()[1].clone(); + assert_eq!(steered.id.as_str(), second); + assert!(matches!(steered.delivery, Delivery::Steer { .. })); + assert_eq!(state(&runtime, &second), Some(InputState::Accepted)); +} + +/// An edited message that is waiting for the turn is still one message: +/// it runs once, and edits after it ran send nothing. +#[tokio::test] +async fn an_edited_held_message_runs_once() { + let (mut runtime, harness, mut cleanup) = session_fixture(false, true, false); + runtime.agent.names.remember(1, "Owner".into()).await; + let message = |message_id: i64, revision: i64, text: &str| MessageRecord { + chat_id: InlineId::new(9), + message_id: InlineId::new(message_id), + sender_id: InlineId::new(1), + timestamp: 1, + is_outgoing: false, + reply_to_message_id: None, + transaction: None, + content: inline_client::MessageContent::Text { text: text.into() }, + metadata: inline_client::MessageMetadata { + sender_is_bot: Some(false), + revision: Some(revision), + ..Default::default() + }, + }; + runtime.on_message(&message(250, 1, "start")).await.unwrap(); + until(|| live(&harness)).await; + let held = input_id(2, 9, 251, "direct"); + runtime + .on_message(&message(251, 1, "then this")) + .await + .unwrap(); + until(|| state(&runtime, &held) == Some(InputState::Pending)).await; + for revision in 2..5 { + runtime + .on_message(&message(251, revision, "then this, edited")) + .await + .unwrap(); + } + finish(&harness, inline_agent_bridge::TurnOutcome::Completed); + until(|| received_ids(&harness).len() == 2).await; + runtime + .on_message(&message(251, 5, "then this, edited again")) + .await + .unwrap(); + finish(&harness, inline_agent_bridge::TurnOutcome::Completed); + tokio::time::sleep(Duration::from_millis(80)).await; + assert_eq!( + received_ids(&harness), + [input_id(2, 9, 250, "direct"), held], + "each message runs once" + ); + cleanup.tasks.push(runtime.works.remove(&9).unwrap().task); +} diff --git a/cli/src/bridge/v2/work.rs b/cli/src/bridge/v2/work.rs index 1f180b7ac..d4ad2fc05 100644 --- a/cli/src/bridge/v2/work.rs +++ b/cli/src/bridge/v2/work.rs @@ -23,11 +23,11 @@ use inline_agent_bridge::group::{ }; use inline_agent_bridge::harness::ChatId; use inline_agent_bridge::harness::{ - Acceptance, Delivery, Event, EventStream, FieldAnswer, FieldId, FieldInput, HarnessDriver, - HeldBy, Input, InputDisposition, InputFact, InputId, InteractionId, InteractionResponse, Op, - OpError, OpKind, OpenError, OpenMode, OpenSpec, Origin, OutputMode, QuestionForm, QueueOp, - RunState, SendError, Session, SettingsChange, SteerPriority, TurnPhase, UsageUpdate, UserId, - WaitingOn, + Acceptance, Delivery, DeliveryKind, Event, EventStream, FieldAnswer, FieldId, FieldInput, + HarnessDriver, HeldBy, Input, InputDisposition, InputFact, InputId, InteractionId, + InteractionResponse, Op, OpError, OpKind, OpenError, OpenMode, OpenSpec, Origin, OutputMode, + QuestionForm, QueueOp, RunState, SendError, Session, SettingsChange, SteerPriority, TurnPhase, + UsageUpdate, UserId, WaitingOn, }; use inline_agent_bridge::{HostToolResult, MAX_SESSION_TITLE_CHARS, ProviderSessionId, TurnId}; use inline_client::{CreateReplyThreadRequest, FormFieldValue, FormValue, InlineClient, InlineId}; @@ -507,6 +507,7 @@ pub(crate) fn spawn( probe: None, inputs: HashMap::new(), retained: Vec::new(), + held: VecDeque::new(), removing: HashSet::new(), paused: false, stopping: false, @@ -657,6 +658,10 @@ struct Actor { inputs: HashMap, /// Inputs kept pending after a release, offered at the next acquisition. retained: Vec, + /// Input a harness without mid-turn input (ACP) cannot take while a turn + /// runs, oldest first. Each goes out as its own turn when the one before + /// ends, however it ended. + held: VecDeque, /// Inputs this bridge is taking out of the native queue. removing: HashSet, paused: bool, @@ -1646,6 +1651,7 @@ impl Actor { } }, HoldEffect::Lost => { + self.keep_held_pending().await; self.session = None; *self .catalog_session @@ -2077,9 +2083,25 @@ impl Actor { return; } let Some(session) = self.session.clone() else { + self.held.retain(|held| held != &pending.id); self.retained.push(pending); return; }; + // A harness that cannot take this mid-turn gets it when the turn + // ends, behind anything already waiting, so input runs in order. + let waits = if self.held.contains(&pending.id) { + self.held.front() != Some(&pending.id) || waits_for_turn(&session, &input.delivery) + } else { + !self.held.is_empty() || waits_for_turn(&session, &input.delivery) + }; + if waits { + self.hold_input(&pending.id, message_id, false).await; + if live_turn(&session).is_none() { + Box::pin(self.release_held()).await; + } + return; + } + self.held.retain(|held| held != &pending.id); // What the thread said since the agent last took input travels with // it as untrusted context, kept apart from the author's words. Every // harness and version keeps that apart; a separate passive message @@ -2127,7 +2149,15 @@ impl Actor { self.taken_reports .extend(reports.iter().map(|report| report.event_id.clone())); } - if !matches!(input.delivery, Delivery::Queue | Delivery::Passive) { + if !matches!(input.delivery, Delivery::Queue | Delivery::Passive) + || (input.delivery == Delivery::Queue + && !session + .availability() + .delivery(DeliveryKind::Queue) + .is_supported()) + { + // Without a native queue, queued input reaches here only once + // nothing runs, so it starts the next turn. input.delivery = match live_turn(&session) { Some(turn) => Delivery::Steer { expected_turn: turn, @@ -2164,6 +2194,16 @@ impl Actor { expected_turn: active.clone(), priority: SteerPriority::Next, }; + if !takes_mid_turn(&session, &input.delivery) { + // A turn started first: this waits for it, ahead of the rest, + // and keeps the context it already took. + self.return_reports(reports); + if let Some((kept, _, _)) = self.inputs.get_mut(&pending.id) { + kept.content = input.content.clone(); + } + self.hold_input(&pending.id, message_id, true).await; + return; + } result = session.send(input.clone()).await; } else if let Err(SendError::TurnMismatch { active: None }) = &result { input.delivery = Delivery::Turn; @@ -2259,6 +2299,84 @@ impl Actor { } } + /// Keeps input for after the running turn, in arrival order (`front` for + /// one that was next when a turn beat it). The sender hears once. + async fn hold_input(&mut self, id: &InputId, message_id: i64, front: bool) { + self.mark(id, InputState::Pending); + if self.held.contains(id) { + return; + } + if front { + self.held.push_front(id.clone()); + } else { + self.held.push_back(id.clone()); + } + self.reply( + message_id, + &format!( + "Queued: {} can't take messages mid-turn, so this runs after the current turn.", + self.agent.agent_name + ), + ) + .await; + self.report().await; + } + + /// Sends the oldest held input once nothing runs. Each starts its own + /// turn, so the rest wait for that one to end. Pause keeps them all. + async fn release_held(&mut self) { + while !self.paused { + let Some(id) = self.held.front().cloned() else { + return; + }; + if self + .session + .as_ref() + .is_some_and(|session| live_turn(session).is_some()) + { + return; + } + let Some(pending) = self.inputs.get(&id).map(|(_, pending, _)| pending.clone()) else { + self.held.pop_front(); + continue; + }; + self.event(HoldEvent::AcquireRequested { + input: Some(pending), + }) + .await; + if self.held.front() == Some(&id) { + // Waiting on the session, or held again. + if self.inputs.contains_key(&id) { + return; + } + self.held.pop_front(); + } + } + } + + /// The session went away with input still held: it stays pending in + /// Inline and is offered at the next acquisition, like input a release + /// kept. + async fn keep_held_pending(&mut self) { + let held: Vec = self + .held + .drain(..) + .filter_map(|id| self.inputs.get(&id).map(|(_, pending, _)| pending.clone())) + .collect(); + if held.is_empty() { + return; + } + for pending in &held { + self.mark(&pending.id, InputState::Pending); + } + self.notice(&format!( + "{} held message(s) stay pending in Inline; you'll be offered to run them next time.", + held.len() + )) + .await; + self.retained.extend(held); + } + async fn offer(&mut self, inputs: Vec) { for pending in inputs { let Some((_, _, message_id)) = self.inputs.get(&pending.id).cloned() else { @@ -2380,6 +2498,7 @@ impl Actor { } async fn released(&mut self, cause: ReleaseCause, receipts: &[ReleaseReceipt]) { + self.keep_held_pending().await; self.session = None; *self .catalog_session @@ -2810,6 +2929,13 @@ impl Actor { // --------------------------------------------------------------- async fn envelope(&mut self, envelope: inline_agent_bridge::harness::Envelope) { + let turn_ended = matches!( + &envelope.event, + Event::Turn { + phase: TurnPhase::Completed { .. }, + .. + } + ); log::debug!( target: "inline::bridge::v2", "chat={} seq={} event={}", @@ -2948,6 +3074,11 @@ impl Actor { } else { self.report().await; } + // Completed, failed or stopped: held input goes out now, after the + // turn's answer. + if turn_ended { + self.release_held().await; + } } /// Today's speak-gate checks ran out: the owner hears once, in the DM, @@ -3804,7 +3935,8 @@ impl Actor { _ => proto::AgentRunState::Idle, }; state.run_state = run_state as i32; - state.queued_count = self.live.queued.len() as u32; + // Input held for a harness without mid-turn input waits as a queue. + state.queued_count = (self.live.queued.len() + self.held.len()) as u32; let key = proto::AgentSessionState { revision: 0, updated_at: 0, @@ -3900,6 +4032,23 @@ fn live_turn(session: &Arc) -> Option { session.live_work().turn } +/// Whether the session can take this delivery while a turn runs. A direct +/// message joins the turn as a steer. +fn takes_mid_turn(session: &Arc, delivery: &Delivery) -> bool { + let kind = match delivery { + Delivery::Passive => return true, + Delivery::Queue => DeliveryKind::Queue, + Delivery::Turn | Delivery::Steer { .. } => DeliveryKind::SteerNext, + }; + session.availability().delivery(kind).is_supported() +} + +/// A turn runs and this harness cannot take the input into it or its queue +/// (ACP has neither), so the input waits for the turn to end. +fn waits_for_turn(session: &Arc, delivery: &Delivery) -> bool { + live_turn(session).is_some() && !takes_mid_turn(session, delivery) +} + /// The gate's JSON answer; anything unreadable is quiet. fn parse_verdict(text: &str) -> Result { let start = text @@ -4688,6 +4837,7 @@ pub(crate) mod recovery_tests { probe: None, inputs: HashMap::new(), retained: Vec::new(), + held: VecDeque::new(), removing: HashSet::new(), paused: false, stopping: false, From 82e072e046a5026785a43884e432e80d412d99dd Mon Sep 17 00:00:00 2001 From: Mo Rajabi Date: Mon, 23 Nov 2026 11:34:14 +0000 Subject: [PATCH 2/3] cli: hold typed input while an approval card waits while an approval, plan or question card waited, a message typed without replying to it went into the blocked turn, where the harness could not act on it, and the sender was not told. it is now held with a note pointing at the card, and goes in once the card is answered: after a "no", it reaches the agent as what to do differently. --- cli/src/bridge/v2/faults.rs | 12 +++ cli/src/bridge/v2/work.rs | 205 +++++++++++++++++++++++++++++++----- 2 files changed, 191 insertions(+), 26 deletions(-) diff --git a/cli/src/bridge/v2/faults.rs b/cli/src/bridge/v2/faults.rs index 0d3e915d8..e9f28aea0 100644 --- a/cli/src/bridge/v2/faults.rs +++ b/cli/src/bridge/v2/faults.rs @@ -2652,3 +2652,15 @@ async fn an_edited_held_message_runs_once() { ); cleanup.tasks.push(runtime.works.remove(&9).unwrap().task); } + +/// While an approval card waits, a typed message is held with a note, not +/// lost in the blocked turn; answering the card lets it in. +#[tokio::test] +async fn a_message_typed_while_a_card_waits_goes_in_once_it_is_answered() { + let (runtime, harness, _cleanup) = session_fixture(false, true, true); + let session = harness.session.clone(); + work::recovery_tests::input_waits_for_an_open_card(runtime.agent.clone(), move || { + session.received.lock().unwrap().clone() + }) + .await; +} diff --git a/cli/src/bridge/v2/work.rs b/cli/src/bridge/v2/work.rs index d4ad2fc05..fad2a6b4b 100644 --- a/cli/src/bridge/v2/work.rs +++ b/cli/src/bridge/v2/work.rs @@ -2087,18 +2087,23 @@ impl Actor { self.retained.push(pending); return; }; - // A harness that cannot take this mid-turn gets it when the turn - // ends, behind anything already waiting, so input runs in order. + // Input the harness cannot act on yet (a card waits on an answer, or + // a turn runs that it cannot join) goes out once that clears, behind + // anything already waiting, so input runs in order. let waits = if self.held.contains(&pending.id) { - self.held.front() != Some(&pending.id) || waits_for_turn(&session, &input.delivery) + self.held.front() != Some(&pending.id) || self.blocked(&session, &input.delivery) } else { - !self.held.is_empty() || waits_for_turn(&session, &input.delivery) + let newly = !self.held.is_empty() || self.blocked(&session, &input.delivery); + if newly { + self.hold_input(&pending.id, message_id, false).await; + // Held only behind others: the oldest may be free to go. + Box::pin(self.release_held()).await; + return; + } + false }; if waits { self.hold_input(&pending.id, message_id, false).await; - if live_turn(&session).is_none() { - Box::pin(self.release_held()).await; - } return; } self.held.retain(|held| held != &pending.id); @@ -2311,35 +2316,57 @@ impl Actor { } else { self.held.push_back(id.clone()); } - self.reply( - message_id, - &format!( + let text = if self.card_waiting() { + format!( + "Held: {} is waiting on your answer to the request above. This goes to it once you answer.", + self.agent.agent_name + ) + } else { + format!( "Queued: {} can't take messages mid-turn, so this runs after the current turn.", self.agent.agent_name - ), - ) - .await; + ) + }; + self.reply(message_id, &text).await; self.report().await; } - /// Sends the oldest held input once nothing runs. Each starts its own - /// turn, so the rest wait for that one to end. Pause keeps them all. + /// An approval, plan or question card waits on an answer: the harness + /// acts on nothing else until it has one. + fn card_waiting(&self) -> bool { + matches!( + self.waiting, + Some(( + proto::AgentWaitingReason::Approval | proto::AgentWaitingReason::Question, + card, + )) if self.cards.contains_key(&card) + ) + } + + /// Whether this input has to wait: for a card's answer, or for the + /// running turn when the harness cannot take it mid-turn. + fn blocked(&self, session: &Arc, delivery: &Delivery) -> bool { + (self.card_waiting() && matches!(delivery, Delivery::Turn | Delivery::Steer { .. })) + || waits_for_turn(session, delivery) + } + + /// Sends the oldest held input once nothing blocks it. Without mid-turn + /// input each starts its own turn, so the rest wait for that one to + /// end. Pause keeps them all. async fn release_held(&mut self) { while !self.paused { let Some(id) = self.held.front().cloned() else { return; }; - if self - .session - .as_ref() - .is_some_and(|session| live_turn(session).is_some()) - { - return; - } - let Some(pending) = self.inputs.get(&id).map(|(_, pending, _)| pending.clone()) else { + let Some((input, pending, _)) = self.inputs.get(&id).cloned() else { self.held.pop_front(); continue; }; + if let Some(session) = &self.session + && self.blocked(session, &input.delivery) + { + return; + } self.event(HoldEvent::AcquireRequested { input: Some(pending), }) @@ -2929,6 +2956,7 @@ impl Actor { // --------------------------------------------------------------- async fn envelope(&mut self, envelope: inline_agent_bridge::harness::Envelope) { + let card_was_waiting = self.card_waiting(); let turn_ended = matches!( &envelope.event, Event::Turn { @@ -3074,9 +3102,9 @@ impl Actor { } else { self.report().await; } - // Completed, failed or stopped: held input goes out now, after the - // turn's answer. - if turn_ended { + // The card was answered, or the turn completed, failed or stopped: + // held input goes out now, after the turn's answer. + if turn_ended || (card_was_waiting && !self.card_waiting()) { self.release_held().await; } } @@ -4882,6 +4910,131 @@ pub(crate) mod recovery_tests { } } + /// A message typed while an approval card waits is held with a note + /// pointing at the card, and steers the turn once the card is answered: + /// after a "No", it is what to do differently. + pub(crate) async fn input_waits_for_an_open_card( + agent: Arc, + sent: impl Fn() -> Vec, + ) { + use inline_agent_bridge::harness::{ + ApprovalSubject, ClosedBy, Decision, DecisionId, DecisionKind, Envelope, InputContent, + Interaction, InteractionKind, + }; + let input = |message: i64| { + let id = format!("card-input-{message}"); + agent.ledger.begin(&id, 9, message, 1).unwrap(); + let input = InputId::new(id).unwrap(); + Command::Input { + input: Box::new(Input { + id: input.clone(), + content: InputContent::text("typed meanwhile"), + origin: Origin::Owner { user: UserId(1) }, + delivery: Delivery::Turn, + }), + pending: PendingInput { + id: input, + sender: UserId(1), + required: Operation::StartWork, + }, + message_id: message, + answer_reply: false, + reply_to: None, + } + }; + let state = |id: &str| agent.ledger.get(id).unwrap().map(|record| record.state); + let ids = |inputs: Vec| -> Vec { + inputs.iter().map(|input| input.id.to_string()).collect() + }; + let mut work = actor(agent.clone()); + work.command(input(60)).await; + assert_eq!(ids(sent()), ["card-input-60"]); + let session = work.session.clone().expect("held"); + let envelope = |seq: u64, event: Event| Envelope { + session: session.key().clone(), + seq, + checkpoint: None, + at_ms: now_ms(), + event, + }; + // An approval card is up, as if Inline took it. + let deny = DecisionId::new("deny").unwrap(); + let interaction = InteractionId::new("approval-1").unwrap(); + work.renderer.apply(&envelope( + 1, + Event::Interaction(Interaction { + id: interaction.clone(), + turn: None, + item: None, + parent: None, + kind: InteractionKind::Approval { + subject: ApprovalSubject::Command { + command: "rm -rf build".to_owned(), + cwd: None, + reason: None, + network_host: None, + permissions: None, + }, + decisions: vec![Decision { + id: deny.clone(), + label: "No, and tell Claude what to do differently".to_owned(), + kind: DecisionKind::Decline, + description: None, + accepts_message: true, + native: serde_json::Value::Null, + }], + }, + native: serde_json::Value::Null, + }), + )); + work.card_by_interaction.insert(interaction.clone(), 70); + work.cards.insert( + 70, + Card { + chat: 9, + interaction: interaction.clone(), + approval: true, + form: None, + answered: Vec::new(), + }, + ); + work.waiting = Some((proto::AgentWaitingReason::Approval, 70)); + + work.command(input(61)).await; + assert_eq!(ids(sent()), ["card-input-60"], "held while the card waits"); + assert_eq!(state("card-input-61"), Some(InputState::Pending)); + + // Something else happening in the session leaves it held. + work.envelope(envelope( + 2, + Event::Usage { + usage: Default::default(), + }, + )) + .await; + assert_eq!(ids(sent()), ["card-input-60"]); + + work.envelope(envelope( + 3, + Event::InteractionClosed { + id: interaction, + by: ClosedBy::Inline { + user: UserId(1), + decision: Some(deny), + }, + }, + )) + .await; + let delivered = sent(); + assert_eq!(ids(delivered.clone()), ["card-input-60", "card-input-61"]); + assert!( + matches!(delivered[1].delivery, Delivery::Steer { .. }), + "into the running turn" + ); + assert!(work.held.is_empty()); + assert_eq!(state("card-input-61"), Some(InputState::Accepted)); + } + pub(crate) async fn plan_cards_supersede_unless_decided(agent: Arc) { use crate::bridge::v2::blocks::{self, plan_proposal}; let card = || { From a4fc1648a3eb78156b2191cc813d9d038d13e3f1 Mon Sep 17 00:00:00 2001 From: Mo Rajabi Date: Mon, 23 Nov 2026 14:25:16 +0000 Subject: [PATCH 3/3] cli: hold input only for cards the live session still waits on a card left by a session that crashed or was released held every later message, since nothing cleared it and no turn started. input now waits only for an open card whose interaction the current session still reports pending, so answering the newer of two cards keeps waiting for the older one. held input a release keeps is offered once, with one note, and a held message that loses a race to a turn isn't told twice. --- cli/src/bridge/v2/faults.rs | 44 +++- cli/src/bridge/v2/work.rs | 402 ++++++++++++++++++++++++------------ 2 files changed, 315 insertions(+), 131 deletions(-) diff --git a/cli/src/bridge/v2/faults.rs b/cli/src/bridge/v2/faults.rs index e9f28aea0..67639f663 100644 --- a/cli/src/bridge/v2/faults.rs +++ b/cli/src/bridge/v2/faults.rs @@ -81,6 +81,8 @@ struct FakeSession { /// session is scripted like ACP: no steering and no native queue. steers: bool, live: Mutex>, + /// Interactions the session waits on, as `live_work` reports them. + open: Mutex>, } impl FakeSession { @@ -178,6 +180,7 @@ impl Session for FakeSession { fn live_work(&self) -> LiveWork { LiveWork { turn: self.live.lock().unwrap().clone(), + interactions: self.open.lock().unwrap().clone(), ..LiveWork::default() } } @@ -323,6 +326,7 @@ fn session_fixture( turns, steers, live: Mutex::new(None), + open: Mutex::new(Vec::new()), }); let harness = Arc::new(FakeHarness { session, @@ -2653,14 +2657,46 @@ async fn an_edited_held_message_runs_once() { cleanup.tasks.push(runtime.works.remove(&9).unwrap().task); } +fn card_harness(harness: &Arc) -> work::recovery_tests::CardHarness { + let sent = harness.session.clone(); + let open = harness.session.clone(); + let end = harness.session.clone(); + work::recovery_tests::CardHarness { + sent: Box::new(move || sent.received.lock().unwrap().clone()), + open: Box::new(move |ids| *open.open.lock().unwrap() = ids), + end_turn: Box::new(move || *end.live.lock().unwrap() = None), + } +} + /// While an approval card waits, a typed message is held with a note, not /// lost in the blocked turn; answering the card lets it in. #[tokio::test] async fn a_message_typed_while_a_card_waits_goes_in_once_it_is_answered() { let (runtime, harness, _cleanup) = session_fixture(false, true, true); - let session = harness.session.clone(); - work::recovery_tests::input_waits_for_an_open_card(runtime.agent.clone(), move || { - session.received.lock().unwrap().clone() - }) + work::recovery_tests::input_waits_for_an_open_card( + runtime.agent.clone(), + card_harness(&harness), + ) + .await; +} + +/// With two cards up, answering the newer one still holds input for the +/// older one. +#[tokio::test] +async fn held_input_waits_for_every_open_card() { + let (runtime, harness, _cleanup) = session_fixture(false, true, true); + work::recovery_tests::input_waits_for_every_open_card( + runtime.agent.clone(), + card_harness(&harness), + ) .await; } + +/// A card left by a session that ended holds nothing in the next one, and +/// input it held is offered once. +#[tokio::test] +async fn a_card_from_an_ended_session_holds_no_input() { + let (runtime, harness, _cleanup) = session_fixture(false, true, true); + work::recovery_tests::stale_card_holds_nothing(runtime.agent.clone(), card_harness(&harness)) + .await; +} diff --git a/cli/src/bridge/v2/work.rs b/cli/src/bridge/v2/work.rs index fad2a6b4b..0c2957087 100644 --- a/cli/src/bridge/v2/work.rs +++ b/cli/src/bridge/v2/work.rs @@ -1631,15 +1631,16 @@ impl Actor { HoldEffect::PendingNotDelivered { inputs } => { for pending in &inputs { self.mark(&pending.id, InputState::Pending); + self.held.retain(|held| held != &pending.id); } - if !inputs.is_empty() { + // Held input the release already kept is counted once. + let kept = self.keep_pending(inputs); + if kept > 0 { self.notice(&format!( - "{} message(s) stay pending in Inline; you'll be offered to run them next time.", - inputs.len() + "{kept} message(s) stay pending in Inline; you'll be offered to run them next time." )) .await; } - self.retained.extend(inputs); None } HoldEffect::Fork { .. } => match self.fork_here().await { @@ -2084,7 +2085,7 @@ impl Actor { } let Some(session) = self.session.clone() else { self.held.retain(|held| held != &pending.id); - self.retained.push(pending); + self.keep_pending(vec![pending]); return; }; // Input the harness cannot act on yet (a card waits on an answer, or @@ -2095,7 +2096,7 @@ impl Actor { } else { let newly = !self.held.is_empty() || self.blocked(&session, &input.delivery); if newly { - self.hold_input(&pending.id, message_id, false).await; + self.hold_input(&pending.id, message_id, false, true).await; // Held only behind others: the oldest may be free to go. Box::pin(self.release_held()).await; return; @@ -2103,9 +2104,10 @@ impl Actor { false }; if waits { - self.hold_input(&pending.id, message_id, false).await; + self.hold_input(&pending.id, message_id, false, true).await; return; } + let was_held = self.held.contains(&pending.id); self.held.retain(|held| held != &pending.id); // What the thread said since the agent last took input travels with // it as untrusted context, kept apart from the author's words. Every @@ -2206,7 +2208,8 @@ impl Actor { if let Some((kept, _, _)) = self.inputs.get_mut(&pending.id) { kept.content = input.content.clone(); } - self.hold_input(&pending.id, message_id, true).await; + self.hold_input(&pending.id, message_id, true, !was_held) + .await; return; } result = session.send(input.clone()).await; @@ -2289,7 +2292,7 @@ impl Actor { } Err(SendError::HeldElsewhere(by)) => { self.mark(&pending.id, InputState::Pending); - self.retained.push(pending); + self.keep_pending(vec![pending]); Box::pin(self.event(HoldEvent::AcquireConflict { by })).await; } Err(error) => { @@ -2305,8 +2308,9 @@ impl Actor { } /// Keeps input for after the running turn, in arrival order (`front` for - /// one that was next when a turn beat it). The sender hears once. - async fn hold_input(&mut self, id: &InputId, message_id: i64, front: bool) { + /// one that was next when a turn beat it). The sender hears once: `note` + /// is false for input already told. + async fn hold_input(&mut self, id: &InputId, message_id: i64, front: bool, note: bool) { self.mark(id, InputState::Pending); if self.held.contains(id) { return; @@ -2316,6 +2320,10 @@ impl Actor { } else { self.held.push_back(id.clone()); } + if !note { + self.report().await; + return; + } let text = if self.card_waiting() { format!( "Held: {} is waiting on your answer to the request above. This goes to it once you answer.", @@ -2332,15 +2340,20 @@ impl Actor { } /// An approval, plan or question card waits on an answer: the harness - /// acts on nothing else until it has one. + /// acts on nothing else until it has one. Any open card counts, and only + /// while the session holding it still waits on it, so a card left by an + /// ended session never holds input. fn card_waiting(&self) -> bool { - matches!( - self.waiting, - Some(( - proto::AgentWaitingReason::Approval | proto::AgentWaitingReason::Question, - card, - )) if self.cards.contains_key(&card) - ) + let Some(session) = &self.session else { + return false; + }; + if self.cards.is_empty() { + return false; + } + let open = session.live_work().interactions; + self.cards + .values() + .any(|card| open.contains(&card.interaction)) } /// Whether this input has to wait: for a card's answer, or for the @@ -2396,12 +2409,30 @@ impl Actor { for pending in &held { self.mark(&pending.id, InputState::Pending); } - self.notice(&format!( - "{} held message(s) stay pending in Inline; you'll be offered to run them next time.", - held.len() - )) - .await; - self.retained.extend(held); + let kept = self.keep_pending(held); + if kept > 0 { + self.notice(&format!( + "{kept} held message(s) stay pending in Inline; you'll be offered to run them next time." + )) + .await; + } + } + + /// Keeps input to offer at the next acquisition, each once. Returns how + /// many were not kept already. + fn keep_pending(&mut self, inputs: Vec) -> usize { + let mut kept = 0; + for pending in inputs { + if !self + .retained + .iter() + .any(|retained| retained.id == pending.id) + { + self.retained.push(pending); + kept += 1; + } + } + kept } async fn offer(&mut self, inputs: Vec) { @@ -2956,13 +2987,12 @@ impl Actor { // --------------------------------------------------------------- async fn envelope(&mut self, envelope: inline_agent_bridge::harness::Envelope) { - let card_was_waiting = self.card_waiting(); - let turn_ended = matches!( + let unblocks = matches!( &envelope.event, Event::Turn { phase: TurnPhase::Completed { .. }, .. - } + } | Event::InteractionClosed { .. } ); log::debug!( target: "inline::bridge::v2", @@ -3102,9 +3132,9 @@ impl Actor { } else { self.report().await; } - // The card was answered, or the turn completed, failed or stopped: - // held input goes out now, after the turn's answer. - if turn_ended || (card_was_waiting && !self.card_waiting()) { + // A card was answered, or the turn completed, failed or stopped: + // held input goes out once nothing blocks it, after the turn's answer. + if unblocks && !self.held.is_empty() { self.release_held().await; } } @@ -4910,86 +4940,101 @@ pub(crate) mod recovery_tests { } } - /// A message typed while an approval card waits is held with a note - /// pointing at the card, and steers the turn once the card is answered: - /// after a "No", it is what to do differently. - pub(crate) async fn input_waits_for_an_open_card( - agent: Arc, - sent: impl Fn() -> Vec, - ) { - use inline_agent_bridge::harness::{ - ApprovalSubject, ClosedBy, Decision, DecisionId, DecisionKind, Envelope, InputContent, - Interaction, InteractionKind, - }; - let input = |message: i64| { - let id = format!("card-input-{message}"); - agent.ledger.begin(&id, 9, message, 1).unwrap(); - let input = InputId::new(id).unwrap(); - Command::Input { - input: Box::new(Input { - id: input.clone(), - content: InputContent::text("typed meanwhile"), - origin: Origin::Owner { user: UserId(1) }, - delivery: Delivery::Turn, - }), - pending: PendingInput { - id: input, - sender: UserId(1), - required: Operation::StartWork, - }, - message_id: message, - answer_reply: false, - reply_to: None, - } - }; - let state = |id: &str| agent.ledger.get(id).unwrap().map(|record| record.state); - let ids = |inputs: Vec| -> Vec { - inputs.iter().map(|input| input.id.to_string()).collect() - }; - let mut work = actor(agent.clone()); - work.command(input(60)).await; - assert_eq!(ids(sent()), ["card-input-60"]); - let session = work.session.clone().expect("held"); - let envelope = |seq: u64, event: Event| Envelope { - session: session.key().clone(), + /// The scripted session, seen from the work. + pub(crate) struct CardHarness { + /// Inputs the session took, in order. + pub(crate) sent: Box Vec>, + /// Sets the interactions the session waits on. + pub(crate) open: Box)>, + /// Ends the running turn without an event, as a crash does. + pub(crate) end_turn: Box, + } + + fn card_input(agent: &Agent, message: i64) -> Command { + let id = format!("card-input-{message}"); + agent.ledger.begin(&id, 9, message, 1).unwrap(); + let input = InputId::new(id).unwrap(); + Command::Input { + input: Box::new(Input { + id: input.clone(), + content: inline_agent_bridge::harness::InputContent::text("typed meanwhile"), + origin: Origin::Owner { user: UserId(1) }, + delivery: Delivery::Turn, + }), + pending: PendingInput { + id: input, + sender: UserId(1), + required: Operation::StartWork, + }, + message_id: message, + answer_reply: false, + reply_to: None, + } + } + + fn sent_ids(harness: &CardHarness) -> Vec { + (harness.sent)() + .iter() + .map(|input| input.id.to_string()) + .collect() + } + + fn input_state(agent: &Agent, id: &str) -> Option { + agent.ledger.get(id).unwrap().map(|record| record.state) + } + + fn envelope(work: &Actor, seq: u64, event: Event) -> inline_agent_bridge::harness::Envelope { + inline_agent_bridge::harness::Envelope { + session: work.session.as_ref().expect("held").key().clone(), seq, checkpoint: None, at_ms: now_ms(), event, + } + } + + /// Puts up an approval card as if Inline took it: rendered, posted as + /// `message_id`, and pending in the session. + fn open_card( + work: &mut Actor, + harness: &CardHarness, + id: &str, + message_id: i64, + ) -> InteractionId { + use inline_agent_bridge::harness::{ + ApprovalSubject, Decision, DecisionId, DecisionKind, Interaction, InteractionKind, }; - // An approval card is up, as if Inline took it. - let deny = DecisionId::new("deny").unwrap(); - let interaction = InteractionId::new("approval-1").unwrap(); - work.renderer.apply(&envelope( - 1, - Event::Interaction(Interaction { - id: interaction.clone(), - turn: None, - item: None, - parent: None, - kind: InteractionKind::Approval { - subject: ApprovalSubject::Command { - command: "rm -rf build".to_owned(), - cwd: None, - reason: None, - network_host: None, - permissions: None, - }, - decisions: vec![Decision { - id: deny.clone(), - label: "No, and tell Claude what to do differently".to_owned(), - kind: DecisionKind::Decline, - description: None, - accepts_message: true, - native: serde_json::Value::Null, - }], + let interaction = InteractionId::new(id).unwrap(); + let event = Event::Interaction(Interaction { + id: interaction.clone(), + turn: None, + item: None, + parent: None, + kind: InteractionKind::Approval { + subject: ApprovalSubject::Command { + command: "rm -rf build".to_owned(), + cwd: None, + reason: None, + network_host: None, + permissions: None, }, - native: serde_json::Value::Null, - }), - )); - work.card_by_interaction.insert(interaction.clone(), 70); + decisions: vec![Decision { + id: DecisionId::new("deny").unwrap(), + label: "No, and tell Claude what to do differently".to_owned(), + kind: DecisionKind::Decline, + description: None, + accepts_message: true, + native: serde_json::Value::Null, + }], + }, + native: serde_json::Value::Null, + }); + let applied = envelope(work, message_id as u64, event); + work.renderer.apply(&applied); + work.card_by_interaction + .insert(interaction.clone(), message_id); work.cards.insert( - 70, + message_id, Card { chat: 9, interaction: interaction.clone(), @@ -4998,41 +5043,144 @@ pub(crate) mod recovery_tests { answered: Vec::new(), }, ); - work.waiting = Some((proto::AgentWaitingReason::Approval, 70)); - - work.command(input(61)).await; - assert_eq!(ids(sent()), ["card-input-60"], "held while the card waits"); - assert_eq!(state("card-input-61"), Some(InputState::Pending)); - - // Something else happening in the session leaves it held. - work.envelope(envelope( - 2, - Event::Usage { - usage: Default::default(), - }, - )) - .await; - assert_eq!(ids(sent()), ["card-input-60"]); + work.waiting = Some((proto::AgentWaitingReason::Approval, message_id)); + let mut open = work.session.as_ref().unwrap().live_work().interactions; + open.push(interaction.clone()); + (harness.open)(open); + interaction + } - work.envelope(envelope( - 3, + /// The session answers a card: it stops waiting on it, then reports it + /// closed. + async fn close_card( + work: &mut Actor, + harness: &CardHarness, + interaction: InteractionId, + seq: u64, + ) { + use inline_agent_bridge::harness::{ClosedBy, DecisionId}; + let open = work + .session + .as_ref() + .unwrap() + .live_work() + .interactions + .into_iter() + .filter(|open| open != &interaction) + .collect(); + (harness.open)(open); + let closed = envelope( + work, + seq, Event::InteractionClosed { id: interaction, by: ClosedBy::Inline { user: UserId(1), - decision: Some(deny), + decision: Some(DecisionId::new("deny").unwrap()), }, }, - )) - .await; - let delivered = sent(); - assert_eq!(ids(delivered.clone()), ["card-input-60", "card-input-61"]); + ); + work.envelope(closed).await; + } + + /// A message typed while an approval card waits is held with a note + /// pointing at the card, and steers the turn once the card is answered: + /// after a "No", it is what to do differently. + pub(crate) async fn input_waits_for_an_open_card(agent: Arc, harness: CardHarness) { + let mut work = actor(agent.clone()); + work.command(card_input(&agent, 60)).await; + assert_eq!(sent_ids(&harness), ["card-input-60"]); + let card = open_card(&mut work, &harness, "approval-1", 70); + + work.command(card_input(&agent, 61)).await; + assert_eq!( + sent_ids(&harness), + ["card-input-60"], + "held while the card waits" + ); + assert_eq!( + input_state(&agent, "card-input-61"), + Some(InputState::Pending) + ); + + // Something else happening in the session leaves it held. + let usage = envelope( + &work, + 100, + Event::Usage { + usage: Default::default(), + }, + ); + work.envelope(usage).await; + assert_eq!(sent_ids(&harness), ["card-input-60"]); + + close_card(&mut work, &harness, card, 101).await; + let delivered = (harness.sent)(); + assert_eq!(sent_ids(&harness), ["card-input-60", "card-input-61"]); assert!( matches!(delivered[1].delivery, Delivery::Steer { .. }), "into the running turn" ); assert!(work.held.is_empty()); - assert_eq!(state("card-input-61"), Some(InputState::Accepted)); + assert_eq!( + input_state(&agent, "card-input-61"), + Some(InputState::Accepted) + ); + } + + /// Two cards up (parallel permission requests): answering the newer one + /// leaves input held until the older one is answered too. + pub(crate) async fn input_waits_for_every_open_card(agent: Arc, harness: CardHarness) { + let mut work = actor(agent.clone()); + work.command(card_input(&agent, 60)).await; + let older = open_card(&mut work, &harness, "approval-a", 70); + let newer = open_card(&mut work, &harness, "approval-b", 71); + work.command(card_input(&agent, 61)).await; + assert_eq!(sent_ids(&harness), ["card-input-60"]); + + close_card(&mut work, &harness, newer, 100).await; + assert_eq!( + sent_ids(&harness), + ["card-input-60"], + "the older card still waits" + ); + + close_card(&mut work, &harness, older, 101).await; + assert_eq!(sent_ids(&harness), ["card-input-60", "card-input-61"]); + } + + /// A session that ends with a card up (a crash, or a release) leaves the + /// card behind; the next session does not wait on it, so new input runs. + /// Input it was holding is kept pending, and offered once. + pub(crate) async fn stale_card_holds_nothing(agent: Arc, harness: CardHarness) { + let mut work = actor(agent.clone()); + work.command(card_input(&agent, 60)).await; + open_card(&mut work, &harness, "approval-1", 70); + work.command(card_input(&agent, 61)).await; + assert_eq!(work.held.len(), 1); + + // The process dies: no close event, no turn end. + (harness.open)(Vec::new()); + (harness.end_turn)(); + work.event(HoldEvent::Detached).await; + assert!(work.session.is_none()); + assert!(work.held.is_empty()); + assert_eq!(work.retained.len(), 1); + // The hold machine reporting it too keeps one offer. + let held = work.retained[0].clone(); + work.effect(HoldEffect::PendingNotDelivered { inputs: vec![held] }) + .await; + assert_eq!(work.retained.len(), 1, "offered once"); + + // The next message opens a fresh session and runs: the old card + // waits on nothing there. + work.command(card_input(&agent, 62)).await; + assert_eq!(sent_ids(&harness), ["card-input-60", "card-input-62"]); + assert_eq!( + (harness.sent)()[1].delivery, + Delivery::Turn, + "a turn of its own" + ); } pub(crate) async fn plan_cards_supersede_unless_decided(agent: Arc) {