diff --git a/packages/cli-rs/crates/mini/src/prompt/api.rs b/packages/cli-rs/crates/mini/src/prompt/api.rs new file mode 100644 index 00000000000..8ae1cb266a7 --- /dev/null +++ b/packages/cli-rs/crates/mini/src/prompt/api.rs @@ -0,0 +1,229 @@ +//! The requests the footer prompt makes: the completion catalogs (`catalog.shared.ts`), the file search, the +//! session's prompt history (`resolveCurrentSession`), and the turns it sends (`admitPrompt`, `runShellTurn`, +//! `session.compact`, `session.inbox.update` in `stream-v2.transport.ts` and `runtime.ts`). + +use opencode_api::client::{Call, Client, RequestOptions}; +use serde_json::{Map, Value, json}; + +use super::complete::{Agent, Catalog, Command, Reference}; +use super::parts::{Delivery, RunPrompt}; +use crate::replay::encode; + +fn error(error: opencode_api::error::Error) -> String { + error.to_string() +} + +async fn list(client: &Client, path: &str, directory: &str) -> Result, String> { + let mut call = Call::new("GET", path.to_owned(), 200, &[400, 401, 404]); + call.query("location", &json!({ "directory": directory })) + .map_err(error)?; + let value: Value = client + .json(call, &RequestOptions::default()) + .await + .map_err(error)?; + Ok(value["data"].as_array().cloned().unwrap_or_default()) +} + +/// `loadCatalog`: agents, references, and commands of the location; a failed list is empty. +pub async fn catalog(client: &Client, directory: &str) -> Catalog { + let (agents, references, commands) = futures_util::future::join3( + list(client, "/api/agent", directory), + list(client, "/api/reference", directory), + list(client, "/api/command", directory), + ) + .await; + let text = |value: &Value| value.as_str().map(str::to_owned); + Catalog { + agents: agents + .unwrap_or_default() + .iter() + .map(|agent| Agent { + id: text(&agent["id"]).unwrap_or_default(), + name: text(&agent["name"]).unwrap_or_default(), + mode: text(&agent["mode"]).unwrap_or_default(), + hidden: agent["hidden"].as_bool().unwrap_or(false), + }) + .collect(), + references: references + .unwrap_or_default() + .iter() + .filter(|reference| !reference["hidden"].as_bool().unwrap_or(false)) + .map(|reference| Reference { + name: text(&reference["name"]).unwrap_or_default(), + path: text(&reference["path"]).unwrap_or_default(), + description: text(&reference["description"]) + .or_else(|| match reference["source"]["type"].as_str() { + Some("git") => text(&reference["source"]["repository"]), + _ => text(&reference["source"]["path"]), + }) + .unwrap_or_default(), + }) + .collect(), + // `runCommand` keeps the name and description only. + commands: Some( + commands + .unwrap_or_default() + .iter() + .map(|command| Command { + name: text(&command["name"]).unwrap_or_default(), + description: text(&command["description"]), + source: None, + }) + .collect(), + ), + } +} + +/// `findFiles`: the paths of the location's files that match `query`; nothing on a failure. +pub async fn find_files(client: &Client, directory: &str, query: &str) -> Vec { + let mut call = Call::new("GET", "/api/fs/find".to_owned(), 200, &[400, 401, 404]); + let built = [ + call.query("location", &json!({ "directory": directory })), + call.query("query", query), + call.query("type", "file"), + ]; + if built.iter().any(Result::is_err) { + return Vec::new(); + } + client + .json::(call, &RequestOptions::default()) + .await + .map(|value| { + value["data"] + .as_array() + .into_iter() + .flatten() + .filter_map(|entry| entry["path"].as_str().map(str::to_owned)) + .collect() + }) + .unwrap_or_default() +} + +/// `sessionHistory` of `resolveCurrentSession`: the session's user prompts, oldest first. +pub async fn history(client: &Client, session: &str) -> Vec { + crate::replay::messages(client, session, 200) + .await + .unwrap_or_default() + .iter() + .filter(|message| message["type"] == "user") + .map(RunPrompt::from_message) + .collect() +} + +/// `admitPrompt`: `session.command` for a prompt that names a server command, else `session.prompt`. +pub async fn admit(client: &Client, session: &str, prompt: &RunPrompt, delivery: Delivery) -> Result<(), String> { + let mut body = Map::new(); + let (path, status) = match &prompt.command { + Some(command) => { + body.insert("name".into(), command.name.clone().into()); + body.insert("text".into(), command.arguments.clone().into()); + ("command", 204) + } + None => { + if let Some(id) = &prompt.message_id { + body.insert("id".into(), id.clone().into()); + } + body.insert("text".into(), prompt.text.clone().into()); + ("prompt", 200) + } + }; + for (key, list) in [ + ("files", prompt.files()), + ("agents", prompt.agents()), + ("skills", prompt.skills()), + ] { + if !list.is_empty() { + body.insert(key.into(), Value::Array(list)); + } + } + body.insert("delivery".into(), delivery.as_str().into()); + let mut call = Call::new( + "POST", + format!("/api/session/{}/{path}", encode(session)), + status, + &[400, 401, 404, 409, 500], + ); + call.json(&Value::Object(body)).map_err(error)?; + if status == 204 { + return client + .empty(call, &RequestOptions::default()) + .await + .map_err(error); + } + client + .json::(call, &RequestOptions::default()) + .await + .map(drop) + .map_err(error) +} + +/// `runShellTurn`: `session.shell`, which answers once the command ran. +pub async fn shell(client: &Client, session: &str, id: &str, command: &str) -> Result<(), String> { + let mut call = Call::new( + "POST", + format!("/api/session/{}/shell", encode(session)), + 204, + &[400, 401, 404, 409], + ); + call.json(&json!({ "id": id, "command": command })) + .map_err(error)?; + client + .empty(call, &RequestOptions::default()) + .await + .map_err(error) +} + +/// `session.compact`. +pub async fn compact(client: &Client, session: &str) -> Result<(), String> { + let mut call = Call::new( + "POST", + format!("/api/session/{}/compact", encode(session)), + 200, + &[400, 401, 404, 409], + ); + call.json(&json!({})).map_err(error)?; + client + .json::(call, &RequestOptions::default()) + .await + .map(drop) + .map_err(error) +} + +/// `session.inbox.update`: moves a pending prompt between queue and steer. +pub async fn deliver(client: &Client, session: &str, inbox: &str, delivery: Delivery) -> Result<(), String> { + let mut call = Call::new( + "PATCH", + format!("/api/session/{}/inbox/{}", encode(session), encode(inbox)), + 200, + &[400, 401, 404, 409], + ); + call.json(&json!({ "delivery": delivery.as_str() })) + .map_err(error)?; + client + .json::(call, &RequestOptions::default()) + .await + .map(drop) + .map_err(error) +} + +/// `switchAgent` and `switchModel` before an ordinary prompt; a command keeps the session's selection. +pub async fn select(client: &Client, session: &str, agent: Option<&str>, model: Option<&Value>) -> Result<(), String> { + for (path, body) in [ + ("agent", agent.map(|agent| json!({ "agent": agent }))), + ("model", model.map(|model| json!({ "model": model }))), + ] { + let Some(body) = body else { continue }; + let mut call = Call::new( + "POST", + format!("/api/session/{}/{path}", encode(session)), + 204, + &[400, 401, 404], + ); + call.json(&body).map_err(error)?; + client + .empty(call, &RequestOptions::default()) + .await + .map_err(error)?; + } + Ok(()) +} diff --git a/packages/cli-rs/crates/mini/src/prompt/complete.rs b/packages/cli-rs/crates/mini/src/prompt/complete.rs new file mode 100644 index 00000000000..ebf16645977 --- /dev/null +++ b/packages/cli-rs/crates/mini/src/prompt/complete.rs @@ -0,0 +1,358 @@ +//! The prompt's autocomplete options (`footer.prompt.tsx:410-570`): `/` lists mini's built-ins and the server's +//! commands; `@` lists subagents, then the file search's results, then references. A typed query filters them +//! with fuzzysort, except the files, which the server ranks. + +use opencode_ui::prompt_input::parse::{self, LineRange}; +use opencode_ui::select::fuzzy; +use unicode_width::UnicodeWidthStr; + +use super::menu::Item; +use super::parts::{EXIT_COMMANDS, File, Part}; + +/// `RunAgent`. +#[derive(Clone, Debug, PartialEq)] +pub struct Agent { + pub id: String, + pub name: String, + pub mode: String, + pub hidden: bool, +} + +/// `RunReference`. +#[derive(Clone, Debug, PartialEq)] +pub struct Reference { + pub name: String, + pub path: String, + /// The description, else the git repository or the path it came from. + pub description: String, +} + +/// `RunCommand`. +#[derive(Clone, Debug, PartialEq)] +pub struct Command { + pub name: String, + pub description: Option, + pub source: Option, +} + +/// What the footer completes from (`catalog` event). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Catalog { + pub agents: Vec, + pub references: Vec, + /// `None` until the command list arrives: a slash command then waits ("loading commands"). + pub commands: Option>, +} + +/// A slash built-in that is not sent as typed. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Action { + Editor, + Settings, +} + +/// `PromptOption`. +#[derive(Clone, Debug, PartialEq)] +pub enum Choice { + Mention { + display: String, + value: String, + description: Option, + part: Part, + directory: bool, + }, + Slash { + name: String, + display: String, + description: Option, + action: Option, + }, +} + +impl Choice { + pub fn item(&self) -> Item { + let (display, description) = match self { + Choice::Mention { + display, + description, + .. + } + | Choice::Slash { + display, + description, + .. + } => (display, description), + }; + Item { + display: display.clone(), + description: description.clone(), + } + } + + fn keys(&self) -> [Option<&str>; 3] { + match self { + Choice::Mention { + display, + value, + description, + .. + } => [Some(value.trim_end()), Some(display), description.as_deref()], + Choice::Slash { + name, + display, + description, + .. + } => [Some(name.trim_end()), Some(display), description.as_deref()], + } + } +} + +/// The slash options: the server's commands, then the built-ins, sorted by what they show. +pub fn slash(catalog: &Catalog) -> Vec { + let builtin = |name: &str, description: &str, action: Option| Choice::Slash { + name: name.to_owned(), + display: format!("/{name}"), + description: Some(description.to_owned()), + action, + }; + let mut builtins = vec![ + builtin("editor", "compose in your external editor", Some(Action::Editor)), + builtin("settings", "configure Mini transcript output", Some(Action::Settings)), + builtin("new", "start a new session", None), + builtin("compact", "compact older session context to free space", None), + ]; + builtins.extend( + EXIT_COMMANDS + .iter() + .map(|name| builtin(name, "close OpenCode", None)), + ); + let hidden = |name: &str| builtins.iter().any(|item| matches!(item, Choice::Slash { name: other, .. } if other == name)); + let mut all: Vec = catalog + .commands + .iter() + .flatten() + .filter(|command| !hidden(&command.name)) + .map(|command| Choice::Slash { + name: command.name.clone(), + display: format!( + "/{}{}", + command.name, + if command.source.as_deref() == Some("mcp") { + ":mcp" + } else { + "" + } + ), + description: command.description.clone(), + action: None, + }) + .collect(); + all.extend(builtins); + all.sort_by(|a, b| locale_compare(&a.item().display, &b.item().display)); + all +} + +/// The subagents a mention offers: visible agents that are not primary. +pub fn agents(catalog: &Catalog) -> Vec { + catalog + .agents + .iter() + .filter(|agent| !agent.hidden && agent.mode != "primary") + .map(|agent| Choice::Mention { + display: format!("@{}", agent.name), + value: agent.id.clone(), + description: None, + part: Part::Agent { + name: agent.id.clone(), + mention: None, + }, + directory: false, + }) + .collect() +} + +pub fn references(catalog: &Catalog) -> Vec { + catalog + .references + .iter() + .map(|reference| Choice::Mention { + display: format!("@{}", reference.name), + value: reference.name.clone(), + description: Some(reference.description.clone()), + part: Part::File(File { + url: parse::file_url(&reference.path), + mime: Some("application/x-directory".into()), + filename: Some(reference.name.clone()), + ..File::default() + }), + directory: false, + }) + .collect() +} + +/// The file search's results for a query with an optional `#12-20` range, shown by their shortest path suffix +/// that fits `width`. +pub fn files(results: &[String], range: Option, directory: &str, width: usize) -> Vec { + results + .iter() + .map(|item| { + let is_directory = item.ends_with('/'); + let mut url = parse::file_url(&parse::resolve(directory, item)); + let mut filename = item.clone(); + if let Some(range) = range.filter(|_| !is_directory) { + filename = match range.end { + Some(end) => format!("{item}#{}-{end}", range.start), + None => format!("{item}#{}", range.start), + }; + url.push_str(&format!("?start={}", range.start)); + if let Some(end) = range.end { + url.push_str(&format!("&end={end}")); + } + } + let segments: Vec<&str> = filename.split('/').collect(); + let shown = if is_directory { + segments.len() - 1 + } else { + segments.len() + }; + let paths: Vec = (0..shown) + .map(|index| format!("@{}", segments[index..].join("/"))) + .collect(); + let display = paths + .iter() + .find(|path| path.width() <= width) + .or(paths.last()) + .cloned() + .unwrap_or_else(|| format!("@{filename}")); + Choice::Mention { + display, + value: filename.clone(), + description: None, + part: Part::File(File { + url, + mime: Some( + if is_directory { + "application/x-directory" + } else { + "text/plain" + } + .into(), + ), + filename: Some(filename), + ..File::default() + }), + directory: is_directory, + } + }) + .collect() +} + +/// The options for `query` (`options` memo): everything without a query; with one, fuzzysort over agents and +/// references around the unfiltered files, or over every slash option. +pub fn filter(slash_mode: bool, query: &str, catalog: &Catalog, files: Vec) -> Vec { + if slash_mode { + let all = slash(catalog); + if query.is_empty() { + return all; + } + return go(parse::file_line_range(query).0, all); + } + let (agents, references) = (agents(catalog), references(catalog)); + if query.is_empty() { + return agents.into_iter().chain(files).chain(references).collect(); + } + let search = parse::file_line_range(query).0; + go(search, agents) + .into_iter() + .chain(files) + .chain(go(search, references)) + .collect() +} + +/// `fuzzysort.go(search, items, { keys })`: best first, every match. +fn go(search: &str, items: Vec) -> Vec { + fuzzy::go_scored(search, &items, Choice::keys, |_, score, _| score, 0.0, usize::MAX) + .into_iter() + .map(|index| items[index].clone()) + .collect() +} + +/// `localeCompare` for option labels: case-insensitive, lowercase first on a tie. +fn locale_compare(a: &str, b: &str) -> std::cmp::Ordering { + a.to_lowercase() + .cmp(&b.to_lowercase()) + .then_with(|| b.cmp(a)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn catalog() -> Catalog { + let agent = |id: &str, mode: &str| Agent { + id: id.into(), + name: id.into(), + mode: mode.into(), + hidden: false, + }; + let command = |name: &str, description: &str| Command { + name: name.into(), + description: Some(description.into()), + source: Some("command".into()), + }; + Catalog { + agents: vec![ + agent("build", "primary"), + agent("general", "subagent"), + agent("explore", "subagent"), + ], + references: Vec::new(), + commands: Some(vec![ + command("review", "Review the working tree"), + command("init", "Create AGENTS.md"), + command("new", "shadowed by the built-in"), + ]), + } + } + + fn shown(choices: &[Choice]) -> Vec { + choices.iter().map(|choice| choice.item().display).collect() + } + + #[test] + fn slash_lists_builtins_and_commands_as_typescript_does() { + // The order TS mini shows (`parity/scenarios/M.2/slash.pty.ts`). + assert_eq!( + shown(&filter(true, "", &catalog(), Vec::new())), + ["/compact", "/editor", "/exit", "/init", "/new", "/q", "/quit", "/review", "/settings"] + ); + assert_eq!( + shown(&filter(true, "re", &catalog(), Vec::new())), + ["/review", "/init", "/settings", "/new", "/compact", "/editor"] + ); + } + + #[test] + fn mentions_list_subagents_then_files() { + let found = files(&["src/general.ts".into(), "src/".into()], None, "/w", 56); + let choices = filter(false, "gen", &catalog(), found); + assert_eq!(shown(&choices), ["@general", "@src/general.ts", "@src/"]); + let Choice::Mention { part: Part::File(file), directory, .. } = &choices[2] else { + panic!("a file"); + }; + assert!(*directory); + assert_eq!(file.mime.as_deref(), Some("application/x-directory")); + let ranged = files( + &["src/a.ts".into()], + Some(LineRange { start: 3, end: Some(9) }), + "/w", + 8, + ); + let Choice::Mention { display, value, part: Part::File(file), .. } = &ranged[0] else { + panic!("a file"); + }; + assert_eq!(value, "src/a.ts#3-9"); + assert_eq!(display, "@a.ts#3-9"); + assert_eq!(file.url, "file:///w/src/a.ts?start=3&end=9"); + } +} diff --git a/packages/cli-rs/crates/mini/src/prompt/history.rs b/packages/cli-rs/crates/mini/src/prompt/history.rs new file mode 100644 index 00000000000..1ad5cfcd245 --- /dev/null +++ b/packages/cli-rs/crates/mini/src/prompt/history.rs @@ -0,0 +1,153 @@ +//! The prompt's history ring (`prompt.shared.ts`): the session's earlier prompts and those sent since. Up at the +//! start of the text saves the draft and steps back; Down at the end steps forward, and past the newest entry +//! restores the draft. + +use opencode_ui::prompt_input::parse::measure; + +use super::parts::RunPrompt; + +/// `HISTORY_LIMIT`. +const LIMIT: usize = 200; + +/// `PromptHistoryState`. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct History { + pub items: Vec, + pub index: Option, + pub draft: String, +} + +/// `PromptMove`: the new state, and the text and cursor to show when the move applies. +#[derive(Debug, PartialEq)] +pub struct Move { + pub state: History, + pub apply: Option<(String, u32)>, +} + +impl History { + /// `createPromptHistory`: entries with content, without adjacent repeats, the newest `LIMIT`. + pub fn new(items: &[RunPrompt]) -> Self { + let mut next: Vec = Vec::new(); + for item in items.iter().filter(|item| item.has_content()) { + if next.last().is_some_and(|last| last.same(item)) { + continue; + } + next.push(item.copy()); + } + let skip = next.len().saturating_sub(LIMIT); + Self { + items: next.split_off(skip), + index: None, + draft: String::new(), + } + } + + /// `pushPromptHistory`. + pub fn push(&self, prompt: &RunPrompt) -> Self { + if !prompt.has_content() { + return self.clone(); + } + let mut items = self.items.clone(); + if !items.last().is_some_and(|last| last.same(prompt)) { + items.push(prompt.copy()); + } + let skip = items.len().saturating_sub(LIMIT); + Self { + items: items.split_off(skip), + index: None, + draft: String::new(), + } + } + + /// `movePromptHistory`. + pub fn step(&self, up: bool, text: &str, cursor: u32) -> Move { + let none = || Move { + state: self.clone(), + apply: None, + }; + if self.items.is_empty() || (up && cursor != 0) || (!up && cursor != measure(text)) { + return none(); + } + let Some(index) = self.index else { + if !up { + return none(); + } + let index = self.items.len() - 1; + return Move { + state: Self { + index: Some(index), + draft: text.to_owned(), + ..self.clone() + }, + apply: Some((self.items[index].text.clone(), 0)), + }; + }; + if up && index == 0 { + return none(); + } + let next = if up { index - 1 } else { index + 1 }; + if next >= self.items.len() { + return Move { + state: Self { + index: None, + ..self.clone() + }, + apply: Some((self.draft.clone(), measure(&self.draft))), + }; + } + let text = self.items[next].text.clone(); + let cursor = if up { 0 } else { measure(&text) }; + Move { + state: Self { + index: Some(next), + ..self.clone() + }, + apply: Some((text, cursor)), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn texts(history: &History) -> Vec<&str> { + history.items.iter().map(|item| item.text.as_str()).collect() + } + + #[test] + fn entries_drop_empties_and_adjacent_repeats() { + let history = History::new(&[ + RunPrompt::text("a"), + RunPrompt::text(" "), + RunPrompt::text("a"), + RunPrompt::text("b"), + RunPrompt::text("a"), + ]); + assert_eq!(texts(&history), ["a", "b", "a"]); + assert_eq!(texts(&history.push(&RunPrompt::text("a"))), ["a", "b", "a"]); + assert_eq!(texts(&history.push(&RunPrompt::text("c"))), ["a", "b", "a", "c"]); + let many: Vec = (0..205).map(|i| RunPrompt::text(i.to_string())).collect(); + let history = History::new(&many); + assert_eq!(history.items.len(), 200); + assert_eq!(history.items[0].text, "5"); + } + + #[test] + fn steps_follow_the_cursor_and_restore_the_draft() { + let history = History::new(&[RunPrompt::text("first"), RunPrompt::text("second")]); + // Up away from the start does nothing. + assert_eq!(history.step(true, "draft", 3).apply, None); + let up = history.step(true, "draft", 0); + assert_eq!(up.apply, Some(("second".into(), 0))); + let up = up.state.step(true, "second", 0); + assert_eq!(up.apply, Some(("first".into(), 0))); + assert_eq!(up.state.step(true, "first", 0).apply, None); + let down = up.state.step(false, "first", 5); + assert_eq!(down.apply, Some(("second".into(), 6))); + let down = down.state.step(false, "second", 6); + assert_eq!(down.apply, Some(("draft".into(), 5))); + assert_eq!(down.state.index, None); + assert_eq!(down.state.step(false, "draft", 5).apply, None); + } +} diff --git a/packages/cli-rs/crates/mini/src/prompt/menu.rs b/packages/cli-rs/crates/mini/src/prompt/menu.rs new file mode 100644 index 00000000000..7e6522e512d --- /dev/null +++ b/packages/cli-rs/crates/mini/src/prompt/menu.rs @@ -0,0 +1,236 @@ +//! The footer menu (`footer.menu.tsx`) the autocomplete shows below the prompt, and its selection window +//! (`createFooterMenuState` on `ui/select-controller.ts`). Only the flat form is here; the grouped form belongs to +//! M.3's command and selection views. + +use opentui::prelude::*; +use unicode_width::UnicodeWidthStr; + +use crate::theme::FooterTheme; + +/// `FOOTER_MENU_ROWS`. +pub const MENU_ROWS: u16 = 8; +/// `FOOTER_COMPACT_WIDTH`. +pub const COMPACT_WIDTH: u16 = 40; + +/// One row (`RunFooterMenuItem` without icons and footers). +#[derive(Clone, Debug, PartialEq)] +pub struct Item { + pub display: String, + pub description: Option, +} + +/// The highlighted row and the first row shown. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Selection { + pub selected: usize, + pub offset: usize, +} + +impl Selection { + /// The rows the menu takes: at least one, at most `limit`. + pub fn rows(count: usize, limit: usize) -> usize { + count.clamp(1, limit.max(1)) + } + + /// The effect that keeps the selection inside `count` items (`reconcileSelection`, `revealSelectionOffset`). + pub fn reconcile(self, count: usize, limit: usize) -> Self { + let selected = self.selected.min(count.saturating_sub(1)); + Self { + selected, + offset: reveal(self.offset, count, limit.max(1), selected), + } + } + + /// `move`: clamped, with a margin of up to two rows (`moveSelectionOffset`). + pub fn step(self, count: usize, limit: usize, down: bool) -> Self { + let limit = limit.max(1); + if count == 0 { + return Self::default(); + } + let selected = if down { + (self.selected + 1).min(count - 1) + } else { + self.selected.saturating_sub(1) + }; + let max = count.saturating_sub(limit); + let margin = ((limit - 1) / 2).min(2); + let offset = if !down && selected < self.offset + margin { + selected.saturating_sub(margin).min(max) + } else if down && selected + margin + 1 > self.offset + limit { + (selected + margin + 1 - limit).min(max) + } else { + self.offset.min(max) + }; + Self { selected, offset } + } +} + +fn reveal(offset: usize, count: usize, limit: usize, selected: usize) -> usize { + let max = count.saturating_sub(limit); + if selected < offset { + return selected.min(max); + } + if selected >= offset + limit { + return (selected + 1 - limit).min(max); + } + offset.min(max) +} + +/// `Locale.truncateWidth`, or three dots in mono (`footerMenuText`). +pub fn fit(text: &str, width: usize, mono: bool) -> String { + if text.width() <= width { + return text.to_owned(); + } + if width == 0 { + return String::new(); + } + let suffix = if mono { ".".repeat(width.min(3)) } else { "…".to_owned() }; + take_width(text, width - suffix.width()) + &suffix +} + +/// `Locale.takeWidth`. +pub fn take_width(text: &str, width: usize) -> String { + let mut out = String::new(); + for character in text.chars() { + if out.width() + unicode_width::UnicodeWidthChar::width(character).unwrap_or(0) > width { + break; + } + out.push(character); + } + out +} + +/// The menu: a column of one-row items, without the left border (`border={false}`), padded two cells on each +/// side (one below 40 columns). +pub struct Menu { + app: App, + root: View, +} + +impl Menu { + pub fn new(app: &App) -> Self { + Self { + app: app.clone(), + root: View::new(app) + .column() + .shrink(0.0) + .width(Length::percent(100.0)) + .visible(false), + } + } + + pub fn root(&self) -> &View { + &self.root + } + + pub fn hide(&self) { + self.root.visible(false); + } + + /// Shows `rows` items from the selection's offset. + pub fn show( + &self, + items: &[Item], + selection: Selection, + rows: usize, + width: u16, + theme: &FooterTheme, + mono: bool, + ) { + let app = &self.app; + let pad = if width < COMPACT_WIDTH { 1 } else { 2 }; + let available = usize::from(width.saturating_sub(pad * 2)); + let column = items + .iter() + .filter(|item| item.description.is_some()) + .map(|item| item.display.width()) + .max() + .map_or(0, |widest| widest + 2); + self.root.clear(); + self.root.height(rows as u32).visible(true); + if items.is_empty() { + self.root.add( + &View::new(app).height(1).padding_x(u32::from(pad)).child( + &Text::new(app, "No matching items") + .fg(theme.muted) + .wrap(WrapMode::None) + .truncate(true), + ), + ); + return; + } + for (index, item) in items.iter().enumerate().skip(selection.offset).take(rows) { + let active = index == selection.selected; + let fg = if active { + theme.action_focused_text + } else { + theme.formfield_text + }; + let mut display = fit(&item.display, available, mono).fg(fg); + if active { + display = display.bold(); + if mono { + display = display.inverse(); + } + } + let mut spans = vec![display]; + let description = item.description.as_deref().and_then(|description| { + let remaining = available.saturating_sub(column); + (remaining >= description.width().min(12)).then(|| fit(description, remaining, mono)) + }); + if let Some(description) = description { + let muted = if active { + theme.action_focused_text + } else { + theme.muted + }; + spans.push(" ".repeat(column.saturating_sub(item.display.width()).max(1)).fg(muted)); + spans.push(description.fg(muted)); + } + let row = View::new(app) + .row() + .height(1) + .shrink(0.0) + .padding_x(u32::from(pad)) + .child(&Text::new(app, spans).wrap(WrapMode::None).truncate(true)); + if active { + row.bg(theme.action_focused_bg); + } + self.root.add(&row); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn selection_moves_with_a_margin_and_clamps() { + let mut selection = Selection::default(); + for _ in 0..5 { + selection = selection.step(10, 8, true); + } + assert_eq!(selection, Selection { selected: 5, offset: 0 }); + selection = selection.step(10, 8, true); + assert_eq!(selection, Selection { selected: 6, offset: 1 }); + for _ in 0..10 { + selection = selection.step(10, 8, true); + } + assert_eq!(selection, Selection { selected: 9, offset: 2 }); + selection = selection.step(10, 8, false).step(10, 8, false).step(10, 8, false).step(10, 8, false).step(10, 8, false); + assert_eq!(selection, Selection { selected: 4, offset: 2 }); + selection = selection.step(10, 8, false); + assert_eq!(selection, Selection { selected: 3, offset: 1 }); + assert_eq!(Selection { selected: 9, offset: 2 }.reconcile(3, 8), Selection { selected: 2, offset: 0 }); + assert_eq!(Selection::rows(0, 8), 1); + assert_eq!(Selection::rows(20, 8), 8); + } + + #[test] + fn text_fits_its_width() { + assert_eq!(fit("compose in your external editor", 10, false), "compose i…"); + assert_eq!(fit("compose in your external editor", 10, true), "compose..."); + assert_eq!(fit("short", 10, false), "short"); + } +} diff --git a/packages/cli-rs/crates/mini/src/prompt/mod.rs b/packages/cli-rs/crates/mini/src/prompt/mod.rs index 26acfcd63a5..39b8d6a5a2c 100644 --- a/packages/cli-rs/crates/mini/src/prompt/mod.rs +++ b/packages/cli-rs/crates/mini/src/prompt/mod.rs @@ -1,130 +1,1845 @@ -//! The footer prompt (`footer.prompt.tsx`, `runtime.queue.ts`): M.2. +//! The footer prompt (`footer.prompt.tsx`, M.2; rows M04, M09, M13): a composer that grows with its text up to +//! six rows, its autocomplete menu, and the keys that drive it. //! -//! M.1's version is a one-line input with the composer's rail that submits its text. M.2 replaces the body -//! (slash commands, autocomplete, mentions, shell mode, history, the editor, the queue) behind these signatures. +//! - `/` at a word start lists mini's built-ins (`/editor`, `/settings`, `/new`, `/compact`, the exit words) and +//! the server's commands; `@` lists subagents, the file search's results (with `#12-20` line ranges), and +//! references. A pick becomes an atomic mention part. +//! - `!` at the start enters shell mode; Escape, or Backspace at the start, leaves it. +//! - Up at the start and Down at the end step through the session's prompts ([`history`]). +//! - `prompt.editor` and `/editor` compose in `$VISUAL` or `$EDITOR`; pastes and `prompt.paste` attach images, +//! PDFs, and SVGs. +//! - Enter sends with `steer`, `prompt.queue` with `queue`; an empty Enter steers the first queued prompt. The +//! shell runs the turns through [`queue`]. +//! +//! The prompt owns the footer's keymap, so M.3's views add their layers to [`Prompt::keymap`]. -use std::cell::RefCell; +pub mod api; +pub mod complete; +pub mod history; +pub mod menu; +pub mod parts; +pub mod queue; + +use std::cell::{Cell, RefCell}; use std::rc::Rc; +use std::time::Duration; +use opencode_api::client::Client; +use opencode_local::cli_config::Info; +use opencode_ui::dialog::{DialogKeymap, route_keys}; +use opencode_ui::keymap::{Keybinds, KeymapLayer, TuiCommand}; +use opencode_ui::prompt_input::editor::{Mention, normalize, realign_mentions}; +use opencode_ui::prompt_input::parse::{self, measure}; +use opencode_ui::prompt_input::paste::{Content, content, strip_ansi}; +use opencode_ui::prompt_input::{attach, replace}; +use opentui::input::KeyEvent; +use opentui::keymap::{Condition, Disposer}; +use opentui::native::{ClipboardOutcome, EditorQuery}; use opentui::prelude::*; +use opentui::widget::{ExtmarkId, ExtmarkOptions}; +use serde_json::{Value, json}; +use self::complete::{Action, Catalog, Choice}; +use self::history::History; +use self::menu::{MENU_ROWS, Menu, Selection}; +pub use self::parts::{Command, Delivery, File, Part, RunPrompt, is_exit}; use crate::theme::RunTheme; -/// What the prompt submits (`RunPrompt`). -#[derive(Clone, Debug, Default, PartialEq)] -pub struct RunPrompt { - pub message_id: Option, - pub text: String, - /// File, agent, and skill mentions as the server takes them. - pub parts: Vec, - pub delivery: Option, - pub shell: bool, -} - -/// The words that close mini instead of sending (`footer.prompt.tsx`). -pub const EXIT_WORDS: [&str; 4] = ["exit", "quit", "/exit", "/quit"]; - /// `TEXTAREA_MIN_ROWS`. pub const MIN_ROWS: u16 = 1; +/// `TEXTAREA_MAX_ROWS`. +const MAX_ROWS: u16 = 6; +/// `PROMPT_MAX_ROWS`: a terminal at least this plus four rows tall pads the prompt. +pub const PROMPT_MAX_ROWS: u16 = MAX_ROWS + MENU_ROWS; -type Submit = Rc, RunPrompt)>>>>; - -/// The composer in the footer. -#[derive(Clone)] -pub struct Prompt { - root: View, - input: Input, - submit: Submit, - mono: bool, +/// `footerPromptLayout`: the rows of the padding, the textarea, the menu, and the image previews. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Layout { + pub padding: u16, + pub textarea: u16, + pub menu: u16, + pub images: u16, + /// The textarea's shown rows plus the menu and previews. + pub rows: u16, } +pub fn layout(height: u16, lines: u16, options: u16, status_rows: u16, images: bool) -> Layout { + let padding = u16::from(height >= PROMPT_MAX_ROWS + 4); + let available = height.saturating_sub(1 + status_rows + padding * 2).max(1); + let preview = if images && options == 0 { + 4.min(available.saturating_sub(MAX_ROWS.min(lines.max(1)))) + } else { + 0 + }; + let images = if preview >= 3 { preview } else { 0 }; + let textarea = available + .saturating_sub(images + u16::from(options > 0)) + .clamp(1, MAX_ROWS); + let rows = textarea.min(lines.max(1)); + let menu = if options > 0 { + MENU_ROWS.min(options).min(available.saturating_sub(rows)).max(1) + } else { + 0 + }; + Layout { + padding, + textarea, + menu, + images, + rows: rows + menu + images, + } +} + +/// `MenuMode`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Mode { + Mention, + Slash, +} + +/// A prompt waiting in the server's inbox (`FooterQueuedPrompt`, without its text, which M.3's menu shows). +#[derive(Clone, Debug, PartialEq)] +pub struct Queued { + pub id: String, + pub delivery: Delivery, +} + +type Notice = Box; + +/// What the prompt asks of the footer around it. Each returns at once; a hook that needs the event context +/// defers. +#[derive(Default)] +pub struct Hooks { + /// `onSubmit` (`footer.handlePrompt`): a prompt to send. False keeps it in the composer. + pub submit: Option bool>>, + /// `onExitRequest`: Ctrl+C on an empty prompt (the two-press exit). + pub exit_request: Option>, + /// `onExit`: an exit word. + pub exit: Option>, + /// `onInterrupt`: Escape; false when nothing runs. + pub interrupt: Option bool>>, + /// `onInputClear`: typing disarms the two-press gestures. + pub input_clear: Option>, + /// `onStatus`: a notice in the status row. + pub status: Option, + /// The composer's rows or the menu changed; the footer resizes. + pub layout: Option>, + /// `app.clear` (Ctrl+L). + pub clear_screen: Option>, + /// `/settings` (M.4's view). + pub settings: Option>, +} + +/// The session the prompt completes and steers in. +#[derive(Clone)] +struct Target { + client: Client, + session: String, + directory: String, +} + +#[derive(Default)] +struct State { + shell: bool, + first: bool, + running: bool, + history: History, + /// The draft saved when history browsing starts. + stash: RunPrompt, + parts: Vec, + /// Each mark and the part it stands for. + marks: Vec<(ExtmarkId, usize)>, + /// A server command a restored prompt named (`draft.command`). + command: Option, + mode: Option, + /// Where the open trigger starts. + at: u32, + query: String, + selection: Selection, + /// The file search's results for the current query. + files: Vec, + /// Bumped per search, so a stale answer is dropped. + search: u64, + catalog: Catalog, + agent: String, + queued: Vec, + submitting: bool, + /// A paste in flight: a submit waits for it. + pasting: bool, + terminal: (u16, u16), + layout: Layout, +} + +struct Inner { + app: App, + textarea: Textarea, + body: View, + rail: View, + menu: Menu, + keymap: Rc, + theme: RefCell, + mono: bool, + state: RefCell, + hooks: RefCell>, + target: RefCell>, + /// Programmatic edits sync the draft themselves. + quiet: Cell, + layers: RefCell>, +} + +/// The composer in the footer. Cloning is cheap. +#[derive(Clone)] +pub struct Prompt(Rc); + impl Prompt { - pub fn new(app: &App, theme: &RunTheme, mono: bool) -> Self { - let input = Input::new(app) - .grow(1.0) - .placeholder_color(theme.footer.muted); - let root = View::new(app) - .direction(FlexDirection::Row) - .height(u32::from(MIN_ROWS)) - .child(&Text::new(app, if mono { "| " } else { "┃ " }).fg(theme.footer.border)) - .child(&input); - let submit: Submit = Rc::default(); - input.on_submit({ - let (submit, input) = (submit.clone(), input.clone()); - move |cx, value| { - if value.trim().is_empty() { - return; - } - let prompt = RunPrompt { - message_id: Some(opencode_api::id::message()), - text: value.to_owned(), - ..RunPrompt::default() - }; - input.set_value(""); - if let Some(handler) = submit.borrow_mut().as_mut() { - handler(cx, prompt); - } - } - }); - let prompt = Self { - root, - input, - submit, + pub fn new(app: &App, theme: &RunTheme, mono: bool, config: &Info) -> Self { + let textarea = Textarea::new(app) + .set_keymap(opentui::input::Keymap::new()) + .wrap(WrapMode::Word) + .colors(theme.footer.text, theme.background) + .focused_colors(theme.footer.text, theme.background) + .placeholder_color(theme.footer.muted) + .cursor_color(theme.footer.text) + .width(Length::percent(100.0)) + .height(u32::from(MIN_ROWS)); + let vertical = if mono { '|' } else { '┃' }; + let rail = View::new(app) + .column() + .width(Length::percent(100.0)) + .border_sides(Sides::LEFT) + .border_chars(Some([' ', ' ', ' ', ' ', ' ', vertical, ' ', ' ', ' ', ' ', ' '])) + .padding_edge(Edge::Left, 1) + .padding_edge(Edge::Right, 2) + .child(&textarea); + let body = View::new(app) + .column() + .width(Length::percent(100.0)) + .shrink(0.0) + .child(&rail); + let keymap = Rc::new(keymap(app, config, &textarea)); + let terminal = opentui::term::size().unwrap_or((app.size().0, 0)); + let inner = Rc::new(Inner { + app: app.clone(), + textarea, + body, + rail, + menu: Menu::new(app), + keymap, + theme: RefCell::new(theme.clone()), mono, - }; - prompt.set_first(true); + state: RefCell::new(State { + first: true, + terminal, + ..State::default() + }), + hooks: RefCell::default(), + target: RefCell::default(), + quiet: Cell::new(false), + layers: RefCell::default(), + }); + connect(&inner); + install_layers(&inner); + let prompt = Self(inner); + prompt.paint(); prompt } - /// The widget to place in the footer. + /// The composer, padded by the footer. pub fn root(&self) -> &View { - &self.root + &self.0.body } - /// Calls `handler` with each submitted prompt. - pub fn on_submit(&self, handler: impl FnMut(&mut Cx<'_>, RunPrompt) + 'static) { - *self.submit.borrow_mut() = Some(Box::new(handler)); + /// The autocomplete menu, shown below the composer in place of the status row. + pub fn menu_root(&self) -> &View { + self.0.menu.root() + } + + /// The footer's keymap, for M.3's views. + pub fn keymap(&self) -> &Rc { + &self.0.keymap + } + + /// Routes the app's keys through the keymap and expires the leader sequence. + pub fn install(&self) { + let app = &self.0.app; + route_keys(app, self.0.keymap.clone()); + let keymap = Rc::downgrade(&self.0.keymap); + let timer = Rc::new(Cell::new(None::)); + app.on_key(move |cx, _| { + let Some(keys) = keymap.upgrade() else { return }; + if let Some(previous) = timer.take() { + cx.cancel_timer(previous); + } + let Some(deadline) = keys.leader_deadline() else { + return; + }; + let keymap = Rc::downgrade(&keys); + timer.set(Some(cx.set_timeout( + deadline.saturating_duration_since(cx.now()), + move |cx| { + if let Some(keys) = keymap.upgrade() { + keys.expire_leader(cx.now()); + } + }, + ))); + }); + } + + pub fn set_hooks(&self, hooks: Hooks) { + *self.0.hooks.borrow_mut() = Rc::new(hooks); } pub fn focus(&self) { - self.input.focus(); + self.0.textarea.focus(); } pub fn value(&self) -> String { - self.input.value() + self.0.textarea.text() } - /// Clears the draft (`handleInputClear`). - pub fn clear(&self) { - self.input.set_value(""); + /// Whether the composer is in shell mode. + pub fn shell(&self) -> bool { + self.0.state.borrow().shell } - /// Rows the composer needs (`onRows`). - pub fn rows(&self) -> u16 { - MIN_ROWS + /// Whether the autocomplete menu shows. + pub fn menu_visible(&self) -> bool { + self.0.state.borrow().mode.is_some() } - /// The session's earlier prompts, for history (`history` event). - pub fn set_history(&self, _history: Vec) {} + /// The footer's rows for the composer at this terminal size (`applyHeight`'s `rows`): the shown textarea + /// rows and the menu, less one when the menu replaces the status row. Sizes the textarea and the menu. + pub fn rows(&self, terminal: (u16, u16)) -> u16 { + self.0.state.borrow_mut().terminal = terminal; + self.0.measure(); + let layout = self.0.state.borrow().layout; + (layout.rows - u16::from(layout.menu > 0)).max(MIN_ROWS) + } - pub fn set_theme(&self, _theme: &RunTheme) {} + /// The padding rows the composer has at this height. + pub fn padding(&self) -> u16 { + self.0.state.borrow().layout.padding + } + + pub fn set_theme(&self, theme: &RunTheme) { + *self.0.theme.borrow_mut() = theme.clone(); + self.0 + .textarea + .colors(theme.footer.text, theme.background) + .focused_colors(theme.footer.text, theme.background) + .placeholder_color(theme.footer.muted) + .cursor_color(theme.footer.text); + self.paint(); + } /// A session without prompts shows the composer's hint (`first`). pub fn set_first(&self, first: bool) { - let hint = if first { - if self.mono { - "Ask anything, / for commands, @ for context..." - } else { - "Ask anything, / for commands, @ for context…" + self.0.state.borrow_mut().first = first; + self.paint(); + } + + /// The session's earlier prompts, for history (`history` event). + pub fn set_history(&self, history: Vec) { + self.0.state.borrow_mut().history = History::new(&history); + } + + /// The session's agent, which colors the rail. + pub fn set_agent(&self, agent: &str) { + self.0.state.borrow_mut().agent = agent.to_owned(); + self.paint(); + } + + /// The agent's name from the catalog, once it arrived. + pub fn agent_name(&self, id: &str) -> Option { + let state = self.0.state.borrow(); + state + .catalog + .agents + .iter() + .find(|agent| agent.id == id) + .map(|agent| agent.name.clone()) + } + + /// The color of the session's agent (`agentColor`). + pub fn agent_color(&self) -> Color { + self.0.agent_color() + } + + /// `state.phase === "running"`. + pub fn set_running(&self, running: bool) { + let was = std::mem::replace(&mut self.0.state.borrow_mut().running, running); + if was && !running { + self.focus(); + } + } + + /// Opens the session: reads the catalogs, the prompt history, and the inbox. + pub fn open(&self, client: &Client, session: &str, directory: &str, resume: bool) { + *self.0.target.borrow_mut() = Some(Target { + client: client.clone(), + session: session.to_owned(), + directory: directory.to_owned(), + }); + { + let mut state = self.0.state.borrow_mut(); + state.queued.clear(); + if !resume { + state.history = History::default(); } - } else { - "" + } + let weak = Rc::downgrade(&self.0); + let (client, directory) = (client.clone(), directory.to_owned()); + self.0.app.spawn( + async move { api::catalog(&client, &directory).await }, + move |_, catalog| { + if let Some(inner) = weak.upgrade() { + inner.state.borrow_mut().catalog = catalog; + inner.paint(); + inner.refresh(); + } + }, + ); + let Some(target) = self.0.target.borrow().clone() else { + return; }; - self.input.placeholder(hint); + let weak = Rc::downgrade(&self.0); + let client = target.client.clone(); + let session = target.session.clone(); + self.0.app.spawn( + async move { inbox(&client, &session).await }, + move |_, queued| { + if let Some(inner) = weak.upgrade() { + inner.state.borrow_mut().queued = queued; + } + }, + ); + if !resume { + return; + } + let weak = Rc::downgrade(&self.0); + self.0.app.spawn( + async move { api::history(&target.client, &target.session).await }, + move |_, history| { + if let Some(inner) = weak.upgrade() { + let mut state = inner.state.borrow_mut(); + state.history = History::new(&history); + state.first = history.is_empty(); + drop(state); + inner.paint(); + } + }, + ); + } + + /// An inbox event of the session (`syncPending`): the queued and steering prompts. + pub fn inbox_event(&self, event: &Value) { + let data = &event["data"]; + let id = data["inboxID"].as_str().unwrap_or_default().to_owned(); + let mut state = self.0.state.borrow_mut(); + match event["type"].as_str() { + Some("session.inbox.enqueued") if data["item"]["type"] == "user" => { + let delivery = delivery(&data["item"]["delivery"]); + if !state.queued.iter().any(|queued| queued.id == id) { + state.queued.push(Queued { id, delivery }); + } + } + Some("session.inbox.delivery.changed") => { + if let Some(queued) = state.queued.iter_mut().find(|queued| queued.id == id) { + queued.delivery = delivery(&data["delivery"]); + } + } + Some("session.inbox.delivered" | "session.inbox.cancelled") => { + state.queued.retain(|queued| queued.id != id); + } + _ => {} + } + } + + /// A prompt this client admitted (`mergePending`). + pub fn admitted(&self, id: &str, delivery: Delivery) { + let mut state = self.0.state.borrow_mut(); + if !state.queued.iter().any(|queued| queued.id == id) { + state.queued.push(Queued { + id: id.to_owned(), + delivery, + }); + } + } + + pub fn queued(&self) -> Vec { + self.0.state.borrow().queued.clone() + } + + /// Clears the draft (`requestExit`'s first press). False when there was nothing to clear. + pub fn clear(&self) -> bool { + self.0.clear_draft() + } + + /// A sent prompt joins the history (`push`). + pub fn push_history(&self, prompt: &RunPrompt) { + let mut state = self.0.state.borrow_mut(); + state.history = state.history.push(prompt); + } + + fn paint(&self) { + self.0.paint(); } } -/// Whether `text` is one of the exit words. -pub fn is_exit(text: &str) -> bool { - EXIT_WORDS.contains(&text.trim()) +impl Inner { + fn hooks(&self) -> Rc { + self.hooks.borrow().clone() + } + + fn status(&self, text: &str) { + if let Some(status) = &self.hooks().status { + status(text); + } + } + + fn input_clear(&self) { + if let Some(clear) = &self.hooks().input_clear { + clear(); + } + } + + fn agent_color(&self) -> Color { + let theme = self.theme.borrow(); + let state = self.state.borrow(); + let colors = &theme.footer.categorical; + let index = state + .catalog + .agents + .iter() + .filter(|agent| !agent.hidden) + .position(|agent| agent.id == state.agent) + .unwrap_or(0); + colors + .get(index % colors.len().max(1)) + .copied() + .unwrap_or(theme.footer.border) + } + + /// The placeholder and the rail's color. + fn paint(&self) { + let (shell, first) = { + let state = self.state.borrow(); + (state.shell, state.first) + }; + let placeholder = if shell { + "Run a command… \"git status\"" + } else if !first { + "" + } else if self.mono { + "Ask anything, / for commands, @ for context..." + } else { + "Ask anything, / for commands, @ for context…" + }; + self.textarea.placeholder(placeholder); + let rail = if shell { + self.theme.borrow().footer.formfield_focused_text + } else { + self.agent_color() + }; + self.rail.border_color(rail); + } + + fn edit(&self, edit: impl FnOnce()) { + let quiet = self.quiet.replace(true); + edit(); + self.quiet.set(quiet); + } + + fn cursor(&self) -> u32 { + self.textarea.cursor_offset() + } + + fn range(&self, start: u32, end: u32) -> String { + self.textarea + .buffer() + .range(start, end) + .unwrap_or_default() + } + + /// The width the menu and the file paths have (`width` memo). + fn width(&self) -> usize { + let width = self.state.borrow().terminal.0; + usize::from(width.saturating_sub(if width < menu::COMPACT_WIDTH { 2 } else { 4 })) + } + + /// The options for the open trigger. + fn options(&self) -> Vec { + let state = self.state.borrow(); + let Some(mode) = state.mode else { + return Vec::new(); + }; + let directory = self + .target + .borrow() + .as_ref() + .map(|target| target.directory.clone()) + .unwrap_or_default(); + let files = if mode == Mode::Mention { + complete::files( + &state.files, + parse::file_line_range(&state.query).1, + &directory, + self.width(), + ) + } else { + Vec::new() + }; + complete::filter(mode == Mode::Slash, &state.query, &state.catalog, files) + } + + /// The textarea's lines, the layout, and the menu (`syncRows`), then tells the footer. + fn measure(&self) { + let terminal = self.state.borrow().terminal; + let width = u32::from(terminal.0.saturating_sub(4)).max(1); + let lines = self + .textarea + .view() + // `measure` rejects `u32::MAX` rows. + .measure(width, 1000) + .map_or(1, |(rows, _)| rows) + .max(1); + let options = self.options(); + let visible = self.state.borrow().mode.is_some(); + let count = if visible { options.len().max(1) as u16 } else { 0 }; + let next = layout( + terminal.1, + lines.min(u32::from(u16::MAX)) as u16, + count, + u16::from(!visible), + false, + ); + let selection = { + let mut state = self.state.borrow_mut(); + state.layout = next; + state.selection = state + .selection + .reconcile(options.len(), usize::from(next.menu.max(1))); + state.selection + }; + self.textarea + .height(u32::from(next.rows - next.menu - next.images)); + self.body.padding_y(u32::from(next.padding)); + if visible { + let items: Vec = options.iter().map(Choice::item).collect(); + self.menu.show( + &items, + selection, + usize::from(next.menu), + terminal.0, + &self.theme.borrow().footer, + self.mono, + ); + } else { + self.menu.hide(); + } + } + + /// Re-measures and asks the footer to resize. + fn rows(&self) { + self.measure(); + if let Some(layout) = &self.hooks().layout { + layout(); + } + } + + /// Closes the menu. The file results go too: a mention opened with an empty query shows none until a query + /// is typed (the resource only refetches when its query changes). + fn hide(&self) { + let mut state = self.state.borrow_mut(); + state.mode = None; + state.query.clear(); + state.selection = Selection::default(); + state.files.clear(); + state.search += 1; + } + + fn set_shell(&self, shell: bool) { + self.state.borrow_mut().shell = shell; + self.paint(); + self.rows(); + } + + /// `syncParts`: marks' ranges into their parts; a part whose mark or text went is dropped. + fn sync_parts(&self) { + let (parts, marks) = { + let state = self.state.borrow(); + (state.parts.clone(), state.marks.clone()) + }; + let mut next: Vec> = parts + .iter() + .map(|part| match part { + Part::File(file) if file.mention.is_none() => Some(part.clone()), + _ => None, + }) + .collect(); + let mut tracked = 0; + let mut current = self.textarea.extmarks(); + current.sort_by_key(|mark| mark.id); + for mark in current { + let Some(&(_, index)) = marks.iter().find(|(id, _)| *id == mark.id) else { + continue; + }; + let Some(part) = parts.get(index) else { continue }; + let text = self.range(mark.start, mark.end); + if part.mention().map(|mention| mention.text.as_str()) != Some(text.as_str()) { + continue; + } + let mut copy = part.clone(); + copy.set_mention(Mention { + start: mark.start, + end: mark.end, + text, + }); + tracked += 1; + next[index] = Some(copy); + } + let retained: Vec = next.into_iter().flatten().collect(); + let stale = tracked != marks.len() || retained.len() != parts.len(); + if stale { + self.restore_parts(retained); + return; + } + self.state.borrow_mut().parts = retained; + } + + /// `restoreParts`: marks for every part with a mention. + fn restore_parts(&self, parts: Vec) { + self.textarea.clear_extmarks(); + let marks = parts + .iter() + .enumerate() + .filter_map(|(index, part)| { + let mention = part.mention()?; + let id = self.textarea.add_extmark( + mention.start..mention.end, + ExtmarkOptions::default().atomic(), + ); + Some((id, index)) + }) + .collect(); + let mut state = self.state.borrow_mut(); + state.parts = parts; + state.marks = marks; + } + + /// The draft (`syncDraft` then `promptCopy(draft)`). + fn current(&self) -> RunPrompt { + self.sync_parts(); + let text = self.textarea.text(); + let state = self.state.borrow(); + let command = if state.shell { + None + } else { + selected_command(&text, state.command.as_ref()) + }; + RunPrompt { + text, + parts: state.parts.clone(), + shell: state.shell, + command, + ..RunPrompt::default() + } + } + + /// `restore`: shows `prompt` with its marks, the cursor at `cursor` (the end by default). + fn restore(&self, prompt: &RunPrompt, cursor: Option) { + { + let mut state = self.state.borrow_mut(); + state.shell = prompt.shell; + state.command = prompt.command.clone(); + } + self.hide(); + self.edit(|| { + self.textarea.set_text(&prompt.text); + }); + self.restore_parts(prompt.parts.clone()); + let end = measure(&prompt.text); + self.textarea + .set_cursor_offset(cursor.unwrap_or(end).min(end)); + self.paint(); + self.rows(); + self.textarea.focus(); + } + + /// `resetDraft`: an empty composer, in the same mode. + fn reset(&self) { + self.edit(|| { + self.textarea.set_text(""); + }); + self.textarea.clear_extmarks(); + { + let mut state = self.state.borrow_mut(); + state.parts.clear(); + state.marks.clear(); + state.command = None; + } + self.hide(); + self.rows(); + self.textarea.focus(); + } + + fn clear_draft(&self) -> bool { + let has = !self.textarea.text().is_empty() + || self + .state + .borrow() + .parts + .iter() + .any(|part| matches!(part, Part::File(_))); + if has { + self.input_clear(); + self.reset(); + } + has + } + + /// `requestExit`: clears a draft, else asks the footer to exit. + fn request_exit(&self) { + if self.clear_draft() { + return; + } + if let Some(exit) = &self.hooks().exit_request { + exit(); + } + } + + /// `refresh`: opens, follows, or closes the trigger under the cursor. + fn refresh(self: &Rc) { + let cursor = self.cursor(); + let before = self.range(0, cursor); + let slash = parse::slash_trigger(&before); + let (mode, at) = { + let state = self.state.borrow(); + (state.mode, state.at) + }; + if mode == Some(Mode::Slash) { + match slash { + None => self.hide(), + Some(at) => { + let query = self.range(at + 1, cursor); + let mut state = self.state.borrow_mut(); + state.at = at; + if state.query != query { + state.query = query; + state.selection = Selection::default(); + } + } + } + return; + } + if let Some(at) = slash { + let query = self.range(at + 1, cursor); + let mut state = self.state.borrow_mut(); + state.at = at; + state.mode = Some(Mode::Slash); + state.query = query; + state.selection = Selection::default(); + return; + } + if mode == Some(Mode::Mention) { + let text = self.range(at, cursor); + if cursor <= at || text.contains(char::is_whitespace) { + self.hide(); + return; + } + self.set_query(self.range(at + 1, cursor)); + return; + } + if cursor == 0 { + return; + } + if let Some(at) = parse::mention_trigger(&before) { + { + let mut state = self.state.borrow_mut(); + state.at = at; + state.mode = Some(Mode::Mention); + state.selection = Selection::default(); + state.query.clear(); + } + self.set_query(self.range(at + 1, cursor)); + } + } + + /// A new mention query: resets the selection and searches files once the current input settles. + fn set_query(self: &Rc, query: String) { + let search = { + let mut state = self.state.borrow_mut(); + if state.query == query { + return; + } + state.query = query; + state.selection = Selection::default(); + state.search += 1; + if state.query.is_empty() { + state.files.clear(); + return; + } + state.search + }; + // Keys that arrive together search once, for the last query (`createResource` on the settled query). + let weak = Rc::downgrade(self); + self.app.set_timeout(Duration::ZERO, move |_| { + if let Some(inner) = weak.upgrade() { + inner.search(search); + } + }); + } + + fn search(self: &Rc, search: u64) { + let query = { + let state = self.state.borrow(); + if state.search != search || state.mode != Some(Mode::Mention) { + return; + } + state.query.clone() + }; + let Some(target) = self.target.borrow().clone() else { + return; + }; + let base = parse::file_line_range(&query).0.to_owned(); + let weak = Rc::downgrade(self); + self.app.spawn( + async move { api::find_files(&target.client, &target.directory, &base).await }, + move |_, files| { + let Some(inner) = weak.upgrade() else { return }; + { + let mut state = inner.state.borrow_mut(); + if state.search != search { + return; + } + state.files = files; + } + inner.rows(); + }, + ); + } + + /// `onContentChange`. + fn changed(self: &Rc) { + if self.quiet.get() { + return; + } + self.input_clear(); + self.sync_parts(); + self.refresh(); + self.rows(); + } + + /// `cancelAutocomplete`: removes the typed trigger and hides the menu. + fn cancel(&self) { + let (at, cursor) = (self.state.borrow().at, self.cursor()); + self.edit(|| replace(&self.textarea, at, cursor, "")); + self.textarea.set_cursor_offset(at); + self.hide(); + self.sync_parts(); + self.rows(); + } + + fn move_selection(&self, down: bool) { + let count = self.options().len(); + { + let mut state = self.state.borrow_mut(); + let limit = usize::from(state.layout.menu.max(1)); + state.selection = state.selection.step(count, limit, down); + } + self.rows(); + } + + /// `select`: runs a slash pick, or inserts a mention. + fn select(self: &Rc, delivery: Delivery) { + let options = self.options(); + let selected = self.state.borrow().selection.selected; + let Some(choice) = options.get(selected).cloned() else { + return; + }; + let shell = self.state.borrow().shell; + match choice { + Choice::Slash { action: Some(Action::Editor), .. } => { + let text = self.textarea.text(); + let value = match parse::slash_head(&text) { + Some((name, arguments, _)) if name.eq_ignore_ascii_case("editor") => arguments.to_owned(), + _ => text, + }; + self.open_editor(Some(value)); + } + Choice::Slash { action: Some(Action::Settings), .. } if !shell => { + self.cancel(); + if let Some(settings) = &self.hooks().settings { + settings(); + } + } + Choice::Slash { name, .. } => { + let text = self.textarea.text(); + let cursor = self.cursor(); + let head = parse::slash_head(&text); + let local = !shell && (name == "new" || is_exit(&format!("/{name}"))); + let spaced = head + .is_some_and(|(_, _, end)| text[end..].starts_with(char::is_whitespace)); + let separator = if !shell && !local && spaced { "" } else { " " }; + let inserted = format!("/{name}{separator}"); + let end = match head { + Some(_) if shell => cursor, + None => cursor, + Some(_) if local => measure(&text), + Some((_, _, end)) => measure(&text[..end]), + }; + self.edit(|| replace(&self.textarea, 0, end, &inserted)); + self.textarea.set_cursor_offset(measure(&inserted)); + self.hide(); + if !shell { + let prompt = self.current(); + self.submit_prompt(prompt, delivery); + return; + } + self.rows(); + } + Choice::Mention { value, part, .. } => { + let (at, cursor) = (self.state.borrow().at, self.cursor()); + let next = self.range(cursor, cursor + 1); + let mention = format!("@{value}"); + let inserted = if next == " " { + mention.clone() + } else { + format!("{mention} ") + }; + self.edit(|| replace(&self.textarea, at, cursor, &inserted)); + let end = at + measure(&mention); + let mut part = part; + part.set_mention(Mention { + start: at, + end, + text: mention, + }); + if let Part::File(file) = &part { + let previous = self.state.borrow().parts.iter().position( + |item| matches!(item, Part::File(other) if other.url == file.url), + ); + if let Some(previous) = previous { + let mut state = self.state.borrow_mut(); + if let Some(position) = state.marks.iter().position(|(_, index)| *index == previous) { + let (mark, _) = state.marks.remove(position); + self.textarea.remove_extmark(mark); + } + state.parts.remove(previous); + for (_, index) in &mut state.marks { + if *index > previous { + *index -= 1; + } + } + } + } + let mark = self + .textarea + .add_extmark(at..end, ExtmarkOptions::default().atomic()); + { + let mut state = self.state.borrow_mut(); + let index = state.parts.len(); + state.marks.push((mark, index)); + state.parts.push(part); + } + self.hide(); + self.sync_parts(); + self.rows(); + } + } + } + + /// `expand`: Tab on a directory completes it and keeps listing. + fn expand(self: &Rc) { + let options = self.options(); + let selected = self.state.borrow().selection.selected; + let Some(Choice::Mention { + value, + directory: true, + .. + }) = options.get(selected) + else { + return; + }; + let (at, cursor) = (self.state.borrow().at, self.cursor()); + self.edit(|| replace(&self.textarea, at, cursor, &format!("@{value}"))); + self.sync_parts(); + self.refresh(); + self.rows(); + } + + /// `onSubmit`: waits for a paste in flight, then submits the draft. + fn submit(self: &Rc, delivery: Delivery) { + if self.state.borrow().pasting { + return; + } + let prompt = self.current(); + self.submit_prompt(prompt, delivery); + } + + /// `submitPrompt`. + fn submit_prompt(self: &Rc, next: RunPrompt, delivery: Delivery) { + if self.state.borrow().mode.is_some() { + let slash = self.state.borrow().mode == Some(Mode::Slash); + if !slash || !self.options().is_empty() { + self.select(delivery); + return; + } + self.hide(); + self.rows(); + } + if self.state.borrow().submitting { + return; + } + if !next.has_content() { + let queued = (delivery == Delivery::Steer) + .then(|| { + self.state + .borrow() + .queued + .iter() + .find(|queued| queued.delivery == Delivery::Queue) + .cloned() + }) + .flatten(); + if let Some(queued) = queued { + self.steer(queued.id); + return; + } + let running = self.state.borrow().running; + self.status(if running { + "waiting for current response" + } else { + "empty prompt ignored" + }); + return; + } + let command = if next.shell { + None + } else { + selected_command(&next.text, next.command.as_ref()) + }; + let local = parts::is_new(&next.text) + || parts::is_compact(&next.text) + || is_exit(&next.text) + || parts::is_settings(&next.text); + if delivery == Delivery::Queue && (next.shell || local) { + self.status("this prompt cannot be queued"); + return; + } + if command.is_none() && !next.shell && is_exit(&next.text) { + if let Some(exit) = &self.hooks().exit { + exit(); + } + return; + } + if command.is_none() && !next.shell && parts::is_settings(&next.text) { + self.reset(); + if let Some(settings) = &self.hooks().settings { + settings(); + } + return; + } + let skill = next + .parts + .iter() + .any(|part| matches!(part, Part::Skill { .. })); + let command = if command.is_some() || skill || next.shell || parts::is_new(&next.text) { + command + } else { + match parse_slash_command(&next.text, self.state.borrow().catalog.commands.as_deref()) { + Slash::Pending => { + self.status("loading commands"); + return; + } + Slash::None => None, + Slash::Command(command) => Some(command), + } + }; + let submit = RunPrompt { + command, + delivery: Some(delivery), + ..next.clone() + }; + self.state.borrow_mut().submitting = true; + self.reset(); + let accepted = self + .hooks() + .submit + .as_ref() + .is_some_and(|submit_hook| submit_hook(submit)); + self.state.borrow_mut().submitting = false; + if !accepted { + self.restore(&next, None); + return; + } + { + let mut state = self.state.borrow_mut(); + state.history = state.history.push(&next); + state.first = false; + } + if next.shell { + self.set_shell(false); + } + self.paint(); + } + + /// `onQueuedPromptSteer`: steers a queued prompt. + fn steer(self: &Rc, id: String) { + let Some(target) = self.target.borrow().clone() else { + return; + }; + self.state.borrow_mut().submitting = true; + let weak = Rc::downgrade(self); + self.app.spawn( + async move { api::deliver(&target.client, &target.session, &id, Delivery::Steer).await }, + move |_, result| { + let Some(inner) = weak.upgrade() else { return }; + inner.state.borrow_mut().submitting = false; + if let Err(error) = result { + inner.status(&format!("failed to steer pending prompt: {error}")); + } + }, + ); + } + + /// `move`/`historyCommand`: Up and Down move by line, then to the start or end, then through history. + fn history(&self, up: bool) -> bool { + let text = self.textarea.text(); + let cursor = self.cursor(); + let step = { + let state = self.state.borrow(); + state.history.step(up, &text, cursor) + }; + if let Some((_, cursor)) = step.apply { + if up && self.state.borrow().history.index.is_none() { + let draft = self.current(); + self.state.borrow_mut().stash = draft; + } + let value = { + let mut state = self.state.borrow_mut(); + state.history = step.state; + match state.history.index { + None => state.stash.clone(), + Some(index) => state.history.items[index].clone(), + } + }; + self.restore(&value, Some(cursor)); + return true; + } + let end = measure(&text); + let view = self.textarea.view(); + let row = view.viewport().map_or(0, |viewport| viewport.y) + + view + .position(EditorQuery::Cursor) + .map_or(0, |position| position.visual_row); + if up { + if cursor == 0 { + return false; + } + if row == 0 { + self.textarea.set_cursor_offset(0); + } else { + self.textarea.perform(EditorAction::MoveUp); + } + return true; + } + if cursor == end { + return false; + } + let last = view + .info(false) + .map_or(0, |info| info.total_virtual_line_count.saturating_sub(1)); + if row >= last { + self.textarea.set_cursor_offset(end); + } else { + self.textarea.perform(EditorAction::MoveDown); + } + true + } + + /// `openEditor`: composes the draft in `$VISUAL` or `$EDITOR`. + fn open_editor(self: &Rc, value: Option) { + self.input_clear(); + let current = self.current(); + self.hide(); + self.rows(); + let value = value.unwrap_or_else(|| current.text.clone()); + let directory = self + .target + .borrow() + .as_ref() + .map(|target| target.directory.clone()) + .unwrap_or_else(|| ".".to_owned()); + let command = ["VISUAL", "EDITOR"] + .iter() + .find_map(|name| std::env::var(name).ok().filter(|value| !value.is_empty())); + let weak = Rc::downgrade(self); + self.app.release_terminal(move |_| { + let Some(inner) = weak.upgrade() else { return }; + let result = command + .ok_or_else(|| "Set $VISUAL or $EDITOR to open an external editor".to_owned()) + .and_then(|command| { + opencode_ui::prompt_input::editor::edit( + &command, + &value, + std::path::Path::new(&directory), + ) + }); + match result { + Ok(None) => {} + Ok(Some(content)) => { + let text = normalize(&content); + let mentions: Vec> = current + .parts + .iter() + .map(|part| part.mention().cloned()) + .collect(); + let aligned = realign_mentions(&text, &mentions); + let parts = current + .parts + .iter() + .zip(aligned) + .filter_map(|(part, aligned)| match (part.mention(), aligned) { + (None, _) => Some(part.clone()), + (Some(_), None) => None, + (Some(_), Some(mention)) => { + let mut part = part.clone(); + part.set_mention(mention); + Some(part) + } + }) + .collect(); + inner.restore( + &RunPrompt { + text, + parts, + ..current + }, + None, + ); + } + Err(_) => { + inner.restore(¤t, None); + inner.status("failed to open editor"); + } + } + inner.app.request_redraw(); + }); + } + + /// `paste`: a terminal paste (`Some`), or the clipboard (`None`). + fn paste(self: &Rc, text: Option) { + let weak = Rc::downgrade(self); + let Some(text) = text else { + self.state.borrow_mut().pasting = true; + self.app + .read_clipboard_as(&["image/png", "text/plain"], move |_, outcome: ClipboardOutcome| { + let Some(inner) = weak.upgrade() else { return }; + match content(outcome) { + Err(error) => { + inner.state.borrow_mut().pasting = false; + inner.status(&error); + } + Ok(None) => inner.state.borrow_mut().pasting = false, + Ok(Some(Content::Image { mime, data })) => { + inner.state.borrow_mut().pasting = false; + if inner.state.borrow().shell { + inner.status("image attachments are unavailable in shell mode"); + return; + } + inner.attachment(&format!("data:{mime};base64,{data}"), Some("clipboard")); + inner.pasted(); + } + Ok(Some(Content::Text(text))) => inner.paste_text(text), + } + }); + return; + }; + self.state.borrow_mut().pasting = true; + self.paste_text(text); + } + + fn paste_text(self: &Rc, text: String) { + let normalized = strip_ansi(&text).replace("\r\n", "\n").replace('\r', "\n"); + let windows = cfg!(windows); + if self.state.borrow().shell || !attach::may_attach(normalized.trim(), windows) { + self.state.borrow_mut().pasting = false; + self.textarea.insert(&normalized); + self.pasted(); + return; + } + let weak = Rc::downgrade(self); + let input = normalized.clone(); + let before = self.textarea.text(); + self.app.spawn( + async move { + tokio::task::spawn_blocking(move || attach::resolve(&input, windows)) + .await + .ok() + .flatten() + }, + move |_, resolved| { + let Some(inner) = weak.upgrade() else { return }; + inner.state.borrow_mut().pasting = false; + if inner.textarea.text() != before { + return; + } + match resolved { + None => { + inner.textarea.insert(&normalized); + } + Some(files) => { + for file in files { + match file { + attach::Resolved::Text { content, .. } => { + inner.textarea.insert(&content); + } + attach::Resolved::File { uri, filename, .. } => { + inner.attachment(&uri, Some(&filename)); + } + } + } + } + } + inner.pasted(); + }, + ); + } + + /// `pasteAttachment`: `[Image N]` or `[PDF N]` at the cursor, marked as a file part. + fn attachment(&self, uri: &str, filename: Option<&str>) { + self.sync_parts(); + let files: Vec = self + .state + .borrow() + .parts + .iter() + .filter_map(|part| match part { + Part::File(file) => Some(json!({ + "uri": file.url, + "name": file.filename, + "description": file.description, + "mention": file.mention.as_ref().map(|mention| json!({ "text": mention.text })), + })), + _ => None, + }) + .collect(); + let label = match attach::label(&files, uri, filename) { + Ok(label) => label, + Err(error) => { + self.status(&error); + return; + } + }; + self.edit(|| { + self.textarea.insert(format!("{label} ")); + }); + let end = self.cursor().saturating_sub(1); + let start = end.saturating_sub(measure(&label)); + let mark = self + .textarea + .add_extmark(start..end, ExtmarkOptions::default().atomic()); + let mime = uri + .strip_prefix("data:") + .and_then(|rest| rest.split(';').next()) + .map(str::to_owned); + let mut state = self.state.borrow_mut(); + let index = state.parts.len(); + state.marks.push((mark, index)); + state.parts.push(Part::File(File { + url: uri.to_owned(), + mime, + filename: filename.map(str::to_owned), + description: None, + mention: Some(Mention { + start, + end, + text: label, + }), + })); + } + + fn pasted(&self) { + self.hide(); + self.sync_parts(); + self.rows(); + } } + +/// The text change, submit, and paste handlers. +fn connect(inner: &Rc) { + let weak = Rc::downgrade(inner); + inner.textarea.on_change(move |_, _| { + if let Some(inner) = weak.upgrade() { + inner.changed(); + } + }); + let weak = Rc::downgrade(inner); + inner.textarea.on_submit(move |_, _| { + if let Some(inner) = weak.upgrade() { + inner.submit(Delivery::Steer); + } + }); + let weak = Rc::downgrade(inner); + inner.textarea.on_paste(move |cx, text| { + let Some(inner) = weak.upgrade() else { return }; + cx.prevent_default(); + cx.stop_propagation(); + inner.paste((!text.is_empty()).then(|| text.to_owned())); + }); +} + +/// The footer's keymap with `cli.json`'s keybinds; the managed textarea layer edits the prompt. +fn keymap(app: &App, config: &Info, textarea: &Textarea) -> DialogKeymap { + let overrides = config.keybinds.clone().unwrap_or_default().0; + let keybinds = Keybinds::resolve(&overrides, !cfg!(windows)).unwrap_or_else(|error| { + log::warn!("invalid keybinds config: {error}"); + Keybinds::defaults() + }); + let leader_timeout = Duration::from_millis( + config + .leader + .as_ref() + .and_then(|leader| leader.timeout) + .map_or(2000, |timeout| timeout.0), + ); + let focused = { + let (app, textarea) = (app.clone(), textarea.clone()); + Condition::when(move || { + app.focused() + .is_some_and(|widget| widget.id() == textarea.id()) + }) + }; + let run = { + let textarea = textarea.clone(); + Rc::new(move |action| { + textarea.perform(action); + true + }) + }; + DialogKeymap::new( + keybinds, + opencode_ui::keymap::Options { + leader_timeout, + textarea_enabled: focused, + textarea_run: run, + }, + ) +} + +/// The prompt's layers (`footer.prompt.tsx:1162-1344`, `footer.view.tsx:549-558`). The newest layer runs first, +/// as in TS, where the later `createLayer` wins. +fn install_layers(inner: &Rc) { + let when = |check: fn(&Inner) -> bool| { + let weak = Rc::downgrade(inner); + Condition::when(move || weak.upgrade().is_some_and(|inner| check(&inner))) + }; + let run = |action: fn(&Rc) -> bool| { + let weak = Rc::downgrade(inner); + move |_: Option<&str>, _: Option<&KeyEvent>| weak.upgrade().is_some_and(|inner| action(&inner)) + }; + let command = |id: &str, title: &str, group: &str, action: fn(&Rc) -> bool| { + TuiCommand::new(id, run(action)).title(title).group(group) + }; + let inline = |key: &str, title: &str, action: fn(&Rc) -> bool| { + TuiCommand::inline(key, run(action)).title(title).group("Prompt") + }; + let layers = vec![ + KeymapLayer { + commands: vec![command("app.clear", "Clear screen", "System", |inner| { + if let Some(clear) = &inner.hooks().clear_screen { + clear(); + } + true + })], + ..KeymapLayer::default() + }, + KeymapLayer { + commands: vec![command("prompt.clear", "Clear prompt or exit", "Prompt", |inner| { + inner.request_exit(); + true + })], + ..KeymapLayer::default() + }, + KeymapLayer { + commands: vec![ + command("prompt.paste", "Paste", "Prompt", |inner| { + inner.paste(None); + true + }), + command("session.interrupt", "Interrupt session", "Session", |inner| { + if inner.hooks().interrupt.as_ref().is_some_and(|interrupt| interrupt()) { + return true; + } + // `onKeyDown`: Escape while idle disarms the two-press gestures. + if !inner.state.borrow().running { + inner.input_clear(); + } + false + }), + ], + ..KeymapLayer::default() + }, + KeymapLayer { + priority: 1, + enabled: when(|inner| inner.state.borrow().mode != Some(Mode::Mention)), + commands: vec![ + command("prompt.queue", "Queue prompt", "Prompt", |inner| { + inner.submit(Delivery::Queue); + true + }) + .palette(), + ], + ..KeymapLayer::default() + }, + KeymapLayer { + priority: 1, + enabled: when(|inner| !visible(inner)), + commands: vec![command("prompt.editor", "Open editor", "Prompt", |inner| { + inner.open_editor(None); + true + })], + ..KeymapLayer::default() + }, + KeymapLayer { + priority: 1, + enabled: when(|inner| !visible(inner)), + commands: vec![ + command( + "prompt.history.previous", + "Previous prompt history", + "Prompt", + |inner| inner.history(true), + ), + command("prompt.history.next", "Next prompt history", "Prompt", |inner| { + inner.history(false) + }), + ], + ..KeymapLayer::default() + }, + KeymapLayer { + enabled: when(|inner| !visible(inner)), + commands: vec![inline("!", "Shell mode", |inner| { + if inner.state.borrow().shell || inner.cursor() != 0 { + return false; + } + inner.set_shell(true); + true + })], + ..KeymapLayer::default() + }, + KeymapLayer { + enabled: when(|inner| inner.state.borrow().shell && !visible(inner)), + commands: vec![ + inline("escape", "Exit shell mode", |inner| { + inner.set_shell(false); + true + }), + inline("backspace", "Exit shell mode", |inner| { + if inner.cursor() != 0 { + return false; + } + inner.set_shell(false); + true + }), + ], + ..KeymapLayer::default() + }, + KeymapLayer { + enabled: when(visible), + commands: vec![ + command( + "prompt.autocomplete.prev", + "Previous autocomplete item", + "Autocomplete", + |inner| { + inner.move_selection(false); + true + }, + ), + command( + "prompt.autocomplete.next", + "Next autocomplete item", + "Autocomplete", + |inner| { + inner.move_selection(true); + true + }, + ), + command("prompt.autocomplete.hide", "Hide autocomplete", "Autocomplete", |inner| { + inner.cancel(); + true + }), + command( + "prompt.autocomplete.select", + "Select autocomplete item", + "Autocomplete", + |inner| { + if inner.state.borrow().mode == Some(Mode::Slash) && inner.options().is_empty() { + inner.hide(); + inner.rows(); + return true; + } + inner.select(Delivery::Steer); + true + }, + ), + command( + "prompt.autocomplete.complete", + "Complete autocomplete item", + "Autocomplete", + |inner| { + let options = inner.options(); + if inner.state.borrow().mode == Some(Mode::Slash) && options.is_empty() { + inner.hide(); + inner.rows(); + return true; + } + let selected = inner.state.borrow().selection.selected; + if matches!(options.get(selected), Some(Choice::Mention { directory: true, .. })) { + inner.expand(); + return true; + } + inner.select(Delivery::Steer); + true + }, + ), + ], + ..KeymapLayer::default() + }, + ]; + for layer in layers { + match inner.keymap.layer(layer) { + Ok(disposer) => inner.layers.borrow_mut().push(disposer), + Err(error) => log::error!("mini prompt keymap layer: {error}"), + } + } +} + +fn visible(inner: &Inner) -> bool { + inner.state.borrow().mode.is_some() +} + +/// `selectedCommand`: a restored prompt's command while its text still names it. +fn selected_command(text: &str, command: Option<&Command>) -> Option { + let command = command?; + let (name, arguments, _) = parse::slash_head(text)?; + (name == command.name).then(|| Command { + name: command.name.clone(), + arguments: arguments.to_owned(), + source: command.source.clone(), + }) +} + +enum Slash { + None, + Pending, + Command(Command), +} + +/// `parseSlashCommand`: `/name args` for a server command. +fn parse_slash_command(text: &str, commands: Option<&[complete::Command]>) -> Slash { + let Some((name, arguments, _)) = parse::slash_head(text).filter(|(name, _, _)| !name.is_empty()) else { + return Slash::None; + }; + let Some(commands) = commands else { + return Slash::Pending; + }; + match commands.iter().find(|command| command.name == name) { + Some(command) => Slash::Command(Command { + name: name.to_owned(), + arguments: arguments.to_owned(), + source: command.source.clone(), + }), + None => Slash::None, + } +} + +fn delivery(value: &Value) -> Delivery { + match value.as_str() { + Some("queue") => Delivery::Queue, + _ => Delivery::Steer, + } +} + +/// `session.inbox.list`: the session's pending user prompts. +async fn inbox(client: &Client, session: &str) -> Vec { + let call = opencode_api::client::Call::new( + "GET", + format!("/api/session/{}/inbox", crate::replay::encode(session)), + 200, + &[400, 401, 404], + ); + client + .json::(call, &opencode_api::client::RequestOptions::default()) + .await + .map(|value| { + value["data"] + .as_array() + .into_iter() + .flatten() + .filter(|item| item["type"] == "user") + .map(|item| Queued { + id: item["id"].as_str().unwrap_or_default().to_owned(), + delivery: delivery(&item["delivery"]), + }) + .collect() + }) + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn layout_follows_footer_prompt_layout() { + // 20 rows: padded, one row, no menu. + assert_eq!( + layout(20, 1, 0, 1, false), + Layout { + padding: 1, + textarea: 6, + menu: 0, + images: 0, + rows: 1 + } + ); + // Nine slash options in 20 rows: eight menu rows. + assert_eq!(layout(20, 1, 9, 0, false).menu, 8); + assert_eq!(layout(20, 1, 9, 0, false).rows, 9); + // Ten lines grow to six. + assert_eq!(layout(20, 10, 0, 1, false).rows, 6); + // A short terminal: no padding, the menu takes what is left. + let short = layout(8, 2, 9, 0, false); + assert_eq!((short.padding, short.rows, short.menu), (0, 7, 5)); + // Previews take four rows when they fit. + assert_eq!(layout(30, 1, 0, 1, true).images, 4); + assert_eq!(layout(5, 1, 0, 1, true).images, 0); + } + + #[test] + fn slash_commands_parse_against_the_catalog() { + let commands = [complete::Command { + name: "review".into(), + description: None, + source: None, + }]; + assert!(matches!(parse_slash_command("/review src", Some(&commands)), Slash::Command(command) if command.arguments == "src")); + assert!(matches!(parse_slash_command("/nope", Some(&commands)), Slash::None)); + assert!(matches!(parse_slash_command("/review", None), Slash::Pending)); + assert!(matches!(parse_slash_command("plain", None), Slash::None)); + let restored = Command { + name: "review".into(), + arguments: String::new(), + source: Some("command".into()), + }; + assert_eq!( + selected_command("/review now", Some(&restored)).map(|command| command.arguments), + Some("now".into()) + ); + assert_eq!(selected_command("/other", Some(&restored)), None); + } +} + diff --git a/packages/cli-rs/crates/mini/src/prompt/parts.rs b/packages/cli-rs/crates/mini/src/prompt/parts.rs new file mode 100644 index 00000000000..cb0fda4348b --- /dev/null +++ b/packages/cli-rs/crates/mini/src/prompt/parts.rs @@ -0,0 +1,325 @@ +//! What the footer prompt submits (`RunPrompt`, `RunPromptPart` in `mini/types.ts`), how a submitted prompt goes +//! on the wire (`promptFiles`, `promptAgents`, `promptSkills` in `stream-v2.transport.ts`), and how a listed user +//! message becomes a prompt again for history (`messagePrompt` in `session.shared.ts`). + +use opencode_ui::prompt_input::editor::Mention; +use serde_json::{Map, Value, json}; + +/// `RunDelivery`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Delivery { + #[default] + Steer, + Queue, +} + +impl Delivery { + pub fn as_str(self) -> &'static str { + match self { + Delivery::Steer => "steer", + Delivery::Queue => "queue", + } + } +} + +/// A file part: a mention, a reference, or a pasted attachment. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct File { + pub url: String, + pub mime: Option, + pub filename: Option, + pub description: Option, + /// The `@path` or `[Image N]` text the part stands for, while it is in the prompt. + pub mention: Option, +} + +/// `RunPromptPart` of a mention kind. +#[derive(Clone, Debug, PartialEq)] +pub enum Part { + File(File), + Agent { + name: String, + mention: Option, + }, + Skill { + id: String, + mention: Option, + }, +} + +impl Part { + pub fn mention(&self) -> Option<&Mention> { + match self { + Part::File(file) => file.mention.as_ref(), + Part::Agent { mention, .. } | Part::Skill { mention, .. } => mention.as_ref(), + } + } + + pub fn mention_mut(&mut self) -> Option<&mut Mention> { + match self { + Part::File(file) => file.mention.as_mut(), + Part::Agent { mention, .. } | Part::Skill { mention, .. } => mention.as_mut(), + } + } + + pub fn set_mention(&mut self, next: Mention) { + match self { + Part::File(file) => file.mention = Some(next), + Part::Agent { mention, .. } | Part::Skill { mention, .. } => *mention = Some(next), + } + } +} + +/// A server command the prompt names (`RunPrompt.command`). +#[derive(Clone, Debug, PartialEq)] +pub struct Command { + pub name: String, + pub arguments: String, + pub source: Option, +} + +/// `RunPrompt`. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RunPrompt { + pub message_id: Option, + pub text: String, + pub parts: Vec, + pub delivery: Option, + /// `mode: "shell"`. + pub shell: bool, + pub command: Option, +} + +impl RunPrompt { + pub fn text(text: impl Into) -> Self { + Self { + text: text.into(), + ..Self::default() + } + } + + pub fn has_file(&self) -> bool { + self.parts.iter().any(|part| matches!(part, Part::File(_))) + } + + /// Text, or a file to send (`text.trim() || parts.some(file)`). + pub fn has_content(&self) -> bool { + !self.text.trim().is_empty() || self.has_file() + } + + /// `promptCopy`: the prompt without its message ID and delivery. + pub fn copy(&self) -> Self { + Self { + message_id: None, + delivery: None, + ..self.clone() + } + } + + /// `promptSame`. + pub fn same(&self, other: &RunPrompt) -> bool { + self.shell == other.shell + && self.text == other.text + && self.parts == other.parts + && self.command == other.command + } + + /// `promptFiles`: `{ uri, name, description?, mention? }` per file part. + pub fn files(&self) -> Vec { + self.parts + .iter() + .filter_map(|part| match part { + Part::File(file) => { + let mut out = Map::new(); + out.insert("uri".into(), file.url.clone().into()); + if let Some(name) = &file.filename { + out.insert("name".into(), name.clone().into()); + } + if let Some(description) = &file.description { + out.insert("description".into(), description.clone().into()); + } + if let Some(mention) = &file.mention { + out.insert("mention".into(), wire(mention)); + } + Some(Value::Object(out)) + } + _ => None, + }) + .collect() + } + + /// `promptAgents`. + pub fn agents(&self) -> Vec { + self.parts + .iter() + .filter_map(|part| match part { + Part::Agent { name, mention } => Some(with_mention(json!({ "name": name }), mention)), + _ => None, + }) + .collect() + } + + /// `promptSkills`. + pub fn skills(&self) -> Vec { + self.parts + .iter() + .filter_map(|part| match part { + Part::Skill { id, mention } => Some(with_mention(json!({ "id": id }), mention)), + _ => None, + }) + .collect() + } + + /// `messagePrompt`: a listed user message (or an inbox item's payload) as a prompt. + pub fn from_message(message: &Value) -> Self { + let list = |key: &str| message[key].as_array().cloned().unwrap_or_default(); + let files = list("files").into_iter().map(|file| { + let uri = match file["source"]["type"].as_str() { + Some("uri") => file["source"]["uri"].as_str().map(str::to_owned), + _ => None, + } + .or_else(|| file["uri"].as_str().map(str::to_owned)) + .unwrap_or_else(|| { + format!( + "data:{};base64,{}", + file["mime"].as_str().unwrap_or_default(), + file["data"].as_str().unwrap_or_default() + ) + }); + Part::File(File { + url: uri, + mime: file["mime"].as_str().map(str::to_owned), + filename: file["name"].as_str().map(str::to_owned), + description: file["description"].as_str().map(str::to_owned), + mention: mention(&file["mention"]), + }) + }); + let agents = list("agents").into_iter().map(|agent| Part::Agent { + name: agent["name"].as_str().unwrap_or_default().to_owned(), + mention: mention(&agent["mention"]), + }); + let skills = list("skills").into_iter().map(|skill| Part::Skill { + id: skill["id"].as_str().unwrap_or_default().to_owned(), + mention: mention(&skill["mention"]), + }); + Self { + text: message["text"].as_str().unwrap_or_default().to_owned(), + parts: files.chain(agents).chain(skills).collect(), + ..Self::default() + } + } +} + +fn wire(mention: &Mention) -> Value { + json!({ "start": mention.start, "end": mention.end, "text": mention.text }) +} + +fn with_mention(mut value: Value, mention: &Option) -> Value { + if let Some(mention) = mention { + value["mention"] = wire(mention); + } + value +} + +fn mention(value: &Value) -> Option { + Some(Mention { + start: value["start"].as_u64()? as u32, + end: value["end"].as_u64()? as u32, + text: value["text"].as_str()?.to_owned(), + }) +} + +/// `EXIT_COMMANDS`. +pub const EXIT_COMMANDS: [&str; 3] = ["exit", "quit", "q"]; + +/// `isExitCommand`: `:q`, `/exit`, `/quit`, `/q`. +pub fn is_exit(text: &str) -> bool { + let text = text.trim().to_lowercase(); + text == ":q" + || EXIT_COMMANDS + .iter() + .any(|name| text == format!("/{name}")) +} + +/// `isNewCommand`. +pub fn is_new(text: &str) -> bool { + text.trim().to_lowercase() == "/new" +} + +/// `isCompactCommand`. +pub fn is_compact(text: &str) -> bool { + text.trim().to_lowercase() == "/compact" +} + +/// `/settings`, which opens M.4's settings view. +pub fn is_settings(text: &str) -> bool { + text.trim().to_lowercase() == "/settings" +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn local_words() { + for word in [":q", "/exit", " /QUIT ", "/q"] { + assert!(is_exit(word), "{word}"); + } + for word in ["exit", "quit", "/quitter", "q"] { + assert!(!is_exit(word), "{word}"); + } + assert!(is_new(" /NEW")); + assert!(is_compact("/compact")); + assert!(is_settings("/settings ")); + } + + #[test] + fn wire_shapes_follow_the_transport() { + let at = |start, end, text: &str| { + Some(Mention { + start, + end, + text: text.into(), + }) + }; + let prompt = RunPrompt { + text: "ask @general about @src/a.ts".into(), + parts: vec![ + Part::Agent { + name: "general".into(), + mention: at(4, 12, "@general"), + }, + Part::File(File { + url: "file:///w/src/a.ts".into(), + mime: Some("text/plain".into()), + filename: Some("src/a.ts".into()), + description: None, + mention: at(19, 28, "@src/a.ts"), + }), + Part::Skill { + id: "tidy".into(), + mention: None, + }, + ], + ..RunPrompt::default() + }; + assert_eq!( + prompt.files(), + [json!({ "uri": "file:///w/src/a.ts", "name": "src/a.ts", "mention": { "start": 19, "end": 28, "text": "@src/a.ts" } })] + ); + assert_eq!( + prompt.agents(), + [json!({ "name": "general", "mention": { "start": 4, "end": 12, "text": "@general" } })] + ); + assert_eq!(prompt.skills(), [json!({ "id": "tidy" })]); + let back = RunPrompt::from_message(&json!({ + "text": prompt.text, + "files": [{ "uri": "file:///w/src/a.ts", "mime": "text/plain", "name": "src/a.ts", "source": { "type": "uri", "uri": "file:///w/src/a.ts" }, "mention": { "start": 19, "end": 28, "text": "@src/a.ts" } }], + "agents": prompt.agents(), + "skills": prompt.skills(), + })); + assert_eq!(back.files(), prompt.files()); + assert_eq!(back.agents(), prompt.agents()); + assert!(back.has_file()); + } +} diff --git a/packages/cli-rs/crates/mini/src/prompt/queue.rs b/packages/cli-rs/crates/mini/src/prompt/queue.rs new file mode 100644 index 00000000000..c80422908d7 --- /dev/null +++ b/packages/cli-rs/crates/mini/src/prompt/queue.rs @@ -0,0 +1,174 @@ +//! The serial prompt queue (`runtime.queue.ts`) as a state machine the shell drives. Local operations (`/new`, +//! `/compact`) and turns run one at a time. A prompt submitted while an ordinary turn runs goes to the server's +//! inbox right away (steer by default, queue with `prompt.queue`) instead of waiting here. + +use std::collections::VecDeque; + +use super::parts::{Delivery, RunPrompt, is_compact, is_exit, is_new}; + +/// What a submit asks the shell to do. +#[derive(Debug, PartialEq)] +pub enum Submitted { + Ignored, + Exit, + /// Admit to the inbox now; the prompt has its message ID. + Admit(RunPrompt, Delivery), + /// Queued here; call [`Queue::pump`]. `first` clears the first-prompt hint. + Queued { first: bool }, +} + +/// The next piece of work [`Queue::pump`] hands out. +#[derive(Debug, PartialEq)] +pub enum Work { + New, + Compact, + /// A turn; an ordinary prompt has its message ID. + Run(RunPrompt), +} + +#[derive(Debug, Default)] +pub struct Queue { + queue: VecDeque, + /// The turn that runs, or `Some(None)` while a local operation does. + active: Option>, + /// Admissions made while the active turn ran (`admissionVersion`). + admissions: u32, + closed: bool, +} + +impl Queue { + pub fn close(&mut self) { + self.closed = true; + self.queue.clear(); + } + + pub fn busy(&self) -> bool { + self.active.is_some() + } + + /// The running turn, if it is a shell command. + pub fn shell_running(&self) -> bool { + matches!(&self.active, Some(Some(prompt)) if prompt.shell) + } + + /// `submit`. + pub fn submit(&mut self, prompt: RunPrompt) -> Submitted { + if self.closed || (prompt.text.trim().is_empty() && (prompt.shell || !prompt.has_file())) { + return Submitted::Ignored; + } + if !prompt.shell && is_exit(&prompt.text) { + return Submitted::Exit; + } + let local = |prompt: &RunPrompt| !prompt.shell && (is_new(&prompt.text) || is_compact(&prompt.text)); + let ordinary_active = matches!(&self.active, Some(Some(active)) if !active.shell); + if ordinary_active + && !prompt.shell + && prompt.command.as_ref().and_then(|command| command.source.as_deref()) != Some("skill") + && !local(&prompt) + && !self.queue.iter().any(local) + { + self.admissions += 1; + let delivery = prompt.delivery.unwrap_or(Delivery::Queue); + let sent = RunPrompt { + message_id: Some(opencode_api::id::message()), + ..prompt + }; + return Submitted::Admit(sent, delivery); + } + let first = !local(&prompt); + self.queue.push_back(prompt); + Submitted::Queued { first } + } + + /// The next work when nothing runs. + pub fn pump(&mut self) -> Option { + if self.closed || self.active.is_some() { + return None; + } + let prompt = self.queue.pop_front()?; + if !prompt.shell && is_new(&prompt.text) { + self.active = Some(None); + return Some(Work::New); + } + if !prompt.shell && is_compact(&prompt.text) { + self.active = Some(None); + return Some(Work::Compact); + } + let sent = if prompt.shell { + prompt + } else { + RunPrompt { + message_id: prompt.message_id.clone().or_else(|| Some(opencode_api::id::message())), + ..prompt + } + }; + self.admissions = 0; + self.active = Some(Some(sent.clone())); + Some(Work::Run(sent)) + } + + /// Whether prompts were admitted while the active turn ran, so it settles once more before it ends. + pub fn take_admissions(&mut self) -> bool { + std::mem::take(&mut self.admissions) > 0 + } + + /// The active work finished. Returns whether more waits. + pub fn done(&mut self) -> bool { + self.active = None; + !self.queue.is_empty() && !self.closed + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn text(text: &str) -> RunPrompt { + RunPrompt::text(text) + } + + #[test] + fn prompts_while_a_turn_runs_go_to_the_inbox() { + let mut queue = Queue::default(); + assert_eq!(queue.submit(text(" ")), Submitted::Ignored); + assert_eq!(queue.submit(text("/exit")), Submitted::Exit); + assert_eq!(queue.submit(text("one")), Submitted::Queued { first: true }); + let Some(Work::Run(run)) = queue.pump() else { panic!("a turn") }; + assert!(run.message_id.is_some()); + assert_eq!(queue.pump(), None); + // Enter steers; `prompt.queue` queues; a prompt without a delivery queues. + let steer = RunPrompt { + delivery: Some(Delivery::Steer), + ..text("two") + }; + let Submitted::Admit(sent, Delivery::Steer) = queue.submit(steer) else { panic!("admitted") }; + assert!(sent.message_id.is_some()); + assert!(matches!(queue.submit(text("three")), Submitted::Admit(_, Delivery::Queue))); + assert!(queue.take_admissions()); + assert!(!queue.take_admissions()); + assert!(!queue.done()); + } + + #[test] + fn shells_and_local_operations_wait_their_turn() { + let mut queue = Queue::default(); + let shell = RunPrompt { + shell: true, + ..text("ls") + }; + assert_eq!(queue.submit(shell.clone()), Submitted::Queued { first: true }); + assert_eq!(queue.pump(), Some(Work::Run(shell))); + assert!(queue.shell_running()); + // A prompt behind a shell waits here. + assert_eq!(queue.submit(text("after")), Submitted::Queued { first: true }); + assert!(queue.done()); + assert!(matches!(queue.pump(), Some(Work::Run(_)))); + assert_eq!(queue.submit(text("/compact")), Submitted::Queued { first: false }); + // While `/compact` waits, an ordinary prompt waits behind it too. + assert_eq!(queue.submit(text("later")), Submitted::Queued { first: true }); + assert!(queue.done()); + assert_eq!(queue.pump(), Some(Work::Compact)); + assert!(queue.done()); + assert!(matches!(queue.pump(), Some(Work::Run(_)))); + } +} diff --git a/packages/cli-rs/crates/mini/src/shell.rs b/packages/cli-rs/crates/mini/src/shell.rs index f8a1b632f9b..0101ade622b 100644 --- a/packages/cli-rs/crates/mini/src/shell.rs +++ b/packages/cli-rs/crates/mini/src/shell.rs @@ -19,7 +19,8 @@ use opentui::split::{Scrollback, SplitFooter}; use serde_json::{Value, json}; use crate::footers::Footers; -use crate::prompt::{Prompt, RunPrompt}; +use crate::prompt::queue::{Queue, Submitted, Work}; +use crate::prompt::{Delivery, Hooks, PROMPT_MAX_ROWS, Prompt, RunPrompt}; use crate::replay::{self, Envelope, Incoming, Output, Transcript}; use crate::scrollback::{Commit, Flags, Writer}; use crate::settings::MiniSettings; @@ -30,10 +31,10 @@ use crate::{Input, InputError}; /// `FOOTER_HEIGHT`: the footer's rows before the prompt measures itself. const FOOTER_HEIGHT: u16 = 4; -/// `PROMPT_MAX_ROWS`: a terminal at least this plus four rows tall pads the prompt. -const PROMPT_MAX_ROWS: u16 = 14; /// How long the second Ctrl+C or Esc of a two-press gesture may wait. const TWO_PRESS: Duration = Duration::from_secs(5); +/// `NOTICE_DURATION`. +const NOTICE: Duration = Duration::from_secs(3); pub fn run(input: Input) -> anyhow::Result<()> { let settings = MiniSettings::resolve(input.config.mini.as_ref()); @@ -43,14 +44,8 @@ pub fn run(input: Input) -> anyhow::Result<()> { palette_size: 256, ..AppOptions::default() }; - // The footer starts at the composer's height: a height set before the first frame does not resize the - // renderer, so `FOOTER_HEIGHT` would leave the status row below the screen. - let rows = opentui::term::size().map_or(0, |(_, rows)| rows); - options.host.split_footer = Some(if rows == 0 { - FOOTER_HEIGHT - } else { - prompt_height(rows, crate::prompt::MIN_ROWS) - }); + // `applyHeight` below sizes the footer to the composer before the first frame. + options.host.split_footer = Some(FOOTER_HEIGHT); options.host.terminal.mouse = MouseTracking::Off; if settings.mono { options.host.terminal.kitty_keyboard = KittyKeyboard::OFF; @@ -86,16 +81,16 @@ pub fn run(input: Input) -> anyhow::Result<()> { settings.mono, true, ); - let prompt = Prompt::new(&app, &theme, settings.mono); + let prompt = Prompt::new(&app, &theme, settings.mono, &input.config); let status = Text::new(&app, "") .wrap(WrapMode::None) .truncate(true) .height(1) .shrink(0.0); - let body = View::new(&app).child(prompt.root()); app.root() .direction(FlexDirection::Column) - .child(&body) + .child(prompt.root()) + .child(prompt.menu_root()) .child(&status); let mini = Rc::new(Mini { app: app.clone(), @@ -106,8 +101,8 @@ pub fn run(input: Input) -> anyhow::Result<()> { footers: RefCell::new(Footers::default()), session: RefCell::new(None), prompt, - body, status, + queue: RefCell::new(Queue::default()), state: RefCell::new(State::default()), theme_input, settings, @@ -182,6 +177,7 @@ struct State { running: bool, status: String, notice: String, + notice_timer: Option, model: String, agent: String, exit: u8, @@ -202,8 +198,8 @@ struct Mini { footers: RefCell, session: RefCell>, prompt: Prompt, - body: View, status: Text, + queue: RefCell, state: RefCell, theme_input: ThemeInput, settings: MiniSettings, @@ -227,30 +223,52 @@ impl Mini { mini.incoming(cx, incoming); } }); - let mini = self.clone(); - self.prompt - .on_submit(move |cx, prompt| mini.submit(cx, prompt)); - let mini = self.clone(); - self.app.on_key(move |cx, key| { - if key.matches("ctrl+c") { - cx.stop_propagation(); - if mini.prompt.value().is_empty() { - mini.request_exit(cx); - } else { - mini.prompt.clear(); - mini.patch(|state| { - state.exit = 0; - state.interrupt = 0; - }); + let weak = Rc::downgrade(self); + let with = move |run: fn(&Rc)| { + let weak = weak.clone(); + move || { + if let Some(mini) = weak.upgrade() { + run(&mini); } - } else if key.matches("ctrl+d") && mini.prompt.value().is_empty() { - cx.stop_propagation(); - mini.close(cx); - } else if key.matches("escape") { - cx.stop_propagation(); - mini.request_interrupt(cx); } + }; + let weak = Rc::downgrade(self); + let submit = weak.clone(); + let interrupt = weak.clone(); + let status = weak.clone(); + self.prompt.set_hooks(Hooks { + submit: Some(Box::new(move |prompt| { + submit.upgrade().is_some_and(|mini| mini.submit(prompt)) + })), + exit_request: Some(Box::new(with(|mini| { + let mini = mini.clone(); + mini.app.clone().defer(move |cx| mini.request_exit(cx)); + }))), + exit: Some(Box::new(with(|mini| { + let mini = mini.clone(); + mini.app.clone().defer(move |cx| mini.close(cx)); + }))), + interrupt: Some(Box::new(move || { + interrupt + .upgrade() + .is_some_and(|mini| mini.request_interrupt()) + })), + input_clear: Some(Box::new(with(|mini| mini.input_clear()))), + status: Some(Box::new(move |text| { + if let Some(mini) = status.upgrade() { + mini.set_notice(text); + } + })), + layout: Some(Box::new(with(|mini| { + mini.apply_height(); + mini.paint_status(); + }))), + clear_screen: Some(Box::new(with(|mini| mini.clear_screen()))), + // `/settings` opens M.4's settings view. + settings: None, }); + drop(weak); + self.prompt.install(); let mini = self.clone(); self.app.on_resize(move |cx, _, _| mini.resized(cx)); } @@ -335,8 +353,11 @@ impl Mini { self.input.replay_limit, )); *self.session.borrow_mut() = Some(session.clone()); + self.prompt + .set_agent(session.agent.as_deref().unwrap_or_default()); + self.prompt + .open(&self.client, &session.id, &session.directory, target.resume); if target.resume { - self.prompt.set_first(false); self.reset_for_replay(cx); } if target.model.is_none() { @@ -463,6 +484,12 @@ impl Mini { /// Writes a transcript output: footer events, commits, then the status. fn output(&self, cx: &mut Cx<'_>, output: Output) { for event in &output.footer { + if event["type"] + .as_str() + .is_some_and(|kind| kind.starts_with("session.inbox.")) + { + self.prompt.inbox_event(event); + } self.footers.borrow_mut().event(event); } if let Some(title) = &output.title { @@ -487,6 +514,7 @@ impl Mini { state.interrupt = 0; } }); + self.prompt.set_running(self.state.borrow().running); if idle && !self.state.borrow().running { self.complete(cx); } @@ -516,11 +544,10 @@ impl Mini { } } - /// A submitted prompt: an exit word closes mini; anything else is sent, or waits for the session. - fn submit(self: &Rc, cx: &mut Cx<'_>, prompt: RunPrompt) { - if crate::prompt::is_exit(&prompt.text) { - self.close(cx); - return; + /// `footer.handlePrompt`: a prompt from the composer goes to the queue, or waits for the session. + fn submit(self: &Rc, prompt: RunPrompt) -> bool { + if self.state.borrow().closed { + return false; } let ready = self .transcript @@ -529,71 +556,173 @@ impl Mini { .is_some_and(|transcript| transcript.connected); if !ready { self.waiting.borrow_mut().push(prompt); - return; + return true; } - self.send(cx, prompt); + self.enqueue(prompt); + true } - fn send_waiting(self: &Rc, cx: &mut Cx<'_>) { + fn send_waiting(self: &Rc, _cx: &mut Cx<'_>) { let initial = self.initial.borrow_mut().take(); if let Some(text) = initial.filter(|text| !text.trim().is_empty()) { - self.send( - cx, - RunPrompt { - message_id: Some(opencode_api::id::message()), - text, - ..RunPrompt::default() - }, - ); + self.prompt.push_history(&RunPrompt::text(text.clone())); + self.enqueue(RunPrompt::text(text)); } let waiting = std::mem::take(&mut *self.waiting.borrow_mut()); for prompt in waiting { - self.send(cx, prompt); + self.enqueue(prompt); } } - /// `runPromptTurn`: switch the agent and model, admit the prompt with `delivery: "steer"`, wait for the - /// session to settle, then print what the live stream missed. - fn send(self: &Rc, _cx: &mut Cx<'_>, prompt: RunPrompt) { + /// `runPromptQueue`'s `submit`. + fn enqueue(self: &Rc, prompt: RunPrompt) { + let submitted = self.queue.borrow_mut().submit(prompt); + match submitted { + Submitted::Ignored => {} + Submitted::Exit => { + let mini = self.clone(); + self.app.defer(move |cx| mini.close(cx)); + } + Submitted::Admit(prompt, delivery) => self.admit(prompt, delivery), + Submitted::Queued { first } => { + if first { + self.prompt.set_first(false); + } + self.pump(); + } + } + } + + /// Starts the next queued work when nothing runs (`drain`). + fn pump(self: &Rc) { + let work = self.queue.borrow_mut().pump(); + match work { + None => {} + Some(Work::New) => self.new_session(), + Some(Work::Compact) => self.compact(), + Some(Work::Run(prompt)) => self.send(prompt), + } + } + + /// The active work ended: the next starts, or the footer goes idle (`turn.idle`). + fn finish(self: &Rc, cx: &mut Cx<'_>) { + if self.queue.borrow_mut().done() { + self.pump(); + return; + } + self.patch(|state| state.turn = false); + self.output( + cx, + Output { + patch: Some(replay::Patch { + running: Some(false), + status: Some(String::new()), + usage: None, + }), + ..Output::default() + }, + ); + } + + /// `turn.send`. + fn sending(&self, status: &str) { + self.patch(|state| { + state.running = true; + state.turn = true; + state.status = status.into(); + state.notice.clear(); + state.interrupt = 0; + state.exit = 0; + }); + self.prompt.set_running(true); + } + + /// `renderPromptError`. + fn prompt_error(self: &Rc, cx: &mut Cx<'_>, id: &str, error: String) { + self.append( + cx, + Commit { + text: error, + ..Commit::error("").message(id) + }, + ); + } + + /// `run`: a shell command waits for its answer; a server command is admitted; an ordinary prompt switches + /// the agent and model, is admitted with its delivery (`steer` by default), and waits for the session to + /// settle, then prints what the live stream missed (`runPromptTurn`). + fn send(self: &Rc, prompt: RunPrompt) { let Some(session) = self.session.borrow().clone() else { return; }; + let client = self.client.clone(); + let mini = self.clone(); + if prompt.shell { + let id = opencode_api::id::message(); + self.sending("running shell"); + self.trace( + "send.shell", + json!({ "sessionID": session.id, "id": id, "command": prompt.text }), + ); + let command = prompt.text.clone(); + self.app.spawn( + { + let id = id.clone(); + async move { crate::prompt::api::shell(&client, &session.id, &id, &command).await } + }, + move |cx, result| { + if let Err(error) = result { + mini.prompt_error(cx, &id, error); + } + mini.finish(cx); + }, + ); + return; + } let id = prompt .message_id .clone() .unwrap_or_else(opencode_api::id::message); - self.patch(|state| { - state.running = true; - state.turn = true; - state.status = "sending prompt".into(); - state.interrupt = 0; - state.exit = 0; - }); - self.trace( - "send.prompt", - json!({ "sessionID": session.id, "messageID": id, "delivery": "steer" }), - ); - let client = self.client.clone(); - let mini = self.clone(); - let text = prompt.text.clone(); - let failed = Commit::error("").message(&id); + let delivery = prompt.delivery.unwrap_or(Delivery::Steer); + self.sending("sending prompt"); let started = std::time::Instant::now(); + match &prompt.command { + Some(command) => self.trace( + "send.command", + json!({ "sessionID": session.id, "messageID": id, "command": command.name, "delivery": delivery.as_str() }), + ), + None => self.trace( + "send.prompt", + json!({ "sessionID": session.id, "messageID": id, "delivery": delivery.as_str() }), + ), + } + let command = prompt.command.is_some(); + let text = prompt.text.clone(); self.app.spawn( { - let (session, id, text) = (session.clone(), id.clone(), text.clone()); + let (session, id) = (session.clone(), id.clone()); async move { - replay::prompt( - &client, - &session.id, - &id, - &text, - session.agent.as_deref(), - session.model.as_ref(), - ) - .await + if !command { + crate::prompt::api::select( + &client, + &session.id, + session.agent.as_deref(), + session.model.as_ref(), + ) + .await?; + } + let prompt = RunPrompt { + message_id: Some(id), + ..prompt + }; + crate::prompt::api::admit(&client, &session.id, &prompt, delivery).await } }, move |cx, result| match result { + Ok(()) if command => { + mini.turn_summary(cx, started); + mini.finish(cx); + } Ok(()) => { let output = mini .transcript @@ -605,31 +734,132 @@ impl Mini { mini.settle(&session.id, started); } Err(error) => { - mini.patch(|state| state.turn = false); - mini.append( - cx, - Commit { - text: error, - ..failed - }, - ); - mini.output( - cx, - Output { - patch: Some(replay::Patch { - running: Some(false), - status: Some(String::new()), - usage: None, - }), - ..Output::default() - }, - ); + mini.prompt_error(cx, &id, error); + mini.finish(cx); } }, ); } - /// `settleSession`: waits until the session is idle, then lists its messages. + /// A prompt submitted while an ordinary turn runs goes to the inbox at once (`input.admit`). + fn admit(self: &Rc, prompt: RunPrompt, delivery: Delivery) { + let Some(session) = self.session.borrow().clone() else { + return; + }; + let id = prompt.message_id.clone().unwrap_or_default(); + self.trace( + "send.prompt", + json!({ "sessionID": session.id, "messageID": id, "delivery": delivery.as_str() }), + ); + let client = self.client.clone(); + let mini = self.clone(); + let command = prompt.command.is_some(); + let text = prompt.text.clone(); + self.app.spawn( + async move { + if !command { + crate::prompt::api::select( + &client, + &session.id, + session.agent.as_deref(), + session.model.as_ref(), + ) + .await?; + } + crate::prompt::api::admit(&client, &session.id, &prompt, delivery).await + }, + move |cx, result| match result { + Ok(()) => { + mini.prompt.admitted(&id, delivery); + let output = mini + .transcript + .borrow_mut() + .as_mut() + .map(|transcript| transcript.admitted(&id, &text)) + .unwrap_or_default(); + mini.output(cx, output); + } + Err(error) => mini.prompt_error(cx, &id, error), + }, + ); + } + + /// `/compact`: `session.compact`. + fn compact(self: &Rc) { + let Some(session) = self.session.borrow().clone() else { + return; + }; + self.sending("compacting session"); + let client = self.client.clone(); + let mini = self.clone(); + self.app.spawn( + async move { crate::prompt::api::compact(&client, &session.id).await }, + move |cx, result| { + if let Err(error) = result { + let id = opencode_api::id::message(); + mini.prompt_error(cx, &id, error); + } + mini.finish(cx); + }, + ); + } + + /// `/new`: a new session at the launch directory, with the current agent and model (`onNewSession`). + fn new_session(self: &Rc) { + let Some(session) = self.session.borrow().clone() else { + return; + }; + self.sending("starting new session"); + let client = self.client.clone(); + let mini = self.clone(); + let model = session.model.as_ref().and_then(|model| { + Some(opencode_api::generated::ModelRef { + provider_id: opencode_api::generated::ProviderID(model["providerID"].as_str()?.to_owned()), + id: model["id"].as_str()?.to_owned(), + variant: model["variant"].as_str().map(str::to_owned), + }) + }); + let input = target::TargetInput { + directory: Some(self.input.directory.clone()), + agent: session.agent.clone(), + model, + ..target::TargetInput::default() + }; + let agent = session.agent.clone(); + self.app.spawn( + async move { + target::resolve_session_target(&client, input, |next| async move { + Ok(Prepared { + model: next.model, + agent: agent.or(next.agent), + }) + }) + .await + }, + move |cx, result| { + match result { + Ok(next) => { + mini.stop(); + mini.complete(cx); + let id = next.session.id.0.clone(); + mini.opened(cx, next); + mini.prompt.set_first(true); + mini.trace("session.new", json!({ "sessionID": id })); + mini.write(cx, Commit::system(format!("new session {id}"))); + } + Err(error) => { + mini.patch(|state| state.status = "failed to start new session".into()); + let id = opencode_api::id::message(); + mini.prompt_error(cx, &id, error.to_string()); + } + } + mini.finish(cx); + }, + ); + } + + /// `settleSession`: waits until the session is idle, then lists its messages. Prompts admitted meanwhile + /// settle once more. fn settle(self: &Rc, session: &str, started: std::time::Instant) { let client = self.client.clone(); let session = session.to_owned(); @@ -639,12 +869,14 @@ impl Mini { .unwrap_or(replay::DEFAULT_REPLAY_LIMIT); let mini = self.clone(); self.app.spawn( - async move { - replay::wait(&client, &session).await?; - replay::messages(&client, &session, limit).await + { + let session = session.clone(); + async move { + replay::wait(&client, &session).await?; + replay::messages(&client, &session, limit).await + } }, move |cx, result| { - mini.patch(|state| state.turn = false); let mut output = Output::default(); match result { Ok(messages) => { @@ -656,13 +888,13 @@ impl Mini { } Err(error) => log::warn!("mini settle failed: {error}"), } - output.patch = Some(replay::Patch { - running: Some(false), - status: Some(String::new()), - usage: None, - }); mini.output(cx, output); + if mini.queue.borrow_mut().take_admissions() { + mini.settle(&session, started); + return; + } mini.turn_summary(cx, started); + mini.finish(cx); }, ); } @@ -679,7 +911,7 @@ impl Mini { .and_then(|session| session.model.as_ref()?["id"].as_str().map(str::to_owned)) .unwrap_or_else(|| self.state.borrow().model.clone()); let summary = crate::scrollback::TurnSummary { - agent: capitalize(&self.state.borrow().agent), + agent: self.agent_label(&self.state.borrow().agent), model, duration: duration(started.elapsed().as_millis() as u64), }; @@ -717,11 +949,11 @@ impl Mini { } /// Two presses of Esc while the session runs interrupt it (`handleInterrupt`). - fn request_interrupt(self: &Rc, _cx: &mut Cx<'_>) { + fn request_interrupt(self: &Rc) -> bool { let interrupt = { let mut state = self.state.borrow_mut(); if state.closed || !state.running { - return; + return false; } state.interrupt += 1; state.interrupt @@ -735,14 +967,12 @@ impl Mini { self.app.cancel_timer(previous); } self.paint_status(); - return; + return true; } - self.patch(|state| { - state.interrupt = 0; - state.notice = "interrupting".into(); - }); + self.patch(|state| state.interrupt = 0); + self.set_notice("interrupting"); let Some(session) = self.session.borrow().clone() else { - return; + return true; }; self.trace("send.interrupt", json!({ "sessionID": session.id })); let client = self.client.clone(); @@ -754,6 +984,57 @@ impl Mini { } }, ); + true + } + + /// `setStatus`: a notice in the status row for three seconds. + fn set_notice(self: &Rc, text: &str) { + let previous = self.state.borrow_mut().notice_timer.take(); + if let Some(previous) = previous { + self.app.cancel_timer(previous); + } + self.patch(|state| state.notice = text.to_owned()); + if text.is_empty() { + return; + } + let weak = Rc::downgrade(self); + let timer = self.app.set_timeout(NOTICE, move |_| { + if let Some(mini) = weak.upgrade() { + mini.patch(|state| { + state.notice.clear(); + state.notice_timer = None; + }); + } + }); + self.state.borrow_mut().notice_timer = Some(timer); + } + + /// `handleInputClear`: typing disarms the two-press gestures. + fn input_clear(&self) { + let timers = { + let mut state = self.state.borrow_mut(); + if state.interrupt == 0 && state.exit == 0 { + return; + } + state.interrupt = 0; + state.exit = 0; + [state.interrupt_timer.take(), state.exit_timer.take()] + }; + for timer in timers.into_iter().flatten() { + self.app.cancel_timer(timer); + } + self.paint_status(); + } + + /// `app.clear` (`clearScreen`): homes and clears the visible screen, keeps the terminal's scrollback, and + /// repaints the footer. + fn clear_screen(&self) { + if self.state.borrow().closed || !self.footer.is_split() { + return; + } + if let Err(error) = self.footer.reset_for_replay(false) { + log::warn!("mini could not clear the screen: {error}"); + } } /// `close`: finish the streaming entry, leave split mode, and quit. The newline follows `app.run()`. @@ -884,13 +1165,15 @@ impl Mini { self.paint_status(); } - /// `applyHeight` for the composer: the prompt's rows, padded in a tall terminal, plus the status row. + /// `applyHeight` for the composer: the prompt's rows, padded in a tall terminal, plus the status row unless + /// the autocomplete menu replaces it. fn apply_height(&self) { - let terminal = self.footer.terminal_size().1; - let height = prompt_height(terminal, self.prompt.rows()); - let padding = u16::from(terminal >= PROMPT_MAX_ROWS + 4); - self.body.padding_y(u32::from(padding)); - if let Err(error) = self.footer.set_footer_height(height) { + let terminal = self.footer.terminal_size(); + let height = prompt_height(terminal.1, self.prompt.rows(terminal)); + self.status.visible(!self.prompt.menu_visible()); + let r = self.footer.set_footer_height(height); + { use std::io::Write; let mut f = std::fs::OpenOptions::new().create(true).append(true).open("/home/simon/.cache/tmp/opencode/mini-debug.log").unwrap(); writeln!(f, "set {height} -> {:?} now {}", r.as_ref().err(), self.footer.footer_height()).ok(); } + if let Err(error) = r { log::warn!("mini could not set the footer height: {error}"); } } @@ -917,11 +1200,20 @@ impl Mini { .to_owned() .fg(theme.footer.warning), ] + } else if !state.notice.is_empty() { + vec![state.notice.clone().fg(theme.footer.text)] + } else if self.prompt.shell() && !state.running && state.status.is_empty() { + vec![ + "Shell".fg(theme.footer.muted), + separator.fg(theme.footer.muted), + "esc".fg(theme.footer.text), + " normal".fg(theme.footer.muted), + ] } else { - let agent = capitalize(&state.agent); + let agent = self.agent_label(&state.agent); let mut spans = Vec::new(); if !agent.is_empty() { - spans.push(agent.fg(theme.footer.text)); + spans.push(agent.fg(self.prompt.agent_color())); } if !state.model.is_empty() { let lead = if spans.is_empty() { "" } else { separator }; @@ -932,19 +1224,21 @@ impl Mini { }; spans.push(format!("{lead}{model}").fg(theme.footer.muted)); } - let note = if state.notice.is_empty() { - &state.status - } else { - &state.notice - }; - if !note.is_empty() { - spans.push(format!("{separator}{note}").fg(theme.footer.muted)); + if !state.status.is_empty() { + spans.push(format!("{separator}{}", state.status).fg(theme.footer.muted)); } spans }; self.status.set_text(content); } + /// `currentAgent`: the catalog's name for the agent, else its ID in title case. + fn agent_label(&self, agent: &str) -> String { + self.prompt + .agent_name(agent) + .unwrap_or_else(|| capitalize(agent)) + } + /// The terminal title on Linux (`setTitle`): `OC | `, or `OpenCode` without a real title. fn set_title(&self, title: Option<&str>) { if !cfg!(target_os = "linux") { diff --git a/packages/cli-rs/crates/tui/src/prompt/autocomplete/parts.rs b/packages/cli-rs/crates/tui/src/prompt/autocomplete/parts.rs index 68354ac04e5..bbe4b52400e 100644 --- a/packages/cli-rs/crates/tui/src/prompt/autocomplete/parts.rs +++ b/packages/cli-rs/crates/tui/src/prompt/autocomplete/parts.rs @@ -10,8 +10,6 @@ use std::cell::RefCell; use opencode_api::generated::{PromptAgentAttachment, PromptInputSkillAttachment}; -use opentui::native::SelectionColors; -use opentui::prelude::*; use opentui::widget::{ExtmarkId, ExtmarkOptions}; use serde_json::{Value, json}; @@ -254,21 +252,7 @@ pub fn skills(entry: &Value) -> Option<Vec<PromptInputSkillAttachment>> { .filter(|skills| !skills.is_empty()) } -/// Replaces offsets `start..end` with `text` as one edit through the widget, so marks move. -pub fn replace(textarea: &Textarea, start: u32, end: u32, text: &str) { - if start < end { - let _ = textarea - .view() - .select_range(start, end, SelectionColors::default()); - if text.is_empty() { - textarea.perform(EditorAction::Backspace); - return; - } - } - if !text.is_empty() { - textarea.insert(text); - } -} +pub use opencode_ui::prompt_input::replace; /// An atomic mark in the kind's `extmark.*` style. fn options(prompt: &Inner, kind: Kind) -> ExtmarkOptions { diff --git a/packages/cli-rs/crates/ui/src/prompt_input/mod.rs b/packages/cli-rs/crates/ui/src/prompt_input/mod.rs index 30b92f00a77..d8966b307e0 100644 --- a/packages/cli-rs/crates/ui/src/prompt_input/mod.rs +++ b/packages/cli-rs/crates/ui/src/prompt_input/mod.rs @@ -5,3 +5,22 @@ pub mod attach; pub mod editor; pub mod parse; pub mod paste; + +use opentui::native::SelectionColors; +use opentui::prelude::*; + +/// Replaces offsets `start..end` with `text` as one edit through the widget, so marks move. +pub fn replace(textarea: &Textarea, start: u32, end: u32, text: &str) { + if start < end { + let _ = textarea + .view() + .select_range(start, end, SelectionColors::default()); + if text.is_empty() { + textarea.perform(EditorAction::Backspace); + return; + } + } + if !text.is_empty() { + textarea.insert(text); + } +} diff --git a/packages/cli-rs/parity/pty/run.ts b/packages/cli-rs/parity/pty/run.ts index c43e7ae28f7..31500180c21 100644 --- a/packages/cli-rs/parity/pty/run.ts +++ b/packages/cli-rs/parity/pty/run.ts @@ -66,8 +66,8 @@ export type PtyCase = { exits?: boolean // Plan 7.5: line masks for checkpoints. Each match becomes `<masked>`; say why in `reason`. masks?: { pattern: RegExp; reason: string }[] - // Compare the request log too. - requests?: boolean + // Compare the request log too; `"writes"` leaves the reads out, for screens whose reads belong to later steps. + requests?: boolean | "writes" tsOnly?: boolean // As in P-CLI: writes files into the sandbox before the command runs. setup?: (root: string, server: string | undefined) => Promise<void> @@ -171,7 +171,11 @@ export async function runPty(side: Side, value: PtyCase) { ), ]), ), - ...(value.requests ? { requests: requestLog(server?.requests ?? [], context) } : {}), + ...(value.requests === "writes" + ? { requests: { writes: requestLog(server?.requests ?? [], context).writes } } + : value.requests + ? { requests: requestLog(server?.requests ?? [], context) } + : {}), } } diff --git a/packages/cli-rs/parity/scenarios/M.2/fixture.ts b/packages/cli-rs/parity/scenarios/M.2/fixture.ts new file mode 100644 index 00000000000..719b0b5f103 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/M.2/fixture.ts @@ -0,0 +1,111 @@ +// M.1's `ses_mini` server with what the footer prompt needs: the catalogs it completes from (agents, commands, +// references, a file search) and the writes it makes (commands, shells, compaction, inbox changes). +import type { Logged, Options, Route } from "../../lib/fake-server" +import { location, server as base } from "../M.1/fixture" + +import { event } from "../M.1/fixture" + +export { config, event, history, user, assistant } from "../M.1/fixture" + +const listed = (data: unknown[]) => ({ location, data }) + +export const agents = [ + { id: "build", name: "build", description: "Default agent", mode: "primary", hidden: false }, + { id: "plan", name: "plan", description: "Planning agent", mode: "primary", hidden: false }, + { id: "general", name: "general", description: "General purpose subagent", mode: "subagent", hidden: false }, + { id: "explore", name: "explore", description: "Explores the code", mode: "subagent", hidden: false }, +] + +export const commands = [ + { name: "review", description: "Review the working tree", source: "command" }, + { name: "init", description: "Create AGENTS.md", source: "command" }, +] + +export const files = ["src/main.ts", "src/general.ts", "src/", "README.md"] + +// The status row's hints open M.3's views: the command menu (`ctrl+p menu`) and the pending prompts +// (`ctrl+x q 1 pending`). +export const statusMask = { + pattern: /^(ctrl\+x q \d+ pending · )?build · model · demo( · ctrl\+p menu)?$/, + reason: "the ctrl+p menu and pending-prompt hints open M.3's views", +} + +type Script = Omit<NonNullable<Parameters<typeof base>[0]>, "events"> & { + // How long `session.wait` holds a turn open, in ms. + wait?: number + // Events pushed after a prompt, given its ID and the request log (the prompt is its last entry). + events?: (id: string, requests: Logged[]) => unknown[] +} + +const inboxItem = (entry: Logged) => { + const body = entry.body as { id: string; text: string; delivery?: string } + return { + id: body.id, + sessionID: "ses_mini", + time: { created: 3 }, + type: "user", + payload: { text: body.text }, + delivery: body.delivery ?? "steer", + } +} + +export function server(script: Script = {}): Options { + const options = base({ ...script, events: undefined }) + const routes: Route[] = [ + { path: "/api/agent", json: listed(agents) }, + { path: "/api/command", json: listed(commands) }, + { path: "/api/reference", json: listed([]) }, + { + path: "/api/fs/find", + json: (entry) => { + const query = entry.query.query?.[0] ?? "" + return listed(files.filter((file) => file.includes(query)).map((path) => ({ path }))) + }, + }, + { method: "POST", path: "/api/session/ses_mini/command", status: 204 }, + { method: "POST", path: "/api/session/ses_mini/shell", status: 204 }, + { + method: "PATCH", + path: "/api/session/ses_mini/inbox/:id", + json: (entry) => ({ + data: inboxItem({ ...entry, body: { ...(entry.body as object), id: entry.path.split("/").pop(), text: "" } }), + }), + }, + ...(script.wait === undefined + ? [] + : [{ method: "POST", path: "/api/experimental/session/ses_mini/wait", status: 204, delay: script.wait }]), + // Admitted prompts echo their delivery, so a queued prompt reads back as queued. + { + method: "POST", + path: "/api/session/ses_mini/prompt", + json: (entry: Logged) => ({ data: inboxItem(entry) }), + then: (entry: Logged, requests: Logged[]) => script.events?.((entry.body as { id: string }).id, requests) ?? [], + }, + ] + return { ...options, routes: [...routes, ...(options.routes ?? [])] } +} + +// The events of a prompt the server delivers and answers at once. +export const answer = (id: string, reply: string, message = "msg_a4") => [ + event("session.inbox.delivered", { inboxID: id }), + event("session.execution.started", {}), + event("session.step.started", { + assistantMessageID: message, + agent: "build", + model: { id: "model", providerID: "demo" }, + snapshot: "snap_1", + started: 101, + }), + event("session.text.delta", { assistantMessageID: message, ordinal: 0, delta: reply }), + event("session.text.ended", { assistantMessageID: message, ordinal: 0, text: reply }), + event("session.execution.succeeded", {}), +] + +// Every scenario: `mini -s ses_mini` at 60x20, Ctrl+C twice to leave. +export const leave = [ + { keys: "\x03", settle: 200 }, + { keys: "\x03", settle: 400 }, +] + +// Waits for the replayed transcript. +export const opened = { until: { screen: "Third answer" }, settle: 600, timeout: 30_000 } diff --git a/packages/cli-rs/parity/scenarios/M.2/history.pty.ts b/packages/cli-rs/parity/scenarios/M.2/history.pty.ts new file mode 100644 index 00000000000..35a93538c79 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/M.2/history.pty.ts @@ -0,0 +1,25 @@ +// Up at the start steps back through the session's prompts, Down at the end steps forward and restores the draft. +import { definePty } from "../../pty/run" +import { config, leave, opened, server, statusMask } from "./fixture" + +export default definePty({ + args: ["mini", "-s", "ses_mini"], + cols: 60, + rows: 20, + server: server(), + setup: (root) => config(root), + steps: [ + opened, + { keys: "draft", settle: 200 }, + { keys: "\x1b[A", settle: 300, checkpoint: "start" }, + { keys: "\x1b[A", settle: 300, checkpoint: "third" }, + { keys: "\x1b[A", settle: 300, checkpoint: "second" }, + { keys: "\x1b[B", settle: 300 }, + { keys: "\x1b[B", settle: 300, checkpoint: "third-end" }, + { keys: "\x1b[B", settle: 300, checkpoint: "draft" }, + ...leave, + ], + exits: true, + masks: [statusMask], + requests: "writes", +}) diff --git a/packages/cli-rs/parity/scenarios/M.2/mention.pty.ts b/packages/cli-rs/parity/scenarios/M.2/mention.pty.ts new file mode 100644 index 00000000000..701aac61907 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/M.2/mention.pty.ts @@ -0,0 +1,27 @@ +// `@` lists subagents, then the file search's results; Tab picks one as a mention part, and Enter sends it in the +// prompt's `agents` and `files`. +import { definePty } from "../../pty/run" +import { config, leave, opened, server, statusMask } from "./fixture" + +export default definePty({ + args: ["mini", "-s", "ses_mini"], + cols: 60, + rows: 20, + server: server(), + setup: (root) => config(root), + steps: [ + opened, + { keys: "ask @gen", settle: 600, checkpoint: "listed" }, + { keys: "\t", settle: 300, checkpoint: "agent" }, + { keys: "and @main", settle: 600, checkpoint: "file" }, + { keys: "\r", settle: 300, checkpoint: "picked" }, + { keys: "\x7f\x7f", settle: 300, checkpoint: "atomic" }, + { keys: "@main", settle: 600 }, + { keys: "\r", settle: 300 }, + { keys: "\r", settle: 1000, checkpoint: "sent" }, + ...leave, + ], + exits: true, + masks: [statusMask], + requests: "writes", +}) diff --git a/packages/cli-rs/parity/scenarios/M.2/queue.pty.ts b/packages/cli-rs/parity/scenarios/M.2/queue.pty.ts new file mode 100644 index 00000000000..c2016568491 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/M.2/queue.pty.ts @@ -0,0 +1,37 @@ +// While a turn runs, Enter steers the next prompt into the inbox and `prompt.queue` (Ctrl+X Enter) queues one; +// a shell command cannot be queued; Ctrl+L clears the screen. +import { definePty } from "../../pty/run" +import { config, event, leave, opened, server, statusMask } from "./fixture" + +export default definePty({ + args: ["mini", "-s", "ses_mini"], + cols: 60, + rows: 20, + server: server({ + wait: 4000, + // The first prompt starts a turn that stays open while `session.wait` holds. + events: (id, requests) => + requests.filter((entry) => entry.path.endsWith("/prompt")).length === 1 + ? [event("session.inbox.delivered", { inboxID: id }), event("session.execution.started", {})] + : [], + }), + setup: (root) => config(root), + steps: [ + opened, + { keys: "first", settle: 200 }, + { keys: "\r", settle: 600, checkpoint: "running" }, + { keys: "steer this", settle: 200 }, + { keys: "\r", settle: 600 }, + { keys: "queue this", settle: 200 }, + { keys: "\x18\r", settle: 600, checkpoint: "queued" }, + { keys: "!", settle: 100 }, + { keys: "ls", settle: 100 }, + { keys: "\x18\r", settle: 400, checkpoint: "refused" }, + { keys: "\x1b", settle: 100 }, + { keys: "\x0c", settle: 600, checkpoint: "cleared" }, + ...leave, + ], + exits: true, + masks: [statusMask], + requests: "writes", +}) diff --git a/packages/cli-rs/parity/scenarios/M.2/shell.pty.ts b/packages/cli-rs/parity/scenarios/M.2/shell.pty.ts new file mode 100644 index 00000000000..be8179ac1af --- /dev/null +++ b/packages/cli-rs/parity/scenarios/M.2/shell.pty.ts @@ -0,0 +1,25 @@ +// `!` at the start enters shell mode, Escape leaves it, Backspace at the start leaves it; Enter runs the command +// with `session.shell` and the composer returns to normal mode. +import { definePty } from "../../pty/run" +import { config, leave, opened, server, statusMask } from "./fixture" + +export default definePty({ + args: ["mini", "-s", "ses_mini"], + cols: 60, + rows: 20, + server: server(), + setup: (root) => config(root), + steps: [ + opened, + { keys: "!", settle: 300, checkpoint: "shell" }, + { keys: "\x1b", settle: 300, checkpoint: "normal" }, + { keys: "!", settle: 200 }, + { keys: "\x7f", settle: 300, checkpoint: "backspace" }, + { keys: "!ls -la", settle: 300, checkpoint: "typed" }, + { keys: "\r", settle: 800, checkpoint: "ran" }, + ...leave, + ], + exits: true, + masks: [statusMask], + requests: "writes", +}) diff --git a/packages/cli-rs/parity/scenarios/M.2/slash.pty.ts b/packages/cli-rs/parity/scenarios/M.2/slash.pty.ts new file mode 100644 index 00000000000..3345d653094 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/M.2/slash.pty.ts @@ -0,0 +1,27 @@ +// `/` lists mini's built-ins and the server's commands; a query filters them; Escape removes the typed trigger; +// Enter on a command sends it with `session.command`. +import { definePty } from "../../pty/run" +import { config, leave, opened, server, statusMask } from "./fixture" + +export default definePty({ + args: ["mini", "-s", "ses_mini"], + cols: 60, + rows: 20, + server: server(), + setup: (root) => config(root), + steps: [ + opened, + { keys: "/", settle: 400, checkpoint: "slash" }, + { keys: "\x1b[B\x1b[B", settle: 300, checkpoint: "moved" }, + { keys: "re", settle: 400, checkpoint: "filtered" }, + { keys: "\x1b", settle: 300, checkpoint: "hidden" }, + { keys: "/rev", settle: 300 }, + { keys: "\r", settle: 800, checkpoint: "sent" }, + { keys: "/settings", settle: 300 }, + { keys: "\x18\r", settle: 300, checkpoint: "not-queued" }, + ...leave, + ], + exits: true, + masks: [statusMask], + requests: "writes", +}) diff --git a/packages/cli-rs/parity/scenarios/M.2/typing.pty.ts b/packages/cli-rs/parity/scenarios/M.2/typing.pty.ts new file mode 100644 index 00000000000..0c5f713613b --- /dev/null +++ b/packages/cli-rs/parity/scenarios/M.2/typing.pty.ts @@ -0,0 +1,27 @@ +// Typing grows the footer one row per line (Shift+Enter), up to six; Enter sends the prompt with `steer` and the +// footer shrinks back. +import { definePty } from "../../pty/run" +import { answer, assistant, config, leave, opened, server, statusMask, user } from "./fixture" + +export default definePty({ + args: ["mini", "-s", "ses_mini"], + cols: 60, + rows: 20, + server: server({ + events: (id) => answer(id, "Three lines read."), + after: (id) => [user(id, "one\ntwo\nthree", 100), assistant("msg_a4", [{ type: "text", text: "Three lines read." }], 101)], + }), + setup: (root) => config(root), + steps: [ + { ...opened, checkpoint: "open" }, + { keys: "one\x1b[13;2utwo\x1b[13;2uthree", settle: 400, checkpoint: "grown" }, + { keys: "\x1b[13;2u4\x1b[13;2u5\x1b[13;2u6\x1b[13;2u7", settle: 400, checkpoint: "capped" }, + { keys: "\x03", settle: 300 }, + { keys: "one\x1b[13;2utwo\x1b[13;2uthree", settle: 300 }, + { keys: "\r", until: { screen: "Three lines read." }, settle: 800, checkpoint: "sent", scrollback: 8 }, + ...leave, + ], + exits: true, + masks: [statusMask], + requests: "writes", +})