wip: before the machine move

This commit is contained in:
Simon Klee 2026-11-05 12:36:08 +01:00
parent b2cf0b408d
commit 47ad8669cd
No known key found for this signature in database
GPG key ID: B91696044D47BEA3
18 changed files with 4013 additions and 243 deletions

View file

@ -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<Vec<Value>, 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<String> {
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::<Value>(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<RunPrompt> {
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::<Value>(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::<Value>(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::<Value>(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(())
}

View file

@ -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<String>,
pub source: Option<String>,
}
/// What the footer completes from (`catalog` event).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Catalog {
pub agents: Vec<Agent>,
pub references: Vec<Reference>,
/// `None` until the command list arrives: a slash command then waits ("loading commands").
pub commands: Option<Vec<Command>>,
}
/// 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<String>,
part: Part,
directory: bool,
},
Slash {
name: String,
display: String,
description: Option<String>,
action: Option<Action>,
},
}
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<Choice> {
let builtin = |name: &str, description: &str, action: Option<Action>| 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<Choice> = 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<Choice> {
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<Choice> {
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<LineRange>, directory: &str, width: usize) -> Vec<Choice> {
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<String> = (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<Choice>) -> Vec<Choice> {
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<Choice>) -> Vec<Choice> {
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<String> {
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");
}
}

View file

@ -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<RunPrompt>,
pub index: Option<usize>,
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<RunPrompt> = 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<RunPrompt> = (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);
}
}

View file

@ -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<String>,
}
/// 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");
}
}

File diff suppressed because it is too large Load diff

View file

@ -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<String>,
pub filename: Option<String>,
pub description: Option<String>,
/// The `@path` or `[Image N]` text the part stands for, while it is in the prompt.
pub mention: Option<Mention>,
}
/// `RunPromptPart` of a mention kind.
#[derive(Clone, Debug, PartialEq)]
pub enum Part {
File(File),
Agent {
name: String,
mention: Option<Mention>,
},
Skill {
id: String,
mention: Option<Mention>,
},
}
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<String>,
}
/// `RunPrompt`.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct RunPrompt {
pub message_id: Option<String>,
pub text: String,
pub parts: Vec<Part>,
pub delivery: Option<Delivery>,
/// `mode: "shell"`.
pub shell: bool,
pub command: Option<Command>,
}
impl RunPrompt {
pub fn text(text: impl Into<String>) -> 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<Value> {
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<Value> {
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<Value> {
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<Mention>) -> Value {
if let Some(mention) = mention {
value["mention"] = wire(mention);
}
value
}
fn mention(value: &Value) -> Option<Mention> {
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());
}
}

View file

@ -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<RunPrompt>,
/// The turn that runs, or `Some(None)` while a local operation does.
active: Option<Option<RunPrompt>>,
/// 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<Work> {
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(_))));
}
}

View file

@ -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<TimerId>,
model: String,
agent: String,
exit: u8,
@ -202,8 +198,8 @@ struct Mini {
footers: RefCell<Footers>,
session: RefCell<Option<Session>>,
prompt: Prompt,
body: View,
status: Text,
queue: RefCell<Queue>,
state: RefCell<State>,
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<Mini>)| {
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<Self>, 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<Self>, 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<Self>, cx: &mut Cx<'_>) {
fn send_waiting(self: &Rc<Self>, _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<Self>, _cx: &mut Cx<'_>, prompt: RunPrompt) {
/// `runPromptQueue`'s `submit`.
fn enqueue(self: &Rc<Self>, 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<Self>) {
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<Self>, 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<Self>, 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<Self>, 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<Self>, 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<Self>) {
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<Self>) {
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<Self>, 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<Self>, _cx: &mut Cx<'_>) {
fn request_interrupt(self: &Rc<Self>) -> 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<Self>, 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 | <title>`, or `OpenCode` without a real title.
fn set_title(&self, title: Option<&str>) {
if !cfg!(target_os = "linux") {

View file

@ -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 {

View file

@ -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);
}
}

View file

@ -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) }
: {}),
}
}

View file

@ -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 }

View file

@ -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",
})

View file

@ -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",
})

View file

@ -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",
})

View file

@ -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",
})

View file

@ -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",
})

View file

@ -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",
})