use crate::approve::Choice;
use crate::status::Status;
use eclipse_core::commands::{self, Command, Completion, Front};
use eclipse_core::usage::TurnUsage;
use eclipse_core::AgentEvent;
#[derive(Debug, Clone, PartialEq)]
pub enum Block {
Welcome(Welcome),
User(String),
Reply {
text: String,
done: bool,
},
Reasoning {
text: String,
done: bool,
},
Tool {
call_id: String,
name: String,
args: String,
state: ToolState,
output: String,
},
Note {
kind: NoteKind,
text: String,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolState {
Running,
Ok,
Failed,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NoteKind {
Info,
Warn,
Error,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Activity {
Idle,
Requesting,
Streaming,
Tool(String),
}
pub struct Approval {
pub tool: String,
pub summary: String,
pub choice: Choice,
pub reply: tokio::sync::oneshot::Sender<Choice>,
}
impl Approval {
pub fn new(tool: String, summary: String, reply: tokio::sync::oneshot::Sender<Choice>) -> Self {
Self {
tool,
summary,
choice: Choice::Deny,
reply,
}
}
pub fn move_by(&mut self, step: isize) {
let n = Choice::ALL.len() as isize;
let at = Choice::ALL
.iter()
.position(|c| *c == self.choice)
.unwrap_or(Choice::ALL.len() - 1) as isize;
let next = (at + step).rem_euclid(n) as usize;
self.choice = Choice::ALL[next];
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum Action {
None,
Resume(String),
Submit(String),
CancelRun,
Quit,
Command(String),
PickModel(String, Option<String>),
PickProvider(String),
}
#[derive(Debug, Default)]
pub struct History {
entries: Vec<String>,
at: Option<usize>,
draft: String,
}
impl History {
pub fn push(&mut self, line: &str) {
if line.trim().is_empty() || self.entries.last().map(String::as_str) == Some(line) {
return;
}
self.entries.push(line.to_string());
}
#[cfg(test)]
pub fn entries(&self) -> &[String] {
&self.entries
}
fn previous(&mut self, current: &str) -> Option<String> {
if self.entries.is_empty() {
return None;
}
let next = match self.at {
None => {
self.draft = current.to_string();
self.entries.len() - 1
}
Some(0) => 0,
Some(i) => i - 1,
};
self.at = Some(next);
Some(self.entries[next].clone())
}
fn next(&mut self) -> Option<String> {
let at = self.at?;
if at + 1 >= self.entries.len() {
self.at = None;
return Some(std::mem::take(&mut self.draft));
}
self.at = Some(at + 1);
Some(self.entries[at + 1].clone())
}
fn reset(&mut self) {
self.at = None;
self.draft.clear();
}
}
pub struct App {
pub blocks: Vec<Block>,
pub printed: usize,
pub fold: Vec<Option<bool>>,
pub reasoning: Option<crate::reasoning_cli::Live>,
pub reasoning_control: Option<eclipse_core::provider::Reasoning>,
pub frozen_display: Vec<crate::reasoning_cli::Mode>,
pub echo: Option<usize>,
pub input: String,
pub cursor: usize,
pub history: History,
pub show_thinking: bool,
pub status: Status,
pub activity: Activity,
pub approval: Option<Approval>,
pub running: bool,
pub session: Option<String>,
pub profile: Option<String>,
pub model: String,
pub picker: Option<Picker>,
pub menu: Option<Menu>,
pub menu_dismissed: bool,
pub models: Vec<String>,
pub listing_models: bool,
pub workspace: String,
pub quit: bool,
pub ticks: u64,
pub last_error: Option<String>,
pub place: Option<eclipse_core::config::Where>,
pub yolo: crate::yolo::Yolo,
pub config_path: Option<std::path::PathBuf>,
pub pastes: Vec<Paste>,
pub update: Option<eclipse_core::update::Behind>,
pub update_watch: Option<eclipse_core::update::Watch>,
}
pub use eclipse_core::paste::{Paste, PASTE_INLINE_LIMIT};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Welcome {
pub version: String,
pub model: String,
pub endpoint: String,
pub profile: Option<String>,
pub workspace: String,
pub groups: Vec<(String, Vec<String>)>,
pub skills: Vec<(String, Vec<String>)>,
pub approvals: bool,
}
impl Welcome {
pub fn skill_count(&self) -> usize {
self.skills.iter().map(|(_, names)| names.len()).sum()
}
}
pub fn ago(updated_ms: u64) -> String {
if updated_ms == 0 {
return "never".to_string();
}
let now = eclipse_core::session::now_ms();
let secs = now.saturating_sub(updated_ms) / 1000;
match secs {
0..=59 => "just now".to_string(),
60..=3599 => format!("{}m ago", secs / 60),
3600..=86_399 => format!("{}h ago", secs / 3600),
86_400..=2_591_999 => format!("{}d ago", secs / 86_400),
_ => format!("{}mo ago", secs / 2_592_000),
}
}
pub fn blocks_from(records: &[eclipse_core::session::Record]) -> (Vec<Block>, bool) {
use eclipse_core::message::Role;
let mut blocks: Vec<Block> = Vec::new();
let mut waiting: Vec<(String, usize)> = Vec::new();
for record in records {
let message = &record.message;
match message.role {
Role::System => {} Role::User => {
if let Some(text) = &message.content {
if !text.trim().is_empty() {
blocks.push(Block::User(text.clone()));
}
}
}
Role::Assistant => {
if let Some(reasoning) = &message.reasoning {
if !reasoning.trim().is_empty() {
blocks.push(Block::Reasoning {
text: reasoning.clone(),
done: true,
});
}
}
if let Some(text) = &message.content {
if !text.trim().is_empty() {
blocks.push(Block::Reply {
text: text.clone(),
done: true,
});
}
}
for call in &message.tool_calls {
waiting.push((call.id.clone(), blocks.len()));
blocks.push(Block::Tool {
call_id: call.id.clone(),
name: call.function.name.clone(),
args: call.function.arguments.clone(),
state: ToolState::Running,
output: String::new(),
});
}
}
Role::Tool => {
let id = message.tool_call_id.clone().unwrap_or_default();
let output = message.content.clone().unwrap_or_default();
let slot = waiting
.iter()
.position(|(call_id, _)| *call_id == id)
.map(|i| waiting.remove(i).1);
match slot {
Some(index) => {
if let Block::Tool {
state, output: out, ..
} = &mut blocks[index]
{
*out = output;
*state = ToolState::Ok;
}
}
None => blocks.push(Block::Note {
kind: NoteKind::Warn,
text: format!("a tool result arrived with no matching call ({id})"),
}),
}
}
}
}
for (_, index) in waiting.drain(..) {
if let Block::Tool { state, output, .. } = &mut blocks[index] {
*state = ToolState::Failed;
*output = "no result: the run was interrupted before this call returned".to_string();
}
}
let interrupted = blocks.iter().any(|b| {
matches!(
b,
Block::Tool {
state: ToolState::Failed,
output,
..
} if output.starts_with("no result:")
)
});
(blocks, interrupted)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Picked {
pub id: String,
pub title: Option<String>,
pub note: String,
pub ago: String,
pub messages: usize,
pub preview: String,
}
impl Picked {
pub fn label(&self) -> String {
match &self.title {
Some(title) if !title.trim().is_empty() => title.clone(),
_ => {
let preview = self.preview.trim();
if preview.is_empty() {
"untitled".to_string()
} else {
preview.to_string()
}
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PickerKind {
#[default]
Sessions,
Provider,
Model,
Tasks,
}
#[derive(Debug, Clone, Default)]
pub struct Picker {
pub kind: PickerKind,
pub title: &'static str,
pub items: Vec<Picked>,
pub all: Vec<Picked>,
pub query: String,
pub cursor: usize,
pub route: Option<String>,
}
fn fuzzy_at(needle: &str, hay: &str) -> Option<usize> {
let hay: Vec<char> = hay.chars().flat_map(char::to_lowercase).collect();
let mut from = 0;
let mut last = 0;
for want in needle.chars().flat_map(char::to_lowercase) {
if want.is_whitespace() {
continue;
}
let found = hay.get(from..)?.iter().position(|c| *c == want)?;
last = from + found;
from = last + 1;
}
Some(last)
}
impl Picker {
fn of(
kind: PickerKind,
title: &'static str,
items: Vec<Picked>,
cursor: usize,
route: Option<String>,
) -> Self {
Self {
kind,
title,
all: items.clone(),
items,
query: String::new(),
cursor,
route,
}
}
pub fn move_by(&mut self, delta: isize) {
if self.items.is_empty() {
return;
}
let last = self.items.len() - 1;
let next = self.cursor as isize + delta;
self.cursor = next.clamp(0, last as isize) as usize;
}
pub fn current(&self) -> Option<&Picked> {
self.items.get(self.cursor)
}
pub fn type_char(&mut self, c: char) {
if c.is_control() {
return;
}
self.query.push(c);
self.refilter();
}
pub fn backspace(&mut self) -> bool {
if self.query.pop().is_none() {
return false;
}
self.refilter();
true
}
pub fn clear_query(&mut self) -> bool {
if self.query.is_empty() {
return false;
}
self.query.clear();
self.refilter();
true
}
fn refilter(&mut self) {
self.cursor = 0;
if self.query.trim().is_empty() {
self.items = self.all.clone();
return;
}
let mut scored: Vec<(usize, usize, Picked)> = self
.all
.iter()
.enumerate()
.filter_map(|(i, p)| {
let hay = format!("{} {} {}", p.label(), p.preview, p.id);
fuzzy_at(&self.query, &hay).map(|at| (at, i, p.clone()))
})
.collect();
scored.sort_by_key(|(at, i, _)| (*at, *i));
self.items = scored.into_iter().map(|(_, _, p)| p).collect();
}
pub fn count_label(&self) -> String {
let what = match self.kind {
PickerKind::Sessions => "stored",
PickerKind::Provider => "configured",
PickerKind::Model => "served",
PickerKind::Tasks => "tasks",
};
if self.query.trim().is_empty() {
format!("{} {}", self.all.len(), what)
} else {
format!("{} of {} {}", self.items.len(), self.all.len(), what)
}
}
#[cfg(test)]
pub fn cursor_name(&self) -> Option<&str> {
self.current().map(|p| p.id.as_str())
}
}
#[derive(Debug, Clone, Default)]
pub struct Menu {
pub items: Vec<&'static Command>,
pub cursor: usize,
}
impl Menu {
pub fn move_by(&mut self, delta: isize) {
if self.items.is_empty() {
return;
}
let last = self.items.len() - 1;
let next = self.cursor as isize + delta;
self.cursor = next.clamp(0, last as isize) as usize;
}
pub fn current(&self) -> Option<&'static Command> {
self.items.get(self.cursor).copied()
}
}
impl Welcome {
pub fn tool_count(&self) -> usize {
self.groups.iter().map(|(_, names)| names.len()).sum()
}
}
impl App {
pub fn new(status: Status, model: &str, workspace: &str, profile: Option<String>) -> Self {
Self {
blocks: Vec::new(),
reasoning: None,
reasoning_control: None,
frozen_display: Vec::new(),
input: String::new(),
cursor: 0,
history: History::default(),
printed: 0,
fold: Vec::new(),
echo: None,
show_thinking: false,
session: status.session.clone(),
status,
activity: Activity::Idle,
approval: None,
running: false,
profile,
model: model.to_string(),
models: Vec::new(),
listing_models: false,
picker: None,
menu: None,
menu_dismissed: false,
workspace: workspace.to_string(),
quit: false,
ticks: 0,
last_error: None,
place: None,
yolo: crate::yolo::Yolo::new(false),
config_path: None,
pastes: Vec::new(),
update: None,
update_watch: None,
}
}
pub fn reread_update(&mut self) -> bool {
let Some(watch) = &self.update_watch else {
return false;
};
let now = watch.read();
if now == self.update {
return false;
}
self.update = now;
true
}
pub fn set_sessions(&mut self, items: Vec<Picked>) {
if items.is_empty() {
self.note(
NoteKind::Info,
"no sessions yet — this one becomes the first when you send something",
);
self.picker = None;
return;
}
self.picker = Some(Picker::of(PickerKind::Sessions, "session", items, 0, None));
}
pub fn refresh_effort(&mut self) {
let Some(report) = self.effort_report() else {
self.status.effort = None;
return;
};
if self.status.effort.as_ref().is_some_and(|e| {
e.label == report.label
&& e.session == report.session
&& e.by_default == report.by_default
}) {
return;
}
self.status.effort = Some(report);
}
pub fn effort_report(&self) -> Option<eclipse_core::reasoning::InForce> {
let live = self.reasoning.as_ref()?;
Some(eclipse_core::reasoning::report_for(
&live.dial,
self.reasoning_control.as_ref(),
))
}
pub fn set_tasks(&mut self, tasks: Vec<eclipse_core::tasks::Task>) {
if tasks.is_empty() {
self.note(
NoteKind::Info,
"no background tasks — `/bg <prompt>` starts one",
);
self.picker = None;
return;
}
let items: Vec<Picked> = tasks
.into_iter()
.map(|t| {
let state = t.state_now();
Picked {
id: t.session.clone(),
title: Some(t.prompt.clone()),
note: format!("{} · {}", state.word(), ago(t.updated_ms)),
ago: ago(t.updated_ms),
messages: 0,
preview: if t.settled() {
if t.detail.is_empty() {
t.last.clone()
} else {
format!("{} ({})", t.last, t.detail)
}
} else {
format!("pid {} · {}", t.pid, t.last)
},
}
})
.collect();
self.picker = Some(Picker::of(PickerKind::Tasks, "task", items, 0, None));
}
pub fn open_models_from(&mut self, route: Option<String>, models: Vec<String>) {
if models.is_empty() {
self.note(
NoteKind::Warn,
"the endpoint named no models; set `[provider] model` by hand",
);
self.picker = None;
return;
}
let current = self.model.clone();
let items: Vec<Picked> = models
.into_iter()
.map(|name| Picked {
note: if name == current {
"current".to_string()
} else {
String::new()
},
title: Some(name.clone()),
id: name,
ago: String::new(),
messages: 0,
preview: String::new(),
})
.collect();
let cursor = items.iter().position(|p| p.id == current).unwrap_or(0);
self.picker = Some(Picker::of(PickerKind::Model, "model", items, cursor, route));
}
pub fn open_providers(
&mut self,
routes: &[eclipse_core::router::RouteInfo],
current: Option<&str>,
) {
let items: Vec<Picked> = routes
.iter()
.map(|r| Picked {
id: r.name.clone(),
note: if Some(r.name.as_str()) == current {
"current".to_string()
} else {
String::new()
},
title: Some(r.name.clone()),
ago: String::new(),
messages: 0,
preview: r.endpoint.clone(),
})
.collect();
let cursor = current
.and_then(|c| items.iter().position(|p| p.id == c))
.unwrap_or(0);
self.picker = Some(Picker::of(
PickerKind::Provider,
"provider",
items,
cursor,
None,
));
}
pub fn clear_transcript(&mut self) {
self.blocks.clear();
self.printed = 0;
self.fold.clear();
self.echo = None;
}
pub fn apply_session(&mut self, id: String, blocks: Vec<Block>, interrupted: bool) {
self.picker = None;
self.clear_transcript();
self.blocks = blocks;
self.session = Some(id.clone());
self.status.session = Some(id);
if interrupted {
self.note(
NoteKind::Warn,
"the last turn was interrupted mid-tool-call; continuing answers that call with \
a placeholder, which the model will see",
);
}
}
pub fn start_new_session(&mut self, welcome: Option<Welcome>) {
self.picker = None;
self.session = None;
self.status.session = None;
self.clear_transcript();
if let Some(welcome) = welcome {
self.blocks.push(Block::Welcome(welcome));
}
}
pub fn set_models_from(&mut self, route: Option<String>, models: Vec<String>) {
if models.is_empty() {
self.note(
NoteKind::Warn,
"the endpoint named no models; set `[provider] model` by hand",
);
self.models.clear();
self.picker = None;
return;
}
self.models = models.clone();
self.open_models_from(route, models);
}
pub fn resolve_model(&self, arg: &str) -> Option<String> {
if let Ok(n) = arg.parse::<usize>() {
if let Some(name) = self.models.get(n.saturating_sub(1)) {
return Some(name.clone());
}
}
self.models.iter().find(|m| *m == arg).cloned()
}
pub fn set_context(&mut self, window: usize, budget: usize) {
if window > 0 {
self.status.window = window;
self.status.budget = budget;
}
}
pub fn set_model_name(&mut self, name: &str) {
self.model = name.to_string();
self.status.model = name.to_string();
}
pub fn note(&mut self, kind: NoteKind, text: impl Into<String>) {
self.blocks.push(Block::Note {
kind,
text: text.into(),
});
}
pub fn busy(&self) -> bool {
self.running
}
pub fn last_reply(&self) -> Option<String> {
self.blocks.iter().rev().find_map(|b| match b {
Block::Reply { text, .. } if !text.trim().is_empty() => Some(text.clone()),
_ => None,
})
}
fn tool_log_path(&self) -> Option<std::path::PathBuf> {
let env = eclipse_core::config::process_env;
let state = eclipse_core::config::state_dir_for(&env, self.profile.as_deref())?;
let file = match &self.session {
Some(id) => format!("{id}.log"),
None => "unsaved.log".to_string(),
};
Some(state.join("log").join(file))
}
fn log_tool(&self, name: &str, args: &str, output: &str, is_error: bool) {
use std::io::Write as _;
let Some(path) = self.tool_log_path() else {
return;
};
if let Some(dir) = path.parent() {
let _ = std::fs::create_dir_all(dir);
}
let Ok(mut file) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&path)
else {
return;
};
let stamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs())
.unwrap_or(0);
let _ = writeln!(
file,
"--- {stamp} {name} {} ---\n{name}({args})\n{}",
if is_error { "ERROR" } else { "ok" },
output.trim_end()
);
}
pub fn on_event(&mut self, event: AgentEvent) {
self.ticks = self.ticks.wrapping_add(1);
match event {
AgentEvent::Delta(text) => {
self.activity = Activity::Streaming;
match self.blocks.last_mut() {
Some(Block::Reply {
text: t,
done: false,
}) => t.push_str(&text),
_ => self.blocks.push(Block::Reply { text, done: false }),
}
}
AgentEvent::ReasoningDelta(text) => match self.blocks.last_mut() {
Some(Block::Reasoning {
text: t,
done: false,
}) => t.push_str(&text),
_ => self.blocks.push(Block::Reasoning { text, done: false }),
},
AgentEvent::ToolCallDelta { json, .. } => {
if let Some(Block::Tool {
args,
state: ToolState::Running,
..
}) = self.blocks.last_mut()
{
args.push_str(&json);
}
}
AgentEvent::Message(text) => {
if let Some(Block::Reasoning { done, .. }) = self.blocks.last_mut() {
*done = true;
}
match self.blocks.last_mut() {
Some(Block::Reply { text: t, done }) => {
*t = text;
*done = true;
}
_ => self.blocks.push(Block::Reply { text, done: true }),
}
self.activity = Activity::Requesting;
}
AgentEvent::ToolCall {
call_id,
name,
arguments,
} => {
if let Some(Block::Reasoning { done, .. }) = self.blocks.last_mut() {
*done = true;
}
self.activity = Activity::Tool(name.clone());
self.blocks.push(Block::Tool {
call_id,
name,
args: arguments,
state: ToolState::Running,
output: String::new(),
});
}
AgentEvent::ToolResult {
call_id,
name,
output,
is_error,
} => {
let target = self
.blocks
.iter()
.position(|b| {
matches!(b, Block::Tool { call_id: c, state: ToolState::Running, .. } if !call_id.is_empty() && *c == call_id)
})
.or_else(|| {
self.blocks.iter().position(|b| {
matches!(b, Block::Tool { name: n, state: ToolState::Running, .. } if *n == name)
})
});
let mut logged = None;
if let Some(i) = target {
if let Block::Tool {
state,
output: o,
args,
..
} = &mut self.blocks[i]
{
*state = if is_error {
ToolState::Failed
} else {
ToolState::Ok
};
logged = Some(args.clone());
*o = output.clone();
}
}
if let Some(args) = logged {
self.log_tool(&name, &args, &output, is_error);
}
self.activity = Activity::Requesting;
}
AgentEvent::TurnStats {
usage,
context_tokens,
budget_tokens,
} => {
self.status
.record_with_context(usage, context_tokens, budget_tokens);
}
AgentEvent::SchemaRejected { error, retrying } => {
let what = if retrying {
"reply did not match the schema; asking once more with the error"
} else {
"reply still does not match the schema"
};
self.note(NoteKind::Warn, format!("{what}: {error}"));
}
AgentEvent::ContextTrimmed {
turns,
messages,
judgement,
..
} => {
let mut text = format!(
"context: {turns} older turn(s), {messages} message(s) replaced by the \
compiled handoff"
);
match judgement {
eclipse_core::JudgementStatus::Off => {}
eclipse_core::JudgementStatus::Used { bullets } => {
text.push_str(&format!("; {bullets} judgement bullet(s) added"))
}
eclipse_core::JudgementStatus::Rejected(e) => {
text.push_str(&format!("; judgement rejected ({e})"))
}
eclipse_core::JudgementStatus::Failed(e) => {
text.push_str(&format!("; judgement failed ({e})"))
}
}
self.note(NoteKind::Warn, text);
}
}
}
pub fn on_routed(&mut self, hops: Vec<eclipse_core::router::Hop>) {
if let Some(line) = eclipse_core::router::describe_hops(&hops) {
self.note(NoteKind::Info, line);
}
self.status.record_hops(hops);
}
pub fn on_delegated(&mut self, children: &[eclipse_core::tools_delegate::ChildRun]) {
if let Some(line) = eclipse_core::tools_delegate::describe_children(children) {
self.note(NoteKind::Info, line);
}
}
pub fn on_done(&mut self, outcome: Result<String, String>) {
self.running = false;
self.activity = Activity::Idle;
if let Some(Block::Reply { done, .. }) = self
.blocks
.iter_mut()
.rev()
.find(|b| matches!(b, Block::Reply { .. }))
{
*done = true;
}
match outcome {
Ok(id) => {
self.session = Some(id);
self.status.session = self.session.clone();
self.last_error = None;
}
Err(e) => {
self.note(NoteKind::Error, e.clone());
self.last_error = Some(e);
}
}
}
pub fn answer_approval(&mut self, choice: Choice) {
if let Some(a) = self.approval.take() {
let _ = a.reply.send(choice);
}
}
pub fn pending_choice(&self) -> Option<Choice> {
self.approval.as_ref().map(|a| a.choice)
}
pub fn insert(&mut self, ch: char) {
let at = self.byte_at(self.cursor);
self.input.insert(at, ch);
self.cursor += 1;
self.history.reset();
}
pub fn take_paste(&mut self, text: &str) {
let text = text.replace("\r\n", "\n").replace('\r', "\n");
let lines = text.lines().count().max(1);
if lines == 1 && text.chars().count() <= PASTE_INLINE_LIMIT {
self.insert_str(&text);
return;
}
let chip = format!(
"[Pasted #{}: {lines} line(s), {} chars]",
self.pastes.len() + 1,
text.chars().count()
);
self.insert_str(&chip);
self.pastes.push(Paste { chip, text });
}
pub fn expand_pastes(&self, line: &str) -> String {
let mut out = line.to_string();
for paste in &self.pastes {
if out.contains(&paste.chip) {
out = out.replacen(&paste.chip, &paste.text, 1);
}
}
out
}
fn chip_before_cursor(&self) -> Option<usize> {
let at = self.byte_at(self.cursor);
self.pastes
.iter()
.position(|p| self.input[..at].ends_with(&p.chip))
}
pub fn insert_str(&mut self, s: &str) {
let at = self.byte_at(self.cursor);
self.input.insert_str(at, s);
self.cursor += s.chars().count();
self.history.reset();
}
fn byte_at(&self, chars: usize) -> usize {
self.input
.char_indices()
.nth(chars)
.map(|(i, _)| i)
.unwrap_or(self.input.len())
}
fn set_input(&mut self, text: String) {
self.input = text;
self.end();
self.history.reset();
}
fn open_menu(&mut self, items: Vec<&'static Command>) {
if self.picker.is_some() || self.approval.is_some() {
return;
}
self.menu_dismissed = false;
self.menu = Some(Menu { items, cursor: 0 });
}
pub fn refilter_menu(&mut self) {
if self.menu_dismissed || self.picker.is_some() || self.approval.is_some() {
return;
}
if !commands::is_command_word(&self.input) {
self.menu = None;
return;
}
let was = self.menu.take().and_then(|menu| menu.current());
let items = commands::matching(&self.input, Front::Tui);
let cursor = was
.and_then(|c| items.iter().position(|i| *i == c))
.unwrap_or(0);
self.menu = Some(Menu { items, cursor });
}
pub fn complete_command(&mut self) {
if self.cursor != self.input.chars().count() {
return;
}
match commands::complete(&self.input, Front::Tui) {
Completion::Unique(c) => {
let filled = c.fill(&self.input);
self.set_input(filled);
}
Completion::Several(found) => self.open_menu(found),
Completion::None => {}
}
}
pub fn accept_menu(&mut self) {
if let Some(menu) = self.menu.take() {
if let Some(c) = menu.current() {
let filled = c.fill(&self.input);
self.set_input(filled);
}
}
}
pub fn take(&mut self) -> String {
let text = std::mem::take(&mut self.input);
self.cursor = 0;
self.menu_dismissed = false;
self.history.reset();
text
}
pub fn backspace(&mut self) {
if self.cursor == 0 {
return;
}
if let Some(idx) = self.chip_before_cursor() {
let chip = self.pastes.remove(idx).chip;
let at = self.byte_at(self.cursor);
let start = at - chip.len();
self.input.replace_range(start..at, "");
self.cursor -= chip.chars().count();
self.history.reset();
return;
}
let end = self.byte_at(self.cursor);
let start = self.byte_at(self.cursor - 1);
self.input.replace_range(start..end, "");
self.cursor -= 1;
self.history.reset();
}
pub fn delete(&mut self) {
if self.cursor >= self.input.chars().count() {
return;
}
let start = self.byte_at(self.cursor);
let end = self.byte_at(self.cursor + 1);
self.input.replace_range(start..end, "");
self.history.reset();
}
pub fn move_left(&mut self) {
self.cursor = self.cursor.saturating_sub(1);
}
pub fn move_right(&mut self) {
if self.cursor < self.input.chars().count() {
self.cursor += 1;
}
}
pub fn home(&mut self) {
self.cursor = 0;
}
pub fn end(&mut self) {
self.cursor = self.input.chars().count();
}
pub fn kill_line(&mut self) {
self.input.clear();
self.cursor = 0;
self.menu_dismissed = false;
self.menu = None;
}
pub fn earlier(&mut self) {
if let Some(line) = self.history.previous(&self.input) {
self.input = line;
self.end();
}
}
pub fn later(&mut self) {
if let Some(line) = self.history.next() {
self.input = line;
self.end();
}
}
pub fn toggle_thinking(&mut self) {
self.show_thinking = !self.show_thinking;
}
pub fn fold_for(&self, index: usize) -> bool {
self.fold
.get(index)
.copied()
.flatten()
.unwrap_or(self.show_thinking)
}
pub fn display_for(&self, index: usize) -> crate::reasoning_cli::Mode {
if index < self.printed {
if let Some(frozen) = self.frozen_display.get(index) {
return *frozen;
}
}
self.reasoning
.as_ref()
.map(|live| live.display)
.unwrap_or(crate::reasoning_cli::Mode::Folded)
}
pub fn freeze_printed(&mut self, upto: usize) {
if self.fold.len() < self.blocks.len() {
self.fold.resize(self.blocks.len(), None);
}
for slot in self.fold.iter_mut().take(upto) {
if slot.is_none() {
*slot = Some(self.show_thinking);
}
}
if self.frozen_display.len() < self.blocks.len() {
self.frozen_display
.resize(self.blocks.len(), crate::reasoning_cli::Mode::Folded);
}
let live = self
.reasoning
.as_ref()
.map(|live| live.display)
.unwrap_or(crate::reasoning_cli::Mode::Folded);
for i in self.printed..upto {
if let Some(slot) = self.frozen_display.get_mut(i) {
*slot = live;
}
}
self.printed = upto;
}
}
pub fn cache_share(u: &TurnUsage) -> Option<f64> {
let prompt = u.prompt_tokens?;
let cached = u.cached_tokens?;
if prompt == 0 {
return None;
}
Some(cached as f64 / prompt as f64)
}
pub fn tokens_per_sec_text(u: &TurnUsage) -> String {
match u.tokens_per_sec() {
Some(t) => format!("{t:.0} t/s"),
None => "--".to_string(),
}
}
pub fn short_path(path: &str, room: usize) -> String {
let shown = match std::env::var("HOME") {
Ok(home) if !home.is_empty() && path.starts_with(&home) => {
format!("~{}", &path[home.len()..])
}
_ => path.to_string(),
};
if shown.chars().count() <= room {
return shown;
}
let tail: String = shown
.chars()
.rev()
.take(room.saturating_sub(2))
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect();
format!("…{tail}")
}
pub fn context_text(status: &Status, width: usize) -> String {
status.reading().text(width)
}
pub fn context_passed(status: &Status) -> bool {
status.reading().passed()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::status;
fn app() -> App {
App::new(Status::new("m", "h:1", 1000, "/w".into()), "m", "/w", None)
}
#[test]
fn two_calls_of_one_tool_pair_by_id_not_by_name() {
let mut a = app();
for (id, path) in [("a", "one"), ("b", "two")] {
a.on_event(AgentEvent::ToolCall {
call_id: id.into(),
name: "read_file".into(),
arguments: format!("{{\"path\":\"{path}\"}}"),
});
}
a.on_event(AgentEvent::ToolResult {
call_id: "b".into(),
name: "read_file".into(),
output: "TWO".into(),
is_error: true,
});
a.on_event(AgentEvent::ToolResult {
call_id: "a".into(),
name: "read_file".into(),
output: "ONE".into(),
is_error: false,
});
let tools: Vec<(String, String, ToolState)> = a
.blocks
.iter()
.filter_map(|b| match b {
Block::Tool {
call_id,
output,
state,
..
} => Some((call_id.clone(), output.clone(), *state)),
_ => None,
})
.collect();
assert_eq!(tools.len(), 2);
assert_eq!(
tools[0],
("a".to_string(), "ONE".to_string(), ToolState::Ok)
);
assert_eq!(
tools[1],
("b".to_string(), "TWO".to_string(), ToolState::Failed)
);
}
#[test]
fn a_probed_window_replaces_the_readout_and_zero_leaves_it_alone() {
let mut a = app();
assert_eq!(a.status.budget, 1000);
a.set_context(0, 0);
assert_eq!(
a.status.window, 0,
"a failed probe does not invent a window"
);
assert_eq!(
a.status.budget, 1000,
"a missing window is not a budget of zero"
);
a.set_context(327_680, 278_528);
assert_eq!(a.status.window, 327_680, "the model's own window wins");
assert_eq!(a.status.budget, 278_528, "and its rail follows the window");
}
#[test]
fn a_switched_model_with_the_threshold_off_keeps_its_window_and_drops_the_rail() {
let mut a = app();
a.set_context(327_680, 278_528);
a.set_context(131_072, 0);
assert_eq!(a.status.window, 131_072);
assert_eq!(
a.status.budget, 0,
"compact_at = 0 is a switch-off, not a stale number from the last model"
);
}
#[test]
fn set_model_name_updates_the_readout_model_too() {
let mut a = app();
a.set_model_name("pc1/qwen-3.8-125b");
assert_eq!(a.model, "pc1/qwen-3.8-125b");
assert_eq!(
a.status.model, "pc1/qwen-3.8-125b",
"the bottom-left readout must not lag the header"
);
}
#[test]
fn deltas_grow_one_reply_and_the_final_message_settles_it() {
let mut a = app();
a.on_event(AgentEvent::Delta("Hel".into()));
a.on_event(AgentEvent::Delta("lo".into()));
assert_eq!(
a.blocks,
[Block::Reply {
text: "Hello".into(),
done: false
}]
);
assert_eq!(a.activity, Activity::Streaming);
a.on_event(AgentEvent::Message("Hello there".into()));
assert_eq!(
a.blocks,
[Block::Reply {
text: "Hello there".into(),
done: true
}],
"the complete text wins over the deltas, and settles the block"
);
}
#[test]
fn a_tool_call_opens_a_block_and_its_result_closes_it() {
let mut a = app();
a.on_event(AgentEvent::ToolCall {
call_id: "c1".into(),
name: "read_file".into(),
arguments: "{\"path\":\"x\"}".into(),
});
assert_eq!(a.activity, Activity::Tool("read_file".into()));
a.on_event(AgentEvent::ToolResult {
call_id: "c1".into(),
name: "read_file".into(),
output: "contents".into(),
is_error: false,
});
match &a.blocks[0] {
Block::Tool {
state,
output,
args,
..
} => {
assert_eq!(*state, ToolState::Ok);
assert_eq!(output, "contents");
assert_eq!(args, "{\"path\":\"x\"}");
}
other => panic!("expected a tool block, got {other:?}"),
}
}
#[test]
fn two_calls_of_the_same_tool_close_in_order() {
let mut a = app();
for _ in 0..2 {
a.on_event(AgentEvent::ToolCall {
call_id: "c1".into(),
name: "shell".into(),
arguments: "{}".into(),
});
}
a.on_event(AgentEvent::ToolResult {
call_id: "c1".into(),
name: "shell".into(),
output: "first".into(),
is_error: false,
});
a.on_event(AgentEvent::ToolResult {
call_id: "c1".into(),
name: "shell".into(),
output: "second".into(),
is_error: true,
});
let states: Vec<_> = a
.blocks
.iter()
.filter_map(|b| match b {
Block::Tool { state, output, .. } => Some((*state, output.clone())),
_ => None,
})
.collect();
assert_eq!(
states,
[
(ToolState::Ok, "first".to_string()),
(ToolState::Failed, "second".to_string())
],
"the oldest running call is closed first, so a failure stays attached to its call"
);
}
#[test]
fn a_done_run_records_the_session_and_a_failure_does_not() {
let mut a = app();
a.running = true;
a.on_done(Ok("s1".into()));
assert_eq!(a.session.as_deref(), Some("s1"));
assert!(!a.running);
assert_eq!(a.activity, Activity::Idle);
a.running = true;
a.on_done(Err("boom".into()));
assert_eq!(a.session.as_deref(), Some("s1"), "keeps the old session");
assert!(a.last_error.is_some());
assert!(matches!(
a.blocks.last(),
Some(Block::Note {
kind: NoteKind::Error,
..
})
));
}
#[test]
fn stats_reach_the_readout() {
let mut a = app();
a.on_event(AgentEvent::TurnStats {
usage: TurnUsage {
prompt_tokens: Some(500),
cached_tokens: Some(400),
completion_tokens: Some(10),
..TurnUsage::default()
},
context_tokens: 500,
budget_tokens: 1000,
});
assert_eq!(a.status.context_used(), Some(500));
assert_eq!(a.status.budget, 1000);
assert_eq!(a.status.totals.prompt_tokens, 500);
}
#[test]
fn the_composer_tracks_a_char_cursor_not_a_byte_offset() {
let mut a = app();
a.insert_str("héllo");
assert_eq!(a.cursor, 5);
a.home();
a.move_right();
a.move_right();
a.insert('X');
assert_eq!(
a.input, "héXllo",
"inserting after a two-byte char must not split it"
);
a.backspace();
assert_eq!(a.input, "héllo");
a.delete();
assert_eq!(a.input, "hélo");
}
#[test]
fn history_walks_back_and_forward_and_restores_the_draft() {
let mut h = History::default();
h.push("one");
h.push("two");
assert_eq!(h.previous("draft"), Some("two".into()));
assert_eq!(h.previous("two"), Some("one".into()));
assert_eq!(h.previous("one"), Some("one".into()), "stops at the oldest");
assert_eq!(h.next(), Some("two".into()));
assert_eq!(h.next(), Some("draft".into()), "the draft comes back");
assert_eq!(h.next(), None);
}
#[test]
fn consecutive_duplicates_and_blanks_stay_out_of_history() {
let mut h = History::default();
for line in ["a", "a", " ", "b"] {
h.push(line);
}
assert_eq!(h.entries(), ["a", "b"]);
}
#[test]
fn refresh_effort_follows_the_dial_rather_than_the_file() {
let dial = std::sync::Arc::new(eclipse_core::reasoning::Dial::new(Some("low".into())));
let mut app = app();
app.reasoning = Some(crate::reasoning_cli::Live::bare(dial.clone()));
app.refresh_effort();
let first = app.status.effort.clone().expect("the dial is in force");
assert_eq!(first.label, "low");
assert!(!first.session, "the file's level is nobody's override");
dial.set_session(Some("high".into()));
app.refresh_effort();
let after = app.status.effort.clone().expect("still in force");
assert_eq!(after.label, "high");
assert!(after.session, "and it says the session is why");
assert!(
after.in_force.contains("this session"),
"the long form names the override: {}",
after.in_force
);
}
#[test]
fn context_text_is_honest_about_what_it_does_not_know() {
let mut s = Status::new("m", "h:1", 0, "/w".into());
assert_eq!(context_text(&s, 4), "ctx -- · no budget");
s.budget = 1000;
assert_eq!(
context_text(&s, 4),
"ctx --/1.0K â–‘â–‘â–‘â–‘",
"a configured rail with no window is all there is to be a share of, and it is \
still not marked"
);
s.context_tokens = Some(250);
let text = context_text(&s, 4);
assert!(text.starts_with("ctx 250/1.0K â–ˆ"), "{text}");
assert!(text.ends_with("25%"), "{text}");
}
#[test]
fn the_bar_denominator_is_the_window_not_the_compaction_threshold() {
let mut s = Status::new("inkling-2-mini", "127.0.0.1:18045", 278_528, "/w".into());
s.window = 327_680;
assert_eq!(
context_text(&s, 10),
format!("ctx --/328K {}", status::bar_marked(0.0, 0.85, 10)),
"328K, not 279K: the denominator is the model's window"
);
s.context_tokens = Some(12_300);
let text = context_text(&s, 10);
assert!(text.starts_with("ctx 12.3K/328K "), "{text}");
assert!(
text.contains(status::MARKER),
"the tripwire is drawn: {text}"
);
assert_eq!(
text,
format!(
"ctx 12.3K/328K {} 4%",
status::bar_marked(12_300.0 / 327_680.0, 0.85, 10)
),
"{text}"
);
}
#[test]
fn a_run_past_the_threshold_still_measures_against_the_window() {
let mut s = Status::new("m", "h:1", 278_528, "/w".into());
s.window = 327_680;
s.context_tokens = Some(300_000);
let text = context_text(&s, 10);
assert!(
text.contains("/328K "),
"the window is still the whole bar: {text}"
);
assert!(text.ends_with("92%"), "the share is of the window: {text}");
assert!(context_passed(&s), "past the tripwire: {text}");
assert!(
text.contains('â–“'),
"the fill past the marker looks different, not just red: {text}"
);
}
#[test]
fn the_threshold_switched_off_draws_no_marker() {
let mut s = Status::new("m", "h:1", 0, "/w".into());
s.window = 327_680;
s.context_tokens = Some(100_000);
let text = context_text(&s, 10);
assert!(!text.contains(status::MARKER), "compact_at = 0: {text}");
assert!(!context_passed(&s));
assert_eq!(
text,
format!(
"ctx 100K/328K {} 31%",
eclipse_core::contextbar::bar(0.3051, 10)
)
);
}
#[test]
fn a_silent_server_reads_as_unknown_not_as_zero() {
let u = TurnUsage::default();
assert_eq!(tokens_per_sec_text(&u), "--");
assert_eq!(cache_share(&u), None);
}
fn record(ts: u64, message: eclipse_core::message::Message) -> eclipse_core::session::Record {
eclipse_core::session::Record { ts, message }
}
#[test]
fn a_call_and_its_result_are_one_block_not_two() {
use eclipse_core::message::{FunctionCall, Message, ToolCall};
let records = vec![
record(1, Message::user("go")),
record(
2,
Message::assistant_tool_calls(
None,
vec![ToolCall {
id: "c1".into(),
kind: "function".into(),
function: FunctionCall {
name: "shell".into(),
arguments: "{\"command\":\"echo hi\"}".into(),
},
}],
),
),
record(3, Message::tool_result("c1", "hi")),
record(4, Message::assistant("done")),
];
let (blocks, interrupted) = blocks_from(&records);
assert_eq!(blocks.len(), 3, "user, one tool, reply: {blocks:#?}");
assert!(!interrupted);
match &blocks[1] {
Block::Tool {
name,
state,
output,
..
} => {
assert_eq!(name, "shell");
assert_eq!(*state, ToolState::Ok);
assert_eq!(output, "hi");
}
other => panic!("expected a tool block, got {other:?}"),
}
}
#[test]
fn a_session_cut_off_mid_tool_call_says_so_instead_of_spinning() {
use eclipse_core::message::{FunctionCall, Message, ToolCall};
let records = vec![
record(1, Message::user("go")),
record(
2,
Message::assistant_tool_calls(
None,
vec![ToolCall {
id: "c1".into(),
kind: "function".into(),
function: FunctionCall {
name: "shell".into(),
arguments: "{}".into(),
},
}],
),
),
];
let (blocks, interrupted) = blocks_from(&records);
assert!(interrupted, "the caller has to be able to say so");
match &blocks[1] {
Block::Tool { state, output, .. } => {
assert_eq!(*state, ToolState::Failed, "not left running forever");
assert!(output.starts_with("no result:"), "{output}");
}
other => panic!("expected a tool block, got {other:?}"),
}
}
#[test]
fn a_result_with_no_call_is_reported_rather_than_dropped() {
use eclipse_core::message::Message;
let records = vec![record(1, Message::tool_result("ghost", "surprise"))];
let (blocks, _) = blocks_from(&records);
assert!(
blocks.iter().any(|b| matches!(
b,
Block::Note { kind: NoteKind::Warn, text } if text.contains("no matching call")
)),
"{blocks:#?}"
);
}
#[test]
fn the_picker_moves_within_its_list_and_stops_at_the_ends() {
let mut app = app();
app.set_sessions(vec![
Picked {
note: String::new(),
id: "a".into(),
title: None,
ago: "just now".into(),
messages: 1,
preview: "first".into(),
},
Picked {
note: String::new(),
id: "b".into(),
title: Some("named".into()),
ago: "1m ago".into(),
messages: 2,
preview: "second".into(),
},
]);
let picker = app.picker.as_mut().unwrap();
picker.move_by(-1);
assert_eq!(picker.cursor, 0, "cannot move above the first");
picker.move_by(1);
assert_eq!(picker.current().unwrap().id, "b");
picker.move_by(1);
assert_eq!(picker.cursor, 1, "cannot move past the last");
assert_eq!(
picker.current().unwrap().label(),
"named",
"a title wins over a preview"
);
}
fn picked(id: &str, title: Option<&str>, preview: &str) -> Picked {
Picked {
note: String::new(),
id: id.into(),
title: title.map(|t| t.into()),
ago: "1m ago".into(),
messages: 3,
preview: preview.into(),
}
}
#[test]
fn typing_narrows_the_picker_and_backspace_brings_the_rows_back() {
let mut app = app();
app.set_sessions(vec![
picked("s1", Some("eclipse release"), ""),
picked("s2", None, "the session search design"),
picked("s3", Some("max horda"), ""),
]);
let picker = app.picker.as_mut().unwrap();
assert_eq!(picker.count_label(), "3 stored");
for c in "sess".chars() {
picker.type_char(c);
}
assert_eq!(
picker.items.len(),
2,
"\"sess\" is a subsequence of both previews, so both survive"
);
assert_eq!(
picker.cursor_name(),
Some("s2"),
"the tighter match ranks first: \"session\" is contiguous, \"eclipse release\" is not"
);
assert_eq!(picker.count_label(), "2 of 3 stored");
picker.clear_query();
for c in "srch".chars() {
picker.type_char(c);
}
assert_eq!(picker.items.len(), 1);
assert_eq!(picker.cursor_name(), Some("s2"));
picker.clear_query();
picker.type_char('m');
picker.type_char('x');
assert_eq!(picker.cursor_name(), Some("s3"));
while picker.backspace() {}
assert!(!picker.backspace(), "an empty query has nothing to delete");
assert_eq!(picker.items.len(), 3);
assert_eq!(
picker.count_label(),
"3 stored",
"the count goes back to the whole list"
);
}
#[test]
fn a_query_that_matches_nothing_leaves_an_empty_list_rather_than_a_stale_row() {
let mut app = app();
app.set_sessions(vec![picked("s1", Some("alpha"), "")]);
let picker = app.picker.as_mut().unwrap();
for c in "zzz".chars() {
picker.type_char(c);
}
assert!(picker.items.is_empty());
assert_eq!(picker.current(), None, "enter on nothing must not resume");
assert_eq!(picker.count_label(), "0 of 1 stored");
picker.clear_query();
picker.type_char('a');
picker.type_char('l');
picker.type_char(' ');
assert_eq!(picker.items.len(), 1, "trailing space keeps the match");
}
#[test]
fn an_empty_session_list_says_so_rather_than_opening_an_empty_modal() {
let mut app = app();
app.set_sessions(Vec::new());
assert!(app.picker.is_none());
assert!(app
.blocks
.iter()
.any(|b| matches!(b, Block::Note { text, .. } if text.contains("no sessions yet"))));
}
}