diff --git a/packages/cli-rs/Cargo.lock b/packages/cli-rs/Cargo.lock index f15989db1ef..0a4cca7c96b 100644 --- a/packages/cli-rs/Cargo.lock +++ b/packages/cli-rs/Cargo.lock @@ -1229,10 +1229,22 @@ dependencies = [ name = "opencode-mini" version = "0.1.0" dependencies = [ + "anyhow", + "chrono", + "futures-util", + "indexmap", + "log", + "opencode-api", "opencode-local", "opencode-service", "opencode-store", "opencode-ui", + "opentui", + "rustix", + "serde_json", + "tempfile", + "tokio", + "unicode-width", ] [[package]] diff --git a/packages/cli-rs/crates/cli/src/commands/mini.rs b/packages/cli-rs/crates/cli/src/commands/mini.rs index 36013067d68..0bab5d60466 100644 --- a/packages/cli-rs/crates/cli/src/commands/mini.rs +++ b/packages/cli-rs/crates/cli/src/commands/mini.rs @@ -1,8 +1,102 @@ -//! `mini`: the minimal interactive interface. +//! `mini`: the minimal interactive interface (`handlers/mini.ts`, `packages/cli/src/mini.ts`). The handler +//! checks the flags and the terminal, takes piped stdin, connects, and runs `opencode-mini`. -use super::{Context, not_built}; +use std::io::IsTerminal; +use std::time::Instant; + +use opencode_api::generated::SessionID; +use opencode_local::cli_config::CliConfig; +use opencode_local::paths::{self, Paths}; +use opencode_mini::stdin::{self, INTERACTIVE_INPUT_ERROR}; +use opencode_mini::{Input, InputError, signals::Trace}; +use opencode_store::target::{self, TargetInput}; + +use super::Context; +use super::client::connect; use crate::args::MiniArgs; +use crate::output::Exit; -pub fn run(_context: &Context, _args: &MiniArgs) -> anyhow::Result<()> { - not_built("mini", "M.1") +pub fn run(context: &Context, args: &MiniArgs) -> anyhow::Result<()> { + let start = Instant::now(); + if !std::io::stdout().is_terminal() { + return fail("opencode mini requires a TTY stdout"); + } + if let Some(limit) = args.replay_limit + && limit <= 0 + { + return fail("--replay-limit must be a positive integer"); + } + if args.fork && !args.continue_ && args.session.is_none() { + return fail("--fork requires --continue or --session"); + } + let piped = match stdin::take_piped() { + Ok(piped) => piped, + Err(message) if message == INTERACTIVE_INPUT_ERROR => return fail(&message), + Err(message) => anyhow::bail!(message), + }; + let initial_input = stdin::merge_input(piped.as_deref(), args.prompt.as_deref()); + let Ok(directory) = paths::start_directory() else { + let root = std::env::var("PWD").unwrap_or_default(); + return fail(&format!("Failed to change directory to {root}")); + }; + let directory = directory.to_string_lossy().into_owned(); + let Ok(model) = target::parse_model(args.model.as_deref()) else { + return fail("--model must use the format provider/model[#variant]"); + }; + let paths = Paths::from_env()?; + let config = CliConfig::new(&paths).get().unwrap_or_else(|error| { + log::warn!("failed to read cli.json: {error}"); + Default::default() + }); + let mini = config.mini.clone().unwrap_or_default(); + // The TUI's tasks need a multi-threaded runtime: `App::runtime` uses the one it runs inside. + let runtime = tokio::runtime::Builder::new_multi_thread() + .enable_all() + .thread_name("opencode-mini") + .build()?; + let server = runtime.block_on(connect(context))?; + let argv: Vec = std::env::args().skip(1).collect(); + let input = Input { + client: server.client.clone(), + theme_directories: opencode_ui::theme::config_directories( + &paths.config, + std::path::Path::new(&directory), + ), + home: paths.home.clone(), + trace: Trace::from_env(&paths.log, &directory, &argv), + target: TargetInput { + directory: Some(directory.clone()), + continue_latest: args.continue_, + session: args.session.clone().map(SessionID), + fork: args.fork, + model, + agent: args.agent.clone(), + environment: server + .is_service() + .then(opencode_store::environment::session_environment), + }, + directory, + initial_input, + replay: args.replay().or(mini.replay).unwrap_or(true), + replay_limit: args + .replay_limit + .map(|limit| limit as u32) + .or(mini.replay_limit.map(|limit| limit.0 as u32)), + config, + version: crate::help::VERSION.to_owned(), + start, + }; + let _guard = runtime.enter(); + let result = opencode_mini::run(input); + drop(server); + match result { + Err(error) if error.downcast_ref::().is_some() => fail(&error.to_string()), + result => result, + } +} + +/// `fail`: the error in TS's colors on stderr, then exit 1. +fn fail(message: &str) -> anyhow::Result<()> { + eprintln!("\x1b[91m\x1b[1mError: \x1b[0m{message}"); + Err(Exit(1).into()) } diff --git a/packages/cli-rs/crates/mini/Cargo.toml b/packages/cli-rs/crates/mini/Cargo.toml index ee9d698c12e..e1b7fe5264b 100644 --- a/packages/cli-rs/crates/mini/Cargo.toml +++ b/packages/cli-rs/crates/mini/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "opencode-mini" -description = "mini (M.1)." +description = "mini: the split-footer interface (M.1 to M.4)." version.workspace = true edition.workspace = true license.workspace = true @@ -10,7 +10,21 @@ publish.workspace = true workspace = true [dependencies] +opentui.workspace = true +opencode-api.workspace = true opencode-ui.workspace = true opencode-store.workspace = true opencode-service.workspace = true opencode-local.workspace = true +anyhow.workspace = true +chrono.workspace = true +futures-util.workspace = true +indexmap.workspace = true +log.workspace = true +rustix = { workspace = true, features = ["stdio"] } +serde_json.workspace = true +tokio.workspace = true +unicode-width.workspace = true + +[dev-dependencies] +tempfile.workspace = true diff --git a/packages/cli-rs/crates/mini/src/footers/mod.rs b/packages/cli-rs/crates/mini/src/footers/mod.rs new file mode 100644 index 00000000000..36824306fea --- /dev/null +++ b/packages/cli-rs/crates/mini/src/footers/mod.rs @@ -0,0 +1,37 @@ +//! Footer views for requests (`footer.permission.tsx`, `footer.form.tsx`, `footer.subagent.tsx`, +//! `footer.menu.tsx`, `footer.command.tsx`): M.3. +//! +//! M.1 forwards the transcript's request and subagent events here; until M.3 the footer stays on the prompt. + +use serde_json::Value; + +/// Which view the footer shows (`FooterView`). +#[derive(Clone, Debug, Default, PartialEq)] +pub enum FooterView { + #[default] + Prompt, + Permission(Value), + Form(Value), +} + +/// The request and subagent state of the footer. +#[derive(Debug, Default)] +pub struct Footers { + view: FooterView, +} + +impl Footers { + /// One event the transcript did not draw: permissions, forms, tools of subagents, the queue. + pub fn event(&mut self, _event: &Value) -> Option { + None + } + + pub fn view(&self) -> &FooterView { + &self.view + } + + /// Footer rows the view needs beyond the prompt's, as `applyHeight` adds `PERMISSION_ROWS` and the others. + pub fn rows(&self) -> Option { + None + } +} diff --git a/packages/cli-rs/crates/mini/src/lib.rs b/packages/cli-rs/crates/mini/src/lib.rs index 1040a3b326c..d1340caaa3f 100644 --- a/packages/cli-rs/crates/mini/src/lib.rs +++ b/packages/cli-rs/crates/mini/src/lib.rs @@ -1 +1,69 @@ -//! `mini` (M.1). +//! `mini`: the minimal interactive interface (`packages/tui/src/mini`). The app lives in a footer at the bottom +//! of the main screen, and the session's transcript is written to the terminal's scrollback above it. +//! +//! M.1 owns the shell: the split-footer lifecycle (`shell`), the scrollback writer (`scrollback`), the +//! transcript and its replay (`replay`), the theme and monochrome output (`theme`), piped stdin (`stdin`), and +//! signals and traces (`signals`). The prompt (`prompt`, M.2), the request footers (`footers`, M.3), and the +//! tool output, settings, spinners, splash, and variants (M.4) fill the stubs M.1 leaves. + +use std::path::PathBuf; +use std::time::Instant; + +use opencode_api::client::Client; +use opencode_local::cli_config::Info; +use opencode_store::target::TargetInput; + +pub mod footers; +pub mod prompt; +pub mod replay; +pub mod scrollback; +pub mod settings; +pub mod shell; +pub mod signals; +pub mod spinners; +pub mod splash; +pub mod stdin; +pub mod theme; +pub mod tools; +pub mod variants; + +/// What `opencode mini` runs with (`MiniCommandInput` after the handler resolved it). +pub struct Input { + pub client: Client, + /// The logical working directory. + pub directory: String, + /// The home directory, shown as `~` in the entry header. + pub home: PathBuf, + /// Directories custom themes are read from. + pub theme_directories: Vec, + /// The session to open: `--continue`, `--session`, `--fork`, `--model`, `--agent`. + pub target: TargetInput, + /// Piped stdin and `--prompt`, sent as the first prompt. + pub initial_input: Option, + /// `--replay`, else `mini.replay`, else true. + pub replay: bool, + /// `--replay-limit`, else `mini.replay_limit`. + pub replay_limit: Option, + pub config: Info, + pub version: String, + pub trace: Option, + /// When the command started, for `OPENCODE_SHOW_TTFD`. + pub start: Instant, +} + +/// A failure mini reports as `Error: ` and exit code 1 (`MiniInputError`). +#[derive(Debug)] +pub struct InputError(pub String); + +impl std::fmt::Display for InputError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for InputError {} + +/// Runs mini until the user leaves. +pub fn run(input: Input) -> anyhow::Result<()> { + shell::run(input) +} diff --git a/packages/cli-rs/crates/mini/src/prompt/mod.rs b/packages/cli-rs/crates/mini/src/prompt/mod.rs new file mode 100644 index 00000000000..26acfcd63a5 --- /dev/null +++ b/packages/cli-rs/crates/mini/src/prompt/mod.rs @@ -0,0 +1,130 @@ +//! The footer prompt (`footer.prompt.tsx`, `runtime.queue.ts`): M.2. +//! +//! 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. + +use std::cell::RefCell; +use std::rc::Rc; + +use opentui::prelude::*; + +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; + +type Submit = Rc, RunPrompt)>>>>; + +/// The composer in the footer. +#[derive(Clone)] +pub struct Prompt { + root: View, + input: Input, + submit: Submit, + mono: bool, +} + +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, + mono, + }; + prompt.set_first(true); + prompt + } + + /// The widget to place in the footer. + pub fn root(&self) -> &View { + &self.root + } + + /// 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)); + } + + pub fn focus(&self) { + self.input.focus(); + } + + pub fn value(&self) -> String { + self.input.value() + } + + /// Clears the draft (`handleInputClear`). + pub fn clear(&self) { + self.input.set_value(""); + } + + /// Rows the composer needs (`onRows`). + pub fn rows(&self) -> u16 { + MIN_ROWS + } + + /// The session's earlier prompts, for history (`history` event). + pub fn set_history(&self, _history: Vec) {} + + pub fn set_theme(&self, _theme: &RunTheme) {} + + /// 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…" + } + } else { + "" + }; + self.input.placeholder(hint); + } +} + +/// Whether `text` is one of the exit words. +pub fn is_exit(text: &str) -> bool { + EXIT_WORDS.contains(&text.trim()) +} diff --git a/packages/cli-rs/crates/mini/src/replay.rs b/packages/cli-rs/crates/mini/src/replay.rs new file mode 100644 index 00000000000..0b5a0fedcbb --- /dev/null +++ b/packages/cli-rs/crates/mini/src/replay.rs @@ -0,0 +1,1257 @@ +//! The session transcript as scrollback commits (`stream-v2.transport.ts`, `stream-v2.fragment.ts`): hydration +//! from the message list, live events, and replay on resume and resize. +//! +//! [`Transcript`] is a plain state machine on the UI thread: it turns messages and events into [`Commit`]s and +//! remembers what it already showed, so a message that arrives both live and in a later list prints once. The +//! network side ([`connect`], [`messages`]) runs on tokio and posts what it reads to the UI thread. +//! +//! Tools, shells, subagents, permissions, and forms reach this module but are drawn by M.3 and M.4: tool parts go +//! through [`crate::tools::commits`], and requests through [`crate::footers`]. + +use std::collections::{HashMap, HashSet}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use futures_util::StreamExt; +use opencode_api::client::{Call, Client, RequestOptions}; +use opencode_api::generated::EventSubscribeInput; +use opencode_api::transport::SseResponse; +use opentui::app::ProxyError; +use opentui::prelude::*; +use serde_json::{Value, json}; + +use crate::scrollback::{Commit, EntryKind, Phase, Source}; + +/// `--replay-limit`'s default: the newest messages a replay lists. +pub const DEFAULT_REPLAY_LIMIT: u32 = 200; +/// `LOCAL_REPLAY_ROW_LIMIT`: rows printed only locally (errors, prompts in flight) that a resize replays. +pub const LOCAL_ROW_LIMIT: usize = 100; +/// `RESIZE_DELAY`. +pub const RESIZE_DELAY: Duration = Duration::from_millis(250); + +/// A part of a message whose text arrives in pieces (`FragmentRef`). +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct Fragment { + pub message_id: String, + pub part_id: String, +} + +impl Fragment { + /// `fragmentRef`. + pub fn new(message_id: &str, kind: &str, ordinal: u64) -> Self { + Self { + message_id: message_id.to_owned(), + part_id: format!("{kind}:{ordinal}"), + } + } +} + +#[derive(Clone, Debug, Default)] +struct FragmentState { + text: String, + /// Text a list already showed that a live delta may repeat. + projected: Option, +} + +/// What a fragment held before an update. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Update { + pub previous: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Restore { + Append(String), + Covered, + Conflict, +} + +/// `createFragmentReconciler`. +#[derive(Clone, Debug, Default)] +pub struct Fragments(HashMap); + +impl Fragments { + pub fn clear(&mut self) { + self.0.clear(); + } + + pub fn value(&self, fragment: &Fragment) -> Option<&str> { + self.0.get(fragment).map(|state| state.text.as_str()) + } + + /// The fragment's whole text from a list; `visible` when it was shown. + pub fn project(&mut self, fragment: &Fragment, text: &str, visible: bool) -> Update { + let current = self.0.remove(fragment).unwrap_or_default(); + self.0.insert( + fragment.clone(), + FragmentState { + text: text.to_owned(), + projected: if visible { + Some(text.to_owned()) + } else { + current.projected + }, + }, + ); + Update { + previous: current.text, + } + } + + /// A live delta; `None` when a list already showed it. + pub fn delta(&mut self, fragment: &Fragment, delta: &str) -> Option { + let state = self.0.entry(fragment.clone()).or_default(); + // Replay may start after an unseen prefix, so a covered chunk is consumed from anywhere in the projection. + if let Some(projected) = &state.projected + && let Some(at) = projected.find(delta) + { + state.projected = Some(projected[at + delta.len()..].to_owned()); + return None; + } + let previous = state.text.clone(); + state.text.push_str(delta); + Some(Update { previous }) + } + + /// The final text of a fragment. + pub fn end(&mut self, fragment: &Fragment, text: &str) -> Update { + let previous = self + .0 + .insert( + fragment.clone(), + FragmentState { + text: text.to_owned(), + projected: None, + }, + ) + .map(|state| state.text) + .unwrap_or_default(); + Update { previous } + } + + /// A locally printed text, replayed after the list (`restore`). + pub fn restore(&mut self, fragment: &Fragment, text: &str) -> Restore { + let Some(current) = self.0.get(fragment) else { + self.0.insert( + fragment.clone(), + FragmentState { + text: text.to_owned(), + projected: Some(text.to_owned()), + }, + ); + return Restore::Append(text.to_owned()); + }; + if let Some(suffix) = text.strip_prefix(current.text.as_str()) { + let suffix = suffix.to_owned(); + self.0.insert( + fragment.clone(), + FragmentState { + text: text.to_owned(), + projected: Some(text.to_owned()), + }, + ); + return Restore::Append(suffix); + } + if current.text.starts_with(text) { + return Restore::Covered; + } + Restore::Conflict + } +} + +/// A change to the footer's status (`FooterPatch`), as the transcript reports it. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Patch { + pub running: Option, + pub status: Option, + pub usage: Option>, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Usage { + pub tokens: u64, + pub percent: Option, + pub cost: Option, +} + +/// What one message or event produced. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Output { + pub commits: Vec, + pub patch: Option, + /// `session.renamed`. + pub title: Option, + /// Events for the footer views of M.3 (permissions, forms, subagents, the queue). + pub footer: Vec, +} + +impl Output { + fn commits(commits: Vec) -> Self { + Self { + commits, + ..Self::default() + } + } + + fn patch(running: bool, status: &str) -> Self { + Self { + patch: Some(Patch { + running: Some(running), + status: Some(status.to_owned()), + usage: None, + }), + ..Self::default() + } + } + + pub fn extend(&mut self, other: Output) { + self.commits.extend(other.commits); + if other.patch.is_some() { + self.patch = other.patch; + } + if other.title.is_some() { + self.title = other.title; + } + self.footer.extend(other.footer); + } +} + +/// A prompt admitted to the inbox but not yet delivered. +#[derive(Clone, Debug, PartialEq)] +struct Pending { + text: String, +} + +/// The transcript of one session (the state of `createSessionTransport`). +#[derive(Debug)] +pub struct Transcript { + pub session_id: String, + pub thinking: bool, + pub tools: bool, + pub replay: bool, + pub replay_limit: u32, + /// The first hydration has not happened yet; its rows are not remembered locally. + pub initial: bool, + pub connected: bool, + pub root_active: bool, + message_ids: HashSet, + errors: HashSet, + fragments: Fragments, + pending: HashMap, + promoted: HashSet, + /// Events that arrive while a resize replay lists the messages again. + buffered: Option>, + /// Rows printed only locally, newest last (`localRows`). + local: Vec, + /// With tools hidden, a message's text waits for its step to end, and is dropped when the message turns out + /// to call tools (`quietText`, `toolMessages`). + quiet: Vec<(String, Vec<(String, String)>)>, + tool_messages: HashSet, +} + +impl Transcript { + pub fn new( + session_id: &str, + thinking: bool, + tools: bool, + replay: bool, + replay_limit: Option, + ) -> Self { + Self { + session_id: session_id.to_owned(), + thinking, + tools, + replay, + replay_limit: replay_limit.unwrap_or(DEFAULT_REPLAY_LIMIT), + initial: true, + connected: false, + root_active: false, + message_ids: HashSet::new(), + errors: HashSet::new(), + fragments: Fragments::default(), + pending: HashMap::new(), + promoted: HashSet::new(), + buffered: None, + local: Vec::new(), + quiet: Vec::new(), + tool_messages: HashSet::new(), + } + } + + /// The first or a reconnecting hydration (`hydrate`): every listed message, shown unless this is the first + /// hydration and replay is off. + pub fn hydrate(&mut self, messages: &[Value], active: bool) -> Output { + let render = !self.initial || self.replay; + let mut output = Output::default(); + for message in messages { + output.extend(self.message(message, render)); + } + self.root_active = active; + self.initial = false; + self.connected = true; + output.patch = Some(Patch { + running: Some(active), + status: Some(if active { "assistant responding" } else { "" }.to_owned()), + usage: None, + }); + output + } + + /// Starts a resize replay: events wait until [`Self::replayed`]. + pub fn begin_replay(&mut self) { + self.buffered.get_or_insert_with(Vec::new); + } + + pub fn replaying(&self) -> bool { + self.buffered.is_some() + } + + /// Ends a resize replay (`performResizeReplay`) after the terminal was cleared: the listed messages, then the + /// rows only this client printed, then the events that waited. + pub fn replayed(&mut self, messages: &[Value], active: bool) -> Output { + let buffered = self.buffered.take().unwrap_or_default(); + self.message_ids.clear(); + self.errors.clear(); + self.fragments.clear(); + let mut output = Output::default(); + let local = std::mem::take(&mut self.local); + output.extend(self.hydrate(messages, active)); + let mut restored = Vec::new(); + for commit in &local { + if let Some(commit) = self.restore(commit) { + restored.push(commit); + } + } + output.commits.extend(restored); + self.local = local; + for event in &buffered { + output.extend(self.event(event)); + } + output + } + + /// Ends a resize replay that could not list the messages: nothing was cleared, so only the events that waited + /// apply. + pub fn abort_replay(&mut self) -> Output { + let mut output = Output::default(); + for event in self.buffered.take().unwrap_or_default() { + output.extend(self.event(&event)); + } + output + } + + fn restore(&mut self, commit: &Commit) -> Option { + if let (Some(message), Some(part), EntryKind::Assistant | EntryKind::Reasoning) = + (&commit.message_id, &commit.part_id, commit.kind) + { + let prefix = if commit.kind == EntryKind::Reasoning { + "Thinking: " + } else { + "" + }; + let text = commit.text.strip_prefix(prefix).unwrap_or(&commit.text); + let fragment = Fragment { + message_id: message.clone(), + part_id: part.clone(), + }; + return match self.fragments.restore(&fragment, text) { + Restore::Covered => None, + Restore::Append(suffix) if suffix.is_empty() => None, + Restore::Append(suffix) if suffix == text => Some(commit.clone()), + Restore::Append(suffix) => Some(Commit { + text: suffix, + ..commit.clone() + }), + Restore::Conflict => Some(commit.clone()), + }; + } + if commit.kind == EntryKind::Error + && let Some(message) = &commit.message_id + { + return self.errors.insert(message.clone()).then(|| commit.clone()); + } + if commit + .message_id + .as_ref() + .is_some_and(|message| self.message_ids.contains(message)) + { + return None; + } + Some(commit.clone()) + } + + /// Remembers rows this client printed itself, for a resize replay (`rememberLocal`). + pub fn remember(&mut self, commit: &Commit) { + let joins = self.local.last().is_some_and(|last| { + matches!(commit.kind, EntryKind::Assistant | EntryKind::Reasoning) + && last.kind == commit.kind + && last.source == commit.source + && last.message_id == commit.message_id + && last.part_id == commit.part_id + && last.tool == commit.tool + }); + if joins { + self.local.pop(); + } + self.local.push(commit.clone()); + let excess = self.local.len().saturating_sub(LOCAL_ROW_LIMIT); + self.local.drain(..excess); + } + + /// Commits of a live event remembered as local rows: streamed text is remembered whole. + fn remember_all(&mut self, commits: &[Commit]) { + if self.initial || self.buffered.is_some() { + return; + } + for commit in commits { + let whole = match (&commit.message_id, &commit.part_id, commit.kind) { + (Some(message), Some(part), EntryKind::Assistant | EntryKind::Reasoning) => self + .fragments + .value(&Fragment { + message_id: message.clone(), + part_id: part.clone(), + }) + .map(|text| match commit.kind { + EntryKind::Reasoning if !text.is_empty() => format!("Thinking: {text}"), + _ => text.to_owned(), + }), + _ => None, + }; + let commit = match whole { + Some(text) => Commit { + text, + ..commit.clone() + }, + None => commit.clone(), + }; + self.remember(&commit); + } + } + + /// A prompt this client admitted (`mergePending`). It prints once the server delivers it. + pub fn admitted(&mut self, message_id: &str, text: &str) -> Output { + if self.promoted.contains(message_id) { + return self.user(message_id, text, true); + } + self.pending.insert( + message_id.to_owned(), + Pending { + text: text.to_owned(), + }, + ); + Output::default() + } + + fn user(&mut self, message_id: &str, text: &str, render: bool) -> Output { + let visible = !self.message_ids.insert(message_id.to_owned()); + if !render || visible || text.trim().is_empty() { + return Output::default(); + } + let commit = + Commit::new(EntryKind::User, Source::System, Phase::Start, text).message(message_id); + Output::commits(vec![commit]) + } + + /// `rememberToolMessage`: a message that calls tools shows no text while tools are hidden. + fn remember_tool_message(&mut self, message: &str) { + self.tool_messages.insert(message.to_owned()); + self.quiet.retain(|(id, _)| id != message); + } + + /// `bufferQuietText`. + fn buffer_quiet(&mut self, message: &str, part: &str, text: &str, replace: bool) { + if text.is_empty() || self.tool_messages.contains(message) { + return; + } + let parts = match self.quiet.iter_mut().find(|(id, _)| id == message) { + Some((_, parts)) => parts, + None => { + self.quiet.push((message.to_owned(), Vec::new())); + &mut self.quiet.last_mut().expect("just pushed").1 + } + }; + match parts.iter_mut().find(|(id, _)| id == part) { + Some((_, current)) if replace => *current = text.to_owned(), + Some((_, current)) => current.push_str(text), + None => parts.push((part.to_owned(), text.to_owned())), + } + } + + /// `flushQuietText`: the buffered text of a message whose step ended. + fn flush_quiet(&mut self, message: &str) -> Vec { + let Some(index) = self.quiet.iter().position(|(id, _)| id == message) else { + return Vec::new(); + }; + let (_, parts) = self.quiet.remove(index); + if self.tool_messages.contains(message) { + return Vec::new(); + } + parts + .into_iter() + .filter(|(_, text)| !text.is_empty()) + .map(|(part, text)| { + Commit::new( + EntryKind::Assistant, + Source::Assistant, + Phase::Progress, + text, + ) + .message(message) + .part_id(part) + }) + .collect() + } + + /// `renderMessage`: one message of a list. + pub fn message(&mut self, message: &Value, render: bool) -> Output { + let id = message["id"].as_str().unwrap_or_default(); + match message["type"].as_str() { + Some("user") => { + self.pending.remove(id); + self.promoted.insert(id.to_owned()); + self.user(id, message["text"].as_str().unwrap_or_default(), render) + } + Some("compaction") => self.compaction(message, render), + Some("assistant") => self.assistant(message, render), + // Skills and shells are drawn by M.4. + _ => Output::default(), + } + } + + fn compaction(&mut self, message: &Value, render: bool) -> Output { + let id = message["id"].as_str().unwrap_or_default(); + if !self.message_ids.insert(id.to_owned()) { + return Output::default(); + } + let status = message["status"].as_str().unwrap_or_default(); + let header = || { + let mut commit = Commit::new( + EntryKind::System, + Source::System, + Phase::Start, + "Compaction", + ) + .message(id) + .part_id("compaction:header"); + commit.compaction = true; + commit + }; + if status == "failed" { + if !render || message["error"]["type"] == "aborted" { + return Output::default(); + } + let error = Commit::error(message["error"]["message"].as_str().unwrap_or_default()) + .message(id) + .part_id("compaction:error"); + return Output::commits(vec![header(), error]); + } + let summary = message["summary"].as_str().unwrap_or_default(); + let show = render || status == "running"; + let fragment = Fragment { + message_id: id.to_owned(), + part_id: "compaction:summary".into(), + }; + self.fragments.project(&fragment, summary, show); + if !show { + return Output::default(); + } + let part = |text: &str, phase| { + Commit::new(EntryKind::Assistant, Source::Assistant, phase, text) + .message(id) + .part_id("compaction:summary") + }; + let mut commits = vec![header()]; + if !summary.is_empty() { + commits.push(part(summary, Phase::Progress)); + } + if status == "completed" { + commits.push(part("", Phase::Final)); + } + Output::commits(commits) + } + + fn assistant(&mut self, message: &Value, render: bool) -> Output { + let id = message["id"].as_str().unwrap_or_default(); + self.message_ids.insert(id.to_owned()); + let content = message["content"] + .as_array() + .map(Vec::as_slice) + .unwrap_or_default(); + let has_tools = content.iter().any(|item| item["type"] == "tool"); + if has_tools && !self.tools { + self.remember_tool_message(id); + } + let mut commits = Vec::new(); + let (mut text_ordinal, mut reasoning_ordinal) = (0, 0); + for item in content { + let text = item["text"].as_str().unwrap_or_default(); + match item["type"].as_str() { + Some("text") => { + let fragment = Fragment::new(id, "text", text_ordinal); + text_ordinal += 1; + let visible = render && (self.tools || !has_tools); + let update = self.fragments.project(&fragment, text, visible); + if visible && text.len() > update.previous.len() { + commits.push(text_commit(&fragment, suffix(text, &update.previous))); + } + } + Some("reasoning") => { + let fragment = Fragment::new(id, "reasoning", reasoning_ordinal); + reasoning_ordinal += 1; + let update = self.fragments.project(&fragment, text, render); + if render && self.thinking && text.len() > update.previous.len() { + let delta = if update.previous.is_empty() { + format!("Thinking: {text}") + } else { + suffix(text, &update.previous).to_owned() + }; + commits.push(reasoning_commit(&fragment, delta)); + } + } + Some("tool") if render && self.tools => { + commits.extend(crate::tools::commits(id, item)); + } + _ => {} + } + } + if let Some(error) = message.get("error").filter(|error| !error.is_null()) + && self.errors.insert(id.to_owned()) + && render + { + commits.push(Commit::error(error_message(error)).message(id)); + } + Output::commits(commits) + } + + /// `apply`: one live event of this session. Events of other sessions are ignored here (subagents are M.3's). + pub fn event(&mut self, event: &Value) -> Output { + if let Some(buffered) = &mut self.buffered { + buffered.push(event.clone()); + return Output::default(); + } + let data = &event["data"]; + let kind = event["type"].as_str().unwrap_or_default(); + let session = match kind { + "form.created" => data["form"]["sessionID"].as_str(), + _ => data["sessionID"].as_str(), + }; + if session != Some(self.session_id.as_str()) { + return Output::default(); + } + let output = self.apply(kind, event, data); + self.remember_all(&output.commits); + output + } + + fn apply(&mut self, kind: &str, event: &Value, data: &Value) -> Output { + let message = data["assistantMessageID"].as_str().unwrap_or_default(); + let ordinal = data["ordinal"].as_u64().unwrap_or_default(); + match kind { + "session.renamed" => Output { + title: data["title"].as_str().map(str::to_owned), + ..Output::default() + }, + "session.inbox.enqueued" => { + if data["item"]["type"] != "user" { + return Output::default(); + } + let id = data["inboxID"].as_str().unwrap_or_default(); + let text = data["item"]["payload"]["text"].as_str().unwrap_or_default(); + let mut output = self.admitted(id, text); + output.footer.push(event.clone()); + output + } + "session.inbox.delivered" => { + let id = data["inboxID"].as_str().unwrap_or_default(); + self.promoted.insert(id.to_owned()); + let mut output = match self.pending.remove(id) { + Some(pending) => self.user(id, &pending.text, true), + None => Output::default(), + }; + output.extend(Output::patch(true, "waiting for assistant")); + output.footer.push(event.clone()); + output + } + "session.inbox.cancelled" => { + self.pending + .remove(data["inboxID"].as_str().unwrap_or_default()); + Output { + footer: vec![event.clone()], + ..Output::default() + } + } + "session.step.started" => Output::patch(true, "assistant responding"), + "session.text.delta" => { + let fragment = Fragment::new(message, "text", ordinal); + let delta = data["delta"].as_str().unwrap_or_default(); + if self.fragments.delta(&fragment, delta).is_none() { + return Output::default(); + } + if !self.tools { + self.buffer_quiet(message, &fragment.part_id, delta, false); + return Output::default(); + } + Output::commits(vec![text_commit(&fragment, delta)]) + } + "session.text.ended" => { + let fragment = Fragment::new(message, "text", ordinal); + let text = data["text"].as_str().unwrap_or_default(); + let update = self.fragments.end(&fragment, text); + if !self.tools { + self.buffer_quiet(message, &fragment.part_id, text, true); + return Output::default(); + } + if text.len() <= update.previous.len() { + return Output::default(); + } + Output::commits(vec![text_commit(&fragment, suffix(text, &update.previous))]) + } + "session.reasoning.delta" => { + let fragment = Fragment::new(message, "reasoning", ordinal); + let delta = data["delta"].as_str().unwrap_or_default(); + match self.fragments.delta(&fragment, delta) { + Some(update) if self.thinking => { + let text = if update.previous.is_empty() { + format!("Thinking: {delta}") + } else { + delta.to_owned() + }; + Output::commits(vec![reasoning_commit(&fragment, text)]) + } + _ => Output::default(), + } + } + "session.reasoning.ended" => { + let fragment = Fragment::new(message, "reasoning", ordinal); + let text = data["text"].as_str().unwrap_or_default(); + let update = self.fragments.end(&fragment, text); + if !self.thinking || text.len() <= update.previous.len() { + return Output::default(); + } + let text = if update.previous.is_empty() { + format!("Thinking: {text}") + } else { + suffix(text, &update.previous).to_owned() + }; + Output::commits(vec![reasoning_commit(&fragment, text)]) + } + "session.step.ended" => { + let tokens = &data["tokens"]; + let count = |value: &Value| value.as_u64().unwrap_or_default(); + let total = count(&tokens["input"]) + + count(&tokens["output"]) + + count(&tokens["reasoning"]) + + count(&tokens["cache"]["read"]) + + count(&tokens["cache"]["write"]); + let cost = data["cost"].as_f64().filter(|cost| *cost != 0.0); + let quiet = self.flush_quiet(message); + Output { + commits: quiet, + patch: Some(Patch { + usage: Some((total > 0 || cost.is_some()).then_some(Usage { + tokens: total, + percent: None, + cost, + })), + ..Patch::default() + }), + ..Output::default() + } + } + "session.step.failed" => { + let mut commits = self.flush_quiet(message); + if self.errors.insert(message.to_owned()) { + commits.push(Commit::error(error_message(&data["error"])).message(message)); + } + Output::commits(commits) + } + "session.execution.started" => { + self.root_active = true; + Output { + patch: Some(Patch { + running: Some(true), + ..Patch::default() + }), + ..Output::default() + } + } + "session.execution.succeeded" + | "session.execution.failed" + | "session.execution.interrupted" => { + self.root_active = false; + let messages: Vec = self.quiet.iter().map(|(id, _)| id.clone()).collect(); + let commits = messages + .iter() + .flat_map(|id| self.flush_quiet(id)) + .collect(); + Output { + commits, + ..Output::patch(false, "") + } + } + kind if kind.starts_with("session.tool.") && !self.tools => { + self.remember_tool_message(message); + Output { + footer: vec![event.clone()], + ..Output::default() + } + } + kind if kind.starts_with("session.tool.") + || kind.starts_with("session.shell.") + || kind.starts_with("session.compaction.") + || kind.starts_with("permission.") + || kind.starts_with("form.") => + { + Output { + footer: vec![event.clone()], + ..Output::default() + } + } + _ => Output::default(), + } + } +} + +/// `text.slice(previous.length)`, by byte, on a character boundary. +fn suffix<'a>(text: &'a str, previous: &str) -> &'a str { + text.get(previous.len()..).unwrap_or_default() +} + +fn text_commit(fragment: &Fragment, text: impl Into) -> Commit { + Commit::new( + EntryKind::Assistant, + Source::Assistant, + Phase::Progress, + text, + ) + .message(&fragment.message_id) + .part_id(&fragment.part_id) +} + +fn reasoning_commit(fragment: &Fragment, text: impl Into) -> Commit { + Commit::new( + EntryKind::Reasoning, + Source::Reasoning, + Phase::Progress, + text, + ) + .message(&fragment.message_id) + .part_id(&fragment.part_id) +} + +/// `errorMessage`: the message, else the tag. +fn error_message(error: &Value) -> String { + [&error["message"], &error["_tag"]] + .into_iter() + .filter_map(Value::as_str) + .find(|text| !text.is_empty()) + .unwrap_or("Session execution failed") + .to_owned() +} + +/// What the network side posts to the UI thread. +pub enum Incoming { + /// The stream (re)connected and the messages were listed. + Hydrated { + messages: Vec, + active: bool, + }, + Event(Value), + /// The stream dropped; it reconnects. + Disconnected(String), +} + +/// `projectedMessages`: the newest `limit` messages, oldest first. +pub async fn messages(client: &Client, session: &str, limit: u32) -> Result, String> { + let mut call = Call::new( + "GET", + format!("/api/session/{}/message", encode(session)), + 200, + &[400, 401, 404, 500], + ); + call.query("limit", &limit) + .map_err(|error| error.to_string())?; + call.query("order", "desc") + .map_err(|error| error.to_string())?; + let list: Value = client + .json(call, &RequestOptions::default()) + .await + .map_err(|error| error.to_string())?; + let mut data = list["data"].as_array().cloned().unwrap_or_default(); + data.reverse(); + Ok(data) +} + +/// Whether the session is running (`session.active`). +pub async fn active(client: &Client, session: &str) -> bool { + let call = Call::new("GET", "/api/session/active".to_owned(), 200, &[400, 401]); + client + .json::(call, &RequestOptions::default()) + .await + .is_ok_and(|active| active["data"].get(session).is_some()) +} + +/// Lists the messages and whether the session runs, as a hydration does. +pub async fn hydration( + client: &Client, + session: &str, + limit: u32, +) -> Result<(Vec, bool), String> { + let messages = messages(client, session, limit).await?; + Ok((messages, active(client, session).await)) +} + +/// A path segment, encoded as the generated client encodes one. +pub fn encode(segment: &str) -> String { + opencode_api::client::path_param(segment).unwrap_or_else(|_| segment.to_owned()) +} + +/// `connect`: subscribes, hydrates after `server.connected`, then forwards events, reconnecting after 250 ms +/// when the stream drops. Runs until `proxy` closes. +pub async fn connect(client: Client, session: String, limit: u32, proxy: AppProxy) { + loop { + let error = match stream(&client, &session, limit, &proxy).await { + Ok(()) => return, + Err(error) => error, + }; + if !post(&proxy, Incoming::Disconnected(error)).await { + return; + } + tokio::time::sleep(Duration::from_millis(250)).await; + } +} + +/// One connection. `Ok` means the app is gone. +async fn stream( + client: &Client, + session: &str, + limit: u32, + proxy: &AppProxy, +) -> Result<(), String> { + let response = client + .event_subscribe(&EventSubscribeInput::default(), &RequestOptions::default()) + .await + .map_err(|error| error.to_string())?; + let mut events = Box::pin(SseResponse::::new(response.response).events(|| {})); + match events.next().await { + Some(Ok(first)) if first["type"] == "server.connected" => {} + _ => return Err("Event stream disconnected".into()), + } + // Events that arrive meanwhile wait in the stream, so they reach the UI after the hydration. + let (messages, active) = hydration(client, session, limit).await?; + if !post(proxy, Incoming::Hydrated { messages, active }).await { + return Ok(()); + } + while let Some(event) = events.next().await { + let event = event.map_err(|error| error.to_string())?; + if !post(proxy, Incoming::Event(event)).await { + return Ok(()); + } + } + Err("Event stream disconnected".into()) +} + +/// An [`Incoming`] on its way to the UI thread. A full queue drops the envelope but not the message, which the +/// sender still holds and posts again. +#[derive(Clone)] +pub struct Envelope(Arc>>); + +impl Envelope { + pub fn take(&self) -> Option { + self.0.lock().ok()?.take() + } +} + +/// Posts to the UI thread, waiting while its queue is full. False once the app has ended. +pub async fn post(proxy: &AppProxy, incoming: Incoming) -> bool { + let envelope = Envelope(Arc::new(Mutex::new(Some(incoming)))); + loop { + match proxy.send(envelope.clone()) { + Ok(()) => return true, + Err(ProxyError::Full) => tokio::time::sleep(Duration::from_millis(5)).await, + Err(_) => return false, + } + } +} + +/// `session.prompt` with `delivery: "steer"` after switching the agent and model (`runPromptTurn`). Returns the +/// admitted inbox item's text. +pub async fn prompt( + client: &Client, + session: &str, + id: &str, + text: &str, + agent: Option<&str>, + model: Option<&Value>, +) -> Result<(), String> { + let error = |error: opencode_api::error::Error| error.to_string(); + if let Some(agent) = agent { + let mut call = Call::new( + "POST", + format!("/api/session/{}/agent", encode(session)), + 204, + &[400, 401, 404], + ); + call.json(&json!({ "agent": agent })).map_err(error)?; + client + .empty(call, &RequestOptions::default()) + .await + .map_err(error)?; + } + if let Some(model) = model { + let mut call = Call::new( + "POST", + format!("/api/session/{}/model", encode(session)), + 204, + &[400, 401, 404], + ); + call.json(&json!({ "model": model })).map_err(error)?; + client + .empty(call, &RequestOptions::default()) + .await + .map_err(error)?; + } + let mut call = Call::new( + "POST", + format!("/api/session/{}/prompt", encode(session)), + 200, + &[400, 401, 404, 409], + ); + call.json(&json!({ "id": id, "text": text, "delivery": "steer" })) + .map_err(error)?; + client + .json::(call, &RequestOptions::default()) + .await + .map_err(error)?; + Ok(()) +} + +/// `model.default` at `directory`: the model a session without one uses, as `(providerID, id)`. +pub async fn default_model(client: &Client, directory: &str) -> Option<(String, String)> { + let mut call = Call::new( + "GET", + "/api/model/default".to_owned(), + 200, + &[400, 401, 404, 503], + ); + call.query("location", &json!({ "directory": directory })) + .ok()?; + let value: Value = client.json(call, &RequestOptions::default()).await.ok()?; + let data = &value["data"]; + Some(( + data["providerID"].as_str()?.to_owned(), + data["id"].as_str()?.to_owned(), + )) +} + +/// `experimental.session.wait`: returns once the session is idle. +pub async fn wait(client: &Client, session: &str) -> Result<(), String> { + let call = Call::new( + "POST", + format!("/api/experimental/session/{}/wait", encode(session)), + 204, + &[400, 401, 404], + ); + client + .empty(call, &RequestOptions::default()) + .await + .map_err(|error| error.to_string()) +} + +/// `session.interrupt` with `resume: true`. +pub async fn interrupt(client: &Client, session: &str) -> Result<(), String> { + let mut call = Call::new( + "POST", + format!("/api/session/{}/interrupt", encode(session)), + 204, + &[400, 401, 404], + ); + call.json(&json!({ "resume": true })) + .map_err(|error| error.to_string())?; + client + .empty(call, &RequestOptions::default()) + .await + .map_err(|error| error.to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn texts(output: &Output) -> Vec<(EntryKind, String)> { + output + .commits + .iter() + .map(|commit| (commit.kind, commit.text.clone())) + .collect() + } + + fn history() -> Vec { + vec![ + json!({ "id": "msg_u1", "type": "user", "text": "first" }), + json!({ "id": "msg_a1", "type": "assistant", "content": [ + { "type": "reasoning", "text": "hmm" }, + { "type": "text", "text": "answer" }, + ] }), + json!({ "id": "msg_a2", "type": "assistant", "content": [], "error": { "_tag": "Boom" } }), + ] + } + + #[test] + fn hydration_renders_history_only_with_replay() { + let mut quiet = Transcript::new("ses_1", true, true, false, None); + assert!(quiet.hydrate(&history(), false).commits.is_empty()); + let mut shown = Transcript::new("ses_1", true, true, true, None); + assert_eq!( + texts(&shown.hydrate(&history(), false)), + [ + (EntryKind::User, "first".into()), + (EntryKind::Reasoning, "Thinking: hmm".into()), + (EntryKind::Assistant, "answer".into()), + (EntryKind::Error, "Boom".into()), + ] + ); + // A later list prints nothing twice. + assert!(shown.hydrate(&history(), false).commits.is_empty()); + let mut hidden = Transcript::new("ses_1", false, true, true, None); + assert_eq!(hidden.hydrate(&history(), false).commits.len(), 3); + } + + #[test] + fn live_deltas_after_a_list_print_only_what_is_new() { + let mut transcript = Transcript::new("ses_1", true, true, true, None); + transcript.hydrate(&[json!({ "id": "msg_a", "type": "assistant", "content": [{ "type": "text", "text": "Hello" }] })], true); + let delta = |text: &str| { + json!({ "type": "session.text.delta", "data": { + "sessionID": "ses_1", "assistantMessageID": "msg_a", "ordinal": 0, "delta": text } }) + }; + assert!(transcript.event(&delta("Hel")).commits.is_empty()); + assert!(transcript.event(&delta("lo")).commits.is_empty()); + assert_eq!( + texts(&transcript.event(&delta(" world"))), + [(EntryKind::Assistant, " world".into())] + ); + let ended = json!({ "type": "session.text.ended", "data": { + "sessionID": "ses_1", "assistantMessageID": "msg_a", "ordinal": 0, "text": "Hello world!" } }); + assert_eq!( + texts(&transcript.event(&ended)), + [(EntryKind::Assistant, "!".into())] + ); + let other = json!({ "type": "session.text.delta", "data": { + "sessionID": "ses_2", "assistantMessageID": "msg_b", "ordinal": 0, "delta": "x" } }); + assert!(transcript.event(&other).commits.is_empty()); + } + + #[test] + fn with_tools_hidden_text_waits_for_its_step_and_tool_messages_stay_quiet() { + let mut transcript = Transcript::new("ses_1", true, false, true, None); + transcript.hydrate(&[], true); + let event = |kind: &str, data: Value| { + let mut data = data; + data["sessionID"] = json!("ses_1"); + json!({ "type": kind, "data": data }) + }; + let delta = |message: &str, text: &str| { + event( + "session.text.delta", + json!({ "assistantMessageID": message, "ordinal": 0, "delta": text }), + ) + }; + assert!( + transcript + .event(&delta("msg_a", "Hello")) + .commits + .is_empty() + ); + assert!( + transcript + .event(&delta("msg_a", " there")) + .commits + .is_empty() + ); + let ended = event( + "session.step.ended", + json!({ "assistantMessageID": "msg_a", "tokens": {} }), + ); + assert_eq!( + texts(&transcript.event(&ended)), + [(EntryKind::Assistant, "Hello there".into())] + ); + assert!( + transcript + .event(&delta("msg_b", "Let me look")) + .commits + .is_empty() + ); + let tool = event( + "session.tool.called", + json!({ "assistantMessageID": "msg_b", "id": "call_1" }), + ); + assert!(transcript.event(&tool).commits.is_empty()); + let done = event("session.execution.succeeded", json!({})); + assert!(transcript.event(&done).commits.is_empty()); + } + + #[test] + fn an_admitted_prompt_prints_when_delivered() { + let mut transcript = Transcript::new("ses_1", true, true, true, None); + transcript.hydrate(&[], false); + assert!(transcript.admitted("msg_p", "hi").commits.is_empty()); + let delivered = json!({ "type": "session.inbox.delivered", "data": { "sessionID": "ses_1", "inboxID": "msg_p" } }); + let output = transcript.event(&delivered); + assert_eq!(texts(&output), [(EntryKind::User, "hi".into())]); + assert_eq!( + output.patch.unwrap().status.as_deref(), + Some("waiting for assistant") + ); + // The listed user message does not print it again. + let listed = json!({ "id": "msg_p", "type": "user", "text": "hi" }); + assert!(transcript.message(&listed, true).commits.is_empty()); + } + + #[test] + fn a_resize_replay_lists_again_then_restores_local_rows_and_waiting_events() { + let mut transcript = Transcript::new("ses_1", true, true, true, None); + transcript.hydrate(&history(), false); + // A live answer the list does not have yet, and a local error. + let delta = json!({ "type": "session.text.delta", "data": { + "sessionID": "ses_1", "assistantMessageID": "msg_live", "ordinal": 0, "delta": "streamed" } }); + transcript.event(&delta); + transcript.remember(&Commit::error("send failed").message("msg_local")); + transcript.begin_replay(); + let late = json!({ "type": "session.text.delta", "data": { + "sessionID": "ses_1", "assistantMessageID": "msg_live", "ordinal": 0, "delta": " more" } }); + assert!(transcript.event(&late).commits.is_empty()); + let output = transcript.replayed(&history(), false); + assert_eq!( + texts(&output), + [ + (EntryKind::User, "first".into()), + (EntryKind::Reasoning, "Thinking: hmm".into()), + (EntryKind::Assistant, "answer".into()), + (EntryKind::Error, "Boom".into()), + (EntryKind::Assistant, "streamed".into()), + (EntryKind::Error, "send failed".into()), + (EntryKind::Assistant, " more".into()), + ] + ); + assert!(!transcript.replaying()); + } + + #[test] + fn fragments_match_the_reconciler() { + let mut fragments = Fragments::default(); + let part = Fragment::new("msg", "text", 0); + assert_eq!(fragments.project(&part, "abc", true).previous, ""); + assert_eq!(fragments.delta(&part, "b"), None); + assert_eq!(fragments.delta(&part, "c"), None); + assert_eq!(fragments.delta(&part, "d").unwrap().previous, "abc"); + assert_eq!(fragments.restore(&part, "ab"), Restore::Covered); + assert_eq!( + fragments.restore(&part, "abcdef"), + Restore::Append("ef".into()) + ); + assert_eq!(fragments.restore(&part, "xyz"), Restore::Conflict); + assert_eq!(fragments.end(&part, "final").previous, "abcdef"); + } +} diff --git a/packages/cli-rs/crates/mini/src/scrollback.rs b/packages/cli-rs/crates/mini/src/scrollback.rs new file mode 100644 index 00000000000..03c7961fa72 --- /dev/null +++ b/packages/cli-rs/crates/mini/src/scrollback.rs @@ -0,0 +1,981 @@ +//! The scrollback writer (`scrollback.writer.tsx`, `scrollback.surface.ts`, `entry.body.ts`, +//! `scrollback.shared.ts`): turns stream commits into rows above the split footer. +//! +//! Finished entries are painted once into a snapshot. Entries that stream (assistant text, reasoning, running +//! tools) live on a surface whose settled rows are committed as they arrive, so the terminal's scrollback grows +//! with the text and nothing written is ever rewritten. + +use opentui::prelude::*; +use opentui::split::{Scrollback, ScrollbackSurface, SnapshotOptions, SplitFooter, SplitSnapshot}; +use opentui::syntax::SyntaxTheme; +use opentui::widget::{ + ColumnWidthMode, Markdown, MarkdownColors, MarkdownTableOptions, MarkdownTableStyle, +}; +use serde_json::Value; + +use crate::theme::{RunTheme, mono_snapshot, mono_text}; +use crate::tools; + +/// The semantic role of an entry; each has its own color. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum EntryKind { + System, + User, + Assistant, + Reasoning, + Tool, + Error, +} + +/// `start` opens an entry, `progress` appends to it, `final` closes it. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Phase { + Start, + Progress, + Final, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Source { + Assistant, + Reasoning, + Tool, + System, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum ToolState { + Running, + Completed, + Error, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TurnSummary { + pub agent: String, + pub model: String, + pub duration: String, +} + +/// One append-only commit to the scrollback (`StreamCommit`). +#[derive(Clone, Debug, PartialEq)] +pub struct Commit { + pub kind: EntryKind, + pub text: String, + pub image: Option, + pub phase: Phase, + pub source: Source, + pub compaction: bool, + pub summary: Option, + pub message_id: Option, + pub part_id: Option, + pub tool: Option, + pub directory: Option, + /// The tool part as the server sent it. + pub part: Option, + pub interrupted: bool, + pub tool_state: Option, + pub tool_error: Option, + /// The command of a direct shell call. + pub shell: Option, +} + +impl Commit { + pub fn new(kind: EntryKind, source: Source, phase: Phase, text: impl Into) -> Self { + Self { + kind, + text: text.into(), + image: None, + phase, + source, + compaction: false, + summary: None, + message_id: None, + part_id: None, + tool: None, + directory: None, + part: None, + interrupted: false, + tool_state: None, + tool_error: None, + shell: None, + } + } + + pub fn message(mut self, id: impl Into) -> Self { + self.message_id = Some(id.into()); + self + } + + pub fn part_id(mut self, id: impl Into) -> Self { + self.part_id = Some(id.into()); + self + } + + /// A system line (`kind: "system", phase: "final"`), such as `startup 120ms`. + pub fn system(text: impl Into) -> Self { + Self::new(EntryKind::System, Source::System, Phase::Final, text) + } + + /// An error line (`kind: "error", phase: "start"`). + pub fn error(text: impl Into) -> Self { + Self::new(EntryKind::Error, Source::System, Phase::Start, text) + } +} + +/// What an entry draws (`RunEntryBody`). +#[derive(Clone, Debug, PartialEq)] +pub enum Body { + None, + Text(String), + Code { + content: String, + filetype: Option, + }, + Markdown(String), + Structured(tools::Snapshot), +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct BodyOptions { + pub shell_output: bool, + pub mono: bool, +} + +/// Where an entry starts and whether it ends its row (`EntryFlags`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Flags { + pub start_on_new_line: bool, + pub trailing_newline: bool, +} + +/// `entryBody`. +pub fn entry_body(commit: &Commit, options: BodyOptions) -> Body { + if commit.summary.is_some() { + return Body::None; + } + let raw = commit.text.replace("\r\n", "\n").replace('\r', "\n"); + let mono = options.mono; + if commit.image.is_some() { + let caption = match raw.trim() { + "" => "Image", + caption => caption, + }; + return match commit.kind { + EntryKind::User => user_body(caption, mono), + _ => text_body(crate::theme::mono_tool_text(caption, mono)), + }; + } + match commit.kind { + EntryKind::User => user_body(&raw, mono), + EntryKind::Tool => tools::entry_body(commit, &raw, options).unwrap_or(Body::None), + EntryKind::Assistant => match commit.phase { + Phase::Start => Body::None, + Phase::Final if commit.interrupted => text_body("assistant interrupted".into()), + Phase::Final => Body::None, + Phase::Progress => markdown_body(raw), + }, + EntryKind::Reasoning => match commit.phase { + Phase::Start => Body::None, + Phase::Final if commit.interrupted => text_body("reasoning interrupted".into()), + Phase::Final => Body::None, + Phase::Progress => reasoning_body(&raw, mono), + }, + EntryKind::System | EntryKind::Error => { + let text = if commit.phase == Phase::Progress { + raw + } else { + raw.trim().to_owned() + }; + match text_body(text) { + Body::Text(text) => Body::Text(crate::theme::mono_prefix(&text, mono)), + body => body, + } + } + } +} + +fn text_body(content: String) -> Body { + if content.is_empty() { + return Body::None; + } + Body::Text(content) +} + +fn markdown_body(content: String) -> Body { + if content.is_empty() { + return Body::None; + } + Body::Markdown(content) +} + +fn leading_newlines(text: &str) -> (&str, &str) { + let body = text.trim_start_matches('\n'); + (&text[..text.len() - body.len()], body) +} + +fn user_body(raw: &str, mono: bool) -> Body { + if raw.trim().is_empty() { + return Body::None; + } + let (lead, body) = leading_newlines(raw); + text_body(format!("{lead}{} {body}", if mono { ">" } else { "›" })) +} + +fn reasoning_body(raw: &str, mono: bool) -> Body { + let clean = raw.replace("[REDACTED]", ""); + if clean.is_empty() { + return Body::None; + } + let (lead, body) = leading_newlines(&clean); + let code = |content: String| Body::Code { + content, + filetype: Some("markdown".into()), + }; + if let Some(rest) = body.strip_prefix("Thinking:") { + let rest = rest.trim_start(); + if mono { + return text_body(format!("{lead}Thinking: {rest}")); + } + return code(format!("{lead}_Thinking:_ {rest}")); + } + if mono { + return text_body(clean); + } + code(clean) +} + +/// `entryFlags`. +pub fn entry_flags(commit: &Commit) -> Flags { + let flags = |start_on_new_line, trailing_newline| Flags { + start_on_new_line, + trailing_newline, + }; + if commit.summary.is_some() { + return flags(true, false); + } + match commit.kind { + EntryKind::User | EntryKind::Error => flags(true, false), + EntryKind::Tool | EntryKind::Assistant | EntryKind::Reasoning => { + if commit.phase == Phase::Progress { + flags(false, false) + } else { + flags(true, true) + } + } + EntryKind::System => flags(true, true), + } +} + +/// `entryDone`. +pub fn entry_done(commit: &Commit) -> bool { + match commit.kind { + EntryKind::Assistant | EntryKind::Reasoning => commit.phase == Phase::Final, + EntryKind::Tool => { + commit.phase == Phase::Final + || (commit.phase == Phase::Progress + && commit.tool_state == Some(ToolState::Completed)) + } + _ => true, + } +} + +/// `entryCanStream`. +pub fn entry_can_stream(commit: &Commit, body: &Body) -> bool { + if commit.phase != Phase::Progress || *body == Body::None { + return false; + } + match commit.kind { + EntryKind::Tool => commit.tool_state != Some(ToolState::Completed), + EntryKind::Assistant | EntryKind::Reasoning => true, + _ => false, + } +} + +/// `entryGroupKey`: commits of one part share a key and stream into one entry. +pub fn group_key(commit: &Commit) -> Option { + let part = format!( + "{}\u{0}{}", + commit.message_id.as_deref().unwrap_or(""), + commit.part_id.as_deref()? + ); + if tools::structured_final(commit) { + return Some(format!("tool:{part}:final")); + } + Some(format!("{:?}:{part}", commit.kind)) +} + +pub fn same_group(left: Option<&Commit>, right: &Commit) -> bool { + let Some(left) = left else { return false }; + matches!((group_key(left), group_key(right)), (Some(a), Some(b)) if a == b) +} + +fn inline(commit: &Commit, body: &Body) -> bool { + if commit.image.is_some() || commit.kind != EntryKind::Tool { + return false; + } + match body { + Body::Structured(_) | Body::Markdown(_) => false, + Body::Text(content) => { + !(commit.phase == Phase::Progress + && commit.tool_state == Some(ToolState::Completed) + && content.contains('\n')) + } + _ => true, + } +} + +/// `separatorRows`: one blank row between entries, none inside a group or between inline tools. +pub fn separator_rows(previous: Option<&Commit>, next: &Commit, body: &Body) -> u32 { + let Some(previous) = previous else { return 0 }; + if same_group(Some(previous), next) { + return 0; + } + let previous_body = entry_body(previous, BodyOptions::default()); + if inline(previous, &previous_body) && inline(next, body) { + return 0; + } + 1 +} + +/// `entryLook`: the color and attributes of a text entry. +pub fn entry_look(commit: &Commit, theme: &RunTheme) -> (Color, Attributes) { + let entry = &theme.entry; + if commit.kind == EntryKind::User { + return (entry.user.body, Attributes::NONE); + } + if failed(commit) { + return (entry.error.body, Attributes::BOLD); + } + if commit.phase == Phase::Final { + return (entry.system.body, Attributes::NONE); + } + match commit.kind { + EntryKind::Tool if commit.phase == Phase::Start => ( + entry.tool.start.unwrap_or(entry.tool.body), + Attributes::NONE, + ), + EntryKind::Assistant => (entry.assistant.body, Attributes::NONE), + EntryKind::Reasoning => (entry.reasoning.body, Attributes::NONE), + EntryKind::Error => (entry.error.body, Attributes::BOLD), + EntryKind::Tool => (entry.tool.body, Attributes::NONE), + _ => (entry.system.body, Attributes::NONE), + } +} + +/// `entryColor`: the base color of a code or Markdown entry. +pub fn entry_color(commit: &Commit, theme: &RunTheme) -> Color { + match commit.kind { + EntryKind::Assistant => theme.entry.assistant.body, + EntryKind::Reasoning => theme.entry.reasoning.body, + _ if failed(commit) => theme.entry.error.body, + EntryKind::Tool => theme.block.text, + _ => entry_look(commit, theme).0, + } +} + +fn failed(commit: &Commit) -> bool { + commit.kind == EntryKind::Tool + && (commit.tool_state == Some(ToolState::Error) + || commit + .part + .as_ref() + .is_some_and(|part| part["state"]["status"] == "error")) +} + +/// A body that streams on a surface. +enum Stream { + Text(Text), + Markdown(Markdown), +} + +struct Active { + commit: Commit, + /// The body's kind, to tell when a commit of the same group switches kind. + kind: std::mem::Discriminant, + surface: ScrollbackSurface, + widget: Stream, + content: String, + committed_rows: u32, + pending_spacer_rows: u32, + rendered: bool, +} + +/// `RunScrollbackStream`: appends commits to the scrollback. +pub struct Writer { + footer: SplitFooter, + scrollback: Scrollback, + theme: RunTheme, + mono: bool, + shell_output: bool, + /// Something was written above the transcript, so its first entry starts one row lower. + wrote: bool, + tail: Option, + rendered: Option, + active: Option, +} + +impl Writer { + pub fn new( + footer: SplitFooter, + scrollback: Scrollback, + theme: RunTheme, + mono: bool, + wrote: bool, + ) -> Self { + Self { + footer, + scrollback, + theme, + mono, + shell_output: false, + wrote, + tail: None, + rendered: None, + active: None, + } + } + + pub fn footer(&self) -> &SplitFooter { + &self.footer + } + + pub fn scrollback(&self) -> &Scrollback { + &self.scrollback + } + + pub fn theme(&self) -> &RunTheme { + &self.theme + } + + pub fn mono(&self) -> bool { + self.mono + } + + /// New entries use `theme`; rows already written keep theirs. + pub fn set_theme(&mut self, theme: RunTheme) { + self.theme = theme; + } + + pub fn set_mono(&mut self, mono: bool) -> Result<()> { + if self.mono == mono { + return Ok(()); + } + self.complete(false)?; + self.mono = mono; + Ok(()) + } + + pub fn set_shell_output(&mut self, show: bool) { + self.shell_output = show; + } + + /// Writes a snapshot, painted monochrome in mono mode (Core's `EXTERNAL_OUTPUT` hook). + pub fn write(&self, snapshot: SplitSnapshot) -> Result<()> { + if self.mono { + mono_snapshot(&snapshot.buffer)?; + } + self.footer.write(snapshot) + } + + /// Paints `widget` (built with [`Self::app`]) into the scrollback in one piece. + pub fn write_widget(&self, widget: &impl Widget, flags: Flags) -> Result<()> { + let snapshot = self.scrollback.snapshot( + widget, + SnapshotOptions { + start_on_new_line: flags.start_on_new_line, + trailing_newline: flags.trailing_newline, + ..SnapshotOptions::default() + }, + )?; + self.write(snapshot) + } + + /// The detached app scrollback widgets are built with. + pub fn app(&self) -> &App { + self.scrollback.app() + } + + /// Forgets what was written, after the terminal was cleared for a replay (`resetForReplay`). + pub fn reset(&mut self, wrote: bool) { + self.active = None; + self.tail = None; + self.rendered = None; + self.wrote = wrote; + } + + /// `append`. + pub fn append(&mut self, commit: Commit) -> Result<()> { + let same = same_group(self.tail.as_ref(), &commit); + if !same || commit.image.is_some() { + self.finish_active(false)?; + } + if let Some(summary) = &commit.summary { + self.write_spacer(1)?; + let widget = self.summary_widget(summary); + self.write_widget(&widget, entry_flags(&commit))?; + self.rendered = Some(commit.clone()); + self.tail = Some(commit); + return Ok(()); + } + let body = entry_body( + &commit, + BodyOptions { + shell_output: self.shell_output, + mono: self.mono, + }, + ); + if body == Body::None { + if entry_done(&commit) { + self.finish_active(false)?; + } + self.tail = Some(commit); + return Ok(()); + } + let streams = entry_can_stream(&commit, &body) + || (commit.kind == EntryKind::Tool + && commit.phase == Phase::Final + && matches!(body, Body::Markdown(_))); + if !matches!(body, Body::Structured(_)) && streams { + self.write_streaming(&commit, body)?; + if entry_done(&commit) { + self.finish_active(entry_flags(&commit).trailing_newline)?; + } + self.tail = Some(commit); + return Ok(()); + } + if same { + self.finish_active(false)?; + } + let rows = separator_rows(self.rendered.as_ref(), &commit, &body); + let spaced = if rows > 0 { + rows + } else { + u32::from(self.rendered.is_none() && self.wrote) + }; + self.write_spacer(spaced)?; + let body = static_body(&commit, body, spaced); + let widget = self.entry_widget(&commit, &body); + self.write_widget(&widget, entry_flags(&commit))?; + self.rendered = Some(commit.clone()); + self.tail = Some(commit); + Ok(()) + } + + /// Ends the streaming entry, committing its last rows (`complete`). + pub fn complete(&mut self, trailing_newline: bool) -> Result<()> { + self.finish_active(trailing_newline) + } + + /// Whether an entry is still streaming. + pub fn streaming(&self) -> bool { + self.active.is_some() + } + + fn write_spacer(&mut self, rows: u32) -> Result<()> { + if rows == 0 { + return Ok(()); + } + let spacer = Text::new(self.scrollback.app(), ""); + self.write_widget( + &spacer, + Flags { + start_on_new_line: true, + trailing_newline: true, + }, + )?; + self.wrote = false; + Ok(()) + } + + fn write_streaming(&mut self, commit: &Commit, body: Body) -> Result<()> { + let kind = std::mem::discriminant(&body); + let reuse = self + .active + .as_ref() + .is_some_and(|active| same_group(Some(&active.commit), commit) && active.kind == kind); + if !reuse { + self.finish_active(false)?; + self.active = Some(self.create_entry(commit, &body)?); + } + let mono = self.mono; + let active = self.active.as_mut().expect("an active entry"); + active.commit = commit.clone(); + let text = match body { + Body::Text(text) | Body::Markdown(text) => text, + Body::Code { content, .. } => content, + Body::None | Body::Structured(_) => String::new(), + }; + active + .content + .push_str(&if mono { mono_text(&text) } else { text }); + self.flush_active(false, false)?; + if self.active.as_ref().is_some_and(|active| active.rendered) { + self.rendered = self.active.as_ref().map(|active| active.commit.clone()); + } + Ok(()) + } + + fn create_entry(&self, commit: &Commit, body: &Body) -> Result { + let surface = self + .scrollback + .surface(entry_flags(commit).start_on_new_line)?; + let widget = match body { + Body::Text(_) => { + let (fg, attributes) = entry_look(commit, &self.theme); + let text = Text::new(self.scrollback.app(), "") + .wrap(WrapMode::Word) + .fg(fg) + .attributes(attributes); + surface.root().add(&text); + Stream::Text(text) + } + _ => { + let markdown = self.markdown(commit, body, true); + surface.root().add(&markdown); + Stream::Markdown(markdown) + } + }; + let rows = separator_rows(self.rendered.as_ref(), commit, body); + Ok(Active { + commit: commit.clone(), + kind: std::mem::discriminant(body), + surface, + widget, + content: String::new(), + committed_rows: 0, + pending_spacer_rows: if rows > 0 { + rows + } else { + u32::from(self.rendered.is_none() && self.wrote) + }, + rendered: false, + }) + } + + /// Commits the rows that can no longer change. Text and code keep their last row open while streaming. The + /// Markdown widget does not expose its block positions, so a streaming Markdown entry renders only its complete + /// blocks (up to the last blank line outside a fence) and commits those. + fn flush_active(&mut self, done: bool, trailing_newline: bool) -> Result { + let Some(active) = self.active.as_mut() else { + return Ok(false); + }; + let target = match &active.widget { + Stream::Text(text) => { + text.set_text(active.content.clone()); + active.surface.render()?; + let height = active.surface.height(); + if done { + height + } else { + active.committed_rows.max(height.saturating_sub(1)) + } + } + Stream::Markdown(markdown) => { + let content = if done { + active.content.as_str() + } else { + stable_prefix(&active.content) + }; + if content.is_empty() { + return Ok(false); + } + markdown.set_markdown(content); + markdown.streaming(!done); + active.surface.render()?; + active.surface.height() + } + }; + if target <= active.committed_rows { + return Ok(false); + } + let spacer = std::mem::take(&mut active.pending_spacer_rows); + let trailing = done && target == active.surface.height() && trailing_newline; + let snapshot = active + .surface + .commit_rows(active.committed_rows, target, None, trailing)?; + active.committed_rows = target; + active.rendered = true; + self.write_spacer(spacer)?; + if let Some(snapshot) = snapshot { + self.write(snapshot)?; + } + Ok(true) + } + + fn finish_active(&mut self, trailing_newline: bool) -> Result<()> { + if self.active.is_none() { + return Ok(()); + } + let result = self.flush_active(true, trailing_newline); + let active = self.active.take().expect("an active entry"); + if active.rendered { + self.rendered = Some(active.commit); + } + result.map(drop) + } + + /// The widget of a finished entry (`RunEntryContent`). + pub fn entry_widget(&self, commit: &Commit, body: &Body) -> AnyWidget { + let app = self.scrollback.app(); + let theme = &self.theme; + if commit.compaction { + let rule = |app: &App| { + View::new(app) + .border_sides(Sides::TOP) + .border_color(theme.block.muted) + .grow(1.0) + }; + let label = View::new(app) + .padding_x(1) + .child(&Text::new(app, commit.text.clone()).fg(theme.block.muted)); + return View::new(app) + .direction(FlexDirection::Row) + .align_items(Align::Center) + .child(&rule(app)) + .child(&label) + .child(&rule(app)) + .as_any(); + } + match body { + Body::Text(content) => { + let (fg, attributes) = entry_look(commit, theme); + Text::new(app, content.clone()) + .wrap(WrapMode::Word) + .fg(fg) + .attributes(attributes) + .as_any() + } + Body::Markdown(content) | Body::Code { content, .. } => { + let markdown = self.markdown(commit, body, false); + markdown.set_markdown(content.clone()); + markdown.as_any() + } + Body::Structured(snapshot) => tools::structured_widget(app, snapshot, theme, self.mono), + Body::None => Text::new(app, "").as_any(), + } + } + + /// Markdown for assistant text, and for code bodies in Markdown such as reasoning. Code in other languages is + /// M.4's (tool output); it renders as Markdown text here. + fn markdown(&self, commit: &Commit, body: &Body, streaming: bool) -> Markdown { + let app = self.scrollback.app(); + let theme = &self.theme; + let color = entry_color(commit, theme); + let code = matches!(body, Body::Code { .. }); + // A code body draws in one color (``); the conceal of the TS view hides its markers. + let (colors, syntax) = if code || theme.syntax.is_none() { + ( + MarkdownColors { + text: color, + heading: color, + emphasis: color, + code: color, + code_bg: Color::TRANSPARENT, + link: color, + quote: color, + marker: color, + rule: color, + }, + SyntaxTheme::new() + .first_part_fallback() + .style("default", Style::new().fg(color)), + ) + } else { + ( + MarkdownColors { + text: color, + ..theme.markdown + }, + theme.syntax.clone().unwrap_or_default(), + ) + }; + let table = if self.mono { + MarkdownTableOptions { + style: MarkdownTableStyle::Columns, + width_mode: Some(ColumnWidthMode::Content), + borders: Some(false), + ..MarkdownTableOptions::default() + } + } else { + MarkdownTableOptions { + width_mode: Some(ColumnWidthMode::Content), + ..MarkdownTableOptions::default() + } + }; + let syntax = if code { recolor(syntax, color) } else { syntax }; + opencode_ui::grammars::register(); + Markdown::new(app) + .colors(colors) + .syntax_theme(syntax) + .scope_styles(true) + .conceal(true) + .table_options(table) + .streaming(streaming) + } + + fn summary_widget(&self, summary: &TurnSummary) -> Text { + let theme = &self.theme; + let dot = if self.mono { "-" } else { "·" }; + Text::new( + self.scrollback.app(), + vec![ + summary.agent.clone().fg(theme.block.text), + format!(" {dot} {} {dot} {}", summary.model, summary.duration) + .fg(theme.block.muted), + ], + ) + .wrap(WrapMode::None) + .truncate(true) + } +} + +/// Every style of `syntax` in `color`, keeping attributes. +fn recolor(mut syntax: SyntaxTheme, color: Color) -> SyntaxTheme { + let names: Vec = syntax.names().map(str::to_owned).collect(); + for name in names { + if let Some(style) = syntax.get(&name) { + syntax.set(name, style.fg(color)); + } + } + syntax +} + +/// `staticBody`: a completed tool's output already spaced from its title drops its leading newline. +fn static_body(commit: &Commit, body: Body, spaced: u32) -> Body { + match body { + Body::Text(content) + if spaced > 0 + && commit.kind == EntryKind::Tool + && commit.phase == Phase::Progress + && commit.tool_state == Some(ToolState::Completed) + && content.starts_with('\n') => + { + Body::Text(content[1..].to_owned()) + } + body => body, + } +} + +/// The complete Markdown blocks of streaming `content`: everything before its last blank line outside a fence. +pub fn stable_prefix(content: &str) -> &str { + let mut fence: Option<&str> = None; + let mut end = 0; + let mut offset = 0; + let mut previous_blank = false; + for line in content.split_inclusive('\n') { + let trimmed = line.trim_start(); + let marker = ["```", "~~~"] + .into_iter() + .find(|marker| trimmed.starts_with(marker)); + match (fence, marker) { + (None, Some(marker)) => fence = Some(marker), + (Some(open), Some(marker)) if open == marker => fence = None, + _ => {} + } + let blank = line.trim().is_empty() && line.ends_with('\n'); + if blank && fence.is_none() && !previous_blank && offset > 0 { + end = content[..offset].trim_end_matches('\n').len(); + } + previous_blank = blank; + offset += line.len(); + } + &content[..end] +} + +#[cfg(test)] +mod tests { + use super::*; + + fn assistant(text: &str, phase: Phase) -> Commit { + Commit::new(EntryKind::Assistant, Source::Assistant, phase, text) + .message("msg_a") + .part_id("text:0") + } + + #[test] + fn bodies_follow_entry_body() { + let options = BodyOptions::default(); + let user = Commit::new(EntryKind::User, Source::System, Phase::Start, "\nhello"); + assert_eq!(entry_body(&user, options), Body::Text("\n› hello".into())); + let mono = BodyOptions { + mono: true, + ..options + }; + assert_eq!(entry_body(&user, mono), Body::Text("\n> hello".into())); + let blank = Commit::new(EntryKind::User, Source::System, Phase::Start, " "); + assert_eq!(entry_body(&blank, options), Body::None); + assert_eq!( + entry_body(&assistant("**hi**", Phase::Progress), options), + Body::Markdown("**hi**".into()) + ); + assert_eq!( + entry_body(&assistant("", Phase::Final), options), + Body::None + ); + let mut interrupted = assistant("", Phase::Final); + interrupted.interrupted = true; + assert_eq!( + entry_body(&interrupted, options), + Body::Text("assistant interrupted".into()) + ); + let reasoning = Commit::new( + EntryKind::Reasoning, + Source::Reasoning, + Phase::Progress, + "Thinking: a [REDACTED]plan", + ); + assert_eq!( + entry_body(&reasoning, options), + Body::Code { + content: "_Thinking:_ a plan".into(), + filetype: Some("markdown".into()) + } + ); + assert_eq!( + entry_body(&reasoning, mono), + Body::Text("Thinking: a plan".into()) + ); + let system = Commit::system(" → done \n"); + assert_eq!(entry_body(&system, mono), Body::Text("-> done".into())); + } + + #[test] + fn flags_and_separators() { + let user = Commit::new(EntryKind::User, Source::System, Phase::Start, "q"); + assert_eq!( + entry_flags(&user), + Flags { + start_on_new_line: true, + trailing_newline: false + } + ); + let progress = assistant("a", Phase::Progress); + assert!(!entry_flags(&progress).start_on_new_line); + assert_eq!(separator_rows(None, &user, &Body::None), 0); + assert_eq!(separator_rows(Some(&user), &progress, &Body::None), 1); + assert_eq!( + separator_rows( + Some(&progress), + &assistant("b", Phase::Progress), + &Body::None + ), + 0 + ); + assert!(same_group(Some(&progress), &assistant("b", Phase::Final))); + assert!(!same_group(Some(&user), &user)); + } + + #[test] + fn the_stable_prefix_ends_at_the_last_blank_line_outside_a_fence() { + assert_eq!(stable_prefix("one line"), ""); + assert_eq!(stable_prefix("a\n\nb"), "a"); + assert_eq!(stable_prefix("a\n\nb\n\n\nc"), "a\n\nb"); + assert_eq!(stable_prefix("a\n\n```\nx\n\ny"), "a"); + assert_eq!( + stable_prefix("a\n\n```\nx\n\n```\n\nz"), + "a\n\n```\nx\n\n```" + ); + assert_eq!(stable_prefix("\n\nlead"), ""); + } +} diff --git a/packages/cli-rs/crates/mini/src/settings.rs b/packages/cli-rs/crates/mini/src/settings.rs new file mode 100644 index 00000000000..882475a2e29 --- /dev/null +++ b/packages/cli-rs/crates/mini/src/settings.rs @@ -0,0 +1,54 @@ +//! Mini settings (`mini.*` in `cli.json`, `runtime.boot.ts:resolveMiniSettings`). M.1 resolves them at start; +//! the `/settings` panel and verbosity presets that change them are M.4's. + +use opencode_local::cli_config::{Mini, MiniWorkSpinner, Visibility}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct MiniSettings { + pub thinking: Visibility, + pub tools: Visibility, + pub shell_output: Visibility, + pub turn_summary: Visibility, + pub footer: Visibility, + pub splash: Visibility, + pub work_spinner: MiniWorkSpinner, + pub mono: bool, +} + +impl MiniSettings { + /// `resolveMiniSettings`: the configured values with mini's defaults. + pub fn resolve(mini: Option<&Mini>) -> Self { + let mini = mini.cloned().unwrap_or_default(); + Self { + thinking: mini.thinking.unwrap_or(Visibility::Show), + tools: mini.tools.unwrap_or(Visibility::Hide), + shell_output: mini.shell_output.unwrap_or(Visibility::Hide), + turn_summary: mini.turn_summary.unwrap_or(Visibility::Show), + footer: mini.footer.unwrap_or(Visibility::Show), + splash: mini.splash.unwrap_or(Visibility::Show), + work_spinner: mini.work_spinner.unwrap_or(MiniWorkSpinner::BlockSoftSlide), + mono: mini.mono.unwrap_or(false), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn defaults_match_resolve_mini_settings() { + let settings = MiniSettings::resolve(None); + assert_eq!(settings.thinking, Visibility::Show); + assert_eq!(settings.tools, Visibility::Hide); + assert_eq!(settings.splash, Visibility::Show); + assert!(!settings.mono); + let mono = MiniSettings::resolve(Some(&Mini { + mono: Some(true), + thinking: Some(Visibility::Hide), + ..Mini::default() + })); + assert!(mono.mono); + assert_eq!(mono.thinking, Visibility::Hide); + } +} diff --git a/packages/cli-rs/crates/mini/src/shell.rs b/packages/cli-rs/crates/mini/src/shell.rs new file mode 100644 index 00000000000..f8a1b632f9b --- /dev/null +++ b/packages/cli-rs/crates/mini/src/shell.rs @@ -0,0 +1,1068 @@ +//! The split-footer lifecycle (`runtime.lifecycle.ts`, `runtime.ts`, the state half of `footer.ts`). +//! +//! The renderer starts in a footer at the bottom of the main screen and paints at once; the session is resolved +//! behind it. A resumed session clears the terminal and replays its transcript. Closing writes what is queued, +//! leaves split mode, and ends with a newline so the shell continues below the transcript. + +use std::cell::{Cell, RefCell}; +use std::rc::Rc; +use std::time::Duration; + +use anyhow::Context as _; +use opencode_api::client::Client; +use opencode_local::cli_config::{ThemeMode as ConfigMode, Visibility}; +use opencode_store::target::{self, Prepared, SessionTarget, TargetError}; +use opencode_ui::theme::ThemeMode; +use opentui::native::{KittyKeyboard, MouseTracking}; +use opentui::prelude::*; +use opentui::split::{Scrollback, SplitFooter}; +use serde_json::{Value, json}; + +use crate::footers::Footers; +use crate::prompt::{Prompt, RunPrompt}; +use crate::replay::{self, Envelope, Incoming, Output, Transcript}; +use crate::scrollback::{Commit, Flags, Writer}; +use crate::settings::MiniSettings; +use crate::signals::{self, Trace}; +use crate::theme::{self, ThemeInput}; +use crate::variants::{ModelSelection, format_model_label}; +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); + +pub fn run(input: Input) -> anyhow::Result<()> { + let settings = MiniSettings::resolve(input.config.mini.as_ref()); + let mut options = AppOptions { + exit_on_ctrl_c: false, + light_theme: None, + 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) + }); + options.host.terminal.mouse = MouseTracking::Off; + if settings.mono { + options.host.terminal.kitty_keyboard = KittyKeyboard::OFF; + } + let app = App::new(options)?; + let footer = SplitFooter::of(app.session()).context("mini runs in a split footer")?; + let theme_input = ThemeInput { + name: input + .config + .theme + .as_ref() + .and_then(|theme| theme.name.clone()), + mode: input + .config + .theme + .as_ref() + .and_then(|theme| theme.mode) + .and_then(|mode| match mode { + ConfigMode::Light => Some(ThemeMode::Light), + ConfigMode::Dark => Some(ThemeMode::Dark), + ConfigMode::System => None, + }), + palette: app.palette(), + directories: input.theme_directories.clone(), + mono: settings.mono, + }; + let theme = theme::resolve(&theme_input); + // The transcript always starts one row below the terminal's earlier output. + let writer = Writer::new( + footer.clone(), + Scrollback::new(&app)?, + theme.clone(), + settings.mono, + true, + ); + let prompt = Prompt::new(&app, &theme, settings.mono); + 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(&status); + let mini = Rc::new(Mini { + app: app.clone(), + client: input.client.clone(), + footer, + writer: RefCell::new(writer), + transcript: RefCell::new(None), + footers: RefCell::new(Footers::default()), + session: RefCell::new(None), + prompt, + body, + status, + state: RefCell::new(State::default()), + theme_input, + settings, + input: Meta { + directory: input.directory.clone(), + home: input.home.clone(), + version: input.version.clone(), + replay: input.replay, + replay_limit: input.replay_limit, + trace: input.trace.clone(), + }, + initial: RefCell::new(input.initial_input.clone()), + waiting: RefCell::new(Vec::new()), + stream: RefCell::new(None), + resize: Cell::new(None), + size: Cell::new(mini_size(&app)), + exit_splash: Cell::new(false), + failure: RefCell::new(None), + }); + mini.set_title(None); + mini.paint_status(); + mini.apply_height(); + mini.wire(); + mini.resolve(input.target, input.start); + mini.prompt.focus(); + let _theme_signal = signals::on_sigusr2(&app); + app.on_message({ + let mini = mini.clone(); + move |_, _: &signals::ThemeReload| mini.refresh_theme() + }); + let result = app.run(); + mini.stop(); + if !mini.exit_splash.get() { + println!(); + } + result?; + if let Some(failure) = mini.failure.borrow_mut().take() { + return Err(failure); + } + Ok(()) +} + +fn mini_size(app: &App) -> (u16, u16) { + SplitFooter::of(app.session()).map_or((0, 0), |footer| footer.terminal_size()) +} + +/// What the command resolved, kept for the session's lifetime. +struct Meta { + directory: String, + home: std::path::PathBuf, + version: String, + replay: bool, + replay_limit: Option, + trace: Option, +} + +/// The session mini talks to, once resolved. +#[derive(Clone, Debug)] +struct Session { + id: String, + title: Option, + agent: Option, + /// `{ providerID, id, variant }` for `session.switchModel`. + model: Option, + /// The session's location (`state.location.directory`). + directory: String, +} + +/// The footer's state (`FooterState`). +#[derive(Debug, Default)] +struct State { + running: bool, + status: String, + notice: String, + model: String, + agent: String, + exit: u8, + interrupt: u8, + exit_timer: Option, + interrupt_timer: Option, + closed: bool, + /// A prompt turn is in flight (`state.wait`). + turn: bool, +} + +struct Mini { + app: App, + client: Client, + footer: SplitFooter, + writer: RefCell, + transcript: RefCell>, + footers: RefCell, + session: RefCell>, + prompt: Prompt, + body: View, + status: Text, + state: RefCell, + theme_input: ThemeInput, + settings: MiniSettings, + input: Meta, + /// The piped stdin and `--prompt`, sent once the session is ready. + initial: RefCell>, + /// Prompts submitted before the session was ready. + waiting: RefCell>, + stream: RefCell>>, + resize: Cell>, + size: Cell<(u16, u16)>, + exit_splash: Cell, + failure: RefCell>, +} + +impl Mini { + fn wire(self: &Rc) { + let mini = self.clone(); + self.app.on_message(move |cx, envelope: &Envelope| { + if let Some(incoming) = envelope.take() { + 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; + }); + } + } 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 mini = self.clone(); + self.app.on_resize(move |cx, _, _| mini.resized(cx)); + } + + /// Resolves the session behind the first frame (`ensureSession`). + fn resolve(self: &Rc, target: target::TargetInput, start: std::time::Instant) { + if signals::show_timing() { + let mini = self.clone(); + self.app.set_timeout(Duration::ZERO, move |cx| { + let elapsed = start.elapsed().as_millis(); + mini.append(cx, Commit::system(format!("startup {elapsed}ms"))); + }); + } + let client = self.client.clone(); + let agent = target.agent.clone(); + let mini = self.clone(); + self.app.spawn( + async move { + target::resolve_session_target(&client, target, |next| async move { + Ok(Prepared { + model: next.model, + agent: agent.or(next.agent), + }) + }) + .await + }, + move |cx, result| match result { + Ok(target) => mini.opened(cx, target), + Err(TargetError::SessionNotFound) => { + mini.fail(cx, InputError("Session not found".into()).into()) + } + Err(error) => mini.fail(cx, anyhow::Error::new(error)), + }, + ); + } + + fn fail(&self, cx: &mut Cx<'_>, error: anyhow::Error) { + *self.failure.borrow_mut() = Some(error); + self.close(cx); + } + + fn opened(self: &Rc, cx: &mut Cx<'_>, target: SessionTarget) { + if self.state.borrow().closed { + return; + } + let session = Session { + id: target.session.id.0.clone(), + title: target.session.title.clone(), + agent: target.agent.clone(), + directory: target.location.directory.0.clone(), + model: target.model.as_ref().map(|model| { + let mut value = json!({ "providerID": model.provider_id.0, "id": model.id }); + if let Some(variant) = &model.variant { + value["variant"] = json!(variant); + } + value + }), + }; + self.trace( + "session.open", + json!({ "sessionID": session.id, "resume": target.resume }), + ); + self.set_title(session.title.as_deref()); + let label = target.model.as_ref().map(|model| { + format_model_label( + &ModelSelection { + provider_id: model.provider_id.0.clone(), + model_id: model.id.clone(), + }, + model.variant.as_deref(), + ) + }); + self.patch(|state| { + state.agent = session.agent.clone().unwrap_or_default(); + state.model = label.unwrap_or_else(|| "Default model".into()); + }); + *self.transcript.borrow_mut() = Some(Transcript::new( + &session.id, + self.settings.thinking == Visibility::Show, + self.settings.tools == Visibility::Show, + self.input.replay, + self.input.replay_limit, + )); + *self.session.borrow_mut() = Some(session.clone()); + if target.resume { + self.prompt.set_first(false); + self.reset_for_replay(cx); + } + if target.model.is_none() { + self.load_default_model(&session.directory); + } + let proxy = self.app.proxy(); + let limit = self + .input + .replay_limit + .unwrap_or(replay::DEFAULT_REPLAY_LIMIT); + let task = self.app.runtime().spawn(replay::connect( + self.client.clone(), + session.id, + limit, + proxy, + )); + *self.stream.borrow_mut() = Some(task); + } + + /// `loadDefaultModel`: the label of the model a session without one uses. + fn load_default_model(self: &Rc, directory: &str) { + let client = self.client.clone(); + let directory = directory.to_owned(); + let mini = self.clone(); + self.app.spawn( + async move { replay::default_model(&client, &directory).await }, + move |_, model| { + let Some((provider_id, model_id)) = model else { + return; + }; + let label = format_model_label( + &ModelSelection { + provider_id, + model_id, + }, + None, + ); + mini.patch(|state| state.model = label); + }, + ); + } + + /// `resetForReplay`: clears the terminal and its scrollback, then writes the entry header the transcript + /// starts under. + fn reset_for_replay(&self, cx: &mut Cx<'_>) { + let mut writer = self.writer.borrow_mut(); + let result = writer.complete(false).and_then(|()| { + writer.reset(true); + self.footer.reset_for_replay(true)?; + let width = self.footer.renderer_size().0; + let directory = self.session.borrow().as_ref().map_or_else( + || self.input.directory.clone(), + |session| session.directory.clone(), + ); + let detail = directory_label(&directory, &self.input.home); + let header = crate::splash::entry( + writer.app(), + u32::from(width), + &self.input.version, + &detail, + &writer.theme().splash, + writer.mono(), + ); + writer.write_widget( + &header, + Flags { + start_on_new_line: true, + trailing_newline: false, + }, + ) + }); + if let Err(error) = result { + cx.fail(error); + } + } + + fn incoming(self: &Rc, cx: &mut Cx<'_>, incoming: Incoming) { + if self.state.borrow().closed { + return; + } + let output = { + let mut transcript = self.transcript.borrow_mut(); + let Some(transcript) = transcript.as_mut() else { + return; + }; + match incoming { + Incoming::Hydrated { messages, active } => { + self.trace( + "recv.hydrate", + json!({ "messages": messages.len(), "active": active }), + ); + transcript.hydrate(&messages, active) + } + Incoming::Event(event) => { + self.trace("recv.event", event.clone()); + transcript.event(&event) + } + Incoming::Disconnected(error) => { + self.trace("recv.reconnect", json!({ "error": error })); + transcript.connected = false; + Output { + patch: Some(replay::Patch { + running: Some(true), + status: Some("reconnecting".into()), + usage: None, + }), + ..Output::default() + } + } + } + }; + let hydrated = output.patch.is_some() + && self + .transcript + .borrow() + .as_ref() + .is_some_and(|transcript| transcript.connected); + self.output(cx, output); + if hydrated { + self.send_waiting(cx); + } + } + + /// Writes a transcript output: footer events, commits, then the status. + fn output(&self, cx: &mut Cx<'_>, output: Output) { + for event in &output.footer { + self.footers.borrow_mut().event(event); + } + if let Some(title) = &output.title { + if let Some(session) = self.session.borrow_mut().as_mut() { + session.title = Some(title.clone()); + } + self.set_title(Some(title)); + } + for commit in output.commits { + self.write(cx, commit); + } + if let Some(patch) = output.patch { + let idle = patch.running == Some(false); + self.patch(|state| { + if let Some(running) = patch.running { + state.running = running || state.turn; + } + if let Some(status) = patch.status { + state.status = status; + } + if !state.running { + state.interrupt = 0; + } + }); + if idle && !self.state.borrow().running { + self.complete(cx); + } + } + } + + fn write(&self, cx: &mut Cx<'_>, commit: Commit) { + if let Err(error) = self.writer.borrow_mut().append(commit) { + log::warn!("mini scrollback write failed: {error}"); + if self.footer.is_split() { + cx.fail(error); + } + } + } + + /// Appends a row this client prints itself, remembered for a resize replay. + fn append(&self, cx: &mut Cx<'_>, commit: Commit) { + if let Some(transcript) = self.transcript.borrow_mut().as_mut() { + transcript.remember(&commit); + } + self.write(cx, commit); + } + + fn complete(&self, cx: &mut Cx<'_>) { + if let Err(error) = self.writer.borrow_mut().complete(false) { + cx.fail(error); + } + } + + /// 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; + } + let ready = self + .transcript + .borrow() + .as_ref() + .is_some_and(|transcript| transcript.connected); + if !ready { + self.waiting.borrow_mut().push(prompt); + return; + } + self.send(cx, prompt); + } + + 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() + }, + ); + } + let waiting = std::mem::take(&mut *self.waiting.borrow_mut()); + for prompt in waiting { + self.send(cx, 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) { + let Some(session) = self.session.borrow().clone() else { + 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 started = std::time::Instant::now(); + self.app.spawn( + { + let (session, id, text) = (session.clone(), id.clone(), text.clone()); + async move { + replay::prompt( + &client, + &session.id, + &id, + &text, + session.agent.as_deref(), + session.model.as_ref(), + ) + .await + } + }, + move |cx, result| match result { + Ok(()) => { + let output = mini + .transcript + .borrow_mut() + .as_mut() + .map(|transcript| transcript.admitted(&id, &text)) + .unwrap_or_default(); + mini.output(cx, output); + 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() + }, + ); + } + }, + ); + } + + /// `settleSession`: waits until the session is idle, then lists its messages. + fn settle(self: &Rc, session: &str, started: std::time::Instant) { + let client = self.client.clone(); + let session = session.to_owned(); + let limit = self + .input + .replay_limit + .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 + }, + move |cx, result| { + mini.patch(|state| state.turn = false); + let mut output = Output::default(); + match result { + Ok(messages) => { + if let Some(transcript) = mini.transcript.borrow_mut().as_mut() { + for message in &messages { + output.extend(transcript.message(message, true)); + } + } + } + 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); + mini.turn_summary(cx, started); + }, + ); + } + + /// `turn.duration`: the agent, model, and time of a finished turn, below its answer. + fn turn_summary(&self, cx: &mut Cx<'_>, started: std::time::Instant) { + if self.settings.turn_summary == Visibility::Hide { + return; + } + let model = self + .session + .borrow() + .as_ref() + .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), + model, + duration: duration(started.elapsed().as_millis() as u64), + }; + let mut commit = Commit::system(format!( + "{} · {} · {}", + summary.agent, summary.model, summary.duration + )); + commit.summary = Some(summary); + self.write(cx, commit); + } + + /// Two presses within five seconds leave (`handleExit`). + fn request_exit(self: &Rc, cx: &mut Cx<'_>) { + let exit = { + let mut state = self.state.borrow_mut(); + if state.closed { + return; + } + state.exit += 1; + state.interrupt = 0; + state.exit + }; + if exit >= 2 { + self.close(cx); + return; + } + let mini = self.clone(); + let timer = self + .app + .set_timeout(TWO_PRESS, move |_| mini.patch(|state| state.exit = 0)); + if let Some(previous) = self.state.borrow_mut().exit_timer.replace(timer) { + self.app.cancel_timer(previous); + } + self.paint_status(); + } + + /// Two presses of Esc while the session runs interrupt it (`handleInterrupt`). + fn request_interrupt(self: &Rc, _cx: &mut Cx<'_>) { + let interrupt = { + let mut state = self.state.borrow_mut(); + if state.closed || !state.running { + return; + } + state.interrupt += 1; + state.interrupt + }; + if interrupt < 2 { + let mini = self.clone(); + let timer = self + .app + .set_timeout(TWO_PRESS, move |_| mini.patch(|state| state.interrupt = 0)); + if let Some(previous) = self.state.borrow_mut().interrupt_timer.replace(timer) { + self.app.cancel_timer(previous); + } + self.paint_status(); + return; + } + self.patch(|state| { + state.interrupt = 0; + state.notice = "interrupting".into(); + }); + let Some(session) = self.session.borrow().clone() else { + return; + }; + self.trace("send.interrupt", json!({ "sessionID": session.id })); + let client = self.client.clone(); + self.app.spawn( + async move { replay::interrupt(&client, &session.id).await }, + |_, result| { + if let Err(error) = result { + log::warn!("mini interrupt failed: {error}"); + } + }, + ); + } + + /// `close`: finish the streaming entry, leave split mode, and quit. The newline follows `app.run()`. + fn close(&self, cx: &mut Cx<'_>) { + { + let mut state = self.state.borrow_mut(); + if state.closed { + return; + } + state.closed = true; + state.status = "exiting".into(); + } + self.stop(); + let _ = self.writer.borrow_mut().complete(false); + let session = self.session.borrow().clone(); + if let Some(session) = session + && self.settings.splash == Visibility::Show + { + let writer = self.writer.borrow(); + if let Some(banner) = crate::splash::exit( + writer.app(), + session.title.as_deref(), + &session.id, + &writer.theme().splash, + writer.mono(), + ) && writer + .write_widget( + &banner, + Flags { + start_on_new_line: true, + trailing_newline: true, + }, + ) + .is_ok() + { + self.exit_splash.set(true); + } + } + if cfg!(target_os = "linux") { + self.app.set_title(""); + } + if let Err(error) = self.footer.leave() { + log::warn!("mini could not leave the split footer: {error}"); + } + cx.quit(); + } + + fn stop(&self) { + if let Some(task) = self.stream.borrow_mut().take() { + task.abort(); + } + } + + /// A terminal resize: the footer follows at once, the theme and the transcript after 250 ms of quiet. + fn resized(self: &Rc, _cx: &mut Cx<'_>) { + let size = self.footer.terminal_size(); + if size == self.size.replace(size) { + return; + } + self.apply_height(); + if let Some(timer) = self.resize.take() { + self.app.cancel_timer(timer); + } + let mini = self.clone(); + let timer = self.app.set_timeout(replay::RESIZE_DELAY, move |cx| { + mini.resize.set(None); + if mini.state.borrow().closed { + return; + } + mini.refresh_theme(); + mini.replay_on_resize(cx); + }); + self.resize.set(Some(timer)); + } + + /// `replayOnResize`: clear, list the messages again, and write the transcript at the new width. + fn replay_on_resize(self: &Rc, _cx: &mut Cx<'_>) { + let session = { + let mut transcript = self.transcript.borrow_mut(); + let Some(transcript) = transcript.as_mut() else { + return; + }; + if !self.input.replay || !transcript.connected || transcript.replaying() { + return; + } + transcript.begin_replay(); + transcript.session_id.clone() + }; + self.trace("replay.resize", json!({ "sessionID": session })); + let client = self.client.clone(); + let limit = self + .input + .replay_limit + .unwrap_or(replay::DEFAULT_REPLAY_LIMIT); + let mini = self.clone(); + self.app.spawn( + async move { replay::hydration(&client, &session, limit).await }, + move |cx, result| { + let output = match result { + Ok((messages, active)) => { + mini.reset_for_replay(cx); + mini.transcript + .borrow_mut() + .as_mut() + .map(|transcript| transcript.replayed(&messages, active)) + } + // Nothing was cleared; the events that waited still apply. + Err(error) => { + log::warn!("mini resize replay failed: {error}"); + mini.transcript + .borrow_mut() + .as_mut() + .map(Transcript::abort_replay) + } + }; + if let Some(output) = output { + mini.output(cx, output); + } + }, + ); + } + + /// Re-resolves the theme (SIGUSR2, resize). New entries take it; written rows keep theirs. + fn refresh_theme(&self) { + let theme = theme::resolve(&self.theme_input); + self.prompt.set_theme(&theme); + self.writer.borrow_mut().set_theme(theme); + self.paint_status(); + } + + /// `applyHeight` for the composer: the prompt's rows, padded in a tall terminal, plus the status row. + 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) { + log::warn!("mini could not set the footer height: {error}"); + } + } + + fn patch(&self, change: impl FnOnce(&mut State)) { + change(&mut self.state.borrow_mut()); + self.paint_status(); + } + + /// The status row: the two-press hints, else the agent and model, then the status. + fn paint_status(&self) { + let state = self.state.borrow(); + let theme = self.writer.borrow().theme().clone(); + let separator = if self.settings.mono { " - " } else { " · " }; + let content: Vec = if state.exit > 0 { + vec![ + "Press ctrl+c again to exit" + .to_owned() + .fg(theme.footer.warning), + ] + } else if state.interrupt > 0 { + vec![ + "Press esc again to interrupt" + .to_owned() + .fg(theme.footer.warning), + ] + } else { + let agent = capitalize(&state.agent); + let mut spans = Vec::new(); + if !agent.is_empty() { + spans.push(agent.fg(theme.footer.text)); + } + if !state.model.is_empty() { + let lead = if spans.is_empty() { "" } else { separator }; + let model = if self.settings.mono { + state.model.replace(" · ", separator) + } else { + state.model.clone() + }; + 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)); + } + spans + }; + self.status.set_text(content); + } + + /// 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") { + return; + } + match title.filter(|title| !title.is_empty() && !is_fallback_title(title)) { + None => self.app.set_title("OpenCode"), + Some(title) => { + let short = if title.encode_utf16().count() > 40 { + format!("{}…", title.chars().take(37).collect::<String>()) + } else { + title.to_owned() + }; + self.app.set_title(&format!("OC | {short}")); + } + } + } + + fn trace(&self, kind: &str, data: Value) { + if let Some(trace) = &self.input.trace { + trace.write(kind, data); + } + } +} + +/// `footerPromptLayout` and `applyHeight` for the composer: padding rows in a tall terminal, the textarea, and the +/// status row, leaving one transcript row. +pub fn prompt_height(terminal: u16, rows: u16) -> u16 { + let padding = u16::from(terminal >= PROMPT_MAX_ROWS + 4); + (padding * 2 + 1 + rows.max(1)) + .min(terminal.saturating_sub(1)) + .max(1) +} + +/// `isFallbackTitle`: a stored `New session - <ISO time>` or `Child session - <ISO time>` title. +fn is_fallback_title(title: &str) -> bool { + let Some(stamp) = title + .strip_prefix("New session - ") + .or_else(|| title.strip_prefix("Child session - ")) + else { + return false; + }; + let shape = "0000-00-00T00:00:00.000Z"; + stamp.len() == shape.len() + && stamp.bytes().zip(shape.bytes()).all(|(have, want)| { + if want == b'0' { + have.is_ascii_digit() + } else { + have == want + } + }) +} + +/// `directoryLabel`: the home directory as `~`, with forward slashes. +fn directory_label(directory: &str, home: &std::path::Path) -> String { + let home = home.to_string_lossy(); + let display = if directory == home { + "~".to_owned() + } else if let Some(rest) = directory.strip_prefix(&format!("{home}/")) { + format!("~/{rest}") + } else { + directory.to_owned() + }; + display.replace('\\', "/") +} + +/// `Locale.duration`. +pub fn duration(ms: u64) -> String { + match ms { + 0..1_000 => format!("{ms}ms"), + // `toFixed(1)` rounds the exact decimal half up; `{:.1}` would round half to even. + 1_000..60_000 => { + let tenths = (ms + 50) / 100; + format!("{}.{}s", tenths / 10, tenths % 10) + } + 60_000..3_600_000 => format!("{}m {}s", ms / 60_000, ms % 60_000 / 1000), + 3_600_000..86_400_000 => format!("{}h {}m", ms / 3_600_000, ms % 3_600_000 / 60_000), + _ => format!("{}d {}h", ms / 86_400_000, ms % 86_400_000 / 3_600_000), + } +} + +fn capitalize(text: &str) -> String { + let mut chars = text.chars(); + match chars.next() { + Some(first) => first.to_uppercase().chain(chars).collect(), + None => String::new(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_footer_is_padded_in_tall_terminals() { + assert_eq!(prompt_height(16, 1), 2); + assert_eq!(prompt_height(17, 1), 2); + assert_eq!(prompt_height(18, 1), 4); + assert_eq!(prompt_height(40, 3), 6); + assert_eq!(prompt_height(2, 1), 1); + } + + #[test] + fn fallback_titles_and_labels() { + assert!(is_fallback_title("New session - 2026-11-05T10:20:30.123Z")); + assert!(is_fallback_title( + "Child session - 2026-11-05T10:20:30.123Z" + )); + assert!(!is_fallback_title("New session - today")); + assert!(!is_fallback_title("Fix the bug")); + let home = std::path::Path::new("/home/me"); + assert_eq!(directory_label("/home/me", home), "~"); + assert_eq!(directory_label("/home/me/src", home), "~/src"); + assert_eq!(directory_label("/home/meow", home), "/home/meow"); + assert_eq!(capitalize("build"), "Build"); + assert_eq!(duration(950), "950ms"); + assert_eq!(duration(1_250), "1.3s"); + assert_eq!(duration(61_000), "1m 1s"); + assert_eq!(duration(3_660_000), "1h 1m"); + } +} diff --git a/packages/cli-rs/crates/mini/src/signals.rs b/packages/cli-rs/crates/mini/src/signals.rs new file mode 100644 index 00000000000..f092f77687c --- /dev/null +++ b/packages/cli-rs/crates/mini/src/signals.rs @@ -0,0 +1,157 @@ +//! Signals and diagnostics of the mini host (`packages/cli/src/mini-host.ts:32-86,161-164`): SIGUSR2 reloads the +//! theme, `OPENCODE_SHOW_TTFD` prints the time to the first frame, and `OPENCODE_DIRECT_TRACE` writes a JSONL +//! trace of what mini sends and receives. +//! +//! SIGINT and SIGTERM stay with the renderer, which ends the app; mini then closes as on any exit. + +use std::fs::{self, OpenOptions}; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; + +use opentui::prelude::*; +use serde_json::{Value, json}; + +/// `OPENCODE_SHOW_TTFD` is `1` or `true`, in any case. +pub fn show_timing() -> bool { + std::env::var("OPENCODE_SHOW_TTFD") + .is_ok_and(|value| matches!(value.to_lowercase().as_str(), "1" | "true")) +} + +/// The JSONL trace (`createTrace`), on when `OPENCODE_DIRECT_TRACE` is set to anything. +#[derive(Clone)] +pub struct Trace { + path: PathBuf, + pid: u32, + file: Arc<Mutex<fs::File>>, +} + +impl Trace { + /// Starts a trace under `<log>/direct/<stamp>-<pid>.jsonl` and points `<log>/direct/latest.json` at it. + pub fn from_env(log: &Path, cwd: &str, argv: &[String]) -> Option<Self> { + std::env::var_os("OPENCODE_DIRECT_TRACE")?; + Self::start(log, std::process::id(), cwd, argv) + .inspect_err(|error| log::warn!("mini trace failed to start: {error}")) + .ok() + } + + fn start(log: &Path, pid: u32, cwd: &str, argv: &[String]) -> std::io::Result<Self> { + let directory = log.join("direct"); + let stamp = chrono::Utc::now().format("%Y%m%dT%H%M%SZ"); + let path = directory.join(format!("{stamp}-{pid}.jsonl")); + fs::create_dir_all(&directory)?; + let latest = json!({ "time": now(), "pid": pid, "cwd": cwd, "argv": argv, "path": path }); + fs::write(directory.join("latest.json"), format!("{latest}\n"))?; + let file = OpenOptions::new().create(true).append(true).open(&path)?; + let trace = Self { + path: path.clone(), + pid, + file: Arc::new(Mutex::new(file)), + }; + trace.write( + "trace.start", + json!({ "argv": argv, "cwd": cwd, "path": path }), + ); + Ok(trace) + } + + pub fn path(&self) -> &Path { + &self.path + } + + /// Appends one record: `{ time, pid, type, data }`. + pub fn write(&self, kind: &str, data: Value) { + let mut record = json!({ "time": now(), "pid": self.pid, "type": kind }); + if !data.is_null() { + record["data"] = data; + } + if let Ok(mut file) = self.file.lock() { + let _ = writeln!(file, "{record}"); + } + } +} + +/// `new Date().toISOString()`. +fn now() -> String { + chrono::Utc::now() + .format("%Y-%m-%dT%H:%M:%S%.3fZ") + .to_string() +} + +/// Sent to the app on each SIGUSR2 (`signals.sigusr2`); mini reloads its theme. +pub struct ThemeReload; + +/// Delivers [`ThemeReload`] to the app's message handlers for every SIGUSR2 until the guard drops. +#[cfg(unix)] +pub fn on_sigusr2(app: &App) -> Subscription { + use tokio::signal::unix::{SignalKind, signal}; + + let proxy = app.proxy(); + let task = app.runtime().spawn(async move { + let Ok(mut signals) = signal(SignalKind::user_defined2()) else { + log::warn!("mini could not listen for SIGUSR2"); + return; + }; + while signals.recv().await.is_some() { + if proxy.send(ThemeReload).is_err() { + return; + } + } + }); + Subscription(Some(task)) +} + +#[cfg(not(unix))] +pub fn on_sigusr2(_app: &App) -> Subscription { + Subscription(None) +} + +/// Stops listening when dropped. +pub struct Subscription(Option<tokio::task::JoinHandle<()>>); + +impl Drop for Subscription { + fn drop(&mut self) { + if let Some(task) = self.0.take() { + task.abort(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_trace_writes_latest_and_records() { + let dir = tempfile::tempdir().unwrap(); + let trace = Trace::start(dir.path(), 42, "/work", &["mini".into()]).unwrap(); + trace.write("send.prompt", json!({ "sessionID": "ses_1" })); + trace.write("ui.idle", Value::Null); + let latest: Value = serde_json::from_str( + &fs::read_to_string(dir.path().join("direct/latest.json")).unwrap(), + ) + .unwrap(); + assert_eq!(latest["pid"], 42); + assert_eq!(latest["path"], json!(trace.path())); + let name = trace + .path() + .file_name() + .unwrap() + .to_string_lossy() + .into_owned(); + assert!(name.ends_with("Z-42.jsonl"), "{name}"); + let lines: Vec<Value> = fs::read_to_string(trace.path()) + .unwrap() + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect(); + let kinds: Vec<_> = lines.iter().map(|line| line["type"].clone()).collect(); + assert_eq!( + kinds, + [json!("trace.start"), json!("send.prompt"), json!("ui.idle")] + ); + assert_eq!(lines[0]["data"]["cwd"], "/work"); + assert_eq!(lines[1]["data"]["sessionID"], "ses_1"); + assert!(lines[2].get("data").is_none()); + } +} diff --git a/packages/cli-rs/crates/mini/src/spinners.rs b/packages/cli-rs/crates/mini/src/spinners.rs new file mode 100644 index 00000000000..f5f1c7ef0e1 --- /dev/null +++ b/packages/cli-rs/crates/mini/src/spinners.rs @@ -0,0 +1,11 @@ +//! The 14 work spinners (`config/index.tsx:29-44`): M.4. M.1's footer shows no spinner. + +use opencode_local::cli_config::MiniWorkSpinner; + +/// The frames of `spinner`, and how long each shows. Empty until M.4. +pub fn frames( + _spinner: MiniWorkSpinner, + _mono: bool, +) -> (&'static [&'static str], std::time::Duration) { + (&[], std::time::Duration::from_millis(80)) +} diff --git a/packages/cli-rs/crates/mini/src/splash.rs b/packages/cli-rs/crates/mini/src/splash.rs new file mode 100644 index 00000000000..c85811cd2d2 --- /dev/null +++ b/packages/cli-rs/crates/mini/src/splash.rs @@ -0,0 +1,129 @@ +//! Entry and exit splash (`splash.ts`): M.4. M.1 writes the one-row entry header that a replay starts with +//! (`entrySplash`); the exit banner and the startup animation are M.4's. + +use opentui::prelude::*; +use unicode_width::UnicodeWidthStr; + +use crate::theme::SplashTheme; + +/// `entrySplashLayout`: the label and as much metadata as fits, in priority order. +pub fn entry_layout(width: usize, version: &str, detail: &str, mono: bool) -> (String, String) { + let segments: Vec<&str> = detail + .split(['/', '\\']) + .filter(|part| !part.is_empty()) + .collect(); + let leaf = segments.last().copied().unwrap_or(detail); + let separator = if mono { " - " } else { " · " }; + let ellipsis = if mono { "..." } else { "…" }; + let slash = if detail.contains('\\') { "\\" } else { "/" }; + let mut paths: Vec<String> = (1..segments.len()) + .map(|start| format!("{ellipsis}{slash}{}", segments[start..].join(slash))) + .filter(|path| path.width() < detail.width()) + .collect(); + paths.reverse(); + if !detail.is_empty() { + paths.push(detail.to_owned()); + } + let mut label = take_width("oc mini", width); + let (mut current_version, mut path) = (String::new(), String::new()); + let mut metadata = String::new(); + let mut stages: Vec<(Option<String>, Option<String>, Option<String>)> = vec![( + Some(format!("{} oc mini", if mono { "[O]" } else { "▪" })), + None, + None, + )]; + if !leaf.is_empty() { + stages.push((None, None, Some(leaf.to_owned()))); + } + if !version.is_empty() { + stages.push((None, Some(version.to_owned()), None)); + } + stages.extend(paths.into_iter().map(|path| (None, None, Some(path)))); + // Stop at the first stage that does not fit instead of backfilling lower-priority metadata. + for (next_label, next_version, next_path) in stages { + let next_label = next_label.unwrap_or_else(|| label.clone()); + let next_version = next_version.unwrap_or_else(|| current_version.clone()); + let next_path = next_path.unwrap_or_else(|| path.clone()); + let next_metadata = format!( + "{}{}", + if next_version.is_empty() { + String::new() + } else { + format!(" v{next_version}") + }, + if next_path.is_empty() { + String::new() + } else { + format!("{separator}{next_path}") + } + ); + if (next_label.clone() + &next_metadata).width() > width { + break; + } + (label, current_version, path, metadata) = + (next_label, next_version, next_path, next_metadata); + } + (label, metadata) +} + +fn take_width(text: &str, width: usize) -> String { + let mut taken = String::new(); + for c in text.chars() { + if (taken.clone() + &c.to_string()).width() > width { + break; + } + taken.push(c); + } + taken +} + +/// `entrySplash`: a blank row, then the header, as a two-row block that starts on a new line. +pub fn entry( + app: &App, + width: u32, + version: &str, + detail: &str, + theme: &SplashTheme, + mono: bool, +) -> View { + let (label, metadata) = entry_layout(width as usize, version, detail, mono); + View::new(app).height(2).padding_edge(Edge::Top, 1).child( + &Text::new(app, vec![label.fg(theme.right), metadata.fg(theme.left)]).wrap(WrapMode::None), + ) +} + +/// `exitSplash`: the banner written when mini closes. `None` until M.4, so mini prints a newline instead. +pub fn exit( + _app: &App, + _title: Option<&str>, + _session_id: &str, + _theme: &SplashTheme, + _mono: bool, +) -> Option<View> { + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_entry_header_drops_metadata_that_does_not_fit() { + let layout = |width| entry_layout(width, "1.2.3", "/home/me/src/app", false); + assert_eq!( + layout(80), + ("▪ oc mini".into(), " v1.2.3 · /home/me/src/app".into()) + ); + assert_eq!( + layout(28), + ("▪ oc mini".into(), " v1.2.3 · …/src/app".into()) + ); + assert_eq!(layout(20), ("▪ oc mini".into(), " · app".into())); + assert_eq!(layout(14), ("▪ oc mini".into(), "".into())); + assert_eq!(layout(5), ("oc mi".into(), "".into())); + assert_eq!( + entry_layout(80, "local", "/tmp/mini", true), + ("[O] oc mini".into(), " vlocal - /tmp/mini".into()) + ); + } +} diff --git a/packages/cli-rs/crates/mini/src/stdin.rs b/packages/cli-rs/crates/mini/src/stdin.rs new file mode 100644 index 00000000000..bf9e7c5913a --- /dev/null +++ b/packages/cli-rs/crates/mini/src/stdin.rs @@ -0,0 +1,75 @@ +//! Piped stdin (`packages/cli/src/mini.ts:38`, `mini-host.ts:88-113`): `cat file | opencode mini` reads the pipe +//! into the first prompt, then reads keys from the controlling terminal instead. + +use std::io::{IsTerminal, Read}; + +pub const INTERACTIVE_INPUT_ERROR: &str = "opencode mini requires a controlling terminal for input"; + +/// Reads piped stdin to its end, then puts the controlling terminal (`/dev/tty`) on fd 0, where the renderer reads +/// keys. Returns `None` when stdin is already a terminal. +pub fn take_piped() -> Result<Option<String>, String> { + if std::io::stdin().is_terminal() { + return Ok(None); + } + let mut bytes = Vec::new(); + std::io::stdin() + .read_to_end(&mut bytes) + .map_err(|error| format!("failed to read stdin: {error}"))?; + reopen_terminal()?; + Ok(Some(String::from_utf8_lossy(&bytes).into_owned())) +} + +#[cfg(unix)] +fn reopen_terminal() -> Result<(), String> { + let terminal = std::fs::OpenOptions::new() + .read(true) + .open("/dev/tty") + .map_err(|_| INTERACTIVE_INPUT_ERROR.to_owned())?; + rustix::stdio::dup2_stdin(&terminal).map_err(|_| INTERACTIVE_INPUT_ERROR.to_owned()) +} + +#[cfg(not(unix))] +fn reopen_terminal() -> Result<(), String> { + Err(INTERACTIVE_INPUT_ERROR.to_owned()) +} + +/// `mergeInput`: the piped text, then `--prompt` on its own line; either alone; `None` when both are empty. +pub fn merge_input(piped: Option<&str>, prompt: Option<&str>) -> Option<String> { + let piped = piped.filter(|text| !text.is_empty()); + let prompt = prompt.filter(|text| !text.is_empty()); + match (piped, prompt) { + (None, None) => None, + (Some(text), None) | (None, Some(text)) => Some(text.to_owned()), + (Some(piped), Some(prompt)) => Some(format!("{piped}\n{prompt}")), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn merge_input_matches_mini_ts() { + // The first two are the cases of `packages/cli/test/mini.test.ts`. + assert_eq!( + merge_input(Some("from stdin"), None).as_deref(), + Some("from stdin") + ); + assert_eq!( + merge_input(Some("from stdin"), Some("from flag")).as_deref(), + Some("from stdin\nfrom flag") + ); + assert_eq!(merge_input(None, None), None); + assert_eq!(merge_input(Some(""), Some("")), None); + assert_eq!(merge_input(Some("piped"), None).as_deref(), Some("piped")); + assert_eq!(merge_input(None, Some("prompt")).as_deref(), Some("prompt")); + assert_eq!( + merge_input(Some(""), Some("prompt")).as_deref(), + Some("prompt") + ); + assert_eq!( + merge_input(Some("piped\n"), Some("prompt")).as_deref(), + Some("piped\n\nprompt") + ); + } +} diff --git a/packages/cli-rs/crates/mini/src/theme.rs b/packages/cli-rs/crates/mini/src/theme.rs new file mode 100644 index 00000000000..f51ca30d269 --- /dev/null +++ b/packages/cli-rs/crates/mini/src/theme.rs @@ -0,0 +1,587 @@ +//! The mini theme (`packages/tui/src/mini/theme.ts`): the TUI theme mapped to the few roles the split footer +//! and the scrollback use. Scrollback is immutable once written, so its colors are quantized to the terminal's +//! palette slots, and a palette change later still reads well. `mini.mono` uses the terminal's default colors +//! only. + +use std::path::PathBuf; + +use opencode_ui::theme::{ + Catalog, TerminalColors, Theme as UiTheme, ThemeMode, discover, generate_system, terminal_mode, +}; +use opentui::prelude::*; +use opentui::style::Intent; +use opentui::syntax::SyntaxTheme; +use opentui::term::TerminalPalette; +use opentui::widget::MarkdownColors; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Tone { + pub body: Color, + pub start: Option<Color>, +} + +/// One color per scrollback entry kind (`RunEntryTheme`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct EntryTheme { + pub system: Tone, + pub user: Tone, + pub assistant: Tone, + pub reasoning: Tone, + pub tool: Tone, + pub error: Tone, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SplashTheme { + pub left: Color, + pub right: Color, + pub left_shadow: Color, +} + +/// The footer's colors (`RunFooterTheme`). They are not quantized: the footer repaints. +#[derive(Clone, Debug, PartialEq)] +pub struct FooterTheme { + pub action_secondary_text: Color, + pub action_focused_bg: Color, + pub action_focused_text: Color, + pub formfield_text: Color, + pub formfield_focused_bg: Color, + pub formfield_focused_text: Color, + pub selection: Color, + pub running: Color, + pub question: Color, + pub permission: Color, + pub success: Color, + pub link: Color, + pub categorical: Vec<Color>, + pub warning: Color, + pub error: Color, + pub muted: Color, + pub text: Color, + pub shade: Color, + pub surface: Color, + pub pane: Color, + pub border: Color, + pub line: Color, +} + +/// Colors of structured blocks in the scrollback (`RunBlockTheme`). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct BlockTheme { + pub text: Color, + pub muted: Color, + pub faint: Color, + pub warning: Color, + pub diff_removed: Color, + pub diff_added_bg: Color, + pub diff_removed_bg: Color, + pub diff_context_bg: Color, + pub diff_highlight_added: Color, + pub diff_highlight_removed: Color, + pub diff_line_number: Color, + pub diff_added_line_number_bg: Color, + pub diff_removed_line_number_bg: Color, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct RunTheme { + pub background: Color, + pub footer: FooterTheme, + pub entry: EntryTheme, + pub splash: SplashTheme, + pub block: BlockTheme, + /// Code and Markdown highlighting, quantized like the entries; `None` in mono. + pub syntax: Option<SyntaxTheme>, + pub markdown: MarkdownColors, +} + +/// What the theme is resolved from. +#[derive(Clone, Debug, Default)] +pub struct ThemeInput { + /// `theme.name` from `cli.json`, `opencode` when unset. + pub name: Option<String>, + /// `theme.mode` from `cli.json`, used when the terminal does not report its background. + pub mode: Option<ThemeMode>, + /// The colors the terminal reported at startup. + pub palette: Option<TerminalPalette>, + /// Where custom themes live (`configDirectories`). + pub directories: Vec<PathBuf>, + pub mono: bool, +} + +/// `resolveRunTheme`. +pub fn resolve(input: &ThemeInput) -> RunTheme { + let colors = input + .palette + .as_ref() + .map(TerminalColors::from_palette) + .filter(TerminalColors::usable); + let mode = colors + .as_ref() + .and_then(terminal_mode) + .or(input.mode) + .unwrap_or(ThemeMode::Dark); + if input.mono { + return mono(mode); + } + let name = input.name.as_deref().unwrap_or("opencode"); + let indexed = indexed(input.palette.as_ref()); + if name == "system" && colors.is_none() { + return map(&fallback(mode), &indexed, false); + } + let mut catalog = Catalog::default(); + if name == "system" { + catalog.set_system(colors.as_ref().map(|colors| generate_system(colors, mode))); + } else if let Ok(custom) = discover(&input.directories) { + catalog.set_custom(custom); + } + // Mini keeps the terminal background, so a theme without this mode falls back to opencode. + let resolved = catalog + .load(name, mode) + .ok() + .filter(|loaded| loaded.mode == mode) + .map(|loaded| loaded.theme); + let system = name == "system" && resolved.is_some(); + let theme = resolved.unwrap_or_else(|| fallback(mode)); + let mut run = map(&theme, &indexed, system); + run.background = terminal_default( + input + .palette + .as_ref() + .and_then(|palette| palette.background) + .unwrap_or(theme.background.base), + ); + run +} + +fn fallback(mode: ThemeMode) -> UiTheme { + Catalog::default() + .load("opencode", mode) + .expect("the built-in opencode theme resolves") + .theme +} + +/// The 256 palette slots: the terminal's colors where it reported them, else xterm's. +fn indexed(palette: Option<&TerminalPalette>) -> Vec<(u8, Color)> { + (0..=255u8) + .map(|index| { + let reported = palette + .and_then(|palette| palette.colors.get(usize::from(index)).copied().flatten()); + let fallback = Color::indexed(index); + let color = reported.unwrap_or(fallback); + (index, Color::rgb(color.r, color.g, color.b)) + }) + .collect() +} + +/// The terminal's default color, with `color` as its snapshot (`RGBA.defaultForeground(color)`). +fn terminal_default(color: Color) -> Color { + Color::default_with(color.r, color.g, color.b) +} + +fn map(theme: &UiTheme, indexed: &[(u8, Color)], system: bool) -> RunTheme { + // The V1 system migration serializes colors; restore the terminal defaults before quantizing scrollback. + let exact = |color: Color| { + if system && color == theme.text.base { + return terminal_default(color); + } + if system && color == theme.background.base { + return terminal_default(color); + } + color + }; + let scrollback = |color: Color| { + let value = exact(color); + if value.a == 0 || value.intent() != Intent::Rgb { + return value; + } + nearest(indexed, value) + }; + let tone = |color: Color| Tone { + body: scrollback(color), + start: None, + }; + let text = &theme.text; + let mut categorical: Vec<Color> = Vec::new(); + for scale in theme.categorical() { + let color = exact(scale.step(200)); + if !categorical.contains(&color) { + categorical.push(color); + } + } + let mut syntax = opencode_ui::code::syntax_theme(theme); + let names: Vec<String> = syntax.names().map(str::to_owned).collect(); + for name in names { + if let Some(mut style) = syntax.get(&name) { + style.fg = style.fg.map(scrollback); + style.bg = style.bg.map(scrollback); + syntax.set(name, style); + } + } + let markdown = opencode_ui::markdown::colors(theme); + RunTheme { + background: terminal_default(theme.background.base), + footer: FooterTheme { + action_secondary_text: exact(text.action.secondary.base), + action_focused_bg: exact(theme.background.action.primary.focused), + action_focused_text: exact(text.action.primary.focused), + formfield_text: exact(text.formfield.base), + formfield_focused_bg: exact(theme.background.formfield.focused), + formfield_focused_text: exact(text.formfield.focused), + selection: exact(text.formfield.selected), + running: exact(theme.interactive().step(200)), + question: exact(theme.accent().step(200)), + permission: exact(theme.accent().step(200)), + success: exact(text.feedback.success.base), + link: exact(theme.markdown.link), + categorical, + warning: exact(text.feedback.warning.base), + error: exact(text.feedback.error.base), + muted: exact(text.muted), + text: exact(text.base), + shade: exact(theme.background.raised.base), + surface: exact(theme.background.raised.base), + pane: exact(theme.background.raised.high), + border: exact(theme.border.base), + line: exact(theme.background.raised.high), + }, + entry: EntryTheme { + system: tone(text.muted), + user: tone(text.base), + assistant: tone(theme.markdown.text), + reasoning: tone(text.muted), + tool: Tone { + body: scrollback(text.muted), + start: Some(scrollback(text.muted)), + }, + error: tone(text.feedback.error.base), + }, + splash: SplashTheme { + left: nearest(indexed, text.muted), + right: nearest(indexed, text.base), + left_shadow: nearest(indexed, theme.background.raised.base), + }, + block: BlockTheme { + text: scrollback(text.base), + muted: scrollback(text.muted), + faint: scrollback(text.faint), + warning: scrollback(text.feedback.warning.base), + diff_removed: scrollback(theme.diff.text.removed), + diff_added_bg: scrollback(theme.diff.background.added), + diff_removed_bg: scrollback(theme.diff.background.removed), + diff_context_bg: scrollback(theme.diff.background.context), + diff_highlight_added: scrollback(theme.diff.highlight.added), + diff_highlight_removed: scrollback(theme.diff.highlight.removed), + diff_line_number: scrollback(theme.diff.line_number.text), + diff_added_line_number_bg: scrollback(theme.diff.line_number.background.added), + diff_removed_line_number_bg: scrollback(theme.diff.line_number.background.removed), + }, + syntax: Some(syntax), + markdown: MarkdownColors { + text: scrollback(markdown.text), + heading: scrollback(markdown.heading), + emphasis: scrollback(markdown.emphasis), + code: scrollback(markdown.code), + // Mini keeps the terminal background behind code spans. + code_bg: Color::TRANSPARENT, + link: scrollback(markdown.link), + quote: scrollback(markdown.quote), + marker: scrollback(markdown.marker), + rule: scrollback(markdown.rule), + }, + } +} + +/// `monoTheme`: the terminal's default foreground and background only. +pub fn mono(mode: ThemeMode) -> RunTheme { + let (fg, bg) = match mode { + ThemeMode::Light => ( + Color::default_with(0, 0, 0), + Color::default_with(255, 255, 255), + ), + ThemeMode::Dark => ( + Color::default_with(255, 255, 255), + Color::default_with(0, 0, 0), + ), + }; + let tone = Tone { + body: fg, + start: None, + }; + RunTheme { + background: bg, + footer: FooterTheme { + action_secondary_text: fg, + action_focused_bg: bg, + action_focused_text: fg, + formfield_text: fg, + formfield_focused_bg: bg, + formfield_focused_text: fg, + selection: fg, + running: fg, + question: fg, + permission: fg, + success: fg, + link: fg, + categorical: vec![fg], + warning: fg, + error: fg, + muted: fg, + text: fg, + shade: bg, + surface: bg, + pane: bg, + border: fg, + line: bg, + }, + entry: EntryTheme { + system: tone, + user: tone, + assistant: tone, + reasoning: tone, + tool: tone, + error: tone, + }, + splash: SplashTheme { + left: fg, + right: fg, + left_shadow: bg, + }, + block: BlockTheme { + text: fg, + muted: fg, + faint: fg, + warning: fg, + diff_removed: fg, + diff_added_bg: bg, + diff_removed_bg: bg, + diff_context_bg: bg, + diff_highlight_added: fg, + diff_highlight_removed: fg, + diff_line_number: fg, + diff_added_line_number_bg: bg, + diff_removed_line_number_bg: bg, + }, + syntax: None, + markdown: MarkdownColors { + text: fg, + heading: fg, + emphasis: fg, + code: fg, + code_bg: Color::TRANSPARENT, + link: fg, + quote: fg, + marker: fg, + rule: fg, + }, + } +} + +/// `nearestIndexed`: the palette slot closest in OKLab, with lightness weighted double. +pub fn nearest(indexed: &[(u8, Color)], color: Color) -> Color { + let target = oklab(color); + let mut best = (f64::INFINITY, 0u8); + for (index, sample) in indexed { + let sample = oklab(*sample); + let (dl, da, db) = ( + sample.0 - target.0, + sample.1 - target.1, + sample.2 - target.2, + ); + let distance = dl * dl * 2.0 + da * da + db * db; + if distance < best.0 { + best = (distance, *index); + } + } + // The slot's snapshot is xterm's color; terminals with a palette draw their own. + Color::indexed(best.1) +} + +fn oklab(color: Color) -> (f64, f64, f64) { + let linear = |channel: u8| { + let value = f64::from(channel) / 255.0; + if value <= 0.04045 { + value / 12.92 + } else { + ((value + 0.055) / 1.055).powf(2.4) + } + }; + let (r, g, b) = (linear(color.r), linear(color.g), linear(color.b)); + let l = (0.412_221_470_8 * r + 0.536_332_536_3 * g + 0.051_445_992_9 * b).cbrt(); + let m = (0.211_903_498_2 * r + 0.680_699_545_1 * g + 0.107_396_956_6 * b).cbrt(); + let s = (0.088_302_461_9 * r + 0.281_718_837_6 * g + 0.629_978_700_5 * b).cbrt(); + ( + 0.210_454_255_3 * l + 0.793_617_785 * m - 0.004_072_046_8 * s, + 1.977_998_495_1 * l - 2.428_592_205 * m + 0.450_593_709_9 * s, + 0.025_904_037_1 * l + 0.782_771_766_2 * m - 0.808_675_766 * s, + ) +} + +/// `prefixes` of `mono.ts`: status glyphs at the start of a line. +fn prefix(c: char) -> Option<&'static str> { + Some(match c { + '\u{2192}' => "->", + '\u{2190}' => "<-", + '\u{2731}' | '\u{2699}' | '\u{25c8}' | '\u{25c9}' | '\u{27f3}' => "*", + '\u{2716}' | '\u{2717}' => "!", + _ => return None, + }) +} + +/// `markdown` of `mono.ts`: ASCII for the characters text commonly uses. +fn ascii(c: char) -> Option<&'static str> { + prefix(c).or(Some(match c { + '\u{a0}' => " ", + '\u{b7}' | '\u{2010}' | '\u{2011}' | '\u{2012}' | '\u{2013}' => "-", + '\u{2014}' => "--", + '\u{2018}' | '\u{2019}' => "'", + '\u{201c}' | '\u{201d}' => "\"", + '\u{2022}' => "*", + '\u{2026}' => "...", + '\u{2191}' => "up", + '\u{2193}' => "down", + _ => return None, + })) +} + +/// `monoText`: printable ASCII, tabs, and newlines stay; known characters become ASCII, others `?`. +pub fn mono_text(value: &str) -> String { + value + .chars() + .map(|c| match c { + '\t' | '\n' | ' '..='~' => c.to_string(), + c => ascii(c).unwrap_or("?").to_owned(), + }) + .collect() +} + +/// `monoPrefix`: a leading status glyph as ASCII. +pub fn mono_prefix(value: &str, mono: bool) -> String { + let mut chars = value.chars(); + match (mono, chars.next().and_then(prefix)) { + (true, Some(prefix)) => format!("{prefix}{}", chars.as_str()), + _ => value.to_owned(), + } +} + +/// `monoToolText`: `monoPrefix`, and ` - ` for the dot of a completed tool's summary. +pub fn mono_tool_text(value: &str, mono: bool) -> String { + let result = mono_prefix(value, mono); + if !mono { + return result; + } + let separator = " \u{b7} "; + let Some(index) = result.rfind(separator) else { + return result; + }; + let head = &result[..index]; + let questions = head + .strip_suffix(" questions") + .is_some_and(|count| !count.is_empty() && count.bytes().all(|b| b.is_ascii_digit())); + if !head.contains(" completed") && head != "patch" && !questions { + return result; + } + format!("{head} - {}", &result[index + separator.len()..]) +} + +/// `monoTruncate`. +pub fn mono_truncate(value: &str, width: usize, mono: bool) -> String { + let count = value.chars().count(); + if !mono || count <= width { + return value.to_owned(); + } + if width <= 3 { + return ".".repeat(width); + } + value.chars().take(width - 3).chain("...".chars()).collect() +} + +/// `monoSnapshot`: every non-ASCII cell of a scrollback snapshot as one ASCII character, colors kept. +pub fn mono_snapshot(buffer: &opentui::native::Buffer) -> opentui::Result<()> { + let capture = buffer.capture()?; + for y in 0..capture.height { + for x in 0..capture.width { + let Some(cell) = capture.cell(x, y) else { + continue; + }; + let mut chars = cell.symbol.chars(); + let character = match (chars.next(), chars.next()) { + (Some(c), None) if c.is_ascii() => continue, + // The trailing cell of a wide character. + (None, _) => ' ', + (Some('\u{2500}'), None) => '-', + (Some('\u{2502}'), None) => '|', + (Some(c), None) => ascii(c).and_then(|text| text.chars().next()).unwrap_or('?'), + // A grapheme cluster. + (Some(_), Some(_)) => '?', + }; + let style = Style { + fg: Some(cell.fg), + bg: Some(cell.bg), + attributes: cell.attributes, + }; + buffer.cell(x as i32, y as i32, character, style)?; + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn mono_text_matches_mono_ts() { + assert_eq!(mono_text("a — b… “q” • ✓\tx"), "a -- b... \"q\" * ?\tx"); + assert_eq!(mono_prefix("→ Skill", true), "-> Skill"); + assert_eq!(mono_prefix("→ Skill", false), "→ Skill"); + assert_eq!( + mono_tool_text("2 questions · done", true), + "2 questions - done" + ); + assert_eq!(mono_tool_text("read · a.ts", true), "read · a.ts"); + assert_eq!(mono_truncate("abcdefgh", 6, true), "abc..."); + } + + #[test] + fn nearest_picks_the_closest_slot() { + let slots = indexed(None); + assert_eq!( + nearest(&slots, Color::rgb(255, 0, 0)).intent(), + Intent::Indexed(9) + ); + assert_eq!( + nearest(&slots, Color::rgb(0, 0, 0)).intent(), + Intent::Indexed(0) + ); + // A gray lands on the gray ramp, not on a primary. + let gray = nearest(&slots, Color::rgb(0x80, 0x80, 0x80)); + assert!(matches!(gray.intent(), Intent::Indexed(8 | 244))); + } + + #[test] + fn scrollback_colors_are_palette_slots_and_footer_colors_are_not() { + let theme = resolve(&ThemeInput::default()); + assert!(matches!(theme.entry.user.body.intent(), Intent::Indexed(_))); + assert!(matches!(theme.markdown.text.intent(), Intent::Indexed(_))); + assert_eq!(theme.footer.text.intent(), Intent::Rgb); + assert_eq!(theme.background.intent(), Intent::Default); + } + + #[test] + fn mono_uses_default_colors_by_mode() { + let dark = resolve(&ThemeInput { + mono: true, + ..ThemeInput::default() + }); + assert_eq!(dark.entry.assistant.body.intent(), Intent::Default); + assert_eq!((dark.entry.user.body.r, dark.background.r), (255, 0)); + let light = resolve(&ThemeInput { + mono: true, + mode: Some(ThemeMode::Light), + ..ThemeInput::default() + }); + assert_eq!((light.entry.user.body.r, light.background.r), (0, 255)); + assert!(light.syntax.is_none()); + } +} diff --git a/packages/cli-rs/crates/mini/src/tools.rs b/packages/cli-rs/crates/mini/src/tools.rs new file mode 100644 index 00000000000..a9bc24315d6 --- /dev/null +++ b/packages/cli-rs/crates/mini/src/tools.rs @@ -0,0 +1,68 @@ +//! Tool rendering in the scrollback (`tool.ts`, `stream-v2.subagent.ts`): M.4. +//! +//! M.1 leaves the signatures the writer and the transcript call. Until M.4, tool parts print nothing, which is +//! what `mini.tools = "hide"`, the default, shows. + +use opentui::prelude::*; +use serde_json::Value; + +use crate::scrollback::{Body, BodyOptions, Commit}; +use crate::theme::RunTheme; + +/// A structured tool body (`ToolSnapshot`). +#[derive(Clone, Debug, PartialEq)] +pub enum Snapshot { + Code { + title: String, + content: String, + file: Option<String>, + }, + Diff { + items: Vec<DiffItem>, + }, + Task { + title: String, + rows: Vec<String>, + tail: String, + }, + Todo { + items: Vec<Value>, + }, + Question { + items: Vec<(String, String)>, + tail: String, + }, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct DiffItem { + pub title: String, + pub diff: String, + pub file: Option<String>, + pub deletions: Option<u64>, +} + +/// The commits of one tool part of a listed assistant message (`renderTool`, `toolCommit`). +pub fn commits(_message_id: &str, _part: &Value) -> Vec<Commit> { + Vec::new() +} + +/// `toolEntryBody`: what a tool commit draws. +pub fn entry_body(_commit: &Commit, _raw: &str, _options: BodyOptions) -> Option<Body> { + None +} + +/// `toolStructuredFinal`: whether a final tool commit draws a structured body, which groups on its own. +pub fn structured_final(_commit: &Commit) -> bool { + false +} + +/// The widget of a structured body (`RunEntryContent`'s snapshot cases). +pub fn structured_widget( + app: &App, + _snapshot: &Snapshot, + _theme: &RunTheme, + _mono: bool, +) -> AnyWidget { + Text::new(app, "").as_any() +} diff --git a/packages/cli-rs/crates/mini/src/variants.rs b/packages/cli-rs/crates/mini/src/variants.rs new file mode 100644 index 00000000000..a11e707141f --- /dev/null +++ b/packages/cli-rs/crates/mini/src/variants.rs @@ -0,0 +1,16 @@ +//! Models and variants (`variant.shared.ts`): M.4 adds variant cycling and the names from the provider list. + +/// A model selection (`{ providerID, modelID }`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ModelSelection { + pub provider_id: String, + pub model_id: String, +} + +/// `formatModelLabel`: `model · provider`, then the variant. M.1 has no provider list, so it shows the IDs. +pub fn format_model_label(model: &ModelSelection, variant: Option<&str>) -> String { + let variant = variant + .map(|variant| format!(" · {variant}")) + .unwrap_or_default(); + format!("{} · {}{variant}", model.model_id, model.provider_id) +} diff --git a/packages/cli-rs/parity/deviations/M01-mini-shell.md b/packages/cli-rs/parity/deviations/M01-mini-shell.md new file mode 100644 index 00000000000..ed2ff7b1f35 --- /dev/null +++ b/packages/cli-rs/parity/deviations/M01-mini-shell.md @@ -0,0 +1,37 @@ +# M01, M03, M11, M15: mini shell differences + +## Markdown after a resize replay (TypeScript defect) + +After a resize, TS `mini` writes assistant Markdown at the wrong column: at 34 columns, `Second answer:` comes out +as `Sec` / `ond answer:`, and `Third answer, the last one.` wraps after `the` although it fits. Prompts, errors, +and the entry header are right. The Rust client wraps them at the new width. `parity/scenarios/M.1/resize.pty.ts` +therefore replays a plain-text history (prompts and errors), which both clients write cell for cell. Seen with +`resize.pty.ts` at 24 and 34 columns over the Markdown history of `fixture.ts`. + +## Streaming Markdown commits complete blocks + +Core commits a streaming Markdown entry block by block from the renderable's block positions. opentui-rust's +Markdown widget does not expose them, so the Rust writer renders the text before the last blank line outside a +fence and commits those rows (`scrollback::stable_prefix`). A finished entry is the same; while it streams, a +paragraph shows once it is followed by a blank line or the entry ends. + +## Reasoning is drawn by the Markdown widget + +As in the TUI (`V04-reasoning-blocks.md`): TS draws reasoning with `<code filetype="markdown">`, whose conceal +hides `_Thinking:_`'s markers. opentui-rust's `Code` has no conceal, so the Markdown widget draws it in the +reasoning color. + +## SIGINT and SIGUSR2 + +- TS turns an external SIGINT into the two-press exit. In the Rust client the renderer owns SIGINT and ends the + app; mini then closes as on any exit (writes what is queued, leaves split mode, prints the newline). Ctrl+C in + the terminal is a key and keeps the two-press exit. +- SIGUSR2 resolves the theme again (custom theme files and `cli.json`'s theme as read at start) against the + palette the terminal reported at start. TS asks the terminal for its palette again; opentui-rust cannot query + the terminal while the app runs. + +## Scrollback colors + +Scrollback colors are quantized to the nearest palette slot as in TS. The slot's fallback snapshot is xterm's +color for that slot, not the color the terminal reported; terminals with a palette draw their own color either +way. diff --git a/packages/cli-rs/parity/scenarios/M.1/fixture.ts b/packages/cli-rs/parity/scenarios/M.1/fixture.ts new file mode 100644 index 00000000000..a6af418319d --- /dev/null +++ b/packages/cli-rs/parity/scenarios/M.1/fixture.ts @@ -0,0 +1,163 @@ +// A fake server for `mini`: one session `ses_mini` with a short history, an event stream that stays open, and +// the reads the split-footer transport makes when it hydrates. The splash is off in every case: it is M.4's. +import type { Logged, Options, Route } from "../../lib/fake-server" + +export const directory = "/tmp/mini" +export const location = { directory, project: { id: "proj_test", directory, canonical: directory } } +export const session = (id = "ses_mini", extra: Record<string, unknown> = {}) => ({ + id, + title: "Mini history", + projectID: "proj_test", + cost: 0, + tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, + time: { created: 1, updated: 1 }, + location: { directory }, + agent: "build", + model: { providerID: "demo", id: "model" }, + ...extra, +}) + +export const user = (id: string, text: string, created: number) => ({ + id, + type: "user", + sessionID: "ses_mini", + text, + time: { created }, +}) + +export const assistant = (id: string, content: unknown[], created: number) => ({ + id, + type: "assistant", + sessionID: "ses_mini", + agent: "build", + model: { providerID: "demo", id: "model" }, + content, + finish: "stop", + cost: 0, + tokens: { input: 5, output: 7, reasoning: 0, cache: { read: 0, write: 0 } }, + time: { created, completed: created + 1 }, +}) + +// Oldest first: three turns, the second with reasoning and a list. +export const history = [ + user("msg_u1", "first question", 10), + assistant("msg_a1", [{ type: "text", text: "First answer." }], 11), + user("msg_u2", "second question", 20), + assistant( + "msg_a2", + [ + { type: "reasoning", text: "Weighing the options." }, + { type: "text", text: "Second answer:\n\n- one\n- two" }, + ], + 21, + ), + user("msg_u3", "third question", 30), + assistant("msg_a3", [{ type: "text", text: "Third answer, the last one." }], 31), +] + +let counter = 0 +export const event = (type: string, data: Record<string, unknown>, created = 100) => ({ + id: `evt_${type.replace(/\W/g, "")}${String(++counter).padStart(8, "0")}`, + created, + type, + durable: { aggregateID: "ses_mini", seq: counter }, + data: { sessionID: "ses_mini", ...data }, +}) + +export function promptID(requests: Logged[]) { + const prompt = requests.findLast((entry) => entry.method === "POST" && entry.path.endsWith("/prompt")) + return (prompt?.body as { id?: string } | undefined)?.id ?? "msg_missing" +} + +// The message list honours `limit` and `order=desc` as the server does, so `--replay-limit` shows. +function listed(entry: Logged, requests: Logged[], base: unknown[], extra: (requests: Logged[]) => unknown[]) { + const all = [...base, ...extra(requests)] + const limit = Number(entry.query.limit?.[0] ?? all.length) + const desc = entry.query.order?.[0] === "desc" + const ordered = desc ? all.toReversed() : all + return { data: ordered.slice(0, limit), cursor: {} } +} + +// Plain-text entries only: prompts and errors. Core's Markdown wraps assistant text at the wrong column after a +// resize (see `parity/deviations/M01-mini-shell.md`), so the resize case leaves Markdown out. +export const plain = [ + user("msg_u1", "first question about a rather long topic", 10), + { + ...assistant("msg_a1", [], 11), + error: { _tag: "ProviderError", message: "The provider refused the first request" }, + }, + user("msg_u2", "second question", 20), + { ...assistant("msg_a2", [], 21), error: { _tag: "ProviderError", message: "Rate limited" } }, +] + +type Script = { + routes?: Route[] + // The session's history, oldest first; `history` by default. + messages?: unknown[] + // Messages after the history once a prompt was sent, given its ID. + after?: (id: string) => unknown[] + // Events pushed after the prompt, given its ID. + events?: (id: string) => unknown[] +} + +export function server(script: Script = {}): Options { + const after = (requests: Logged[]) => + requests.some((entry) => entry.method === "POST" && entry.path.endsWith("/prompt")) + ? (script.after?.(promptID(requests)) ?? []) + : [] + return { + routes: [ + ...(script.routes ?? []), + { path: "/api/location", json: location }, + { path: "/api/session/ses_mini", json: { data: session() } }, + { method: "POST", path: "/api/session", json: { data: session("ses_new", { title: "" }) } }, + { path: "/api/event", events: [{ id: "evt_connected0000", type: "server.connected", data: {} }] }, + { + method: "POST", + path: "/api/session/ses_mini/prompt", + json: (entry: Logged) => ({ + data: { + id: (entry.body as { id: string }).id, + sessionID: "ses_mini", + time: { created: 3 }, + type: "user", + payload: { text: (entry.body as { text: string }).text }, + delivery: "steer", + }, + }), + then: (entry: Logged) => script.events?.((entry.body as { id: string }).id) ?? [], + }, + { method: "POST", path: "/api/session/ses_mini/agent", status: 204 }, + { method: "POST", path: "/api/session/ses_mini/model", status: 204 }, + { method: "POST", path: "/api/experimental/session/ses_mini/wait", status: 204, delay: 200 }, + { path: "/api/session/ses_mini/permission", json: { data: [] } }, + { path: "/api/session/ses_mini/form", json: { data: [] } }, + { path: "/api/form", json: { location, data: [] } }, + { path: "/api/session/active", json: { data: {} } }, + { path: "/api/session/ses_mini/inbox", json: { data: [] } }, + { + path: "/api/session/ses_mini/message", + json: (entry: Logged, requests: Logged[]) => listed(entry, requests, script.messages ?? history, after), + }, + { path: "/api/model/default", json: { data: { providerID: "demo", id: "model" } } }, + // A new session (`mini` without `-s`): empty. + { path: "/api/session/ses_new/message", json: { data: [], cursor: {} } }, + { path: "/api/session/ses_new/inbox", json: { data: [] } }, + { path: "/api/session/ses_new/permission", json: { data: [] } }, + { path: "/api/session/ses_new/form", json: { data: [] } }, + ], + fallback: "tui", + } +} + +// `cli.json` for both sides: no splash (M.4), so the scrollback holds only the transcript. +export async function config(root: string, extra: Record<string, unknown> = {}) { + const file = `${root}/home/.config/opencode/cli.json` + await Bun.write(file, JSON.stringify({ mini: { splash: "hide", ...extra } })) +} + +// The footer's status row ends with the command menu's hint in TS; the menu is M.3's. +export const statusMask = { + pattern: /^Build · model · demo( · ctrl\+p menu)?$/, + reason: "the ctrl+p menu hint is M.3's", +} diff --git a/packages/cli-rs/parity/scenarios/M.1/flags.pty.ts b/packages/cli-rs/parity/scenarios/M.1/flags.pty.ts new file mode 100644 index 00000000000..99c944dea8a --- /dev/null +++ b/packages/cli-rs/parity/scenarios/M.1/flags.pty.ts @@ -0,0 +1,11 @@ +// Flag errors under a terminal: `--fork` without a session to fork. +import { definePty } from "../../pty/run" + +export default definePty({ + args: ["mini", "--fork"], + cols: 80, + rows: 6, + server: { routes: [] }, + steps: [{ until: { screen: "Error" }, settle: 300, checkpoint: "error" }], + exits: true, +}) diff --git a/packages/cli-rs/parity/scenarios/M.1/mono.pty.ts b/packages/cli-rs/parity/scenarios/M.1/mono.pty.ts new file mode 100644 index 00000000000..fa29e8edc80 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/M.1/mono.pty.ts @@ -0,0 +1,18 @@ +// `mini.mono = true`: the replayed transcript in ASCII (`>` prompts, `[O]` header, ` - ` separators). +import { definePty } from "../../pty/run" +import { config, server } from "./fixture" + +export default definePty({ + args: ["mini", "-s", "ses_mini"], + cols: 60, + rows: 16, + server: server(), + setup: (root) => config(root, { mono: true }), + steps: [ + { until: { screen: "Third answer" }, settle: 600, timeout: 30_000, checkpoint: "mono", scrollback: 16 }, + { keys: "\x03", settle: 200 }, + { keys: "\x03", settle: 400 }, + ], + exits: true, + masks: [{ pattern: /^Build - model - demo( - ctrl\+p menu)?$/, reason: "the ctrl+p menu hint is M.3's" }], +}) diff --git a/packages/cli-rs/parity/scenarios/M.1/no-replay.pty.ts b/packages/cli-rs/parity/scenarios/M.1/no-replay.pty.ts new file mode 100644 index 00000000000..b5a66769a82 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/M.1/no-replay.pty.ts @@ -0,0 +1,19 @@ +// `mini -s ses_mini --no-replay`: the terminal is still cleared for the resumed session, but its history is not +// written again. +import { definePty } from "../../pty/run" +import { config, server, statusMask } from "./fixture" + +export default definePty({ + args: ["mini", "-s", "ses_mini", "--no-replay"], + cols: 60, + rows: 16, + server: server(), + setup: (root) => config(root), + steps: [ + { until: { screen: "oc mini" }, settle: 800, timeout: 30_000, checkpoint: "cleared" }, + { keys: "\x03", settle: 200 }, + { keys: "\x03", settle: 400 }, + ], + exits: true, + masks: [statusMask], +}) diff --git a/packages/cli-rs/parity/scenarios/M.1/no-tty.cli.ts b/packages/cli-rs/parity/scenarios/M.1/no-tty.cli.ts new file mode 100644 index 00000000000..e16de7ee7a2 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/M.1/no-tty.cli.ts @@ -0,0 +1,7 @@ +// `mini` with stdout on a pipe fails before it connects. +import { defineCli } from "../../cli/run" + +export default defineCli({ + args: ["mini"], + server: { routes: [] }, +}) diff --git a/packages/cli-rs/parity/scenarios/M.1/replay-limit-zero.pty.ts b/packages/cli-rs/parity/scenarios/M.1/replay-limit-zero.pty.ts new file mode 100644 index 00000000000..662dc43f71e --- /dev/null +++ b/packages/cli-rs/parity/scenarios/M.1/replay-limit-zero.pty.ts @@ -0,0 +1,11 @@ +// `--replay-limit 0` is rejected before anything is drawn. +import { definePty } from "../../pty/run" + +export default definePty({ + args: ["mini", "--replay-limit", "0"], + cols: 80, + rows: 6, + server: { routes: [] }, + steps: [{ until: { screen: "Error" }, settle: 300, checkpoint: "error" }], + exits: true, +}) diff --git a/packages/cli-rs/parity/scenarios/M.1/replay-limit.pty.ts b/packages/cli-rs/parity/scenarios/M.1/replay-limit.pty.ts new file mode 100644 index 00000000000..36ba12717bc --- /dev/null +++ b/packages/cli-rs/parity/scenarios/M.1/replay-limit.pty.ts @@ -0,0 +1,18 @@ +// `mini -s ses_mini --replay-limit 2`: only the newest two messages are listed and replayed, below the header. +import { definePty } from "../../pty/run" +import { config, server, statusMask } from "./fixture" + +export default definePty({ + args: ["mini", "-s", "ses_mini", "--replay-limit", "2"], + cols: 60, + rows: 16, + server: server(), + setup: (root) => config(root), + steps: [ + { until: { screen: "Third answer" }, settle: 600, timeout: 30_000, checkpoint: "replayed", scrollback: 8 }, + { keys: "\x03", settle: 200 }, + { keys: "\x03", settle: 400 }, + ], + exits: true, + masks: [statusMask], +}) diff --git a/packages/cli-rs/parity/scenarios/M.1/resize.pty.ts b/packages/cli-rs/parity/scenarios/M.1/resize.pty.ts new file mode 100644 index 00000000000..7c92277516c --- /dev/null +++ b/packages/cli-rs/parity/scenarios/M.1/resize.pty.ts @@ -0,0 +1,20 @@ +// A resize replays the transcript at the new width: the terminal is cleared, the messages are listed again, and the +// header and the wrapped rows follow the new width. The history is plain text (prompts and errors). +import { definePty } from "../../pty/run" +import { config, plain, server, statusMask } from "./fixture" + +export default definePty({ + args: ["mini", "-s", "ses_mini"], + cols: 60, + rows: 16, + server: server({ messages: plain }), + setup: (root) => config(root), + steps: [ + { until: { screen: "Rate limited" }, settle: 600, timeout: 30_000 }, + { resize: { cols: 24, rows: 16 }, settle: 1500, checkpoint: "narrow", scrollback: 24 }, + { keys: "\x03", settle: 200 }, + { keys: "\x03", settle: 400 }, + ], + exits: true, + masks: [statusMask], +}) diff --git a/packages/cli-rs/parity/scenarios/M.1/resume.pty.ts b/packages/cli-rs/parity/scenarios/M.1/resume.pty.ts new file mode 100644 index 00000000000..cd4e4835f1d --- /dev/null +++ b/packages/cli-rs/parity/scenarios/M.1/resume.pty.ts @@ -0,0 +1,19 @@ +// `mini -s ses_mini`: the session's history is replayed into the scrollback above the footer, then Ctrl+C twice +// leaves split mode. The footer itself is M.2's and M.3's, so the rows below the transcript are masked. +import { definePty } from "../../pty/run" +import { config, server, statusMask } from "./fixture" + +export default definePty({ + args: ["mini", "-s", "ses_mini"], + cols: 60, + rows: 16, + server: server(), + setup: (root) => config(root), + steps: [ + { until: { screen: "Third answer" }, settle: 600, timeout: 30_000, checkpoint: "resume", scrollback: 16 }, + { keys: "\x03", settle: 200 }, + { keys: "\x03", settle: 400, checkpoint: "exit" }, + ], + exits: true, + masks: [statusMask], +}) diff --git a/packages/cli-rs/parity/scenarios/M.1/stdin.pty.ts b/packages/cli-rs/parity/scenarios/M.1/stdin.pty.ts new file mode 100644 index 00000000000..1b6cdb72c36 --- /dev/null +++ b/packages/cli-rs/parity/scenarios/M.1/stdin.pty.ts @@ -0,0 +1,50 @@ +// `printf 'piped text' | mini -s ses_mini --prompt 'from flag'`: the pipe and the flag become the first prompt, and +// keys still come from the terminal (Ctrl+C twice leaves). +import { definePty } from "../../pty/run" +import { command, withServer } from "../../cli/client" +import { config, event, server, statusMask, user, assistant } from "./fixture" + +const state = { server: "" } +const args = ["mini", "-s", "ses_mini", "--prompt", "from flag"] + +export default definePty({ + args, + command: (side) => { + const argv = command(side, withServer(args, state.server)).map((arg) => `'${arg.replaceAll("'", "'\\''")}'`) + return ["sh", "-c", `printf 'piped text' | ${argv.join(" ")}`] + }, + cols: 60, + rows: 20, + server: server({ + events: (id) => [ + event("session.inbox.delivered", { inboxID: id }), + event("session.execution.started", {}), + event("session.step.started", { + assistantMessageID: "msg_a4", + agent: "build", + model: { id: "model", providerID: "demo" }, + snapshot: "snap_1", + started: 101, + }), + event("session.text.delta", { assistantMessageID: "msg_a4", ordinal: 0, delta: "Got the " }), + event("session.text.delta", { assistantMessageID: "msg_a4", ordinal: 0, delta: "pipe." }), + event("session.text.ended", { assistantMessageID: "msg_a4", ordinal: 0, text: "Got the pipe." }), + event("session.execution.succeeded", {}), + ], + after: (id) => [ + user(id, "piped text\nfrom flag", 100), + assistant("msg_a4", [{ type: "text", text: "Got the pipe." }], 101), + ], + }), + setup: async (root, url) => { + state.server = url ?? "" + await config(root) + }, + steps: [ + { until: { screen: "Got the pipe." }, settle: 800, timeout: 30_000, checkpoint: "answered", scrollback: 6 }, + { keys: "\x03", settle: 200 }, + { keys: "\x03", settle: 400 }, + ], + exits: true, + masks: [statusMask], +}) diff --git a/packages/cli-rs/parity/scenarios/M.1/ttfd.pty.ts b/packages/cli-rs/parity/scenarios/M.1/ttfd.pty.ts new file mode 100644 index 00000000000..128d02ba48b --- /dev/null +++ b/packages/cli-rs/parity/scenarios/M.1/ttfd.pty.ts @@ -0,0 +1,19 @@ +// `OPENCODE_SHOW_TTFD=1` on a new session: the time to the first frame is the first row of the transcript. +import { definePty } from "../../pty/run" +import { config, server, statusMask } from "./fixture" + +export default definePty({ + args: ["mini"], + cols: 60, + rows: 10, + env: { OPENCODE_SHOW_TTFD: "1" }, + server: server(), + setup: (root) => config(root), + steps: [ + { until: { screen: /startup \d+ms/ }, settle: 600, timeout: 30_000, checkpoint: "startup" }, + { keys: "\x03", settle: 200 }, + { keys: "\x03", settle: 400 }, + ], + exits: true, + masks: [statusMask, { pattern: /startup \d+ms/, reason: "the time differs per run" }], +})