From b7b01494926a134f39daf8102281889702ddf62b Mon Sep 17 00:00:00 2001 From: salmonik Date: Sun, 15 Nov 2026 17:13:24 +0100 Subject: 0.5.3: session locking, UTF-8 and size guards for edit, correct character widths - exclusive flock on session files - edit refuses non-UTF-8 and >64 MiB files with actionable messages - editor uses unicode-width, expands tabs, handles resize --- CHANGELOG.md | 15 +++++++++++++++ Cargo.lock | 9 ++++++++- Cargo.toml | 3 ++- src/line.rs | 45 ++++++++++++++++++++++++++++++++++++++++++++- src/session.rs | 15 +++++++++++++++ src/tools/fs.rs | 17 ++++++++++++++++- tests/loop.rs | 7 +++++++ tests/sessions.rs | 22 ++++++++++++++++++++++ 8 files changed, 129 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 38d38e2..7d63d98 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,21 @@ break the interface, **PATCH** for bug fixes. file, and the tool schemas the model sees. Anything a script or a resumed session could depend on counts as API. +## 0.5.3 + +### Fixed +- Two processes could append to the same session and interleave messages, which + corrupts a transcript permanently. A session now takes an exclusive `flock` and + the second process is told the session is already open. +- `edit` on a file that is not valid UTF-8 failed with a raw codec error after + reading it; it now says so up front and points at `bash`. Files over 64 MiB are + refused the same way, instead of failing mid-rewrite on the 32-bit target. +- The line editor counted every character as one column, so CJK text, combining + marks and pasted tabs put the caret in the wrong place. Widths now come from + `unicode-width`, with tabs expanded to the next multiple of eight. +- A terminal resize during editing left the redraw's row count stale and could + erase output above the prompt; the editor now starts a fresh prompt line. + ## 0.5.2 ### Fixed diff --git a/Cargo.lock b/Cargo.lock index 6ab1c18..13e1252 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10,13 +10,14 @@ checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" [[package]] name = "agent686" -version = "0.5.2" +version = "0.5.3" dependencies = [ "crossterm", "libc", "regex", "serde", "serde_json", + "unicode-width", "ureq", ] @@ -566,6 +567,12 @@ version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" +[[package]] +name = "unicode-width" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" + [[package]] name = "untrusted" version = "0.9.0" diff --git a/Cargo.toml b/Cargo.toml index 14e7bc2..f11e198 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "agent686" -version = "0.5.2" +version = "0.5.3" edition = "2021" description = "A small coding agent for a 32-bit Debian box" publish = false @@ -12,6 +12,7 @@ ureq = { version = "3", features = ["rustls"] } libc = "0.2" crossterm = "0.29.0" regex = "1.13.1" +unicode-width = "0.2.3" [profile.release] strip = true diff --git a/src/line.rs b/src/line.rs index accf6cd..1ae210a 100644 --- a/src/line.rs +++ b/src/line.rs @@ -57,6 +57,14 @@ impl Editor { insert(&mut buffer, &mut cursor, &text); draw(prompt, &buffer, cursor, &mut rows)?; } + Event::Resize(_, _) => { + // The terminal reflowed the block we were tracking, so the + // old row count is meaningless. Start a fresh prompt line + // rather than risk erasing output above it. + println!(); + rows = 1; + draw(prompt, &buffer, cursor, &mut rows)?; + } Event::Key(key) if key.kind == KeyEventKind::Press => { match handle_key(key, &mut buffer, &mut cursor, self) { Action::Continue => {} @@ -266,7 +274,17 @@ fn layout(prompt: &str, buffer: &[char], upto: usize, width: usize) -> (usize, u col = 0; pending_wrap = false; } - col += 1; + + let cells = cells(ch, col); + if cells == 0 { + // Combining marks draw on top of the previous cell. + continue; + } + if col + cells > width { + row += 1; + col = 0; + } + col += cells; if col >= width { col = width - 1; pending_wrap = true; @@ -276,6 +294,15 @@ fn layout(prompt: &str, buffer: &[char], upto: usize, width: usize) -> (usize, u (row, col) } +/// Columns a character occupies at the given cursor position. Terminals expand +/// a tab to the next multiple of eight; wide characters occupy two cells. +fn cells(ch: char, col: usize) -> usize { + if ch == '\t' { + return 8 - (col % 8); + } + unicode_width::UnicodeWidthChar::width(ch).unwrap_or(1) +} + fn draw(prompt: &str, buffer: &[char], cursor: usize, rows: &mut usize) -> io::Result<()> { let width = terminal_width(); let mut out = io::stdout(); @@ -406,6 +433,22 @@ mod tests { assert!(terminal_width() >= 1); } + #[test] + fn layout_counts_wide_and_combining_characters() { + let wide: Vec = "日本語".chars().collect(); + assert_eq!(layout("> ", &wide, 3, 20), (0, 8)); + + let combining: Vec = "e\u{0301}".chars().collect(); + assert_eq!(layout("", &combining, 2, 20), (0, 1)); + } + + #[test] + fn layout_expands_tabs_to_the_next_stop() { + let tab: Vec = "\t".chars().collect(); + assert_eq!(layout("> ", &tab, 1, 80), (0, 8)); + assert_eq!(layout("", &tab, 1, 80), (0, 8)); + } + #[test] fn insert_normalises_line_endings() { let mut buffer = vec!['a']; diff --git a/src/session.rs b/src/session.rs index 6e3c1c1..6416b56 100644 --- a/src/session.rs +++ b/src/session.rs @@ -2,6 +2,7 @@ use std::fs::{File, OpenOptions}; use std::hash::{Hash, Hasher}; use std::io::{BufRead, BufReader, Read, Write}; use std::os::unix::fs::PermissionsExt; +use std::os::unix::io::AsRawFd; use std::path::Path; use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; @@ -48,6 +49,18 @@ fn restrict(path: &Path, mode: u32) { let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)); } +/// Two processes appending to one transcript interleave messages and corrupt it +/// permanently, because history is never rewritten. Refuse the second one. +fn lock_exclusive(file: &File, id: &str) -> Result<(), String> { + let locked = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }; + if locked != 0 { + return Err(format!( + "session {id} is already open in another process" + )); + } + Ok(()) +} + pub struct Session { pub id: String, pub model: String, @@ -84,6 +97,7 @@ impl Session { .open(&path) .map_err(|e| format!("{}: {e}", path.display()))?; restrict(&path, 0o600); + lock_exclusive(&file, &id)?; let cwd = std::env::current_dir() .map(|path| path.display().to_string()) @@ -164,6 +178,7 @@ impl Session { .map_err(|e| format!("{}: {e}", path.display()))?; // Older builds created these 0644. restrict(&path, 0o600); + lock_exclusive(&file, &session_id)?; Ok(( Session { diff --git a/src/tools/fs.rs b/src/tools/fs.rs index 947649f..ac0a475 100644 --- a/src/tools/fs.rs +++ b/src/tools/fs.rs @@ -10,6 +10,9 @@ const MAX_LINE_BYTES: usize = 4096; const MAX_READ_LINES: usize = 2000; const MAX_MATCHES: usize = 200; const MAX_SCAN_BYTES: u64 = 4 * 1024 * 1024; +/// Edit rewrites the whole file, so it has to fit comfortably in the 32-bit +/// address space together with its own copy. +const MAX_EDIT_BYTES: u64 = 64 * 1024 * 1024; const PREVIEW_BUDGET: usize = 60; const SKIP_DIRS: &[&str] = &[ @@ -239,7 +242,19 @@ pub fn plan_edit(args: &Value) -> Result { if old.is_empty() { return Err("`old` must not be empty; use write to create a file".into()); } - let text = fs::read_to_string(&path).map_err(|e| format!("{path}: {e}"))?; + let bytes = fs::read(&path).map_err(|e| format!("{path}: {e}"))?; + if bytes.len() as u64 > MAX_EDIT_BYTES { + return Err(format!( + "{path} is {} MiB, too large to edit safely; use bash (sed) instead", + bytes.len() / (1024 * 1024) + )); + } + let text = String::from_utf8(bytes).map_err(|_| { + format!( + "{path} is not valid UTF-8, so edit cannot round-trip it without \ + corrupting the file; use bash (sed, perl) instead" + ) + })?; // Fail before the approval prompt if the match is unusable. locate(&text, &old)?; Ok(Change::Edit { path, old, new }) diff --git a/tests/loop.rs b/tests/loop.rs index ac137da..d6df43c 100644 --- a/tests/loop.rs +++ b/tests/loop.rs @@ -7,6 +7,9 @@ use std::thread; use serde_json::json; +/// Tests in this binary share process-wide environment variables. +static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + use agent686::agent; use agent686::config::Config; use agent686::session::Session; @@ -57,6 +60,7 @@ fn temp_dir(tag: &str) -> PathBuf { #[test] fn runs_a_tool_call_then_finishes_and_records_every_message() { + let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let dir = temp_dir("write"); let target = dir.join("hello.txt"); let arguments = json!({ @@ -128,6 +132,7 @@ fn runs_a_tool_call_then_finishes_and_records_every_message() { #[test] fn a_denied_tool_call_is_returned_as_data() { + let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let dir = temp_dir("denied"); let target = dir.join("never.txt"); let arguments = json!({ @@ -201,6 +206,7 @@ fn tool_call(index: usize, id: &str, name: &str, arguments: serde_json::Value) - #[test] fn aborting_between_tool_calls_answers_every_call() { + let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let dir = temp_dir("abort-mid-calls"); let slow = sse(&format!( "data: {}\n\ndata: [DONE]\n\n", @@ -271,6 +277,7 @@ fn aborting_between_tool_calls_answers_every_call() { #[test] fn opening_a_session_with_unanswered_calls_repairs_it() { + let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let dir = temp_dir("repair"); std::env::set_var("AGENT686_DATA", dir.join("data")); diff --git a/tests/sessions.rs b/tests/sessions.rs index b445242..f21be24 100644 --- a/tests/sessions.rs +++ b/tests/sessions.rs @@ -4,6 +4,9 @@ use std::process::Command; use serde_json::json; +/// Tests in this binary share process-wide environment variables. +static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + use agent686::session::{self, Session}; fn temp_dir(tag: &str) -> PathBuf { @@ -15,6 +18,7 @@ fn temp_dir(tag: &str) -> PathBuf { #[test] fn sessions_create_list_and_replay() { + let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); let dir = temp_dir("roundtrip"); std::env::set_var("AGENT686_DATA", &dir); @@ -50,6 +54,8 @@ fn sessions_create_list_and_replay() { assert_eq!(listed[0].model, "model-a"); assert_eq!(listed[0].messages, 2); + // A session holds an exclusive lock while open. + drop(alpha); let (reopened, system_back, messages) = Session::open("alpha").unwrap(); assert_eq!(reopened.id, "alpha"); assert_eq!(system_back["content"], "frozen"); @@ -73,3 +79,19 @@ fn cli_lists_sessions_without_a_key() { let stdout = String::from_utf8_lossy(&output.stdout); assert!(stdout.contains("no sessions"), "{stdout}"); } + +#[test] +fn a_session_cannot_be_open_twice() { + let _env = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let dir = temp_dir("lock"); + std::env::set_var("AGENT686_DATA", &dir); + + let system = json!({ "role": "system", "content": "x" }); + let first = Session::create_as("locked".into(), "m", &system).unwrap(); + + let error = Session::open("locked").err().expect("second open must fail"); + assert!(error.contains("already open"), "{error}"); + + drop(first); + Session::open("locked").expect("after the first handle closes it is available"); +} -- cgit v1.2.3