Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

Merge latest upstream dev and integrate steering with current TUI

tikikun520d805a9de1
diff --cc src-tauri/src/core/agent/loop.rs
index e8914a140,f6b1c4b56..b1f50bcfb
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@@ -1437,9 -1763,20 +1782,20 @@@ async fn orchestrate_inner
if result.is_ok() {
bg.join_all().await;
}
+ if index_memory {
+ if let Ok(completion) = &result {
+ if let Some(answer) = extract_choice_message(completion).and_then(|m| {
+ m.get("content")
+ .and_then(|c| c.as_str())
+ .map(str::to_string)
+ }) {
+ crate::core::agent::memory::index_message(root, "assistant", &answer);
+ }
+ }
+ }
result
} else {
- run_turn_cycle(
+ run_turn_cycle_steered(
events,
json_body,
&model_id,
@@@ -1588,48 -1980,8 +2000,70 @@@ fn body_session_budget(json_body: &serd
.filter(|v| *v > 0)
}
+#[cfg(test)]
#[allow(clippy::too_many_arguments)]
async fn run_turn_cycle(
+ events: &mpsc::UnboundedSender<StreamEvent>,
+ json_body: &serde_json::Value,
+ model_id: &str,
+ openai_tools: &[serde_json::Value],
+ conversation_messages: Vec<serde_json::Value>,
+ max_turns: usize,
+ budget: &mut SessionBudget,
+ model: &dyn ModelInvoker,
+ tools: &dyn ToolInvoker,
+ run_mode: crate::core::agent::plan::RunMode,
+ todo_registry: Option<&crate::core::agent::todo::TodoRegistry>,
+ // Forces the model's very first tool call (`turn == 0` only) to be this
+ // named tool -- used to make the eager-todo nudge actually reliable
+ // instead of an easily-ignored suggestion. `None` for every later turn.
+ force_first_tool: Option<&str>,
+) -> Result<serde_json::Value, String> {
- run_turn_cycle_steered(events, json_body, model_id, openai_tools,
- conversation_messages, max_turns, budget, model, tools, run_mode,
- todo_registry, force_first_tool, None).await
++ run_turn_cycle_steered(
++ events,
++ json_body,
++ model_id,
++ openai_tools,
++ conversation_messages,
++ max_turns,
++ budget,
++ model,
++ tools,
++ run_mode,
++ todo_registry,
++ force_first_tool,
++ None,
++ )
++ .await
+}
+
+async fn receive_steering(
+ steering: Option<&mpsc::UnboundedSender<SteeringRequest>>,
+ messages: &mut Vec<serde_json::Value>,
+ run_mode: crate::core::agent::plan::RunMode,
+) -> bool {
- let Some(steering) = steering else { return false };
++ let Some(steering) = steering else {
++ return false;
++ };
+ let (reply, response) = tokio::sync::oneshot::channel();
- if steering.send(SteeringRequest { messages: messages.clone(), reply, run_mode }).is_err() {
++ if steering
++ .send(SteeringRequest {
++ messages: messages.clone(),
++ reply,
++ run_mode,
++ })
++ .is_err()
++ {
+ return false;
+ }
+ let incoming = response.await.unwrap_or_default();
+ let received = !incoming.is_empty();
+ messages.extend(incoming);
+ received
+}
+
+#[allow(clippy::too_many_arguments)]
+async fn run_turn_cycle_steered(
events: &mpsc::UnboundedSender<StreamEvent>,
json_body: &serde_json::Value,
model_id: &str,
@@@ -1747,18 -2122,6 +2206,22 @@@
.and_then(|c| c.as_str())
.unwrap_or_default()
.to_string();
+ // Include the completed assistant response before any new user input.
+ // The terminal-boundary handshake also catches input submitted during
+ // the final model request without starting a separate run.
- if steering.is_some() && !budget.exhausted() && (unlimited || turn + 1 < max_turns) {
++ if steering.is_some() && (unlimited || turn + 1 < max_turns) {
+ let mut continued = conversation_messages.clone();
- continued.push(serde_json::json!({ "role": "assistant", "content": final_text }));
++ let mut assistant = extract_choice_message(&completion)
++ .cloned()
++ .unwrap_or_else(|| serde_json::json!({ "content": final_text }));
++ assistant["role"] = serde_json::json!("assistant");
++ continued.push(assistant);
+ if receive_steering(steering, &mut continued, run_mode).await {
+ conversation_messages = continued;
+ turn += 1;
+ continue;
+ }
+ }
let awaiting_user = final_text.trim_end().ends_with('?');
if !closeout_nudged
&& run_mode == crate::core::agent::plan::RunMode::Normal
@@@ -2163,81 -2602,6 +2702,142 @@@ mod tests
})
}
+ #[tokio::test]
+ async fn steering_enters_after_all_tool_results_in_submission_order() {
+ let (events, _rx) = mpsc::unbounded_channel();
+ let (steering, mut requests) = mpsc::unbounded_channel::<SteeringRequest>();
+ let mut completion = tool_call_completion();
+ let mut second = completion["choices"][0]["message"]["tool_calls"][0].clone();
+ second["id"] = json!("call_2");
- completion["choices"][0]["message"]["tool_calls"].as_array_mut().unwrap().push(second);
- let model = MockModel::new(vec![completion,
- json!({"choices": [{"message": {"content": "done"}, "finish_reason": "stop"}]})]);
++ completion["choices"][0]["message"]["tool_calls"]
++ .as_array_mut()
++ .unwrap()
++ .push(second);
++ let model = MockModel::new(vec![
++ completion,
++ json!({"choices": [{"message": {"content": "done"}, "finish_reason": "stop"}]}),
++ ]);
+ let consumer = tokio::spawn(async move {
+ let first = requests.recv().await.unwrap();
+ first.reply.send(vec![]).unwrap();
+ let boundary = requests.recv().await.unwrap();
- let roles: Vec<_> = boundary.messages.iter().map(|m| m["role"].as_str().unwrap()).collect();
++ let roles: Vec<_> = boundary
++ .messages
++ .iter()
++ .map(|m| m["role"].as_str().unwrap())
++ .collect();
+ assert_eq!(roles, ["user", "assistant", "tool", "tool"]);
+ assert_eq!(boundary.messages[2]["tool_call_id"], "call_1");
+ assert_eq!(boundary.messages[3]["tool_call_id"], "call_2");
- boundary.reply.send(vec![json!({"role": "user", "content": "use pnpm"}),
- json!({"role": "user", "content": "then test"})]).unwrap();
- while let Some(request) = requests.recv().await { request.reply.send(vec![]).unwrap(); }
++ boundary
++ .reply
++ .send(vec![
++ json!({"role": "user", "content": "use pnpm"}),
++ json!({"role": "user", "content": "then test"}),
++ ])
++ .unwrap();
++ while let Some(request) = requests.recv().await {
++ request.reply.send(vec![]).unwrap();
++ }
+ });
+ let mut budget = SessionBudget::new(None);
- run_turn_cycle_steered(&events, &json!({}), "m", &[],
- vec![json!({"role": "user", "content": "start"})], 8, &mut budget,
- &model, &MockTool::default(), crate::core::agent::plan::RunMode::Normal,
- None, None, Some(&steering)).await.unwrap();
++ run_turn_cycle_steered(
++ &events,
++ &json!({}),
++ "m",
++ &[],
++ vec![json!({"role": "user", "content": "start"})],
++ 8,
++ &mut budget,
++ &model,
++ &MockTool::default(),
++ crate::core::agent::plan::RunMode::Normal,
++ None,
++ None,
++ Some(&steering),
++ )
++ .await
++ .unwrap();
+ let sent = model.requests.lock().unwrap();
+ let messages = sent[1]["messages"].as_array().unwrap();
+ assert_eq!(messages[4]["content"], "use pnpm");
+ assert_eq!(messages[5]["content"], "then test");
+ assert_eq!(sent.len(), 2);
+ drop(sent);
+ drop(steering);
+ consumer.await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn steering_during_final_response_continues_the_same_run() {
+ let (events, _rx) = mpsc::unbounded_channel();
+ let (steering, mut requests) = mpsc::unbounded_channel::<SteeringRequest>();
+ let model = MockModel::new(vec![
- json!({"choices": [{"message": {"content": "first answer"}, "finish_reason": "stop"}]}),
- json!({"choices": [{"message": {"content": "revised answer"}, "finish_reason": "stop"}]})]);
++ json!({"choices": [{"message": {"content": "first answer", "reasoning_content": "considered options"}, "finish_reason": "stop"}]}),
++ json!({"choices": [{"message": {"content": "revised answer"}, "finish_reason": "stop"}]}),
++ ]);
+ let consumer = tokio::spawn(async move {
+ requests.recv().await.unwrap().reply.send(vec![]).unwrap();
+ let final_boundary = requests.recv().await.unwrap();
- assert_eq!(final_boundary.messages.last().unwrap()["content"], "first answer");
- final_boundary.reply.send(vec![json!({"role": "user", "content": "correction"})]).unwrap();
- while let Some(request) = requests.recv().await { request.reply.send(vec![]).unwrap(); }
++ assert_eq!(
++ final_boundary.messages.last().unwrap()["content"],
++ "first answer"
++ );
++ final_boundary
++ .reply
++ .send(vec![json!({"role": "user", "content": "correction"})])
++ .unwrap();
++ while let Some(request) = requests.recv().await {
++ request.reply.send(vec![]).unwrap();
++ }
+ });
+ let mut budget = SessionBudget::new(None);
- let result = run_turn_cycle_steered(&events, &json!({}), "m", &[],
- vec![json!({"role": "user", "content": "start"})], 8, &mut budget,
- &model, &MockTool::default(), crate::core::agent::plan::RunMode::Normal,
- None, None, Some(&steering)).await.unwrap();
++ let result = run_turn_cycle_steered(
++ &events,
++ &json!({}),
++ "m",
++ &[],
++ vec![json!({"role": "user", "content": "start"})],
++ 8,
++ &mut budget,
++ &model,
++ &MockTool::default(),
++ crate::core::agent::plan::RunMode::Normal,
++ None,
++ None,
++ Some(&steering),
++ )
++ .await
++ .unwrap();
+ assert_eq!(result["choices"][0]["message"]["content"], "revised answer");
+ let sent = model.requests.lock().unwrap();
+ assert_eq!(sent[1]["messages"][1]["content"], "first answer");
++ assert_eq!(
++ sent[1]["messages"][1]["reasoning_content"],
++ "considered options"
++ );
+ assert_eq!(sent[1]["messages"][2]["content"], "correction");
+ drop(sent);
+ drop(steering);
+ consumer.await.unwrap();
+ }
+
+ #[tokio::test]
+ async fn steering_disconnected_surface_does_not_block_the_loop() {
+ let (steering, receiver) = mpsc::unbounded_channel();
+ drop(receiver);
+ let mut messages = vec![json!({"role": "user", "content": "start"})];
- assert!(!receive_steering(Some(&steering), &mut messages,
- crate::core::agent::plan::RunMode::Normal).await);
++ assert!(
++ !receive_steering(
++ Some(&steering),
++ &mut messages,
++ crate::core::agent::plan::RunMode::Normal
++ )
++ .await
++ );
+ assert_eq!(messages.len(), 1);
+ }
+
#[tokio::test]
async fn turn_cycle_executes_tool_then_returns_final() {
let (tx, mut rx) = mpsc::unbounded_channel();
diff --cc src-tauri/src/core/cli/tui.rs
index 56b0a68f4,5a17e00ba..a20060371
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@@ -44,7 -47,10 +47,10 @@@ use super::mcp::McpServerEntry
use super::{sort_threads_recent, AgentSession, ResumeTarget, SessionLimits};
use crate::core::agent::events::{describe_tool_call, StreamEvent, Usage};
use crate::core::agent::git;
- use crate::core::agent::r#loop::{run_orchestration_steered, OrchestrationArgs, PermissionRegistry, SteeringRequest};
+ use crate::core::agent::r#loop::{
- run_orchestration_streamed, OrchestrationArgs, PermissionRegistry,
++ run_orchestration_steered, OrchestrationArgs, PermissionRegistry, SteeringRequest,
+ };
+ use serde_json::Value;
use tauri_plugin_agent_tools::tools::gate::PermissionDecision;
use tauri_plugin_agent_tools::workspace;
@@@ -389,32 -848,6 +849,34 @@@ struct CurrentRun
handle: JoinHandle<()>,
}
+enum RunEvent {
+ Stream(Option<StreamEvent>),
+ Steering(SteeringRequest),
+}
+
+struct PendingMessage {
+ text: String,
+ message: serde_json::Value,
+ images: Vec<String>,
+ display: bool,
++ invocation: Option<(String, String, String)>,
+ run_mode: Option<crate::core::agent::plan::RunMode>,
+}
+
+#[cfg(test)]
+impl From<&str> for PendingMessage {
+ fn from(text: &str) -> Self {
+ Self {
+ text: text.to_string(),
+ message: serde_json::json!({ "role": "user", "content": text }),
+ images: Vec::new(),
+ display: true,
++ invocation: None,
+ run_mode: None,
+ }
+ }
+}
+
/// One folded call's retained detail, so an expanded group can reconstruct each
/// individual call and its result without re-fetching anything.
struct GroupedCall {
@@@ -2271,6 -3463,105 +3491,100 @@@ impl App
}
}
+ /// Cut `start..end` out of the buffer and leave the caret at `start`.
+ /// Every kill below funnels through here so none of them can forget the
+ /// hint refresh that an edit owes the popups.
+ fn delete_span(&mut self, start: usize, end: usize) {
+ if start >= end {
+ return;
+ }
+ self.input.replace_range(start..end, "");
+ self.cursor = start;
+ self.reset_slash_hint();
+ self.refresh_path_hints();
+ }
+
+ fn cursor_word_left(&mut self) {
+ self.cursor = prev_word_start(&self.input, self.cursor);
+ }
+
+ fn cursor_word_right(&mut self) {
+ self.cursor = next_word_end(&self.input, self.cursor);
+ }
+
+ fn cursor_line_start(&mut self) {
+ self.cursor = line_bounds(&self.input, self.cursor).0;
+ }
+
+ fn cursor_line_end(&mut self) {
+ self.cursor = line_bounds(&self.input, self.cursor).1;
+ }
+
+ /// Alt+Backspace / Ctrl+Backspace.
+ fn delete_word_left(&mut self) {
+ let start = prev_word_start(&self.input, self.cursor);
+ self.delete_span(start, self.cursor);
+ }
+
+ /// Ctrl-W, on the wider whitespace-delimited word.
+ fn delete_unix_word_left(&mut self) {
+ let start = prev_unix_word_start(&self.input, self.cursor);
+ self.delete_span(start, self.cursor);
+ }
+
+ /// Alt+D / Ctrl+Delete.
+ fn delete_word_right(&mut self) {
+ let end = next_word_end(&self.input, self.cursor);
+ self.delete_span(self.cursor, end);
+ }
+
+ /// Ctrl-U (and Cmd+Backspace).
+ fn delete_to_line_start(&mut self) {
+ let start = line_bounds(&self.input, self.cursor).0;
+ self.delete_span(start, self.cursor);
+ }
+
+ /// Ctrl-K. Already at the end of a line, it swallows the newline instead of
+ /// doing nothing, so repeated presses join the buffer up as readline does.
+ fn delete_to_line_end(&mut self) {
+ let end = line_bounds(&self.input, self.cursor).1;
+ if end == self.cursor {
+ self.delete_span(self.cursor, (self.cursor + 1).min(self.input.len()));
+ } else {
+ self.delete_span(self.cursor, end);
+ }
+ }
+
+ /// Ctrl-T: swap the chars either side of the caret and step past the pair.
+ /// At the end of the buffer there is nothing after the caret, so the last
+ /// two chars swap in place, matching readline.
+ fn transpose_chars(&mut self) {
+ let before = &self.input[..self.cursor];
+ let Some(prev) = before.chars().next_back() else {
+ return;
+ };
+ let (first, second, start, end) = match self.input[self.cursor..].chars().next() {
+ Some(next) => (
+ prev,
+ next,
+ self.cursor - prev.len_utf8(),
+ self.cursor + next.len_utf8(),
+ ),
+ None => {
+ let head = &before[..before.len() - prev.len_utf8()];
+ let Some(prev2) = head.chars().next_back() else {
+ return;
+ };
+ (prev2, prev, head.len() - prev2.len_utf8(), self.cursor)
+ }
+ };
+ self.input
+ .replace_range(start..end, &format!("{second}{first}"));
+ self.cursor = end;
+ self.reset_slash_hint();
+ self.refresh_path_hints();
+ }
+
- /// Queue a user message: record it in history and the transcript, and ask
- /// the loop to start a run. Flips to `Running` synchronously so further keys
- /// in the same input batch can't slip through as a second submit.
- /// When already running, the message is enqueued instead and auto-submitted
- /// when the current turn finishes.
/// Advance the spinner by however many whole `SPINNER_ADVANCE_MS` frames
/// have elapsed since the last advance (0 if under one frame, >1 on catch-up
/// after a stalled tick). The baseline moves forward by whole frames only so
@@@ -2300,9 -3591,27 +3614,9 @@@
fn submit_user_text(&mut self, text: String, display: bool) {
if self.model.is_empty() {
- self.note("not signed in — run /login to sign in to Tokamak first");
+ self.note("not signed in — run /login to choose a provider first");
return;
}
- // If a turn is already in progress, enqueue the message instead
- if self.status == Status::Running {
- self.message_queue.push_back(text.clone());
- self.note(&format!(
- "⏳ message queued ({} in queue)",
- self.message_queue.len()
- ));
- return;
- }
- // Mid-prompt `/skill:<name>` token: dispatch to the skill, threading
- // the surrounding prose as its arguments (queued messages re-enter
- // this method via `dequeue_next`, so the token is re-parsed there too).
- if let Some((name, args)) = crate::core::agent::skills::parse_invocation(&text) {
- if self.dispatch_skill(&name, &args) {
- return;
- }
- }
- self.ensure_base_snapshot();
let images = if display {
std::mem::take(&mut self.pending_images)
} else {
@@@ -2317,35 -3626,16 +3631,58 @@@
} else {
format!("{clean_text}\n\n---\nReferenced file contents:\n\n{injected_contents}")
};
- self.history.push(build_user_message(&final_text, &images));
- if display {
- self.push_user_line(&text, &names);
- // The typed text, not `final_text`: `@path` expansions are context
- // for the model, and the row never showed them.
++ let invocation =
++ crate::core::agent::skills::parse_invocation(&text).and_then(|(name, args)| {
++ crate::core::agent::skills::build_invocation_message(
++ &self.project_root,
++ &name,
++ &args,
++ )
++ .ok()
++ .map(|(message, description)| (name, args, message, description))
++ });
++ let model_text = invocation
++ .as_ref()
++ .map_or(final_text.as_str(), |(_, _, message, _)| message.as_str());
+ let pending = PendingMessage {
++ message: build_user_message(model_text, &images),
++ invocation: invocation.map(|(name, args, _, description)| (name, args, description)),
+ text,
- message: build_user_message(&final_text, &images),
+ images: names,
+ display,
+ run_mode: Some(self.run_mode),
+ };
+ if self.status == Status::Running {
+ self.message_queue.push_back(pending);
- self.note(&format!("message pending for next agent step ({} pending)", self.message_queue.len()));
++ self.note(&format!(
++ "message pending for next agent step ({} pending)",
++ self.message_queue.len()
++ ));
+ return;
+ }
+ self.start_pending_message(pending);
+ }
+
+ fn record_pending_message(&mut self, pending: PendingMessage) {
+ self.history.push(pending.message);
+ if pending.display {
- self.push_user_line(&pending.text, &pending.images);
++ let text = if let Some((name, args, description)) = pending.invocation {
++ self.push_invocation_row(&format!("[skill:{name}]"), &args, &description);
++ format!("[skill:{name}] {args}")
++ } else {
++ self.push_user_line(&pending.text, &pending.images);
++ pending.text
++ };
self.display_log.push(DisplayEntry::User {
- text: pending.text,
- text: text.clone(),
- images: names,
++ text,
+ images: pending.images,
});
}
+ }
+
+ fn start_pending_message(&mut self, pending: PendingMessage) {
+ self.ensure_base_snapshot();
+ self.record_pending_message(pending);
self.begin_turn();
// A fresh user turn is new context: allow the next boundary to remind
// again even if the open work is unchanged (dedup is "twice in a row"),
@@@ -2446,8 -3796,11 +3843,11 @@@
if self.message_queue.is_empty() {
return;
}
- let next = self.message_queue.pop_front().expect("checked non-empty above");
+ let next = self
+ .message_queue
+ .pop_front()
+ .expect("checked non-empty above");
- if !next.is_empty() {
+ if !next.text.is_empty() || !next.images.is_empty() {
self.note(&format!(
"⏩ dequeuing next message ({} remaining)",
self.message_queue.len()
@@@ -2456,33 -3809,6 +3856,44 @@@
}
}
+ fn steer_run(&mut self, request: SteeringRequest) {
+ // A plan-mode transition needs a fresh run with rebuilt tool policy.
+ // Dedicated permission/ask replies remain separate from chat input.
+ let count = if self.pending_queue.is_empty() && self.ask_queue.is_empty() {
- self.message_queue.iter().take_while(|m| {
- m.run_mode.is_none_or(|mode| mode == request.run_mode)
- && !self.want_start
- }).count()
- } else { 0 };
- let messages = self.message_queue.iter().take(count)
- .map(|m| m.message.clone()).collect();
++ self.message_queue
++ .iter()
++ .take_while(|m| {
++ m.run_mode.is_none_or(|mode| mode == request.run_mode) && !self.want_start
++ })
++ .count()
++ } else {
++ 0
++ };
++ let messages = self
++ .message_queue
++ .iter()
++ .take(count)
++ .map(|m| m.message.clone())
++ .collect();
+ if request.reply.send(messages).is_err() || count == 0 {
+ return;
+ }
+ self.flush_assistant();
+ self.finalize_tool_group();
+ self.history = request.messages;
+ for _ in 0..count {
- let pending = self.message_queue.pop_front().expect("counted pending messages");
++ let pending = self
++ .message_queue
++ .pop_front()
++ .expect("counted pending messages");
+ self.record_pending_message(pending);
+ }
+ self.last_todo_reminder = None;
+ self.reminder_count = 0;
+ self.reminder_awaiting_progress = false;
+ self.persist();
+ }
+
/// Render a user turn: the prompt line, then one dotted connector row per
/// attached image ending in an `[IMAGE]` label (basename when known).
fn push_user_line(&mut self, text: &str, images: &[String]) {
@@@ -4370,12 -6431,11 +6516,16 @@@ fn strip_system_xml_tags(text: &str) -
fn spawn_run(args: &Arc<OrchestrationArgs>, body: serde_json::Value) -> CurrentRun {
let (tx, rx) = mpsc::unbounded_channel::<StreamEvent>();
+ let (steering_tx, steering) = mpsc::unbounded_channel();
let args = Arc::clone(args);
let handle = tokio::spawn(async move {
- let _ = run_orchestration_streamed(&tx, &body, &args).await;
+ let _ = run_orchestration_steered(&tx, &body, &args, Some(&steering_tx)).await;
});
- CurrentRun { rx, steering, handle }
- CurrentRun { rx, handle }
++ CurrentRun {
++ rx,
++ steering,
++ handle,
++ }
}
/// Await the next event of the active run, or park forever when idle.
@@@ -4956,46 -7498,10 +7594,13 @@@ async fn chat_loop<B: Backend>
(None, _) => {}
}
}
- ev = next_event(&mut current) => match ev {
- RunEvent::Stream(Some(StreamEvent::Done { stop_reason, usage })) => {
- app.on_done(stop_reason, usage);
- current = None;
- // Auto-compact when approaching the context limit. Handed to
- // the loop like `/compact` so the summarizing call runs off
- // the render loop.
- if app.should_auto_compact() && app.compacting.is_none() {
- app.compact_request = Some(CompactKind::Auto);
- }
- }
- RunEvent::Stream(Some(StreamEvent::Error { code, message })) => {
- app.on_error(code, message);
- current = None;
- }
- // Each model roundtrip is one turn toward the finished-todo
- // aging grace period. A single run can span many tool-call
- // turns, so aging must count turns, not runs -- otherwise a
- // finished plan lingers through the rest of a long run.
- RunEvent::Stream(Some(ev @ StreamEvent::Step { .. })) => {
- app.apply(ev);
- age_closed_todos(app).await;
- }
- RunEvent::Stream(Some(other)) => app.apply(other),
- RunEvent::Steering(request) => app.steer_run(request),
- RunEvent::Stream(None) => {
- // Stream closed without a terminal event (aborted task).
- // Keep any partial prose/tool calls already streamed.
- app.pending_queue.clear();
- if app.status == Status::Running {
- app.flush_assistant();
- app.abort_tool_rows();
- app.status = Status::Idle;
- app.run_started = None;
- }
- // Auto-dequeue the next queued message
- app.dequeue_next();
- current = None;
+ ev = next_event(&mut current) => {
- apply_stream_event(app, ev, &mut current).await;
++ match ev {
++ RunEvent::Stream(ev) => apply_stream_event(app, ev, &mut current).await,
++ RunEvent::Steering(request) => app.steer_run(request),
+ }
- },
+ drain_stream_events(app, &mut current).await;
+ }
}
}
@@@ -5843,7 -9154,8 +9253,8 @@@ const SLASH_COMMANDS: &[SlashCommand]
SlashCommand {
name: "/cancel",
hint: "[N]",
- description: "Cancel queued messages (bare: all, or index)",
+ description: "Cancel pending messages (bare: all, or index)",
+ alias_of: None,
},
SlashCommand {
name: "/login",
@@@ -9146,16 -15326,43 +15425,43 @@@ fn input_box(app: &App) -> Paragraph<'s
} else if app.status == Status::Running && app.input.is_empty() {
// Show queue status when running with empty input
if app.message_queue.is_empty() {
- // The spinner carries the motion; the rest of the row is static so
- // the text stays readable rather than shifting under the eye.
- Paragraph::new(Line::from(vec![
- Span::styled(format!("{} ", app.spinner()), Style::new().cyan()),
- Span::styled(
- "working… (Esc to cancel, type to steer the agent)",
+ // The spinner carries the fast motion; the action word turns over
+ // on a slower cadence, cycling "working" synonyms -- or "thinking"
+ // synonyms in orange while a reasoning block streams -- so the row
+ // reads alive without shifting under the eye.
+ let step = app.spinner_frame / WORD_ROTATE_FRAMES;
+ let (word, style) = if app.reasoning_open() {
+ (
+ THINKING_WORDS[step % THINKING_WORDS.len()],
+ Style::new().fg(THINKING_ORANGE).italic(),
+ )
+ } else {
+ (
+ WORKING_WORDS[step % WORKING_WORDS.len()],
Style::new().dim().italic(),
- ),
- ]))
- .block(block)
+ )
+ };
+ // With `wave` set, the glyph travels along the action word in place
+ // of the leading throbber: one moving thing per row, not two.
+ let message = format!("{word}…");
+ let mut spans = Vec::with_capacity(6);
+ match wave_glyph() {
+ Some(glyph) => {
+ spans.extend(wave_sweep_line(&message, &glyph, app.spinner_frame, style).spans)
+ }
+ None => {
+ spans.push(Span::styled(
+ format!("{} ", app.spinner()),
+ Style::new().cyan(),
+ ));
+ spans.push(Span::styled(message, style));
+ }
+ }
+ spans.push(Span::styled(
- " (Esc to cancel, type to queue next message)",
++ " (Esc to cancel, type to steer the agent)",
+ Style::new().dim().italic(),
+ ));
+ Paragraph::new(Line::from(spans)).block(block)
} else {
let n = app.message_queue.len();
Paragraph::new(Line::from(vec![
@@@ -9167,11 -15374,19 +15473,19 @@@
]))
.block(block)
}
+ } else if let Some(what) = app.blocking_dock() {
+ // The dock owns the keyboard while it is open, so this field takes
+ // nothing: say so instead of showing a cursor that will never move.
+ Paragraph::new(Line::styled(
+ format!("{what} - the field is inactive"),
+ Style::new().dim().italic(),
+ ))
+ .block(block)
} else if app.input.is_empty() {
- // Same `› ` arrow as the typing view, then a fixed (non-blinking)
+ // Same `> ` prompt as the typing view, then a fixed (non-blinking)
// block cursor in front of the placeholder.
let placeholder = if app.status == Status::Running {
- "Type to queue next message"
+ "Type to steer the agent"
} else {
"Type here to chat with agent"
};
@@@ -9299,10 -15514,13 +15613,13 @@@ fn footer_spans(app: &App) -> Vec<Span<
],
);
if queue_count > 0 {
- s.insert(0, Span::styled(
- format!("⏳ Pending ({queue_count}) "),
- Style::new().yellow().bold(),
- ));
+ s.insert(
+ 0,
+ Span::styled(
- format!("⏳ Queued ({queue_count}) "),
++ format!("⏳ Pending ({queue_count}) "),
+ Style::new().yellow().bold(),
+ ),
+ );
}
s
}
@@@ -9315,10 -15533,13 +15632,13 @@@
// lands in the same column as the other states.
let mut s = vec![Span::raw(" ")];
if queue_count > 0 {
- s.insert(0, Span::styled(
- format!("⏳ Pending ({queue_count}) "),
- Style::new().yellow().bold(),
- ));
+ s.insert(
+ 0,
+ Span::styled(
- format!("⏳ Queued ({queue_count}) "),
++ format!("⏳ Pending ({queue_count}) "),
+ Style::new().yellow().bold(),
+ ),
+ );
}
s
}
@@@ -9337,35 -15558,43 +15657,44 @@@
#[cfg(test)]
mod tests {
- use super::{SessionLimits, SteeringRequest, RunEvent, next_event, cancel_command};
+
+ /// An empty MCP map, for the `run_command`/`handle_key` paths that take one
+ /// but whose behaviour under test has nothing to do with MCP.
+ fn no_mcp() -> crate::core::state::SharedMcpServers {
+ std::sync::Arc::new(tokio::sync::Mutex::new(std::collections::HashMap::new()))
+ }
+ use super::journal::{self, DisplayEntry};
- use super::SessionLimits;
++ use super::{cancel_command, next_event, RunEvent, SessionLimits, SteeringRequest};
+ use tokio::sync::mpsc;
- use super::{journal, DisplayEntry};
use super::{
- age_closed_todos, apply_resume, assistant_is_awaiting_user_answer, brand, build_user_message,
- clipboard_path,
- diff_lines, Row, group_detail_lines, group_summary, handle_ask_key,
- handle_ask_mouse, handle_key, handle_mouse, image_mime, input_content_lines,
- route_paste_event,
- compact_tokens, finish_compaction, finish_login, finish_update_install,
- image_mime_of, load_first_file_image, load_image_file, MAX_IMAGE_BYTES,
- message_text, CompactKind, MAX_OVERFLOW_RETRIES,
- estimate_token_count, header_spans, status_panel, SubagentPanel,
- note_update, open_config_screen, spawn_branch_poll, await_branch_poll,
- parse_command, partial_json_field, restore_goal, restore_run_mode, restore_todos,
- autoscroll_selection, selection_text, Selection, SelectionMode, COPY_NOTICE,
- run_command, starting_call_lines, unescape_partial_json_string,
- running_group_row, split_reasoning, strip_system_xml_tags, subagent_activity,
- subagent_name_from_run_id, summarize_result, tilde_path, tokens_per_second,
- tool_activity, tool_finished,
- transcript_top_padding, rewind_to,
- row_width, user_content_parts, App, CurrentRun, Pending, PendingImage, PickerKind,
- ResumeTarget, RowKind,
- SnapshotJob, Status, AGENT_SETTINGS, ALT_SCROLL_RESTORE, ALT_SCROLL_SAVE_OFF,
- COMMAND_LABEL_MAX, DIFF_ADD_BG, DIFF_DEL_BG, DIFF_MAX_ROWS, DIFF_PREVIEW_MAX_ROWS,
- KEY_BINDINGS, MOUSE_TRACK_ON, SLASH_COMMANDS, SPINNER,
- SPINNER_ADVANCE_MS,
+ age_closed_todos, alt_scroll_restore, alt_scroll_save_off, answer_without_reasoning,
+ apply_resume, apply_stream_event, assistant_is_awaiting_user_answer, assistant_runs,
+ autoscroll_selection, await_branch_poll, backgrounded_job_id, brand, build_user_message,
+ clipboard_path, compact_tokens, diff_lines, drain_stream_events, estimate_token_count,
+ finish_account_login, finish_compaction, finish_login, finish_plugin_install,
+ finish_tokamak_login, finish_update_install, group_detail_lines, group_summary,
+ handle_ask_key, handle_ask_mouse, handle_key, handle_mouse, header_spans, image_mime,
+ image_mime_of, input_content_lines, load_first_file_image, load_image_file, message_text,
+ note_update, open_config_screen, open_rewind_picker, pairs_to_str, parse_command,
+ partial_json_field, provider_label_for_model, rebuild_recall, replay_display_log,
+ restore_goal, restore_run_mode, restore_todos, resume_hint, rewind_to, route_paste_event,
+ row_width, run_command, running_group_rows, selection_text, spans_width, spawn_branch_poll,
+ split_reasoning, starting_call_lines, startup_modes, strip_system_xml_tags,
+ subagent_activity, subagent_name_from_run_id, summarize_result, sync_output_for,
+ thinking_open, tilde_path, tokens_per_second, tool_activity, tool_finished,
+ transcript_top_padding, unescape_partial_json_string, user_content_parts, wave_sweep_line,
+ with_wave_glyph, without_think_tags, App, CompactKind, CurrentRun, McpField, McpPrompt,
+ Pending, PendingImage, PickerKind, ProviderField, ReasoningSeg, ResumeTarget, Row, RowKind,
+ Selection, SelectionMode, SnapshotJob, Status, AGENT_SETTINGS, ALT_SCROLL_RESTORE,
+ ALT_SCROLL_SAVE_OFF, COPY_NOTICE, DIFF_ADD_BG, DIFF_DEL_BG, DIFF_MAX_ROWS,
+ DIFF_PREVIEW_MAX_ROWS, KEY_BINDINGS, KITTY_KEYS_OFF, KITTY_KEYS_ON, MAX_IMAGE_BYTES,
+ MAX_OVERFLOW_RETRIES, MOUSE_TRACK_ON, PROVIDERS_SETTINGS_ROW, SLASH_COMMANDS, SPINNER,
+ SPINNER_ADVANCE_MS, THINKING_WORDS, WORKING_WORDS,
};
- use std::time::{Duration, Instant};
+ use crate::core::agent::events::{StreamEvent, Usage};
+ use crate::core::agent::r#loop::PermissionRegistry;
+ use crate::core::cli::updater::{AvailableUpdate, UpdateOutcome};
+ use ratatui::buffer::Buffer;
use ratatui::crossterm::event::{
Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent,
MouseEventKind,
@@@ -9454,143 -15683,55 +15783,300 @@@
TestApp { app, _dir: dir }
}
- fn steering_request(messages: Vec<serde_json::Value>) -> (SteeringRequest, tokio::sync::oneshot::Receiver<Vec<serde_json::Value>>) {
++ fn steering_request(
++ messages: Vec<serde_json::Value>,
++ ) -> (
++ SteeringRequest,
++ tokio::sync::oneshot::Receiver<Vec<serde_json::Value>>,
++ ) {
+ let (reply, receiver) = tokio::sync::oneshot::channel();
- (SteeringRequest { messages, reply, run_mode: crate::core::agent::plan::RunMode::Normal }, receiver)
++ (
++ SteeringRequest {
++ messages,
++ reply,
++ run_mode: crate::core::agent::plan::RunMode::Normal,
++ },
++ receiver,
++ )
+ }
+
+ #[test]
+ fn steering_preserves_images_paths_order_and_transcript_once() {
+ let mut app = test_app();
+ let files = tempfile::tempdir().unwrap();
+ app.project_root = files.path().to_path_buf();
+ std::fs::write(files.path().join("note.txt"), "original context").unwrap();
+ app.submit_user("start".into());
+ app.want_start = false;
- app.pending_images.push(PendingImage { name: "pic.png".into(), data_url: "data:image/png;base64,AAAA".into() });
++ app.pending_images.push(PendingImage {
++ name: "pic.png".into(),
++ data_url: "data:image/png;base64,AAAA".into(),
++ });
+ app.submit_user("read @note.txt".into());
+ app.submit_user("then test".into());
+ assert!(app.pending_images.is_empty());
+ assert_eq!(app.history.len(), 1);
+ std::fs::write(files.path().join("note.txt"), "changed later").unwrap();
+ let (request, mut receiver) = steering_request(app.history.clone());
+ app.steer_run(request);
+ let messages = receiver.try_recv().unwrap();
+ assert_eq!(messages.len(), 2);
- assert!(messages[0]["content"][0]["text"].as_str().unwrap().contains("original context"));
- assert_eq!(messages[0]["content"][1]["image_url"]["url"], "data:image/png;base64,AAAA");
++ assert!(messages[0]["content"][0]["text"]
++ .as_str()
++ .unwrap()
++ .contains("original context"));
++ assert_eq!(
++ messages[0]["content"][1]["image_url"]["url"],
++ "data:image/png;base64,AAAA"
++ );
+ assert_eq!(messages[1]["content"], "then test");
+ assert_eq!(app.history.len(), 3);
+ assert!(app.message_queue.is_empty());
- assert_eq!(app.display_log.iter().filter(|e| matches!(e, DisplayEntry::User { .. })).count(), 3);
++ assert_eq!(
++ app.display_log
++ .iter()
++ .filter(|e| matches!(e, DisplayEntry::User { .. }))
++ .count(),
++ 3
++ );
+ let (request, mut receiver) = steering_request(app.history.clone());
+ app.steer_run(request);
+ assert!(receiver.try_recv().unwrap().is_empty());
+ assert_eq!(app.history.len(), 3);
+ }
+
+ #[test]
+ fn steering_cancel_removes_only_pending_input() {
+ let mut app = test_app();
+ app.submit_user("start".into());
+ app.want_start = false;
+ app.submit_user("remove me".into());
+ app.submit_user("keep me".into());
+ cancel_command(&mut app, "1");
+ let (request, mut receiver) = steering_request(app.history.clone());
+ app.steer_run(request);
- assert_eq!(receiver.try_recv().unwrap(), vec![json!({"role": "user", "content": "keep me"})]);
++ assert_eq!(
++ receiver.try_recv().unwrap(),
++ vec![json!({"role": "user", "content": "keep me"})]
++ );
++ }
++
++ #[test]
++ fn steering_does_not_answer_or_bypass_a_permission_prompt() {
++ let mut app = test_app();
++ app.submit_user("start".into());
++ app.want_start = false;
++ app.submit_user("correction".into());
++ app.pending_queue.push_back(pending(false));
++ let (request, mut receiver) = steering_request(app.history.clone());
++ app.steer_run(request);
++ assert!(receiver.try_recv().unwrap().is_empty());
++ assert_eq!(app.pending_queue.len(), 1);
++ assert_eq!(app.message_queue.len(), 1);
+ }
+
+ #[test]
+ fn steering_failed_handoff_keeps_input_for_next_turn() {
+ let mut app = test_app();
+ app.submit_user("start".into());
+ app.want_start = false;
+ app.submit_user("late follow-up".into());
+ let (request, receiver) = steering_request(app.history.clone());
+ drop(receiver);
+ app.steer_run(request);
+ assert_eq!(app.message_queue.len(), 1);
+ assert_eq!(app.history.len(), 1);
+ app.on_done("stop".into(), None);
+ assert!(app.message_queue.is_empty());
+ assert_eq!(app.history.last().unwrap()["content"], "late follow-up");
+ assert!(app.want_start);
+ }
+
+ #[test]
+ fn steering_plan_transition_waits_for_a_new_run() {
+ let mut app = test_app();
+ app.submit_user("start".into());
+ app.want_start = false;
+ app.run_mode = crate::core::agent::plan::RunMode::Plan;
+ app.submit_user("plan only".into());
+ let (request, mut receiver) = steering_request(app.history.clone());
+ app.steer_run(request);
+ assert!(receiver.try_recv().unwrap().is_empty());
+ assert_eq!(app.message_queue.len(), 1);
+ }
+
+ #[tokio::test]
+ async fn steering_waits_until_earlier_stream_events_are_rendered() {
+ let (tx, rx) = mpsc::unbounded_channel();
+ let (steering_tx, steering) = mpsc::unbounded_channel();
- tx.send(StreamEvent::Token { text: "answer".into() }).unwrap();
++ tx.send(StreamEvent::Token {
++ text: "answer".into(),
++ })
++ .unwrap();
+ let (request, _receiver) = steering_request(vec![]);
+ steering_tx.send(request).unwrap();
- let mut current = Some(CurrentRun { rx, steering, handle: tokio::spawn(async {}) });
- assert!(matches!(next_event(&mut current).await, RunEvent::Stream(Some(StreamEvent::Token { .. }))));
- assert!(matches!(next_event(&mut current).await, RunEvent::Steering(_)));
++ let mut current = Some(CurrentRun {
++ rx,
++ steering,
++ handle: tokio::spawn(async {}),
++ });
++ assert!(matches!(
++ next_event(&mut current).await,
++ RunEvent::Stream(Some(StreamEvent::Token { .. }))
++ ));
++ assert!(matches!(
++ next_event(&mut current).await,
++ RunEvent::Steering(_)
++ ));
+ }
+
+ #[test]
+ fn steering_error_and_cancel_fallback_keep_attachments() {
+ for cancel in [false, true] {
+ let mut app = test_app();
+ app.submit_user("start".into());
+ app.want_start = false;
- app.pending_images.push(PendingImage { name: "pic.png".into(), data_url: "data:image/png;base64,AAAA".into() });
++ app.pending_images.push(PendingImage {
++ name: "pic.png".into(),
++ data_url: "data:image/png;base64,AAAA".into(),
++ });
+ app.submit_user("follow-up".into());
- if cancel { app.cancel_run(); } else { app.on_error("error".into(), "offline".into()); }
++ if cancel {
++ app.cancel_run();
++ } else {
++ app.on_error("error".into(), "offline".into());
++ }
+ assert!(app.message_queue.is_empty());
+ assert!(app.want_start);
- assert_eq!(app.history.last().unwrap()["content"][1]["image_url"]["url"], "data:image/png;base64,AAAA");
++ assert_eq!(
++ app.history.last().unwrap()["content"][1]["image_url"]["url"],
++ "data:image/png;base64,AAAA"
++ );
+ }
+ }
+
+ #[test]
+ fn steering_session_reset_discards_old_pending_input() {
+ let mut app = test_app();
+ app.submit_user("start".into());
+ app.want_start = false;
+ app.submit_user("old session only".into());
+ app.reset_session();
+ let (request, mut receiver) = steering_request(vec![]);
+ app.steer_run(request);
+ assert!(receiver.try_recv().unwrap().is_empty());
+ assert!(app.history.is_empty());
+ assert!(app.message_queue.is_empty());
+ }
+
+ #[tokio::test]
+ async fn steering_consumed_input_survives_resume_once() {
+ let mut app = test_app();
+ app.submit_user("start".into());
+ app.want_start = false;
+ app.submit_user("correction".into());
+ let (request, mut receiver) = steering_request(app.history.clone());
+ app.steer_run(request);
+ assert_eq!(receiver.try_recv().unwrap().len(), 1);
+ app.join_journal();
+ let mut restored = test_app();
+ restored.agent_dir = app.agent_dir.clone();
+ apply_resume(&mut restored, &ResumeTarget::Latest).await;
- assert_eq!(restored.history.iter().filter(|m| m["content"] == "correction").count(), 1);
- assert_eq!(restored.display_log.iter().filter(|e| matches!(e, DisplayEntry::User { text, .. } if text == "correction")).count(), 1);
++ assert_eq!(
++ restored
++ .history
++ .iter()
++ .filter(|m| m["content"] == "correction")
++ .count(),
++ 1
++ );
++ assert_eq!(
++ restored
++ .display_log
++ .iter()
++ .filter(|e| matches!(e, DisplayEntry::User { text, .. } if text == "correction"))
++ .count(),
++ 1
++ );
+ assert!(restored.message_queue.is_empty());
+ }
+
++ #[tokio::test]
++ async fn steering_expands_skill_input_without_resetting_the_run() {
++ let (mut app, root) = skill_test_app("deploy", "How to deploy.");
++ app.submit_user("start".into());
++ app.want_start = false;
++ app.pending_images.push(PendingImage {
++ name: "pic.png".into(),
++ data_url: "data:image/png;base64,AAAA".into(),
++ });
++ app.submit_user("please /skill:deploy carefully".into());
++ let (request, mut receiver) = steering_request(app.history.clone());
++ app.steer_run(request);
++ let messages = receiver.try_recv().unwrap();
++ assert!(messages[0]["content"][0]["text"]
++ .as_str()
++ .unwrap()
++ .contains("User: please carefully"));
++ assert_eq!(
++ messages[0]["content"][1]["image_url"]["url"],
++ "data:image/png;base64,AAAA"
++ );
++ assert!(!app.want_start);
++ assert!(transcript_text(&app).contains("[skill:deploy] please carefully"));
++ app.join_journal();
++ std::fs::remove_dir_all(root).unwrap();
++ }
++
+ /// App whose project has one installed skill `<name>/SKILL.md` with the
+ /// given frontmatter description, so slash-popup and dispatch tests run
+ /// against a real `.jan/agent/skills/` tree. Returns the temp project
+ /// root for cleanup.
+ fn skill_test_app(name: &str, description: &str) -> (App, std::path::PathBuf) {
+ skill_test_app_fm(name, description, "")
+ }
+
+ /// Like `skill_test_app` but with extra frontmatter lines (before the
+ /// closing `---`), for invocation-flag tests.
+ fn skill_test_app_fm(
+ name: &str,
+ description: &str,
+ extra_fm: &str,
+ ) -> (App, std::path::PathBuf) {
+ let root = std::env::temp_dir().join(format!(
+ "jan_tui_skill_{}_{}",
+ std::process::id(),
+ uuid::Uuid::new_v4()
+ ));
+ let agent_dir = root.join(".jan/agent");
+ std::fs::create_dir_all(agent_dir.join("skills").join(name)).unwrap();
+ std::fs::write(
+ agent_dir.join("skills").join(name).join("SKILL.md"),
+ format!(
+ "---\nname: {name}\ndescription: {description}\n{extra_fm}---\n\n# {name}\n\nBody.\n"
+ ),
+ )
+ .unwrap();
+ (
+ App::new(
+ "m".into(),
+ super::SessionLimits {
+ context_window: 128_000,
+ context_window_source:
+ crate::core::cli::model_capabilities::ContextWindowSource::Fallback,
+ reserve_tokens: 16_384,
+ max_tokens: None,
+ max_session_tokens: 128_000,
+ },
+ false,
+ agent_dir,
+ root.clone(),
+ None,
+ ),
+ root,
+ )
+ }
+
/// Draw `app` into an off-screen terminal and return its rows as strings.
fn render_rows(app: &mut App, w: u16, h: u16) -> Vec<String> {
use ratatui::{backend::TestBackend, Terminal};
@@@ -13169,507 -24923,566 +25268,566 @@@
);
}
+ /// Every dispatch joins the one panel; nothing is committed to the chat.
#[test]
- fn group_row_stays_running_while_a_sibling_call_is_outstanding() {
+ fn parallel_dispatches_share_one_pinned_panel() {
let mut app = test_app();
- app.apply(StreamEvent::ToolCall {
- id: "c1".into(),
- name: "bash".into(),
- args: json!({ "command": "sleep 10" }),
- });
- app.apply(StreamEvent::ToolCall {
- id: "c2".into(),
- name: "read".into(),
- args: json!({ "path": "main.rs" }),
- });
- let idx = app.tool_group.as_ref().unwrap().idx;
- // Results can land out of dispatch order; the row must not claim the
- // batch is done while an earlier call is still outstanding.
- app.apply(StreamEvent::ToolResult {
- id: "c2".into(),
- content: "fn main() {}".into(),
- is_error: false,
- diff: None,
- });
- assert!(app.tool_group.as_ref().unwrap().is_running());
- let row = row_text(&app.transcript[idx]);
- assert!(!row.contains("✓"), "resolved early: {row}");
- app.apply(StreamEvent::ToolResult {
- id: "c1".into(),
- content: "done".into(),
- is_error: false,
- diff: None,
+ start_subagent(&mut app, "r0", "alpha");
+ let before = app.transcript.len();
+ start_subagent(&mut app, "r1", "beta");
+ assert_eq!(app.transcript.len(), before, "no transcript rows committed");
+ let rows = render_rows(&mut app, 100, 24);
+ assert_eq!(
+ rows.iter().filter(|r| r.contains("agents")).count(),
+ 1,
+ "one panel head only: {rows:?}"
+ );
+ assert!(rows.iter().any(|r| r.contains("2 agents")), "{rows:?}");
+ }
+
+ /// The panel is live state: when the last child ends it vanishes, leaving
+ /// the committed summary row as the only trace in the conversation.
+ #[test]
+ fn panel_clears_when_the_last_child_ends() {
+ let mut app = test_app();
+ start_subagent(&mut app, "r0", "alpha");
+ app.apply(StreamEvent::SubagentEnd {
+ run_id: "r0".into(),
+ name: "alpha".into(),
});
- assert!(!app.tool_group.as_ref().unwrap().is_running());
- assert!(row_text(&app.transcript[idx]).contains("✓"));
+ assert!(app.subagents.is_empty(), "live panel closed");
+ let rows = render_rows(&mut app, 100, 24);
+ assert!(
+ !rows.iter().any(|r| r.contains("1 agent")),
+ "panel must be gone: {rows:?}"
+ );
+ assert!(
+ rows.iter().any(|r| r.contains("subagent alpha finished")),
+ "summary row missing: {rows:?}"
+ );
}
+ /// `await_subagent` on a child that already has a live panel used to print
+ /// a second "Awaiting subagent: X" row directly under the block that was
+ /// showing that child's progress. Only an orphaned wait gets a row.
#[test]
- fn handle_mouse_click_maps_row_to_region_toggle() {
+ fn awaiting_row_is_suppressed_while_the_child_has_a_live_panel() {
let mut app = test_app();
+ start_subagent(&mut app, "r0", "alpha");
app.apply(StreamEvent::ToolCall {
- id: "c1".into(),
- name: "memory_read".into(),
- args: json!({ "name": "x" }),
- });
- app.apply(StreamEvent::ToolResult {
- id: "c1".into(),
- content: "result".into(),
- is_error: false,
- diff: None,
+ id: "a1".into(),
+ name: "await_subagent".into(),
+ args: json!({ "run_id": "r0" }),
});
- app.apply(StreamEvent::Token { text: "Done.".into() });
- let group_idx = app.groups[0].idx;
-
- // Simulate what `draw` would have recorded: the group's row is the
- // only transcript row, right under the top border at row 1.
- app.transcript_rect = Rect::new(0, 0, 80, 10);
- app.last_scroll = 0;
- app.row_index = vec![Some(group_idx)];
-
- click(&mut app, 5, 1);
- assert!(app.expanded.contains(&group_idx));
+ assert_eq!(app.awaiting.len(), 1, "wait state is still tracked");
+ let rows = render_rows(&mut app, 100, 24);
+ assert!(
+ !rows.iter().any(|r| r.contains("Awaiting subagent")),
+ "live panel already reports this child: {rows:?}"
+ );
- // Clicking outside the viewport (past the bottom border) is a no-op.
- click(&mut app, 5, 9);
- assert!(app.expanded.contains(&group_idx));
+ // The child ends while its result is still in flight: with no panel
+ // left to report it, the wait gets its own row again.
+ app.subagents.clear();
+ let rows = render_rows(&mut app, 100, 24);
+ assert!(
+ rows.iter().any(|r| r.contains("Awaiting subagent")),
+ "orphaned wait must stay visible: {rows:?}"
+ );
}
+ /// Regression: a child streaming a large `write` completes no tool call
+ /// for the whole request, so the panel used to sit frozen on
+ /// "0 tools / starting…" for exactly the stretch the user most wants
+ /// feedback on. Its in-flight call must report progress like the parent's.
#[test]
- fn wheel_scrolls_transcript() {
+ fn subagent_reports_its_in_flight_call() {
let mut app = test_app();
- app.transcript_rect = Rect::new(0, 0, 80, 10);
- let up = |app: &mut App| {
- handle_mouse(
- app,
- MouseEvent {
- kind: MouseEventKind::ScrollUp,
- column: 5,
- row: 5,
- modifiers: KeyModifiers::NONE,
- },
- )
- };
- up(&mut app);
- up(&mut app);
- assert_eq!(app.scrollback, 2);
- handle_mouse(
+ start_subagent(&mut app, "r0", "flappy-2d");
+ subagent_event(
&mut app,
- MouseEvent {
- kind: MouseEventKind::ScrollDown,
- column: 5,
- row: 5,
- modifiers: KeyModifiers::NONE,
+ "r0",
+ "flappy-2d",
+ StreamEvent::Step { index: 1, max: 8 },
+ );
+
+ // The child announces a write and starts streaming its arguments --
+ // no ToolCall yet, which is the whole problem.
+ subagent_event(
+ &mut app,
+ "r0",
+ "flappy-2d",
+ StreamEvent::ToolCallStarted {
+ id: "c1".into(),
+ name: "write".into(),
},
);
- assert_eq!(app.scrollback, 1);
- }
+ let out = render_rows(&mut app, 100, 20).join("\n");
+ assert!(
+ !out.contains("starting…"),
+ "should have moved off the placeholder: {out}"
+ );
+ assert!(
+ out.contains("write"),
+ "should name the tool being assembled: {out}"
+ );
- #[test]
- fn toggle_region_expands_still_running_group() {
- // A tool group is still open (not yet finalized into `app.groups`)
- // while the agent is actively executing -- clicking its row must
- // still toggle it, not just after it finishes.
- let mut app = test_app();
- app.apply(StreamEvent::ToolCall {
- id: "c1".into(),
- name: "grep".into(),
- args: json!({ "pattern": "foo" }),
- });
- let idx = app.tool_group.as_ref().expect("group open").idx;
- assert!(app.groups.is_empty(), "not finalized yet");
+ // Once the path arrives it names the destination, still mid-stream.
+ for delta in [r#"{"path":"flappy"#, r#"-2d.html","content":"<!doct"#] {
+ subagent_event(
+ &mut app,
+ "r0",
+ "flappy-2d",
+ StreamEvent::ToolCallArgsDelta {
+ id: "c1".into(),
+ delta: delta.into(),
+ },
+ );
+ }
+ let out = render_rows(&mut app, 100, 20).join("\n");
+ assert!(
+ out.contains("flappy-2d.html"),
+ "destination should surface: {out}"
+ );
+ assert!(out.contains("0t · "), "still no completed call: {out}");
- app.toggle_region(idx);
- assert!(app.expanded.contains(&idx));
- app.toggle_region(idx);
- assert!(app.expanded.is_empty());
+ // The completed call supersedes the in-progress row.
+ subagent_event(
+ &mut app,
+ "r0",
+ "flappy-2d",
+ StreamEvent::ToolCall {
+ id: "c1".into(),
+ name: "write".into(),
+ args: json!({ "path": "flappy-2d.html" }),
+ },
+ );
+ let out = render_rows(&mut app, 100, 20).join("\n");
+ assert!(out.contains("1t · "), "completed call should count: {out}");
+ assert!(
+ app.subagents[0].active.is_none(),
+ "in-flight view should clear once the call lands"
+ );
}
+ /// Before a child reports usage there is no honest percentage to show, and
+ /// "0.0%" would read as a stalled agent.
#[test]
- fn clicking_anywhere_in_expanded_block_collapses_it() {
- // Once a block (e.g. long reasoning) has expanded past the viewport,
- // its header row can scroll out of view. A click on any of its detail
- // rows -- not just the header -- must still collapse it.
+ fn subagent_hides_context_share_until_it_reports() {
let mut app = test_app();
- app.push_assistant_blocks("<think>line one\nline two\nline three</think>answer");
- assert_eq!(app.reasoning_blocks.len(), 1);
- let idx = app.reasoning_blocks[0].idx;
-
- app.toggle_region(idx);
- assert!(app.expanded.contains(&idx));
-
- // Detail rows map back to the same idx as the header (see draw()).
- app.transcript_rect = Rect::new(0, 0, 80, 10);
- app.last_scroll = 0;
- app.row_index = vec![Some(idx), Some(idx), Some(idx)];
- click(&mut app, 5, 2); // a detail row, not the header at row 1
- assert!(app.expanded.is_empty(), "click on a detail row should collapse");
+ start_subagent(&mut app, "r1", "alpha");
+ let out = render_rows(&mut app, 100, 20).join("\n");
+ assert!(out.contains("1 agent"), "{out}");
+ assert!(out.contains("starting…"), "{out}");
+ assert!(
+ !out.contains('%'),
+ "no share before the first response: {out}"
+ );
}
+ /// The running placeholder is the row a user stares at during a long turn.
+ /// A static "working…" reads as a hung UI, so it animates on the same
+ /// cadence as every other throbber: the spinner glyph rotates, and the
+ /// action word cycles through synonyms of "working".
#[test]
- fn silent_tool_turns_keep_folding_across_step_boundaries() {
+ fn working_placeholder_animates() {
let mut app = test_app();
- // One tool per turn (Step between each), no prose: the agent-loop shape.
- for (i, id) in ["c1", "c2", "c3"].iter().enumerate() {
- app.apply(StreamEvent::Step {
- index: i as u32 + 1,
- max: 8,
- });
- app.apply(StreamEvent::ToolCall {
- id: (*id).into(),
- name: "bash".into(),
- args: json!({ "command": "ls" }),
- });
- app.apply(StreamEvent::ToolResult {
- id: (*id).into(),
- content: "ok".into(),
- is_error: false,
- diff: None,
- });
- }
- // Still one open group after three turns, not a row per turn.
- assert!(app.tool_group.is_some());
- let tool_rows = app
- .transcript
- .iter()
- .filter(|l| {
- let t = row_text(l);
- t.contains("Executing") || t.contains("Running") || t.contains("Ran")
+ app.submit_user("go".into());
+ assert_eq!(app.status, Status::Running);
+
+ // Pinned off: these assert on the spinner glyph and the intact action
+ // word, both of which the sweep overwrites a cell of. `wave` is on by
+ // default now, so the sweep has its own tests and these keep testing
+ // the row underneath it.
+ let frame_of = |app: &mut App| {
+ with_wave_glyph(None, || {
+ render_rows(app, 80, 12)
+ .into_iter()
- .find(|r| r.contains("(Esc to cancel, type to queue next message)"))
++ .find(|r| r.contains("(Esc to cancel, type to steer the agent)"))
+ .expect("running placeholder present")
})
- .count();
- assert_eq!(tool_rows, 1);
- app.on_done("stop".into(), None);
- let row = app
- .transcript
- .iter()
- .map(row_text)
- .find(|t| t.contains("Ran "))
- .unwrap();
- assert!(row.contains("✓ Ran 3 commands"), "row: {row}");
- }
+ };
- #[test]
- fn reasoning_before_tool_call_renders_above_it_in_order() {
- let mut app = test_app();
- // Reasoning model thinks, then acts. The thought must commit above the
- // tool row (emission order), not linger in the live tail below it.
- app.apply(StreamEvent::Token {
- text: "<think>let me look at the config</think>".into(),
- });
- app.apply(StreamEvent::ToolCall {
- id: "c1".into(),
- name: "bash".into(),
- args: json!({ "command": "ls" }),
- });
- app.apply(StreamEvent::ToolResult {
- id: "c1".into(),
- content: "ok".into(),
- is_error: false,
- diff: None,
- });
- // Buffer is drained: the reasoning is committed, not stranded below.
- assert!(app.assistant_buf.is_empty());
- // Reasoning folds to a collapsed summary row (raw thought hidden), which
- // still lands above the tool row it preceded (emission order).
- let rows: Vec<String> = app.transcript.iter().map(row_text).collect();
+ app.spinner_frame = 0;
+ let first = frame_of(&mut app);
assert!(
- !rows.iter().any(|r| r.contains("let me look")),
- "raw reasoning must be hidden by default: {rows:?}"
+ first.contains(SPINNER[0]),
+ "expected frame 0 glyph: {first:?}"
);
- let think_at = rows.iter().position(|r| r.contains("reasoning (1 line)")).unwrap();
- let tool_at = rows
- .iter()
- .position(|r| r.contains("Executing") || r.contains("Running") || r.contains("Ran"))
- .unwrap();
+
+ // While a plain turn is running (no reasoning), the row shows a
+ // rotating synonym of "working".
assert!(
- think_at < tool_at,
- "reasoning must render above the tool row it preceded: {rows:?}"
+ WORKING_WORDS.iter().any(|w| first.contains(w)),
+ "expected a working synonym in: {first:?}"
+ );
+
+ app.spinner_frame = 3;
+ let later = frame_of(&mut app);
+ assert!(
+ later.contains(SPINNER[3]),
+ "expected frame 3 glyph: {later:?}"
+ );
+ assert_ne!(first, later, "row must change as the frame advances");
+
+ assert!(
- later.contains("(Esc to cancel, type to queue next message)"),
++ later.contains("(Esc to cancel, type to steer the agent)"),
+ "{later:?}"
);
- // The raw thought is retained on the block for expansion.
- let block = &app.reasoning_blocks[0];
- assert!(block.detail.iter().map(line_text).any(|l| l.contains("let me look")));
}
+ /// When the model is reasoning (a ` think>` block is streaming), the input
+ /// placeholder cycles through synonyms of "thinking".
#[test]
- fn reasoning_row_is_separated_from_following_prose_by_a_blank_line() {
+ fn thinking_placeholder_uses_thinking_synonyms() {
let mut app = test_app();
+ app.submit_user("go".into());
app.apply(StreamEvent::Token {
- text: "<think>thinking</think>Hi there!".into(),
+ text: "<think>ponder the plan".into(),
+ });
+ // Pinned off for the same reason as `working_placeholder_animates`:
+ // the sweep replaces a letter of the word being matched.
+ let row = with_wave_glyph(None, || {
+ render_rows(&mut app, 80, 12)
+ .into_iter()
- .find(|r| r.contains("(Esc to cancel, type to queue next message)"))
++ .find(|r| r.contains("(Esc to cancel, type to steer the agent)"))
+ .expect("running placeholder present")
});
- app.apply(StreamEvent::Step { index: 1, max: 8 });
- let rows: Vec<String> = app.transcript.iter().map(row_text).collect();
- let think_at = rows.iter().position(|r| r.contains("reasoning (1 line)")).unwrap();
- let prose_at = rows.iter().position(|r| r.contains("Hi there!")).unwrap();
- assert!(think_at < prose_at);
- // A blank line must sit between the reasoning row and the prose.
assert!(
- rows[think_at + 1..prose_at].iter().any(|r| r.trim().is_empty()),
- "expected a blank line between reasoning and prose: {rows:?}"
+ THINKING_WORDS.iter().any(|w| row.contains(w)),
+ "expected a thinking synonym in: {row:?}"
+ );
+ assert!(
+ !WORKING_WORDS.iter().any(|w| row.contains(w)),
+ "no working synonym while reasoning: {row:?}"
);
}
+ /// Thinking synonyms are coloured orange so the active reasoning state
+ /// stands out from the quiet working rows.
#[test]
- fn committed_reasoning_folds_and_expands_via_keybinding() {
+ fn thinking_synonym_is_orange() {
+ use ratatui::{backend::TestBackend, Terminal};
let mut app = test_app();
+ app.submit_user("go".into());
app.apply(StreamEvent::Token {
- text: "<think>step one\nstep two</think>The answer is 42.".into(),
+ text: "<think>ponder the plan".into(),
});
- // A turn boundary commits the buffer.
- app.apply(StreamEvent::Step { index: 1, max: 8 });
-
- let rows: Vec<String> = app.transcript.iter().map(row_text).collect();
- assert!(rows.iter().any(|r| r.contains("reasoning (2 lines)")));
- assert!(rows.iter().any(|r| r.contains("The answer is 42")));
- // Raw reasoning is hidden until expanded.
- assert!(!rows.iter().any(|r| r.contains("step one")));
- assert_eq!(app.reasoning_blocks.len(), 1);
-
- let idx = app.reasoning_blocks[0].idx;
- app.toggle_regions();
- assert!(app.expanded.contains(&idx));
- app.toggle_regions();
- assert!(app.expanded.is_empty());
+ let mut terminal = Terminal::new(TestBackend::new(80, 12)).unwrap();
+ // Pinned off: the row is located by matching the intact word, which
+ // the sweep breaks.
+ with_wave_glyph(None, || {
+ terminal.draw(|f| super::draw(f, &mut app)).unwrap();
+ });
+ let buf = terminal.backend().buffer().clone();
+ // Locate the placeholder row, then assert the action word's cells are
+ // orange (the trailing hint stays dim, so only the word carries it).
+ let orange = (0..buf.area.height).any(|y| {
+ let row: String = (0..buf.area.width).map(|x| buf[(x, y)].symbol()).collect();
+ if !THINKING_WORDS.iter().any(|w| row.contains(w)) {
+ return false;
+ }
+ (0..buf.area.width).any(|x| buf[(x, y)].style().fg == Some(super::THINKING_ORANGE))
+ });
+ assert!(orange, "thinking synonym not orange");
}
+ /// The working word rotates to a different synonym as the frame advances.
#[test]
- fn silent_consecutive_tool_calls_still_fold() {
+ fn working_synonym_rotates_across_frames() {
let mut app = test_app();
- // No reasoning/prose between calls: they must fold into one group row.
- for id in ["c1", "c2", "c3"] {
- app.apply(StreamEvent::ToolCall {
- id: id.into(),
- name: "bash".into(),
- args: json!({ "command": "ls" }),
- });
- app.apply(StreamEvent::ToolResult {
- id: id.into(),
- content: "ok".into(),
- is_error: false,
- diff: None,
+ app.submit_user("go".into());
+ let mut word_at = |frame: usize| {
+ app.spinner_frame = frame;
+ // Pinned off: the sweep would eat a letter of the very word this
+ // looks up.
+ let row = with_wave_glyph(None, || {
+ render_rows(&mut app, 80, 12)
+ .into_iter()
- .find(|r| r.contains("(Esc to cancel, type to queue next message)"))
++ .find(|r| r.contains("(Esc to cancel, type to steer the agent)"))
+ .expect("running placeholder present")
});
- }
- assert!(app.tool_group.is_some());
- let tool_rows = app
- .transcript
- .iter()
- .filter(|l| {
- let t = row_text(l);
- t.contains("Executing") || t.contains("Running") || t.contains("Ran ")
- })
- .count();
- assert_eq!(tool_rows, 1);
- app.apply(StreamEvent::Token {
- text: "All done.".into(),
- });
- assert!(app.tool_group.is_none());
- let row = app
- .transcript
- .iter()
- .map(row_text)
- .find(|t| t.contains("Ran "))
- .unwrap();
- assert!(row.contains("✓ Ran 3 commands"), "row: {row}");
+ WORKING_WORDS
+ .iter()
+ .find(|w| row.contains(*w))
+ .map(|w| w.to_string())
+ .expect("working synonym present")
+ };
+ let a = word_at(0);
+ let b = word_at(super::WORD_ROTATE_FRAMES);
+ assert_ne!(a, b, "working word must rotate as frames advance: {a}");
}
+ /// A queued-message row is still a running row, so it animates too.
#[test]
- fn on_done_normal_stop_with_answer_has_no_warning() {
+ fn queued_placeholder_animates() {
let mut app = test_app();
- app.apply(StreamEvent::Token {
- text: "The answer.".into(),
- });
- app.on_done("stop".into(), None);
- assert!(!app
- .transcript
- .iter()
- .any(|l| row_text(l).contains("finished")));
+ app.submit_user("go".into());
+ app.message_queue.push_back("next".into());
+ app.spinner_frame = 5;
+ let row = render_rows(&mut app, 80, 12)
+ .into_iter()
- .find(|r| r.contains("Queued"))
++ .find(|r| r.contains("Pending"))
+ .expect("queued row present");
+ assert!(row.contains(SPINNER[5]), "expected frame 5 glyph: {row:?}");
}
+ /// Native reasoning events (a dedicated `reasoning_content` field) drive the
+ /// same orange thinking placeholder as inline `<`> tags, are folded into the
+ /// transcript like a wrapped block on flush, and never enter the wire answer.
#[test]
- fn on_done_truncated_finish_warns_in_timeline() {
+ fn native_reasoning_drives_thinking_placeholder_and_folds_on_flush() {
let mut app = test_app();
+ app.submit_user("go".into());
+ app.apply(StreamEvent::Reasoning {
+ text: "ponder the plan".into(),
+ });
+ // Pinned off: this asserts on the *word*, and the sweep overwrites a
+ // letter of it with the travelling glyph. `wave` is on by default now,
+ // so leaving it to the process state makes this test depend on
+ // whichever config the shared cell resolved first.
+ let row = with_wave_glyph(None, || {
+ render_rows(&mut app, 80, 12)
+ .into_iter()
- .find(|r| r.contains("(Esc to cancel, type to queue next message)"))
++ .find(|r| r.contains("(Esc to cancel, type to steer the agent)"))
+ .expect("running placeholder present")
+ });
+ assert!(
+ THINKING_WORDS.iter().any(|w| row.contains(w)),
+ "expected a thinking synonym while reasoning: {row:?}"
+ );
+ // The answer arrives: reasoning stays folded into a summary row.
app.apply(StreamEvent::Token {
- text: "partial".into(),
+ text: "Here is the answer".into(),
});
- app.on_done("length".into(), None);
- let warn = app
- .transcript
- .iter()
- .map(row_text)
- .find(|t| t.contains("finished early"))
- .unwrap();
- assert!(warn.contains("length"), "warn: {warn}");
+ app.on_done("stop".into(), None);
+ assert_eq!(
+ app.reasoning_blocks.len(),
+ 1,
+ "reasoning folded into one block"
+ );
+ // The wire history carries the answer, with the reasoning preserved on
+ // the message's `reasoning_content` rather than inlined into `content`.
+ let last = app.history.last().expect("assistant turn in history");
+ assert_eq!(last["content"], "Here is the answer");
+ assert_eq!(
+ last["reasoning_content"], "ponder the plan",
+ "reasoning must be preserved for resend: {last}"
+ );
+ assert!(
+ !last["content"]
+ .as_str()
+ .unwrap_or_default()
+ .contains("ponder the plan"),
+ "reasoning must not be inlined into the answer content: {last}"
+ );
}
+ /// The resend policy reaches the wire: a default session sends an unchanged
+ /// body (the loop defaults to resending), and opting out forwards the flag.
#[test]
- fn on_done_stop_without_answer_warns() {
+ fn send_reasoning_opt_out_is_forwarded_in_the_request_body() {
let mut app = test_app();
- // Only reasoning, no answer prose (or an empty/malformed completion).
- app.apply(StreamEvent::Token {
- text: "<think>hmm</think>".into(),
- });
- app.on_done("stop".into(), None);
- assert!(app
- .transcript
- .iter()
- .any(|l| row_text(l).contains("finished with no answer")));
+ app.submit_user("go".into());
+ assert!(
+ app.body().get("send_reasoning").is_none(),
+ "the default session must send an unchanged body"
+ );
+ app.send_reasoning = false;
+ assert_eq!(
+ app.body()["send_reasoning"],
+ serde_json::json!(false),
+ "opting out must reach the loop"
+ );
}
+ /// A cancelled turn keeps the reasoning that produced its partial answer,
+ /// so the next prompt resumes with the same context the model had.
#[test]
- fn permission_prompt_does_not_break_tool_folding() {
+ fn cancel_preserves_native_reasoning_on_the_partial_answer() {
let mut app = test_app();
- for id in ["c1", "c2"] {
- app.apply(StreamEvent::ToolCall {
- id: id.into(),
- name: "bash".into(),
- args: json!({ "command": "grep -n foo src/" }),
- });
- app.apply(StreamEvent::PermissionRequest {
- request_id: format!("p-{id}"),
- tool_name: "bash".into(),
- capability: "exec".into(),
- path: None,
- command: Some("grep -n foo src/".into()),
- diff: None,
- prompt_kind: "exec".into(),
- offers_always: true,
- });
- app.pending_queue.clear(); // simulate approval
- app.apply(StreamEvent::ToolResult {
- id: id.into(),
- content: "ok".into(),
- is_error: false,
- diff: None,
- });
- }
- // Both gated calls stayed in one running group despite the prompts.
- assert!(app.tool_group.is_some());
- let tool_rows = app
- .transcript
- .iter()
- .filter(|l| {
- let t = row_text(l);
- t.contains("Executing") || t.contains("Running") || t.contains("Ran")
- })
- .count();
- assert_eq!(tool_rows, 1);
+ app.submit_user("go".into());
+ app.apply(StreamEvent::Reasoning {
+ text: "half a thought".into(),
+ });
+ app.apply(StreamEvent::Token {
+ text: "Partial answer".into(),
+ });
+ app.cancel_run();
+ let last = app.history.last().expect("assistant turn in history");
+ assert_eq!(last["content"], "Partial answer");
+ assert_eq!(last["reasoning_content"], "half a thought");
}
+ /// A turn with no native reasoning must not grow a `reasoning_content` key:
+ /// providers that reject unknown assistant fields see an unchanged shape.
#[test]
- fn diff_tool_result_keeps_separate_rows_and_panel() {
+ fn a_turn_without_reasoning_adds_no_reasoning_key_to_history() {
let mut app = test_app();
- app.apply(StreamEvent::ToolCall {
- id: "c1".into(),
- name: "edit".into(),
- args: json!({ "path": "a.txt" }),
- });
- let before = app.transcript.len();
- app.apply(StreamEvent::ToolResult {
- id: "c1".into(),
- content: "edited".into(),
- is_error: false,
- diff: Some("- old\n+ new".into()),
+ app.submit_user("go".into());
+ app.apply(StreamEvent::Token {
+ text: "Just an answer".into(),
});
- // Call row preserved; result row + boxed diff appended below it.
- assert!(app.transcript.len() > before);
- let joined: String = app
- .transcript
- .iter()
- .map(row_text)
- .collect::<Vec<_>>()
- .join("\n");
- // The call row resolves to past tense once the result lands.
- assert!(joined.contains("Edited a.txt"), "{joined}");
- assert!(!joined.contains("Editing a.txt"), "{joined}");
- assert!(joined.contains('┌') && joined.contains('┘'), "{joined}");
+ app.on_done("stop".into(), None);
+ let last = app.history.last().expect("assistant turn in history");
+ assert_eq!(last["content"], "Just an answer");
+ assert!(
+ last.get("reasoning_content").is_none(),
+ "no reasoning streamed, so the key must be absent: {last}"
+ );
}
+ /// The `[thinking]` badge and the orange placeholder must close when the
+ /// answer starts streaming: native segments live until the next flush, so
+ /// only the "newest segment is still at the tail" check can tell the two
+ /// apart. Without it the badge shimmered through the whole answer and
+ /// `[thought for Ns]` never appeared for a `reasoning_content` provider.
#[test]
- fn diff_tool_row_reads_present_tense_until_its_result_lands() {
+ fn native_reasoning_badge_closes_once_prose_starts() {
let mut app = test_app();
- app.apply(StreamEvent::ToolCall {
- id: "c1".into(),
- name: "write".into(),
- args: json!({ "path": "a.txt", "content": "x" }),
+ app.submit_user("go".into());
+ app.apply(StreamEvent::Reasoning {
+ text: "ponder".into(),
});
- assert!(row_text(app.transcript.last().unwrap()).contains("Writing a.txt"));
- app.apply(StreamEvent::ToolResult {
- id: "c1".into(),
- content: "boom".into(),
- is_error: true,
- diff: None,
+ assert_eq!(
+ app.reasoning_status().map(|(w, _)| w),
+ Some("thinking".to_string())
+ );
+ assert!(app.reasoning_open(), "reasoning is live");
+ app.apply(StreamEvent::Token {
+ text: "Answer".into(),
});
- let joined: String = app
- .transcript
+ assert!(!app.reasoning_open(), "prose has started");
+ assert_eq!(
+ app.reasoning_status().map(|(w, _)| w),
+ Some("thought for 0s".to_string()),
+ "the closed block reports its duration"
+ );
+ }
+
+ fn detail_text(block: &super::ReasoningBlock) -> String {
+ block
+ .detail
.iter()
- .map(row_text)
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|sp| sp.content.as_ref())
+ .collect::<String>()
+ })
.collect::<Vec<_>>()
- .join("\n");
- assert!(joined.contains("✗ Wrote a.txt"), "{joined}");
- assert!(app.pending_rows.is_empty());
+ .join(" ")
}
+ /// Reasoning that mentions a `</think>` tag must not close the block it is
+ /// wrapped in and spill the rest of the thought into the answer.
#[test]
- fn summarize_result_first_line_plus_count() {
- assert_eq!(summarize_result("only line", 80), "only line");
- assert_eq!(summarize_result("a\nb\nc", 80), "a (+2 lines)");
- assert_eq!(summarize_result(" \nreal\nx", 80), "real (+1 lines)");
- // Collapses internal whitespace runs (e.g. columnar grep output).
- assert_eq!(summarize_result("a b\tc", 80), "a b c");
- // Truncates the head to max.
- assert_eq!(summarize_result("abcdefgh", 4), "abc…");
+ fn native_reasoning_mentioning_a_close_tag_stays_reasoning() {
+ let mut app = test_app();
+ app.submit_user("go".into());
+ app.apply(StreamEvent::Reasoning {
+ text: "the </think> tag is tricky".into(),
+ });
+ app.on_done("stop".into(), None);
+ let rows = render_rows(&mut app, 80, 30).join("\n");
+ assert!(
+ !rows.contains("tag is tricky"),
+ "reasoning rendered as answer prose: {rows}"
+ );
+ assert_eq!(app.reasoning_blocks.len(), 1, "one folded reasoning block");
+ // Kept verbatim: reasoning never shares a string with the prose, so
+ // there is no block for the tag to close and nothing to neutralize.
+ assert!(
+ detail_text(&app.reasoning_blocks[0]).contains("</think>"),
+ "the tag is preserved as written: {}",
+ detail_text(&app.reasoning_blocks[0])
+ );
}
- /// Run one turn that reasons, calls a diff-producing tool, and answers,
- /// leaving it persisted (messages + journal) in `app.agent_dir`.
- fn record_full_turn(app: &mut App) {
- app.submit_user("do it".to_string());
- app.apply(StreamEvent::Token {
- text: "<think>my private reasoning</think>".into(),
- });
- app.apply(StreamEvent::ToolCall {
- id: "c1".into(),
- name: "write".into(),
- args: json!({ "path": "a.txt", "content": "x" }),
+ /// Interleaved reasoning keeps emission order: each stretch folds where it
+ /// streamed instead of every thought being hoisted above all the prose.
+ #[test]
+ fn interleaved_native_reasoning_keeps_emission_order() {
+ let mut app = test_app();
+ app.submit_user("go".into());
+ app.apply(StreamEvent::Reasoning {
+ text: "first thought".into(),
});
- app.apply(StreamEvent::ToolResult {
- id: "c1".into(),
- content: "wrote 1 line".into(),
- is_error: false,
- diff: Some("@@ created file @@\n+ 1 | x".into()),
+ app.apply(StreamEvent::Token {
+ text: "Part one.".into(),
});
- app.apply(StreamEvent::MessagesUpdated {
- messages: vec![
- json!({ "role": "user", "content": "do it" }),
- json!({ "role": "assistant", "content": "", "tool_calls": [{
- "id": "c1",
- "type": "function",
- "function": { "name": "write", "arguments": "{\"path\":\"a.txt\"}" },
- }]}),
- json!({ "role": "tool", "tool_call_id": "c1", "content": "wrote 1 line" }),
- ],
+ app.apply(StreamEvent::Reasoning {
+ text: "second thought".into(),
});
app.apply(StreamEvent::Token {
- text: "Answer.".into(),
+ text: " Part two.".into(),
});
app.on_done("stop".into(), None);
- app.join_journal();
+ assert_eq!(app.reasoning_blocks.len(), 2, "two separate stretches");
+ // Journaled apart: prose verbatim, each stretch at the offset it
+ // streamed at, so a replay rebuilds the order without parsing markers.
+ let DisplayEntry::Assistant { text, reasoning } = app
+ .display_log
+ .iter()
+ .rev()
+ .find(|e| matches!(e, DisplayEntry::Assistant { .. }))
+ .expect("assistant entry journaled")
+ else {
+ unreachable!()
+ };
+ assert_eq!(text, "Part one. Part two.");
+ assert_eq!(
+ reasoning,
+ &vec![
+ ReasoningSeg {
+ at: 0,
+ text: "first thought".into()
+ },
+ ReasoningSeg {
+ at: 9,
+ text: "second thought".into()
+ },
+ ]
+ );
+ // The wire answer is prose only; both thoughts ride along on
+ // `reasoning_content`, concatenated in emission order.
+ let last = app.history.last().expect("assistant turn in history");
+ assert_eq!(last["content"], "Part one. Part two.");
+ assert_eq!(
+ last["reasoning_content"], "first thoughtsecond thought",
+ "both stretches must be preserved for resend: {last}"
+ );
}
- #[tokio::test]
- async fn resume_restores_reasoning_tool_rows_and_diffs() {
+ #[test]
+ fn compact_tokens_keeps_a_stable_width() {
+ assert_eq!(compact_tokens(0), "0");
+ assert_eq!(compact_tokens(840), "840");
+ assert_eq!(compact_tokens(1_100), "1.1K");
+ assert_eq!(compact_tokens(43_000), "43K");
+ assert_eq!(compact_tokens(1_500_000), "1.5M");
+ }
+
+ /// The turn receipt reports what the whole turn cost, which for a
+ /// tool-using turn is more than the final request's usage.
+ #[test]
+ fn turn_stats_sum_output_across_requests() {
let mut app = test_app();
- record_full_turn(&mut app);
- let live: String = app
- .transcript
- .iter()
- .map(row_text)
- .collect::<Vec<_>>()
- .join("\n");
+ app.submit_user("go".into());
+ for _ in 0..3 {
+ app.apply(StreamEvent::TurnUsage {
+ usage: Usage {
+ prompt_tokens: Some(40_000),
+ completion_tokens: Some(500),
+ total_tokens: Some(40_500),
+ },
+ });
+ }
+ assert_eq!(app.turn_output_tokens, 1_500);
+ assert_eq!(app.turn_prompt_tokens, 40_000);
- let mut fresh = test_app();
- fresh.agent_dir = app.agent_dir.clone();
- apply_resume(&mut fresh, &ResumeTarget::Latest).await;
- let resumed: String = fresh
+ app.on_done("stop".into(), None);
+ let out: String = app
.transcript
.iter()
.map(row_text)
@@@ -13840,316 -25633,529 +25978,532 @@@
}
#[tokio::test]
- async fn apply_resume_latest_restores_history_and_model() {
+ async fn help_lists_effort_aliases_and_marks_effort_canonical() {
let mut app = test_app();
- let history = vec![
- json!({ "role": "user", "content": "first" }),
- json!({ "role": "assistant", "content": "reply" }),
- ];
- let id =
- super::super::cli_save_thread(&app.agent_dir, None, "saved-model", &history, None)
- .unwrap();
+ run_command(&mut app, "help", &no_mcp()).await;
+ let text: String = app.transcript.iter().map(row_text).collect();
+ // `/effort` desc has no alias prefix; each alias row derives from
+ // `alias_of` and must read as an alias of `/effort`. Signatures are
+ // wider than the 18-char pad, so assert on the embedded parts rather
+ // than exact column alignment.
+ assert!(
+ text.contains("alias of /effort"),
+ "alias annotation missing: {text}"
+ );
+ assert!(
+ text.contains("/think [low|medium|high] alias of /effort"),
+ "think row: {text}"
+ );
+ assert!(
+ text.contains("/reasoning [low|medium|high] alias of /effort"),
+ "reasoning row: {text}"
+ );
+ assert!(
+ text.contains("/effort [low|medium|high] Set reasoning effort"),
+ "canonical effort row must not be an alias: {text}"
+ );
+ }
- let mut fresh = test_app();
- fresh.agent_dir = app.agent_dir.clone();
- apply_resume(&mut fresh, &ResumeTarget::Latest).await;
+ #[test]
+ fn partial_json_field_reads_a_truncated_value() {
+ // Closed value.
+ let done = r#"{"path":"a.html","content":"<h1>hi</h1>"}"#;
+ assert_eq!(partial_json_field(done, "path"), Some("a.html"));
+ assert_eq!(partial_json_field(done, "content"), Some("<h1>hi</h1>"));
- assert_eq!(fresh.thread_id.as_deref(), Some(id.as_str()));
- assert_eq!(fresh.history, history);
- assert_eq!(fresh.model, "saved-model");
- let joined: String = fresh
- .transcript
- .iter()
- .map(row_text)
- .collect::<Vec<_>>()
- .join("\n");
- assert!(joined.contains("first") && joined.contains("reply"), "{joined}");
+ // Cut mid-value: everything that arrived is the value.
+ let cut = r#"{"path":"a.html","content":"<!doctype html>\n<html"#;
+ assert_eq!(
+ partial_json_field(cut, "content"),
+ Some(r#"<!doctype html>\n<html"#)
+ );
- // Re-saving the resumed session updates the same thread, not a new one.
- app.agent_dir = fresh.agent_dir.clone();
- let same =
- super::super::cli_save_thread(&app.agent_dir, Some(&id), "saved-model", &fresh.history, None)
- .unwrap();
- assert_eq!(same, id);
- assert_eq!(super::super::list_threads_in(&app.agent_dir).unwrap().len(), 1);
- }
+ // Cut before the field even opens.
+ assert_eq!(partial_json_field(r#"{"path":"a.htm"#, "content"), None);
- #[tokio::test]
- async fn resuming_restores_the_recall_history() {
- let app = test_app();
- let history = vec![
- json!({ "role": "user", "content": "first" }),
- json!({ "role": "assistant", "content": "reply" }),
- json!({ "role": "user", "content": "second" }),
- ];
- super::super::cli_save_thread(&app.agent_dir, None, "saved-model", &history, None).unwrap();
+ // An escaped quote inside the value does not end it.
+ let escaped = r#"{"content":"say \"hi\" now"#;
+ assert_eq!(
+ partial_json_field(escaped, "content"),
+ Some(r#"say \"hi\" now"#)
+ );
- let mut fresh = test_app();
- fresh.agent_dir = app.agent_dir.clone();
- // A line typed before the resume belongs to the session being replaced.
- fresh.record_submitted("stale");
- apply_resume(&mut fresh, &ResumeTarget::Latest).await;
+ // The field name occurring inside an earlier value is not the field.
+ let decoy = r#"{"path":"my\"content\".txt","content":"real"#;
+ assert_eq!(partial_json_field(decoy, "content"), Some("real"));
+ }
- assert_eq!(fresh.input_history, vec!["first", "second"]);
- assert!(fresh.recall_prev(), "Up recalls instead of scrolling");
- assert_eq!(fresh.input, "second");
- assert!(fresh.recall_prev());
- assert_eq!(fresh.input, "first");
- assert_eq!(fresh.scrollback, 0, "recall must not scroll the transcript");
+ #[test]
+ fn unescape_partial_json_string_survives_a_cut_escape() {
+ assert_eq!(unescape_partial_json_string(r#"a\nb"#), "a\nb");
+ // Dangling backslash: the escape's payload hasn't arrived.
+ assert_eq!(unescape_partial_json_string(r#"a\nb\"#), "a\nb");
+ // An even run is a real escaped backslash, keep it.
+ assert_eq!(unescape_partial_json_string(r#"a\\"#), r"a\");
+ // Partial \u escape.
+ assert_eq!(unescape_partial_json_string(r#"hi \u26"#), "hi ");
+ assert_eq!(unescape_partial_json_string(r#"hi ☃"#), "hi ☃");
}
- #[tokio::test]
- async fn apply_resume_notes_when_nothing_to_resume() {
- let mut app = test_app();
- apply_resume(&mut app, &ResumeTarget::Latest).await;
- let joined: String = app
- .transcript
+ /// A streaming `write` previews the file as it arrives instead of sitting
+ /// on a featureless "Preparing write" spinner.
+ #[test]
+ fn streaming_write_previews_the_body() {
+ let body: String = (1..=20).map(|n| format!("line {n}\\n")).collect();
+ let mut call = super::StartingCall::new("c1".into(), "write".into());
+ call.args = format!(r#"{{"path":"game.html","content":"{body}"#);
+ let text: Vec<String> = starting_call_lines(&mut call, "⠋")
.iter()
- .map(row_text)
- .collect::<Vec<_>>()
- .join("\n");
- assert!(joined.contains(super::super::NO_SESSION_TO_RESUME), "{joined}");
- assert!(app.thread_id.is_none());
- assert!(app.history.is_empty());
- }
+ .map(line_text)
+ .collect();
+ let joined = text.join("\n");
- #[test]
- fn sort_threads_recent_orders_newest_first() {
- let mut threads = vec![
- json!({ "id": "a", "updated": 100.0 }),
- json!({ "id": "b", "updated": 300.0 }),
- json!({ "id": "c", "created": 200.0 }),
- json!({ "id": "d" }),
- ];
- super::sort_threads_recent(&mut threads);
- let ids: Vec<&str> = threads.iter().map(|t| t["id"].as_str().unwrap()).collect();
- assert_eq!(ids, ["b", "c", "a", "d"]);
+ assert!(
+ joined.contains("Write: game.html"),
+ "no destination: {joined}"
+ );
+ assert!(
+ joined.contains("… (streaming)"),
+ "no streaming marker: {joined}"
+ );
+ // 20 body lines plus the empty one after the final \n = 21; a 12-line
+ // window leaves 9 behind.
+ assert!(
+ joined.contains("… (9 earlier lines)"),
+ "wrong elision: {joined}"
+ );
+ assert!(
+ !joined.contains("line 9\n"),
+ "line 9 is outside the window: {joined}"
+ );
+ assert!(
+ joined.contains("line 20"),
+ "tail should include the newest line: {joined}"
+ );
+ // Numbers are absolute, not window-relative, and right-aligned.
+ assert!(
+ text.iter().any(|l| l.contains(" 10 line 10")),
+ "gutter: {text:?}"
+ );
+ assert!(
+ text.iter().any(|l| l.contains(" 20 line 20")),
+ "gutter: {text:?}"
+ );
}
+ /// The preview is derived from an append-only buffer, so an unchanged
+ /// length means unchanged content -- the 50ms render tick must not pay for
+ /// a full rescan of a file-sized argument on every frame.
#[test]
- fn thread_display_name_prefers_title() {
- let base = std::path::Path::new("/nonexistent");
- assert_eq!(super::thread_display_name(base, "id", Some("My Title")), "My Title");
- assert_eq!(super::thread_display_name(base, "id", Some(" padded ")), "padded");
+ fn preview_is_only_rederived_when_new_bytes_arrive() {
+ let mut call = super::StartingCall::new("c1".into(), "write".into());
+ call.args = r#"{"path":"a.html","content":"one\ntwo"#.into();
+ call.refresh_preview();
+ let first = call.preview_at;
+ assert_eq!(
+ tail_text(&call),
+ Some(vec!["one".to_string(), "two".to_string()])
+ );
+
+ // Same bytes: the cache holds and nothing is recomputed.
+ call.preview.tail = Some(vec![vec![ratatui::text::Span::raw("sentinel")]]);
+ call.refresh_preview();
+ assert_eq!(tail_text(&call), Some(vec!["sentinel".to_string()]));
+ assert_eq!(call.preview_at, first);
+
+ // New bytes invalidate it.
+ call.args.push_str(r#"\nthree"#);
+ call.refresh_preview();
+ assert_eq!(
+ tail_text(&call),
+ Some(vec![
+ "one".to_string(),
+ "two".to_string(),
+ "three".to_string()
+ ])
+ );
}
+ /// Before `content` opens there is nothing to preview, but the path is
+ /// already worth showing.
#[test]
- fn truncate_is_char_safe() {
- assert_eq!(super::truncate("héllo wörld", 5), "héll…");
- assert_eq!(super::truncate("short", 20), "short");
+ fn streaming_write_shows_the_path_before_the_body() {
+ let mut call = super::StartingCall::new("c1".into(), "write".into());
+ call.args = r#"{"path":"game.html","cont"#.into();
+ let text: Vec<String> = starting_call_lines(&mut call, "⠋")
+ .iter()
+ .map(line_text)
+ .collect();
+ assert_eq!(text.len(), 1);
+ assert!(
+ text[0].contains("Preparing write: game.html"),
+ "got {text:?}"
+ );
}
+ /// Tools other than `write` keep the plain throbber -- there is no file
+ /// body to stream.
#[test]
- fn parse_command_splits_name_and_arg() {
- assert_eq!(parse_command("resume abc123"), ("resume", "abc123"));
- assert_eq!(parse_command("help"), ("help", ""));
- assert_eq!(parse_command(" resume abc "), ("resume", "abc"));
- assert_eq!(parse_command(""), ("", ""));
+ fn other_tools_keep_the_plain_throbber() {
+ let mut call = super::StartingCall::new("c1".into(), "bash".into());
+ call.args = r#"{"command":"ls -la"#.into();
+ let text: Vec<String> = starting_call_lines(&mut call, "⠋")
+ .iter()
+ .map(line_text)
+ .collect();
+ assert_eq!(text.len(), 1);
+ assert!(text[0].contains("Preparing bash"), "got {text:?}");
}
+ /// A `write` of minified or single-line content (a bundle, a JSON blob)
+ /// grows one preview line without bound. Unclamped that line is
+ /// re-highlighted in full on every argument delta -- syntect is linear in
+ /// line length -- and its wrapped row count floods the viewport the
+ /// preview lives in. Both are bounded by clamping the line itself.
#[test]
- fn mouse_tracking_requests_buttons_wheel_and_held_drags() {
- assert!(MOUSE_TRACK_ON.contains("?1000h"), "buttons and wheel");
- assert!(MOUSE_TRACK_ON.contains("?1002h"), "drag while held");
- assert!(MOUSE_TRACK_ON.contains("?1006h"), "SGR coordinates");
+ fn an_enormous_single_preview_line_is_clamped() {
+ let mut call = super::StartingCall::new("c1".into(), "write".into());
+ let body = "x".repeat(20_000);
+ call.args = format!(r#"{{"path":"bundle.js","content":"{body}"#);
+ let text: Vec<String> = starting_call_lines(&mut call, "\u{280b}")
+ .iter()
+ .map(line_text)
+ .collect();
+
+ let body_row = text
+ .iter()
+ .find(|l| l.contains("xxx"))
+ .unwrap_or_else(|| panic!("no body row in {text:?}"));
+ let xs = body_row.chars().filter(|&c| c == 'x').count();
assert!(
- !MOUSE_TRACK_ON.contains("1003"),
- "any-motion would report every idle pointer move: {MOUSE_TRACK_ON:?}"
+ xs <= super::STREAM_MAX_LINE_CHARS,
+ "preview line kept {xs} chars of a 20000-char line"
);
assert!(
- ALT_SCROLL_SAVE_OFF.contains("?1007l"),
- "the wheel must never arrive as arrow keys"
+ body_row.contains('\u{2026}'),
+ "clamped line is not marked as truncated: {body_row:?}"
);
- assert!(ALT_SCROLL_RESTORE.contains("?1007r"), "restore on exit");
}
+ /// Which end survives the clamp differs by line: a finished line reads
+ /// from its start, while the last one is still open and is where new bytes
+ /// land, so watching its tail is what shows the write progressing.
#[test]
- fn linear_selection_spans_whole_rows_between_the_ends() {
- let sel = Selection {
- anchor: (5, 1),
- head: (2, 3),
- mode: SelectionMode::Linear,
- dragging: false,
- moved: true,
- };
- assert_eq!(sel.spans(10), vec![(1, 5, 9), (2, 0, 9), (3, 0, 2)]);
+ fn a_clamped_line_keeps_its_head_unless_it_is_the_open_one() {
+ let mut call = super::StartingCall::new("c1".into(), "write".into());
+ let filler = "-".repeat(super::STREAM_MAX_LINE_CHARS * 2);
+ call.args =
+ format!(r#"{{"path":"a.txt","content":"HEAD1{filler}TAIL1\nHEAD2{filler}TAIL2"#);
+ let text: Vec<String> = starting_call_lines(&mut call, "\u{280b}")
+ .iter()
+ .map(line_text)
+ .collect();
+ let joined = text.join("\n");
+
+ assert!(
+ joined.contains("HEAD1"),
+ "finished line lost its head: {joined}"
+ );
+ assert!(
+ !joined.contains("TAIL1"),
+ "finished line kept its tail: {joined}"
+ );
+ assert!(
+ joined.contains("TAIL2"),
+ "open line lost its tail: {joined}"
+ );
+ assert!(
+ !joined.contains("HEAD2"),
+ "open line kept its head: {joined}"
+ );
}
- #[test]
- fn selection_spans_are_direction_independent() {
- let forward = Selection {
- anchor: (5, 1),
- head: (2, 3),
- mode: SelectionMode::Linear,
- dragging: false,
- moved: true,
- };
- let backward = Selection {
- anchor: (2, 3),
- head: (5, 1),
- ..forward
- };
- assert_eq!(forward.spans(10), backward.spans(10));
+ /// A file-sized `write` streams its arguments in thousands of deltas. One
+ /// repaint each is thousands of full frames for a preview that only ever
+ /// shows its last few lines, so a burst already sitting in the channel is
+ /// drained into a single frame.
+ #[tokio::test]
+ async fn a_burst_of_stream_events_is_drained_into_one_frame() {
+ let mut app = test_app();
+ let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
+ let mut current = Some(CurrentRun {
+ rx,
++ steering: mpsc::unbounded_channel().1,
+ handle: tokio::spawn(async {}),
+ });
+
+ tx.send(StreamEvent::ToolCallStarted {
+ id: "c1".into(),
+ name: "write".into(),
+ })
+ .expect("send");
+ for _ in 0..64 {
+ tx.send(StreamEvent::ToolCallArgsDelta {
+ id: "c1".into(),
+ delta: "ab".into(),
+ })
+ .expect("send");
+ }
+
+ let drained = drain_stream_events(&mut app, &mut current).await;
+ assert_eq!(drained, 65, "the whole burst must land in one pass");
+ assert_eq!(app.starting[0].args.len(), 128);
+ assert!(current.is_some(), "an unfinished run must stay live");
+
+ // Nothing left: draining an empty channel is a no-op, not a stall.
+ assert_eq!(drain_stream_events(&mut app, &mut current).await, 0);
}
- #[test]
- fn block_selection_spans_a_rectangle() {
- let sel = Selection {
- anchor: (6, 3),
- head: (2, 1),
- mode: SelectionMode::Block,
- dragging: false,
- moved: true,
- };
- assert_eq!(sel.spans(10), vec![(1, 2, 6), (2, 2, 6), (3, 2, 6)]);
+ /// The drain must not starve input handling: a run that emits faster than
+ /// the loop can drain still has to yield back to the keyboard poll.
+ #[tokio::test]
+ async fn the_drain_is_bounded() {
+ let mut app = test_app();
+ let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
+ let mut current = Some(CurrentRun {
+ rx,
++ steering: mpsc::unbounded_channel().1,
+ handle: tokio::spawn(async {}),
+ });
+ for _ in 0..(super::EVENT_DRAIN_MAX + 50) {
+ tx.send(StreamEvent::Token { text: "x".into() })
+ .expect("send");
+ }
+ assert_eq!(
+ drain_stream_events(&mut app, &mut current).await,
+ super::EVENT_DRAIN_MAX
+ );
}
- /// A block drag lifts one column out of a table without the neighbours a
- /// linear drag would sweep up.
- #[test]
- fn selection_text_reads_cells_and_trims_row_padding() {
- let area = Rect::new(0, 0, 12, 3);
- let mut buf = Buffer::empty(area);
- buf.set_string(0, 0, "alpha one", Style::new());
- buf.set_string(0, 1, "beta two", Style::new());
+ /// A terminal event inside a burst ends the run there and stops the drain,
+ /// so nothing queued behind it is applied to a finished run.
+ #[tokio::test]
+ async fn the_drain_stops_at_a_terminal_event() {
+ let mut app = test_app();
+ let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
+ let mut current = Some(CurrentRun {
+ rx,
++ steering: mpsc::unbounded_channel().1,
+ handle: tokio::spawn(async {}),
+ });
+ tx.send(StreamEvent::Token { text: "hi".into() })
+ .expect("send");
+ tx.send(StreamEvent::Done {
+ stop_reason: "stop".into(),
+ usage: None,
+ })
+ .expect("send");
+ tx.send(StreamEvent::Token {
+ text: "late".into(),
+ })
+ .expect("send");
- let linear = Selection {
- anchor: (0, 0),
- head: (10, 1),
- mode: SelectionMode::Linear,
- dragging: false,
- moved: true,
- };
- assert_eq!(selection_text(&buf, linear, area), "alpha one\nbeta two");
+ let drained = drain_stream_events(&mut app, &mut current).await;
+ assert_eq!(drained, 2, "drain must stop on the terminal event");
+ assert!(current.is_none(), "the run was not cleared");
+ }
- let block = Selection {
- anchor: (8, 0),
- head: (10, 1),
- mode: SelectionMode::Block,
- dragging: false,
- moved: true,
- };
- assert_eq!(selection_text(&buf, block, area), "one\ntwo");
+ /// A path-carrying tool that isn't `write` must be named as itself.
+ #[test]
+ fn starting_throbber_names_the_actual_tool() {
+ for name in ["read", "edit", "list"] {
+ let mut call = super::StartingCall::new("c1".into(), name.into());
+ call.args = r#"{"path":"src/main.rs"#.into();
+ let text: Vec<String> = starting_call_lines(&mut call, "⠋")
+ .iter()
+ .map(line_text)
+ .collect();
+ assert_eq!(text.len(), 1);
+ assert!(
+ text[0].contains(&format!("Preparing {name}: src/main.rs")),
+ "got {text:?}"
+ );
+ assert!(!text[0].contains("write"), "wrong tool named: {text:?}");
+ }
+ }
- // A row selected past its text keeps no trailing padding.
- let padded = Selection {
- anchor: (0, 0),
- head: (11, 0),
- mode: SelectionMode::Linear,
- dragging: false,
- moved: true,
- };
- assert_eq!(selection_text(&buf, padded, area), "alpha one");
+ #[test]
+ fn stream_error_clears_the_preparing_throbber() {
+ let mut app = test_app();
+ app.submit_user("do a thing".into());
+ app.apply(StreamEvent::ToolCallStarted {
+ id: "c1".into(),
+ name: "write".into(),
+ });
+ assert!(!app.starting.is_empty());
+ app.on_error("stream".into(), "connection reset".into());
+ assert!(
+ app.starting.is_empty(),
+ "an aborted run leaves a throbber naming a tool that never ran"
+ );
}
+ /// A run can end normally while a tool call was still streaming its
+ /// arguments: the upstream stops mid-call and the assembled completion
+ /// carries no `tool_calls`, so no `ToolCall` ever supersedes the throbber
+ /// and no `ToolResult` ever resolves the pending row.
#[test]
- fn a_drag_selects_instead_of_toggling_the_row_under_it() {
+ fn normal_done_clears_an_unfinished_tool_call() {
let mut app = test_app();
- app.apply(StreamEvent::ToolCall {
+ app.submit_user("do a thing".into());
+ app.apply(StreamEvent::ToolCallStarted {
id: "c1".into(),
- name: "grep".into(),
- args: json!({ "pattern": "foo" }),
+ name: "write".into(),
});
- let idx = app.tool_group.as_ref().expect("group open").idx;
- app.transcript_rect = Rect::new(0, 0, 80, 10);
- app.last_scroll = 0;
- app.row_index = vec![Some(idx)];
+ app.apply(StreamEvent::ToolCall {
+ id: "c2".into(),
+ name: "write".into(),
+ args: serde_json::json!({ "path": "a.txt", "content": "x" }),
+ });
+ assert_eq!(app.starting.len(), 1);
+ assert_eq!(app.pending_rows.len(), 1);
- handle_mouse(
- &mut app,
- mouse_at(MouseEventKind::Down(MouseButton::Left), 5, 1),
- );
- handle_mouse(
- &mut app,
- mouse_at(MouseEventKind::Drag(MouseButton::Left), 30, 1),
+ app.on_done("stop".into(), None);
+
+ assert!(
+ app.starting.is_empty(),
+ "a finished run leaves a throbber naming a tool that never ran"
);
- handle_mouse(
- &mut app,
- mouse_at(MouseEventKind::Up(MouseButton::Left), 30, 1),
+ assert!(
+ app.pending_rows.is_empty(),
+ "a finished run leaves a call row spinning for a result that never comes"
);
+ }
- assert!(app.expanded.is_empty(), "a drag must not expand the row");
- assert!(app.copy_armed, "the release arms the copy");
- let sel = app.selection.expect("selection held after release");
- assert!(!sel.dragging);
- assert_eq!(sel.spans(80), vec![(1, 5, 30)]);
+ /// An `await_subagent` whose result never lands is the same orphan: the
+ /// child cannot outlive the run whose stream carried its events.
+ #[test]
+ fn terminal_events_clear_an_unresolved_await() {
+ for terminal in [0, 1] {
+ let mut app = test_app();
+ app.submit_user("do a thing".into());
+ app.awaiting
+ .push(("c1".into(), "run-1".into(), "explorer".into()));
+ if terminal == 0 {
+ app.on_done("stop".into(), None);
+ } else {
+ app.on_error("stream".into(), "connection reset".into());
+ }
+ assert!(
+ app.awaiting.is_empty(),
+ "an awaiting throbber outlived the run that could resolve it"
+ );
+ }
}
+ /// The deltas have to actually reach the call they belong to.
#[test]
- fn alt_drag_selects_a_block() {
+ fn args_deltas_accumulate_onto_the_starting_call() {
let mut app = test_app();
- handle_mouse(
- &mut app,
- MouseEvent {
- kind: MouseEventKind::Down(MouseButton::Left),
- column: 5,
- row: 1,
- modifiers: KeyModifiers::ALT,
- },
- );
- assert_eq!(
- app.selection.expect("selection").mode,
- SelectionMode::Block
- );
+ app.apply(StreamEvent::ToolCallStarted {
+ id: "c1".into(),
+ name: "write".into(),
+ });
+ for delta in [r#"{"path":"a"#, r#".html","content":"he"#, "llo"] {
+ app.apply(StreamEvent::ToolCallArgsDelta {
+ id: "c1".into(),
+ delta: delta.into(),
+ });
+ }
+ let call = &mut app.starting[0];
+ call.refresh_preview();
+ assert_eq!(call.preview.path.as_deref(), Some("a.html"));
+ assert_eq!(tail_text(call), Some(vec!["hello".to_string()]));
+
+ // A delta for an unknown call is dropped, not panicked on.
+ app.apply(StreamEvent::ToolCallArgsDelta {
+ id: "nope".into(),
+ delta: "x".into(),
+ });
+ assert_eq!(app.starting.len(), 1);
}
- #[test]
- fn scrolling_drops_a_finished_selection() {
+ /// `/help` is the home for keybindings now that the footer no longer
+ /// carries them, so every advertised binding has to reach the listing.
+ #[tokio::test]
+ async fn help_lists_every_keybinding() {
let mut app = test_app();
- handle_mouse(
- &mut app,
- mouse_at(MouseEventKind::Down(MouseButton::Left), 5, 1),
- );
- handle_mouse(
- &mut app,
- mouse_at(MouseEventKind::Drag(MouseButton::Left), 9, 1),
- );
- handle_mouse(&mut app, mouse_at(MouseEventKind::ScrollUp, 5, 1));
- assert!(app.selection.is_none(), "content moved out from under it");
+ run_command(&mut app, "help", &no_mcp()).await;
+ let text: String = app.transcript.iter().map(row_text).collect();
+ for (keys, description) in KEY_BINDINGS {
+ assert!(text.contains(keys), "missing keys {keys:?} in: {text}");
+ assert!(
+ text.contains(description),
+ "missing description {description:?} in: {text}"
+ );
+ }
}
+ /// The idle footer carries no cheat sheet at all -- not on a fresh
+ /// session, not while typing the first message, not after it. Discovery
+ /// lives in the opening transcript note and `/help`.
#[test]
- fn a_held_drag_past_an_edge_scrolls_the_transcript() {
+ fn idle_footer_never_shows_a_cheat_sheet() {
let mut app = test_app();
- app.transcript_rect = Rect::new(0, 0, 80, 10);
- handle_mouse(
- &mut app,
- mouse_at(MouseEventKind::Down(MouseButton::Left), 5, 5),
- );
+ type Setup<'a> = (&'a str, &'a dyn Fn(&mut App));
+ let states: [Setup; 3] = [
+ ("fresh", &|_: &mut App| {}),
+ ("typing", &|a: &mut App| {
+ for c in "hel".chars() {
+ a.input_insert(c);
+ }
+ }),
+ ("used", &|a: &mut App| {
+ a.history.push(json!({ "role": "user", "content": "hi" }));
+ }),
+ ];
+ for (label, setup) in states {
+ setup(&mut app);
+ let rows = render_rows(&mut app, 80, 12);
+ // The dock is the last row: location on the left, hints on the
+ // right. Idle contributes no hints, so only the location shows.
+ let dock = rows.last().expect("non-empty render").trim();
+ assert!(
+ dock.starts_with("📂") && !dock.contains("Ctrl-"),
+ "{label}: idle dock should carry no cheat sheet, got {dock:?}"
+ );
+ }
+ }
- // Above the top border: scroll back through history.
- handle_mouse(
- &mut app,
- mouse_at(MouseEventKind::Drag(MouseButton::Left), 5, 0),
+ /// A transient detail (`stop_reason=...`, `cancelled`) still owns the
+ /// footer row, and starts at the same column the hints used to.
+ #[test]
+ fn idle_footer_still_shows_transient_detail() {
+ let mut app = test_app();
+ app.detail = "stop_reason=stop".into();
+ let rows = render_rows(&mut app, 80, 12);
+ let dock = rows.last().unwrap();
+ assert!(dock.trim_end().ends_with("stop_reason=stop"), "{dock:?}");
+ assert!(
+ dock.contains("/tmp/repo"),
+ "location keeps its place: {dock:?}"
);
- autoscroll_selection(&mut app);
- autoscroll_selection(&mut app);
- assert_eq!(app.scrollback, 2);
+ }
- // Below the last body row: scroll back toward the newest output.
- handle_mouse(
- &mut app,
- mouse_at(MouseEventKind::Drag(MouseButton::Left), 5, 9),
+ /// Working dir + branch share the single dock row below the input with the
+ /// key hints -- not split across the top and bottom of the screen, and not
+ /// spending a row of their own.
+ #[test]
+ fn path_shares_the_dock_row_with_the_hints() {
+ let mut app = test_app();
+ app.git_branch = Some("goal/general-agent".into());
+ app.status = Status::Running;
+ let rows = render_rows(&mut app, 100, 12);
+ let dock = rows.last().expect("non-empty render");
+ assert!(
+ dock.contains("/tmp/repo") && dock.contains("goal/general-agent"),
+ "expected dir+branch on the dock row, got {dock:?}"
);
- autoscroll_selection(&mut app);
- assert_eq!(app.scrollback, 1);
-
- // Inside the viewport, nothing moves.
- handle_mouse(
- &mut app,
- mouse_at(MouseEventKind::Drag(MouseButton::Left), 5, 4),
+ assert!(
+ dock.contains("cancel") && dock.contains("scroll"),
+ "hints share the same row: {dock:?}"
);
- autoscroll_selection(&mut app);
- assert_eq!(app.scrollback, 1);
-
- // A released drag stops scrolling even parked past the edge.
- handle_mouse(
- &mut app,
- mouse_at(MouseEventKind::Up(MouseButton::Left), 5, 0),
+ // Nothing but the header above the transcript any more.
+ assert!(
+ !rows[1].contains("/tmp/repo"),
+ "path line should no longer render at the top: {:?}",
+ rows[1]
);
- app.selection.as_mut().expect("selection").head = (5, 0);
- autoscroll_selection(&mut app);
- assert_eq!(app.scrollback, 1);
}
#[test]
@@@ -15318,35 -27464,34 +27812,34 @@@
}
#[tokio::test]
- async fn todo_reminder_suppressed_while_ask_pending() {
+ async fn plan_review_execute_switches_normal_and_queues_continuation() {
+ use crate::core::agent::plan::RunMode;
let mut app = test_app();
- seed_open_todos(&mut app);
+ app.run_mode = RunMode::Plan;
+ app.apply(StreamEvent::TodoUpdate {
+ list: staged_todos(),
+ });
+ app.status = Status::Running; // an in-flight turn owns the ask
let registry = crate::core::agent::interaction::new_registry();
- let (request_id, _rx) = crate::core::agent::interaction::register(&registry).await;
+ let (request_id, receiver) = crate::core::agent::interaction::register(&registry).await;
app.apply(StreamEvent::AskRequest {
request_id,
- request: ask_request(false, false),
+ request: plan_review_request(),
+ timeout_secs: None,
});
- finish_clean_turn(&mut app);
- assert!(!app.want_start, "a pending ask blocks the reminder boundary");
- }
-
- #[test]
- fn todo_reminder_deduplicates_repeats() {
- let mut app = test_app();
- seed_open_todos(&mut app);
- finish_clean_turn(&mut app);
- assert!(app.want_start);
- assert!(last_history_content(&app).contains("unfinished todos"));
- // The loop consumes want_start when it spawns the continuation run.
- app.want_start = false;
- // Model responds without changing todos and yields again: the same open
- // summary must not fire a second identical reminder.
- finish_clean_turn(&mut app);
- assert!(!app.want_start, "identical reminder must not repeat");
+ // Default selection 0 = "Execute plan"; Enter submits.
+ press_ask(&mut app, &registry, KeyCode::Enter).await;
+ assert_eq!(app.run_mode, RunMode::Normal);
assert!(
- !last_history_content(&app).contains("unfinished todos"),
- "last message should be the assistant answer, not a repeat reminder"
+ app.message_queue
+ .iter()
- .any(|m| m.as_str() == "Proceed with the plan."),
++ .any(|m| m.text == "Proceed with the plan."),
+ "execute must queue a continuation turn"
+ );
+ let answers = receiver.await.unwrap().unwrap();
+ assert_eq!(
+ answers[0].selected,
+ vec![crate::core::agent::plan::EXECUTE_PLAN_LABEL]
);
}