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.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue