From 02922eb89da8ef74a26e771413c5b546def6de6c Mon Sep 17 00:00:00 2001 From: danny Date: Sun, 8 Nov 2026 12:18:28 +0100 Subject: [PATCH] A1: layout.get/layout.set keep the editor tab layout per project; editor.tabs.preview setting The tab layout of the open project lives in /layout/.json (written atomically, 256 KiB cap both ways, a broken file reads as null), never in webview storage. New bool setting editor.tabs.preview (default on). Co-Authored-By: Claude Opus 5.5 --- crates/control/tests/events.rs | 1 + crates/engine/src/cmd/layout.rs | 139 +++++++++++++++++++++++++++++++ crates/engine/src/cmd/mod.rs | 3 + crates/engine/src/settings.rs | 8 ++ crates/engine/tests/layout.rs | 142 ++++++++++++++++++++++++++++++++ crates/engine/tests/settings.rs | 2 + 6 files changed, 295 insertions(+) create mode 100644 crates/engine/src/cmd/layout.rs create mode 100644 crates/engine/tests/layout.rs diff --git a/crates/control/tests/events.rs b/crates/control/tests/events.rs index 9bc8afc..77f63da 100644 --- a/crates/control/tests/events.rs +++ b/crates/control/tests/events.rs @@ -209,6 +209,7 @@ fn settings_changes_stream_and_persist() { "editor.completion.autoPopup": true, "editor.completion.delayMs": 0, "editor.hover.delayMs": 350, + "editor.tabs.preview": true, "git.executable": "", "git.pull.mode": "merge" }), diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs new file mode 100644 index 0000000..c7075e9 --- /dev/null +++ b/crates/engine/src/cmd/layout.rs @@ -0,0 +1,139 @@ +//! `layout.get` and `layout.set` (C10 A1): the editor tab layout of the +//! open project, kept in Lutra's own state file +//! `/layout/.json` (the project id is the hash the +//! crash-recovery journal uses), never in the webview's storage. +//! +//! The engine treats the layout as an opaque JSON object: the frontend +//! writes it and reads it back defensively. Its size is capped by +//! [`MAX_BYTES`] both ways. An engine without persistence keeps nothing. + +use std::path::PathBuf; + +use serde::Deserialize; +use serde_json::{Map, Value, json}; + +use super::params::parse; +use crate::journal::hex_hash; +use crate::{Command, CommandSpec, EngineError, Outcome, Registry, State}; + +/// Directory below the data directory that holds the layout files. +const DIR_NAME: &str = "layout"; + +/// Largest layout file read or written, in bytes. +pub const MAX_BYTES: usize = 256 * 1024; + +/// Registers `layout.get` and `layout.set`. +/// +/// # Errors +/// [`EngineError::Internal`] if an id is taken. +pub fn register(registry: &mut Registry) -> Result<(), EngineError> { + registry.register(Box::new(Get))?; + registry.register(Box::new(Set)) +} + +/// The layout file of the open project, `None` without a project or +/// without persistence. +fn file(state: &State) -> Option { + let root = state.project.as_ref()?.project.root(); + let config = state.config.as_ref()?; + Some(config.data_dir.join(DIR_NAME).join(format!( + "{}.json", + hex_hash(root.to_string_lossy().as_bytes()) + ))) +} + +/// Reads the stored layout. A missing, oversized or unreadable file gives +/// `None`: the layout is a convenience, so a broken file only means the +/// tabs start empty, and the next `layout.set` replaces it. +fn read(state: &State) -> Option> { + let path = file(state)?; + let meta = std::fs::metadata(&path).ok()?; + if usize::try_from(meta.len()).map_or(true, |len| len > MAX_BYTES) { + return None; + } + let bytes = std::fs::read(&path).ok()?; + match serde_json::from_slice::(&bytes).ok()? { + Value::Object(map) => Some(map), + _ => None, + } +} + +/// `layout.get`. +struct Get; + +impl Command for Get { + fn spec(&self) -> &CommandSpec { + &CommandSpec { + id: "layout.get", + label: "Editor: Read Tab Layout", + menu_path: None, + default_shortcut: None, + params: "no params; returns { layout: object | null }, the editor tab layout last stored for the open project (null when none was stored, the file is unreadable or the engine keeps no files)", + } + } + + fn enabled(&self, state: &State) -> bool { + state.has_project() + } + + fn run(&self, state: &mut State, _params: Value) -> Result { + let layout = read(state).map_or(Value::Null, Value::Object); + Ok(Outcome::value(json!({ "layout": layout }))) + } +} + +/// Params of `layout.set`. +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct SetParams { + /// The layout, an object the frontend defines. + layout: Map, +} + +/// `layout.set`. +struct Set; + +impl Command for Set { + fn spec(&self) -> &CommandSpec { + &CommandSpec { + id: "layout.set", + label: "Editor: Store Tab Layout", + menu_path: None, + default_shortcut: None, + params: "{ layout: object } (at most 256 KiB as JSON); stores the editor tab layout of the open project in Lutra's state file; returns { stored: bool }, false when the engine keeps no files", + } + } + + fn enabled(&self, state: &State) -> bool { + state.has_project() + } + + fn run(&self, state: &mut State, params: Value) -> Result { + let command = self.spec().id; + let p: SetParams = parse(command, params)?; + let text = serde_json::to_vec(&Value::Object(p.layout)) + .map_err(|e| EngineError::Internal(format!("layout: {e}")))?; + if text.len() > MAX_BYTES { + return Err(EngineError::invalid_params( + command, + format!("layout is larger than {MAX_BYTES} bytes"), + )); + } + let Some(path) = file(state) else { + return Ok(Outcome::value(json!({ "stored": false }))); + }; + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir).map_err(|e| { + EngineError::Failed(format!("cannot create {}: {e}", dir.display())) + })?; + } + lutra_vfs::write_atomic(&path, &text) + .map_err(|e| EngineError::Failed(format!("cannot store the tab layout: {e}")))?; + Ok(Outcome::value(json!({ "stored": true }))) + } +} + +/// 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] = &["layout.get", "layout.set"]; diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs index 0706c22..bf221bd 100644 --- a/crates/engine/src/cmd/mod.rs +++ b/crates/engine/src/cmd/mod.rs @@ -15,6 +15,7 @@ pub mod git_merge; pub mod git_remote; pub mod git_stash; pub mod goto; +mod layout; mod lsp_assist; mod lsp_diagnostics; mod lsp_nav; @@ -88,6 +89,7 @@ pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> { git_chunks::register(registry)?; git_ignore::register(registry)?; deploy::register(registry)?; + layout::register(registry)?; Ok(()) } @@ -111,6 +113,7 @@ pub(crate) const BUILTIN_COMMAND_IDS: &[&[&str]] = &[ git_remote::COMMAND_IDS, git_stash::COMMAND_IDS, goto::COMMAND_IDS, + layout::COMMAND_IDS, lsp_assist::COMMAND_IDS, lsp_diagnostics::COMMAND_IDS, lsp_nav::COMMAND_IDS, diff --git a/crates/engine/src/settings.rs b/crates/engine/src/settings.rs index 9588ede..2b65c19 100644 --- a/crates/engine/src/settings.rs +++ b/crates/engine/src/settings.rs @@ -389,6 +389,14 @@ pub const DEFS: &[Def] = &[ description_key: "settings.editor.hover.delayMs.description", section: "editor", }, + Def { + key: "editor.tabs.preview", + kind: Kind::Bool, + default: DefaultValue::Bool(true), + label_key: "settings.editor.tabs.preview.label", + description_key: "settings.editor.tabs.preview.description", + section: "editor", + }, Def { key: "git.executable", kind: Kind::Path { max_len: 4096 }, diff --git a/crates/engine/tests/layout.rs b/crates/engine/tests/layout.rs new file mode 100644 index 0000000..a04f7b1 --- /dev/null +++ b/crates/engine/tests/layout.rs @@ -0,0 +1,142 @@ +//! `layout.get` / `layout.set` (C10 A1): the editor tab layout per project in +//! Lutra's own state file. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::path::PathBuf; + +use lutra_engine::{Engine, EngineConfig}; +use serde_json::{Value, json}; +use tempfile::TempDir; + +/// Two projects and the engine directories. +struct Setup { + /// Holds everything. + _tmp: TempDir, + /// First project. + a: PathBuf, + /// Second project. + b: PathBuf, + /// Engine directories. + config: EngineConfig, +} + +fn setup() -> Setup { + let tmp = tempfile::tempdir().unwrap(); + let a = tmp.path().join("a"); + let b = tmp.path().join("b"); + std::fs::create_dir(&a).unwrap(); + std::fs::create_dir(&b).unwrap(); + let config = EngineConfig { + config_dir: tmp.path().join("config"), + data_dir: tmp.path().join("data"), + }; + Setup { + _tmp: tmp, + a, + b, + config, + } +} + +fn run(engine: &mut Engine, command: &str, params: Value) -> Value { + engine + .execute(command, params) + .unwrap_or_else(|e| panic!("{command}: {e}")) + .value +} + +#[test] +fn the_layout_survives_a_restart_and_is_kept_per_project() { + let s = setup(); + let layout = json!({"version": 1, "groups": [{"tabs": [{"path": "x.php", "pinned": true, "preview": false}], "active": "x.php"}]}); + { + let mut engine = Engine::with_config(s.config.clone()).unwrap(); + run(&mut engine, "project.open", json!({"path": s.a})); + assert_eq!( + run(&mut engine, "layout.get", json!({})), + json!({"layout": null}) + ); + assert_eq!( + run(&mut engine, "layout.set", json!({"layout": layout})), + json!({"stored": true}) + ); + run(&mut engine, "project.open", json!({"path": s.b})); + assert_eq!( + run(&mut engine, "layout.get", json!({})), + json!({"layout": null}) + ); + } + let mut engine = Engine::with_config(s.config.clone()).unwrap(); + run(&mut engine, "project.open", json!({"path": s.a})); + assert_eq!( + run(&mut engine, "layout.get", json!({})), + json!({"layout": layout}) + ); + let files: Vec<_> = std::fs::read_dir(s.config.data_dir.join("layout")) + .unwrap() + .collect(); + assert_eq!(files.len(), 1); +} + +#[test] +fn bad_params_and_broken_files_are_refused_without_harm() { + let s = setup(); + let mut engine = Engine::with_config(s.config.clone()).unwrap(); + assert!(engine.execute("layout.get", json!({})).is_err()); + run(&mut engine, "project.open", json!({"path": s.a})); + for params in [ + json!({}), + json!({"layout": [1]}), + json!({"layout": {}, "x": 1}), + ] { + let err = engine.execute("layout.set", params).unwrap_err(); + assert_eq!(err.code(), "invalid_params"); + } + let big = "x".repeat(lutra_engine_max()); + let err = engine + .execute("layout.set", json!({"layout": {"pad": big}})) + .unwrap_err(); + assert_eq!(err.code(), "invalid_params"); + + run(&mut engine, "layout.set", json!({"layout": {"version": 1}})); + let dir = s.config.data_dir.join("layout"); + let file = std::fs::read_dir(&dir) + .unwrap() + .next() + .unwrap() + .unwrap() + .path(); + for content in [&b"{not json"[..], b"[1, 2]", b""] { + std::fs::write(&file, content).unwrap(); + assert_eq!( + run(&mut engine, "layout.get", json!({})), + json!({"layout": null}) + ); + } + std::fs::write(&file, vec![b' '; lutra_engine_max() + 1]).unwrap(); + assert_eq!( + run(&mut engine, "layout.get", json!({})), + json!({"layout": null}) + ); +} + +#[test] +fn an_engine_without_files_keeps_nothing() { + let s = setup(); + let mut engine = Engine::new().unwrap(); + run(&mut engine, "project.open", json!({"path": s.a})); + assert_eq!( + run(&mut engine, "layout.set", json!({"layout": {"version": 1}})), + json!({"stored": false}) + ); + assert_eq!( + run(&mut engine, "layout.get", json!({})), + json!({"layout": null}) + ); +} + +/// The size cap of a layout file (256 KiB). +fn lutra_engine_max() -> usize { + 256 * 1024 +} diff --git a/crates/engine/tests/settings.rs b/crates/engine/tests/settings.rs index d64df0c..2b368fb 100644 --- a/crates/engine/tests/settings.rs +++ b/crates/engine/tests/settings.rs @@ -58,6 +58,7 @@ fn list_describes_the_c2_keys_with_catalog_keys_only() { "editor.completion.autoPopup", "editor.completion.delayMs", "editor.hover.delayMs", + "editor.tabs.preview", "git.executable", "git.pull.mode" ] @@ -133,6 +134,7 @@ fn get_set_reset_and_events() { "editor.completion.autoPopup": true, "editor.completion.delayMs": 0, "editor.hover.delayMs": 350, + "editor.tabs.preview": true, "git.executable": "", "git.pull.mode": "merge" })