From e348bd15eb0dafebeb318a81f5cc15ccdc0dc5e9 Mon Sep 17 00:00:00 2001 From: Simon Klee Date: Wed, 18 Nov 2026 20:40:22 +0100 Subject: [PATCH] docs(cli-rs): describe shell and feature lifecycles directly Document input precedence, connection ordering, terminal restoration and shared state where they constrain the implementation. Remove porting milestones, review credits and source-line citations from the shell, feature services, client MCP and panel modules. --- packages/cli-rs/crates/tui/src/app.rs | 83 +++++++------------ .../cli-rs/crates/tui/src/client_mcp/mod.rs | 8 +- .../tui/src/features/attention/focus.rs | 6 +- .../tui/src/features/attention/notify.rs | 7 +- .../src/features/attention/program_status.rs | 14 +--- .../tui/src/features/attention/sound.rs | 9 +- .../cli-rs/crates/tui/src/features/clear.rs | 4 +- .../crates/tui/src/features/console_copy.rs | 4 +- .../crates/tui/src/features/devtools.rs | 14 ++-- .../cli-rs/crates/tui/src/features/drive.rs | 5 +- .../crates/tui/src/features/epilogue.rs | 21 ++--- .../cli-rs/crates/tui/src/features/events.rs | 26 ++---- .../crates/tui/src/features/foreground.rs | 3 +- .../crates/tui/src/features/highlights.rs | 9 +- .../crates/tui/src/features/home_forms.rs | 4 +- .../cli-rs/crates/tui/src/features/links.rs | 11 +-- .../crates/tui/src/features/location.rs | 15 +--- .../crates/tui/src/features/overlays.rs | 19 +---- .../crates/tui/src/features/quick_switch.rs | 4 +- .../crates/tui/src/features/route_missing.rs | 4 +- .../crates/tui/src/features/selection.rs | 19 +---- .../crates/tui/src/features/session_links.rs | 13 +-- .../cli-rs/crates/tui/src/features/startup.rs | 21 ++--- .../tui/src/features/system_commands.rs | 24 ++---- .../cli-rs/crates/tui/src/features/title.rs | 15 +--- packages/cli-rs/crates/tui/src/lib.rs | 2 +- packages/cli-rs/crates/tui/src/local.rs | 22 ++--- packages/cli-rs/crates/tui/src/panel/mod.rs | 6 +- 28 files changed, 111 insertions(+), 281 deletions(-) diff --git a/packages/cli-rs/crates/tui/src/app.rs b/packages/cli-rs/crates/tui/src/app.rs index f8ac8017ed7..e04f839e756 100644 --- a/packages/cli-rs/crates/tui/src/app.rs +++ b/packages/cli-rs/crates/tui/src/app.rs @@ -1,4 +1,4 @@ -//! TypeScript: `packages/tui/src/app.tsx`. +//! The TUI shell, route lifecycle, and application keymap. use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; @@ -29,11 +29,10 @@ pub struct Deps { pub route: Route, pub continue_: bool, pub events: bool, - /// The built-ins from other crates, in TS order: Mermaid and LaTeX. `tui` does not depend on them, so an edit - /// there does not rebuild it. + /// Renderer plugins in registration order: Mermaid, then LaTeX. The shell receives them from the caller to avoid + /// depending on the renderers. pub builtins: Vec, - /// Runs every built-in plugin through the byte shims of the C ABI, as a loaded library runs, instead of with Rust - /// values: the other carrier, for the tests that compare the two (`carrier-equal`, P6a). + /// Run built-ins through the native plugin ABI for carrier comparison tests. pub abi_builtins: bool, } @@ -61,8 +60,7 @@ pub struct Tui { pub toasts: Toasts, pub theme: RefCell, pub directory: String, - /// The prompt textarea while it has the keymap's edit bindings (E.2 fills it). The keymap's - /// `textarea_enabled` holds while it is focused. + /// The prompt textarea with edit bindings. `textarea_enabled` also requires focus. pub textarea: Rc>>, pub prompt: crate::prompt::editor::Shared, pub settings: crate::dialogs::settings::Live, @@ -97,9 +95,9 @@ pub struct Tui { /// The routes shown before the plugin routes on screen, the latest last: where the reserved chord goes back to. before_plugin: RefCell>, view: RefCell>>, - /// The page theme the shell was last painted with, which the route view's parts read when they paint. + /// Page theme of the current route. painted: Live, - /// A theme change arrived while a key sequence was pending; remount once it ends. + /// Defer the theme remount until the pending key sequence ends. restyle: Cell, seen: Cell, /// [`Tui::hold_sync`]. @@ -153,7 +151,7 @@ impl Tui { ); } - /// The resolved config now (`useConfig().data`). Keep the borrow short: a change replaces it. + /// Borrow the current resolved config briefly: a settings change replaces it. pub fn config(&self) -> std::cell::Ref<'_, Resolved> { self.settings.config() } @@ -193,9 +191,8 @@ impl Tui { let complete = remount .then(|| self.prompt.current.borrow().upgrade().and_then(|prompt| prompt.autocomplete.get()?.take_open())) .flatten(); - // A remount of a plugin's route drops the old view once the new one is mounted, so a plugin that counts its - // mounts (`mounts()`) hears the new one begin before the old one ends, and keeps its state (review carbon-4). - // The host's own routes drop it first: the composer hands its draft on as it goes. + // Mount the new plugin view before dropping its predecessor so mount counts never reach zero. Host routes drop + // the old view first to hand over the draft. let old = self.view.borrow_mut().take(); if let Some(view) = &old { view.root().detach(); @@ -243,8 +240,7 @@ impl Tui { } } *self.view.borrow_mut() = Some(view); - // Only over the new composer when it takes the focus (now, or once the dialog closes); else the list's mode goes - // after the event, as a dropped prompt's does, and keys reach what has the focus. + // Restore list mode only when the new composer owns focus, including after a dialog closes. if let Some(open) = complete { let prompt = self.prompt.current.borrow().upgrade(); let focused = |prompt: &Rc| target == Some(prompt.textarea.as_any()); @@ -284,7 +280,7 @@ impl Tui { self.seen.get() == self.data.revision() } - /// Passes what changed since the last sync to the route view. + /// Pass changes accumulated between syncs to the route view. fn sync(&self) { if self.held.get() { return; @@ -319,9 +315,7 @@ impl Tui { crate::features::attention::program_status::sync(self); } - /// Calls `sync` with `target` and the store's changes at each flush, after the route view, until the returned - /// disposer runs or `target` is gone. An open dialog or viewer follows the store this way, on the route view's - /// update path (O-104). + /// Sync `target` after the route view on each store flush, until the disposer runs or the target drops. pub(crate) fn follow(&self, target: &Rc, sync: impl Fn(&T, &Tui, &Changes) + 'static) -> Disposer { let target = Rc::downgrade(target); let follower: Follower = @@ -344,7 +338,7 @@ impl Tui { self.app.request_redraw(); } - /// Syncs the route view with no store changes, after view state outside the store changed (E.13b's composer). + /// Refresh the route for a view change outside the store. pub(crate) fn sync_view(&self) { if let Some(view) = self.view.borrow().as_ref() { view.sync(self, &opencode_store::Changes::default()); @@ -386,9 +380,7 @@ impl Tui { self.app.set_theme(app_theme(&theme)); self.dialogs.set_theme(theme.clone()); self.toasts.set_theme(theme); - // The route view restyles in place, as TS's does, and so does a plugin's route. The diff viewer's route mounts - // again, and its focus would clear a half-typed sequence such as `l` that TS keeps, so wait for that to - // end. + // Remounting the diff viewer resets focus; defer it until the pending key sequence ends. if matches!(self.route(), Route::Plugin { .. }) && self.keymap.keymap().has_pending_sequence() { self.restyle.set(true); return; @@ -558,9 +550,7 @@ pub fn mount_with(app: &App, deps: Deps, args: Args) -> Rc { install_keys(&tui); install_theme(&tui); crate::plugins::host::count_local(&tui); - // Before the connection starts: a broadcast receiver gets only later events, and the first `server.connected` - // (terminal support, the client MCP) can arrive before mount ends. TS subscribes synchronously during mount, before - // its event stream yields anything. + // Subscribe before connecting: broadcasts do not replay the initial `server.connected` event. crate::features::events::install(&tui); let wakeups = install_wakeups(&tui, deps.events); crate::tabs::install(&tui); @@ -583,13 +573,12 @@ pub fn mount_with(app: &App, deps: Deps, args: Args) -> Rc { crate::dialogs::pair::install(&tui); crate::dialogs::model::install(&tui); crate::dialogs::integration::install(&tui); - // TS loads the built-in plugins once the first route has mounted, so the palette lists their commands first. + // Mount the route before registering built-ins to preserve palette order. let held = tui.keymap.hold(|| crate::plugins::host::install(&tui)); tui.startup.aim(&deps.route, deps.continue_); tui.navigate(deps.route); drop(held); - // After the first route's reads, as in TS, where they start during mount and the event stream connects later. - // Otherwise `session.active` can answer first and read again the running sessions the route's family read brings. + // Start route reads before the event stream to avoid reading active sessions twice. let status = deps.events.then(|| connect(&tui)); pump(&tui.app, wakeups, status); crate::features::highlights::install(&tui, deps.continue_); @@ -602,13 +591,13 @@ pub fn mount_with(app: &App, deps: Deps, args: Args) -> Rc { pub fn options() -> AppOptions { AppOptions { exit_on_ctrl_c: false, - // `terminal.suspend` (E.20) owns Ctrl+Z, so `keybinds` can turn it off. + // Let the configurable `terminal.suspend` binding own Ctrl+Z. suspend_on_ctrl_z: false, palette_size: 16, // `--print-logs` records and stray stderr writes would draw over the screen; they go to the console and // reach the real stderr once the terminal is restored. capture_stderr: true, - // `autoFocus: false` (`app.tsx:258`): a click moves no focus unless its handler does. + // A click moves focus only when its handler requests it. focus_on_click: false, ..AppOptions::default() } @@ -641,12 +630,11 @@ pub fn run_on(app: App, launch: Launch, started: impl FnOnce(&Rc) -> opentu started(&tui)?; crate::prompt::editor_context::start(&tui, crate::prompt::editor_context::Source::from_env()); let result = app.run(); - // As soon as the terminal is restored, as TS does: the teardown below runs with Ctrl+C sending SIGINT again, so a - // second press while it runs would end the process before a later summary. + // Print as soon as the terminal returns: a second Ctrl+C can interrupt teardown. if let Some(text) = crate::features::epilogue::text(&tui).filter(|_| result.is_ok()) { crate::features::epilogue::print(&text); } - // As TS's plugin context on exit: every active plugin is disposed while the TUI is still alive. + // Dispose active plugins while their TUI still exists. tui.plugins.deactivate_all(); // Their storage writes reach the disk before the process can exit; UI effects and replies are not waited for. crate::plugins::host::flush_storage(&tui); @@ -655,9 +643,7 @@ pub fn run_on(app: App, launch: Launch, started: impl FnOnce(&Rc) -> opentu result } -/// Sends keys to the keymap before any widget, as `opencode_ui::dialog::route_keys` does, with the plugins' rules -/// (synthesis 3.8): a mode the host ended goes before the key is routed, and what a plugin's handler asked for (an -/// edit of the composer, a mode, a focus) applies before the next key of the same batch. +/// Route keys before widgets. Apply plugin edits, mode changes, and focus changes before the next key in the batch. fn route_keys(tui: &Rc) { let weak = tui.weak(); tui.app.on_key_capture(move |cx, key| { @@ -687,8 +673,7 @@ fn close_plugin_surface(tui: &Tui) -> bool { tui.panels.close(tui); return true; } - // A slot surface a plugin focused (a field, `focus-input`): the composer takes the focus back, and the chord stops - // there, so neither the composer's draft nor the app is lost to it (carbon c2a-1). + // The reserved chord returns focus from a plugin field to the composer without clearing its draft or exiting. if tui.router.surface_focused(tui) && !matches!(tui.route(), Route::Plugin { .. }) { opencode_plugin::Host::focus_composer(tui); if opencode_plugin::Host::composer_focused(tui) { @@ -701,7 +686,7 @@ fn close_plugin_surface(tui: &Tui) -> bool { return false; } let back = tui.before_plugin.borrow_mut().pop().unwrap_or(Route::Home); - // Going back to an earlier plugin route keeps what was before it. + // Preserve the back stack when returning to a plugin route. let rest = std::mem::take(&mut *tui.before_plugin.borrow_mut()); tui.navigate(back); if matches!(tui.route(), Route::Plugin { .. }) { @@ -711,7 +696,7 @@ fn close_plugin_surface(tui: &Tui) -> bool { } fn install_keys(tui: &Rc) { - // The reserved chord resets the plugins' input before anything may stop it, and goes on (synthesis 3.8). + // Reset plugin input before routing the reserved chord. let weak = tui.weak(); tui.app.on_key_capture(move |cx, key| { let Some(tui) = weak.upgrade() else { return }; @@ -727,17 +712,14 @@ fn install_keys(tui: &Rc) { cx.stop_propagation(); } }); - // Console copy, then the selection keys, go before the keymap (E.20). crate::features::console_copy::install(tui); crate::features::selection::install(tui); - // A focused terminal takes keys before the keymap (E.13a). crate::terminal::install_keys(tui); route_keys(tui); tui.layers.borrow_mut().push(opencode_ui::dialog::expire_leader(&tui.app, &tui.keymap)); tui.keymap.set_first_layer(app_commands()); - // As `app.tsx:1303-1335`: the commands live in a global layer without bindings, so the palette - // reaches them over a dialog, and separate layers bind their keys. + // Keep commands globally available to the palette over dialogs; bind their keys in separate layers. let weak = tui.weak(); let command = |id: &str, run: fn(&Tui)| TuiCommand::new(id, bind!(weak, |tui, _, _| run(&tui))).bind(Bind::Off); let commands = KeymapLayer::global(vec![ @@ -789,7 +771,6 @@ fn install_keys(tui: &Rc) { palette::show(&tui.dialogs, crate::dialogs::settings::palette_options(tui), Some(run)) }), ]); - // `app.exit`'s keys work unless the focused prompt has text (`app.tsx:1329-1335`). let exit = KeymapLayer::default() .enabled({ let app = tui.app.clone(); @@ -816,7 +797,7 @@ fn install_keys(tui: &Rc) { } } -/// `appCommands` (`app.tsx:752-1300`) in its order, the layer the palette lists last (D131). +/// Application commands in palette order. fn app_commands() -> Vec { let names = |names: &[&str]| names.iter().map(|name| (*name).to_owned()).collect::>(); let numbered = |prefix: &str, count: usize| (1..=count).map(|n| format!("{prefix}{n}")).collect::>(); @@ -881,7 +862,7 @@ fn install_theme(tui: &Rc) { tui.theme.borrow_mut().terminal_mode(mode); tui.theme_changed(); })); - // TS reads the palette again on `?997` (`theme.tsx:263-268`), so `system` follows a terminal theme switch. + // Re-read the palette on `?997` so the system theme follows the terminal. tui.app.on_color_scheme(bind!(tui, |tui, _| { tui.theme.borrow_mut().colors_changed(); tui.theme_changed(); @@ -957,7 +938,7 @@ fn install_wakeups(tui: &Rc, connect: bool) -> Wakeups { &tui, state ))); - // Offline until the connection reports connected, so reads behind `refresh` wait for it as in TS. + // Start offline so refresh waits for the first connection. if connect { tui.data.set_online(false); } @@ -1128,8 +1109,6 @@ mod tests { Arc::new(serde_json::from_value(serde_json::json!({ "id": "evt_1", "type": kind, "data": {} })).unwrap()) } - // Expected: the first layer is `appCommands` of the TS source, name for name; a `${i + 1}` name stands for each - // number its `Array.from({ length })` makes. #[test] fn the_first_layer_follows_app_tsx() { let source = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../tui/src/app.tsx")).unwrap(); @@ -1151,8 +1130,6 @@ mod tests { assert_eq!(app_commands(), names); } - // Expected: a full UI queue (a burst, a suspended terminal) delays the pump's store revisions, signals and - // connection changes; once it drains they arrive, and later ones still do (reviews bigboi-1 and carbon-2). #[test] fn a_full_queue_delays_the_pump_but_never_stops_it() { let app = TestApp::new(10, 4); diff --git a/packages/cli-rs/crates/tui/src/client_mcp/mod.rs b/packages/cli-rs/crates/tui/src/client_mcp/mod.rs index 028df93e77b..056d5767303 100644 --- a/packages/cli-rs/crates/tui/src/client_mcp/mod.rs +++ b/packages/cli-rs/crates/tui/src/client_mcp/mod.rs @@ -1,9 +1,5 @@ -//! The client MCP socket (E.13b, rows A05 and X03): `context/client-mcp.tsx`. -//! -//! While the `client-mcp` experiment is on, the TUI serves two tools to the server as the client MCP server `tui`, so -//! the model sees `tui_open_terminal` and `tui_write_terminal`. Both act on the terminal of the calling session's -//! family that this TUI shows: the routed session if it is in that family, else the family's root while it is open in -//! a tab. The socket reconnects when the flag, the viewed location, or the server changes. +//! The client MCP socket exposes terminal tools for the current session family. Reconnect when the experiment, +//! location, or server changes. use std::sync::{Arc, Mutex}; diff --git a/packages/cli-rs/crates/tui/src/features/attention/focus.rs b/packages/cli-rs/crates/tui/src/features/attention/focus.rs index ae52fd433c3..e0fc4b1ff7c 100644 --- a/packages/cli-rs/crates/tui/src/features/attention/focus.rs +++ b/packages/cli-rs/crates/tui/src/features/attention/focus.rs @@ -1,8 +1,4 @@ -//! Focus rules (E.19a, rows N01 and N04, `attention.ts:22,78-102`): the terminal's focus as its focus reports -//! last said, and whether a notification or sound asked for `always`, `focused`, or `blurred` goes out. -//! -//! The focus is unknown until the first report, so a `focused` or `blurred` request waits on a terminal that -//! reports focus. `app::mount` calls [`install`] once. +//! Terminal focus is unknown until the first report. Focus-dependent notifications and sounds wait for it. use crate::prelude::*; diff --git a/packages/cli-rs/crates/tui/src/features/attention/notify.rs b/packages/cli-rs/crates/tui/src/features/attention/notify.rs index fde16fb929d..ff46a7c7367 100644 --- a/packages/cli-rs/crates/tui/src/features/attention/notify.rs +++ b/packages/cli-rs/crates/tui/src/features/attention/notify.rs @@ -1,9 +1,4 @@ -//! Notifications (E.19a, row N01, `attention.ts:35-189`): the attention service plugins call (TS -//! `context.attention.notify`). A request becomes a desktop notification through the terminal when -//! `attention.notifications` is on and its focus rule holds, and its sound plays (E.19b, [`super::sound`]) when -//! `attention.sound` is on and the sound's focus rule holds. -//! -//! `app::Tui` holds one [`Attention`]; `app::mount` calls [`install`] once. +//! Desktop notifications and sounds obey separate focus rules and settings. use std::cell::{Cell, RefCell}; use std::sync::LazyLock; diff --git a/packages/cli-rs/crates/tui/src/features/attention/program_status.rs b/packages/cli-rs/crates/tui/src/features/attention/program_status.rs index a1af05e72a4..32b7c970a1c 100644 --- a/packages/cli-rs/crates/tui/src/features/attention/program_status.rs +++ b/packages/cli-rs/crates/tui/src/features/attention/program_status.rs @@ -1,10 +1,4 @@ -//! Program status (E.19a, row N03, `context/program-status.ts`, `context/session-tabs.tsx:180-200`): OSC 7501 -//! records that mirror the sessions waiting on the user or working. There is one root summary plus one record -//! per pending session among the open tabs and the viewed session. Terminals drop working and blocked records -//! when the process exits, and quitting clears the root. -//! -//! `Tui::sync`, `Tui::navigate`, and the tabs call [`sync`]; `app.exit` calls [`clear`] before the terminal is -//! released. Records are not sent again after a suspend and resume (G.4). +//! OSC 7501 publishes a root summary and records for pending sessions. Clear the root before releasing the terminal. use std::sync::LazyLock; @@ -58,10 +52,10 @@ impl Record { } } -/// The records the terminal took, by ID, in the order they were first sent. +/// Terminal records by ID, in insertion order. pub type Sent = IndexMap; -/// Sends the records that changed since the last sync. +/// Send changed status records. pub fn sync(tui: &Tui) { let reports = reports(&pending(tui)); let mut sent = tui.attention.program.borrow_mut(); @@ -102,7 +96,7 @@ fn pending(tui: &Tui) -> Vec { .collect() } -/// `title` of `session-tabs.tsx` without a persisted title: the store's, else the timestamped fallback. +/// Prefer the stored session title; fall back to its timestamp. fn title(tui: &Tui, id: &str) -> Option { tui.data.read(|state| { let info = state.session(&SessionID(id.to_owned()))?; diff --git a/packages/cli-rs/crates/tui/src/features/attention/sound.rs b/packages/cli-rs/crates/tui/src/features/attention/sound.rs index 96bb92d5a27..01326cf204f 100644 --- a/packages/cli-rs/crates/tui/src/features/attention/sound.rs +++ b/packages/cli-rs/crates/tui/src/features/attention/sound.rs @@ -1,10 +1,5 @@ -//! Sounds (E.19b, row N02): `attention.ts:36-43,77-121` and `audio.ts`. A request's sound name picks the -//! `attention.sounds` override, then the bundled sound (`attention-sounds.bun.ts`); the first that loads and plays wins. -//! The volume is the request's, else `attention.volume`, clamped to 0..1. -//! -//! The engine (OpenTUI's native audio) starts on the first sound. Only the real terminal app opens a playback device -//! ([`Output::Device`]); every other app, tests included, mixes without one, so nothing plays out loud and -//! [`Player::audio`] can read what would have. +//! Prefer configured sounds over bundled ones. The audio engine starts on demand; headless clients mix without a +//! playback device. use std::cell::{Cell, OnceCell, RefCell}; use std::collections::HashMap; diff --git a/packages/cli-rs/crates/tui/src/features/clear.rs b/packages/cli-rs/crates/tui/src/features/clear.rs index 9d891e33db1..3f125b712cf 100644 --- a/packages/cli-rs/crates/tui/src/features/clear.rs +++ b/packages/cli-rs/crates/tui/src/features/clear.rs @@ -1,6 +1,4 @@ -//! `session.clear` (`/clear`, row T25, `app.tsx:802-827`): closes the session's tab and goes home in the -//! new-session location, keeping the agent and model the session had. `session.new` (`app.tsx:775-800`) is the same -//! without closing the tab. +//! Both session commands keep the agent and model. Only `/clear` closes the current tab. use opencode_local::cli_config::NewLocation; use opencode_store::Location; diff --git a/packages/cli-rs/crates/tui/src/features/console_copy.rs b/packages/cli-rs/crates/tui/src/features/console_copy.rs index c8bdd4c55b9..5570b9fe19c 100644 --- a/packages/cli-rs/crates/tui/src/features/console_copy.rs +++ b/packages/cli-rs/crates/tui/src/features/console_copy.rs @@ -1,6 +1,4 @@ -//! Console copy (E.20, row T28): Ctrl+Y in the console overlay copies the selected text with the "Copied to -//! clipboard" toast and clears the selection (`app.tsx:261-263,601-611`). TS binds the key in the console's own -//! options; here it is a key handler that acts only while the console is visible. +//! Ctrl+Y copies the console selection while the overlay is visible. use crate::prelude::*; diff --git a/packages/cli-rs/crates/tui/src/features/devtools.rs b/packages/cli-rs/crates/tui/src/features/devtools.rs index 1fd00269642..79763a031fb 100644 --- a/packages/cli-rs/crates/tui/src/features/devtools.rs +++ b/packages/cli-rs/crates/tui/src/features/devtools.rs @@ -1,4 +1,4 @@ -//! TypeScript: `packages/tui/src/component/devtools-bar.tsx`, `app.tsx:497`. +//! Developer tools bar and runtime samples. use opencode_api::events::{State, Status}; use opencode_api::generated::ExperimentalSessionLogInput; @@ -148,8 +148,7 @@ struct Bar { dump: RefCell>>, focus: RefCell>, first_draw: Cell>, - /// The items and actions of this render. Their handlers hold them weakly, since a widget whose handler holds the - /// widget is never freed. + /// Handlers hold widgets weakly to avoid ownership cycles. shown: RefCell>>, /// The item or action a press landed on, kept until its release so that redraws in between do not drop it. pressed: RefCell>>, @@ -229,8 +228,7 @@ fn install_connection(tui: &Rc, bar: &Rc) { }); } -/// Takes a UI sample now and every 2 s while the bar shows: CPU, memory, and how late the sampling timer fired. A -/// hidden bar reads nothing and starts over when it shows again, as TS mounts the bar afresh. +/// Sample CPU, memory, and timer delay every two seconds while visible. Reopening starts a new sample series. fn install_samples(tui: &Rc, bar: &Rc) { let last = Cell::new((tui.app.now(), 0.0, false)); let sample = bind!(bar, |bar, now: Instant| { @@ -689,7 +687,7 @@ impl Bar { } } -/// Runs `run` after the current event, since bar handlers run inside widgets a render replaces. +/// Defer the action past the event: painting replaces the handler's widget. fn defer(tui: &Tui, run: impl FnOnce(&Tui) + 'static) { tui.app.defer(bind!(tui, |tui, _| run(&tui))); } @@ -797,7 +795,7 @@ fn memory() -> f64 { opencode_util::win::resident_memory().map_or(0.0, |bytes| bytes as f64) } -/// Milliseconds since the process started (`performance.now()` at the first draw). +/// Process uptime in milliseconds. #[cfg(windows)] fn process_age_ms() -> f64 { opencode_util::win::process_times().map_or(0.0, |times| times.age_ms.max(0.0)) @@ -823,7 +821,7 @@ fn memory() -> f64 { .map_or(0.0, |kilobytes| kilobytes * 1024.0) } -/// Milliseconds since the process started (`performance.now()` at the first draw), from `/proc` on Linux. +/// Process uptime in milliseconds from Linux `/proc`. #[cfg(not(windows))] fn process_age_ms() -> f64 { const TICKS: f64 = 100.0; diff --git a/packages/cli-rs/crates/tui/src/features/drive.rs b/packages/cli-rs/crates/tui/src/features/drive.rs index e2438d27d99..c9d36726988 100644 --- a/packages/cli-rs/crates/tui/src/features/drive.rs +++ b/packages/cli-rs/crates/tui/src/features/drive.rs @@ -1,4 +1,4 @@ -//! TypeScript: `app.tsx:276-279`. +//! Headless simulation endpoint. use crate::app::{Launch, Tui}; use opencode_drive::Manifest; @@ -12,8 +12,7 @@ pub fn manifest() -> Option> { .map(|manifest| manifest.map_err(opentui::Error::other)) } -/// Runs the TUI on a headless app at the manifest's viewport (100 by 40 without one, as `renderer.ts` sizes it) and -/// serves the endpoint until the TUI quits. +/// Serve the headless TUI at the manifest viewport, defaulting to 100 by 40, until it quits. pub fn run(manifest: Manifest, options: AppOptions, launch: Launch) -> opentui::Result<()> { let (width, height) = manifest.viewport.unwrap_or((100, 40)); let app = App::headless(HeadlessOptions { diff --git a/packages/cli-rs/crates/tui/src/features/epilogue.rs b/packages/cli-rs/crates/tui/src/features/epilogue.rs index d8dd303b42a..1153f67c785 100644 --- a/packages/cli-rs/crates/tui/src/features/epilogue.rs +++ b/packages/cli-rs/crates/tui/src/features/epilogue.rs @@ -1,8 +1,4 @@ -//! What the TUI prints after it exits (E.1, row G14): the wordmark, the updated version, and the open -//! session with the command that continues it (`util/presentation.ts`, `app.tsx:485-490`). -//! -//! E.18b records an installed update with [`Epilogue::updated_version`]. `app::run` [`print`]s [`text`] once the -//! terminal is restored. +//! Exit summary and command to continue the last session. use crate::prelude::*; @@ -26,9 +22,7 @@ impl Epilogue { } } -/// The text to print after exit, or none when there is nothing to say. The session is the one the session -/// route shows when the TUI quits, its title cut to 50 characters (`Locale.truncate`). An untitled session reads -/// "New session" or "Child session" (`displayLabel`), where TS prints an empty title (D131-epilogue-untitled). +/// Build the exit text from the current session. An untitled session uses its display label. pub fn text(tui: &Tui) -> Option { let session = match tui.route() { Route::Session { id } => { @@ -46,16 +40,13 @@ pub fn text(tui: &Tui) -> Option { }; let session = session.as_ref().map(|(title, id)| (title.as_str(), id.0.as_str())); let updated = tui.epilogue.updated_version.borrow().clone(); - // The command name in the continue hint. TS prints "opencode"; this client names itself, so the hint - // reopens the client the user ran. + // Use this client's executable name so the hint reopens it. let cli_name = std::env::var("OPENCODE_CLI_NAME").unwrap_or_else(|_| "opencode-native".to_owned()); render(session, updated.as_deref(), &cli_name) } -/// Prints `text` and a newline on stdout (`process.stdout.write(text + "\n")`), once the renderer has put the terminal -/// back. On Windows that turned the console's escape sequences off again, and conhost would show the colors as -/// `←[90m`; TS writes through libuv, which turns them on for a console it writes to. So they go on for this write, -/// and back to what they were after it. +/// Print the exit text after terminal restoration. Windows console output needs escape processing enabled until the +/// write flushes. pub fn print(text: &str) { let _ = write(&mut Stdout::default(), &mut std::io::stdout().lock(), text); } @@ -177,8 +168,6 @@ mod tests { assert!(text.contains("\x1b[1mxy\x1b[0m"), "{text:?}"); } - /// D131 N1: the renderer has restored the console when the epilogue is written, so the write turns escape - /// sequences on before it and restores the mode only once the text is flushed. #[test] fn writes_with_escape_sequences_on() { struct Log<'a>(&'a RefCell>); diff --git a/packages/cli-rs/crates/tui/src/features/events.rs b/packages/cli-rs/crates/tui/src/features/events.rs index 600600ca970..b50a0ac9d91 100644 --- a/packages/cli-rs/crates/tui/src/features/events.rs +++ b/packages/cli-rs/crates/tui/src/features/events.rs @@ -1,15 +1,5 @@ -//! Server-driven events (E.1, rows T10 to T12, `app.tsx:556-584,1338-1377`): -//! -//! - `tui.command.execute`, `tui.toast.show`, `tui.session.select`, and `tui.prompt.append` -//! (`prompt/index.tsx:341-352`), for the current location only; -//! - `session.deleted` of the open session goes home with a toast; -//! - `session.execution.succeeded` of the open session reloads the usage limits (`usage.tsx:219-223`); -//! - a toast when an MCP server of the default location fails or needs authentication, once per state. -//! -//! `session.moved` updates the open dialog's cache, which E.11a replaced with the store's sessions. -//! `app::mount` calls [`install`] once and `Tui::sync` calls [`sync`]. The app's pump posts each store signal once as -//! a [`Signal`]; [`handle`] sees it first, then every [`subscribe`]r in order. When it skipped signals, it posts -//! [`Lagged`] instead. +//! Dispatch store signals to the TUI, then subscribers in registration order. A missed broadcast sends `Lagged` so +//! consumers can resync. use std::sync::Arc; @@ -20,7 +10,7 @@ use crate::prelude::*; type Subscribers = Rc)>>>; type DeltaSubscribers = Rc, Rc)>>>; -/// The last status each MCP server was alerted for, and the signal and delta subscribers. +/// Last reported MCP status per server and subscribers to signals and deltas. #[derive(Default)] pub struct Events { alerted: RefCell>, @@ -77,8 +67,7 @@ handled! { pub fn install(tui: &Tui) { std::mem::forget(tui.data.listen(HANDLED.iter().map(|(tag, _)| *tag))); tui.app.on_message(bind!(tui, |tui, _, Signal(event)| { - // What the plugins asked for while the signal before it was handled runs first (`opencode_plugin::flush`): a - // signal runs plugin handlers and can navigate. + // Flush the previous signal's plugin actions before the next signal can navigate. opencode_plugin::flush(); if let Some(event) = Handled::of(event) { handle(&tui, &event); @@ -125,7 +114,7 @@ fn resync(tui: &Tui) { handle(tui, &Handled::SessionDeleted(&event)); } tui.resync(); - // The subscribers missed what changed too, as across a reconnect: they hear it as one (carbon's review of P6c, 6). + // Notify subscribers to resync after a missed broadcast, as on reconnect. let event = V2Event::ServerConnected(V2EventServerConnected { r#type: "server.connected".to_owned(), ..V2EventServerConnected::default() @@ -157,8 +146,7 @@ pub fn subscribe>( }) } -/// Calls `subscriber` with the streaming deltas the store applied since it last called it, or since it subscribed, -/// once a frame that has any, until the disposer drops (the plugins' `on_deltas`). +/// Deliver accumulated streaming deltas once per frame until the subscription is disposed. pub fn subscribe_deltas(tui: &Tui, subscriber: impl Fn(&[V2Event]) + 'static) -> Disposer { let id = tui.events.next.get(); tui.events.next.set(id + 1); @@ -207,7 +195,7 @@ fn handle(tui: &Tui, event: &Handled) { crate::features::quick_switch::event(tui, event); crate::dialogs::worktrees::event(event); crate::dialogs::open::event(event); - // Every connection, also one the connection status coalesced (`context/location.tsx`). + // Include connections that coalesce into a single status change. if let Handled::ServerConnected(_) = event { crate::features::location::reconnected(tui); } diff --git a/packages/cli-rs/crates/tui/src/features/foreground.rs b/packages/cli-rs/crates/tui/src/features/foreground.rs index 8e86f695d18..1be7169ec19 100644 --- a/packages/cli-rs/crates/tui/src/features/foreground.rs +++ b/packages/cli-rs/crates/tui/src/features/foreground.rs @@ -96,8 +96,7 @@ thread_local! { static EXITED: RefCell> = RefCell::default(); } -/// Runs `exited` each time a plugin's program exits, before its reply goes, or nothing for `None`: a test closes a -/// mount between a program's launch and its reply (bigboi's ownership pass). +/// Run `exited` between a foreground program's exit and delivery of its reply. `None` removes the hook. #[doc(hidden)] pub fn on_exit(exited: Option) { EXITED.set(exited); diff --git a/packages/cli-rs/crates/tui/src/features/highlights.rs b/packages/cli-rs/crates/tui/src/features/highlights.rs index 7d19b751d31..056959cb977 100644 --- a/packages/cli-rs/crates/tui/src/features/highlights.rs +++ b/packages/cli-rs/crates/tui/src/features/highlights.rs @@ -1,10 +1,5 @@ -//! Release highlights (E.18b, rows DLG08 and T03): `opencode.highlights` (`/highlights`, `app.tsx:1033-1043`) and the -//! auto-open once after an update (`app.tsx:728-750`, `util/highlights.ts`). -//! -//! As in TS, only stable release builds embed highlights (`OPENCODE_RELEASE_HIGHLIGHTS` at build time, a JSON array -//! of `{ title, body }`); every other build has none, so the command is not registered. The auto-open runs once, -//! when the event connection first connects, into an idle home screen, and claims the version in the `highlights` -//! storage under its lock, so only one of several TUIs starting together shows it. +//! Stable builds embed release highlights. The first idle home screen to claim the version in shared storage shows +//! them. use crate::dialogs::highlights::{self, Highlight}; use crate::prelude::*; diff --git a/packages/cli-rs/crates/tui/src/features/home_forms.rs b/packages/cli-rs/crates/tui/src/features/home_forms.rs index 729e2bd7318..11d6a1a84e7 100644 --- a/packages/cli-rs/crates/tui/src/features/home_forms.rs +++ b/packages/cli-rs/crates/tui/src/features/home_forms.rs @@ -1,6 +1,4 @@ -//! The global form overlay on home (E.9b, row T30; `routes/home.tsx:36-38,109-120`). Global MCP elicitations can -//! arrive without a session route, so home shows the first one of its location over the screen's bottom. The home -//! prompt keeps its place but takes no keys meanwhile. +//! Show the current location's global form over home. The prompt keeps its place but yields its keys. use opencode_store::Location; use opencode_store::forms::GLOBAL; diff --git a/packages/cli-rs/crates/tui/src/features/links.rs b/packages/cli-rs/crates/tui/src/features/links.rs index 6f8c69be2c7..845cdbd7158 100644 --- a/packages/cli-rs/crates/tui/src/features/links.rs +++ b/packages/cli-rs/crates/tui/src/features/links.rs @@ -1,12 +1,5 @@ -//! Clickable links and opening URLs and paths (E.20, row T23): `ui/link.tsx`, `@opencode/util/open`, and the -//! root `onMouseUp` of `app.tsx:1419-1423`. -//! -//! A plain left click on a cell that carries a hyperlink opens it: a press and a release on the same cell, with -//! no modifier and no selected text. TS reads that from the selection (`isStart` with `cell` behavior); here the -//! press position stands in for it. Modified clicks are left to the terminal. -//! -//! [`open_url`] and [`open_path`] start the system opener. Tests call [`testing::capture`] first, so nothing -//! opens a browser or file manager. +//! Open a link only for an unmodified press and release on the same cell with no selection. Leave modified clicks to +//! the terminal. use crate::prelude::*; diff --git a/packages/cli-rs/crates/tui/src/features/location.rs b/packages/cli-rs/crates/tui/src/features/location.rs index b8c5e624c41..c116ac44f0b 100644 --- a/packages/cli-rs/crates/tui/src/features/location.rs +++ b/packages/cli-rs/crates/tui/src/features/location.rs @@ -1,10 +1,5 @@ -//! The current location (E.1, `context/location.tsx`): the location the home or the open session works in, -//! read with `location.sync` while connected, and the "location not found" error the session route shows as -//! the location-missing view (row T18). -//! -//! Home sets its target (the one [`navigate_home`] passed, else the default), the session route sets the -//! session's location, and every new connection reads it again. Opening a session also uploads the -//! terminal's environment to it when the server is local (row G13, `app.tsx:529-539`). +//! Track the location of home or the open session. On reconnect, refresh it and upload the terminal environment only to +//! a local server. use opencode_store::location::Catalog; use opencode_store::{Error, Location}; @@ -61,8 +56,7 @@ pub fn home(tui: &Tui) { set(tui, explicit.unwrap_or(default)); } -/// A home without a location of its own moves with the default, as a read adopts the server's directory -/// (`home.tsx`'s effect). A `/cd` holds until the default changes. +/// A home without its own location follows the default. A `/cd` selection lasts until the default changes. pub fn follow_default(tui: &Tui) { let default = tui.data.read(|state| state.default_location().clone()); let mut followed = tui.location.followed.borrow_mut(); @@ -97,8 +91,7 @@ pub(crate) fn reconnected(tui: &Tui) { } } -/// The status turned connected: uploads the open session's environment again. TS runs the upload as an -/// effect of the connection status (`app.tsx:529-539`), which turns connected after `server.connected`. +/// Upload the open session's environment when its connection becomes ready. pub(crate) fn connected_again(tui: &Tui) { tui.location.uploaded.borrow_mut().take(); if let Route::Session { id } = tui.route() { diff --git a/packages/cli-rs/crates/tui/src/features/overlays.rs b/packages/cli-rs/crates/tui/src/features/overlays.rs index 2b66b530880..64f4e400a6f 100644 --- a/packages/cli-rs/crates/tui/src/features/overlays.rs +++ b/packages/cli-rs/crates/tui/src/features/overlays.rs @@ -1,15 +1,5 @@ -//! App-wide overlays (E.1, rows T04 to T07): -//! -//! - the reconnecting overlay, shown 1 s into reconnecting or 5 s into the first connection -//! (`app.tsx:1379-1403`, `component/reconnecting.tsx`); -//! - the data migration overlay, which polls the V1 migration status from 1 s after the first connection -//! (`component/migration-overlay.tsx`; TS starts 1 s after mount); -//! - the startup loading screen waits for TS plugins to load (`component/startup-loading.tsx`). Built-in -//! Rust plugins are ready at mount, so it never shows, as in TS when plugins load within 500 ms; -//! - the error boundary screen (`component/error-component.tsx`) has no Rust equivalent: a panic in the UI -//! restores the terminal and ends the process (see the E.1 report). -//! -//! `app::mount` calls [`install`] once and [`connection_changed`] on every connection state. +//! Connection and data-migration overlays. Delay the first reconnect indication longer than subsequent ones to avoid +//! flashing during startup. use opencode_api::events::{State, Status}; use opencode_ui::motion::Spinner; @@ -42,8 +32,7 @@ pub fn connection_changed(tui: &Tui, state: &State) { } let connected = state.status == Status::Connected; if connected && !overlays.connected.replace(true) { - // TS polls 1 s after mount whatever the connection; polling from the first connection keeps a - // server that is still starting from showing "Data migration failed". + // Wait for a connection before polling; a starting server must not look like a failed migration. if !overlays.polling.replace(true) { let weak = tui.weak(); tui.app.set_timeout(MIGRATION_POLL, move |_| poll_migration(&weak)); @@ -112,7 +101,7 @@ fn reconnecting(tui: &Tui) -> View { .child(&panel) } -/// One `v1.status` read; a running migration shows its progress, and polling stops once it completed. +/// Read migration status and continue polling while it runs. fn poll_migration(weak: &Weak) { let Some(tui) = weak.upgrade() else { return }; let client = tui.data.client().clone(); diff --git a/packages/cli-rs/crates/tui/src/features/quick_switch.rs b/packages/cli-rs/crates/tui/src/features/quick_switch.rs index a9daf6441e3..a3c61e24be4 100644 --- a/packages/cli-rs/crates/tui/src/features/quick_switch.rs +++ b/packages/cli-rs/crates/tui/src/features/quick_switch.rs @@ -1,6 +1,4 @@ -//! Quick switch (E.11b, row W03; `app.tsx:841-848,1323-1327`, `context/local.tsx:549-601`): with tabs off, -//! `1` to `9` open the pinned root sessions in pin order. Pins are toggled in the session -//! list (`session.pin.toggle`, `dialogs::session_list::pins`); a deleted session loses its pin. +//! With tabs off, the leader and a digit open pinned root sessions in pin order. use crate::dialogs::session_list::pins; use crate::features::events::Handled; diff --git a/packages/cli-rs/crates/tui/src/features/route_missing.rs b/packages/cli-rs/crates/tui/src/features/route_missing.rs index 7a41393d4bf..4e1606c3b32 100644 --- a/packages/cli-rs/crates/tui/src/features/route_missing.rs +++ b/packages/cli-rs/crates/tui/src/features/route_missing.rs @@ -1,6 +1,4 @@ -//! The missing plugin route screen (E.1, row T26, `component/plugin-route-missing.tsx`): the route's name in -//! the warning color and a "go home" button, centered. The route of a plugin that failed says that instead, and points -//! to `/plugins` (PL-8, deviation `F16-plugin-failed-route`). +//! Explain unavailable plugin routes and direct the user to the plugin manager after a failure. use crate::prelude::*; diff --git a/packages/cli-rs/crates/tui/src/features/selection.rs b/packages/cli-rs/crates/tui/src/features/selection.rs index 0f7109aa345..ef615453124 100644 --- a/packages/cli-rs/crates/tui/src/features/selection.rs +++ b/packages/cli-rs/crates/tui/src/features/selection.rs @@ -1,21 +1,11 @@ -//! Text selection and copy (E.20, rows T13 and CB01): `util/selection.ts`, `app.tsx:586-611`, and the clipboard -//! write of `clipboard.ts:53-61`. -//! -//! - With `terminal.copy: "select"` (the default outside Windows), releasing a drag copies the selected text. -//! - With `"manual"`, a right click copies it, and Ctrl+C copies it instead of exiting. -//! - Ctrl+C under copy-on-select, Escape, and any other key clear the selection; Ctrl+C and Escape go on to the -//! keymap only when there was nothing to copy or clear. A key aimed at the focused prompt keeps the prompt's -//! own selection, as TS keeps an editor's. -//! -//! [`copy`] is the one clipboard write of the TUI: it drops NUL, then writes OSC 52 and the host clipboard -//! (`App::copy_to_clipboard`, G.4), and toasts. +//! Selection and clipboard handling. The focused editor keeps its own selection; Ctrl+C copies or clears a selection +//! before the exit binding runs. use opencode_local::cli_config::TerminalCopy; use crate::prelude::*; -/// Registers the selection keys, the release copy, and the right-click copy. `app::install_keys` calls it before -/// the keymap's key handler, as TS intercepts selection keys at priority 101 (`app.tsx:589-596`). +/// Install selection handling before the keymap so copying a selection takes priority. pub fn install(tui: &Rc) { let weak = tui.weak(); tui.app.on_key_capture(bind!(weak, |tui, cx, key| handle_key(&tui, cx, key))); @@ -87,8 +77,7 @@ pub fn put(app: &App, text: &str) -> bool { fn handle_key(tui: &Tui, cx: &mut Cx<'_>, key: &KeyEvent) { let Some(text) = tui.app.selected_text() else { return }; - // TS checks that the focused editor is part of the mouse selection; a keyboard selection in the prompt - // ends the mouse selection here, so the prompt's own selection is the one that counts. + // A keyboard selection in the prompt takes precedence over the mouse selection. let editing = tui.textarea.borrow().as_ref().is_some_and(|textarea| { tui.app.focused().is_some_and(|widget| widget.id() == textarea.id()) && !textarea.selected_text().is_empty() }); diff --git a/packages/cli-rs/crates/tui/src/features/session_links.rs b/packages/cli-rs/crates/tui/src/features/session_links.rs index 447178ceff9..6f9800738c4 100644 --- a/packages/cli-rs/crates/tui/src/features/session_links.rs +++ b/packages/cli-rs/crates/tui/src/features/session_links.rs @@ -1,10 +1,5 @@ -//! Session IDs as links (`ui/session-link.ts`, `useSessionLinks`, #63224 and #63247): a Markdown that names another -//! session by ID shows it as `@` (the ID itself when markers are shown) in `markup.link.url`, underlined, and -//! a plain click on it opens that session. The current session, archived sessions and sessions that cannot be loaded -//! stay plain IDs. When a title changes, only the blocks that mention that session are drawn again. -//! -//! The transcript's text parts, the compaction summary and the `/btw` answer use it, through [`attach`]; other -//! plugins' Markdown does not, as in TS. +//! Link known, unarchived session IDs in transcript text, compaction summaries, and `/btw` answers. Title changes +//! invalidate only blocks that mention the session. use std::collections::HashSet; @@ -16,7 +11,7 @@ use crate::prelude::*; /// A Markdown with session links. Its owner holds it; the TUI's [`Registry`] and the click handler hold it weakly. pub struct Links { pub markdown: Markdown, - /// The label each mentioned ID was last drawn with (`None`: plain), so a sync draws again only on a change. + /// Last rendered label by ID; `None` denotes an unlinked ID. used: Rc<RefCell<HashMap<SessionID, Option<String>>>>, /// Where a plain left press went down, until its release. pressed: Cell<Option<(u16, u16)>>, @@ -114,7 +109,7 @@ fn link_spans( spans: Vec<InlineSpan>, cx: &InlineContext<'_>, ) -> Vec<InlineSpan> { - // Core never passes table cells to the chunk callback, so TS shows their IDs as written. + // Table cells bypass the chunk callback and keep literal IDs. if cx.table_cell { return spans; } diff --git a/packages/cli-rs/crates/tui/src/features/startup.rs b/packages/cli-rs/crates/tui/src/features/startup.rs index b69fd7a5985..7a19d61cd6f 100644 --- a/packages/cli-rs/crates/tui/src/features/startup.rs +++ b/packages/cli-rs/crates/tui/src/features/startup.rs @@ -1,10 +1,5 @@ -//! Startup flows (E.1, rows T02, T14b and T27): `--continue`, `--session` with and without `--fork`, -//! `--prompt`, a new session ID taken from `--session`, `--agent` and `--model`, and `OPENCODE_ROUTE` -//! (`app.tsx:664-726`, `context/args.tsx`, `context/route.tsx:48-69`). C.13 adds where `--prompt` goes. -//! -//! `app::mount` mounts the initial route, then calls [`run`]. The root command resolves `--session` -//! first: an ID the server knows opens that session; any other becomes [`Startup::take_new_session_id`], -//! the ID of the first session the home prompt creates. +//! Resolve the initial route, model, agent, and prompt. An unknown `--session` ID becomes the ID of the first session +//! created from home. use indexmap::IndexMap; use opencode_api::generated::{SessionForkInput, SessionListInput, SessionListInputOrder}; @@ -27,7 +22,7 @@ pub struct Args { pub server_executable: Option<std::path::PathBuf>, pub auto: bool, pub environment: Option<IndexMap<String, String>>, - /// What the parent tells a client it starts after a plugin crash (P4c). + /// State passed to a client restarted after a plugin crash. pub contain: crate::plugins::contain::Contain, } @@ -57,8 +52,7 @@ pub struct Startup { prompt: RefCell<Option<Target>>, } -/// Which prompt receives `--prompt`: TS hands it to the first home, or through `route.prompt` to the -/// session that startup opens. +/// Destination for `--prompt`: home or the session selected at startup. #[derive(Clone, Debug, PartialEq)] enum Target { Home, @@ -118,14 +112,13 @@ impl Startup { self.new_session_id.borrow_mut().get_or_insert(id); } - /// `--model` as `provider/model`, once it parsed (`util/model.ts` `parse`). + /// Parse `--model` as `provider/model`. pub fn model(&self) -> Option<(String, String)> { parse_model(self.args.model.as_deref()?) } } -/// `OPENCODE_ROUTE`: a JSON route for the first screen (`context/route.tsx` `initialRoute`). Anything that is -/// not a route reads as none. +/// Decode the initial route from `OPENCODE_ROUTE`, ignoring invalid values. pub fn env_route(value: &str) -> Option<Route> { let value: serde_json::Value = serde_json::from_str(value).inspect_err(|error| log::warn!("OPENCODE_ROUTE is not JSON: {error}")).ok()?; @@ -138,7 +131,7 @@ pub fn env_route(value: &str) -> Option<Route> { } } -/// Runs once after the first route mounted (`app.tsx` `onMount` and the `--continue` and `--fork` effects). +/// Apply startup arguments after the first route mounts. pub fn run(tui: &Tui, continue_: bool) { if let Some(model) = tui.startup.args.model.as_deref() && parse_model(model).is_none() diff --git a/packages/cli-rs/crates/tui/src/features/system_commands.rs b/packages/cli-rs/crates/tui/src/features/system_commands.rs index 0bccf167c19..0a72c273998 100644 --- a/packages/cli-rs/crates/tui/src/features/system_commands.rs +++ b/packages/cli-rs/crates/tui/src/features/system_commands.rs @@ -1,15 +1,4 @@ -//! System commands and toggles (E.20, rows T16 and T19), `app.tsx:1083-1290`. T.1 registers `app.exit`, -//! `help.show`, `session.new`, and the palette in `app::install_keys`, and calls [`install`] once for the rest. -//! -//! As in TS, only `docs.open`, `app.console`, and `location.reload` show in the palette; the others run from -//! their keybinds (all `none` by default except `terminal.suspend`, Ctrl+Z). The toggles write `cli.json` -//! through the settings writer (E.18a), so every view that reads the live config follows them. -//! -//! `service.restart` is not registered: TS offers it only for a managed service, and restarting stops the -//! shared service, which this client never does (orchestrator O-21). -//! -//! T16: [`mouse_tracking`] picks the startup mouse mode, and `mouse` changes apply while the TUI runs; -//! [`cursor`] is the prompt's cursor shape. +//! System commands and settings toggles. Restart is unavailable because the client shares its background service. use opencode_local::cli_config::{CursorStyle, DiffWrap, Info, PromptPaste, Resolved}; use opentui::native::{Control, MouseTracking}; @@ -98,14 +87,12 @@ pub fn cursor(config: &Resolved) -> (opentui::native::CursorStyle, bool) { (style, config.cursor_blinking) } -/// Tool-result images stay in the store only while the transcript can show them (`omitToolFileData` in -/// `context/data.tsx`): live tool events carry screenshots as inline base64. +/// Retain screenshot payloads only while transcript previews are enabled; live events carry inline base64. pub(crate) fn image_preview(info: &Info) -> bool { info.session.as_ref().and_then(|session| session.image_preview) == Some(true) } -/// What TS effects redo when the config changes: `renderer.useMouse = config.data.mouse`, the title effect, -/// which sets the route's title again once `terminal.title` is back on, and the data context's image previews. +/// Apply live mouse, title, and transcript preview settings. fn install_effects(tui: &Rc<Tui>) { let mouse = Rc::new(Cell::new(tui.config().mouse)); let title = Rc::new(Cell::new(title_enabled(&tui.config().info))); @@ -118,7 +105,7 @@ fn install_effects(tui: &Rc<Tui>) { let next = image_preview(&info); if preview.replace(next) != next { tui.data.set_omit_tool_file_data(!next); - // Turning previews on brings back the screenshots dropped while they were off. + // Reload screenshots discarded while previews are off. if next { tui.data.restore_files(); } @@ -152,8 +139,7 @@ fn write(tui: &Tui, path: &'static [&'static str], value: Value) { tui.dialogs.clear(); } -/// "Disable X" while on, "Enable X" while off. The titles are fixed at startup: TS shows them only in the -/// palette, and these commands are not in it. +/// Hidden toggle commands use their startup titles. fn toggle_title(on: bool, what: &str) -> String { format!("{} {what}", if on { "Disable" } else { "Enable" }) } diff --git a/packages/cli-rs/crates/tui/src/features/title.rs b/packages/cli-rs/crates/tui/src/features/title.rs index c83200741a6..85ab6a769dd 100644 --- a/packages/cli-rs/crates/tui/src/features/title.rs +++ b/packages/cli-rs/crates/tui/src/features/title.rs @@ -1,10 +1,4 @@ -//! The terminal title (E.1, row T09, `app.tsx:636-662`): "OpenCode" on home and for a session without a -//! real title, "OC | <title>" for a session, and "OC | <name>" for a plugin route. `terminal.title: false` -//! leaves the title alone until quitting, which clears it whatever the setting (`util/renderer.ts` -//! `destroyRenderer`). -//! -//! `app::mount` calls [`install`] once, `Tui::navigate` calls [`route_changed`], and `Tui::sync` calls -//! [`sync`] with what changed. +//! Terminal titles for home and session routes. use crate::prelude::*; @@ -12,8 +6,7 @@ use crate::prelude::*; pub struct Title { /// The title last sent, so a sync that changes nothing sends nothing. sent: RefCell<Option<String>>, - /// The last session the session route showed, with its title (TS `active`). The deleted toast names it - /// after the store dropped the session. + /// Cache the last viewed session title for the deletion toast, which follows removal from the store. active: RefCell<Option<(SessionID, Option<String>)>>, } @@ -27,7 +20,7 @@ impl Title { *self.sent.borrow_mut() = Some(title); } - /// The title of `id` when it was the last session shown. + /// Return the title if `id` matches the last session shown. pub fn active(&self, id: &SessionID) -> Option<String> { self.active.borrow().as_ref().filter(|(active, _)| active == id).and_then(|(_, title)| title.clone()) } @@ -86,7 +79,7 @@ pub fn clear(tui: &Tui) { tui.title.set(tui, String::new()); } -/// `terminal.title` as the last settings write left it, so `terminal.title.toggle` (E.20) takes effect. +/// Read the latest `terminal.title` setting. fn enabled(tui: &Tui) -> bool { crate::features::system_commands::title_enabled(&tui.settings.info()) } diff --git a/packages/cli-rs/crates/tui/src/lib.rs b/packages/cli-rs/crates/tui/src/lib.rs index bac822617fc..fd4b04730a9 100644 --- a/packages/cli-rs/crates/tui/src/lib.rs +++ b/packages/cli-rs/crates/tui/src/lib.rs @@ -1,4 +1,4 @@ -//! TypeScript: `packages/tui/src/app.tsx`. +//! The native terminal UI. pub mod app; pub mod client_mcp; diff --git a/packages/cli-rs/crates/tui/src/local.rs b/packages/cli-rs/crates/tui/src/local.rs index 1e5dff0e5a5..a6c22ff6453 100644 --- a/packages/cli-rs/crates/tui/src/local.rs +++ b/packages/cli-rs/crates/tui/src/local.rs @@ -1,10 +1,5 @@ -//! The model and agent state of `context/local.tsx` (E.16). -//! -//! [`Local`] holds the current location's catalog (models, providers, agents, integrations, and the configured -//! model, read through the store; and the usage limits), `model.json`, and the per-session and per-agent -//! selections. It sends no mutating request: the prompt commits a selection when it submits -//! (`prompt/index.tsx:1293`), and the session's `session.agent.selected` and `session.model.selected` settle the -//! drafts that commit sent. `model.json` writes run in order on one worker thread, because its file lock blocks. +//! Local model and agent selections. The composer commits drafts on submit; selection events settle them. Serialize +//! preference writes off the UI thread because the file lock blocks. use std::collections::HashSet; use std::path::PathBuf; @@ -75,11 +70,11 @@ pub struct Local { state: RefCell<State>, listeners: Listeners, next_listener: Cell<u64>, - /// The usage warnings shown, once per model and level while the TUI runs (`usage.tsx` `warned`). + /// Usage warnings already shown by model and severity. pub(crate) warned: RefCell<HashSet<String>>, - /// `--agent`, which a session without an agent draft shows over its own agent (`local.tsx:90-96`). + /// Startup agent selection when a session has no agent draft. pub(crate) startup_agent: RefCell<Option<String>>, - /// `--model`, which `fallbackModel` tries first (`local.tsx:184-193`). + /// First model to try when falling back. pub(crate) startup_model: RefCell<Option<Model>>, watch: RefCell<Option<Watch>>, pub(crate) layers: RefCell<Vec<Disposer>>, @@ -399,8 +394,7 @@ impl Local { } } - /// The prompt's effect (`prompt/index.tsx:1578-1582`): loads the limits once when OpenCode Console serves the - /// selected model. + /// Load limits when OpenCode Console serves the selected model. pub(crate) fn load_served_usage(&self) { let served = self .current() @@ -658,9 +652,7 @@ impl Local { self.reconcile(session, &[]); } - // `reconcileSessionSelection` and the agent arm of `session.agent.selected`, once for the agent and - // model after each selection event of the batch, as TS handles each event, then for the session as the - // store holds it. + // Reconcile each selection event before reconciling the final stored session. fn reconcile(&self, id: &SessionID, selected: &[Selected]) { let session = self.data.read(|state| state.session(id).cloned()); let Some(session) = session else { return }; diff --git a/packages/cli-rs/crates/tui/src/panel/mod.rs b/packages/cli-rs/crates/tui/src/panel/mod.rs index 0842ad5e38d..8d65450feb7 100644 --- a/packages/cli-rs/crates/tui/src/panel/mod.rs +++ b/packages/cli-rs/crates/tui/src/panel/mod.rs @@ -1,8 +1,4 @@ -//! Plugin side panels (W07): the state of `context/panel.tsx` and the host of `component/panel-host.tsx`. -//! -//! A plugin opens a panel for a session with [`Panels::open`]; the session frame shows it beside the session, -//! or over the whole screen when the room is too small to split or the plugin asks for it. The host is a -//! raised, focusable box that the plugin's panel surface (P2) fills; E.15a's diff viewer is the first user. +//! Session plugin panels. Show a panel beside the session when it fits, or full-screen when requested. use crate::frame::layout::SESSION_PANEL_SPLIT_MIN_WIDTH; use crate::prelude::*;