docs(cli-rs): describe prompt and dialog behavior directly

Keep the reasons drafts survive remounts, edits cancel pending submits,
and writes run in order. Replace implementation history and TypeScript
line references with short descriptions of the behavior.
This commit is contained in:
Simon Klee
2026-11-18 20:44:34 +01:00
Unverified
parent a30c3d0e07
commit 2a3fe884ca
53 changed files with 140 additions and 369 deletions
@@ -1,4 +1,4 @@
//! Agent dialog (E.16): `component/dialog-agent.tsx`, "Select agent".
//! Agent picker.
use crate::local::Local;
use crate::prelude::*;
@@ -1,14 +1,11 @@
//! Debug dialog (E.18a): `packages/tui/src/component/dialog-debug.tsx`.
//!
//! The facts to paste into a bug report, one per row, and a copy action (`c`) that
//! puts them on the clipboard. Rows are not click-to-copy, so a mouse selection still copies a single value.
//! Debug details and clipboard export for bug reports.
use opencode_ui::dialog::{DIALOG_INSET, FooterAction, FooterProps, footer, layout_view};
use opencode_util::time;
use crate::prelude::*;
/// Like the TypeScript client, a build without `OPENCODE_VERSION` reports `local`.
/// Builds without an embedded version report `local`.
pub const VERSION: &str = match option_env!("OPENCODE_VERSION") {
Some(version) => version,
None => "local",
@@ -115,7 +112,7 @@ pub fn show(tui: &Tui) {
);
}
/// Redraws the footer after the current event, since a footer action runs inside the footer it replaces.
/// Defer redraw until the action returns; the redraw replaces its own footer.
fn redraw(tui: &Weak<Tui>, hook: &Hook) {
let (Some(tui), Some(draw)) = (tui.upgrade(), hook.borrow().as_ref().and_then(Weak::upgrade)) else { return };
tui.app.defer(move |_| draw());
@@ -1,4 +1,4 @@
//! TypeScript: `packages/tui/src/component/dialog-error-details.tsx`.
//! Error details with copy and investigation actions.
use opencode_ui::dialog::{DialogCx, FooterAction, FooterProps, footer};
@@ -1,6 +1,4 @@
//! Execute dialog (E.7b): `DialogExecute` (`routes/session/dialog-execute.tsx`). The code and the
//! output of a code-mode `execute` call, with copy actions. It follows the call while it runs: the
//! transcript row passes each new state to [`Live::set`].
//! Code-mode execution details and nested tool calls.
use opencode_api::generated::{SessionMessageAssistantTool, SessionMessageAssistantToolState, ToolContent};
use opencode_ui::dialog::{DIALOG_INSET, DialogCx, FooterAction, FooterProps, footer};
@@ -1,4 +1,4 @@
//! TypeScript: `packages/tui/src/component/dialog-experiments.tsx`.
//! Opt-in feature settings.
use opencode_ui::select::select;
@@ -12,9 +12,7 @@ pub struct Experiment {
pub description: &'static str,
}
/// In-flight features anyone can opt into. Each entry is temporary: an experiment either graduates (delete the
/// entry, make the behavior unconditional) or dies (delete the entry and the branch it gated). `new-designs`
/// graduated here: the Rust client draws only the new designs, though the TypeScript TUI still lists it.
/// Experiments available in the settings dialog.
pub const EXPERIMENTS: &[Experiment] = &[Experiment {
id: "client-mcp",
title: "TUI tools",
@@ -35,8 +33,7 @@ fn options(tui: &Tui) -> Vec<SelectOption<&'static str>> {
.collect()
}
/// Flips experiment `id`. All experiments are booleans, so either direction toggles. While `saving` holds, the
/// previous change is still being written and this one is ignored, as in TS.
/// Toggle the experiment unless its previous save is pending.
fn toggle(tui: &Tui, saving: &Rc<Cell<bool>>, id: &'static str) {
if saving.get() {
return;
@@ -1,7 +1,4 @@
//! Export dialogs (E.10a, rows DLG31 and DLG32): `ui/dialog-export-options.tsx` and `ui/dialog-export-result.tsx`,
//! as they look under `new-designs`. The options pick a format (Markdown with or without thinking and tools, or
//! JSON, sanitized or not), where a saved file goes, and an action (copy or save to a file); the result shows where
//! the file went.
//! Session export options and result dialogs.
use opencode_ui::dialog::{DIALOG_INSET, FooterAction, FooterProps, layout_with};
use opencode_ui::select::{ActionRun, FooterHint, Group, SelectAction};
@@ -1,4 +1,4 @@
//! TypeScript: `component/dialog-workspace-file-changes.tsx`.
//! Worktree changes and the actions available for them.
use opencode_api::generated::{FileDiffInfoStatus, VcsFileStatus};
use opencode_ui::dialog::{DIALOG_INSET, FooterAction, FooterProps, layout};
@@ -1,6 +1,4 @@
//! Fork dialog (E.10a, row DLG37): `routes/session/dialog-fork.tsx`. "Full session", then the session's prompts,
//! newest first. A pick forks the session before that prompt (`POST /api/session/:id/fork`), opens the fork, and
//! puts the prompt back in its composer.
//! Fork a session in full or before a selected prompt.
use opencode_api::generated::{SessionForkInput, SessionMessageID};
use opencode_ui::dialog::{DIALOG_LIST_INSET, layout_with};
@@ -47,7 +45,7 @@ pub fn show(tui: &Tui, session: SessionID, message: Option<String>, on_move: OnM
);
}
/// `fork`: shows "Forking session…", forks, then opens the fork with the prompt it was forked before.
/// Open the fork with the selected prompt ready to edit.
fn fork(tui: &Tui, session: SessionID, message: Option<String>) {
pending(tui);
let prompt = message.as_deref().and_then(|message| {
@@ -1,5 +1,4 @@
//! Free models dialog (E.16): `component/dialog-model-free.tsx`, the model picker while no provider is
//! connected.
//! Model picker for users without a connected provider.
use opencode_api::generated::ModelInfoStatus;
use opencode_local::model_pref::Model;
@@ -1,4 +1,4 @@
//! TypeScript: `component/dialog-go-upsell.tsx`, `routes/session/index.tsx:633-758`.
//! OpenCode Go subscription offer and device sign-in.
use opencode_api::generated::{
ConnectionInfo, IntegrationAttempt, IntegrationAttemptID, IntegrationID, IntegrationMethod, IntegrationMethodID,
@@ -64,9 +64,8 @@ pub struct Offer {
pub on_subscribe: Rc<dyn Fn()>,
}
/// Offers OpenCode Go at most once a day across clients, unless "don't show again" was chosen
/// (`routes/session/index.tsx:682-757`). The session route calls this when `provider.free-limit` stops a turn and
/// the prompt came back empty-handed.
/// Offer at most once a day across clients. Respect dismissal preferences and check the current session before showing
/// the offer.
pub fn offer(local: &Rc<Local>, offer: Offer, now: f64) {
if local.dialogs.is_open() {
return;
@@ -276,7 +275,7 @@ fn build(cx: &Rc<DialogCx>, local: &Rc<Local>, offer: Offer) -> View {
let compact = short || height < if narrow { 26 } else { 22 };
let mut art = None;
if compact {
// TS's scrollbox takes its whole `maxHeight`, so the panel reaches the buttons at the bottom.
// Reserve the full scroll area to keep the buttons at the bottom.
let top = if short { 1 } else { height / 4 + 1 };
let footer_rows = if narrow { ACTIONS.len() as u16 } else { 1 };
let gaps = if short { 1 } else { 4 };
@@ -1,9 +1,4 @@
//! The Go upsell's art (E.16): `component/go-upsell-art.ts`. Rings radiate from the GO logo while a shimmer crosses
//! it, at 30 frames a second while animations run; with them off it shows the frame halfway through the period.
//!
//! Colors are quantized after every mix, as Core 0.8.4's `RGBA` setters store bytes. TS takes its half-block path
//! only when the terminal reports 24-bit color; OpenTUI's Rust crates expose no color depth, so this always takes it
//! (DLG07).
//! Animate the Go logo with a shimmer and expanding rings.
use std::cell::OnceCell;
use std::f64::consts::PI;
@@ -1,5 +1,4 @@
//! Release highlights dialog (E.18b): `packages/tui/src/component/dialog-highlights.tsx`, "What's new in …".
//! `features::highlights` opens it from `/highlights` and once after an update.
//! Release highlights dialog.
use opencode_ui::dialog::{DIALOG_INSET, FooterAction, FooterProps, layout};
use serde::Deserialize;
@@ -1,9 +1,4 @@
//! Image preview dialog (E.4, row DLG09): `packages/tui/src/component/dialog-image-preview.tsx`.
//!
//! "Image N of M": one image at a time, fitted to the dialog (extra large, centered), with Left and Right
//! (or the footer's previous and next) moving through them. The footer names the image by its prompt
//! label, or `No preview` when it does not load. A `media:` ref reads its bytes from the server once
//! (`createMediaSource`).
//! Full-size image preview with navigation between attachments.
use opencode_api::generated::{ExperimentalMediaGetInput, MediaHash};
use opencode_ui::dialog::{DialogCx, FooterAction, FooterProps, layout};
@@ -1,8 +1,4 @@
//! A connect method's form, one dialog per field (`formAnswer` and its field dialogs in
//! `component/dialog-integration.tsx:862-1247`).
//!
//! Each field replaces the dialog. Closing a field's dialog cancels the whole form; the next field's `replace`
//! closes the previous one too, so each step resolves once and ignores the close that follows.
//! Collect integration credentials one field at a time.
use opencode_api::generated::{
FormAnswer, FormBooleanField, FormExternalField, FormField, FormMultiselectField, FormStringField, FormValue,
@@ -34,7 +30,7 @@ struct Run {
done: RefCell<Option<Done>>,
}
/// Asks `fields` in order and calls `done` with the answer, or `None` when a field's dialog was closed.
/// Ask the fields in order. Closing a field dialog returns `None`.
pub(super) fn answer(
local: &Rc<Local>,
title: String,
@@ -369,7 +365,7 @@ fn custom(local: &Rc<Local>, title: String, field: Rc<FormMultiselectField>, sel
);
}
/// `externalAnswer`: open the field's link, then confirm once it was opened.
/// Confirm only after opening the external link.
fn external(local: &Rc<Local>, title: String, field: FormExternalField, opened: bool, resolve: Resolve) {
let mut open = SelectOption::new(if opened { "Open link again" } else { "Open link" }, true);
open.description = Some(field.url.clone());
@@ -1,13 +1,4 @@
//! "Connect an integration" (E.17a, row DLG10): `component/dialog-integration.tsx`.
//!
//! The list of integrations (`/connect`, the model dialog's connect action, the prompt without a model, the
//! sidebar's getting-started link, and the MCP dialog for a server that signs in through an integration), the
//! accounts of a connected integration (activate, rename, remove), the method picker, and the four ways to
//! connect: an API key, OAuth in the browser (an automatic or a pasted code), an external connect, and a command.
//! A method with a form asks its fields first (`form.rs`).
//!
//! Everything reads and refreshes the catalog of [`Local`]. Browsers open through `Local::open_url`, which tests
//! replace.
//! Manage integration accounts and connect using a key, browser, external link, or command.
mod form;
@@ -62,8 +53,7 @@ pub fn show(local: &Rc<Local>, on_connected: Option<OnConnected>) {
open_list(Flow { local: local.clone(), on_connected }, None);
}
/// `DialogIntegration { integrationID, autoConnect }`, which the MCP dialog (E.17b) opens for a server that needs
/// sign-in: the integration's accounts or methods at once. Without `on_connected`, a connect closes the dialog.
/// Open the named integration's sign-in method directly from the MCP dialog.
pub fn show_auto_connect(tui: &Tui, integration: &IntegrationID, on_connected: Option<OnConnected>) {
open_list(Flow { local: tui.local.clone(), on_connected }, Some(integration.clone()));
}
@@ -200,7 +190,7 @@ fn listed(local: &Local, only: Option<&IntegrationID>) -> Vec<IntegrationInfo> {
fn open_list(flow: Flow, only: Option<IntegrationID>) {
let local = flow.local.clone();
// An auto-connect may name an integration that appeared after the catalog was read.
// Refresh the catalog in case it predates the requested integration.
if local.integrations().is_none() || only.as_ref().is_some_and(|id| flow.latest(id).is_none()) {
local.load_integrations();
}
@@ -726,8 +716,7 @@ fn key_prompt(flow: &Flow, integration: IntegrationInfo, title: String, answer:
);
}
/// An error line that starts empty, and its setter. With `boxed`, the line sits in a `<box gap={1}>` that the
/// layout keeps even while empty, as the TS descriptions that wrap their `<Show>` in a box do.
/// Error message and its setter. A boxed line reserves spacing even when empty.
fn error_slot(cx: &Rc<DialogCx>, boxed: bool) -> (View, Rc<dyn Fn(String)>) {
let line = Text::new(&cx.app, "").fg(cx.theme.text.feedback.error.base).visible(false);
let slot = View::new(&cx.app).gap(1).child(&line);
@@ -948,8 +937,8 @@ impl Oauth {
);
}
/// `OAuthAuto` for an attempt with `paste`: a field for the URL the browser was redirected to, for a browser
/// that cannot reach this machine. Enter on an empty field opens the link; the status poll still settles it.
/// Accept the redirect URL from another machine. An empty submission opens the link; polling still detects
/// completion.
fn paste(self: &Rc<Self>) {
let me = self.clone();
self.flow.local.dialogs.replace(
@@ -1,4 +1,4 @@
//! TypeScript: `packages/tui/src/component/dialog-mcp.tsx`.
//! MCP server status and actions.
use opencode_api::generated::{
ExperimentalMcpConnectInput, ExperimentalMcpDisconnectInput, LocationQueryInput, McpServer, McpServerStatus,
@@ -76,7 +76,7 @@ pub fn show_server(tui: &Tui, initial: Option<String>, details: bool) {
handle.move_to(name);
}
*mcp.select.borrow_mut() = Some(handle);
// The footer reads the selection through the handle, which exists only now.
// Refresh the footer once the selection handle exists.
mcp.refresh();
if let Some(tui) = mcp.tui.upgrade() {
// Refreshes the list after each store flush that touched the location.
@@ -1,5 +1,4 @@
//! Message actions dialog (E.10b, row DLG38): `routes/session/dialog-message.tsx`. A click on a user message, or
//! Enter in the timeline (E.10a), opens it: jump to the message, revert to it, copy its text, or fork before it.
//! Jump to, revert, copy, or fork from a user message.
use opencode_api::generated::{SessionMessageAssistantContentItem, SessionMessageID, SessionRevertStageInput};
use opencode_ui::dialog::Dialogs;
@@ -1,4 +1,4 @@
//! TypeScript: `component/dialog-model.tsx`, `component/model-options.tsx`, `app.tsx:903-1018`.
//! Model selection, favorites, and usage alerts.
use opencode_api::generated::{ModelInfo, ModelInfoStatus, ProviderInfo};
use opencode_api::js::locale_compare;
@@ -396,8 +396,7 @@ pub fn install(tui: &Rc<Tui>) {
local.load();
}
/// Applies `--agent` and `--model` once the agents, the models, and `model.json` have loaded (`app.tsx:666-678`).
/// `model` is already parsed; an invalid one only got its toast.
/// Apply startup agent and model choices when their catalogs and saved preferences are available.
pub fn startup(local: &Rc<Local>, agent: Option<String>, model: Option<Model>) {
if agent.is_none() && model.is_none() {
return;
@@ -418,8 +417,7 @@ pub fn startup(local: &Rc<Local>, agent: Option<String>, model: Option<Model>) {
if let Some(agent) = agent {
local.set_agent(&agent);
}
// TS sets it before it opens `-s` or `-c`'s session (`app.tsx:666-686`), so a session already open
// keeps its own model and `--model` only joins the recent models.
// A session opened at startup keeps its own model; the flag still updates recents.
match model {
Some(model) if local.route().is_some() => local.add_recent_valid(&model),
Some(model) => local.set(&model, true),
@@ -431,8 +429,7 @@ pub fn startup(local: &Rc<Local>, agent: Option<String>, model: Option<Model>) {
apply();
}
/// `useUsageAlerts` (`usage.tsx:224-251`): on a session, warns once per model as the selected model runs low and once
/// as it reaches its limit.
/// Warn once per model as it approaches and reaches a limit.
pub fn usage_alerts(local: &Local) {
use crate::dialogs::usage::{Level, format_dollars, format_reset, level};
if local.route().is_none() {
+5 -11
View File
@@ -1,8 +1,4 @@
//! Open dialog (E.11a, row DLG14): `packages/tui/src/component/dialog-open.tsx`.
//!
//! "Open": recent root sessions (those awaiting input first) and the projects, in two sections
//! with `alt+up`/`alt+down` between them. An exact session ID finds a session outside the recent
//! list. `right` on a Git project lists its worktrees, where `ctrl+n` creates one.
//! Open a recent session or worktree.
use opencode_api::generated::{
ProjectID, SessionGetInput, SessionInfo, SessionListInput, SessionListInputOrder, WorktreeCreateInput,
@@ -25,7 +21,7 @@ pub const KEY: &str = "open";
const RECENT_LIMIT: usize = 8;
thread_local! {
/// `openSessions` in `app.tsx:555`: the last recent read, shown at once when the dialog reopens.
/// Show the last recent-session result immediately on reopen.
static RECENT: RefCell<Vec<SessionInfo>> = const { RefCell::new(Vec::new()) };
static OPEN: RefCell<Weak<Open>> = const { RefCell::new(Weak::new()) };
}
@@ -276,7 +272,7 @@ impl Open {
let mut state = open.state.borrow_mut();
state.recent = Some(recent.is_ok());
if let Ok(response) = recent {
// A session deleted while the read was in flight stays out.
// Do not resurrect sessions deleted during the read.
let sessions: Vec<SessionInfo> = tui.data.read(|store| {
response.data.into_iter().filter(|session| !store.is_missing(&session.id)).collect()
});
@@ -291,8 +287,7 @@ impl Open {
);
}
/// Reads the requests of running sessions and the root sessions that wait on one, so their rows show and sort
/// by attention (`dialog-open.tsx:178-196`).
/// Read pending requests so sessions needing attention appear in priority order.
fn sync_attention(&self) {
let Some(tui) = self.tui() else { return };
let state = self.state.borrow();
@@ -426,7 +421,6 @@ impl Open {
}
};
drop(state);
// Hidden when empty, so it takes no place in the footer row and draws no band (TS renders nothing).
self.footer.visible(line.is_some());
if let Some(line) = line {
self.footer.add(&line);
@@ -729,7 +723,7 @@ impl Open {
async move { client.worktree_create(&input).await },
bind!(self, |open, _, result| {
let Some(tui) = open.tui() else { return };
// The prompt closed or was replaced while the request ran.
// Ignore a completion for a prompt that no longer exists.
let Some(current) = open.prompt.borrow().clone() else { return };
match result {
Ok(created) => {
@@ -1,8 +1,4 @@
//! Pair dialog (E.18b): `packages/tui/src/component/dialog-pair.tsx`, `server.pair` (`/pair`, `/web`).
//!
//! It reads `GET /api/info` and asks `POST /api/pair` for a one-time code, then shows a connect link for each
//! server URL, one for this device on `localhost`, and a QR code of the first link (`renderUnicodeCompact`).
//! Opening the dialog creates a pairing code on the server, so tests prove it against a test transport only.
//! Pair a device with the active server.
use opencode_api::generated::{PairingCode, ServerInfo};
use opencode_ui::dialog::{DialogCx, layout};
@@ -1,6 +1,4 @@
//! Pending steer dialog (E.10b, row DLG40): a click on a user message still waiting to steer
//! (`routes/session/index.tsx:2398-2414`). "Move to queue" queues it and "Delete" cancels it; the dialog closes once
//! the server took the change.
//! Move a pending steer back into the queue or delete it.
use crate::prelude::*;
use crate::routes::session::queued::{self, Action};
@@ -1,6 +1,4 @@
//! Queued prompts dialog (E.10b, row DLG41): `openQueuedPrompts` (`routes/session/index.tsx:788-844`). The
//! session's queued prompts with `1 of n` footers; Enter steers one, `queued_prompt.delete` cancels it, and
//! `queued_prompt.undo` takes it back into the composer. The list follows the inbox while the dialog is open.
//! Inspect, steer, undo, or delete queued prompts.
use opencode_ui::select::{FooterHint, Group, Select, SelectAction};
@@ -87,7 +85,7 @@ impl List {
});
}
/// Cancels the prompt; the dialog closes when it was the last one.
/// Cancel the prompt and close the dialog if the queue is empty.
fn delete(&self, inbox: &str) {
let (Some(tui), Some(view)) = (self.tui.upgrade(), self.view.upgrade()) else { return };
let last = tui.data.read(|state| queued::prompts(state, &view.session).len() == 1);
@@ -1,4 +1,4 @@
//! TypeScript: `packages/tui/src/component/dialog-session-rename.tsx`.
//! Rename a session or generate its title.
use opencode_api::generated::SessionUpdateInput;
use opencode_ui::prompt::{PromptProps, prompt};
@@ -1,8 +1,4 @@
//! Session list dialog (E.11a, row DLG16): `packages/tui/src/component/dialog-session-list.tsx`.
//!
//! "Sessions": the root sessions of the picker's location (or of every project, `ctrl+a`), newest
//! first under date headings, with pinned sessions on top. The list is read from the server with
//! the typed search, debounced by 150 ms. Actions: open, pin, delete (press twice), and rename.
//! Search and manage sessions in the current location or across projects.
use std::collections::HashSet;
use std::path::PathBuf;
@@ -648,10 +644,7 @@ fn resolve_up(flavor: Flavor, directory: &str, ups: usize) -> String {
flavor.resolve(&paths)
}
/// Pinned sessions in `<state>/session.json` (`context/local.tsx:508-603`), shared with the TS
/// TUI. Read once per state directory and kept in memory, as TS does. Each pin, unpin, and prune is
/// written in order on one worker thread, under the file's lock, from what the file holds then
/// (`opencode_local::pins`).
/// Pinned sessions in `<state>/session.json`, shared across clients. Keep writes ordered for each state directory.
pub mod pins {
use std::sync::OnceLock;
@@ -1,10 +1,4 @@
//! Settings dialog (E.18a): `packages/tui/src/component/dialog-config.tsx`.
//!
//! [`SETTINGS`] is the TS `settings` table. The dialog lists them by category with the current value as the
//! footer; Enter and Right step to the next value, Left to the previous one. Each change is one `cli.json`
//! update by path, queued on a worker thread because the file lock blocks. [`Live`] holds the resolved config
//! that every reader queries; writes and outside `cli.json` edits replace it, so everything follows a change
//! without a restart.
//! Settings writes run on a worker because the config lock blocks. File changes refresh the live configuration.
use std::cell::Ref;
use std::collections::VecDeque;
@@ -120,7 +114,7 @@ use Lit::Str as S;
use crate::prelude::*;
/// The TS `settings` table, in its order (`dialog-config.tsx:27-382`).
/// Settings in display order.
pub const SETTINGS: &[Setting] = &[
choice(
"Theme",
@@ -452,7 +446,7 @@ pub const SETTINGS: &[Setting] = &[
type Listener = Rc<dyn Fn(&Tui)>;
/// What a write runs when it lands, in the order writes were queued.
/// Completion callbacks in write order.
type Done = Box<dyn FnOnce(&Tui)>;
pub struct Live {
@@ -494,7 +488,7 @@ impl Live {
}
}
/// The resolved config now (`useConfig().data`). Keep the borrow short: a change replaces it.
/// Borrow the current configuration briefly; a change replaces it.
pub fn config(&self) -> Ref<'_, Resolved> {
self.resolved.borrow()
}
@@ -676,8 +670,7 @@ pub fn display(tui: &Tui, setting: &Setting) -> String {
.map_or_else(|| js_string(&current), |label| (*label).to_owned())
}
/// Steps `SETTINGS[index]` by `direction` and writes it (`change` in `dialog-config.tsx`).
/// While `saving` holds, the dialog's previous step is still being written and this one is ignored, as in TS.
/// Step the selected value and save it. Ignore additional steps until the write completes.
fn change(tui: &Tui, saving: &Rc<Cell<bool>>, index: usize, direction: i32) {
if saving.get() {
return;
@@ -721,7 +714,7 @@ fn options(tui: &Tui) -> Vec<SelectOption<usize>> {
.collect()
}
/// The palette's settings rows (`settingOptions` in `command-palette.tsx`), shown while filtering.
/// Settings commands shown while filtering the palette.
pub fn palette_options(tui: &Tui) -> Vec<SelectOption<String>> {
SETTINGS
.iter()
@@ -1,8 +1,4 @@
//! Shell output dialog (E.13b, row DLG18): `packages/tui/src/component/dialog-shell-output.tsx`.
//!
//! The composer's Shell tab opens it for a running command. It polls the shell's info and output while it is open,
//! even after the command exits, so the last flush shows: the newest 64 KiB first, then each new page, one second
//! apart once it has caught up.
//! Interactive shell output with paging, live follow, and copy actions.
use opencode_api::client::Client;
use opencode_api::error::Error;
@@ -229,7 +225,7 @@ impl Poll {
let mut output = self.output.borrow_mut();
let mut next = output.take().unwrap_or_default();
next.push_str(&loaded.page.output);
// Like `next.slice(-PAGE_BYTES)` in UTF-16 code units, without starting on half a character.
// The tail limit counts UTF-16 units but must not split a character.
let tail = text_boundary::tail(&next, PAGE_BYTES as usize);
if tail.len() < next.len() {
self.omitted.set(true);
@@ -1,8 +1,4 @@
//! Skills dialog (E.17b, row DLG19): `packages/tui/src/component/dialog-skill.tsx`.
//!
//! "Skills": the location's skills, read once if the store has none, with the description after
//! the padded name. Choosing one hands its ID to the caller and closes the dialog; the prompt
//! inserts an `@skill` mention as a prompt part (`prompt::autocomplete::parts::insert_skill`).
//! Select a skill to insert it into the prompt.
use opencode_api::generated::{SkillID, SkillInfo};
use opencode_store::{Catalog, Location};
@@ -102,7 +98,7 @@ fn open(tui: &Tui, load: Load, on_select: OnSelect) -> Rc<Cell<bool>> {
}
fn options(skills: &[SkillInfo]) -> Vec<SelectOption<SkillID>> {
// `padEnd` counts UTF-16 units; skill names are ASCII identifiers.
// Skill names are ASCII, so character counts match UTF-16 padding here.
let width = skills.iter().map(|skill| skill.name.0.chars().count()).max().unwrap_or(0);
skills
.iter()
@@ -1,8 +1,4 @@
//! Stash dialog (E.4, row DLG20): `packages/tui/src/component/dialog-stash.tsx`.
//!
//! "Stash": the stashed prompts, newest first, each with its first line, when it was stashed, and
//! `~N lines` for longer ones. Choosing one takes it out of the stash and hands it to the prompt;
//! `stash.delete` (Ctrl+D) deletes on the second press.
//! Restore or delete stashed prompts.
use opencode_ui::select::{Select, SelectAction};
use opencode_util::time::Zone;
@@ -1,5 +1,4 @@
//! Status dialog (E.18b): `packages/tui/src/component/dialog-status.tsx`, `opencode.status` (`/status`,
//! `<leader>s`). It lists the default location's MCP servers and follows the store while it is open.
//! Status of services at the default location.
use opencode_api::generated::{McpServer, McpServerStatus};
use opencode_store::Catalog;
@@ -92,7 +91,7 @@ fn color(theme: &Theme, status: &McpServerStatus) -> Color {
}
}
/// The muted text after the name; an unknown status shows its name, as the TS `Switch` fallback does.
/// Display unknown statuses by name.
fn describe(status: &McpServerStatus) -> String {
match status {
McpServerStatus::Connected(_) => "Connected".to_owned(),
@@ -1,9 +1,4 @@
//! Themes dialog (E.18b): `packages/tui/src/component/dialog-theme-list.tsx`, `/themes` (`theme.switch`) and
//! Settings → Theme.
//!
//! Moving, or filtering to a first match, previews the theme; Enter keeps it and Escape restores the theme the
//! dialog opened with. A preview stays in memory and only Enter writes `theme.name`; TS writes on every move and
//! writes the old name back on cancel, which leaves the same file.
//! Preview themes while browsing; persist the choice only on Enter.
use opencode_ui::select::{Select, select};
@@ -125,7 +120,7 @@ impl List {
}
}
/// `onCleanup`: restores the opening theme unless one was picked.
/// Restore the opening theme on cancel.
fn closed(&self) {
if self.confirmed.get() {
return;
@@ -1,5 +1,4 @@
//! Timeline dialog (E.10a, row DLG39): `routes/session/dialog-timeline.tsx`. The session's prompts, newest
//! first; moving jumps the transcript to the prompt, and Enter opens the message actions (E.10b).
//! Browse prompts newest first and jump to the highlighted message.
use opencode_util::time::Zone;
@@ -1,9 +1,4 @@
//! Update dialog (E.18b): `packages/tui/src/component/dialog-update.tsx`. `features::update_notification` opens it
//! from `/update` and the home notice, and owns the state it shows.
//!
//! Opening it with `checks` runs a check of the updater. Its buttons are `Skip`, which dismisses the notice, then
//! `Update` to install or `Restart` after an install; the last one starts active. The arrows and Tab move between
//! them and Enter runs the active one.
//! Update check and installation dialog.
use opencode_ui::dialog::{DialogButton, DialogButtons, DialogCx};
use opencode_ui::motion::Spinner;
@@ -1,6 +1,4 @@
//! Usage dialog (E.16): `/usage` in `component/usage.tsx`, on the limit math of `util/usage-limits.ts`.
//!
//! The limits come from `GET /api/experimental/usage/limits`, which asks OpenCode Console.
//! Workspace usage limits and account status.
use opencode_api::generated::{
ModelInfo, ProviderInfo, UsageLimitsBudget, UsageLimitsBudgetCoverage, UsageLimitsBudgetPer,
@@ -229,7 +227,7 @@ fn rows(local: &Local) -> Vec<Row> {
fn build(cx: &Rc<DialogCx>, local: &Rc<Local>) -> View {
let error = cx.theme.text.feedback.error.base;
let state = local.usage();
// Reopen once the limits arrive or sign-in changes, since the three states lay out differently.
// Reopen on a state change because signed-out, loading, and ready states use different layouts.
let shown = state.as_ref().map(Option::is_some);
let weak = Rc::downgrade(local);
let reopened = Rc::new(Cell::new(false));
@@ -1,5 +1,4 @@
//! Model usage dialog (E.16): `DialogUsageModel` in `component/usage.tsx`, every limit on one model, the one
//! setting what's left marked.
//! Limits for one model, highlighting the binding limit.
use opencode_api::generated::ModelInfo;
use opencode_ui::dialog::layout;
@@ -1,4 +1,4 @@
//! Variant dialog (E.16): `component/dialog-variant.tsx`, "Select variant".
//! Select the current model's variant.
use crate::local::Local;
use crate::prelude::*;
@@ -1,4 +1,4 @@
//! TypeScript: `ui/working-directory-actions.tsx`.
//! Working-directory actions and clipboard export.
use crate::prelude::*;
@@ -38,7 +38,7 @@ fn options(tui: &Rc<Tui>, directory: &str) -> Vec<SelectOption<String>> {
vec![
SelectOption::new("Copy path", "location.copy".to_owned()).description(directory).on_select(action(
|tui, directory| {
// TS closes the dialog only once the write succeeded.
// Close only on a successful copy.
if crate::features::selection::write(tui, directory) {
tui.dialogs.clear();
tui.toasts.show(ToastOptions::new(Variant::Info, "Path copied to clipboard"));
@@ -1,7 +1,4 @@
//! Name worktree dialog (E.11b, row DLG27): `component/dialog-worktree-name.tsx`.
//!
//! "Name worktree" asks for a name; `tab` (`dialog.worktree.generate`) fills in a generated one, and an empty
//! or symbol-only name becomes a generated one on Enter.
//! Choose or generate a name for a new worktree.
use opencode_ui::prompt::{PromptAction, PromptProps, prompt};
@@ -1,13 +1,4 @@
//! Worktrees dialog (E.11b, row DLG26): `component/dialog-workspaces.tsx`.
//!
//! "Worktrees" lists a project's checkouts: the current one first under "Current", then the others, with
//! the session subdirectories under each. Enter picks one for the caller (`/worktrees` in the prompt, the
//! location-missing view). `ctrl+a` names a new worktree, `ctrl+d` twice deletes one (asking again when it
//! has file changes), `ctrl+r` asks the server to look for worktrees, and in a session `ctrl+m` moves the
//! session there.
//!
//! Like the open dialog, each change of the loading or deleting state builds the dialog again, restoring the
//! filter and the selection, so the list's lock and current marker follow it (TS props are reactive).
//! Select, create, or remove a project worktree.
use opencode_api::generated::{
AbsolutePath, LocationGetInput, LocationQueryInput, ProjectID, SessionMoveInput, VcsStatusInput, WorktreeDirectory,
@@ -600,8 +591,7 @@ impl Workspaces {
state.removing = None;
state.working = false;
}
// TS leaves a home dialog that stays open showing the deletion; this reads
// the list again instead.
// Refresh a home dialog that stays open after deletion.
if !workspaces.removed_current(deleting_current) {
workspaces.reopen(None);
} else if workspaces.shown.get() {
@@ -15,7 +15,7 @@ pub struct Previews {
paints: Paints,
}
/// The files, height, and option the previews were last built for.
/// Files, height, and option used by the preview cache.
type Shown = (Vec<(Option<String>, Option<String>, usize)>, u16, bool);
impl Previews {
@@ -1,6 +1,4 @@
//! `/cd` (`session.cd`, row P11; `component/prompt/index.tsx:265-315`): a session moves to the
//! directory; on home, the next session's directory changes. Either way the directory joins the
//! project's recents, which the `/cd` argument completion lists first.
//! `/cd` moves the current session or selects the directory of the next session on home.
use opencode_api::generated::{AbsolutePath, LocationGetInput, LocationQueryInput, SessionMoveInput};
use opencode_ui::keymap::Slash;
@@ -1,12 +1,4 @@
//! Prompt autocomplete (E.3, rows P05, P11, K04; `component/prompt/autocomplete.tsx`).
//!
//! `/` at the start of the prompt lists slash commands: the keymap's and the server's. `@` at a word
//! start lists skills, references, subagents, and files from `/api/fs/find`. The argument of `/cd`
//! lists directories from `/api/fs/list`, with recent directories first. A pick becomes a prompt part
//! ([`parts`]); a command without arguments runs.
//!
//! While the popup shows, the keymap is in the `autocomplete` mode, so the prompt's own layers
//! (submit, history, shell mode) are off and this module's layer takes the keys.
//! Slash-command, mention, file, and directory completion for the prompt.
pub mod cd;
pub use opencode_ui::prompt_input::parse;
@@ -58,8 +50,7 @@ pub enum Mode {
pub struct Shared {
frecency: Arc<Mutex<Option<Frecency>>>,
recents: Arc<Mutex<Option<Value>>>,
/// The last recents change sent; a written file replaces memory only if no newer change was sent, and the
/// loaded file only if none was.
/// Apply a disk result only if it does not predate an in-memory edit.
recents_writes: Arc<AtomicU64>,
writer: Rc<OnceCell<Serial>>,
loaded: Rc<Cell<bool>>,
@@ -161,7 +152,7 @@ impl Shared {
});
}
/// Changes the project's list in memory now and in storage on a blocking thread.
/// Update project recents in memory and serialize persistence on a worker.
fn update_recents(&self, tui: &Tui, project: &str, change: impl Fn(&mut Vec<Value>) + Send + Clone + 'static) {
let project = project.to_owned();
let apply = move |value: &mut Value, change: &dyn Fn(&mut Vec<Value>)| {
@@ -217,8 +208,7 @@ fn load_frecency(slot: &Mutex<Option<Frecency>>, state: &Path, cwd: &Path) {
#[derive(Clone, Copy)]
struct RecentsChanged;
/// Tells the UI that the recents in memory changed, so an open `/cd` picker lists them, as TS's store redraws it.
/// Waits while the UI queue is full.
/// Notify an open directory picker when recents change; retry a full UI queue.
fn recents_changed(proxy: &AppProxy) {
while let Err(ProxyError::Full) = proxy.send(RecentsChanged) {
std::thread::sleep(Duration::from_millis(5));
@@ -303,10 +293,9 @@ pub struct Open {
selected: usize,
offset: usize,
placed: f64,
/// The popup's entry on the keymap's mode stack, handed on rather than pushed again, so the stack stays as it was:
/// a dialog opened over the list stays above it.
/// Transfer the popup's mode entry on remount so a dialog above it still receives keys first.
entry: Option<Disposer>,
/// The last file or directory search's results and the search they answer, unless one was still on its way.
/// Cached file or directory results and the search that produced them.
results: Option<(Results, Requested)>,
}
@@ -322,7 +311,7 @@ struct State {
dismissed: RefCell<Option<String>>,
confirming: RefCell<Option<String>>,
results: RefCell<Results>,
/// The search the last request was for, since the popup opened.
/// Last search requested for this open popup.
requested: RefCell<Requested>,
loading: Cell<bool>,
generation: Cell<u64>,
@@ -439,9 +428,7 @@ impl Autocomplete {
Some(Open { mode, index, selected, offset, placed, entry, results })
}
/// Opens the popup where `open` was, over the prompt's text as it is now: a remount of the route keeps an open
/// list open, as TS's stays open while a plugin loads. The options are those of now, the selection kept by its
/// place, as TS keeps `selected` until the search changes; a file or directory search is not asked again.
/// Restore the open popup at its previous position against the current prompt text.
pub fn reopen(&self, open: Open) {
let state = &self.0;
state.placed.set(Some(open.placed));
@@ -561,10 +548,7 @@ impl State {
self.request_redraw();
}
/// Follows the prompt's place while the popup shows, as TS polls its anchor every 50 ms
/// (`autocomplete.tsx:120-133`): a prompt laid out, moved or resized after the popup drew (one mounted again by a
/// plugin's load and typed into before its first frame) draws the popup again at its height
/// (select-search-flake).
/// Track the prompt's anchor while the popup is open, including the first layout after remount.
fn follow(&self, tui: &Tui) {
if self.follow.get().is_some() {
return;
@@ -636,9 +620,7 @@ impl State {
})
}
/// Runs the file (`/api/fs/find`) or directory (`/api/fs/list`) search for `search`, unless the
/// last one since the popup opened was for the same search (TS refetches when its source
/// changes).
/// Start a search unless this popup already requested the same input.
fn fetch(&self, tui: &Tui, mode: Mode, search: &str, location: &Location) {
let key = (mode, search.to_owned(), location.directory.clone());
if self.requested.borrow().as_ref() == Some(&key) {
@@ -772,9 +754,7 @@ impl State {
ROWS.min(count).min(anchor.max(1))
}
/// The prompt's row on the screen, or the row of the prompt this popup was reopened from while this one has no
/// layout yet: a second remount before the screen laid out again hands that row on, not the new prompt's 0
/// (select-search-flake).
/// Use the previous anchor until the remounted prompt has a layout.
fn anchor_row(&self) -> f64 {
let rect = self.anchor.rect();
match self.placed.get() {
@@ -844,7 +824,7 @@ impl State {
self.hide(true);
}
self.editing.set(false);
// TS handles the pick's own edit after it; a reopened trigger shows again.
// Recheck completion after applying the edit: the new text can open another list.
self.on_input(&prompt.textarea.text());
}
@@ -1345,8 +1325,7 @@ fn home() -> String {
mod tests {
use super::*;
/// P-ORACLE: `parity/oracle/E.3-fuzzy.ts` ran fuzzysort as the `options` memo does; the order must be the
/// same, ties and the limit of ten included.
/// Compare the ranked options, including ties and truncation, against the reference ordering.
#[test]
fn rank_matches_fuzzysort() {
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../parity/fixtures/E.3/fuzzy.json");
@@ -1,11 +1,4 @@
//! Mentions as prompt parts: each `@file`, `@agent`, and `@skill` in the text is an atomic extmark,
//! highlighted and deleted as one unit, tied to its entry in the `PromptInfo`'s `files`, `agents`, or
//! `skills` (`component/prompt/index.tsx:765-880`, `insertPart` in `autocomplete.tsx`). Compact pastes
//! (`pasted`) and pasted attachments (E.4) are parts on the same marks.
//!
//! The `PromptInfo` keeps each part's `mention` (`start`, `end`, `text`), or a paste's `source`. Every
//! edit moves the marks; [`sync`] then copies their ranges into the parts and drops the parts whose
//! marks went.
//! Atomic prompt extmarks for file, agent, and skill mentions.
use opencode_api::generated::{PromptAgentAttachment, PromptInputSkillAttachment};
use opentui::widget::{ExtmarkId, ExtmarkOptions};
@@ -55,8 +48,7 @@ impl Kind {
#[derive(Default)]
pub struct Parts {
marks: RefCell<Vec<(ExtmarkId, Kind, usize)>>,
/// Pastes whose marks an edit removed. TS keeps a paste's text on its extmark; here [`sync`] keeps it by mark id
/// until undo or redo brings the mark back.
/// Keep removed paste data by mark ID so undo and redo can restore it.
dropped: RefCell<Vec<Dropped>>,
}
@@ -114,8 +106,7 @@ pub fn insert(prompt: &Inner, start: u32, text: &str, kind: Kind, part: Value) {
prompt.parts.marks.borrow_mut().push((id, kind, list.len() - 1));
}
/// The skills dialog's pick: `@id ` at the cursor, unless the prompt has the skill
/// (`prompt.skills` in `component/prompt/index.tsx`).
/// Insert the selected skill at the cursor unless the prompt already includes it.
pub fn insert_skill(prompt: &Inner, id: &str) {
if has(prompt, Kind::Skill, "id", &json!(id)) {
return;
@@ -135,7 +126,7 @@ pub fn insert_skill(prompt: &Inner, id: &str) {
prompt.parts.marks.borrow_mut().push((mark, Kind::Skill, skills.len() - 1));
}
/// Marks the mentions of the `PromptInfo` the textarea now shows (`restoreExtmarksFromPrompt`).
/// Restore mention extmarks for the displayed prompt.
pub fn restore(prompt: &Inner) {
prompt.textarea.clear_extmarks();
prompt.parts.clear();
@@ -154,9 +145,7 @@ pub fn restore(prompt: &Inner) {
}
}
/// Paints the marks of `old`'s styles in `new`'s, as TS's marks follow their style IDs. A mark's style is fixed when
/// it is added, so each is added again, in creation order (which [`sync`] reads from the IDs), over the same range;
/// its part follows the new ID. A mark an edit removed keeps its old style if undo brings it back.
/// Reapply mention styles without changing text, selection, or edit history.
pub fn restyle(prompt: &Inner, old: &Theme, new: &Theme) {
const SCOPES: [&str; 4] = ["extmark.file", "extmark.agent", "extmark.skill", "extmark.paste"];
let (old, new) = (opencode_ui::code::syntax_theme(old), opencode_ui::code::syntax_theme(new));
@@ -183,7 +172,6 @@ pub fn restyle(prompt: &Inner, old: &Theme, new: &Theme) {
/// (`syncExtmarksWithPromptParts`). Files without a mention stay.
pub fn sync(prompt: &Inner) {
let mut marks = prompt.textarea.extmarks();
// Marks in creation order, as TS lists them.
marks.sort_by_key(|mark| mark.id);
let mut mapped = prompt.parts.marks.borrow().clone();
let mut info = prompt.prompt.borrow_mut();
@@ -1,6 +1,4 @@
//! Prompt drafts (E.2, row P12): one in-progress prompt per session, and one for home, kept across
//! route changes (`component/prompt/draft-stash.ts`). Taking a draft removes it, so a stale copy
//! never shadows newer input.
//! Preserve the in-progress prompt for each session and for home across navigation.
use crate::prelude::*;
+15 -35
View File
@@ -1,9 +1,4 @@
//! The prompt editor (E.2, rows P01, P02, P13, P14): the textarea, its keymap layers, and the
//! composer state (`component/prompt/index.tsx`).
//!
//! The textarea has no key bindings of its own. While it is focused, the keymap's managed textarea
//! layer runs the 36 `input.*` commands on it through `Tui::textarea` (U.2), and the layers here add
//! submit, queue, clear, history, shell mode, interrupt, and background.
//! Prompt editing, focus, draft lifecycle, and key bindings.
use futures_util::FutureExt;
use futures_util::future::BoxFuture;
@@ -53,7 +48,7 @@ pub struct Shared {
pub complete: autocomplete::Shared,
pub editor: editor_context::Context,
pub stash: super::stash::Stash,
/// The prompt last mounted, whose pastes a copy expands (E.4).
/// Mounted prompt used to expand collapsed pastes on copy.
pub(crate) current: RefCell<Weak<Inner>>,
/// Each session's last pending interrupt request, which waits for the ones before it. It outlives the composer
/// that sent it, as a later prompt from another composer must still wait for it.
@@ -75,9 +70,7 @@ impl Shared {
}
}
/// Resolves once every interrupt request for `session` has its answer, at once without one. A submit's
/// requests wait for it, so the server sees them in the order they were made, as TS's fetches start in call
/// order (`ctrl+⏎ interrupt & send`).
/// Wait for this session's pending interrupts before sending its next prompt.
pub(crate) fn interrupted(&self, session: &SessionID) -> BoxFuture<'static, ()> {
let pending = self.pending_interrupt(session);
async move {
@@ -93,9 +86,7 @@ impl Shared {
self.interrupts.borrow().get(session).cloned()
}
/// Runs `run` at once, or once every pending interrupt of `session` has its answer, so what a slash command
/// sends reaches the server after them, as a prompt does; TS runs it at once (deviation
/// O89-slash-after-interrupt).
/// Run the command after earlier interrupts of the same session finish.
pub(crate) fn after_interrupts(&self, tui: &Tui, session: Option<&SessionID>, run: impl FnOnce(&Tui) + 'static) {
match session.and_then(|session| self.pending_interrupt(session)) {
Some(pending) => {
@@ -176,11 +167,10 @@ pub struct Inner {
pub(crate) parts: parts::Parts,
pub(crate) history: super::history::Cursor,
pub(crate) autocomplete: OnceCell<Autocomplete>,
/// Pastes waiting for files or the clipboard (E.4).
/// Outstanding file and clipboard pastes.
pub(crate) paste: super::paste::Queue,
previews: super::attach::Previews,
/// `--prompt`, or an Enter pressed before the catalogs loaded, until it is submitted (`home.tsx:68-79`,
/// `session/index.tsx:623-630`; deviation `P02-early-enter`).
/// Pending submission while the catalogs load; editing the text cancels it.
pub(crate) startup: RefCell<Option<(String, SessionInboxDelivery)>>,
pub(crate) staging: super::r#move::Move,
/// `props.disabled`: a home form holds the keys, so a click does not focus the prompt.
@@ -201,13 +191,12 @@ impl Prompt {
self.inner.mode.get()
}
/// The prompt's state, for views beside it that read its mode and focus it (E.10b's queued undo).
/// Weak reference for views that inspect the prompt mode or request focus.
pub(crate) fn weak(&self) -> Weak<Inner> {
Rc::downgrade(&self.inner)
}
/// Paints in the page theme in place, as TS's prompt follows it: the text, cursor, undo history, mentions and
/// focus stay. The footer's plugin claims take the theme in place, or mount again when one cannot.
/// Restyle in place to preserve text, cursor, undo history, and focus.
pub fn restyle(&self, tui: &Tui) {
let inner = &self.inner;
let theme = tui.page();
@@ -301,7 +290,6 @@ pub fn mount(tui: &Tui, session: Option<&SessionID>) -> Prompt {
let padding = if width < 44 { 1 } else { 2 };
let cursor = crate::features::system_commands::cursor(&tui.config());
let textarea = Textarea::new(app)
// Core's textarea sets no pointer shape, so the TS TUI keeps the default pointer everywhere.
.mouse_pointer(MousePointer::DEFAULT)
.set_keymap(Keymap::new())
.cursor_style(cursor.0, cursor.1)
@@ -403,8 +391,7 @@ pub fn mount(tui: &Tui, session: Option<&SessionID>) -> Prompt {
disabled: Cell::new(false),
this: this.clone(),
});
// `prompt/index.tsx:1838-1844`: a left press focuses the prompt unless it is disabled. With the right pane
// active, the session frame takes the release instead.
// A click returns focus to the enabled prompt, including from a docked pane.
inner.textarea.on_mouse(bind!(inner, |prompt, cx, event| {
let MouseEventKind::Down(button) = event.kind else { return };
let Some(tui) = prompt.tui.upgrade() else { return };
@@ -419,8 +406,7 @@ pub fn mount(tui: &Tui, session: Option<&SessionID>) -> Prompt {
connect(&inner);
connect_location(&inner);
install_layers(tui, &inner);
// After the prompt's layers, as TS renders it after them: the newer layer runs first, so its
// `prompt.clear` wins while the popup shows.
// Register completion last so its clear action wins while the popup is open.
let _ = inner.autocomplete.set(autocomplete::mount(tui, &inner, &inner.root));
*tui.textarea.borrow_mut() = Some(inner.textarea.clone());
*tui.prompt.current.borrow_mut() = Rc::downgrade(&inner);
@@ -499,8 +485,7 @@ impl Inner {
prompt["text"] = Value::String(text.to_owned());
prompt["mode"] = Value::String(self.mode.get().as_str().to_owned());
self.restore(prompt);
// Replacing the text calls no change handler, so the completion hears of it here, as TS's `setText` tells it:
// the popup of the old text closes, and one the new text starts opens.
// Replacing all text bypasses the change handler; explicitly resync completion.
if let Some(complete) = self.autocomplete.get() {
complete.on_input(&self.textarea.text());
}
@@ -682,8 +667,7 @@ impl Inner {
Mode::Shell => Display { agent: Some("Shell".into()), ..display },
Mode::Normal => display,
};
// `borderHighlight` tints toward the highlight as the agent label fades in; `tint` returns an opaque
// color, so a border token with alpha draws at full strength as in TS.
// Tinting produces an opaque border, even when the source token has alpha.
let border =
opencode_ui::theme::tint(theme.border.base, highlight, if display.agent.is_some() { 1.0 } else { 0.0 });
self.frame.border_color(border);
@@ -758,9 +742,7 @@ impl Inner {
cut.trim_end().to_owned()
}
/// The scanner in the agent's color, `[⋯]` with animations off (`component/prompt/index.tsx:1913-1919`). It
/// mounts when the session starts running and drops when it stops, so it starts at its first frame each time
/// and no timer runs while idle.
/// Activity scanner in the agent's color. Show a still glyph when animations are disabled.
fn show_spinner(&self, tui: &Tui, theme: &Theme, running: bool, color: Color) {
let mut spinner = self.spinner.borrow_mut();
if !running {
@@ -886,8 +868,7 @@ fn connect(inner: &Rc<Inner>) {
}));
}
/// The footer's location brightens under the pointer, and a click opens the working directory dialog (E.20,
/// `useWorkingDirectoryActions`). While a reply runs the footer shows the interrupt hint instead.
/// Show and open the working directory from the footer.
fn connect_location(inner: &Rc<Inner>) {
inner.location_box.on_resize(bind!(inner, |prompt, _, rect| {
let width = rect.width.max(0.0) as u16;
@@ -950,8 +931,7 @@ fn install_layers(tui: &Tui, inner: &Rc<Inner>) {
};
let layers = vec![
// The prompt's commands in the order of `promptCommands`, which the palette keeps; then `session.cd`, whose TS
// layer is older.
// Palette order follows layer registration order.
KeymapLayer::global(vec![
command("prompt.clear", "Clear prompt", "Prompt", |prompt, tui| {
prompt.clear(tui);
@@ -1,15 +1,4 @@
//! IDE editor context (E.5, row P08): the file and selection open in the IDE the terminal runs in
//! (`context/editor.ts`, `editor.ts`, `editor-zed.ts`).
//!
//! Two sources, tried in this order on every connection attempt:
//!
//! - the IDE's MCP server over a WebSocket, at `CLAUDE_CODE_SSE_PORT` or `OPENCODE_EDITOR_SSE_PORT`, else at the
//! port of the best `~/.claude/ide/<port>.lock` for the directory. It sends `selection_changed` and
//! `at_mentioned` notifications;
//! - in a Zed terminal, Zed's SQLite database (`OPENCODE_ZED_DB`, else Zed's default path), read every second.
//!
//! A task on the runtime owns the socket and the polling; it posts what it reads to the UI thread, where
//! [`Context`] keeps the state the prompt shows. Changing the directory replaces the task.
//! Track the terminal's editor selection and turn IDE mentions into prompt attachments.
use std::path::{Path, PathBuf};
use std::sync::Arc;
@@ -51,8 +40,7 @@ impl Source {
}
}
/// `resolveZedDbPath`'s candidates: `OPENCODE_ZED_DB`, then Zed's macOS and Linux paths under the home directory.
/// On Windows, Zed's `%LOCALAPPDATA%\Zed` comes last, which TS does not read (deviation W11-zed-windows-db).
/// Resolve the Zed database override before the platform's default locations.
fn zed_db_candidates(env: Option<String>, home: Option<&Path>, local_app_data: Option<String>) -> Vec<PathBuf> {
let db = |dir: PathBuf| dir.join("db").join("0-stable").join("db.sqlite");
env.map(PathBuf::from)
@@ -686,8 +674,7 @@ fn server_info(result: &Value) -> bool {
})
}
/// Reading Zed's workspace database (`editor-zed.ts`) through the system SQLite, loaded at run time. Without the
/// library there is no Zed context (deviation P08-zed-system-sqlite).
/// Read workspace selections from Zed using dynamically loaded system SQLite. Missing SQLite disables this source.
pub mod zed {
use std::path::Path;
@@ -850,7 +837,7 @@ pub mod zed {
}
}
/// The longest workspace path that contains `cwd`, in UTF-16 units as TS measures it; 0 for none.
/// Longest containing workspace path in UTF-16 units, or zero if no path contains `cwd`.
fn workspace_score(paths: Option<&str>, cwd: &Path) -> usize {
let Some(paths) = paths else { return 0 };
let list: Vec<String> = match serde_json::from_str::<serde_json::Value>(paths) {
@@ -880,7 +867,7 @@ pub mod zed {
text.char_indices().map(|(index, c)| index + c.len_utf8()).find(|end| *end >= offset).unwrap_or(text.len())
}
/// The 1-based line and UTF-16 column of byte index `index` (`offsetsToSelection`).
/// Convert a byte offset to a one-based line and UTF-16 column.
fn position(text: &str, index: usize) -> Position {
let before = &text[..index];
let line_start = before.rfind('\n').map_or(0, |at| at + 1);
@@ -901,7 +888,7 @@ mod sqlite {
#[cfg(target_os = "macos")]
const LIBRARY: &str = "/usr/lib/libsqlite3.dylib";
// The SQLite Windows itself uses, in System32 since Windows 10.
// Use the SQLite library provided by Windows.
#[cfg(windows)]
const LIBRARY: &str = "winsqlite3.dll";
#[cfg(not(any(target_os = "macos", windows)))]
@@ -1,9 +1,4 @@
//! External editor (E.5, row P09): `prompt.editor` (`<leader>e`, `/editor`) opens the prompt in `$VISUAL` or
//! `$EDITOR` and reads it back (`openEditor` in `editor.ts`, `prompt.editor` in `component/prompt/index.tsx`).
//!
//! The prompt goes to a temporary `.md` file. The terminal is released to the editor while it runs and taken
//! back when it exits; the UI waits meanwhile, as TS's suspended renderer does. Mentions that survive the edit
//! keep their parts, moved to where their text now is.
//! Edit the prompt in `$VISUAL` or `$EDITOR`, then restore its mentions.
use std::path::PathBuf;
@@ -1,9 +1,4 @@
//! Prompt history (E.2, row P03): `<state>/prompt-history.jsonl`, shared by every prompt of the app
//! (`prompt/history.tsx`), and Up and Down in the prompt (`component/prompt/index.tsx:1022-1096`).
//!
//! F.5's `jsonl::History` owns the format and the entries in memory; each prompt keeps its own [`Cursor`]
//! (`usePromptHistory`). Stepping and appending run on the UI thread. The file, which the TS TUI shares, is touched on one worker thread in order: the load
//! first, then each new entry under the file's lock (`jsonl::save_history`).
//! Shared prompt history and per-editor navigation.
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
@@ -27,13 +22,12 @@ pub struct History {
#[derive(Default)]
struct Memory {
history: jsonl::History,
/// Entries appended before the file was read, `None` once it is; they go after its entries.
/// Entries added during the initial read follow the entries loaded from disk.
early: Option<Vec<Value>>,
}
impl History {
/// Loads `<state>/prompt-history.jsonl` on the worker; until then the history holds what was
/// appended meanwhile.
/// Load history on the worker and preserve entries added during the read.
pub fn load(_app: &App, state: Option<PathBuf>) -> Self {
let Some(state) = state else { return Self::default() };
let memory = Arc::new(Mutex::new(Memory { early: Some(Vec::new()), ..Memory::default() }));
@@ -1,4 +1,4 @@
//! TypeScript: `component/prompt/metadata.tsx`, `context/local.tsx`.
//! Agent, model, variant, and usage labels below the prompt.
use opencode_api::generated::{
AgentInfo, ConfigEntry, ConfigEntryDocumentInfoModel, ModelInfo, ModelRef, ProviderID, ProviderInfo,
@@ -131,8 +131,7 @@ pub struct Display {
pub model: String,
pub provider: String,
pub variant: Option<String>,
/// What the workspace's limits leave for the model, once it is running low, and whether that is in the error
/// color (E.16, `limitLabel`).
/// Remaining workspace allowance and its warning severity for the selected model.
pub limit: Option<(String, bool)>,
}
@@ -160,8 +159,7 @@ impl Row {
if let Some(agent) = &layout.agent {
spans.push(agent.clone().fg(highlight));
}
// TS lays the row out as separate texts with `gap={1}`, so no text draws the gaps: a transparent
// foreground keeps the one beneath, as there.
// Leave gaps transparent so the color underneath remains visible.
let gap = || " ".fg(Color::TRANSPARENT);
if layout.auto {
spans.extend([gap(), "auto".fg(theme.text.muted)]);
@@ -1,9 +1,4 @@
//! Worktrees from the prompt (E.11b, rows P16 and P17): `session.move` (`/worktrees`) and
//! `component/prompt/move.tsx`.
//!
//! `/worktrees` opens the worktrees dialog for the prompt's project. Picking a checkout goes home there. A
//! new worktree is created at once from a session; on home it is staged, the footer says "(new worktree)",
//! and the first submit creates it ("Creating worktree…", then "Creating session…") before the session.
//! Move the current session to a worktree or stage one for the next session.
use opencode_api::generated::{LocationGetInput, LocationQueryInput, ProjectID, SessionInfo, WorktreeCreateInput};
use opencode_store::Location;
+4 -18
View File
@@ -1,16 +1,4 @@
//! Pastes (E.4, rows P06 and CB02): terminal pastes and `prompt.paste` (Ctrl+V) in the prompt
//! (`component/prompt/index.tsx:373-394,470-493,1407-1522,1798-1851`, `clipboard.ts:24-52`).
//!
//! - A paste of three or more lines, or of more than 150 characters, becomes `[Pasted ~N lines]`: an atomic
//! mark tied to a `pasted` part that keeps the text. Submitting sends the text; clicking the mark, or
//! pasting the same text again right after it, expands it in place. `prompt.paste: "full"` turns this off.
//! - A paste that names image, PDF, or SVG files attaches them ([`super::attach`]).
//! - `prompt.paste` reads the clipboard as `image/png`, else `text/plain`: an image attaches as
//! `[Image N]`, text pastes as above. An empty terminal paste does the same, for terminals that paste an
//! image clipboard as nothing.
//!
//! Pastes run one after another. A paste whose file or clipboard read finishes after the prompt changed
//! (its text or mode, or the prompt went) is dropped, as in TS.
//! Clipboard and terminal pastes, including collapsed text and file attachments.
use std::collections::VecDeque;
@@ -75,8 +63,7 @@ pub fn connect(inner: &Rc<Inner>) {
}
enqueue(&prompt, Job::Text(text.replace("\r\n", "\n").replace('\r', "\n")));
}));
// A plugin's mode of the composer ends as the composer loses the focus (synthesis 3.8), and so does a capture that
// began with the focus there; also when the composer went with its route, before it heard of its focus.
// Losing composer focus ends its plugin mode and any pointer capture started there.
let (tui, id) = (inner.tui.clone(), inner.textarea.id());
inner.textarea.on_focus(move |_, focused| {
if let (false, Some(tui)) = (focused, tui.upgrade()) {
@@ -96,8 +83,7 @@ pub fn connect(inner: &Rc<Inner>) {
.extmarks_at(cursor)
.into_iter()
.find(|mark| matches!(prompt.parts.get(mark.id), Some((Kind::Pasted, _))));
// TS prevents the press's default, so the click selects nothing. The press already started a selection
// here; without ending it, the release would select across the expanded text.
// End the press selection so release does not trigger copy-on-select.
if mark.is_some_and(|mark| expand(&prompt, mark.id)) {
cx.app().clear_selection();
}
@@ -225,7 +211,7 @@ fn insert(prompt: &Inner, normalized: &str, pasted: &str) {
.tui
.upgrade()
.is_none_or(|tui| tui.settings.info().prompt.and_then(|prompt| prompt.paste) != Some(PromptPaste::Full));
// `pastedContent.length` counts UTF-16 units.
// Count UTF-16 units for the paste threshold.
if (lines >= 3 || pasted.encode_utf16().count() > 150) && compact {
// The same text pasted right after its mark expands it.
let cursor = prompt.textarea.cursor_offset();
@@ -1,4 +1,4 @@
//! TypeScript: `component/prompt/index.tsx:964-1020`.
//! Shell-mode prompt and bindings.
use opencode_ui::dialog::FocusId;
+3 -12
View File
@@ -1,11 +1,4 @@
//! The prompt stash (E.4, row P04): `prompt.stash`, `prompt.stash.pop`, and `prompt.stash.list` over
//! `<state>/prompt-stash.jsonl`, shared by every prompt of the app (`prompt/stash.tsx`,
//! `component/prompt/index.tsx:882-946`).
//!
//! F.5's `jsonl` owns the format and writes the file. The UI keeps its own copy of the entries, so
//! commands answer at once, as TS's store does. The file is touched on one worker thread in order: the
//! load first, then each change under the file's lock, against what the file holds then, so entries
//! another TUI stashed meanwhile stay.
//! Persistent prompt stash shared across sessions.
use std::path::{Path, PathBuf};
@@ -29,8 +22,7 @@ pub struct Stash {
}
impl Stash {
/// Loads `<state>/prompt-stash.jsonl` on the worker; until then the stash holds what was stashed
/// meanwhile, which then goes after the file's entries.
/// Load the stash on a worker. Keep entries added during the read after the entries from disk.
pub fn load(app: &App, state: Option<PathBuf>) -> Self {
let Some(state) = state else { return Self::default() };
let writer = Serial::new("prompt-stash.jsonl");
@@ -61,8 +53,7 @@ impl Stash {
self.entries.borrow().is_empty()
}
/// `push({prompt})`, stamped now; the oldest entries past the limit go. A failed save shows an
/// error toast; TS ignores it (deviation O89-stash-save-toast). The entry stays in memory.
/// Timestamp and append a prompt, evicting the oldest entries beyond the limit. Report persistence errors.
pub fn push(&self, tui: &Tui, prompt: Value) {
let entry = jsonl::stash_entry(prompt, opencode_util::time::now_ms());
{
@@ -1,8 +1,4 @@
//! Submit, queue, and steer (E.2, rows P02 and P07; `component/prompt/index.tsx:1098-1405`).
//!
//! A submit snapshots the prompt and clears it at once; the requests then run on the runtime, and a
//! failure puts the prompt back unless something new was typed. On home, it creates the session
//! first (optimistically, so the session opens at once) and the prompt waits for the creation.
//! Submit, queue, and steer prompts. Restore the snapshot on failure only if the user has not started a new draft.
use indexmap::IndexMap;
use opencode_api::client::Client;
@@ -32,7 +28,7 @@ pub fn submit(prompt: &Rc<Inner>, delivery: SessionInboxDelivery) -> bool {
}
fn run(tui: &Tui, prompt: &Rc<Inner>, delivery: SessionInboxDelivery) -> bool {
// A staged worktree is being created; its submit runs once it exists (E.11b).
// Submit after the staged worktree exists.
if prompt.staging.creating() {
return false;
}
@@ -68,7 +64,7 @@ fn run(tui: &Tui, prompt: &Rc<Inner>, delivery: SessionInboxDelivery) -> bool {
});
return true;
}
// The editor context goes once, before the prompt it came with (E.5).
// Include editor context once, before the prompt.
let editor = prompt
.editor_context(tui)
.filter(|_| tui.prompt.editor.label_state() == super::editor_context::LabelState::Pending);
@@ -78,7 +74,7 @@ fn run(tui: &Tui, prompt: &Rc<Inner>, delivery: SessionInboxDelivery) -> bool {
}
let Some(catalog) = prompt.catalog.borrow().clone() else {
// Sent once the catalogs load, as `--prompt` is, unless the text changes first. TS drops it.
// Retry when catalogs load only if the prompt text still matches.
*prompt.startup.borrow_mut() = Some((prompt.textarea.text(), delivery));
return true;
};
@@ -109,8 +105,7 @@ fn run(tui: &Tui, prompt: &Rc<Inner>, delivery: SessionInboxDelivery) -> bool {
let head = slash_head(&text);
let command = head.as_ref().filter(|(name, _)| catalog.commands.iter().any(|command| command == name)).cloned();
// Snapshot, then clear before any request: text typed meanwhile survives, and history records
// exactly what was sent.
// Snapshot before starting the request so new typing survives and history records the sent content.
let entry = prompt.snapshot();
let (files, agents, skills) = (
serde_json::from_value(super::attach::files_for_server(&entry, tui.startup.args.local)).ok(),
@@ -130,7 +125,7 @@ fn run(tui: &Tui, prompt: &Rc<Inner>, delivery: SessionInboxDelivery) -> bool {
let staged = super::r#move::create_staged(tui, prompt, move |tui, prompt, directory| {
let typed = prompt.textarea.text();
if !typed.is_empty() {
// Typed while the worktree was created: kept as home's draft.
// Preserve text typed during worktree creation as the home draft.
let mut draft = prompt.snapshot();
draft["text"] = Value::String(typed);
tui.prompt.drafts.save(None, Draft { prompt: draft, cursor: u32::MAX });
@@ -400,7 +395,7 @@ impl Failure {
}
}
/// Shows the error, also after the composer unmounted, and restores the prompt unless something new was typed.
/// Report submission failure even after unmount; restore the draft only if no new text replaces it.
fn fail(tui: &std::rc::Weak<Tui>, prompt: &std::rc::Weak<Inner>, title: &str, error: &Error, entry: &Value) {
let Some(tui) = tui.upgrade() else { return };
tui.toasts.show(ToastOptions::new(Variant::Error, error.tui_message()).title(title));