Revert to tokio::sync::Mutex, fix lock-across-await bugs, move input ownership to InteractScreen
The std::sync::Mutex detour caught every place a MutexGuard lived across an await point in Agent::turn — the compiler enforced Send safety that tokio::sync::Mutex silently allows. With those fixed, switch back to tokio::sync::Mutex (std::sync blocks tokio worker threads and panics inside the runtime). Input and command dispatch now live in InteractScreen (chat.rs): - Enter pushes directly to SharedMindState.input (no app.submitted hop) - sync_from_agent displays pending input with dimmed color - Slash command table moved from event_loop.rs to chat.rs - cmd_switch_model kept as pub fn for tool-initiated switches Co-Authored-By: Proof of Concept <poc@bcachefs.org>
This commit is contained in:
parent
3e1be4d353
commit
48beb8b663
9 changed files with 404 additions and 370 deletions
309
src/user/chat.rs
309
src/user/chat.rs
|
|
@ -17,6 +17,166 @@ use super::{
|
|||
screen_legend,
|
||||
};
|
||||
use crate::user::ui_channel::{UiMessage, StreamTarget};
|
||||
use crate::mind::MindCommand;
|
||||
|
||||
// --- Slash command table ---
|
||||
|
||||
type CmdHandler = fn(&InteractScreen, &str);
|
||||
|
||||
struct SlashCommand {
|
||||
name: &'static str,
|
||||
help: &'static str,
|
||||
handler: CmdHandler,
|
||||
}
|
||||
|
||||
fn commands() -> Vec<SlashCommand> { vec![
|
||||
SlashCommand { name: "/quit", help: "Exit consciousness",
|
||||
handler: |_, _| {} },
|
||||
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())); } },
|
||||
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 mut ag = agent.lock().await;
|
||||
let entries = ag.entries_mut();
|
||||
let mut last_user_text = None;
|
||||
while let Some(entry) = entries.last() {
|
||||
if entry.message().role == crate::agent::api::types::Role::User {
|
||||
last_user_text = Some(entries.pop().unwrap().message().content_text().to_string());
|
||||
break;
|
||||
}
|
||||
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()));
|
||||
}
|
||||
}
|
||||
});
|
||||
} },
|
||||
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())));
|
||||
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()));
|
||||
}
|
||||
} 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;
|
||||
});
|
||||
}
|
||||
} },
|
||||
SlashCommand { name: "/score", help: "Score memory importance",
|
||||
handler: |s, _| { let _ = s.mind_tx.send(MindCommand::Score); } },
|
||||
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,
|
||||
)));
|
||||
} },
|
||||
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()));
|
||||
} },
|
||||
SlashCommand { name: "/wake", help: "Wake DMN to foraging",
|
||||
handler: |s, _| {
|
||||
let mut st = s.shared_mind.lock().unwrap();
|
||||
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()));
|
||||
} },
|
||||
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()));
|
||||
} },
|
||||
SlashCommand { name: "/help", help: "Show this help",
|
||||
handler: |s, _| { send_help(&s.ui_tx); } },
|
||||
]}
|
||||
|
||||
fn dispatch_command(input: &str) -> Option<SlashCommand> {
|
||||
let cmd_name = input.split_whitespace().next()?;
|
||||
commands().into_iter().find(|c| c.name == cmd_name)
|
||||
}
|
||||
|
||||
/// Switch model — used by both /model command and tool-initiated switches.
|
||||
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)));
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
let new_client = crate::agent::api::ApiClient::new(
|
||||
&resolved.api_base, &resolved.api_key, &resolved.model_id,
|
||||
);
|
||||
let prompt_changed = {
|
||||
let ag = agent.lock().await;
|
||||
resolved.prompt_file != ag.prompt_file
|
||||
};
|
||||
let mut ag = agent.lock().await;
|
||||
ag.swap_client(new_client);
|
||||
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,
|
||||
)));
|
||||
} else {
|
||||
let _ = ui_tx.send(UiMessage::Info(format!(
|
||||
"Switched to {} ({})", name, 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)));
|
||||
}
|
||||
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.
|
||||
#[derive(Clone, Copy, PartialEq, Default)]
|
||||
|
|
@ -245,12 +405,21 @@ pub(crate) struct InteractScreen {
|
|||
// State sync with agent — double buffer
|
||||
last_generation: u64,
|
||||
last_entries: Vec<crate::agent::context::ConversationEntry>,
|
||||
pending_display_count: usize,
|
||||
/// Reference to agent for state sync
|
||||
agent: std::sync::Arc<std::sync::Mutex<crate::agent::Agent>>,
|
||||
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 {
|
||||
pub fn new(agent: std::sync::Arc<std::sync::Mutex<crate::agent::Agent>>) -> Self {
|
||||
pub fn new(
|
||||
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),
|
||||
conversation: PaneState::new(true),
|
||||
|
|
@ -266,7 +435,11 @@ impl InteractScreen {
|
|||
call_timeout_secs: 60,
|
||||
last_generation: 0,
|
||||
last_entries: Vec::new(),
|
||||
pending_display_count: 0,
|
||||
agent,
|
||||
shared_mind,
|
||||
mind_tx,
|
||||
ui_tx,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -317,59 +490,99 @@ impl InteractScreen {
|
|||
}
|
||||
}
|
||||
|
||||
/// Sync conversation display from agent entries.
|
||||
/// Sync conversation display from agent entries + pending input.
|
||||
fn sync_from_agent(&mut self) {
|
||||
let agent = self.agent.lock().unwrap();
|
||||
let generation = agent.generation;
|
||||
let entries = agent.entries();
|
||||
|
||||
// Phase 1: detect desync and pop
|
||||
if generation != self.last_generation {
|
||||
self.conversation = PaneState::new(true);
|
||||
self.autonomous = PaneState::new(true);
|
||||
self.tools = PaneState::new(false);
|
||||
self.last_entries.clear();
|
||||
} else {
|
||||
// Pop entries from the tail that don't match
|
||||
while !self.last_entries.is_empty() {
|
||||
let i = self.last_entries.len() - 1;
|
||||
if entries.get(i) == Some(&self.last_entries[i]) {
|
||||
break;
|
||||
}
|
||||
let popped = self.last_entries.pop().unwrap();
|
||||
for (target, _, _) in Self::route_entry(&popped) {
|
||||
match target {
|
||||
PaneTarget::Conversation | PaneTarget::ConversationAssistant
|
||||
=> self.conversation.pop_line(),
|
||||
PaneTarget::Tools | PaneTarget::ToolResult
|
||||
=> self.tools.pop_line(),
|
||||
}
|
||||
}
|
||||
}
|
||||
// Pop previously-displayed pending input
|
||||
for _ in 0..self.pending_display_count {
|
||||
self.conversation.pop_line();
|
||||
}
|
||||
self.pending_display_count = 0;
|
||||
|
||||
// Phase 2: push new entries
|
||||
let start = self.last_entries.len();
|
||||
for entry in entries.iter().skip(start) {
|
||||
for (target, text, marker) in Self::route_entry(entry) {
|
||||
match target {
|
||||
PaneTarget::Conversation =>
|
||||
self.conversation.push_line_with_marker(text, Color::Cyan, marker),
|
||||
PaneTarget::ConversationAssistant =>
|
||||
self.conversation.push_line_with_marker(text, Color::Reset, marker),
|
||||
PaneTarget::Tools =>
|
||||
self.tools.push_line(text, Color::Yellow),
|
||||
PaneTarget::ToolResult => {
|
||||
for line in text.lines().take(20) {
|
||||
self.tools.push_line(format!(" {}", line), Color::DarkGray);
|
||||
// Sync agent entries
|
||||
if let Ok(agent) = self.agent.try_lock() {
|
||||
let generation = agent.generation;
|
||||
let entries = agent.entries();
|
||||
|
||||
// Phase 1: detect desync and pop
|
||||
if generation != self.last_generation {
|
||||
self.conversation = PaneState::new(true);
|
||||
self.autonomous = PaneState::new(true);
|
||||
self.tools = PaneState::new(false);
|
||||
self.last_entries.clear();
|
||||
} else {
|
||||
// Pop entries from the tail that don't match
|
||||
while !self.last_entries.is_empty() {
|
||||
let i = self.last_entries.len() - 1;
|
||||
if entries.get(i) == Some(&self.last_entries[i]) {
|
||||
break;
|
||||
}
|
||||
let popped = self.last_entries.pop().unwrap();
|
||||
for (target, _, _) in Self::route_entry(&popped) {
|
||||
match target {
|
||||
PaneTarget::Conversation | PaneTarget::ConversationAssistant
|
||||
=> self.conversation.pop_line(),
|
||||
PaneTarget::Tools | PaneTarget::ToolResult
|
||||
=> self.tools.pop_line(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.last_entries.push(entry.clone());
|
||||
|
||||
// Phase 2: push new entries
|
||||
let start = self.last_entries.len();
|
||||
for entry in entries.iter().skip(start) {
|
||||
for (target, text, marker) in Self::route_entry(entry) {
|
||||
match target {
|
||||
PaneTarget::Conversation =>
|
||||
self.conversation.push_line_with_marker(text, Color::Cyan, marker),
|
||||
PaneTarget::ConversationAssistant =>
|
||||
self.conversation.push_line_with_marker(text, Color::Reset, marker),
|
||||
PaneTarget::Tools =>
|
||||
self.tools.push_line(text, Color::Yellow),
|
||||
PaneTarget::ToolResult => {
|
||||
for line in text.lines().take(20) {
|
||||
self.tools.push_line(format!(" {}", line), Color::DarkGray);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.last_entries.push(entry.clone());
|
||||
}
|
||||
|
||||
self.last_generation = generation;
|
||||
}
|
||||
|
||||
self.last_generation = generation;
|
||||
// Display pending input (queued in Mind, not yet accepted)
|
||||
let mind = self.shared_mind.lock().unwrap();
|
||||
for input in &mind.input {
|
||||
self.conversation.push_line_with_marker(
|
||||
input.clone(), Color::DarkGray, Marker::User,
|
||||
);
|
||||
self.pending_display_count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// Dispatch user input — slash commands or conversation.
|
||||
fn dispatch_input(&self, input: &str, app: &mut App) {
|
||||
let input = input.trim();
|
||||
if input.is_empty() { return; }
|
||||
|
||||
if input == "/quit" || input == "/exit" {
|
||||
app.should_quit = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if input.starts_with('/') {
|
||||
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))));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Regular input → queue to Mind
|
||||
self.shared_mind.lock().unwrap().input.push(input.to_string());
|
||||
}
|
||||
|
||||
/// Process a UiMessage — update pane state.
|
||||
|
|
@ -680,7 +893,8 @@ impl ScreenView for InteractScreen {
|
|||
self.input_history.push(input.clone());
|
||||
}
|
||||
self.history_index = None;
|
||||
// TODO: push to submitted via app or return action
|
||||
self.dispatch_input(&input, app);
|
||||
self.textarea = new_textarea(vec![String::new()]);
|
||||
}
|
||||
}
|
||||
KeyCode::Up if key.modifiers.contains(KeyModifiers::CONTROL) => self.scroll_active_up(3),
|
||||
|
|
@ -727,6 +941,7 @@ impl ScreenView for InteractScreen {
|
|||
self.draw_main(frame, area, app);
|
||||
None
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// Draw the conversation pane with a two-column layout: marker gutter + text.
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ use ratatui::crossterm::event::{Event, EventStream, KeyEventKind};
|
|||
use futures::StreamExt;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::sync::Mutex;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::agent::Agent;
|
||||
use crate::agent::api::ApiClient;
|
||||
|
|
@ -19,89 +19,6 @@ use crate::user::ui_channel::{self, UiMessage};
|
|||
|
||||
// ── Slash commands ─────────────────────────────────────────────
|
||||
|
||||
type CmdHandler = for<'a> fn(
|
||||
&'a crate::mind::Mind,
|
||||
&'a tokio::sync::mpsc::UnboundedSender<MindCommand>,
|
||||
&'a ui_channel::UiSender,
|
||||
&'a str,
|
||||
);
|
||||
|
||||
struct SlashCommand {
|
||||
name: &'static str,
|
||||
help: &'static str,
|
||||
handler: CmdHandler,
|
||||
}
|
||||
|
||||
fn commands() -> Vec<SlashCommand> { vec![
|
||||
SlashCommand { name: "/quit", help: "Exit consciousness",
|
||||
handler: |_, _, _, _| {} },
|
||||
SlashCommand { name: "/new", help: "Start fresh session (saves current)",
|
||||
handler: |_, tx, _, _| { let _ = tx.send(MindCommand::NewSession); } },
|
||||
SlashCommand { name: "/save", help: "Save session to disk",
|
||||
handler: |_, _, ui, _| { let _ = ui.send(UiMessage::Info("Conversation is saved automatically.".into())); } },
|
||||
SlashCommand { name: "/retry", help: "Re-run last turn",
|
||||
handler: |m, tx, ui, _| {
|
||||
let agent = m.agent.clone();
|
||||
let mind_tx = tx.clone();
|
||||
let ui_tx = ui.clone();
|
||||
let mut tw = m.turn_watch();
|
||||
tokio::spawn(async move {
|
||||
let _ = tw.wait_for(|&active| !active).await;
|
||||
cmd_retry_inner(&agent, &mind_tx, &ui_tx).await;
|
||||
});
|
||||
} },
|
||||
SlashCommand { name: "/model", help: "Show/switch model (/model <name>)",
|
||||
handler: |m, _, ui, arg| {
|
||||
if arg.is_empty() {
|
||||
if let Ok(ag) = m.agent.try_lock() {
|
||||
let _ = ui.send(UiMessage::Info(format!("Current model: {}", ag.model())));
|
||||
let names = ag.app_config.model_names();
|
||||
if !names.is_empty() {
|
||||
let _ = ui.send(UiMessage::Info(format!("Available: {}", names.join(", "))));
|
||||
}
|
||||
} else {
|
||||
let _ = ui.send(UiMessage::Info("(busy)".into()));
|
||||
}
|
||||
} else {
|
||||
let agent = m.agent.clone();
|
||||
let ui_tx = ui.clone();
|
||||
let name = arg.to_string();
|
||||
tokio::spawn(async move { cmd_switch_model(&agent, &name, &ui_tx).await; });
|
||||
}
|
||||
} },
|
||||
SlashCommand { name: "/score", help: "Score memory importance",
|
||||
handler: |_, tx, _, _| { let _ = tx.send(MindCommand::Score); } },
|
||||
SlashCommand { name: "/dmn", help: "Show DMN state",
|
||||
handler: |m, _, ui, _| {
|
||||
let s = m.shared.lock().unwrap();
|
||||
let _ = ui.send(UiMessage::Info(format!("DMN: {:?} ({}/{})", s.dmn, s.dmn_turns, s.max_dmn_turns)));
|
||||
} },
|
||||
SlashCommand { name: "/sleep", help: "Put DMN to sleep",
|
||||
handler: |m, _, ui, _| {
|
||||
let mut s = m.shared.lock().unwrap();
|
||||
s.dmn = crate::mind::dmn::State::Resting { since: std::time::Instant::now() };
|
||||
s.dmn_turns = 0;
|
||||
let _ = ui.send(UiMessage::Info("DMN sleeping.".into()));
|
||||
} },
|
||||
SlashCommand { name: "/wake", help: "Wake DMN to foraging",
|
||||
handler: |m, _, ui, _| {
|
||||
let mut s = m.shared.lock().unwrap();
|
||||
if matches!(s.dmn, crate::mind::dmn::State::Off) { crate::mind::dmn::set_off(false); }
|
||||
s.dmn = crate::mind::dmn::State::Foraging;
|
||||
s.dmn_turns = 0;
|
||||
let _ = ui.send(UiMessage::Info("DMN foraging.".into()));
|
||||
} },
|
||||
SlashCommand { name: "/pause", help: "Full stop — no autonomous ticks (Ctrl+P)",
|
||||
handler: |m, _, ui, _| {
|
||||
let mut s = m.shared.lock().unwrap();
|
||||
s.dmn = crate::mind::dmn::State::Paused;
|
||||
s.dmn_turns = 0;
|
||||
let _ = ui.send(UiMessage::Info("DMN paused.".into()));
|
||||
} },
|
||||
SlashCommand { name: "/help", help: "Show this help",
|
||||
handler: |_, _, ui, _| { send_help(ui); } },
|
||||
]}
|
||||
|
||||
/// Top-level entry point — creates Mind and UI, wires them together.
|
||||
pub async fn start(cli: crate::user::CliArgs) -> Result<()> {
|
||||
let (config, _figment) = crate::config::load_session(&cli)?;
|
||||
|
|
@ -116,8 +33,8 @@ pub async fn start(cli: crate::user::CliArgs) -> Result<()> {
|
|||
|
||||
let mind = crate::mind::Mind::new(config, ui_tx.clone(), turn_tx);
|
||||
|
||||
let shared_context = mind.agent.lock().unwrap().shared_context.clone();
|
||||
let shared_active_tools = mind.agent.lock().unwrap().active_tools.clone();
|
||||
let shared_context = mind.agent.lock().await.shared_context.clone();
|
||||
let shared_active_tools = mind.agent.lock().await.active_tools.clone();
|
||||
|
||||
let mut result = Ok(());
|
||||
tokio_scoped::scope(|s| {
|
||||
|
|
@ -138,55 +55,7 @@ pub async fn start(cli: crate::user::CliArgs) -> Result<()> {
|
|||
result
|
||||
}
|
||||
|
||||
fn dispatch_command(input: &str) -> Option<SlashCommand> {
|
||||
let cmd_name = input.split_whitespace().next()?;
|
||||
commands().into_iter().find(|c| c.name == cmd_name)
|
||||
}
|
||||
|
||||
fn send_help(ui_tx: &ui_channel::UiSender) {
|
||||
for cmd in &commands() {
|
||||
let _ = ui_tx.send(UiMessage::Info(format!(" {:12} {}", cmd.name, cmd.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 F10=context F2=agents".into(),
|
||||
));
|
||||
let _ = ui_tx.send(UiMessage::Info(
|
||||
" Shift+click for native text selection (copy/paste)".into(),
|
||||
));
|
||||
}
|
||||
|
||||
async fn cmd_retry_inner(
|
||||
agent: &Arc<Mutex<Agent>>,
|
||||
mind_tx: &tokio::sync::mpsc::UnboundedSender<MindCommand>,
|
||||
ui_tx: &ui_channel::UiSender,
|
||||
) {
|
||||
let mut agent_guard = agent.lock().unwrap();
|
||||
let entries = agent_guard.entries_mut();
|
||||
let mut last_user_text = None;
|
||||
while let Some(entry) = entries.last() {
|
||||
if entry.message().role == crate::agent::api::types::Role::User {
|
||||
last_user_text = Some(entries.pop().unwrap().message().content_text().to_string());
|
||||
break;
|
||||
}
|
||||
entries.pop();
|
||||
}
|
||||
drop(agent_guard);
|
||||
match last_user_text {
|
||||
Some(text) => {
|
||||
let preview_len = text.len().min(60);
|
||||
let _ = ui_tx.send(UiMessage::Info(format!("(retrying: {}...)", &text[..preview_len])));
|
||||
// Send as a Turn command — Mind will process it
|
||||
let _ = mind_tx.send(MindCommand::Turn(text, crate::user::ui_channel::StreamTarget::Conversation));
|
||||
}
|
||||
None => {
|
||||
let _ = ui_tx.send(UiMessage::Info("(nothing to retry)".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn hotkey_cycle_reasoning(mind: &crate::mind::Mind, ui_tx: &ui_channel::UiSender) {
|
||||
if let Ok(mut ag) = mind.agent.try_lock() {
|
||||
|
|
@ -211,7 +80,7 @@ fn hotkey_cycle_reasoning(mind: &crate::mind::Mind, ui_tx: &ui_channel::UiSender
|
|||
}
|
||||
|
||||
async fn hotkey_kill_processes(mind: &crate::mind::Mind, ui_tx: &ui_channel::UiSender) {
|
||||
let active_tools = mind.agent.lock().unwrap().active_tools.clone();
|
||||
let active_tools = mind.agent.lock().await.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()));
|
||||
|
|
@ -278,44 +147,6 @@ pub fn send_context_info(config: &crate::config::SessionConfig, ui_tx: &ui_chann
|
|||
)));
|
||||
}
|
||||
|
||||
pub async fn cmd_switch_model(
|
||||
agent: &Arc<Mutex<Agent>>,
|
||||
name: &str,
|
||||
ui_tx: &ui_channel::UiSender,
|
||||
) {
|
||||
let resolved = {
|
||||
let ag = agent.lock().unwrap();
|
||||
match ag.app_config.resolve_model(name) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
let _ = ui_tx.send(UiMessage::Info(format!("{}", e)));
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let new_client = ApiClient::new(&resolved.api_base, &resolved.api_key, &resolved.model_id);
|
||||
let prompt_changed = {
|
||||
let ag = agent.lock().unwrap();
|
||||
resolved.prompt_file != ag.prompt_file
|
||||
};
|
||||
|
||||
let mut ag = agent.lock().unwrap();
|
||||
ag.swap_client(new_client);
|
||||
|
||||
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,
|
||||
)));
|
||||
} else {
|
||||
let _ = ui_tx.send(UiMessage::Info(format!(
|
||||
"Switched to {} ({})", name, resolved.model_id,
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
fn diff_mind_state(
|
||||
cur: &crate::mind::MindState,
|
||||
|
|
@ -336,8 +167,6 @@ fn diff_mind_state(
|
|||
}
|
||||
// Input consumed — Mind started a turn with it
|
||||
if !prev.input.is_empty() && cur.input.is_empty() {
|
||||
let text = prev.input.join("\n");
|
||||
let _ = ui_tx.send(UiMessage::UserInput(text));
|
||||
*dirty = true;
|
||||
}
|
||||
if cur.turn_active != prev.turn_active {
|
||||
|
|
@ -382,7 +211,9 @@ 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());
|
||||
let mut interact = crate::user::chat::InteractScreen::new(
|
||||
mind.agent.clone(), mind.shared.clone(), mind_tx.clone(), ui_tx.clone(),
|
||||
);
|
||||
// Overlay screens: F2=conscious, F3=subconscious, F4=unconscious, F5=thalamus
|
||||
let mut screens: Vec<Box<dyn tui::ScreenView>> = vec![
|
||||
Box::new(crate::user::context::ConsciousScreen::new()),
|
||||
|
|
@ -443,11 +274,10 @@ pub async fn run(
|
|||
continue;
|
||||
}
|
||||
|
||||
// Global keys (Ctrl combos)
|
||||
app.handle_global_key(key);
|
||||
|
||||
// Store pending key for active overlay screen
|
||||
pending_key = Some(key);
|
||||
// Global keys (Ctrl combos) — only pass to screen if not consumed
|
||||
if !app.handle_global_key(key) {
|
||||
pending_key = Some(key);
|
||||
}
|
||||
dirty = true;
|
||||
}
|
||||
Some(Ok(Event::Mouse(_mouse))) => {
|
||||
|
|
@ -509,23 +339,6 @@ pub async fn run(
|
|||
}
|
||||
}
|
||||
|
||||
// Process submitted input
|
||||
let submitted: Vec<String> = app.submitted.drain(..).collect();
|
||||
for input in submitted {
|
||||
let input = input.trim().to_string();
|
||||
if input.is_empty() { continue; }
|
||||
if input == "/quit" || input == "/exit" {
|
||||
app.should_quit = true;
|
||||
} else if let Some(cmd) = dispatch_command(&input) {
|
||||
(cmd.handler)(mind, &mind_tx, &ui_tx, &input[cmd.name.len()..].trim_start());
|
||||
} else {
|
||||
let mut s = shared_mind.lock().unwrap();
|
||||
diff_mind_state(&s, &prev_mind, &ui_tx, &mut dirty);
|
||||
s.input.push(input);
|
||||
prev_mind = s.clone();
|
||||
}
|
||||
}
|
||||
|
||||
// Handle hotkey actions
|
||||
let actions: Vec<HotkeyAction> = app.hotkey_actions.drain(..).collect();
|
||||
for action in actions {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue