diff --git a/packages/cli-rs/crates/local/src/jsonl.rs b/packages/cli-rs/crates/local/src/jsonl.rs index fba4ced6c0a..e66e459542d 100644 --- a/packages/cli-rs/crates/local/src/jsonl.rs +++ b/packages/cli-rs/crates/local/src/jsonl.rs @@ -3,8 +3,9 @@ //! //! Ports the three TypeScript providers (`packages/tui/src/prompt/{history,stash,frecency}.tsx`): their //! parse and limit rules, the rewrite on load that heals a broken file, appends, and the full rewrites -//! after a trim. Write failures are ignored, as in TypeScript. Prompt entries stay -//! `serde_json::Value`, so fields this client does not know survive. +//! after a trim. Full rewrites are atomic, and the history, which both TUIs append to, is written +//! under its lock from what the file holds. Write failures are ignored, as in TypeScript. Prompt +//! entries stay `serde_json::Value`, so fields this client does not know survive. use std::fs; use std::io::{self, Write}; @@ -15,6 +16,8 @@ use indexmap::IndexMap; use serde_json::{Map, Value, json}; use crate::jsonc; +use crate::lock; +use crate::storage::write_text_atomic; pub const MAX_HISTORY_ENTRIES: usize = 50; pub const MAX_STASH_ENTRIES: usize = 50; @@ -56,11 +59,9 @@ fn body<'a>(entries: impl Iterator) -> String { .collect() } +// A full rewrite, atomic so a concurrent reader never sees a partial file. fn write_text(file: &Path, text: &str) { - let _ = file - .parent() - .map_or(Ok(()), fs::create_dir_all) - .and_then(|()| fs::write(file, text)); + let _ = write_text_atomic(file, text, || true); } fn append_text(file: &Path, text: &str) { @@ -82,25 +83,31 @@ pub fn parse_history(text: &str) -> Vec { last(lines(text).filter(is_prompt).collect(), MAX_HISTORY_ENTRIES) } -/// `usePromptHistory`: the prompt history and its cursor. -#[derive(Debug)] +/// `usePromptHistory`: the prompt history and its cursor, in memory. [`save_history`] writes an +/// entry to the file. +#[derive(Debug, Default)] pub struct History { - file: PathBuf, entries: Vec, index: i64, } impl History { - /// Loads `/prompt-history.jsonl` and rewrites its valid, retained entries. + /// Loads `/prompt-history.jsonl` and, under the lock, rewrites it with its valid, retained + /// entries when that changes it. pub fn load(state: &Path) -> Self { - let file = state.join("prompt-history.jsonl"); - let entries = parse_history(&fs::read_to_string(&file).unwrap_or_default()); - if !entries.is_empty() { - write_text(&file, &body(entries.iter())); + let file = history_file(state); + let healed = with_lock(state, &file, || { + rewrite(&file, |text| { + let entries = parse_history(text); + let healed = body(entries.iter()); + (!entries.is_empty() && healed != text).then_some(healed) + }) + }); + if let Err(error) = healed { + log::warn!("prompt-history.jsonl: {error}"); } Self { - file, - entries, + entries: parse_history(&fs::read_to_string(&file).unwrap_or_default()), index: 0, } } @@ -127,27 +134,88 @@ impl History { at(&self.entries, next).cloned() } - /// `append(item)`: skips a repeat of the last entry, trims to the limit, and resets the cursor. - pub fn append(&mut self, entry: Value) { + /// `append(item)` in memory: skips a repeat of the last entry, trims to the limit, and resets the + /// cursor. Returns whether the entry is new, so the caller saves it. + pub fn append(&mut self, entry: Value) -> bool { self.index = 0; if self .entries .last() .is_some_and(|previous| jsonc::stringify(previous) == jsonc::stringify(&entry)) { - return; + return false; } - let line = jsonc::stringify(&entry) + "\n"; self.entries.push(entry); - if self.entries.len() > MAX_HISTORY_ENTRIES { - self.entries = last(std::mem::take(&mut self.entries), MAX_HISTORY_ENTRIES); - write_text(&self.file, &body(self.entries.iter())); - return; - } - append_text(&self.file, &line); + self.entries = last(std::mem::take(&mut self.entries), MAX_HISTORY_ENTRIES); + true } } +/// `append(item)`'s write, under the `Flock` lock in `/locks`: skips a repeat of the file's last +/// entry, appends the line, and past the limit rewrites the file atomically with the newest entries. +/// The file is read again, so entries the TypeScript TUI appended stay. +pub fn save_history(state: &Path, entry: &Value) -> Result<(), lock::Error> { + let file = history_file(state); + let line = jsonc::stringify(entry); + with_lock(state, &file, || { + let text = fs::read_to_string(&file).unwrap_or_default(); + let valid: Vec = lines(&text).filter(is_prompt).collect(); + if valid + .last() + .is_some_and(|previous| jsonc::stringify(previous) == line) + { + return Ok(()); + } + if valid.len() < MAX_HISTORY_ENTRIES { + append_text(&file, &(line.clone() + "\n")); + return Ok(()); + } + rewrite(&file, |text| { + let mut entries: Vec = lines(text).filter(is_prompt).collect(); + entries.push(entry.clone()); + Some(body(last(entries, MAX_HISTORY_ENTRIES).iter())) + }) + }) +} + +fn history_file(state: &Path) -> PathBuf { + state.join("prompt-history.jsonl") +} + +fn with_lock( + state: &Path, + file: &Path, + f: impl FnOnce() -> io::Result<()>, +) -> Result<(), lock::Error> { + lock::with_lock( + &state.join("locks"), + &file.to_string_lossy(), + &lock::Options::default(), + f, + )? + .map_err(lock::Error::Io) +} + +/// How often [`rewrite`] reads the file again after another client appended to it. +const REWRITE_ATTEMPTS: usize = 5; + +// Rewrites `file` atomically with `change(text)` when that gives a new text. A client that appends +// without the lock (the TypeScript TUI) writes to the file the rename would replace, so when the file +// grew meanwhile the rewrite reads it again rather than drop that line. +fn rewrite(file: &Path, change: impl Fn(&str) -> Option) -> io::Result<()> { + for _ in 0..REWRITE_ATTEMPTS { + let text = fs::read_to_string(file).unwrap_or_default(); + let Some(next) = change(&text) else { + return Ok(()); + }; + let size = || fs::metadata(file).map_or(0, |metadata| metadata.len()); + if write_text_atomic(file, &next, || size() == text.len() as u64)? { + return Ok(()); + } + } + Ok(()) +} + // `Array.prototype.at`. fn at(items: &[Value], index: i64) -> Option<&Value> { let index = if index < 0 { @@ -368,8 +436,8 @@ mod tests { fs::read_to_string(&file).unwrap(), "{\"text\":\"a\",\"pasted\":[]}\n" ); - history.append(prompt("b")); - history.append(prompt("b")); + assert!(history.append(prompt("b"))); + assert!(!history.append(prompt("b"))); assert_eq!(history.entries().len(), 2); assert_eq!(history.step(-1, ""), Some(prompt("b"))); assert_eq!( @@ -384,7 +452,28 @@ mod tests { history.append(prompt(&index.to_string())); } assert_eq!(history.entries().len(), MAX_HISTORY_ENTRIES); - assert_eq!(fs::read_to_string(&file).unwrap().lines().count(), 50); + } + + #[test] + fn saves_keep_lines_another_client_appended() { + let state = tempfile::tempdir().unwrap(); + let file = state.path().join("prompt-history.jsonl"); + save_history(state.path(), &prompt("a")).unwrap(); + save_history(state.path(), &prompt("a")).unwrap(); + // The TypeScript TUI appends without the lock. + append_text(&file, "{\"text\":\"ts\",\"pasted\":[]}\n"); + for index in 0..49 { + save_history(state.path(), &prompt(&index.to_string())).unwrap(); + } + let text = fs::read_to_string(&file).unwrap(); + let entries = parse_history(&text); + assert_eq!(text.lines().count(), MAX_HISTORY_ENTRIES); + assert_eq!(entries[0]["text"], "ts", "the trim kept the newest 50"); + assert_eq!(entries[49]["text"], "48"); + // A load that changes nothing does not rewrite the file. + let before = fs::metadata(&file).unwrap().modified().unwrap(); + History::load(state.path()); + assert_eq!(fs::metadata(&file).unwrap().modified().unwrap(), before); } #[test] diff --git a/packages/cli-rs/crates/local/src/lib.rs b/packages/cli-rs/crates/local/src/lib.rs index 619fcf89992..39ff2007a75 100644 --- a/packages/cli-rs/crates/local/src/lib.rs +++ b/packages/cli-rs/crates/local/src/lib.rs @@ -9,7 +9,9 @@ pub mod lock; pub mod migrate; pub mod model_pref; pub mod paths; +pub mod pins; pub mod registration; +pub mod serial; pub mod service_config; pub mod storage; pub mod watch; diff --git a/packages/cli-rs/crates/local/src/pins.rs b/packages/cli-rs/crates/local/src/pins.rs new file mode 100644 index 00000000000..481159d2592 --- /dev/null +++ b/packages/cli-rs/crates/local/src/pins.rs @@ -0,0 +1,124 @@ +//! Pinned sessions in `/session.json`, shared with the TypeScript TUI (`context/local.tsx:508-603`). +//! +//! TypeScript reads the file once and writes its whole list with `writeJsonAtomic`. Here every change +//! runs under the `Flock` lock in `/locks` with the file path as the key, reads the file again, +//! and applies only its own pin or unpin, so pins another client wrote since survive. Other fields of +//! the file survive too. + +use std::fs; +use std::path::{Path, PathBuf}; + +use serde_json::{Map, Value}; + +use crate::lock; +use crate::storage::write_json_atomic; + +pub fn file(state: &Path) -> PathBuf { + state.join("session.json") +} + +/// The pinned session IDs, oldest pin first; none when the file is missing or broken. +pub fn load(state: &Path) -> Vec { + pinned(&read(&file(state))) +} + +/// Adds `id` at the end, or with `pinned: false` removes it, and returns the list written. +pub fn set(state: &Path, id: &str, pinned: bool) -> Result, lock::Error> { + let file = file(state); + lock::with_lock( + &state.join("locks"), + &file.to_string_lossy(), + &lock::Options::default(), + || { + let mut document = read(&file); + let mut list = self::pinned(&document); + let present = list.iter().any(|pin| pin == id); + if present == pinned { + return Ok(list); + } + if pinned { + list.push(id.to_owned()); + } else { + list.retain(|pin| pin != id); + } + document.insert( + "pinned".into(), + Value::Array(list.iter().cloned().map(Value::String).collect()), + ); + write_json_atomic(&file, &Value::Object(document))?; + Ok(list) + }, + )? + .map_err(lock::Error::Io) +} + +fn read(file: &Path) -> Map { + fs::read_to_string(file) + .ok() + .and_then(|text| serde_json::from_str::(&text).ok()) + .and_then(|value| match value { + Value::Object(map) => Some(map), + _ => None, + }) + .unwrap_or_default() +} + +fn pinned(document: &Map) -> Vec { + document + .get("pinned") + .and_then(Value::as_array) + .map(|pinned| { + pinned + .iter() + .filter_map(Value::as_str) + .map(str::to_owned) + .collect() + }) + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn changes_keep_pins_and_fields_written_since() { + let state = tempfile::tempdir().unwrap(); + assert_eq!(set(state.path(), "a", true).unwrap(), ["a"]); + // Another client pins `b` and adds a field after this one read the file. + fs::write(file(state.path()), r#"{"pinned":["a","b"],"other":1}"#).unwrap(); + assert_eq!(set(state.path(), "c", true).unwrap(), ["a", "b", "c"]); + assert_eq!(set(state.path(), "a", false).unwrap(), ["b", "c"]); + assert_eq!(set(state.path(), "a", false).unwrap(), ["b", "c"]); + assert_eq!( + fs::read_to_string(file(state.path())).unwrap(), + r#"{"pinned":["b","c"],"other":1}"# + ); + assert_eq!(load(state.path()), ["b", "c"]); + let leftovers: Vec<_> = fs::read_dir(state.path()) + .unwrap() + .filter_map(|entry| entry.ok()) + .filter(|entry| entry.file_name().to_string_lossy().ends_with(".tmp")) + .collect(); + assert!(leftovers.is_empty()); + } + + #[test] + fn concurrent_changes_lose_nothing() { + let state = tempfile::tempdir().unwrap(); + let threads: Vec<_> = (0..4) + .map(|n| { + let state = state.path().to_owned(); + std::thread::spawn(move || { + for i in 0..5 { + set(&state, &format!("{n}-{i}"), true).unwrap(); + } + }) + }) + .collect(); + for thread in threads { + thread.join().unwrap(); + } + assert_eq!(load(state.path()).len(), 20); + } +} diff --git a/packages/cli-rs/crates/local/src/serial.rs b/packages/cli-rs/crates/local/src/serial.rs new file mode 100644 index 00000000000..e8179b08028 --- /dev/null +++ b/packages/cli-rs/crates/local/src/serial.rs @@ -0,0 +1,32 @@ +//! One worker thread that runs blocking file jobs in the order they were sent, so writes that wait +//! on a file lock stay off the UI thread and land in order. + +use std::sync::mpsc; + +type Job = Box; + +#[derive(Clone, Debug)] +pub struct Serial(mpsc::Sender); + +impl Serial { + /// Starts the worker; it stops once every clone is dropped and the queued jobs ran. + pub fn new(name: &str) -> Self { + let (send, receive) = mpsc::channel::(); + let spawned = std::thread::Builder::new() + .name(name.to_owned()) + .spawn(move || { + for job in receive { + job(); + } + }); + if let Err(error) = spawned { + log::warn!("{name}: {error}"); + } + Self(send) + } + + /// Queues `job` after every job sent before it. + pub fn run(&self, job: impl FnOnce() + Send + 'static) { + let _ = self.0.send(Box::new(job)); + } +} diff --git a/packages/cli-rs/crates/local/src/storage.rs b/packages/cli-rs/crates/local/src/storage.rs index 5bcd618dd4e..34edd7abd91 100644 --- a/packages/cli-rs/crates/local/src/storage.rs +++ b/packages/cli-rs/crates/local/src/storage.rs @@ -111,7 +111,18 @@ fn segment(value: &str) -> Result<&str, Error> { /// `writeJsonAtomic`: compact `JSON.stringify` to `...tmp`, then a rename. The /// temporary file is removed when either step fails. -pub(crate) fn write_json_atomic(file: &Path, value: &Value) -> io::Result<()> { +pub fn write_json_atomic(file: &Path, value: &Value) -> io::Result<()> { + write_text_atomic(file, &jsonc::stringify(value), || true).map(|_| ()) +} + +/// Writes `text` to `...tmp` and renames it over `file` when `ready()` still holds +/// once the temporary file is written. Returns whether it renamed; the temporary file never +/// outlives the call. +pub fn write_text_atomic( + file: &Path, + text: &str, + ready: impl FnOnce() -> bool, +) -> io::Result { if let Some(dir) = file.parent() { fs::create_dir_all(dir)?; } @@ -121,11 +132,16 @@ pub(crate) fn write_json_atomic(file: &Path, value: &Value) -> io::Result<()> { std::process::id(), uuid::Uuid::new_v4() )); - fs::write(&temp, jsonc::stringify(value)) - .and_then(|()| fs::rename(&temp, file)) - .inspect_err(|_| { - let _ = fs::remove_file(&temp); - }) + let result = fs::write(&temp, text).and_then(|()| { + if !ready() { + return Ok(false); + } + fs::rename(&temp, file).map(|()| true) + }); + if !matches!(result, Ok(true)) { + let _ = fs::remove_file(&temp); + } + result } #[cfg(test)] diff --git a/packages/cli-rs/crates/tui/src/dialogs/session_list.rs b/packages/cli-rs/crates/tui/src/dialogs/session_list.rs index 9bd13eab607..6430b363391 100644 --- a/packages/cli-rs/crates/tui/src/dialogs/session_list.rs +++ b/packages/cli-rs/crates/tui/src/dialogs/session_list.rs @@ -898,8 +898,14 @@ fn relative(from: &str, to: &str) -> String { } /// Pinned sessions in `/session.json` (`context/local.tsx:508-603`), shared with the TS -/// TUI. Read once per state directory and kept in memory, as TS does; written atomically. +/// TUI. Read once per state directory and kept in memory, as TS does. Each pin, unpin, and prune is +/// written in order on one worker thread, under the file's lock, from what the file holds then +/// (`opencode_local::pins`). pub mod pins { + use std::sync::OnceLock; + + use opencode_local::serial::Serial; + use super::*; thread_local! { @@ -912,7 +918,14 @@ pub mod pins { PINS.with(|pins| { pins.borrow_mut() .entry(key.clone()) - .or_insert_with(|| key.as_deref().map(read).unwrap_or_default()) + .or_insert_with(|| { + key.as_deref() + .map(opencode_local::pins::load) + .unwrap_or_default() + .into_iter() + .map(SessionID) + .collect() + }) .clone() }) } @@ -935,48 +948,33 @@ pub mod pins { /// `togglePin`. pub fn toggle(tui: &Tui, id: &SessionID) { - let mut pinned = list(tui); - match pinned.iter().position(|pin| pin == id) { - Some(index) => { - pinned.remove(index); - } - None => pinned.push(id.clone()), + let pinned = !list(tui).contains(id); + set(tui, id, pinned); + } + + /// `prune` on `session.deleted`: the file loses the pin even when only another client had it. + pub fn prune(tui: &Tui, id: &SessionID) { + set(tui, id, false); + } + + fn set(tui: &Tui, id: &SessionID, pinned: bool) { + let mut list = list(tui); + list.retain(|pin| pin != id); + if pinned { + list.push(id.clone()); } let key = tui.state_dir(); - PINS.with(|pins| pins.borrow_mut().insert(key.clone(), pinned.clone())); + PINS.with(|pins| pins.borrow_mut().insert(key.clone(), list)); let Some(state) = key else { return }; - tui.app.runtime().spawn_blocking(move || { - let value = - json!({ "pinned": pinned.iter().map(|id| id.0.clone()).collect::>() }); - if let Err(error) = write(&state.join("session.json"), &value) { - log::warn!("failed to save session.json: {error}"); - } - }); - } - - fn read(state: &std::path::Path) -> Vec { - std::fs::read_to_string(state.join("session.json")) - .ok() - .and_then(|text| serde_json::from_str::(&text).ok()) - .and_then(|value| value.get("pinned").and_then(Value::as_array).cloned()) - .map(|pinned| { - pinned - .iter() - .filter_map(Value::as_str) - .map(|id| SessionID(id.to_owned())) - .collect() - }) - .unwrap_or_default() - } - - // `writeJsonAtomic`: a temporary file beside the target, then a rename. - fn write(file: &std::path::Path, value: &Value) -> std::io::Result<()> { - if let Some(parent) = file.parent() { - std::fs::create_dir_all(parent)?; - } - let temp = file.with_extension(format!("json.{}.tmp", std::process::id())); - std::fs::write(&temp, serde_json::to_string_pretty(value)?)?; - std::fs::rename(temp, file) + let id = id.0.clone(); + static WRITER: OnceLock = OnceLock::new(); + WRITER + .get_or_init(|| Serial::new("session.json")) + .run(move || { + if let Err(error) = opencode_local::pins::set(&state, &id, pinned) { + log::warn!("failed to save session.json: {error}"); + } + }); } } diff --git a/packages/cli-rs/crates/tui/src/prompt/history.rs b/packages/cli-rs/crates/tui/src/prompt/history.rs index fde0f68c05e..68a175f40c0 100644 --- a/packages/cli-rs/crates/tui/src/prompt/history.rs +++ b/packages/cli-rs/crates/tui/src/prompt/history.rs @@ -1,69 +1,84 @@ //! Prompt history (E.2, row P03): `/prompt-history.jsonl`, shared by every prompt of the app //! (`prompt/history.tsx`), and Up and Down in the prompt (`component/prompt/index.tsx:1022-1096`). //! -//! F.5's `jsonl::History` owns the format and the cursor. Loading and appending touch the file, so -//! they run on blocking threads; stepping only reads memory and runs on the UI thread. +//! F.5's `jsonl::History` owns the format and the cursor in memory; stepping and appending run on the +//! UI thread. The file, which the TS TUI shares, is touched on one worker thread in order: the load +//! first, then each new entry under the file's lock (`jsonl::save_history`). use std::path::PathBuf; use std::sync::{Arc, Mutex}; use opencode_local::jsonl; +use opencode_local::serial::Serial; use opentui::native::EditorQuery; use opentui::prelude::*; use serde_json::Value; use super::editor::Inner; -/// The app's prompt history. Without a state directory nothing is kept, as nothing is written. +/// The app's prompt history. Without a state directory it lives in memory only. #[derive(Clone, Default)] pub struct History { - slot: Arc>>, - /// Entries not appended yet, in submit order. - queue: Arc>>, - state: Option, + memory: Arc>, + file: Option<(PathBuf, Serial)>, +} + +#[derive(Default)] +struct Memory { + history: jsonl::History, + /// Entries appended before the file was read, `None` once it is; they go after its entries. + early: Option>, } impl History { - /// Loads `/prompt-history.jsonl` on a blocking thread; until then the history is empty. - pub fn load(app: &App, state: Option) -> Self { - let history = Self { - state, - ..Self::default() + /// Loads `/prompt-history.jsonl` on the worker; until then the history holds what was + /// appended meanwhile. + pub fn load(_app: &App, state: Option) -> Self { + let Some(state) = state else { + return Self::default(); }; - history.write(app); - history + let memory = Arc::new(Mutex::new(Memory { + early: Some(Vec::new()), + ..Memory::default() + })); + let writer = Serial::new("prompt-history.jsonl"); + let slot = memory.clone(); + let file = state.clone(); + writer.run(move || { + let mut history = jsonl::History::load(&file); + let Ok(mut memory) = slot.lock() else { return }; + for entry in memory.early.take().unwrap_or_default() { + history.append(entry); + } + memory.history = history; + }); + Self { + memory, + file: Some((state, writer)), + } } /// `move(direction, input)`. pub fn step(&self, direction: i64, input: &str) -> Option { - self.slot.lock().ok()?.as_mut()?.step(direction, input) + self.memory.lock().ok()?.history.step(direction, input) } - /// `append(entry)`, written on a blocking thread. - pub fn append(&self, app: &App, entry: Value) { - if self.state.is_none() { - return; - } - if let Ok(mut queue) = self.queue.lock() { - queue.push(entry); - } - self.write(app); - } - - /// Loads the file if no task has yet, then appends every queued entry. Blocking tasks run in any order, - /// so each one takes the whole queue while it holds the history: entries land in submit order, and one - /// submitted before the load finished is not lost. - fn write(&self, app: &App) { - let Some(state) = self.state.clone() else { + /// `append(entry)`: in memory at once, and written after the load and every earlier entry. + pub fn append(&self, _app: &App, entry: Value) { + let Ok(mut memory) = self.memory.lock() else { return; }; - let (slot, queue) = (self.slot.clone(), self.queue.clone()); - app.runtime().spawn_blocking(move || { - let Ok(mut slot) = slot.lock() else { return }; - let history = slot.get_or_insert_with(|| jsonl::History::load(&state)); - let entries = queue.lock().map(|mut queue| std::mem::take(&mut *queue)); - for entry in entries.unwrap_or_default() { - history.append(entry); + let added = memory.history.append(entry.clone()); + if let Some(early) = memory.early.as_mut().filter(|_| added) { + early.push(entry.clone()); + } + drop(memory); + let Some((state, writer)) = self.file.clone().filter(|_| added) else { + return; + }; + writer.run(move || { + if let Err(error) = jsonl::save_history(&state, &entry) { + log::warn!("prompt-history.jsonl: {error}"); } }); }