use super::*;
use async_trait::async_trait;
use crossterm::event::{
KeyCode as CtKeyCode, KeyEvent, KeyEventState, KeyModifiers as CtKeyModifiers,
};
use ratatui::backend::TestBackend;
use std::sync::atomic::AtomicUsize;
use std::time::Instant;
use tokio::time::{self, Duration as TokioDuration};
#[derive(Default)]
struct CountingModel {
events_seen: usize,
quit: bool,
}
impl TuiModel for CountingModel {
fn should_quit(&self) -> bool {
self.quit
}
}
fn render_counts(f: &mut ratatui::Frame, model: &CountingModel) {
use ratatui::widgets::Paragraph;
f.render_widget(Paragraph::new(format!("{}", model.events_seen)), f.area());
}
struct NoopEngine;
#[async_trait]
impl TuiEngine for NoopEngine {
async fn handle_input(
&self,
_line: String,
_tx: UnboundedSender<ReplEvent>,
) -> anyhow::Result<bool> {
Ok(true)
}
async fn setup(&self, _tx: UnboundedSender<ReplEvent>) -> anyhow::Result<()> {
Ok(())
}
}
fn key_event(code: CtKeyCode, kind: KeyEventKind) -> KeyEvent {
KeyEvent {
code,
modifiers: CtKeyModifiers::NONE,
kind,
state: KeyEventState::NONE,
}
}
#[test]
fn classify_maps_key_press_and_repeat() {
let press = classify(CtEvent::Key(key_event(
CtKeyCode::Char('a'),
KeyEventKind::Press,
)));
assert!(matches!(press, Some(ReplEvent::Key(_))));
let repeat = classify(CtEvent::Key(key_event(
CtKeyCode::Char('a'),
KeyEventKind::Repeat,
)));
assert!(matches!(repeat, Some(ReplEvent::Key(_))));
}
#[test]
fn classify_filters_key_release() {
let release = classify(CtEvent::Key(key_event(
CtKeyCode::Char('a'),
KeyEventKind::Release,
)));
assert_eq!(
release, None,
"Release must not fire a second ReplEvent::Key"
);
}
#[test]
fn classify_maps_resize() {
assert_eq!(
classify(CtEvent::Resize(120, 40)),
Some(ReplEvent::Resize(120, 40))
);
}
#[test]
fn classify_maps_mouse_scroll_up_and_down() {
let up = classify(CtEvent::Mouse(MouseEvent {
kind: MouseEventKind::ScrollUp,
column: 0,
row: 0,
modifiers: CtKeyModifiers::NONE,
}));
assert_eq!(up, Some(ReplEvent::Scroll(-SCROLL_DELTA)));
let down = classify(CtEvent::Mouse(MouseEvent {
kind: MouseEventKind::ScrollDown,
column: 0,
row: 0,
modifiers: CtKeyModifiers::NONE,
}));
assert_eq!(down, Some(ReplEvent::Scroll(SCROLL_DELTA)));
}
#[test]
fn classify_ignores_other_mouse_events() {
let moved = classify(CtEvent::Mouse(MouseEvent {
kind: MouseEventKind::Moved,
column: 0,
row: 0,
modifiers: CtKeyModifiers::NONE,
}));
assert_eq!(moved, None);
}
#[test]
fn key_reader_guard_drop_completes_promptly_without_a_keypress() {
let (tx, _rx) = mpsc::unbounded_channel::<ReplEvent>();
let guard = spawn_key_reader(tx);
let start = Instant::now();
drop(guard);
let elapsed = start.elapsed();
assert!(
elapsed < Duration::from_secs(2),
"KeyReaderGuard::drop must not block on a keystroke; took {:?}",
elapsed
);
}
#[tokio::test]
async fn event_loop_applies_events_and_redraws() {
let backend = TestBackend::new(20, 5);
let mut terminal = Terminal::new(backend).expect("construct terminal");
let (tx, rx) = mpsc::unbounded_channel::<ReplEvent>();
tx.send(ReplEvent::StatusMessage("one".into())).unwrap();
tx.send(ReplEvent::StatusMessage("two".into())).unwrap();
drop(tx);
let model = event_loop(
&mut terminal,
CountingModel::default(),
rx,
|m, _ev| {
m.events_seen += 1;
},
render_counts,
)
.await
.expect("event_loop must succeed");
assert_eq!(model.events_seen, 2);
}
#[tokio::test]
async fn event_loop_stops_when_model_requests_quit() {
let backend = TestBackend::new(20, 5);
let mut terminal = Terminal::new(backend).expect("construct terminal");
let (tx, rx) = mpsc::unbounded_channel::<ReplEvent>();
for _ in 0..10 {
tx.send(ReplEvent::Cancel).unwrap();
}
let model = event_loop(
&mut terminal,
CountingModel::default(),
rx,
|m, _ev| {
m.events_seen += 1;
if m.events_seen == 1 {
m.quit = true;
}
},
render_counts,
)
.await
.expect("event_loop must succeed");
assert_eq!(
model.events_seen, 1,
"must stop at the first quit-triggering event"
);
}
#[tokio::test]
async fn event_loop_coalesces_a_burst_into_one_redraw() {
const BURST: usize = 50;
let backend = TestBackend::new(20, 5);
let mut terminal = Terminal::new(backend).expect("construct terminal");
let (tx, rx) = mpsc::unbounded_channel::<ReplEvent>();
for i in 0..BURST {
tx.send(ReplEvent::StatusMessage(format!("chunk {i}")))
.expect("queue the burst before the loop starts");
}
drop(tx);
let redraws = Arc::new(AtomicUsize::new(0));
let redraws_in_render = redraws.clone();
let model = event_loop(
&mut terminal,
CountingModel::default(),
rx,
|m, _ev| m.events_seen += 1,
move |f, m| {
redraws_in_render.fetch_add(1, Ordering::SeqCst);
render_counts(f, m);
},
)
.await
.expect("event_loop must succeed");
assert_eq!(
model.events_seen, BURST,
"coalescing must drop nothing — every event still reaches `apply`"
);
let drawn = redraws.load(Ordering::SeqCst);
assert!(
drawn < BURST,
"a burst of {BURST} events must not cost {BURST} frames; drew {drawn}"
);
}
#[tokio::test]
async fn event_loop_stops_draining_at_a_quit() {
let backend = TestBackend::new(20, 5);
let mut terminal = Terminal::new(backend).expect("construct terminal");
let (tx, rx) = mpsc::unbounded_channel::<ReplEvent>();
for _ in 0..10 {
tx.send(ReplEvent::StatusMessage("x".into())).unwrap();
}
let model = event_loop(
&mut terminal,
CountingModel::default(),
rx,
|m, _ev| {
m.events_seen += 1;
if m.events_seen == 3 {
m.quit = true;
}
},
render_counts,
)
.await
.expect("event_loop must succeed");
assert_eq!(
model.events_seen, 3,
"the drain must stop at the quit, not finish the backlog"
);
}
#[tokio::test]
async fn event_loop_stops_when_channel_closes() {
let backend = TestBackend::new(20, 5);
let mut terminal = Terminal::new(backend).expect("construct terminal");
let (tx, rx) = mpsc::unbounded_channel::<ReplEvent>();
drop(tx);
let model = event_loop(
&mut terminal,
CountingModel::default(),
rx,
|m, _ev| m.events_seen += 1,
render_counts,
)
.await
.expect("event_loop must succeed even with zero events");
assert_eq!(model.events_seen, 0);
assert!(!model.quit);
}
#[tokio::test(start_paused = true)]
async fn event_loop_redraws_on_tick_even_without_events() {
let backend = TestBackend::new(20, 5);
let mut terminal = Terminal::new(backend).expect("construct terminal");
let (tx, rx) = mpsc::unbounded_channel::<ReplEvent>();
let redraw_count = Arc::new(AtomicUsize::new(0));
let redraw_count_in_render = redraw_count.clone();
let handle = tokio::spawn(async move {
event_loop(
&mut terminal,
CountingModel::default(),
rx,
move |m, _ev| m.events_seen += 1,
move |f, m| {
redraw_count_in_render.fetch_add(1, Ordering::SeqCst);
render_counts(f, m);
},
)
.await
});
time::sleep(TokioDuration::from_millis(1)).await;
for _ in 0..3 {
time::advance(TICK).await;
}
time::advance(TICK).await;
drop(tx);
let _model = handle
.await
.expect("task must not panic")
.expect("loop must succeed");
assert!(
redraw_count.load(Ordering::SeqCst) >= 4,
"expected at least 4 redraws (1 initial + 3 ticks), got {}",
redraw_count.load(Ordering::SeqCst)
);
}
#[allow(dead_code)]
async fn run_type_checks(engine: Arc<NoopEngine>) -> anyhow::Result<()> {
run(
engine,
CountingModel::default(),
|m: &mut CountingModel, _ev| m.events_seen += 1,
render_counts,
)
.await
}
use crate::app::{ChatRole, ReplApp, apply as app_apply};
use crate::event::{KeyCode, KeyInput, KeyModifiers};
use crate::model::CancelReply;
use std::sync::atomic::AtomicU64;
use tokio::sync::Notify;
#[derive(Default)]
struct MockEngine {
cancel_calls: AtomicUsize,
handle_input_calls: AtomicUsize,
handle_input_returns_quit: AtomicBool,
hold_until: Option<Arc<Notify>>,
chunk_sent: AtomicBool,
completed: AtomicBool,
send_status_only: AtomicBool,
returns_err: AtomicBool,
permission_answers: StdMutex<Vec<(String, crate::model::PermissionAnswer)>>,
respond_permission_returns_err: AtomicBool,
hold_cancel_until: Option<Arc<Notify>>,
cancel_dispatched: AtomicBool,
cancel_reply: StdMutex<Option<CancelReply>>,
}
#[async_trait]
impl TuiEngine for MockEngine {
async fn handle_input(
&self,
_line: String,
tx: UnboundedSender<ReplEvent>,
) -> anyhow::Result<bool> {
self.handle_input_calls.fetch_add(1, Ordering::SeqCst);
if let Some(notify) = &self.hold_until {
let _ = tx.send(ReplEvent::AssistantOutput {
chunk: "partial".to_string(),
done: false,
is_error: false,
});
self.chunk_sent.store(true, Ordering::SeqCst);
notify.notified().await;
self.completed.store(true, Ordering::SeqCst);
}
if self.returns_err.load(Ordering::SeqCst) {
return Err(anyhow::anyhow!("mock engine failure"));
}
if self.send_status_only.load(Ordering::SeqCst) {
let _ = tx.send(ReplEvent::StatusMessage("workstreams: a, b, c".to_string()));
}
Ok(!self.handle_input_returns_quit.load(Ordering::SeqCst))
}
async fn setup(&self, _tx: UnboundedSender<ReplEvent>) -> anyhow::Result<()> {
Ok(())
}
async fn cancel_session_reply(&self) -> CancelReply {
self.cancel_calls.fetch_add(1, Ordering::SeqCst);
if let Some(notify) = &self.hold_cancel_until {
self.cancel_dispatched.store(true, Ordering::SeqCst);
notify.notified().await;
}
self.cancel_reply
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
.unwrap_or(CancelReply::Stopped)
}
async fn respond_permission(
&self,
request_id: String,
answer: crate::model::PermissionAnswer,
) -> anyhow::Result<()> {
self.permission_answers
.lock()
.unwrap_or_else(|e| e.into_inner())
.push((request_id, answer));
if self.respond_permission_returns_err.load(Ordering::SeqCst) {
return Err(anyhow::anyhow!("mock respond_permission failure"));
}
Ok(())
}
}
fn new_generation() -> Generation {
Arc::new(AtomicU64::new(0))
}
fn ctrl_c() -> ReplEvent {
ReplEvent::Key(KeyInput {
code: KeyCode::Char('c'),
modifiers: KeyModifiers {
ctrl: true,
alt: false,
shift: false,
},
})
}
#[tokio::test]
async fn dispatch_pending_cancel_reaches_cancel_session_reply() {
let engine = Arc::new(MockEngine::default());
let mut app = ReplApp::new("demo", "u");
app.busy = true;
app_apply(&mut app, ctrl_c());
assert!(app.pending_cancel, "reducer must stage pending_cancel");
let (tx, _rx) = mpsc::unbounded_channel::<ReplEvent>();
let current_task: CurrentTask = Arc::new(StdMutex::new(None));
let generation = new_generation();
dispatch_pending(&mut app, &engine, &tx, ¤t_task, &generation);
assert!(!app.pending_cancel, "must be drained synchronously");
assert!(
app.cancelling,
"the request must enter the cancelling state"
);
assert!(app.busy, "input stays closed until the cancel is confirmed");
for _ in 0..200 {
if engine.cancel_calls.load(Ordering::SeqCst) > 0 {
break;
}
tokio::task::yield_now().await;
}
assert_eq!(
engine.cancel_calls.load(Ordering::SeqCst),
1,
"Ctrl-C must reach engine.cancel_session_reply() exactly once"
);
}
async fn dispatch_cancel(
app: &mut ReplApp,
engine: &Arc<MockEngine>,
tx: &UnboundedSender<ReplEvent>,
current_task: &CurrentTask,
generation: &Generation,
) {
app_apply(app, ctrl_c());
dispatch_pending(app, engine, tx, current_task, generation);
for _ in 0..500 {
if engine.cancel_dispatched.load(Ordering::SeqCst) {
break;
}
tokio::task::yield_now().await;
}
assert!(
engine.cancel_dispatched.load(Ordering::SeqCst),
"the cancel RPC must be in flight, or this test proves nothing"
);
}
async fn next_event(app: &mut ReplApp, rx: &mut UnboundedReceiver<ReplEvent>) -> ReplEvent {
for _ in 0..500 {
if let Ok(ev) = rx.try_recv() {
app_apply(app, ev.clone());
return ev;
}
tokio::task::yield_now().await;
}
panic!("no event reached the render loop");
}
fn scrollback(app: &ReplApp) -> String {
app.chat
.iter()
.map(|l| l.text.as_str())
.collect::<Vec<_>>()
.join("\n")
}
#[tokio::test]
async fn dispatch_pending_cancel_holds_input_until_the_reply_lands() {
let notify = Arc::new(Notify::new());
let engine = Arc::new(MockEngine {
hold_cancel_until: Some(Arc::clone(¬ify)),
..Default::default()
});
let mut app = ReplApp::new("demo", "u");
app.busy = true;
let (tx, mut rx) = mpsc::unbounded_channel::<ReplEvent>();
let current_task: CurrentTask = Arc::new(StdMutex::new(None));
let generation = new_generation();
dispatch_cancel(&mut app, &engine, &tx, ¤t_task, &generation).await;
assert!(
!app.accepts_submit(),
"input must stay closed while the cancel is unconfirmed"
);
let text = scrollback(&app);
assert!(text.contains("cancelling"), "{text}");
assert!(
!text.contains("cancelled"),
"nothing may claim the run stopped before the reply: {text}"
);
app_apply(&mut app, ReplEvent::Submit("q".to_string()));
dispatch_pending(&mut app, &engine, &tx, ¤t_task, &generation);
for _ in 0..200 {
tokio::task::yield_now().await;
}
assert_eq!(
engine.handle_input_calls.load(Ordering::SeqCst),
0,
"a prompt submitted inside the cancel window must never reach the engine"
);
notify.notify_one();
let ev = next_event(&mut app, &mut rx).await;
assert_eq!(ev, ReplEvent::CancelSettled(CancelReply::Stopped));
assert!(app.accepts_submit(), "a confirmed stop reopens input");
assert!(scrollback(&app).contains("cancelled"));
}
#[tokio::test]
async fn dispatch_pending_cancel_still_cancelling_keeps_input_closed() {
let engine = Arc::new(MockEngine {
hold_cancel_until: Some(Arc::new(Notify::new())),
cancel_reply: StdMutex::new(Some(CancelReply::StillCancelling {
detail: "session s-1: cancellation requested but the task did not stop within 10s"
.to_string(),
})),
..Default::default()
});
let mut app = ReplApp::new("demo", "u");
app.busy = true;
let (tx, mut rx) = mpsc::unbounded_channel::<ReplEvent>();
let current_task: CurrentTask = Arc::new(StdMutex::new(None));
let generation = new_generation();
dispatch_cancel(&mut app, &engine, &tx, ¤t_task, &generation).await;
if let Some(notify) = &engine.hold_cancel_until {
notify.notify_one();
}
next_event(&mut app, &mut rx).await;
assert!(
!app.accepts_submit(),
"an unconfirmed cancel must not reopen input"
);
let text = scrollback(&app);
assert!(text.contains("still cancelling"), "{text}");
assert!(!text.contains("cancelled"), "{text}");
assert!(!text.contains("-32010"), "{text}");
}
#[tokio::test]
async fn dispatch_pending_cancel_failure_never_reports_cancelled() {
let engine = Arc::new(MockEngine {
hold_cancel_until: Some(Arc::new(Notify::new())),
cancel_reply: StdMutex::new(Some(CancelReply::Failed {
error: "no tcode daemon is answering on /tmp/tcode.sock".to_string(),
})),
..Default::default()
});
let mut app = ReplApp::new("demo", "u");
app.busy = true;
let (tx, mut rx) = mpsc::unbounded_channel::<ReplEvent>();
let current_task: CurrentTask = Arc::new(StdMutex::new(None));
let generation = new_generation();
dispatch_cancel(&mut app, &engine, &tx, ¤t_task, &generation).await;
if let Some(notify) = &engine.hold_cancel_until {
notify.notify_one();
}
next_event(&mut app, &mut rx).await;
assert!(!app.cancelling, "the pane must not stay cancelling forever");
let text = scrollback(&app);
assert!(text.contains("cancel failed"), "{text}");
assert!(
!text.contains("cancelled"),
"no failure arm may report cancelled: {text}"
);
}
#[tokio::test]
async fn dispatch_pending_permission_answer_reaches_respond_permission() {
let engine = Arc::new(MockEngine::default());
let mut app = ReplApp::new("demo", "u");
app_apply(
&mut app,
ReplEvent::PermissionRequested {
request_id: "req-1".to_string(),
agent: "python-engineer".to_string(),
agent_id: "spawn-1".to_string(),
tool: "bash".to_string(),
subject: "rm -rf build".to_string(),
rule: "bash[rm *]".to_string(),
},
);
app_apply(
&mut app,
ReplEvent::Key(KeyInput {
code: KeyCode::Char('a'),
modifiers: KeyModifiers::default(),
}),
);
assert!(
app.pending_permission_response.is_some(),
"reducer must stage the answer"
);
let (tx, _rx) = mpsc::unbounded_channel::<ReplEvent>();
let current_task: CurrentTask = Arc::new(StdMutex::new(None));
let generation = new_generation();
dispatch_pending(&mut app, &engine, &tx, ¤t_task, &generation);
assert!(
app.pending_permission_response.is_none(),
"must be drained synchronously"
);
assert_eq!(
generation.load(Ordering::SeqCst),
0,
"an answer releases a held call; it starts no turn"
);
for _ in 0..200 {
if !engine
.permission_answers
.lock()
.unwrap_or_else(|e| e.into_inner())
.is_empty()
{
break;
}
tokio::task::yield_now().await;
}
let answers = engine
.permission_answers
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
assert_eq!(
answers,
vec![(
"req-1".to_string(),
crate::model::PermissionAnswer::AllowForSession { pattern: None }
)],
"the answer must reach the engine verbatim, exactly once"
);
}
#[tokio::test]
async fn dispatch_pending_permission_answer_failure_reopens_the_prompt() {
let engine = Arc::new(MockEngine::default());
engine
.respond_permission_returns_err
.store(true, Ordering::SeqCst);
let mut app = ReplApp::new("demo", "u");
app_apply(
&mut app,
ReplEvent::PermissionRequested {
request_id: "req-1".to_string(),
agent: "python-engineer".to_string(),
agent_id: "spawn-1".to_string(),
tool: "bash".to_string(),
subject: "rm -rf build".to_string(),
rule: "bash[rm *]".to_string(),
},
);
app_apply(
&mut app,
ReplEvent::Key(KeyInput {
code: KeyCode::Char('y'),
modifiers: KeyModifiers::default(),
}),
);
assert!(
app.pending_permission.is_none(),
"answering closes the prompt optimistically"
);
let (tx, mut rx) = mpsc::unbounded_channel::<ReplEvent>();
let current_task: CurrentTask = Arc::new(StdMutex::new(None));
let generation = new_generation();
dispatch_pending(&mut app, &engine, &tx, ¤t_task, &generation);
let mut published = None;
for _ in 0..200 {
if let Ok(ev) = rx.try_recv() {
published = Some(ev);
break;
}
tokio::task::yield_now().await;
}
let published = published.expect("a failed respond_permission must publish an event");
app_apply(&mut app, published);
assert_eq!(
app.pending_permission
.as_ref()
.expect("the prompt must reopen so the answer can be retried")
.request_id,
"req-1",
"the reopened prompt must be the one that failed to send"
);
let transcript = app
.chat
.iter()
.map(|l| l.text.as_str())
.collect::<Vec<_>>()
.join("\n");
assert!(
transcript.contains("mock respond_permission failure"),
"the status line must name the failure: {transcript}"
);
}
#[tokio::test]
async fn dispatch_pending_submit_reaches_handle_input() {
let engine = Arc::new(MockEngine::default());
let mut app = ReplApp::new("demo", "u");
app_apply(&mut app, ReplEvent::Submit("hello".to_string()));
assert_eq!(app.pending_submit.as_deref(), Some("hello"));
let (tx, _rx) = mpsc::unbounded_channel::<ReplEvent>();
let current_task: CurrentTask = Arc::new(StdMutex::new(None));
let generation = new_generation();
dispatch_pending(&mut app, &engine, &tx, ¤t_task, &generation);
assert!(
app.pending_submit.is_none(),
"must be drained synchronously"
);
for _ in 0..200 {
if engine.handle_input_calls.load(Ordering::SeqCst) > 0 {
break;
}
tokio::task::yield_now().await;
}
assert_eq!(engine.handle_input_calls.load(Ordering::SeqCst), 1);
}
#[tokio::test]
async fn dispatch_pending_submit_ok_false_relays_quit_event() {
let engine = Arc::new(MockEngine::default());
engine
.handle_input_returns_quit
.store(true, Ordering::SeqCst);
let mut app = ReplApp::new("demo", "u");
app_apply(&mut app, ReplEvent::Submit("bye".to_string()));
let (tx, mut rx) = mpsc::unbounded_channel::<ReplEvent>();
let current_task: CurrentTask = Arc::new(StdMutex::new(None));
let generation = new_generation();
dispatch_pending(&mut app, &engine, &tx, ¤t_task, &generation);
let ev = rx.recv().await.expect("Quit event must be sent");
assert_eq!(ev, ReplEvent::Quit);
}
#[tokio::test]
async fn dispatch_pending_cancel_aborts_genuinely_in_flight_submit_task() {
let notify = Arc::new(Notify::new());
let engine = Arc::new(MockEngine {
hold_until: Some(Arc::clone(¬ify)),
..Default::default()
});
let mut app = ReplApp::new("demo", "u");
let (tx, _rx) = mpsc::unbounded_channel::<ReplEvent>();
let current_task: CurrentTask = Arc::new(StdMutex::new(None));
let generation = new_generation();
app_apply(&mut app, ReplEvent::Submit("long task".to_string()));
dispatch_pending(&mut app, &engine, &tx, ¤t_task, &generation);
assert!(
current_task.lock().unwrap().is_some(),
"submit must stash a JoinHandle in current_task"
);
for _ in 0..500 {
if engine.chunk_sent.load(Ordering::SeqCst) {
break;
}
tokio::task::yield_now().await;
}
assert!(
engine.chunk_sent.load(Ordering::SeqCst),
"task must reach its await point before we cancel it, or this test proves nothing"
);
app.busy = true;
app_apply(&mut app, ctrl_c());
dispatch_pending(&mut app, &engine, &tx, ¤t_task, &generation);
assert!(
current_task.lock().unwrap().is_none(),
"cancel must take (and abort) the stashed handle"
);
assert!(
app.cancelling,
"the request must enter the cancelling state"
);
notify.notify_one();
for _ in 0..500 {
tokio::task::yield_now().await;
}
assert!(
!engine.completed.load(Ordering::SeqCst),
"an aborted task must never resume past its await point, even when its wait condition is satisfied afterward"
);
}
#[tokio::test]
async fn dispatch_pending_noop_when_nothing_pending() {
let engine = Arc::new(MockEngine::default());
let mut app = ReplApp::new("demo", "u");
app_apply(
&mut app,
ReplEvent::Key(KeyInput {
code: KeyCode::Char('h'),
modifiers: KeyModifiers::default(),
}),
);
let (tx, _rx) = mpsc::unbounded_channel::<ReplEvent>();
let current_task: CurrentTask = Arc::new(StdMutex::new(None));
let generation = new_generation();
dispatch_pending(&mut app, &engine, &tx, ¤t_task, &generation);
tokio::task::yield_now().await;
assert_eq!(engine.cancel_calls.load(Ordering::SeqCst), 0);
assert_eq!(engine.handle_input_calls.load(Ordering::SeqCst), 0);
}
#[tokio::test]
async fn forward_while_current_generation_drops_stale_generation_message() {
let (turn_tx, turn_rx) = mpsc::unbounded_channel::<ReplEvent>();
let (real_tx, mut real_rx) = mpsc::unbounded_channel::<ReplEvent>();
let generation: Generation = Arc::new(AtomicU64::new(5));
turn_tx
.send(ReplEvent::AssistantOutput {
chunk: "partial".to_string(),
done: false,
is_error: false,
})
.unwrap();
generation.store(6, Ordering::SeqCst);
drop(turn_tx);
forward_while_current_generation(turn_rx, real_tx, generation, 5, no_terminal_flag()).await;
assert!(
real_rx.try_recv().is_err(),
"a message tagged for a superseded generation must never reach the real channel"
);
}
#[tokio::test]
async fn forward_while_current_generation_forwards_matching_generation_message() {
let (turn_tx, turn_rx) = mpsc::unbounded_channel::<ReplEvent>();
let (real_tx, mut real_rx) = mpsc::unbounded_channel::<ReplEvent>();
let generation: Generation = Arc::new(AtomicU64::new(1));
turn_tx
.send(ReplEvent::AssistantOutput {
chunk: "hello".to_string(),
done: true,
is_error: false,
})
.unwrap();
drop(turn_tx);
forward_while_current_generation(turn_rx, real_tx, generation, 1, no_terminal_flag()).await;
let ev = real_rx
.try_recv()
.expect("matching-generation message must forward");
assert_eq!(
ev,
ReplEvent::AssistantOutput {
chunk: "hello".to_string(),
done: true,
is_error: false,
}
);
}
fn no_terminal_flag() -> Arc<AtomicBool> {
Arc::new(AtomicBool::new(false))
}
#[tokio::test]
async fn forward_while_current_generation_flags_terminal_assistant_output() {
let (turn_tx, turn_rx) = mpsc::unbounded_channel::<ReplEvent>();
let (real_tx, _real_rx) = mpsc::unbounded_channel::<ReplEvent>();
let generation: Generation = Arc::new(AtomicU64::new(1));
let saw_terminal = Arc::new(AtomicBool::new(false));
turn_tx
.send(ReplEvent::AssistantOutput {
chunk: "done".to_string(),
done: true,
is_error: false,
})
.unwrap();
drop(turn_tx);
forward_while_current_generation(turn_rx, real_tx, generation, 1, Arc::clone(&saw_terminal))
.await;
assert!(saw_terminal.load(Ordering::SeqCst));
}
#[tokio::test]
async fn forward_while_current_generation_flags_quit() {
let (turn_tx, turn_rx) = mpsc::unbounded_channel::<ReplEvent>();
let (real_tx, _real_rx) = mpsc::unbounded_channel::<ReplEvent>();
let generation: Generation = Arc::new(AtomicU64::new(1));
let saw_terminal = Arc::new(AtomicBool::new(false));
turn_tx.send(ReplEvent::Quit).unwrap();
drop(turn_tx);
forward_while_current_generation(turn_rx, real_tx, generation, 1, Arc::clone(&saw_terminal))
.await;
assert!(saw_terminal.load(Ordering::SeqCst));
}
#[tokio::test]
async fn forward_while_current_generation_does_not_flag_non_terminal_events() {
let (turn_tx, turn_rx) = mpsc::unbounded_channel::<ReplEvent>();
let (real_tx, mut real_rx) = mpsc::unbounded_channel::<ReplEvent>();
let generation: Generation = Arc::new(AtomicU64::new(1));
let saw_terminal = Arc::new(AtomicBool::new(false));
turn_tx
.send(ReplEvent::StatusMessage("workstream list: ...".to_string()))
.unwrap();
turn_tx
.send(ReplEvent::AssistantOutput {
chunk: "still streaming".to_string(),
done: false,
is_error: false,
})
.unwrap();
drop(turn_tx);
forward_while_current_generation(turn_rx, real_tx, generation, 1, Arc::clone(&saw_terminal))
.await;
assert!(!saw_terminal.load(Ordering::SeqCst));
assert!(real_rx.try_recv().is_ok());
assert!(real_rx.try_recv().is_ok());
}
#[tokio::test]
async fn dispatch_pending_second_submit_while_busy_does_not_start_second_task() {
let engine = Arc::new(MockEngine::default());
let mut app = ReplApp::new("demo", "u");
let (tx, _rx) = mpsc::unbounded_channel::<ReplEvent>();
let current_task: CurrentTask = Arc::new(StdMutex::new(None));
let generation = new_generation();
app_apply(&mut app, ReplEvent::Submit("explain X".to_string()));
dispatch_pending(&mut app, &engine, &tx, ¤t_task, &generation);
for _ in 0..200 {
if engine.handle_input_calls.load(Ordering::SeqCst) > 0 {
break;
}
tokio::task::yield_now().await;
}
assert_eq!(engine.handle_input_calls.load(Ordering::SeqCst), 1);
assert!(app.busy, "first submit must leave the app busy");
app_apply(&mut app, ReplEvent::Submit("explain Y".to_string()));
assert!(app.pending_submit.is_none(), "must not stage a second turn");
dispatch_pending(&mut app, &engine, &tx, ¤t_task, &generation);
tokio::task::yield_now().await;
assert_eq!(
engine.handle_input_calls.load(Ordering::SeqCst),
1,
"a second submit while busy must never reach handle_input"
);
}
async fn drain_all_and_apply(app: &mut ReplApp, mut rx: UnboundedReceiver<ReplEvent>) {
tokio::time::timeout(Duration::from_secs(5), async {
while let Some(ev) = rx.recv().await {
app_apply(app, ev);
}
})
.await
.expect("channel must close — a stuck task would hang this instead");
}
#[tokio::test]
async fn dispatch_pending_ok_true_with_no_terminal_output_still_clears_busy() {
let engine = Arc::new(MockEngine::default());
let mut app = ReplApp::new("demo", "u");
let (tx, rx) = mpsc::unbounded_channel::<ReplEvent>();
let current_task: CurrentTask = Arc::new(StdMutex::new(None));
let generation = new_generation();
app_apply(&mut app, ReplEvent::Submit("do a thing".to_string()));
assert!(app.busy, "submit must mark busy");
dispatch_pending(&mut app, &engine, &tx, ¤t_task, &generation);
drop(tx);
drain_all_and_apply(&mut app, rx).await;
assert!(
!app.busy,
"busy must clear even when handle_input sends zero events"
);
}
#[tokio::test]
async fn dispatch_pending_ok_true_with_only_status_message_still_clears_busy() {
let engine = Arc::new(MockEngine {
send_status_only: AtomicBool::new(true),
..Default::default()
});
let mut app = ReplApp::new("demo", "u");
let (tx, rx) = mpsc::unbounded_channel::<ReplEvent>();
let current_task: CurrentTask = Arc::new(StdMutex::new(None));
let generation = new_generation();
app_apply(&mut app, ReplEvent::Submit("/workstream list".to_string()));
dispatch_pending(&mut app, &engine, &tx, ¤t_task, &generation);
drop(tx);
drain_all_and_apply(&mut app, rx).await;
assert!(
!app.busy,
"busy must clear when handle_input only ever sends a StatusMessage"
);
}
#[tokio::test]
async fn dispatch_pending_err_clears_busy_and_surfaces_visible_error() {
let engine = Arc::new(MockEngine {
returns_err: AtomicBool::new(true),
..Default::default()
});
let mut app = ReplApp::new("demo", "u");
let (tx, rx) = mpsc::unbounded_channel::<ReplEvent>();
let current_task: CurrentTask = Arc::new(StdMutex::new(None));
let generation = new_generation();
app_apply(&mut app, ReplEvent::Submit("boom".to_string()));
dispatch_pending(&mut app, &engine, &tx, ¤t_task, &generation);
drop(tx);
drain_all_and_apply(&mut app, rx).await;
assert!(!app.busy, "busy must clear on engine error");
assert!(
app.chat
.iter()
.any(|line| line.role == ChatRole::Error && line.text.contains("mock engine failure")),
"the error must be surfaced as a visible chat entry, not silently swallowed"
);
}