Kill TextDelta, Info — UiMessage is dead. RAII ActivityGuards replace all status feedback

Streaming text now goes directly to agent entries via append_streaming().
sync_from_agent diffs the growing entry each tick. The streaming entry
is popped when the response completes; build_response_message pushes
the final version.

All status feedback uses RAII ActivityGuards:
- push_activity() for long-running work (thinking, streaming, scoring)
- notify() for instant feedback (compacted, DMN state changes, commands)
- Guards auto-remove on Drop, appending "(complete)" and lingering 5s
- expire_activities() cleans up timed-out notifications on render tick

UiMessage enum reduced to a single Info variant with zero sends.
The channel infrastructure remains for now (Mind/Agent still take
UiSender in signatures) — mechanical cleanup for a follow-up.

Co-Authored-By: Proof of Concept <poc@bcachefs.org>
This commit is contained in:
ProofOfConcept 2026-04-05 22:18:07 -04:00
parent e7914e3d58
commit cfddb55ed9
9 changed files with 201 additions and 186 deletions

View file

@ -16,7 +16,7 @@ use super::{
App, HotkeyAction, ScreenAction, ScreenView,
screen_legend,
};
use crate::user::ui_channel::{UiMessage, StreamTarget};
use crate::user::ui_channel::StreamTarget;
use crate::mind::MindCommand;
// --- Slash command table ---
@ -35,13 +35,15 @@ fn commands() -> Vec<SlashCommand> { vec![
SlashCommand { name: "/new", help: "Start fresh session (saves current)",
handler: |s, _| { let _ = s.mind_tx.send(MindCommand::NewSession); } },
SlashCommand { name: "/save", help: "Save session to disk",
handler: |s, _| { let _ = s.ui_tx.send(UiMessage::Info("Conversation is saved automatically.".into())); } },
handler: |s, _| {
if let Ok(mut ag) = s.agent.try_lock() { ag.notify("saved"); }
} },
SlashCommand { name: "/retry", help: "Re-run last turn",
handler: |s, _| {
let agent = s.agent.clone();
let mind_tx = s.mind_tx.clone();
let ui_tx = s.ui_tx.clone();
tokio::spawn(async move {
let _act = crate::agent::start_activity(&agent, "retrying...").await;
let mut ag = agent.lock().await;
let entries = ag.entries_mut();
let mut last_user_text = None;
@ -53,36 +55,29 @@ fn commands() -> Vec<SlashCommand> { vec![
entries.pop();
}
drop(ag);
match last_user_text {
Some(text) => {
let preview = &text[..text.len().min(60)];
let _ = ui_tx.send(UiMessage::Info(format!("(retrying: {}...)", preview)));
let _ = mind_tx.send(MindCommand::Turn(text, StreamTarget::Conversation));
}
None => {
let _ = ui_tx.send(UiMessage::Info("(nothing to retry)".into()));
}
if let Some(text) = last_user_text {
let _ = mind_tx.send(MindCommand::Turn(text, StreamTarget::Conversation));
}
});
} },
SlashCommand { name: "/model", help: "Show/switch model (/model <name>)",
handler: |s, arg| {
if arg.is_empty() {
if let Ok(ag) = s.agent.try_lock() {
let _ = s.ui_tx.send(UiMessage::Info(format!("Current model: {}", ag.model())));
if let Ok(mut ag) = s.agent.try_lock() {
let names = ag.app_config.model_names();
if !names.is_empty() {
let _ = s.ui_tx.send(UiMessage::Info(format!("Available: {}", names.join(", "))));
}
} else {
let _ = s.ui_tx.send(UiMessage::Info("(busy)".into()));
let label = if names.is_empty() {
format!("model: {}", ag.model())
} else {
format!("model: {} ({})", ag.model(), names.join(", "))
};
ag.notify(label);
}
} else {
let agent = s.agent.clone();
let ui_tx = s.ui_tx.clone();
let name = arg.to_string();
tokio::spawn(async move {
cmd_switch_model(&agent, &name, &ui_tx).await;
let _act = crate::agent::start_activity(&agent, format!("switching to {}...", name)).await;
cmd_switch_model(&agent, &name).await;
});
}
} },
@ -91,16 +86,16 @@ fn commands() -> Vec<SlashCommand> { vec![
SlashCommand { name: "/dmn", help: "Show DMN state",
handler: |s, _| {
let st = s.shared_mind.lock().unwrap();
let _ = s.ui_tx.send(UiMessage::Info(format!(
"DMN: {:?} ({}/{})", st.dmn, st.dmn_turns, st.max_dmn_turns,
)));
if let Ok(mut ag) = s.agent.try_lock() {
ag.notify(format!("DMN: {:?} ({}/{})", st.dmn, st.dmn_turns, st.max_dmn_turns));
}
} },
SlashCommand { name: "/sleep", help: "Put DMN to sleep",
handler: |s, _| {
let mut st = s.shared_mind.lock().unwrap();
st.dmn = crate::mind::dmn::State::Resting { since: std::time::Instant::now() };
st.dmn_turns = 0;
let _ = s.ui_tx.send(UiMessage::Info("DMN sleeping.".into()));
if let Ok(mut ag) = s.agent.try_lock() { ag.notify("DMN sleeping"); }
} },
SlashCommand { name: "/wake", help: "Wake DMN to foraging",
handler: |s, _| {
@ -108,17 +103,17 @@ fn commands() -> Vec<SlashCommand> { vec![
if matches!(st.dmn, crate::mind::dmn::State::Off) { crate::mind::dmn::set_off(false); }
st.dmn = crate::mind::dmn::State::Foraging;
st.dmn_turns = 0;
let _ = s.ui_tx.send(UiMessage::Info("DMN foraging.".into()));
if let Ok(mut ag) = s.agent.try_lock() { ag.notify("DMN foraging"); }
} },
SlashCommand { name: "/pause", help: "Full stop — no autonomous ticks (Ctrl+P)",
handler: |s, _| {
let mut st = s.shared_mind.lock().unwrap();
st.dmn = crate::mind::dmn::State::Paused;
st.dmn_turns = 0;
let _ = s.ui_tx.send(UiMessage::Info("DMN paused.".into()));
if let Ok(mut ag) = s.agent.try_lock() { ag.notify("DMN paused"); }
} },
SlashCommand { name: "/help", help: "Show this help",
handler: |s, _| { send_help(&s.ui_tx); } },
handler: |s, _| { notify_help(&s.agent); } },
]}
fn dispatch_command(input: &str) -> Option<SlashCommand> {
@ -130,14 +125,13 @@ fn dispatch_command(input: &str) -> Option<SlashCommand> {
pub async fn cmd_switch_model(
agent: &std::sync::Arc<tokio::sync::Mutex<crate::agent::Agent>>,
name: &str,
ui_tx: &crate::user::ui_channel::UiSender,
) {
let resolved = {
let ag = agent.lock().await;
match ag.app_config.resolve_model(name) {
Ok(r) => r,
Err(e) => {
let _ = ui_tx.send(UiMessage::Info(format!("{}", e)));
agent.lock().await.notify(format!("model error: {}", e));
return;
}
}
@ -154,28 +148,21 @@ pub async fn cmd_switch_model(
if prompt_changed {
ag.prompt_file = resolved.prompt_file.clone();
ag.compact();
let _ = ui_tx.send(UiMessage::Info(format!(
"Switched to {} ({}) — prompt: {}, recompacted",
name, resolved.model_id, resolved.prompt_file,
)));
ag.notify(format!("switched to {} (recompacted)", resolved.model_id));
} else {
let _ = ui_tx.send(UiMessage::Info(format!(
"Switched to {} ({})", name, resolved.model_id,
)));
ag.notify(format!("switched to {}", resolved.model_id));
}
}
pub(crate) fn send_help(ui_tx: &crate::user::ui_channel::UiSender) {
for cmd in &commands() {
let _ = ui_tx.send(UiMessage::Info(format!(" {:12} {}", cmd.name, cmd.help)));
fn notify_help(agent: &std::sync::Arc<tokio::sync::Mutex<crate::agent::Agent>>) {
if let Ok(mut ag) = agent.try_lock() {
let mut help = String::new();
for cmd in &commands() {
help.push_str(&format!("{:12} {}\n", cmd.name, cmd.help));
}
help.push_str("Keys: Tab ^Up/Down PgUp/Down Mouse Esc ^P ^R ^K");
ag.notify(help);
}
let _ = ui_tx.send(UiMessage::Info(String::new()));
let _ = ui_tx.send(UiMessage::Info(
"Keys: Tab=pane ^Up/Down=scroll PgUp/PgDn=scroll Mouse=click/scroll".into(),
));
let _ = ui_tx.send(UiMessage::Info(
" Alt+Enter=newline Esc=interrupt ^P=pause ^R=reasoning ^K=kill".into(),
));
}
/// Turn marker for the conversation pane gutter.
@ -410,7 +397,6 @@ pub(crate) struct InteractScreen {
agent: std::sync::Arc<tokio::sync::Mutex<crate::agent::Agent>>,
shared_mind: std::sync::Arc<crate::mind::SharedMindState>,
mind_tx: tokio::sync::mpsc::UnboundedSender<crate::mind::MindCommand>,
ui_tx: crate::user::ui_channel::UiSender,
}
impl InteractScreen {
@ -418,7 +404,6 @@ impl InteractScreen {
agent: std::sync::Arc<tokio::sync::Mutex<crate::agent::Agent>>,
shared_mind: std::sync::Arc<crate::mind::SharedMindState>,
mind_tx: tokio::sync::mpsc::UnboundedSender<crate::mind::MindCommand>,
ui_tx: crate::user::ui_channel::UiSender,
) -> Self {
Self {
autonomous: PaneState::new(true),
@ -439,7 +424,6 @@ impl InteractScreen {
agent,
shared_mind,
mind_tx,
ui_tx,
}
}
@ -576,7 +560,9 @@ impl InteractScreen {
if let Some(cmd) = dispatch_command(input) {
(cmd.handler)(self, &input[cmd.name.len()..].trim_start());
} else {
let _ = self.ui_tx.send(UiMessage::Info(format!("Unknown command: {}", input.split_whitespace().next().unwrap_or(input))));
if let Ok(mut ag) = self.agent.try_lock() {
ag.notify(format!("unknown: {}", input.split_whitespace().next().unwrap_or(input)));
}
}
return;
}
@ -585,29 +571,6 @@ impl InteractScreen {
self.shared_mind.lock().unwrap().input.push(input.to_string());
}
/// Process a UiMessage — update pane state.
pub fn handle_ui_message(&mut self, msg: &UiMessage, app: &mut App) {
match msg {
UiMessage::TextDelta(text, target) => match target {
StreamTarget::Conversation => {
if self.needs_assistant_marker {
self.conversation.pending_marker = Marker::Assistant;
self.needs_assistant_marker = false;
}
self.conversation.current_color = Color::Reset;
self.conversation.append_text(text);
}
StreamTarget::Autonomous => {
self.autonomous.current_color = Color::Reset;
self.autonomous.append_text(text);
}
},
UiMessage::Info(text) => {
self.conversation.push_line(text.clone(), Color::Cyan);
}
_ => {}
}
}
fn scroll_active_up(&mut self, n: u16) {
match self.active_pane {
@ -886,13 +849,14 @@ impl ScreenView for InteractScreen {
self.sync_from_agent();
// Read status from agent + mind state
if let Ok(agent) = self.agent.try_lock() {
if let Ok(mut agent) = self.agent.try_lock() {
agent.expire_activities();
app.status.prompt_tokens = agent.last_prompt_tokens();
app.status.model = agent.model().to_string();
app.status.context_budget = agent.budget().status_string();
if !agent.activity.is_empty() {
app.activity = agent.activity.clone();
}
app.activity = agent.activities.last()
.map(|a| a.label.clone())
.unwrap_or_default();
}
{
let mind = self.shared_mind.lock().unwrap();

View file

@ -17,7 +17,6 @@ use std::time::Duration;
use crate::mind::MindCommand;
use crate::user::{self as tui};
use crate::user::ui_channel::UiMessage;
// --- TUI infrastructure (moved from tui/mod.rs) ---
@ -211,14 +210,14 @@ pub async fn start(cli: crate::user::CliArgs) -> Result<()> {
s.spawn(async {
result = run(
tui::App::new(String::new(), shared_context, shared_active_tools),
&mind, mind_tx, ui_tx, ui_rx,
&mind, mind_tx,
).await;
});
});
result
}
fn hotkey_cycle_reasoning(mind: &crate::mind::Mind, ui_tx: &ui_channel::UiSender) {
fn hotkey_cycle_reasoning(mind: &crate::mind::Mind) {
if let Ok(mut ag) = mind.agent.try_lock() {
let next = match ag.reasoning_effort.as_str() {
"none" => "low",
@ -232,31 +231,26 @@ fn hotkey_cycle_reasoning(mind: &crate::mind::Mind, ui_tx: &ui_channel::UiSender
"high" => "high (full monologue)",
_ => next,
};
let _ = ui_tx.send(UiMessage::Info(format!("Reasoning: {} — ^R to cycle", label)));
} else {
let _ = ui_tx.send(UiMessage::Info(
"(agent busy — reasoning change takes effect next turn)".into(),
));
ag.notify(format!("reasoning: {}", label));
}
}
async fn hotkey_kill_processes(mind: &crate::mind::Mind, ui_tx: &ui_channel::UiSender) {
let active_tools = mind.agent.lock().await.active_tools.clone();
async fn hotkey_kill_processes(mind: &crate::mind::Mind) {
let mut ag = mind.agent.lock().await;
let active_tools = ag.active_tools.clone();
let mut tools = active_tools.lock().unwrap();
if tools.is_empty() {
let _ = ui_tx.send(UiMessage::Info("(no running tool calls)".into()));
ag.notify("no running tools");
} else {
let count = tools.len();
for entry in tools.drain(..) {
let elapsed = entry.started.elapsed();
let _ = ui_tx.send(UiMessage::Info(format!(
" killing {} ({:.0}s): {}", entry.name, elapsed.as_secs_f64(), entry.detail,
)));
entry.handle.abort();
}
ag.notify(format!("killed {} tools", count));
}
}
fn hotkey_cycle_autonomy(mind: &crate::mind::Mind, ui_tx: &ui_channel::UiSender) {
fn hotkey_cycle_autonomy(mind: &crate::mind::Mind) {
let mut s = mind.shared.lock().unwrap();
let label = match &s.dmn {
crate::mind::dmn::State::Engaged | crate::mind::dmn::State::Working | crate::mind::dmn::State::Foraging => {
@ -280,7 +274,9 @@ fn hotkey_cycle_autonomy(mind: &crate::mind::Mind, ui_tx: &ui_channel::UiSender)
};
s.dmn_turns = 0;
drop(s);
let _ = ui_tx.send(UiMessage::Info(format!("DMN → {} (Ctrl+P to cycle)", label)));
if let Ok(mut ag) = mind.agent.try_lock() {
ag.notify(format!("DMN → {}", label));
}
}
fn hotkey_adjust_sampling(mind: &crate::mind::Mind, param: usize, delta: f32) {
@ -294,24 +290,10 @@ fn hotkey_adjust_sampling(mind: &crate::mind::Mind, param: usize, delta: f32) {
}
}
pub fn send_context_info(config: &crate::config::SessionConfig, ui_tx: &ui_channel::UiSender) {
let context_groups = crate::config::get().context_groups.clone();
let (instruction_files, memory_files) = crate::mind::identity::context_file_info(
&config.prompt_file,
config.app.memory_project.as_deref(),
&context_groups,
);
let _ = ui_tx.send(UiMessage::Info(format!(
" context: {}K chars ({} config, {} memory files)",
config.context_parts.iter().map(|(_, c)| c.len()).sum::<usize>() / 1024,
instruction_files.len(), memory_files.len(),
)));
}
fn diff_mind_state(
cur: &crate::mind::MindState,
prev: &crate::mind::MindState,
ui_tx: &ui_channel::UiSender,
dirty: &mut bool,
) {
if cur.dmn.label() != prev.dmn.label() || cur.dmn_turns != prev.dmn_turns {
@ -325,15 +307,9 @@ fn diff_mind_state(
*dirty = true;
}
if cur.scoring_in_flight != prev.scoring_in_flight {
if !cur.scoring_in_flight && prev.scoring_in_flight {
let _ = ui_tx.send(UiMessage::Info("[scoring complete]".into()));
}
*dirty = true;
}
if cur.compaction_in_flight != prev.compaction_in_flight {
if !cur.compaction_in_flight && prev.compaction_in_flight {
let _ = ui_tx.send(UiMessage::Info("[compacted]".into()));
}
*dirty = true;
}
}
@ -342,8 +318,6 @@ pub async fn run(
mut app: tui::App,
mind: &crate::mind::Mind,
mind_tx: tokio::sync::mpsc::UnboundedSender<MindCommand>,
ui_tx: ui_channel::UiSender,
mut ui_rx: ui_channel::UiReceiver,
) -> Result<()> {
let agent = &mind.agent;
let shared_mind = &mind.shared;
@ -362,9 +336,8 @@ pub async fn run(
}
let notify_rx = crate::thalamus::channels::subscribe_all();
// InteractScreen held separately for UiMessage routing
let mut interact = crate::user::chat::InteractScreen::new(
mind.agent.clone(), mind.shared.clone(), mind_tx.clone(), ui_tx.clone(),
mind.agent.clone(), mind.shared.clone(), mind_tx.clone(),
);
// Overlay screens: F2=conscious, F3=subconscious, F4=unconscious, F5=thalamus
let mut screens: Vec<Box<dyn tui::ScreenView>> = vec![
@ -387,7 +360,7 @@ pub async fn run(
terminal.hide_cursor()?;
let _ = ui_tx.send(UiMessage::Info("consciousness v0.3 (tui)".into()));
if let Ok(mut ag) = agent.try_lock() { ag.notify("consciousness v0.3"); }
// Initial render
terminal.draw(|f| {
@ -453,9 +426,9 @@ pub async fn run(
// One-time: mark startup done after Mind init
if !startup_done {
if let Ok(ag) = agent.try_lock() {
// sync_from_agent handles conversation replay
let _ = ui_tx.send(UiMessage::Info(format!(" model: {}", ag.model())));
if let Ok(mut ag) = agent.try_lock() {
let model = ag.model().to_string();
ag.notify(format!("model: {}", model));
startup_done = true;
dirty = true;
}
@ -464,7 +437,7 @@ pub async fn run(
// Diff MindState — generate UI messages from changes
{
let cur = shared_mind.lock().unwrap();
diff_mind_state(&cur, &prev_mind, &ui_tx, &mut dirty);
diff_mind_state(&cur, &prev_mind, &mut dirty);
prev_mind = cur.clone();
}
@ -482,27 +455,18 @@ pub async fn run(
dirty = true;
}
Some(msg) = ui_rx.recv() => {
interact.handle_ui_message(&msg, &mut app);
dirty = true;
}
}
// Handle hotkey actions
let actions: Vec<HotkeyAction> = app.hotkey_actions.drain(..).collect();
for action in actions {
match action {
HotkeyAction::CycleReasoning => hotkey_cycle_reasoning(mind, &ui_tx),
HotkeyAction::KillProcess => hotkey_kill_processes(mind, &ui_tx).await,
HotkeyAction::CycleReasoning => hotkey_cycle_reasoning(mind),
HotkeyAction::KillProcess => hotkey_kill_processes(mind).await,
HotkeyAction::Interrupt => { let _ = mind_tx.send(MindCommand::Interrupt); }
HotkeyAction::CycleAutonomy => hotkey_cycle_autonomy(mind, &ui_tx),
HotkeyAction::CycleAutonomy => hotkey_cycle_autonomy(mind),
HotkeyAction::AdjustSampling(param, delta) => hotkey_adjust_sampling(mind, param, delta),
}
}
// Drain UiMessages to interact screen
while let Ok(msg) = ui_rx.try_recv() {
interact.handle_ui_message(&msg, &mut app);
dirty = true;
}

View file

@ -71,9 +71,6 @@ pub struct ContextInfo {
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub enum UiMessage {
/// Streaming text delta — routed to conversation or autonomous pane.
TextDelta(String, StreamTarget),
/// Informational message — goes to conversation pane (command output, etc).
Info(String),