fix(cli-rs): serialize frecency, recents and layout writes

Frecency visits, directory recents, the layout widths and the terminal
selection were written from unordered spawn_blocking tasks, so an older
write could land last. Each now runs on an ordered worker thread. A
written recents file replaces memory only when no newer change was sent,
as tabs.json does.
This commit is contained in:
Simon Klee
2026-11-05 01:22:17 +01:00
Unverified
parent 5a712a80d7
commit cda5aa9ac9
3 changed files with 70 additions and 28 deletions
+5 -2
View File
@@ -9,9 +9,11 @@ pub mod resize;
use std::cell::{Cell, RefCell};
use std::rc::{Rc, Weak};
use std::sync::OnceLock;
use opencode_api::generated::SessionID;
use opencode_local::cli_config::TabsLayout;
use opencode_local::serial::Serial;
use opencode_local::storage::Storage;
use opencode_ui::keymap::{Bind, GLOBAL_MODE, KeymapLayer, TuiCommand};
use opentui::keymap::{Condition, Disposer};
@@ -169,11 +171,12 @@ pub fn reload(tui: &Tui, storage: &Storage) {
refresh(tui);
}
/// Writes one `layout` width under the storage lock, off the UI thread.
/// Writes one `layout` width under the storage lock, on one worker thread so the writes land in order.
fn save_layout(tui: &Tui, key: &'static str, width: u16) {
tui.frame.layout.borrow_mut()[key] = json!(width);
let Some(storage) = tui.storage() else { return };
tui.app.runtime().spawn_blocking(move || {
static WRITER: OnceLock<Serial> = OnceLock::new();
WRITER.get_or_init(|| Serial::new("layout")).run(move || {
let result = storage.update("layout", &json!({}), |value| {
if let Some(object) = value.as_object_mut() {
object.insert(key.to_owned(), json!(width));
@@ -14,7 +14,9 @@ pub mod parts;
use std::cell::{Cell, OnceCell, RefCell};
use std::cmp::Ordering;
use std::path::{Path, PathBuf};
use std::rc::{Rc, Weak};
use std::sync::atomic::{self, AtomicU64};
use std::sync::{Arc, Mutex};
use opencode_api::client::RequestOptions;
@@ -23,6 +25,7 @@ use opencode_api::generated::{
ReferenceSource,
};
use opencode_local::jsonl::{self, Frecency};
use opencode_local::serial::Serial;
use opencode_local::storage::Storage;
use opencode_store::location::{Catalog, Location};
use opencode_ui::dialog::FocusId;
@@ -54,15 +57,21 @@ pub enum Mode {
}
/// State every prompt shares: `frecency.jsonl` and directory recents.
///
/// Memory answers on the UI thread. The files are read and written on one worker thread, in order: the
/// loads first, then each visit and recents change.
#[derive(Clone, Default)]
pub struct Shared {
frecency: Arc<Mutex<Option<Frecency>>>,
recents: Arc<Mutex<Option<Value>>>,
/// The last recents change sent; a written file replaces memory only if no newer change was sent.
recents_writes: Arc<AtomicU64>,
writer: Rc<OnceCell<Serial>>,
loaded: Rc<Cell<bool>>,
}
impl Shared {
/// Loads both files on a blocking thread, once.
/// Loads both files on the worker, once.
fn load(&self, tui: &Tui) {
if self.loaded.replace(true) {
return;
@@ -73,11 +82,9 @@ impl Shared {
let (frecency, recents, storage) =
(self.frecency.clone(), self.recents.clone(), tui.storage());
// `paths.cwd`: the directory the TUI started in.
let cwd = std::path::PathBuf::from(&tui.directory);
tui.app.runtime().spawn_blocking(move || {
if let Ok(mut slot) = frecency.lock() {
slot.get_or_insert_with(|| Frecency::load(&state, &cwd));
}
let cwd = PathBuf::from(&tui.directory);
self.writer().run(move || {
load_frecency(&frecency, &state, &cwd);
let stored =
storage.and_then(|storage| storage.load(RECENTS_KEY, &recents_initial()).ok());
if let Ok(mut slot) = recents.lock() {
@@ -86,6 +93,11 @@ impl Shared {
});
}
fn writer(&self) -> &Serial {
self.writer
.get_or_init(|| Serial::new("prompt-autocomplete"))
}
/// `getFrecency(path)`.
fn score(&self, path: &str) -> f64 {
self.frecency
@@ -98,18 +110,25 @@ impl Shared {
.unwrap_or(0.0)
}
/// `updateFrecency(path)`, written on a blocking thread. A pick can run before the load does, so
/// whichever runs first loads the file.
/// `updateFrecency(path)`, written on the worker under the file's lock. A pick can run before the
/// load does, so whichever runs first loads the file.
fn visit(&self, tui: &Tui, path: String) {
let Some(state) = tui.state_dir() else {
return;
};
let frecency = self.frecency.clone();
let cwd = std::path::PathBuf::from(&tui.directory);
tui.app.runtime().spawn_blocking(move || {
if let Ok(mut slot) = frecency.lock() {
slot.get_or_insert_with(|| Frecency::load(&state, &cwd))
.update(&path, jsonl::now_ms());
let cwd = PathBuf::from(&tui.directory);
self.writer().run(move || {
load_frecency(&frecency, &state, &cwd);
match jsonl::save_frecency(&state, &cwd, &path, jsonl::now_ms()) {
Ok((path, visit)) => {
if let Some(frecency) =
frecency.lock().ok().as_mut().and_then(|slot| slot.as_mut())
{
frecency.record(path, visit);
}
}
Err(error) => log::warn!("frecency.jsonl: {error}"),
}
});
}
@@ -179,14 +198,17 @@ impl Shared {
let Some(storage): Option<Storage> = tui.storage() else {
return;
};
let recents = self.recents.clone();
tui.app.runtime().spawn_blocking(move || {
let (recents, writes) = (self.recents.clone(), self.recents_writes.clone());
let revision = writes.fetch_add(1, atomic::Ordering::SeqCst) + 1;
self.writer().run(move || {
let written = storage.update(RECENTS_KEY, &recents_initial(), |value| {
apply(value, &change);
});
match written {
Ok(value) => {
if let Ok(mut slot) = recents.lock() {
if let Ok(mut slot) = recents.lock()
&& writes.load(atomic::Ordering::SeqCst) == revision
{
*slot = Some(value);
}
}
@@ -196,6 +218,18 @@ impl Shared {
}
}
/// Loads `frecency.jsonl` into `slot` unless it is loaded, without holding `slot` meanwhile: the load
/// waits on the file's lock, and the UI thread reads `slot` for scores.
fn load_frecency(slot: &Mutex<Option<Frecency>>, state: &Path, cwd: &Path) {
if slot.lock().is_ok_and(|slot| slot.is_some()) {
return;
}
let loaded = Frecency::load(state, cwd);
if let Ok(mut slot) = slot.lock() {
slot.get_or_insert(loaded);
}
}
fn recents_initial() -> Value {
json!({ "projects": {} })
}
+15 -10
View File
@@ -11,7 +11,7 @@ pub mod pane;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Arc;
use std::sync::{Arc, OnceLock};
use indexmap::IndexMap;
use opencode_api::client::RequestOptions;
@@ -20,6 +20,7 @@ use opencode_api::generated::{
SessionID, V2Event,
};
use opencode_api::pty::{Connector, Tungstenite};
use opencode_local::serial::Serial;
use opencode_ui::keymap::{Bind, GLOBAL_MODE, KeymapLayer, Slash, TuiCommand};
use opentui::keymap::{Condition, Disposer};
use serde_json::{Value, json};
@@ -344,17 +345,21 @@ pub fn select(tui: &Tui, session: &str, pty: Option<&str>, focus: bool) {
if let Some(storage) = tui.storage() {
let session = session.to_owned();
let pty = pty.map(str::to_owned);
tui.app.runtime().spawn_blocking(move || {
let result = storage.update(SELECTION, &json!({ "sessions": {} }), |value| {
if !value["sessions"].is_object() {
value["sessions"] = json!({});
// One worker thread, so the selections land in the order they were made.
static WRITER: OnceLock<Serial> = OnceLock::new();
WRITER
.get_or_init(|| Serial::new("terminal-selection"))
.run(move || {
let result = storage.update(SELECTION, &json!({ "sessions": {} }), |value| {
if !value["sessions"].is_object() {
value["sessions"] = json!({});
}
value["sessions"][session] = json!(pty);
});
if let Err(error) = result {
log::error!("Failed to persist terminal selection: {error}");
}
value["sessions"][session] = json!(pty);
});
if let Err(error) = result {
log::error!("Failed to persist terminal selection: {error}");
}
});
}
crate::frame::refresh(tui);
update_layer(tui);