fix(cli-rs): make the TUI config live and queue its writes

Tui::config was frozen at startup, so most /settings options and the
file_context, diffwrap and animations toggles did nothing until restart.
settings::Live now holds the resolved config that Tui::config() reads; a
change re-runs the tabs, frame and leader timeout, and the transcript and
prompt follow through listeners, as TS's reactive ConfigProvider does.

CliConfig::watch now reloads cli.json after an outside edit. Writes and
reloads run in order on one Serial worker instead of a global saving
guard that dropped a second write; only the settings dialog's own steps
wait for the previous one, as dialog-config.tsx does.
session.toggle.thinking writes session.thinking like TS. L03 is
corrected. Fixes carbon-2.
This commit is contained in:
Simon Klee
2026-11-05 01:26:29 +01:00
Unverified
parent c729edd201
commit e357f442e4
24 changed files with 470 additions and 136 deletions
+11 -11
View File
@@ -9,7 +9,7 @@ use std::sync::atomic::{AtomicBool, Ordering};
use opencode_api::client::Client;
use opencode_api::events::{self, Connection};
use opencode_api::generated::SessionInfo;
use opencode_local::cli_config::{CliConfig, Info, Permissions, Resolved, ThemeMode as ConfigMode};
use opencode_local::cli_config::{CliConfig, Info, Resolved, ThemeMode as ConfigMode};
use opencode_local::paths::Paths;
use opencode_local::storage::Storage;
use opencode_store::{Data, Options};
@@ -66,14 +66,13 @@ pub struct Tui {
pub dialogs: Dialogs,
pub toasts: Toasts,
pub theme: RefCell<ThemeState>,
pub config: Resolved,
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.
pub textarea: Rc<RefCell<Option<Textarea>>>,
/// Prompt history, drafts, and catalogs, shared by every prompt (E.2).
pub prompt: crate::prompt::editor::Shared,
/// The config as settings writes left it (E.18a).
/// The live config: settings writes and `cli.json` edits replace it (E.18a).
pub settings: crate::dialogs::settings::Live,
/// The model and agent state (E.16).
pub local: Rc<crate::dialogs::model::Local>,
@@ -140,6 +139,11 @@ impl Tui {
self.this.clone()
}
/// The resolved config now (`useConfig().data`). Keep the borrow short: a change replaces it.
pub fn config(&self) -> std::cell::Ref<'_, Resolved> {
self.settings.config()
}
/// TUI storage (`useStorage`), when the TUI has real roots.
pub fn storage(&self) -> Option<Storage> {
self.files.as_ref().and_then(|files| files.storage.clone())
@@ -304,11 +308,7 @@ pub fn mount(app: &App, deps: Deps) -> Rc<Tui> {
}
/// [`mount`] with the startup arguments.
pub fn mount_with(app: &App, mut deps: Deps, args: Args) -> Rc<Tui> {
// `--auto` wins over `session.permissions` (`context/permission.tsx`).
if args.auto {
deps.config.permissions = Permissions::Autoaccept;
}
pub fn mount_with(app: &App, deps: Deps, args: Args) -> Rc<Tui> {
let runtime = app.runtime();
let _guard = runtime.enter();
let data = Data::with_runtime(
@@ -366,11 +366,12 @@ pub fn mount_with(app: &App, mut deps: Deps, args: Args) -> Rc<Tui> {
storage: files.as_ref().and_then(|files| files.storage.clone()),
});
let plugins = crate::plugins::host::registry(&deps.config.info);
let settings = crate::dialogs::settings::Live::new(
deps.config.info.clone(),
deps.config,
args.auto,
files.as_ref().map(|files| files.config.clone()),
);
let plugins = crate::plugins::host::registry(&deps.config.info);
let tui = Rc::new_cyclic(|this: &Weak<Tui>| Tui {
local: crate::dialogs::model::Local::new(
app,
@@ -387,7 +388,6 @@ pub fn mount_with(app: &App, mut deps: Deps, args: Args) -> Rc<Tui> {
dialogs,
toasts,
theme: RefCell::new(theme),
config: deps.config,
directory: deps.directory,
textarea,
prompt: crate::prompt::editor::Shared::new(
@@ -124,7 +124,7 @@ fn fork(tui: &Tui, session: SessionID, message: Option<String>) {
/// The pending view: the header and a spinner, at the list inset.
fn pending(tui: &Tui) {
let animations = opencode_ui::motion::enabled(tui.config.info.animations);
let animations = opencode_ui::motion::enabled(tui.config().info.animations);
tui.dialogs.replace(
move |cx| {
let spinner = Spinner::new(&cx.app)
@@ -121,7 +121,7 @@ pub fn show(tui: &Tui) {
let tabs = list
.tui
.upgrade()
.is_some_and(|tui| tui.config.tabs.enabled);
.is_some_and(|tui| tui.config().tabs.enabled);
props.actions = vec![
SelectAction {
hidden: tabs,
@@ -374,7 +374,7 @@ impl List {
if let Some(tui) = self.tui.upgrade()
&& let Some(storage) = tui.storage()
{
let initial = json!({ "allProjects": tui.config.tabs.scope != TabsScope::Cwd });
let initial = json!({ "allProjects": tui.config().tabs.scope != TabsScope::Cwd });
tui.app.runtime().spawn_blocking(move || {
let result = storage.update("session-list", &initial, |draft| {
if let Value::Object(map) = draft {
@@ -585,7 +585,7 @@ impl List {
return Vec::new();
};
let theme = dialog_theme(&tui);
let tabs = tui.config.tabs.enabled;
let tabs = tui.config().tabs.enabled;
let pinned_ids = if tabs { Vec::new() } else { pins::list(&tui) };
let slots: HashMap<SessionID, usize> = if tabs {
HashMap::new()
@@ -748,7 +748,7 @@ fn picker_directory(tui: &Tui) -> String {
/// `prefs.allProjects` from the `session-list` storage key.
fn load_all_projects(tui: &Tui) -> bool {
let initial = tui.config.tabs.scope != TabsScope::Cwd;
let initial = tui.config().tabs.scope != TabsScope::Cwd;
tui.storage()
.and_then(|storage| storage.load("session-list", &json!({})).ok())
.and_then(|value| value.get("allProjects").and_then(Value::as_bool))
@@ -2,13 +2,17 @@
//!
//! [`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, run on a blocking thread because the file lock blocks. [`Live`] holds the config as the last
//! write left it, so the dialogs, the DevTools bar, and the theme follow a change without a restart.
//! 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.
use std::cell::{Cell, RefCell};
use std::cell::{Cell, Ref, RefCell};
use std::collections::VecDeque;
use std::rc::{Rc, Weak};
use opencode_local::cli_config::{CliConfig, Info, merge};
use opencode_local::cli_config::{CliConfig, Info, Permissions, Resolved, merge};
use opencode_local::serial::Serial;
use opencode_local::watch::Watch;
use opencode_ui::dialog::DialogOptions;
use opencode_ui::keymap::{Bind, GLOBAL_MODE, KeymapLayer, Slash, TuiCommand};
use opencode_ui::select::{Choice, Detail, SelectOption, SelectProps, select};
@@ -495,81 +499,104 @@ pub const SETTINGS: &[Setting] = &[
),
];
/// A listener of config changes made through [`update`].
/// A listener of config changes, from [`update`] or an outside `cli.json` edit.
type Listener = Rc<dyn Fn(&Tui)>;
/// The config as the last settings write left it, and the write state. One per TUI.
/// What a write runs when it lands, in the order writes were queued.
type Done = Box<dyn FnOnce(&Tui)>;
/// The resolved config now, which every reader queries, and the write state. One per TUI.
pub struct Live {
info: RefCell<Info>,
resolved: RefCell<Resolved>,
/// `--auto`, which wins over `session.permissions` (`context/permission.tsx`).
auto: bool,
config: Option<CliConfig>,
saving: Cell<bool>,
/// Runs writes and reloads one at a time, in order, off the UI thread.
serial: Option<Serial>,
done: RefCell<VecDeque<Done>>,
watch: RefCell<Option<Watch>>,
listeners: RefCell<Vec<Listener>>,
layers: RefCell<Vec<Disposer>>,
}
/// A write or reload that finished on the serial worker.
enum Loaded {
Written(Result<Info, String>),
Reloaded(Info),
}
impl Live {
/// `config` is `None` without real roots: changes then stay in memory.
pub fn new(info: Info, config: Option<CliConfig>) -> Self {
pub fn new(mut resolved: Resolved, auto: bool, config: Option<CliConfig>) -> Self {
if auto {
resolved.permissions = Permissions::Autoaccept;
}
Self {
info: RefCell::new(info),
resolved: RefCell::new(resolved),
auto,
serial: config.as_ref().map(|_| Serial::new("cli-config")),
config,
saving: Cell::new(false),
done: RefCell::default(),
watch: RefCell::default(),
listeners: RefCell::default(),
layers: RefCell::default(),
}
}
/// The resolved config now (`useConfig().data`). Keep the borrow short: a change replaces it.
pub fn config(&self) -> Ref<'_, Resolved> {
self.resolved.borrow()
}
pub fn info(&self) -> Info {
self.info.borrow().clone()
self.resolved.borrow().info.clone()
}
/// Whether an `experimental` flag is on now.
pub fn experiment(&self, name: &str) -> bool {
self.info.borrow().experiment(name)
self.resolved.borrow().info.experiment(name)
}
/// Whether a write is in flight; changes are ignored until it ends, as in TS.
pub fn saving(&self) -> bool {
self.saving.get()
}
/// Calls `listener` after each change [`update`] applies.
/// Calls `listener` after each config change.
pub fn on_change(&self, listener: impl Fn(&Tui) + 'static) {
self.listeners.borrow_mut().push(Rc::new(listener));
}
fn resolve(&self, info: Info) -> Resolved {
let mut resolved = self.resolved.borrow().with_info(info);
if self.auto {
resolved.permissions = Permissions::Autoaccept;
}
resolved
}
}
/// `config.update(draft => ...)` by JSON path, off the UI thread, then [`apply`]. A failed write shows an error
/// toast. Ignored while another write is in flight.
/// `config.update(draft => ...)` by JSON path, then [`apply`]. Writes queue behind each other off the UI thread,
/// so none is dropped. A failed write shows an error toast.
pub fn update(tui: &Tui, change: impl FnOnce(&mut Value) + Send + 'static) {
write(tui, change, |_| {});
}
/// [`update`], then `done` once the write landed or failed.
fn write(
tui: &Tui,
change: impl FnOnce(&mut Value) + Send + 'static,
done: impl FnOnce(&Tui) + 'static,
) {
let live = &tui.settings;
if live.saving.replace(true) {
return;
}
let Some(config) = live.config.clone() else {
let (Some(config), Some(serial)) = (live.config.clone(), live.serial.as_ref()) else {
let mut value = live.info().to_value();
change(&mut value);
live.saving.set(false);
apply(tui, merge(&[Some(value)]));
done(tui);
return;
};
let weak = tui.weak();
tui.app.spawn(
async move {
tokio::task::spawn_blocking(move || config.update_value(change))
.await
.map_err(|error| error.to_string())
.and_then(|result| result.map_err(|error| error.to_string()))
},
move |_, result| {
let Some(tui) = weak.upgrade() else { return };
tui.settings.saving.set(false);
match result {
Ok(info) => apply(&tui, info),
Err(error) => tui.toasts.error(error),
}
},
);
live.done.borrow_mut().push_back(Box::new(done));
let proxy = tui.app.proxy();
serial.run(move || {
let result = config.update_value(change).map_err(|error| error.to_string());
let _ = proxy.send(Loaded::Written(result));
});
}
/// Sets `path` to `value`, creating the objects on the way (`dialog-config.tsx:463-468`).
@@ -596,11 +623,16 @@ pub fn set_path(root: &mut Value, path: &[&str], value: Value) {
}
/// Takes `info` as the current config and carries out what TS does reactively: the theme follows `theme.*`,
/// and listeners run.
/// the frame, tabs, and leader timeout follow the rest, and listeners run.
fn apply(tui: &Tui, info: Info) {
let before = tui.settings.info.replace(info.clone());
let next = tui.settings.resolve(info);
if *tui.settings.config() == next {
return;
}
let before = tui.settings.resolved.replace(next);
let info = tui.settings.info();
let theme = |info: &Info| info.theme.clone().unwrap_or_default();
let (old, new) = (theme(&before), theme(&info));
let (old, new) = (theme(&before.info), theme(&info));
let mut changed = false;
{
let mut state = tui.theme.borrow_mut();
@@ -621,10 +653,15 @@ fn apply(tui: &Tui, info: Info) {
if changed {
tui.theme_changed();
}
let leader = tui.settings.config().leader_timeout;
tui.keymap.set_leader_timeout(leader);
crate::tabs::route_changed(tui);
crate::frame::refresh(tui);
let listeners = tui.settings.listeners.borrow().clone();
for listener in listeners {
listener(tui);
}
tui.app.request_redraw();
}
/// The value of `setting` now: the config's, else the default (the active theme for `theme.name`).
@@ -668,8 +705,9 @@ pub fn display(tui: &Tui, setting: &Setting) -> String {
}
/// Steps `SETTINGS[index]` by `direction` and writes it (`change` in `dialog-config.tsx`).
pub fn change(tui: &Tui, index: usize, direction: i32) {
if tui.settings.saving() {
/// While `saving` holds, the dialog's previous step is still being written and this one is ignored, as in TS.
fn change(tui: &Tui, saving: &Rc<Cell<bool>>, index: usize, direction: i32) {
if saving.get() {
return;
}
let Some(setting) = SETTINGS.get(index) else {
@@ -696,7 +734,13 @@ pub fn change(tui: &Tui, index: usize, direction: i32) {
return;
}
let path = setting.path;
update(tui, move |draft| set_path(draft, path, next));
saving.set(true);
let saving = saving.clone();
write(
tui,
move |draft| set_path(draft, path, next),
move |_| saving.set(false),
);
}
/// The dialog rows.
@@ -756,11 +800,12 @@ pub fn show(tui: &Tui, current: Option<&str>) {
return opentui::prelude::View::new(&cx.app);
};
let selected = Rc::new(Cell::new(current));
let saving = Rc::new(Cell::new(false));
let step = |direction: i32| {
let (weak, selected) = (weak.clone(), selected.clone());
let (weak, selected, saving) = (weak.clone(), selected.clone(), saving.clone());
move |_: Option<&str>, _: Option<&opentui::prelude::KeyEvent>| {
if let Some(tui) = weak.upgrade() {
change(&tui, selected.get(), direction);
change(&tui, &saving, selected.get(), direction);
}
}
};
@@ -777,7 +822,7 @@ pub fn show(tui: &Tui, current: Option<&str>) {
move |option| selected.set(option.value)
}));
props.on_select = Some(Rc::new({
let weak = weak.clone();
let (weak, saving) = (weak.clone(), saving.clone());
move |option| {
let Some(tui) = weak.upgrade() else { return };
// `open`: Enter on Theme opens the theme list, which comes back here.
@@ -791,7 +836,7 @@ pub fn show(tui: &Tui, current: Option<&str>) {
super::theme_list::show(&tui, Some(back));
return;
}
change(&tui, option.value, 1);
change(&tui, &saving, option.value, 1);
}
}));
props.bindings = vec![
@@ -873,6 +918,44 @@ pub fn install(tui: &Rc<Tui>) {
Ok(disposer) => tui.settings.layers.borrow_mut().push(disposer),
Err(error) => log::error!("settings keymap layer: {error}"),
}
install_reload(tui);
}
/// Applies what the serial worker finished, and reloads `cli.json` after its directory changed, as
/// `ConfigProvider`'s watch does. A reload runs on the same worker as the writes, so it never lands out of order.
fn install_reload(tui: &Rc<Tui>) {
let weak = tui.weak();
tui.app.on_message(move |_, loaded: &Loaded| {
let Some(tui) = weak.upgrade() else { return };
match loaded {
Loaded::Written(result) => {
match result {
Ok(info) => apply(&tui, info.clone()),
Err(error) => tui.toasts.error(error.clone()),
}
let done = tui.settings.done.borrow_mut().pop_front();
if let Some(done) = done {
done(&tui);
}
}
Loaded::Reloaded(info) => apply(&tui, info.clone()),
}
});
let live = &tui.settings;
let (Some(config), Some(serial)) = (live.config.clone(), live.serial.clone()) else {
return;
};
let proxy = tui.app.proxy();
let watch = config.clone().watch(move || {
let (config, proxy) = (config.clone(), proxy.clone());
// A failed read keeps the config as it is (`.catch(() => {})`).
serial.run(move || {
if let Ok(info) = config.get() {
let _ = proxy.send(Loaded::Reloaded(info));
}
});
});
*live.watch.borrow_mut() = watch;
}
/// A JSON number as JS writes it: whole numbers without a fraction.
@@ -509,7 +509,7 @@ impl Workspaces {
};
let session = matches!(tui.route(), Route::Session { .. });
let current = self.current_value();
let animations = opencode_ui::motion::enabled(tui.config.info.animations);
let animations = opencode_ui::motion::enabled(tui.config().info.animations);
let height = i64::from(tui.app.size().1);
let full_height = (height - height / 4 - 2).clamp(8, 16) as u32;
let built = self.clone();
@@ -81,7 +81,7 @@ fn new_location(tui: &Tui) -> Location {
let unavailable = crate::features::location::error(tui);
match current {
Some(current)
if tui.config.new_location == NewLocation::Inherit
if tui.config().new_location == NewLocation::Inherit
&& Some(&current) != unavailable.as_ref() =>
{
current
@@ -101,7 +101,7 @@ fn reconnecting(tui: &Tui) -> View {
} else {
"Connection lost…"
})
.animations(opencode_ui::motion::enabled(tui.config.info.animations));
.animations(opencode_ui::motion::enabled(tui.config().info.animations));
let note = Text::new(
app,
if managed {
@@ -206,7 +206,7 @@ fn set_migration(tui: &Tui, progress: Option<String>) {
let spinner = Spinner::new(app)
.color(theme.text.feedback.info.base)
.label(progress)
.animations(opencode_ui::motion::enabled(tui.config.info.animations));
.animations(opencode_ui::motion::enabled(tui.config().info.animations));
let view = View::new(app)
.absolute()
.z_index(10_000)
@@ -18,7 +18,7 @@ pub fn install(tui: &Rc<Tui>) {
let weak = weak.clone();
move || {
let weak = weak.clone();
Condition::when(move || weak.upgrade().is_some_and(|tui| !tui.config.tabs.enabled))
Condition::when(move || weak.upgrade().is_some_and(|tui| !tui.config().tabs.enabled))
}
};
let commands: Vec<TuiCommand> = (1..=9)
@@ -173,8 +173,8 @@ pub fn cursor(config: &Resolved) -> (opentui::native::CursorStyle, bool) {
/// What TS effects redo when the config changes: `renderer.useMouse = config.data.mouse`, and the title effect,
/// which sets the route's title again once `terminal.title` is back on.
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)));
let mouse = Rc::new(Cell::new(tui.config().mouse));
let title = Rc::new(Cell::new(title_enabled(&tui.config().info)));
tui.settings.on_change(move |tui| {
let info = tui.settings.info();
if !title.replace(title_enabled(&info)) && title.get() {
+1 -1
View File
@@ -210,7 +210,7 @@ fn visible(tui: &Tui) -> bool {
}
fn vertical(tui: &Tui) -> bool {
tui.config.tabs.layout == TabsLayout::Vertical
tui.config().tabs.layout == TabsLayout::Vertical
&& layout::tabs_fit_vertically(i64::from(tui.app.size().0), tui.frame.tabs_resize.size(tui))
}
@@ -75,7 +75,7 @@ impl Pending {
let spinner = Spinner::new(&tui.app)
.color(tui.page().interactive().step(200))
.label("/btw")
.animations(opencode_ui::motion::enabled(tui.config.info.animations));
.animations(opencode_ui::motion::enabled(tui.config().info.animations));
let root = View::new(&tui.app)
.shrink(0.0)
.child(&spinner)
@@ -168,7 +168,7 @@ fn answer(tui: &Tui, question: String, text: String) {
let renderers = crate::plugins::host::code_blocks(tui);
let page = tui.page();
let conceal = tui
.config
.config()
.info
.session
.as_ref()
@@ -231,7 +231,7 @@ pub fn mount(tui: &Tui, session: Option<&SessionID>) -> Prompt {
let background = prompt_background(&theme);
let (width, height) = app.size();
let padding = if width < 44 { 1 } else { 2 };
let cursor = crate::features::system_commands::cursor(&tui.config);
let cursor = crate::features::system_commands::cursor(&tui.config());
let textarea = Textarea::new(app)
.set_keymap(Keymap::new())
.colors(theme.text.base, background)
@@ -290,7 +290,7 @@ pub fn mount(tui: &Tui, session: Option<&SessionID>) -> Prompt {
.frames(&scanner_frames(&scanner(theme.border.base)))
.interval(Duration::from_millis(40))
.still("[⋯]")
.animations(opencode_ui::motion::enabled(tui.config.info.animations));
.animations(opencode_ui::motion::enabled(tui.config().info.animations));
let running = View::new(app)
.margin_edge(Edge::Left, 1)
.shrink(0.0)
@@ -299,7 +299,7 @@ pub fn mount(tui: &Tui, session: Option<&SessionID>) -> Prompt {
let footer = Text::new(app, "").truncate(true).wrap(WrapMode::None);
let staging = super::r#move::Move::new(
app,
opencode_ui::motion::enabled(tui.config.info.animations),
opencode_ui::motion::enabled(tui.config().info.animations),
);
let editor_file = Text::new(app, "")
.truncate(true)
@@ -419,6 +419,17 @@ pub fn mount(tui: &Tui, session: Option<&SessionID>) -> Prompt {
}
});
inner.layers.borrow_mut().push(mentions);
// `useCursorStyle` and the animations follow the config, as the metadata row's auto-accept mark does.
let weak = Rc::downgrade(&inner);
tui.settings.on_change(move |tui| {
let Some(inner) = weak.upgrade() else { return };
let cursor = crate::features::system_commands::cursor(&tui.config());
inner.textarea.cursor_style(cursor.0, cursor.1);
let animations = opencode_ui::motion::enabled(tui.config().info.animations);
inner.spinner.set_animations(animations);
inner.staging.set_animations(animations);
inner.refresh(tui);
});
// Home drops the last session's selection; a session follows its directory (`editor.reconnect`).
match session {
None => tui.prompt.editor.clear_selection(),
@@ -536,7 +547,7 @@ impl Inner {
/// dismissed it (`editorContext`).
pub(crate) fn editor_context(&self, tui: &Tui) -> Option<Selection> {
let enabled = tui
.config
.config()
.info
.prompt
.as_ref()
@@ -637,7 +648,7 @@ impl Inner {
self.frame.border_color(highlight);
self.bottom.border_color(highlight);
self.spinner.set_color(
if opencode_ui::motion::enabled(tui.config.info.animations) {
if opencode_ui::motion::enabled(tui.config().info.animations) {
scanner_colors(&scanner(agent_color.unwrap_or(theme.border.base)))
} else {
SpinnerColor::from(theme.text.muted)
@@ -649,7 +660,7 @@ impl Inner {
let (model, provider) = catalog.labels(selection.model.as_ref());
Display {
agent: Some(metadata::titlecase(selection.agent.id.as_str())),
auto: tui.config.permissions == Permissions::Autoaccept,
auto: tui.config().permissions == Permissions::Autoaccept,
model,
provider,
variant: selection
@@ -72,6 +72,10 @@ impl Move {
}
}
pub fn set_animations(&self, enabled: bool) {
self.spinner.set_animations(enabled);
}
pub fn root(&self) -> &View {
&self.root
}
@@ -18,7 +18,7 @@ use opencode_api::generated::{
SessionMessageAssistantContentItem, SessionMessageAssistantFinish, SessionMessageCompaction,
SessionMessageID, SessionMessageInfo,
};
use opencode_local::cli_config::{Markdown as MarkdownMode, TurnTokens, Visibility};
use opencode_local::cli_config::{Markdown as MarkdownMode, Resolved, TurnTokens, Visibility};
use opencode_store::location::{Catalog, Location};
use opencode_store::{Changes, LoadMore, MessageExt, State};
use opencode_ui::keymap::{KeymapLayer, TuiCommand};
@@ -45,6 +45,33 @@ pub const BACKFILL_CHUNK: usize = 60;
#[derive(Clone)]
pub struct Transcript(Rc<Inner>);
#[derive(Clone, Copy, PartialEq)]
struct RowSettings {
conceal: bool,
tps: bool,
turn_tokens: Option<TurnTokens>,
image_preview: bool,
hide_thinking: bool,
}
impl RowSettings {
fn read(config: &Resolved) -> Self {
let session = config.info.session.clone().unwrap_or_default();
Self {
conceal: session.markdown.unwrap_or(MarkdownMode::Rendered) == MarkdownMode::Rendered,
tps: config.tps,
turn_tokens: config
.info
.debug
.as_ref()
.and_then(|debug| debug.turn_tokens)
.filter(|tokens| *tokens != TurnTokens::Enabled(false)),
image_preview: session.image_preview.unwrap_or(false),
hide_thinking: session.thinking.unwrap_or(Visibility::Hide) == Visibility::Hide,
}
}
}
struct Inner {
root: View,
scroll: ScrollBox,
@@ -59,11 +86,8 @@ struct Inner {
syntax: SyntaxTheme,
thinking_syntax: SyntaxTheme,
renderers: CodeBlockRenderers,
conceal: bool,
tps: bool,
turn_tokens: Option<TurnTokens>,
image_preview: bool,
hide_thinking: Cell<bool>,
/// The `session` and `debug` settings the rows show with, as the config has them now.
view: Cell<RowSettings>,
groups: Rc<grouping::Settings>,
session: RefCell<Option<SessionID>>,
location: RefCell<Option<Location>>,
@@ -144,8 +168,6 @@ impl Transcript {
let revert = revert::Banner::new(tui, &theme);
scroll.add(background.root());
scroll.add(revert.root());
let session = tui.config.info.session.clone().unwrap_or_default();
let image_preview = session.image_preview.unwrap_or(false);
let syntax = opencode_ui::code::syntax_theme(&theme);
let inner = Rc::new_cyclic(|this| Inner {
root,
@@ -161,19 +183,7 @@ impl Transcript {
syntax,
theme,
renderers: crate::plugins::host::code_blocks(tui),
conceal: session.markdown.unwrap_or(MarkdownMode::Rendered) == MarkdownMode::Rendered,
tps: tui.config.tps,
turn_tokens: tui
.config
.info
.debug
.as_ref()
.and_then(|debug| debug.turn_tokens)
.filter(|tokens| *tokens != TurnTokens::Enabled(false)),
image_preview,
hide_thinking: Cell::new(
session.thinking.unwrap_or(Visibility::Hide) == Visibility::Hide,
),
view: Cell::new(RowSettings::read(&tui.config())),
groups: grouping::Settings::new(&tui.settings.info()),
session: RefCell::default(),
location: RefCell::default(),
@@ -366,7 +376,14 @@ impl Inner {
let weak = self.this.clone();
tui.settings.on_change(move |tui| {
let Some(inner) = weak.upgrade() else { return };
if inner.groups.read(&tui.settings.info()) {
let view = RowSettings::read(&tui.config());
let before = inner.view.replace(view);
let groups = inner.groups.read(&tui.settings.info());
if before.hide_thinking != view.hide_thinking {
dispose(tui, inner.layer.take());
inner.register(tui);
}
if groups || before != view {
inner.render(tui, |_| true);
}
});
@@ -407,11 +424,10 @@ impl Inner {
self.register(tui);
}
/// `session.toggle.thinking` (`index.tsx:1163-1180`). The mode lives for this view; the
/// `cli.json` write waits for a config update API.
/// `session.toggle.thinking` (`index.tsx:1163-1180`): writes `session.thinking`, which the rows follow.
fn register(&self, tui: &Tui) {
let weak = self.this.clone();
let title = if self.hide_thinking.get() {
let title = if self.view.get().hide_thinking {
"Expand thinking"
} else {
"Collapse thinking"
@@ -421,10 +437,18 @@ impl Inner {
let Some(tui) = inner.tui.upgrade() else {
return;
};
inner.hide_thinking.set(!inner.hide_thinking.get());
inner.render(&tui, |_| true);
dispose(&tui, inner.layer.take());
inner.register(&tui);
let next = if inner.view.get().hide_thinking {
Visibility::Show
} else {
Visibility::Hide
};
crate::dialogs::settings::update(&tui, move |draft| {
crate::dialogs::settings::set_path(
draft,
&["session", "thinking"],
next.as_str().into(),
);
});
tui.dialogs.clear();
})
.title(title)
@@ -476,7 +500,8 @@ impl Inner {
.into_iter()
.map(|(id, _)| id)
.collect();
let mut rows = reduce(messages, self.turn_tokens.is_some());
let view = self.view.get();
let mut rows = reduce(messages, view.turn_tokens.is_some());
rows.retain(|spec| !matches!(spec, Spec::Message(id) if queued.contains(id)));
let mut specs = grouping::project(rows, messages, self.groups.verbosity.get());
// Compactions waiting in the inbox go last (`createSessionRows`).
@@ -501,7 +526,7 @@ impl Inner {
state,
keys: &keys,
directory: info.map(|info| info.location.directory.as_str()),
image_preview: self.image_preview,
image_preview: view.image_preview,
session: &session,
agents: catalogs
.and_then(|data| data.agent.as_deref())
@@ -517,12 +542,12 @@ impl Inner {
syntax: &self.syntax,
thinking_syntax: &self.thinking_syntax,
renderers: &self.renderers,
conceal: self.conceal,
hide_thinking: self.hide_thinking.get(),
conceal: view.conceal,
hide_thinking: view.hide_thinking,
groups: &self.groups,
tps: self.tps,
verbose_tokens: self.turn_tokens == Some(TurnTokens::Verbose),
animations: opencode_ui::motion::enabled(tui.config.info.animations),
tps: view.tps,
verbose_tokens: view.turn_tokens == Some(TurnTokens::Verbose),
animations: opencode_ui::motion::enabled(tui.config().info.animations),
mode,
width,
session_agent: info
@@ -146,7 +146,7 @@ impl Permission {
super::form::quiet(tui, tui.data.permission_sync(&id));
}
}
if tui.config.permissions == Permissions::Autoaccept {
if tui.config().permissions == Permissions::Autoaccept {
inner.auto_approve(tui, &requests);
return;
}
@@ -195,7 +195,7 @@ impl Drop for Permission {
/// transcript draws it in the warning color. It takes the store's state, since the transcript asks while
/// it reads the store.
pub fn tool_pending(tui: &Tui, state: &State, session: &SessionID, part: &str) -> bool {
if tui.config.permissions == Permissions::Autoaccept {
if tui.config().permissions == Permissions::Autoaccept {
return false;
}
state
@@ -828,7 +828,7 @@ fn edit_body(tui: &Tui, theme: &Theme, current: &Presentation) -> View {
.basis(Length::Auto)
.min_height(0);
if let Some(diff) = &current.diff {
let view = match tui.config.info.diffs.as_ref().and_then(|diffs| diffs.view) {
let view = match tui.config().info.diffs.as_ref().and_then(|diffs| diffs.view) {
Some(ConfigDiffView::Unified) => DiffView::Unified,
Some(ConfigDiffView::Split) => DiffView::Split,
_ if tui.app.size().0 > 120 => DiffView::Split,
@@ -67,7 +67,8 @@ impl Edit {
self.shown.take();
return;
};
let diffs = cx.tui.config.info.diffs.as_ref();
let diffs = cx.tui.config().info.diffs.clone();
let diffs = diffs.as_ref();
let view = match diffs.and_then(|diffs| diffs.view) {
Some(ConfigDiffView::Unified) => DiffView::Unified,
Some(ConfigDiffView::Split) => DiffView::Split,
@@ -203,7 +203,8 @@ fn shown(cx: &Context<'_>, props: &Props<'_>) -> Shown {
};
let files = parse_files(props.metadata.get("files"));
if !files.is_empty() {
let diffs = cx.tui.config.info.diffs.as_ref();
let diffs = cx.tui.config().info.diffs.clone();
let diffs = diffs.as_ref();
let view = match diffs.and_then(|diffs| diffs.view) {
Some(ConfigDiffView::Unified) => DiffView::Unified,
Some(ConfigDiffView::Split) => DiffView::Split,
+3 -3
View File
@@ -113,13 +113,13 @@ impl Tabs {
/// `config.tabs.enabled`.
pub fn enabled(tui: &Tui) -> bool {
tui.config.tabs.enabled
tui.config().tabs.enabled
}
/// The open tabs of the configured scope.
pub fn tabs(&self, tui: &Tui) -> Vec<Tab> {
let file = self.file.borrow();
let scope = match tui.config.tabs.scope {
let scope = match tui.config().tabs.scope {
opencode_local::cli_config::TabsScope::Cwd => file.cwd.get(self.cwd.borrow().as_str()),
_ => Some(&file.global),
};
@@ -671,7 +671,7 @@ fn update(tui: &Tui, mutation: impl Fn(&mut Scope) + Send + Sync + 'static) {
let mutation: Mutation = Arc::new(mutation);
let cwd = tui.tabs.cwd.borrow().clone();
let scoped = matches!(
tui.config.tabs.scope,
tui.config().tabs.scope,
opencode_local::cli_config::TabsScope::Cwd
);
let apply = {
+2 -2
View File
@@ -194,9 +194,9 @@ impl Component for Rail {
let width = painter.width();
let height = painter.height() as i32;
let compact = self.compact(width);
let animations = opencode_ui::motion::enabled(tui.config.info.animations);
let animations = opencode_ui::motion::enabled(tui.config().info.animations);
let numbers = matches!(
tui.config.tabs.indicators,
tui.config().tabs.indicators,
opencode_local::cli_config::TabsIndicators::Numbers
);
let background = theme.background.raised.base;
+2 -2
View File
@@ -239,9 +239,9 @@ impl Component for Strip {
return;
};
let theme = tui.page();
let animations = opencode_ui::motion::enabled(tui.config.info.animations);
let animations = opencode_ui::motion::enabled(tui.config().info.animations);
let numbers = matches!(
tui.config.tabs.indicators,
tui.config().tabs.indicators,
opencode_local::cli_config::TabsIndicators::Numbers
);
let (items, new_tab) = self.items(&tui);
@@ -0,0 +1,171 @@
//! The live config (`rs-ms34-config`): settings writes and outside `cli.json` edits reach every reader at once,
//! as TS's reactive `ConfigProvider` does (`packages/tui/src/config/index.tsx:354-371`), and writes queue
//! instead of dropping.
use std::path::Path;
use std::rc::Rc;
use std::sync::Arc;
use std::time::{Duration, Instant};
use bytes::Bytes;
use opencode_api::client::Client;
use opencode_api::transport::{BoxFuture, Request, Response, Transport};
use opencode_local::cli_config::{CliConfig, Info, Resolved};
use opencode_local::paths::Paths;
use opencode_tui::app::Roots;
use opencode_tui::dialogs::settings;
use opencode_tui::tabs::Tabs;
use opencode_tui::{Deps, Route, Tui};
use opentui::testing::TestApp;
use serde_json::{Value, json};
use crate::support::wait::WAIT;
/// An empty session list; anything else is a 404.
struct Empty;
impl Transport for Empty {
fn send(&self, request: Request) -> BoxFuture<'_, Result<Response, String>> {
let (status, body) = match request.url.path() {
"/api/session" => (200, json!({ "data": [], "cursor": {} })),
_ => (404, json!({})),
};
let body = serde_json::to_vec(&body).unwrap();
Box::pin(async move {
Ok(Response {
status,
headers: vec![("content-type".into(), "application/json".into())],
body: Box::pin(futures_util::stream::iter([Ok(Bytes::from(body))])),
})
})
}
}
fn mount(app: &TestApp, info: Info, roots: Option<Roots>) -> Rc<Tui> {
let client = Client::with_transport("http://opencode.local", Arc::new(Empty)).unwrap();
opencode_tui::mount(
app,
Deps {
client,
directory: "/project".into(),
config: Resolved::new(info, |_| None),
roots,
route: Route::Home,
continue_: false,
events: false,
},
)
}
fn paths(home: &Path) -> Paths {
let vars = [
("HOME", home.to_path_buf()),
("XDG_CONFIG_HOME", home.join("config")),
("XDG_STATE_HOME", home.join("state")),
("XDG_DATA_HOME", home.join("data")),
("XDG_CACHE_HOME", home.join("cache")),
];
Paths::from_vars(|name| {
vars.iter()
.find(|(key, _)| *key == name)
.map(|(_, value)| value.clone().into_os_string())
})
.unwrap()
}
/// A TUI over a `cli.json` holding `text` in a temporary home.
fn mount_with_file(app: &TestApp, home: &Path, text: &str) -> (Rc<Tui>, std::path::PathBuf) {
let paths = paths(home);
std::fs::create_dir_all(&paths.config).unwrap();
let file = paths.config.join("cli.json");
std::fs::write(&file, text).unwrap();
let info = CliConfig::with_content(&paths, None).get().unwrap();
let tui = mount(
app,
info,
Some(Roots {
paths,
storage_channel: "test".into(),
}),
);
(tui, file)
}
fn set(path: &'static [&'static str], value: Value) -> impl FnOnce(&mut Value) + Send + 'static {
move |draft| settings::set_path(draft, path, value)
}
#[test]
fn a_settings_write_reaches_the_tabs_and_the_leader_timeout_at_once() {
let app = TestApp::new(100, 30);
let tui = mount(&app, Info::default(), None);
assert!(Tabs::enabled(&tui));
settings::update(&tui, set(&["tabs", "mode"], json!("off")));
assert!(!Tabs::enabled(&tui), "tabs.mode stayed at its startup value");
// `leader.timeout` shortens the next leader. The leader's deadline is in real time, not the test clock, so
// the expiry is checked at instants past the press.
settings::update(&tui, set(&["leader", "timeout"], json!(250)));
app.press("ctrl+x");
let pressed = Instant::now();
assert!(tui.keymap.leader_active());
assert!(
tui.keymap.expire_leader(pressed + Duration::from_millis(300)),
"the leader waited for the startup timeout"
);
assert!(!tui.keymap.leader_active());
// And lengthens it.
settings::update(&tui, set(&["leader", "timeout"], json!(5000)));
app.press("ctrl+x");
let pressed = Instant::now();
assert!(!tui.keymap.expire_leader(pressed + Duration::from_millis(2500)));
assert!(tui.keymap.leader_active());
assert!(tui.keymap.expire_leader(pressed + Duration::from_millis(5100)));
assert!(!tui.keymap.leader_active());
}
#[test]
fn an_outside_cli_json_edit_reloads() {
let home = tempfile::tempdir().unwrap();
let app = TestApp::new(100, 30);
let (tui, file) = mount_with_file(&app, home.path(), "{}\n");
assert!(Tabs::enabled(&tui));
// As the TS TUI or an editor would: a new file renamed over the old one.
let temp = file.with_extension("json.edit");
std::fs::write(
&temp,
"{\n // edited elsewhere\n \"tabs\": { \"mode\": \"off\" }\n}\n",
)
.unwrap();
std::fs::rename(&temp, &file).unwrap();
assert!(
app.wait_until(WAIT, || !Tabs::enabled(&tui)),
"the edit never reloaded"
);
assert_eq!(
tui.settings.info().to_value()["tabs"],
json!({ "mode": "off" })
);
}
#[test]
fn two_quick_writes_both_reach_the_file() {
let home = tempfile::tempdir().unwrap();
let app = TestApp::new(100, 30);
let (tui, file) = mount_with_file(&app, home.path(), "{}\n");
settings::update(&tui, set(&["session", "scrollbar"], json!(true)));
settings::update(&tui, set(&["mouse"], json!(false)));
let both = || {
let text = std::fs::read_to_string(&file).unwrap_or_default();
text.contains("\"scrollbar\": true") && text.contains("\"mouse\": false")
};
assert!(
app.wait_until(WAIT, both),
"{}",
std::fs::read_to_string(&file).unwrap()
);
assert!(app.wait_until(WAIT, || {
let info = tui.settings.info();
info.mouse == Some(false) && info.session.and_then(|s| s.scrollbar) == Some(true)
}));
}
@@ -11,6 +11,7 @@ mod app;
mod attach;
mod complete;
mod composer;
mod config_live;
mod diffs;
mod editor;
mod form;
@@ -274,6 +274,40 @@ fn user_markdown_reasoning_and_footer_render_as_the_typescript_rows() {
assert!(screen.contains("┃ Plan the fix."), "{screen}");
}
/// A settings change reaches the rows at once, as TS's reactive config does: thinking opens and the
/// tokens-per-second footer goes, then `session.toggle.thinking` writes the config back.
#[test]
fn config_changes_reach_the_transcript_without_a_restart() {
let messages = vec![assistant(
"msg_2",
1500,
json!([{ "type": "reasoning", "text": "Plan the fix.", "time": { "created": 1500, "completed": 3000 } }]),
Some(4000),
)];
let h = open(80, 20, "ses_r", messages, Info::default());
let screen = h.wait_for("+ Thought");
assert!(!screen.contains("Plan the fix."), "{screen}");
assert!(screen.contains("tok/s"), "{screen}");
opencode_tui::dialogs::settings::update(&h.tui, |draft| {
opencode_tui::dialogs::settings::set_path(draft, &["session", "thinking"], json!("show"));
opencode_tui::dialogs::settings::set_path(draft, &["session", "tps"], json!(false));
});
let screen = h.wait_for("Plan the fix.");
assert!(!screen.contains("tok/s"), "{screen}");
h.tui.keymap.dispatch("session.toggle.thinking", None);
assert!(
h.app
.wait_until(Duration::from_secs(5), || !h.app.text().contains("Plan the fix.")),
"{}",
h.app.text()
);
assert_eq!(
h.tui.settings.info().session.and_then(|session| session.thinking),
Some(Visibility::Hide)
);
}
#[test]
fn a_streamed_reply_updates_in_place_and_gains_its_footer() {
let messages = vec![
@@ -1,10 +1,13 @@
# L03: `cli.json` reload is debounced
**TypeScript.** `ConfigProvider` (`packages/tui/src/config/index.tsx:363-371`) reloads on every `fs.watch` event
in the config directory, one reload after another.
in the config directory, one reload after another, and applies each result.
**Rust.** `CliConfig::watch` uses the same 50 ms debounce as storage and `model.json`
(`crates/local/src/watch.rs`), so a temporary-file-and-rename write gives one reload.
**Rust.** The settings module (`crates/tui/src/dialogs/settings.rs`, `install_reload`) starts
`CliConfig::watch` on the config directory when the TUI has real roots. The watch uses the same 50 ms debounce as
storage and `model.json` (`crates/local/src/watch.rs`), so a temporary-file-and-rename write gives one reload.
The reload runs `CliConfig::get` on the same worker thread as settings writes, so a reload and a write land in
the order they ran. A reload that resolves to the config already shown changes nothing.
**Reason.** The reloads TS runs for the intermediate events read the same file; only the last one shows. The
debounce removes redundant reads and no state is visible in between.