feat(cli-rs): add the mini shell (M.1)

opencode-rs mini runs in a split footer and writes the session's transcript to the scrollback above it: the flags, piped stdin, session resolution behind the first frame, replay on resume and resize with --replay-limit, the theme quantized to the palette and mono output, SIGUSR2 theme reload, OPENCODE_SHOW_TTFD and OPENCODE_DIRECT_TRACE. The prompt, request footers, and tool output are stubs for M.2 to M.4. P-PTY scenarios in parity/scenarios/M.1 match the TS mini.
This commit is contained in:
Simon Klee
2026-11-05 00:59:59 +01:00
Unverified
parent 6b6caff206
commit 7d656b33a7
29 changed files with 5156 additions and 6 deletions
+12
View File
@@ -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]]
@@ -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<String> = 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::<InputError>().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())
}
+15 -1
View File
@@ -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
@@ -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<FooterView> {
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<u16> {
None
}
}
+69 -1
View File
@@ -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<PathBuf>,
/// 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<String>,
/// `--replay`, else `mini.replay`, else true.
pub replay: bool,
/// `--replay-limit`, else `mini.replay_limit`.
pub replay_limit: Option<u32>,
pub config: Info,
pub version: String,
pub trace: Option<signals::Trace>,
/// When the command started, for `OPENCODE_SHOW_TTFD`.
pub start: Instant,
}
/// A failure mini reports as `Error: <message>` 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)
}
@@ -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<String>,
pub text: String,
/// File, agent, and skill mentions as the server takes them.
pub parts: Vec<serde_json::Value>,
pub delivery: Option<String>,
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<RefCell<Option<Box<dyn FnMut(&mut Cx<'_>, 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<RunPrompt>) {}
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())
}
File diff suppressed because it is too large Load Diff
@@ -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<String>,
pub phase: Phase,
pub source: Source,
pub compaction: bool,
pub summary: Option<TurnSummary>,
pub message_id: Option<String>,
pub part_id: Option<String>,
pub tool: Option<String>,
pub directory: Option<String>,
/// The tool part as the server sent it.
pub part: Option<Value>,
pub interrupted: bool,
pub tool_state: Option<ToolState>,
pub tool_error: Option<String>,
/// The command of a direct shell call.
pub shell: Option<String>,
}
impl Commit {
pub fn new(kind: EntryKind, source: Source, phase: Phase, text: impl Into<String>) -> 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<String>) -> Self {
self.message_id = Some(id.into());
self
}
pub fn part_id(mut self, id: impl Into<String>) -> 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<String>) -> Self {
Self::new(EntryKind::System, Source::System, Phase::Final, text)
}
/// An error line (`kind: "error", phase: "start"`).
pub fn error(text: impl Into<String>) -> 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<String>,
},
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<String> {
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<Body>,
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<Commit>,
rendered: Option<Commit>,
active: Option<Active>,
}
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<Active> {
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<bool> {
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 (`<code fg>`); 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<String> = 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"), "");
}
}
@@ -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);
}
}
File diff suppressed because it is too large Load Diff
+157
View File
@@ -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());
}
}
@@ -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))
}
+129
View File
@@ -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())
);
}
}
+75
View File
@@ -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")
);
}
}
+587
View File
@@ -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());
}
}
+68
View File
@@ -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()
}
@@ -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)
}
@@ -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.
+163
View File
@@ -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",
}
+11
View File
@@ -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,
})
+18
View File
@@ -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" }],
})
+19
View File
@@ -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],
})
+7
View File
@@ -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: [] },
})
@@ -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,
})
@@ -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],
})
+20
View File
@@ -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],
})
+19
View File
@@ -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],
})
+50
View File
@@ -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],
})
+19
View File
@@ -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" }],
})