Lutra/crates/engine/src/cmd/buffer.rs
danny 95fd9b926f A3: derive the pinned command and catalog key lists in tests
Each command module keeps its own COMMAND_IDS next to its commands; the
engine listing test checks their union against the registry, so a missing
or extra command still fails without one shared list. The menu and palette
tests derive their expectation from the listing and check grouping and
ordering rules; the catalog's runtime keys are scanned from the sources.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 18:38:41 +01:00

266 lines
8.8 KiB
Rust

//! Buffer commands: `buffer.get`, `buffer.edit`, `buffer.close`,
//! `buffer.list`.
//!
//! Edits use UTF-16 code unit offsets, as CodeMirror and LSP do, and follow
//! CodeMirror's change-set semantics: every `{from, to}` of a batch refers
//! to the text at `baseVersion`, ranges must not overlap, and the batch is
//! applied atomically. An edit based on an older version is rejected with
//! `stale_version`; the client fetches the text with `buffer.get` and
//! reapplies its pending changes.
use serde::Deserialize;
use serde_json::{Value, json};
use super::params::parse;
use crate::buffers::{BufferId, LineEndingName};
use crate::journal;
use crate::workspace::path_string;
use crate::{Command, CommandSpec, EngineError, Event, Outcome, State};
/// Most edits accepted in one `buffer.edit`.
pub const MAX_EDITS: usize = 100_000;
/// Most inserted bytes accepted in one `buffer.edit`.
pub const MAX_INSERT_BYTES: usize = 64 * 1024 * 1024;
/// The full description of buffer `id`, as returned by `file.open` and
/// `buffer.get`.
///
/// # Errors
/// [`EngineError::Failed`] for an unknown buffer.
pub fn describe(state: &State, command: &str, id: BufferId) -> Result<Value, EngineError> {
let open = state
.buffers
.get(id)
.ok_or_else(|| EngineError::Failed(format!("{command}: no buffer {id}")))?;
Ok(json!({
"id": id,
"path": path_string(&open.path),
"text": open.buffer.text(),
"version": open.version,
"dirty": open.dirty(),
"lineEnding": LineEndingName::from(open.buffer.line_ending()),
}))
}
/// Params naming one buffer.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct IdParams {
/// Buffer id.
id: BufferId,
}
/// `buffer.get`: the text and state of a buffer.
pub struct Get;
impl Command for Get {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "buffer.get",
label: "Get Buffer",
menu_path: None,
default_shortcut: None,
params: "{ id: number }; returns { id, path, text, version, dirty, lineEnding }",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let p: IdParams = parse(self.spec().id, params)?;
describe(state, self.spec().id, p.id).map(Outcome::value)
}
}
/// One change of a `buffer.edit` batch.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Change {
/// Start, in UTF-16 code units of the text at the base version.
from: usize,
/// End (exclusive), same units; equal to `from` for an insertion.
to: usize,
/// Text to insert; empty for a deletion.
#[serde(default)]
insert: String,
}
/// Params of `buffer.edit`.
#[derive(Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
struct EditParams {
/// Buffer id.
id: BufferId,
/// The version the changes are based on.
base_version: u64,
/// The changes.
edits: Vec<Change>,
}
/// `buffer.edit`: applies a batch of changes.
pub struct Edit;
impl Command for Edit {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "buffer.edit",
label: "Edit Buffer",
menu_path: None,
default_shortcut: None,
params: "{ id: number, baseVersion: number, edits: [{ from, to, insert }] } with UTF-16 offsets into the text at baseVersion; returns { id, version, dirty }; fails with stale_version if baseVersion is not the current version",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let command = self.spec().id;
let p: EditParams = parse(command, params)?;
if p.edits.len() > MAX_EDITS {
return Err(EngineError::invalid_params(
command,
format!("at most {MAX_EDITS} edits per call"),
));
}
let inserted: usize = p.edits.iter().map(|c| c.insert.len()).sum();
if inserted > MAX_INSERT_BYTES {
return Err(EngineError::invalid_params(
command,
format!("at most {MAX_INSERT_BYTES} inserted bytes per call"),
));
}
let open = state
.buffers
.get_mut(p.id)
.ok_or_else(|| EngineError::Failed(format!("{command}: no buffer {}", p.id)))?;
if p.base_version != open.version {
return Err(EngineError::StaleVersion {
id: p.id,
base: p.base_version,
current: open.version,
});
}
if p.edits.is_empty() {
let (version, dirty) = (open.version, open.dirty());
return Ok(Outcome::value(
json!({ "id": p.id, "version": version, "dirty": dirty }),
));
}
let mut edits = Vec::with_capacity(p.edits.len());
for change in p.edits {
let invalid =
|e: lutra_text::TextError| EngineError::invalid_params(command, e.to_string());
let from = open.buffer.utf16_to_offset(change.from).map_err(invalid)?;
let to = open.buffer.utf16_to_offset(change.to).map_err(invalid)?;
edits.push(lutra_text::Edit::replace(from..to, change.insert));
}
let was_dirty = open.dirty();
open.buffer
.apply(&edits)
.map_err(|e| EngineError::invalid_params(command, e.to_string()))?;
open.version = open.version.saturating_add(1);
let (version, dirty) = (open.version, open.dirty());
let now = std::time::Instant::now();
journal::mark_edited(state, p.id, now);
crate::lsp::record_edits(state, p.id, p.base_version, &edits);
super::syntax::record_edits(state, p.id, p.base_version, edits, now);
state.emit(Event::BufferChanged { id: p.id, version });
if dirty != was_dirty {
state.emit(Event::DirtyChanged { id: p.id, dirty });
}
Ok(Outcome::value(
json!({ "id": p.id, "version": version, "dirty": dirty }),
))
}
}
/// Params of `buffer.close`.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct CloseParams {
/// Buffer id.
id: BufferId,
/// Discard unsaved changes.
#[serde(default)]
force: bool,
}
/// `buffer.close`: closes a buffer.
pub struct Close;
impl Command for Close {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "buffer.close",
label: "Close Buffer",
menu_path: Some("File/Close Tab"),
default_shortcut: Some("Mod+W"),
params: "{ id: number, force?: bool (discard unsaved changes) }; returns null; fails with unsaved_changes if the buffer is dirty and force is not set",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let command = self.spec().id;
let p: CloseParams = parse(command, params)?;
let open = state
.buffers
.get(p.id)
.ok_or_else(|| EngineError::Failed(format!("{command}: no buffer {}", p.id)))?;
if open.dirty() && !p.force {
return Err(EngineError::UnsavedChanges(path_string(&open.path)));
}
journal::forget(state, p.id);
state.buffers.remove(p.id);
state.emit(Event::BufferClosed { id: p.id });
Ok(Outcome::value(Value::Null))
}
}
/// `buffer.list`: the open buffers without their text, for agents (MCP
/// resources) that need to know which files are open.
pub struct List;
impl Command for List {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "buffer.list",
label: "List Buffers",
menu_path: None,
default_shortcut: None,
params: "none; returns [{ id, path, version, dirty }] ordered by id, empty without a project",
}
}
fn run(&self, state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
let list: Vec<Value> = state
.buffers
.ids()
.into_iter()
.filter_map(|id| {
let open = state.buffers.get(id)?;
Some(json!({
"id": id,
"path": path_string(&open.path),
"version": open.version,
"dirty": open.dirty(),
}))
})
.collect();
Ok(Outcome::value(Value::Array(list)))
}
}
/// The ids of the commands this module registers, checked against the
/// registry by the engine's listing test. Add a new command's id here.
#[cfg(test)]
pub(crate) const COMMAND_IDS: &[&str] =
&["buffer.close", "buffer.edit", "buffer.get", "buffer.list"];