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.

feat(agent-tui): accept user steering at safe agent loop boundaries

tikikune69ddc4ae590
diff --git a/docs/specs/agent-loop-steering.md b/docs/specs/agent-loop-steering.md
deleted file mode 100644
index 59856d125..000000000
--- a/docs/specs/agent-loop-steering.md
+++ /dev/null
@@ -1,55 +0,0 @@
-# Active-loop steering for Jan Agent CLI TUI
-
-Status: proposed; runtime implementation is not included in this specification.
-
-Tracking issue: https://github.com/janhq/jan/issues/8863
-
-## Problem
-
-Messages submitted while Jan Agent CLI TUI is working currently wait until the entire agent turn finishes. A correction such as "use pnpm instead" should be able to jump into the active loop before the next model step, rather than wait until the agent has completed work based on outdated instructions.
-
-This follows up on #8485 (message queuing for agent turns). That request made input non-blocking with turn-end dequeueing; this request changes when the active agent consumes a user's follow-up.
-
-## Goal
-
-Let users steer the running Jan agent, similar to the requested Claude Code interaction: submit a message while the agent is working and have it considered at the next safe boundary within the same run.
-
-Scope: Jan Agent CLI TUI and the shared loop plumbing needed to support it. No change to desktop/web queue behavior in this request.
-
-## Requested UX
-
-1. Keep the composer editable while the agent is running.
-2. Enter submits a steering message to the active run, rather than waiting for the whole turn to finish.
-3. Show that the message is pending until the loop acknowledges consumption, then display it once in the transcript.
-4. Consume steering before the next model request, after any in-flight tool-call batch has recorded all its results. Do not forcibly abort tools or leave unmatched tool calls.
-5. Preserve submission order when multiple messages arrive. A message submitted as a run finishes must not disappear or be processed twice; fall back to a new turn when it can no longer join the active run.
-6. Preserve image attachments and resolved @path context for each submitted message.
-7. Keep cancellation discoverable for messages not yet consumed; make clear that removing a pending message does not undo tool execution.
-
-## Technical Considerations
-
-- `App::submit_user_text` in `src-tauri/src/core/cli/tui.rs` currently stores running-time input in `message_queue`; `dequeue_next` submits it after a turn ends.
-- Add a session/run-scoped input channel and consumption acknowledgement between the TUI and `src-tauri/src/core/agent/loop.rs`.
-- Keep canonical model history, visible transcript, and persisted session history consistent, with exactly-once message delivery.
-- Do not inject user text between an assistant tool-call message and its corresponding tool results.
-- Handle completion/error/cancel races and session switch/reset without dropping input or leaking it to another session or a child agent.
-- Preserve dedicated permission/question input routing; steering must not implicitly approve a tool or answer an outstanding question.
-- Keep callers without a steering channel behaving as before.
-
-## Acceptance Criteria
-
-- [ ] During a multi-step tool run, a follow-up is included in the next eligible model request before the original turn finishes.
-- [ ] Multiple follow-ups are consumed once, in submission order.
-- [ ] In-flight tool results remain correctly paired and tool execution is not forcibly interrupted.
-- [ ] Pending/consumed state is visible; consumed messages appear once in transcript and persisted history.
-- [ ] Attachments and @path expansions remain associated with the correct message.
-- [ ] Completion, error, cancellation, and session-switch races neither lose nor duplicate messages.
-- [ ] Permission/question prompts and non-TUI callers do not regress.
-- [ ] Tests cover safe-boundary injection, ordering, acknowledgement, lifecycle races, and history consistency.
-
-## Branches
-
-- Base branch for the implementation PR: `dev`.
-- This supersedes only the turn-end delivery behavior requested in #8485, not its non-blocking-input goal.
-
-/cc @thinhlpg
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index db538b0ae..e8914a140 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -935,15 +935,21 @@ pub(crate) async fn run_server_side_openai_orchestration(
#[cfg(not(feature = "cli"))]
const PROXY_DEFAULT_MAX_TURNS: u64 = 8;
-/// Streaming entry point. Emits `Step`/`ToolCall`/`ToolResult` progress events
-/// and exactly one terminal `Done`/`Error` derived from the final result, while
-/// still returning the completion JSON (or error) to the caller.
-pub(crate) async fn run_orchestration_streamed(
+/// A safe-boundary handoff. The TUI retains pending input until it can reply,
+/// so cancellation and late submissions use the ordinary next-turn path.
+pub(crate) struct SteeringRequest {
+ pub run_mode: crate::core::agent::plan::RunMode,
+ pub messages: Vec<serde_json::Value>,
+ pub reply: tokio::sync::oneshot::Sender<Vec<serde_json::Value>>,
+}
+
+pub(crate) async fn run_orchestration_steered(
events: &mpsc::UnboundedSender<StreamEvent>,
json_body: &serde_json::Value,
args: &OrchestrationArgs,
+ steering: Option<&mpsc::UnboundedSender<SteeringRequest>>,
) -> Result<serde_json::Value, String> {
- let result = orchestrate_inner(events, json_body, args).await;
+ let result = orchestrate_inner(events, json_body, args, steering).await;
match &result {
Ok(completion) => {
let _ = events.send(StreamEvent::Done {
@@ -961,6 +967,17 @@ pub(crate) async fn run_orchestration_streamed(
result
}
+/// Streaming entry point. Emits `Step`/`ToolCall`/`ToolResult` progress events
+/// and exactly one terminal `Done`/`Error` derived from the final result, while
+/// still returning the completion JSON (or error) to the caller.
+pub(crate) async fn run_orchestration_streamed(
+ events: &mpsc::UnboundedSender<StreamEvent>,
+ json_body: &serde_json::Value,
+ args: &OrchestrationArgs,
+) -> Result<serde_json::Value, String> {
+ run_orchestration_steered(events, json_body, args, None).await
+}
+
/// Restrict the collected MCP tools to `allowed` (by tool name), pruning both
/// the OpenAI tool array and the tool->server routing map in lockstep.
fn apply_tool_allowlist(
@@ -1093,6 +1110,7 @@ async fn orchestrate_inner(
events: &mpsc::UnboundedSender<StreamEvent>,
json_body: &serde_json::Value,
args: &OrchestrationArgs,
+ steering: Option<&mpsc::UnboundedSender<SteeringRequest>>,
) -> Result<serde_json::Value, String> {
let OrchestrationArgs {
client,
@@ -1397,7 +1415,7 @@ async fn orchestrate_inner(
auto_approve: *auto_approve,
run_mode,
};
- let result = run_turn_cycle(
+ let result = run_turn_cycle_steered(
events,
json_body,
&model_id,
@@ -1410,6 +1428,7 @@ async fn orchestrate_inner(
run_mode,
todo_registry.as_ref(),
force_first_tool,
+ steering,
)
.await;
// On a clean exit, wait for any subagents the model dispatched but never
@@ -1420,7 +1439,7 @@ async fn orchestrate_inner(
}
result
} else {
- run_turn_cycle(
+ run_turn_cycle_steered(
events,
json_body,
&model_id,
@@ -1433,6 +1452,7 @@ async fn orchestrate_inner(
run_mode,
todo_registry.as_ref(),
force_first_tool,
+ steering,
)
.await
}
@@ -1568,8 +1588,48 @@ fn body_session_budget(json_body: &serde_json::Value) -> Option<u64> {
.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
+}
+
+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 (reply, response) = tokio::sync::oneshot::channel();
+ 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,
@@ -1585,6 +1645,7 @@ async fn run_turn_cycle(
// 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>,
+ steering: Option<&mpsc::UnboundedSender<SteeringRequest>>,
) -> Result<serde_json::Value, String> {
// `max_turns == 0` is the normal case: the session token budget and user
// cancellation are the real guards, so a run isn't cut off mid-task by a
@@ -1605,6 +1666,7 @@ async fn run_turn_cycle(
let mut closeout_nudged = false;
while unlimited || turn < max_turns {
+ receive_steering(steering, &mut conversation_messages, run_mode).await;
let _ = events.send(StreamEvent::Step {
index: (turn as u32) + 1,
max: max_turns as u32,
@@ -1685,6 +1747,18 @@ async fn run_turn_cycle(
.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) {
+ let mut continued = conversation_messages.clone();
+ continued.push(serde_json::json!({ "role": "assistant", "content": final_text }));
+ 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
@@ -2089,6 +2163,81 @@ 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"}]})]);
+ 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();
+ 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(); }
+ });
+ 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();
+ 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"}]})]);
+ 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(); }
+ });
+ 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();
+ 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"][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_eq!(messages.len(), 1);
+ }
+
#[tokio::test]
async fn turn_cycle_executes_tool_then_returns_final() {
let (tx, mut rx) = mpsc::unbounded_channel();
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index 1eef73e98..56b0a68f4 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -44,7 +44,7 @@ use super::journal::{self, DisplayEntry};
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_streamed, OrchestrationArgs, PermissionRegistry};
+use crate::core::agent::r#loop::{run_orchestration_steered, OrchestrationArgs, PermissionRegistry, SteeringRequest};
use tauri_plugin_agent_tools::tools::gate::PermissionDecision;
use tauri_plugin_agent_tools::workspace;
@@ -385,9 +385,36 @@ impl LoginPrompt {
/// A spawned agent run: the event stream and its abort handle.
struct CurrentRun {
rx: mpsc::UnboundedReceiver<StreamEvent>,
+ steering: mpsc::UnboundedReceiver<SteeringRequest>,
handle: JoinHandle<()>,
}
+enum RunEvent {
+ Stream(Option<StreamEvent>),
+ Steering(SteeringRequest),
+}
+
+struct PendingMessage {
+ text: String,
+ message: serde_json::Value,
+ images: Vec<String>,
+ display: bool,
+ 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,
+ 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 {
@@ -1278,9 +1305,8 @@ struct App {
copy_request: Option<String>,
/// (when, line count) of the last copy, for the transient dock notice.
copied: Option<(Instant, usize)>,
- /// Messages queued while a run is in progress, dequeued automatically
- /// when the current turn finishes.
- message_queue: std::collections::VecDeque<String>,
+ /// Pending input, consumed at the next safe loop boundary or next run.
+ message_queue: std::collections::VecDeque<PendingMessage>,
/// Canonical session todo list projection, kept in sync via
/// `StreamEvent::TodoUpdate`. Empty = no todos declared this session.
todos: crate::core::agent::todo::TodoList,
@@ -2245,11 +2271,6 @@ impl App {
}
}
- /// 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
@@ -2282,13 +2303,6 @@ impl App {
self.note("not signed in — run /login to sign in to Tokamak 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;
- }
- self.ensure_base_snapshot();
let images = if display {
std::mem::take(&mut self.pending_images)
} else {
@@ -2303,16 +2317,35 @@ impl App {
} 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 pending = PendingMessage {
+ 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()));
+ 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);
self.display_log.push(DisplayEntry::User {
- text: text.clone(),
- images: names,
+ text: pending.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"),
@@ -2414,13 +2447,40 @@ impl App {
return;
}
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()
));
- self.submit_user(next);
+ self.start_pending_message(next);
+ }
+ }
+
+ 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();
+ 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");
+ 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
@@ -4310,17 +4370,24 @@ fn strip_system_xml_tags(text: &str) -> String {
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, handle }
+ CurrentRun { rx, steering, handle }
}
/// Await the next event of the active run, or park forever when idle.
-async fn next_event(current: &mut Option<CurrentRun>) -> Option<StreamEvent> {
+async fn next_event(current: &mut Option<CurrentRun>) -> RunEvent {
match current {
- Some(c) => c.rx.recv().await,
+ Some(c) => tokio::select! {
+ // Preserve event order: commit streamed prose/tool results before
+ // showing the user message accepted at their boundary.
+ biased;
+ event = c.rx.recv() => RunEvent::Stream(event),
+ Some(request) = c.steering.recv() => RunEvent::Steering(request),
+ },
None => pending().await,
}
}
@@ -4890,7 +4957,7 @@ async fn chat_loop<B: Backend>(
}
}
ev = next_event(&mut current) => match ev {
- Some(StreamEvent::Done { stop_reason, usage }) => {
+ 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
@@ -4900,7 +4967,7 @@ async fn chat_loop<B: Backend>(
app.compact_request = Some(CompactKind::Auto);
}
}
- Some(StreamEvent::Error { code, message }) => {
+ RunEvent::Stream(Some(StreamEvent::Error { code, message })) => {
app.on_error(code, message);
current = None;
}
@@ -4908,12 +4975,13 @@ async fn chat_loop<B: Backend>(
// 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.
- Some(ev @ StreamEvent::Step { .. }) => {
+ RunEvent::Stream(Some(ev @ StreamEvent::Step { .. })) => {
app.apply(ev);
age_closed_todos(app).await;
}
- Some(other) => app.apply(other),
- None => {
+ 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();
@@ -5775,7 +5843,7 @@ 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)",
},
SlashCommand {
name: "/login",
@@ -6573,13 +6641,13 @@ async fn todo_command(app: &mut App, arg: &str) {
/// message. Notes the result or when the queue is empty.
fn cancel_command(app: &mut App, arg: &str) {
if app.message_queue.is_empty() {
- app.note("no queued messages to cancel");
+ app.note("no pending messages to cancel");
return;
}
if arg.is_empty() {
let n = app.message_queue.len();
app.message_queue.clear();
- app.note(&format!("cancelled all {n} queued message(s)"));
+ app.note(&format!("cancelled all {n} pending message(s)"));
return;
}
// Try to parse as a 1-indexed position
@@ -6593,7 +6661,7 @@ fn cancel_command(app: &mut App, arg: &str) {
}
let removed = app.message_queue.remove(idx - 1);
if let Some(text) = removed {
- let preview = truncate(&text, 40);
+ let preview = truncate(&text.text, 40);
app.note(&format!(
"cancelled message #{idx}: \"{preview}\" ({} remaining)",
app.message_queue.len()
@@ -9083,7 +9151,7 @@ fn input_box(app: &App) -> Paragraph<'static> {
Paragraph::new(Line::from(vec![
Span::styled(format!("{} ", app.spinner()), Style::new().cyan()),
Span::styled(
- "working… (Esc to cancel, type to queue next message)",
+ "working… (Esc to cancel, type to steer the agent)",
Style::new().dim().italic(),
),
]))
@@ -9093,7 +9161,7 @@ fn input_box(app: &App) -> Paragraph<'static> {
Paragraph::new(Line::from(vec![
Span::styled(format!("{} ", app.spinner()), Style::new().yellow()),
Span::styled(
- format!("⏳ Queued ({n}) — Esc to cancel, type to add more"),
+ format!("⏳ Pending ({n}) — /cancel to remove, type to steer"),
Style::new().yellow(),
),
]))
@@ -9103,7 +9171,7 @@ fn input_box(app: &App) -> Paragraph<'static> {
// Same `› ` arrow 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"
};
@@ -9232,7 +9300,7 @@ fn footer_spans(app: &App) -> Vec<Span<'static>> {
);
if queue_count > 0 {
s.insert(0, Span::styled(
- format!("⏳ Queued ({queue_count}) "),
+ format!("⏳ Pending ({queue_count}) "),
Style::new().yellow().bold(),
));
}
@@ -9248,7 +9316,7 @@ fn footer_spans(app: &App) -> Vec<Span<'static>> {
let mut s = vec![Span::raw(" ")];
if queue_count > 0 {
s.insert(0, Span::styled(
- format!("⏳ Queued ({queue_count}) "),
+ format!("⏳ Pending ({queue_count}) "),
Style::new().yellow().bold(),
));
}
@@ -9269,7 +9337,8 @@ fn footer_spans(app: &App) -> Vec<Span<'static>> {
#[cfg(test)]
mod tests {
- use super::SessionLimits;
+ use super::{SessionLimits, SteeringRequest, RunEvent, next_event, cancel_command};
+ use tokio::sync::mpsc;
use super::{journal, DisplayEntry};
use super::{
age_closed_todos, apply_resume, assistant_is_awaiting_user_answer, brand, build_user_message,
@@ -9385,6 +9454,143 @@ mod tests {
TestApp { app, _dir: dir }
}
+ 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)
+ }
+
+ #[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.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_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);
+ 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"})]);
+ }
+
+ #[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();
+ 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(_)));
+ }
+
+ #[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.submit_user("follow-up".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");
+ }
+ }
+
+ #[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!(restored.message_queue.is_empty());
+ }
+
/// 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};
@@ -14350,7 +14556,7 @@ mod tests {
assert_ne!(first, later, "row must change as the frame advances");
// The wording itself does not move, only the glyph.
- assert!(later.contains("(Esc to cancel, type to queue next message)"), "{later:?}");
+ assert!(later.contains("(Esc to cancel, type to steer the agent)"), "{later:?}");
}
/// A queued-message row is still a running row, so it animates too.
@@ -14362,7 +14568,7 @@ mod tests {
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:?}");
}
@@ -15750,7 +15956,7 @@ mod tests {
assert!(
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();