From f2d7a4fe7d30f073980b89ca924a754d9dff040b Mon Sep 17 00:00:00 2001 From: vangel76 Date: Fri, 16 Oct 2026 22:28:30 +0200 Subject: [PATCH 1/5] M-ctl: MCP bridge never replays a mutation of unknown outcome; queued control requests honour the caller's timeout (#1326, #1331) Co-Authored-By: Claude Sonnet 5.5 --- ROADMAP.md | 1 + apps/wordcraft/src/control_server.rs | 125 +++++++++++++++++++++++++-- crates/mcp/src/backend.rs | 120 +++++++++++++++++++++---- crates/mcp/src/server.rs | 94 ++++++++++++++++++-- crates/ui-egui/src/control.rs | 35 +++++++- crates/ui-egui/src/lib.rs | 5 ++ 6 files changed, 350 insertions(+), 30 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 40407d18b6..b5aa6f28e3 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -135,6 +135,7 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm ## Progress log | Date | What landed | +| 2026-10-16 | Control/MCP delivery (#1326, #1331): the MCP bridge never re-sends a mutation whose outcome is unknown (explicit "outcome unknown" error; reads and not-sent requests still retry); a control request whose caller timed out while queued never runs, and a timeout before execution is told apart from an unknown outcome; bounded MCP and reply line reads; capped unauthenticated control connections with fallible thread creation | | 2026-10-14 | DOCX row table border exceptions render and survive saving. Explicit cell borders win; a row exception does not change other rows. | | 2026-10-14 | Tab stops edited on the ruler: the corner selector picks Left/Center/Right/Decimal/Bar, a click sets a stop (Alt skips the snap), dragging moves it with a guide line and position tooltip, dragging off the ruler clears it; markers draw per kind and mirror for RTL; one `para.tabs` call and one undo step per gesture | | 2026-10-12 | Fields keep `w:dirty` through DOCX saves (#877): a begin marker flagged by a generator that couldn't compute a result (pandoc-style TOC placeholders) keeps the flag on open/save — as a buffered field or a range field — so Word still refreshes it on open; computing a result (Update Field, Update Table) clears it, like Word's F9 | diff --git a/apps/wordcraft/src/control_server.rs b/apps/wordcraft/src/control_server.rs index 2b8f4137d7..353331f2bd 100644 --- a/apps/wordcraft/src/control_server.rs +++ b/apps/wordcraft/src/control_server.rs @@ -9,6 +9,7 @@ use std::io::{BufRead, BufReader, Read, Write}; use std::net::{TcpListener, TcpStream}; use std::path::{Path, PathBuf}; use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::mpsc::{Receiver, Sender, channel}; use std::time::{Duration, Instant}; @@ -21,6 +22,38 @@ const MAX_LINE: usize = 1 << 20; /// A connection that sends no authorised request in this time is closed. const FIRST_REQUEST: Duration = Duration::from_secs(30); +/// How long a caller waits for the UI to answer a request. A request still queued after this +/// is cancelled and never runs. +const REPLY_WAIT: Duration = Duration::from_secs(60); + +/// Connections that have not yet sent an authorised request are limited to this many; more are +/// closed at once. Each one holds a thread until its first request or [`FIRST_REQUEST`]. +const MAX_UNAUTHENTICATED: usize = 64; + +/// Counts one unauthenticated connection until it authenticates or ends. +struct Admission(Option>); + +impl Admission { + fn enter(count: &Arc, max: usize) -> Option { + if count.fetch_add(1, Ordering::SeqCst) >= max { + count.fetch_sub(1, Ordering::SeqCst); + return None; + } + Some(Self(Some(count.clone()))) + } + fn release(&mut self) { + if let Some(c) = self.0.take() { + c.fetch_sub(1, Ordering::SeqCst); + } + } +} + +impl Drop for Admission { + fn drop(&mut self) { + self.release(); + } +} + /// The key file of a running control server; [`KeyFile::remove`] it when the window closes. pub struct KeyFile(PathBuf); @@ -104,14 +137,37 @@ fn keys_match(given: &str, key: &str) -> bool { } fn serve_on(listener: TcpListener, ctx: egui::Context, key: String, first: Duration) -> Receiver { + serve_with(listener, ctx, key, Limits { first, wait: REPLY_WAIT, max_unauthenticated: MAX_UNAUTHENTICATED }) +} + +/// The time and count budgets of a server (small ones in tests). +#[derive(Clone, Copy)] +struct Limits { + first: Duration, + wait: Duration, + max_unauthenticated: usize, +} + +fn serve_with(listener: TcpListener, ctx: egui::Context, key: String, limits: Limits) -> Receiver { let (tx, rx) = channel::(); let key: Arc = key.into(); - std::thread::spawn(move || { + let unauthenticated = Arc::new(AtomicUsize::new(0)); + let accept = move || { for stream in listener.incoming().flatten() { + let Some(admission) = Admission::enter(&unauthenticated, limits.max_unauthenticated) else { + log::warn!("control server: too many unauthenticated connections, one closed"); + continue; + }; let (tx, ctx, key) = (tx.clone(), ctx.clone(), key.clone()); - std::thread::spawn(move || serve(stream, tx, ctx, &key, first)); + // A thread that cannot start closes this connection only (the guard releases its slot). + if let Err(e) = std::thread::Builder::new().name("control-conn".into()).spawn(move || serve(stream, tx, ctx, &key, limits, admission)) { + log::warn!("control server: no thread for a connection: {e}"); + } } - }); + }; + if let Err(e) = std::thread::Builder::new().name("control-accept".into()).spawn(accept) { + log::error!("control server: cannot start the accept thread: {e}"); + } rx } @@ -175,11 +231,11 @@ fn discard_rest_of_line(r: &mut BufReader) { } } -fn serve(stream: TcpStream, tx: Sender, ctx: egui::Context, key: &str, first: Duration) { +fn serve(stream: TcpStream, tx: Sender, ctx: egui::Context, key: &str, limits: Limits, mut admission: Admission) { let Ok(read) = stream.try_clone() else { return }; let mut out = stream; // One overall deadline from accept to the first authorised request; after it, none. - let mut reader = BufReader::new(Timed { s: read, deadline: Some(Instant::now() + first) }); + let mut reader = BufReader::new(Timed { s: read, deadline: Some(Instant::now() + limits.first) }); let mut authorised = false; // The key an `auth` request gave this connection. let mut conn_key: Option = None; @@ -228,6 +284,7 @@ fn serve(stream: TcpStream, tx: Sender, ctx: egui::Context, key: } if !authorised { authorised = true; + admission.release(); reader.get_mut().set_deadline(None); } if method == "auth" { @@ -237,12 +294,18 @@ fn serve(stream: TcpStream, tx: Sender, ctx: egui::Context, key: } continue; } - let (req, rrx) = ControlRequest::new(method, params); + let (req, rrx, waiter) = ControlRequest::with_waiter(method, params); if tx.send(req).is_err() { break; } ctx.request_repaint(); - let r = rrx.recv_timeout(Duration::from_secs(60)).unwrap_or_else(|_| json!({"ok": false, "error": "timeout"})); + let r = rrx.recv_timeout(limits.wait).unwrap_or_else(|_| { + if waiter.cancel() { + json!({"ok": false, "error": "timeout before execution: the request was not run and never will be"}) + } else { + json!({"ok": false, "error": "timeout: outcome unknown, the request had started when the wait ended; inspect the document to check"}) + } + }); if !reply(r) { break; } @@ -532,4 +595,52 @@ mod tests { } let _ = std::fs::remove_dir_all(&dir); } + + fn boot_limits(limits: Limits) -> (u16, Receiver) { + let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); + let port = listener.local_addr().unwrap().port(); + (port, serve_with(listener, egui::Context::default(), KEY.to_string(), limits)) + } + + fn small(wait_ms: u64, max_unauthenticated: usize) -> Limits { + Limits { first: FIRST_REQUEST, wait: Duration::from_millis(wait_ms), max_unauthenticated } + } + + #[test] + fn a_request_that_timed_out_in_the_queue_never_runs() { + let (port, rx) = boot_limits(small(150, 8)); + let mut c = Conn::open(port); + let r = c.call(&format!(r#"{{"id":1,"key":"{KEY}","method":"engine.execute","params":{{"command":"text.insert"}}}}"#)); + assert_eq!(r["ok"], false); + assert!(r["error"].as_str().unwrap_or("").starts_with("timeout before execution"), "{r}"); + // The UI gets to it late: it must not run it. + let req = rx.recv_timeout(Duration::from_secs(5)).unwrap(); + assert!(!req.start(), "a cancelled request was started"); + } + + #[test] + fn a_request_that_started_before_the_timeout_reports_an_unknown_outcome() { + let (port, rx) = boot_limits(small(150, 8)); + let mut c = Conn::open(port); + c.send(&format!(r#"{{"id":1,"key":"{KEY}","method":"engine.execute","params":{{"command":"text.insert"}}}}"#)); + let req = rx.recv_timeout(Duration::from_secs(5)).unwrap(); + assert!(req.start()); + let r = c.recv(); + assert!(r["error"].as_str().unwrap_or("").contains("outcome unknown"), "{r}"); + } + + #[test] + fn unauthenticated_connections_are_limited() { + let (port, rx) = boot_limits(small(5_000, 2)); + let mut idle = [Conn::open(port), Conn::open(port)]; + // Give the server time to count both. + std::thread::sleep(Duration::from_millis(200)); + assert!(Conn::open(port).closed(), "the third idle connection was admitted"); + // One authenticates: its slot is free again. + assert_eq!(idle[0].call(&format!(r#"{{"id":1,"method":"auth","key":"{KEY}"}}"#))["ok"], true); + std::thread::sleep(Duration::from_millis(200)); + let mut again = Conn::open(port); + assert_eq!(again.call(&format!(r#"{{"id":1,"method":"auth","key":"{KEY}"}}"#))["ok"], true); + assert!(rx.try_recv().is_err()); + } } diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index ac32f5d32b..8101a46ba8 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -1,6 +1,6 @@ //! Where MCP tool calls end up: a control-channel method call. -use std::io::{BufRead, BufReader, Write}; +use std::io::{BufRead, BufReader, Read, Write}; use std::net::{IpAddr, SocketAddr, TcpStream, ToSocketAddrs}; use std::path::Path; use std::time::Duration; @@ -141,27 +141,29 @@ impl Remote { Ok(req.to_string()) } - fn roundtrip(&mut self, line: &str) -> std::io::Result { + /// Send one line and read the reply line. A failure before the whole line (with its newline) + /// reached the socket is [`Failure::NotSent`]: the app cannot have run it. Any failure after + /// that is [`Failure::Unknown`]: the app may have run the request and lost the reply. + fn roundtrip(&mut self, line: &str) -> Result { let Some((reader, writer)) = self.conn.as_mut() else { - return Err(std::io::Error::new(std::io::ErrorKind::NotConnected, "not connected")); + return Err(Failure::NotSent(std::io::Error::new(std::io::ErrorKind::NotConnected, "not connected"))); }; - writer.write_all(line.as_bytes())?; - writer.write_all(b"\n")?; - writer.flush()?; - let mut reply = String::new(); - if reader.read_line(&mut reply)? == 0 { - return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "control channel closed")); - } - Ok(reply) + let mut out = Vec::with_capacity(line.len() + 1); + out.extend_from_slice(line.as_bytes()); + out.push(b'\n'); + writer.write_all(&out).and_then(|()| writer.flush()).map_err(Failure::NotSent)?; + let reply = read_bounded_line(reader, MAX_REPLY).map_err(Failure::Unknown)?; + String::from_utf8(reply).map_err(|_| Failure::Unknown(std::io::Error::new(std::io::ErrorKind::InvalidData, "reply is not UTF-8"))) } - /// One request and its reply, with one retry on a new connection (the app may have - /// restarted; a new connection also reads the key again). + /// One request and its reply. A request that was not sent, or one that only reads, is tried + /// once more on a new connection (the app may have restarted; a new connection also reads + /// the key again). A mutation whose outcome is unknown is never sent again: it may have run. fn exchange(&mut self, id: u64, method: &str, params: &Value) -> Result { let unreachable = |addr: &str, e: std::io::Error| format!("WordCraft app at {addr} is not reachable: {e}"); let mut first = true; let reply = loop { - let tried = if self.conn.is_some() { Ok(()) } else { self.reconnect() }; + let tried = if self.conn.is_some() { Ok(()) } else { self.reconnect().map_err(Failure::NotSent) }; let result = match tried { Ok(()) => { let line = self.request_line(id, method, params)?; @@ -171,10 +173,18 @@ impl Remote { }; match result { Ok(r) => break r, - Err(e) => { + Err(f) => { self.conn = None; + if let Failure::Unknown(e) = &f + && !is_read_only(method) + { + return Err(format!( + "outcome unknown: the connection to the WordCraft app at {} failed after `{method}` was sent ({e}); it may have been executed, so it is not sent again. Inspect the document to check", + self.addr + )); + } if !first { - return Err(unreachable(&self.addr, e)); + return Err(unreachable(&self.addr, f.into_error())); } first = false; } @@ -184,6 +194,44 @@ impl Remote { } } +/// Why a round trip failed. +enum Failure { + /// Before the whole request reached the socket: the app did not run it. + NotSent(std::io::Error), + /// After the request was sent: the app may have run it. + Unknown(std::io::Error), +} + +impl Failure { + fn into_error(self) -> std::io::Error { + match self { + Self::NotSent(e) | Self::Unknown(e) => e, + } + } +} + +/// Longest reply line accepted from the app (screenshots and renders come as base64). +const MAX_REPLY: usize = 128 << 20; + +/// Methods that only read: sending them twice does no harm. +fn is_read_only(method: &str) -> bool { + matches!(method, "document.inspect" | "engine.commands" | "ui.inspect" | "ui.parity" | "ui.render" | "ui.screenshot") +} + +/// One line (with its newline) of at most `max` bytes. An end of stream before any byte, or a +/// longer line, is an error. +fn read_bounded_line(r: &mut impl BufRead, max: usize) -> std::io::Result> { + let mut buf = Vec::new(); + let n = Read::take(&mut *r, max as u64 + 1).read_until(b'\n', &mut buf)?; + if n == 0 { + return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "control channel closed")); + } + if buf.len() > max && !buf.ends_with(b"\n") { + return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, format!("reply line longer than {max} bytes"))); + } + Ok(buf) +} + impl Backend for Remote { fn call(&mut self, method: &str, params: Value) -> Result { let id = self.next_id; @@ -382,4 +430,44 @@ mod tests { assert!(e.contains("not a loopback address") && e.contains("not sent"), "{e}"); assert!(seen.recv_timeout(WAIT).unwrap().get("key").is_none()); } + + #[test] + fn a_mutation_with_a_lost_reply_is_not_sent_again() { + // The app runs the request, then the connection drops without a reply. + let (port, seen) = fake_app(|_| None); + let mut r = Remote::connect_with(&format!("127.0.0.1:{port}"), fixed_key("k")).unwrap(); + let e = r.call("engine.execute", json!({"command": "text.insert", "params": {"text": "x"}})).unwrap_err(); + assert!(e.contains("outcome unknown"), "{e}"); + assert_eq!(seen.recv_timeout(WAIT).unwrap()["method"], "engine.execute"); + std::thread::sleep(Duration::from_millis(200)); + assert!(seen.try_recv().is_err(), "the mutation was sent a second time"); + } + + #[test] + fn a_read_with_a_lost_reply_is_sent_again() { + let n = Arc::new(AtomicUsize::new(0)); + let (port, seen) = fake_app(move |_| if n.fetch_add(1, Ordering::SeqCst) == 0 { None } else { Some((json!({"ok": true, "result": 3}), false)) }); + let mut r = Remote::connect_with(&format!("127.0.0.1:{port}"), fixed_key("k")).unwrap(); + assert_eq!(r.call("document.inspect", json!({})).unwrap(), json!(3)); + assert_eq!(seen.try_iter().count(), 2); + } + + #[test] + fn a_mutation_not_sent_goes_out_on_a_new_connection() { + let (port, seen) = fake_app(|_| Some((json!({"ok": true, "result": 1}), false))); + let mut r = Remote::connect_with(&format!("127.0.0.1:{port}"), fixed_key("k")).unwrap(); + r.conn = None; + assert_eq!(r.call("engine.execute", json!({"command": "file.new"})).unwrap(), json!(1)); + assert_eq!(seen.try_iter().count(), 1); + } + + #[test] + fn a_reply_line_is_bounded() { + let mut ok = std::io::Cursor::new(b"abc\nrest".to_vec()); + assert_eq!(read_bounded_line(&mut ok, 8).unwrap(), b"abc\n"); + let mut long = std::io::Cursor::new(vec![b'x'; 100]); + assert!(read_bounded_line(&mut long, 8).is_err()); + let mut empty = std::io::Cursor::new(Vec::new()); + assert!(read_bounded_line(&mut empty, 8).is_err()); + } } diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs index 63f6764c61..2578ba1553 100644 --- a/crates/mcp/src/server.rs +++ b/crates/mcp/src/server.rs @@ -1,6 +1,6 @@ //! JSON-RPC 2.0 framing and the MCP lifecycle / tools / resources methods. -use std::io::{BufRead, Write}; +use std::io::{BufRead, Read, Write}; use serde_json::{Value, json}; @@ -24,6 +24,42 @@ parameters with list_commands and run them with execute (or several with batch). \"Hello\" → execute text.newParagraph → execute para.style {style:\"Heading 1\"} → select_text {text:\"Hello\"} → \ execute format.bold → inspect_document to verify → render_page to look at the result → save {path:\"out.docx\"}."; +/// Longest request line accepted on stdin. +const MAX_LINE: usize = 32 << 20; + +enum Line { + End, + TooLong, + Text(String), +} + +/// The next line of at most `max` bytes. A longer one is read to its end and dropped, a line +/// that is not UTF-8 is replaced lossily (the JSON parser then rejects it). +fn read_line(input: &mut impl BufRead, max: usize) -> std::io::Result { + let mut buf = Vec::new(); + let n = Read::take(&mut *input, max as u64 + 1).read_until(b'\n', &mut buf)?; + if n == 0 { + return Ok(Line::End); + } + if buf.len() > max && !buf.ends_with(b"\n") { + loop { + let (used, done) = match input.fill_buf()? { + [] => break, + b => match b.iter().position(|&c| c == b'\n') { + Some(i) => (i + 1, true), + None => (b.len(), false), + }, + }; + input.consume(used); + if done { + break; + } + } + return Ok(Line::TooLong); + } + Ok(Line::Text(String::from_utf8_lossy(&buf).into_owned())) +} + /// Resource URIs. pub const DOC_URI: &str = "wordcraft://document"; pub const COMMANDS_URI: &str = "wordcraft://commands"; @@ -58,16 +94,25 @@ impl Server { /// Serve newline-delimited JSON-RPC until `input` closes. Logs go to stderr only (stdout is /// the protocol stream). - pub fn serve(&mut self, input: impl BufRead, mut output: impl Write) -> std::io::Result<()> { - for line in input.lines() { - let line = line?; - if let Some(reply) = self.handle_line(&line) { + pub fn serve(&mut self, input: impl BufRead, output: impl Write) -> std::io::Result<()> { + self.serve_bounded(input, output, MAX_LINE) + } + + /// [`Server::serve`] with a request line limit of `max` bytes. A longer line is dropped + /// (without keeping it in memory) and answered with an error. + fn serve_bounded(&mut self, mut input: impl BufRead, mut output: impl Write, max: usize) -> std::io::Result<()> { + loop { + let reply = match read_line(&mut input, max)? { + Line::End => return Ok(()), + Line::TooLong => Some(error(Value::Null, INVALID_REQUEST, format!("request line longer than {max} bytes")).to_string()), + Line::Text(line) => self.handle_line(&line), + }; + if let Some(reply) = reply { output.write_all(reply.as_bytes())?; output.write_all(b"\n")?; output.flush()?; } } - Ok(()) } /// Handle one line; returns the reply line (None for notifications and blank lines). @@ -166,3 +211,40 @@ impl Server { } } } + +#[cfg(test)] +mod bounded_tests { + use super::*; + + struct Null; + impl Backend for Null { + fn call(&mut self, _: &str, _: Value) -> Result { + Ok(Value::Null) + } + fn has_ui(&self) -> bool { + false + } + fn describe(&self) -> String { + "test".into() + } + } + + #[test] + fn an_oversize_line_is_refused_and_the_next_one_still_served() { + let mut input = vec![b'x'; 200]; + input.extend_from_slice(b"\n{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"}\n"); + let mut out = Vec::new(); + Server::new(Box::new(Null)).serve_bounded(std::io::Cursor::new(input), &mut out, 64).unwrap(); + let lines: Vec = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + assert_eq!(lines.len(), 2, "{lines:?}"); + assert_eq!(lines[0]["error"]["code"], INVALID_REQUEST); + assert_eq!(lines[1]["id"], 1); + } + + #[test] + fn a_line_without_a_newline_is_bounded() { + let mut out = Vec::new(); + Server::new(Box::new(Null)).serve_bounded(std::io::Cursor::new(vec![b'x'; 10_000]), &mut out, 64).unwrap(); + assert!(String::from_utf8(out).unwrap().contains("longer than 64")); + } +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 9e09e54fee..9da69d469f 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -23,12 +23,45 @@ pub struct ControlRequest { pub method: String, pub params: Value, pub reply: Sender, + /// Shared with the waiter: whichever of "start" and "give up" happens first wins. + state: std::sync::Arc, +} + +const QUEUED: u8 = 0; +const STARTED: u8 = 1; +const CANCELLED: u8 = 2; + +/// The waiter's side of a [`ControlRequest`]: it gives up on a request that has not started. +#[derive(Clone)] +pub struct ControlWaiter(std::sync::Arc); + +impl ControlWaiter { + /// Cancel the request. True when it had not started: it will never run. False when the UI + /// already started it: its outcome is unknown to the waiter. + pub fn cancel(&self) -> bool { + use std::sync::atomic::Ordering::SeqCst; + self.0.compare_exchange(QUEUED, CANCELLED, SeqCst, SeqCst).is_ok() + } } impl ControlRequest { pub fn new(method: impl Into, params: Value) -> (Self, std::sync::mpsc::Receiver) { + let (req, rx, _) = Self::with_waiter(method, params); + (req, rx) + } + + /// Like [`ControlRequest::new`], plus the handle the waiter uses to cancel a queued request. + pub fn with_waiter(method: impl Into, params: Value) -> (Self, std::sync::mpsc::Receiver, ControlWaiter) { let (tx, rx) = std::sync::mpsc::channel(); - (Self { method: method.into(), params, reply: tx }, rx) + let state = std::sync::Arc::new(std::sync::atomic::AtomicU8::new(QUEUED)); + (Self { method: method.into(), params, reply: tx, state: state.clone() }, rx, ControlWaiter(state)) + } + + /// The UI is about to run the request. False when the waiter already gave up on it: it + /// must not run. + pub fn start(&self) -> bool { + use std::sync::atomic::Ordering::SeqCst; + self.state.compare_exchange(QUEUED, STARTED, SeqCst, SeqCst).is_ok() } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 662516fbd6..5d8ed722b5 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2159,6 +2159,11 @@ impl WordApp { let Some(rx) = self.control_rx.take() else { return }; while let Ok(req) = rx.try_recv() { let reply = req.reply.clone(); + if !req.start() { + // The caller timed out while this waited in the queue and was told it did not run. + log::debug!("control request {} dropped: its caller gave up", req.method); + continue; + } match control::handle(self, ctx, &req) { control::Outcome::Done(v) => { let _ = reply.send(v); From 3445b7226d97251eea2668c8f4fc4b899495006d Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 17 Oct 2026 11:50:34 +0200 Subject: [PATCH 2/5] M-ctl: cargo fmt the MCP bridge test (long fake_app line broke cargo fmt --all --check in CI) --- crates/mcp/src/backend.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index 8101a46ba8..614e451afc 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -446,7 +446,8 @@ mod tests { #[test] fn a_read_with_a_lost_reply_is_sent_again() { let n = Arc::new(AtomicUsize::new(0)); - let (port, seen) = fake_app(move |_| if n.fetch_add(1, Ordering::SeqCst) == 0 { None } else { Some((json!({"ok": true, "result": 3}), false)) }); + let (port, seen) = + fake_app(move |_| if n.fetch_add(1, Ordering::SeqCst) == 0 { None } else { Some((json!({"ok": true, "result": 3}), false)) }); let mut r = Remote::connect_with(&format!("127.0.0.1:{port}"), fixed_key("k")).unwrap(); assert_eq!(r.call("document.inspect", json!({})).unwrap(), json!(3)); assert_eq!(seen.try_iter().count(), 2); From 2f46f194a13a0bdb4c22dbce991bc6376e34fcec Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 21 Oct 2026 23:48:49 +0200 Subject: [PATCH 3/5] render: count legacy effect copies past the glyph box, not the glyph's antialiasing The grey band 120-136 also holds the glyph's own antialiasing pixels on the vertical stem edges; on platforms with many of them (FreeBSD's Mesa AA), their centroid sits at the glyph centre and hides the copy's offset in x (0.95 instead of ~6). The copy is drawn fully past the glyph's bounding box in its own direction, so count grey only outside the box in the copy's quadrant. Fixes the FreeBSD failure of #2783. --- crates/render/src/lib.rs | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index b0416c11e6..59f5ca11a8 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -1578,20 +1578,39 @@ mod tests { fn legacy_font_effects_are_drawn() { use wordcraft_doc::CharProps; // Dark and grey pixel counts, and the grey pixels' mean offset from the dark ones. - let shot = |c: CharProps| { + let shot = |c: CharProps, sign: f64| { let mut d = Document::from_text("x"); let cp = CharProps { size: Some(40.0), bold: Some(true), ..c }; d.body = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("HHHH", cp))]; let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default()); let img = render_page(&d, &l.pages[0], 2.0, &RenderOptions::default()); let (mut dark, mut grey) = ((0.0, 0.0, 0.0f64), (0.0, 0.0, 0.0f64)); + // The glyph's own antialiasing has pixels in the copy's grey range, on the vertical + // stem edges as well as around the copy. Their centroid is the glyph centre, and on + // some platforms they are numerous enough to hide the copy's offset in x. The copy + // is only visible outside the dark glyph's bounding box, so count grey there. + let mut box_ = (i64::MAX, i64::MAX, i64::MIN, i64::MIN); // min x, min y, max x, max y + for (x, y) in (100..800).flat_map(|x| (100..300).map(move |y| (x, y))) { + if (0..60).contains(&img.pixel(x, y)[0]) { + box_ = (box_.0.min(i64::from(x)), box_.1.min(i64::from(y)), box_.2.max(i64::from(x)), box_.3.max(i64::from(y))); + } + } + let (bx0, by0, bx1, by1) = (box_.0, box_.1, box_.2, box_.3); for (x, y) in (100..800).flat_map(|x| (100..300).map(move |y| (x, y))) { let v = img.pixel(x, y)[0]; + // The copy sits down-right (or up-left) of the glyph, fully past its bounding box. + // Counting grey past the box keeps the glyph's own antialiasing, whose centroid + // hides the copy's offset on some platforms, out of the mean. + let in_copy = match sign { + 1.0 => i64::from(x) > bx1 && i64::from(y) > by1, + -1.0 => i64::from(x) < bx0 && i64::from(y) < by0, + _ => true, + }; // The copy is solid RGB 128; a wider range would count the glyph's own // antialiasing, whose centroid hides the copy's offset on some fonts. let acc = match v { 0..60 => &mut dark, - 120..=136 => &mut grey, + 120..=136 if in_copy => &mut grey, _ => continue, }; *acc = (acc.0 + 1.0, acc.1 + f64::from(x), acc.2 + f64::from(y)); @@ -1600,16 +1619,16 @@ mod tests { let ((dx, dy), (gx, gy)) = (mean(dark), mean(grey)); (dark.0, grey.0, (gx - dx, gy - dy)) }; - let (plain_dark, plain_grey, _) = shot(CharProps::default()); + let (plain_dark, plain_grey, _) = shot(CharProps::default(), 1.0); assert!(plain_dark > 2000.0, "plain {plain_dark}"); - let (dark, _, _) = shot(CharProps { outline: Some(true), ..Default::default() }); + let (dark, _, _) = shot(CharProps { outline: Some(true), ..Default::default() }, 1.0); assert!(dark < plain_dark / 3.0, "outline is hollow: {dark} vs {plain_dark}"); for (c, sign) in [ (CharProps { shadow: Some(true), ..Default::default() }, 1.0), (CharProps { emboss: Some(true), ..Default::default() }, 1.0), (CharProps { engrave: Some(true), ..Default::default() }, -1.0), ] { - let (_, grey, (ox, oy)) = shot(c); + let (_, grey, (ox, oy)) = shot(c, sign); assert!(grey > plain_grey * 2.0, "a grey copy: {grey} vs {plain_grey}"); assert!(ox * sign > 1.0 && oy * sign > 1.0, "grey copy offset {ox} {oy}"); } From 0e7dc8da5312f1247dfd82e15ba6284097aef09b Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 31 Oct 2026 22:12:18 +0100 Subject: [PATCH 4/5] fix(control): prevent ambiguous mutation replay (#2596) Propagate accept-thread startup errors and remove the key file. Keep image exports from being retried and continue stdio after invalid UTF-8. Co-Authored-By: Codex --- ROADMAP.md | 4 +- apps/wordcraft/src/control_server.rs | 79 ++++++++++++++++-- crates/mcp/src/backend.rs | 119 +++++++++++++++++++++++---- crates/mcp/src/server.rs | 12 ++- crates/mcp/src/tests.rs | 21 +++++ docs/control-protocol.md | 17 ++++ docs/mcp.md | 18 ++++ 7 files changed, 238 insertions(+), 32 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 01dca5174b..15c1c940c6 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -4,7 +4,7 @@ **Stage: alpha** · next: beta, ~15 points (60% → 75% ready for real work) and ~150–230 h away -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** trivial (progress log: a paragraph naming an undefined style is formatted as Normal, #5077); previously trivial (progress log: TOC page numbers as PAGEREF fields, #5097); previously trivial (progress log: Backstage keytips, #4960); previously trivial (Progress log: only the printer's PDF leaves out links; Save these pages as PDF keeps them, #4734); previously trivial (progress log: Chinese and Japanese text counts a word per character, #4547; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (progress log: corporate authors in bibliographies, #4848); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (progress log: Table Properties follows the selection, #4857); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion walks reference offsets and formatting runs together, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (progress log: RTF pictures stored as Windows or Enhanced Metafiles are imported, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (progress log: Insert › Shapes icon grid, #4349); previously trivial (progress log: AutoCorrect Options with no document open, #4585); previously trivial (progress log: window fallback geometry and equation symbol tooltips); previously trivial (progress log: window titles omit NUL characters, #3634); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (progress log: Custom document properties dialog, #2982; previously trivial: progress log: View › New Window; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: progress log: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: progress log: recovery copies and .json files store pictures as base64, #586 follow-up; previously trivial: progress log: legacy menu keys, #1697; previously trivial: progress log: shape gradients and transparency, #1500; previously trivial: progress log: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: progress log: text above a float's anchor wraps around it, #2048; previously trivial: progress log: File › Recover follows the app theme, #3243; previously trivial: progress log: formatting toolbar with the text context menu, #2959; previously trivial: progress log: caret inside ligatures, #1974; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: progress log: a header-cell picture watermark sits behind the text, #1775; previously trivial: symbols keep their font when the text font changes, #2036; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: Add Font imports every selected font file, #1789); previously trivial (RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: Read Aloud speaks each sentence in its own language, #1843; previously trivial: hint-reliant CJK outlines; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: progress log: Turkish case mapping in AutoCorrect, #1923; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: progress log: Hebrew field results and smart quotes, #1670; previously trivial: Backspace removes a selected table, rows or columns, #1844; previously trivial: progress log: mixed Hebrew/Latin text keeps its order in Word, #1543; previously trivial: progress log: web typing in non-Latin text no longer repeats, #1480; previously trivial: progress log: font family caches bounded and math font lookups follow font changes, #1354; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: progress log: Columns on selected text, #2024; previously trivial: progress log: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: progress log: Indonesian proofing, #498; previously trivial: progress log: DOCX glossary documents (building blocks); previously trivial: progress log: Read Mode keeps the keyboard and shows whole, unobscured columns, #1772); previously trivial: progress log: font list entries of tall-ascent fonts no longer cut off, #2570); previously trivial: progress log: Split Cells and Convert Text to Table dialogs follow the Word check, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout fills the window width, #1876; previously trivial: progress log: Different First Page headers reachable from page 1, #2826; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: progress log: web preferences kept between visits, #2132; previously trivial: progress log: undrawable private-use list bullets show the level's default bullet, #1683; previously trivial: progress log: `w:eastAsianLayout` kept on save; previously trivial: table style editor formats every part, #714); previously trivial: VML freeforms read and kept on save; previously trivial: progress log: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: progress log: grouped `flowChartOr` shapes draw their circle and crossing spokes; previously trivial: progress log: copies keep their formatting in other programs, #1523; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; progress docs restructured) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-31 · **Change:** trivial (Control/MCP #2596 review: partial-write outcomes, path-bearing image exports, accept-thread startup cleanup and malformed UTF-8 handling); previously trivial (progress log: a paragraph naming an undefined style is formatted as Normal, #5077); previously trivial (progress log: TOC page numbers as PAGEREF fields, #5097); previously trivial (progress log: Backstage keytips, #4960); previously trivial (Progress log: only the printer's PDF leaves out links; Save these pages as PDF keeps them, #4734); previously trivial (progress log: Chinese and Japanese text counts a word per character, #4547; previously trivial: aligned-copy review fixes retain the document axis through scrolling and include secondary selections (#4764)); previously trivial (connector rerouting indexes laid-out object positions once per batch (#3631); previously trivial (progress log: corporate authors in bibliographies, #4848); previously trivial (custom-property bookmark-link preservation, #4767); previously trivial (progress log: Table Properties follows the selection, #4857); previously trivial (Relative font-size commands preserve mixed sizes in the selection (#4903); existing button steps and one-point shortcuts are unchanged; readiness estimates unchanged); previously trivial (Arabic Backspace removes one combining mark and keeps its base letter (#4757); previously trivial (note conversion walks reference offsets and formatting runs together, #4750); previously trivial (DOCX comment-ID save lookups); previously trivial (progress log: RTF pictures stored as Windows or Enhanced Metafiles are imported, #4259); previously trivial (#4658 bounds nested Markdown reference-label work); previously trivial (HTML import keeps preformatted lines with CR or CRLF input newlines, #4810); previously trivial (progress log: Insert › Shapes icon grid, #4349); previously trivial (progress log: AutoCorrect Options with no document open, #4585); previously trivial (progress log: window fallback geometry and equation symbol tooltips); previously trivial (progress log: window titles omit NUL characters, #3634); previously trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (progress log: Custom document properties dialog, #2982; previously trivial: progress log: View › New Window; previously trivial: progress log: interface translations come from storytold/craft-i18n through the `craft-i18n` crate; previously trivial: progress log: disabled-control reasons translated in every interface language, #2678; previously trivial: progress log: mail merge record navigation and record ranges for printing, #3028; previously trivial: selection bar for right-to-left paragraphs and table rows; previously trivial: group connector rerouting preserves rotated and flipped free or unresolved endpoints under nonuniform group scaling; readiness estimates unchanged; previously trivial: progress log: a word with no break opportunity in it no longer makes the layout quadratic, #3412; previously trivial: progress log: a relationship the markup names without the prefix is read as it wrote, and an ordinary `id` names no part; previously trivial: progress log: a document with many relationships opens in the time its part takes, and an id the text only mentions is not a reference, #3411; previously trivial: progress log: read only and comments-only protection grey out edits; previously trivial: progress log: an empty paragraph with a hidden mark shows nothing, not even its list number, #3982; previously trivial: progress log: "NaN" in the Font dialog's Size box no longer closes the app, #3663; previously trivial: progress log: a table cell span from a `.json` file no longer overflows, #3637; previously trivial: progress log: a click in the footer while editing the header moves there; previously trivial: explicit documents keep the editor when recovery discovery finishes; readable recovery controls; previously trivial: Slovenian interface catalog, 2,614 entries; previously trivial: Insert Table of Figures dialog for any caption label, #3013; previously trivial: progress log: Home › Underline drop-down, #2738; previously trivial: personal templates in File › New and Save as Word Template, #2852; previously trivial: progress log: the scrollbar page tip stays on one line, #3341; previously trivial: progress log: forms protection greys out the control buttons; previously trivial: progress log: a document with many content controls saves in the time the controls take, #13; previously trivial: progress log: Word signature lines kept on save; previously trivial: a Thai run with Latin finds one installed font covering it all on Linux too, #1549; previously trivial: progress log: closing the header returns to the body selection, #3331; previously trivial: progress log: saving to a NAS share mounted by GVFS, #3003; previously trivial: progress log: a picture dragged near the bottom of a page lands there, #3169; previously trivial: centred list labels after leading page breaks, #2964; previously trivial: progress log: inline pictures drag to an insertion cursor and stay inline, #2233, #2234; previously trivial: progress log: a text file saved over itself closes without asking, #2376; previously trivial: progress log: a text frame in the paragraph defaults frames nothing, #2360; previously trivial: fixed font inputs in four layout controls; previously trivial: typing no longer starts render threads on every repaint, #3027; previously trivial: a right, centre or decimal tab whose text doesn't fit, or a left tab past the right indent, goes to the next line with its text, #1840; previously trivial: progress log: banded rows shade as in Word, #3415; previously trivial: progress log: the table handles show while the caret is in the table, #2428; previously trivial: progress log: a click below a floating table reaches the text after it, #2038; previously trivial: progress log: Delete on selected table cells leaves one empty paragraph in each, #2802; previously trivial: progress log: lam-alef in exported PDFs extracts whole with fonts that draw it as two glyphs, #2310; previously trivial: Bullets and Numbering toggle off style-inherited lists at their effective level, including basedOn chains and numbered ListParagraph styles; other paragraphs and list definitions stay unchanged (related to #3459); previously trivial: Russian sorting keeps ё with е and recognises decomposed ё/й; previously trivial: progress log: a text box that keeps the keyboard no longer resets the input method every frame, #2986; previously trivial: progress log: recovery copies and .json files store pictures as base64, #586 follow-up; previously trivial: progress log: legacy menu keys, #1697; previously trivial: progress log: shape gradients and transparency, #1500; previously trivial: progress log: Focus fills the screen, and Full Screen View shows the pages alone, #1678; previously trivial: progress log: text above a float's anchor wraps around it, #2048; previously trivial: progress log: File › Recover follows the app theme, #3243; previously trivial: progress log: formatting toolbar with the text context menu, #2959; previously trivial: progress log: caret inside ligatures, #1974; previously trivial: text typed into a content control takes the control's formatting; localized placeholder styles recognised; previously trivial: forms protection keeps its content controls: no inserting, Properties or Remove Content Control; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: progress log: a header-cell picture watermark sits behind the text, #1775; previously trivial: symbols keep their font when the text font changes, #2036; previously trivial: opening a DOCX no longer copies its pictures; previously trivial: Add Font imports every selected font file, #1789); previously trivial (RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: Read Aloud speaks each sentence in its own language, #1843; previously trivial: hint-reliant CJK outlines; previously trivial: Ctrl+wheel zoom no longer scrolls the document, #1743; previously trivial: progress log: Turkish case mapping in AutoCorrect, #1923; previously trivial: a mouse drag on a table leaves the view where it is, #1738; previously trivial: progress log: Hebrew field results and smart quotes, #1670; previously trivial: Backspace removes a selected table, rows or columns, #1844; previously trivial: progress log: mixed Hebrew/Latin text keeps its order in Word, #1543; previously trivial: progress log: web typing in non-Latin text no longer repeats, #1480; previously trivial: progress log: font family caches bounded and math font lookups follow font changes, #1354; previously trivial: `-->` AutoCorrect replacement, #2223; previously trivial: numbered headings, #1793; previously trivial: Navigation Find exposes Results, #2096; previously trivial: progress log: Columns on selected text, #2024; previously trivial: progress log: legacy outline, shadow, emboss and imprint text effects drawn, #2534; previously trivial: progress log: Indonesian proofing, #498; previously trivial: progress log: DOCX glossary documents (building blocks); previously trivial: progress log: Read Mode keeps the keyboard and shows whole, unobscured columns, #1772); previously trivial: progress log: font list entries of tall-ascent fonts no longer cut off, #2570); previously trivial: progress log: Split Cells and Convert Text to Table dialogs follow the Word check, #2592; previously trivial: a new source's Tag is made like Word's, three letters of the author and two digits of the year with a number added when taken, and an edit keeps the Tag, #2094; previously trivial: Web Layout fills the window width, #1876; previously trivial: progress log: Different First Page headers reachable from page 1, #2826; previously trivial: Language dialog keeps inherited proofing language and no-proof choices (#2717); previously trivial: progress log: web preferences kept between visits, #2132; previously trivial: progress log: undrawable private-use list bullets show the level's default bullet, #1683; previously trivial: progress log: `w:eastAsianLayout` kept on save; previously trivial: table style editor formats every part, #714); previously trivial: VML freeforms read and kept on save; previously trivial: progress log: consistent preferred cell widths; previously trivial: multi-paragraph field instructions no longer add blank lines; previously trivial: page-break-only list paragraphs hide their labels; previously trivial: progress log: grouped `flowChartOr` shapes draw their circle and crossing spokes; previously trivial: progress log: copies keep their formatting in other programs, #1523; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; progress docs restructured) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-29 · **Change:** trivial (Recipient labels continue across product-sized sheets instead of stopping after the first sheet (#4880)); previously trivial (English dialects in proofing, #1281; previously trivial: triple borders draw three lines, #1740; previously trivial: progress log: double-clicking a later page's footer no longer scrolls up, #2103; previously trivial: long navigation headings wrap onto further lines within the pane, #3015; previously trivial: clearing a no-match font query keeps the recent heading visible, #2068; previously trivial: a word after a slash wraps whole, like Word, #2963; previously trivial: RTF export writes sections (gap 19); previously trivial: ODT export writes sections (gap 19); previously trivial: progress log: pasted blockquotes are indented paragraphs, #1270; previously trivial: progress log: print-area strings translated in every catalog; previously trivial: progress log: comments readable in the dark theme, #2045; previously trivial: progress log: ODT sections, #1379; previously trivial: progress log: table deletes, Change Case and Unlink Fields respect Track Changes and locked content controls, #1329; previously trivial: progress log: rounded rectangle corners, #1476; previously trivial: progress log: Save As type list, #1399; previously trivial: progress log: privacy options on save, #1062; previously trivial: progress log: equation pictures in theme colours on Windows, #1002; previously trivial: symbol fonts, #776; previously trivial: the save prompt answers from the keyboard, #861; previously trivial: table column and row markers on the rulers, #700; previously trivial: table borders and the resize handle drag on the page, #217; previously trivial: formatting revisions landed, #41; previously trivial: Draw tab ink, #307, and Draw Table and Eraser, #303, landed: catalog 402/434; previously minor: readiness table with hours per audience; full number back to the additive weighted sum, 60%; mainstream and essentials numbers added; alpha gate checked; previously major: full re-measure against Word for Mac 16.113.4; progress docs restructured) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 > **Printing update:** 2026-10-12 · direct desktop printing through craft-print; details below. @@ -273,6 +273,7 @@ Imported Word 97–2003 `.doc`/`.dot` files now ask for a supported DOCX target | 2026-10-18 | Clearing a font query with no matches keeps Recently Used Fonts visible at the top of a scrollable list. The initial scroll position no longer skips its heading; measured keyboard scrolling is unchanged (#2068). | | 2026-10-19 | Centred numbered headings after a leading page break keep their number before the text (#2964). The label uses the alignment of the line it is drawn on; heading text positions and page count stay the same. | | 2026-10-17 | Edit Recipient List finds records (#1576): a Find in list box hides rows with no cell containing the text (any case) and counts the matches, and "Show only records that will be merged" hides the rows the filter leaves out; both only change the view. Rows are striped, and edits and removes go to the right record however the grid is narrowed | +| 2026-10-31 | Control/MCP #2596 review: write/flush failures after sending begins are outcome-unknown; image exports to a path are not replayed; accept-thread startup failures disable the server and remove the key; invalid UTF-8 is rejected per line without ending stdio. Synthetic regressions cover partial JSON delivery at EOF, flush failure, export vs in-memory retry and failed startup. | | 2026-10-16 | Control/MCP delivery (#1326, #1331): the MCP bridge never re-sends a mutation whose outcome is unknown (explicit "outcome unknown" error; reads and not-sent requests still retry); a control request whose caller timed out while queued never runs, and a timeout before execution is told apart from an unknown outcome; bounded MCP and reply line reads; capped unauthenticated control connections with fallible thread creation | | 2026-10-17 | Equation arrays centre a row that has no `&` among rows that do, as Word does, so case equations like Word's "First Property of Radicals" no longer push the aligned row right (#2617). | | 2026-10-17 | Formatting revisions: a table, row, cell or section property change made while tracking now records as `w:tblPrChange`/`w:trPrChange`/`w:tcPrChange`/`w:sectPrChange` (structure stays out), so Reject All restores and Accept All keeps it; test tracked_table_changes_are_kept_as_formatting_changes | @@ -681,6 +682,7 @@ Footer page-table height and body wrapping are corrected. Other pagination gaps | Date | Change | Summary | |---|---|---| +| 2026-10-31 | trivial | Control/MCP #2596 review fixes; readiness estimates unchanged | | 2026-10-31 | trivial | Progress log: a paragraph naming an undefined DOCX style is formatted as Normal (#5077) | | 2026-10-31 | trivial | Progress log: TOC page numbers are PAGEREF fields (#5097) | | 2026-10-31 | trivial | Progress log: Backstage keytips, Alt, F, P prints (#4960) | diff --git a/apps/wordcraft/src/control_server.rs b/apps/wordcraft/src/control_server.rs index 353331f2bd..ba8553ec35 100644 --- a/apps/wordcraft/src/control_server.rs +++ b/apps/wordcraft/src/control_server.rs @@ -70,6 +70,15 @@ impl KeyFile { /// cannot be bound or there is no random key (the control channel is off); the key file is /// `None` when it could not be written (requests are then refused). pub fn start(port: u16, ctx: egui::Context, settings: Option<&Path>) -> Option<(Receiver, Option)> { + start_with(port, ctx, settings, |listener, ctx, key| serve_on(listener, ctx, key, FIRST_REQUEST)) +} + +fn start_with( + port: u16, + ctx: egui::Context, + settings: Option<&Path>, + serve: impl FnOnce(TcpListener, egui::Context, String) -> std::io::Result>, +) -> Option<(Receiver, Option)> { let listener = match TcpListener::bind(("127.0.0.1", port)) { Ok(l) => l, Err(e) => { @@ -100,11 +109,21 @@ pub fn start(port: u16, ctx: egui::Context, settings: Option<&Path>) -> Option<( None } }; + let rx = match serve(listener, ctx, key) { + Ok(rx) => rx, + Err(e) => { + if let Some(f) = &key_file { + f.remove(); + } + log::error!("control server off: cannot start the accept thread ({e})"); + return None; + } + }; match &key_file { Some(f) => log::info!("control server listening on 127.0.0.1:{port}, key in {}", f.path().display()), None => log::info!("control server listening on 127.0.0.1:{port}"), } - Some((serve_on(listener, ctx, key, FIRST_REQUEST), key_file)) + Some((rx, key_file)) } /// A new key: 32 random bytes from the operating system, as hex. @@ -136,7 +155,7 @@ fn keys_match(given: &str, key: &str) -> bool { !b.is_empty() && a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0 } -fn serve_on(listener: TcpListener, ctx: egui::Context, key: String, first: Duration) -> Receiver { +fn serve_on(listener: TcpListener, ctx: egui::Context, key: String, first: Duration) -> std::io::Result> { serve_with(listener, ctx, key, Limits { first, wait: REPLY_WAIT, max_unauthenticated: MAX_UNAUTHENTICATED }) } @@ -148,7 +167,17 @@ struct Limits { max_unauthenticated: usize, } -fn serve_with(listener: TcpListener, ctx: egui::Context, key: String, limits: Limits) -> Receiver { +fn serve_with(listener: TcpListener, ctx: egui::Context, key: String, limits: Limits) -> std::io::Result> { + serve_with_spawner(listener, ctx, key, limits, |accept| std::thread::Builder::new().name("control-accept".into()).spawn(accept).map(|_| ())) +} + +fn serve_with_spawner( + listener: TcpListener, + ctx: egui::Context, + key: String, + limits: Limits, + spawn: impl FnOnce(Box) -> std::io::Result<()>, +) -> std::io::Result> { let (tx, rx) = channel::(); let key: Arc = key.into(); let unauthenticated = Arc::new(AtomicUsize::new(0)); @@ -165,10 +194,8 @@ fn serve_with(listener: TcpListener, ctx: egui::Context, key: String, limits: Li } } }; - if let Err(e) = std::thread::Builder::new().name("control-accept".into()).spawn(accept) { - log::error!("control server: cannot start the accept thread: {e}"); - } - rx + spawn(Box::new(accept))?; + Ok(rx) } /// The read side of a connection with an optional overall deadline: each read waits only for @@ -323,7 +350,7 @@ mod tests { fn boot_with(first: Duration) -> (u16, Receiver) { let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); let port = listener.local_addr().unwrap().port(); - (port, serve_on(listener, egui::Context::default(), KEY.to_string(), first)) + (port, serve_on(listener, egui::Context::default(), KEY.to_string(), first).unwrap()) } fn boot() -> (u16, Receiver) { @@ -575,6 +602,40 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn an_accept_thread_spawn_failure_aborts_start_and_removes_the_key() { + let dir = temp_dir("spawn-failure"); + let path = wordcraft_control_key::key_path(&dir, 0); + let mut bound = None; + let result = start_with(0, egui::Context::default(), Some(&dir), |listener, ctx, key| { + bound = Some(listener.local_addr().unwrap()); + assert_eq!(std::fs::read_to_string(&path).unwrap(), key, "startup wrote the key before spawning"); + serve_with_spawner(listener, ctx, key, small(150, 8), |accept| { + drop(accept); + Err(std::io::Error::other("injected accept thread spawn failure")) + }) + }); + assert!(result.is_none(), "a server without its accept thread must not report success"); + assert!(!path.exists(), "failed startup must remove its published key"); + let _listener = TcpListener::bind(bound.unwrap()).unwrap(); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_complete_json_request_at_eof_can_reach_the_ui() { + // This is why a bridge write failure before the newline is outcome-unknown. + let (port, rx) = boot(); + let mut c = Conn::open(port); + let body = json!({"id": 1, "key": KEY, "method": "engine.execute", "params": {"command": "text.insert", "params": {"text": "once"}}}); + c.1.write_all(body.to_string().as_bytes()).unwrap(); + c.1.shutdown(std::net::Shutdown::Write).unwrap(); + let req = answer(&rx); + assert_eq!(req.params["params"]["text"], "once"); + assert_eq!(c.recv()["ok"], true); + assert!(c.closed()); + assert!(rx.try_recv().is_err()); + } + #[test] fn a_stale_key_file_is_replaced() { let dir = temp_dir("stale"); @@ -599,7 +660,7 @@ mod tests { fn boot_limits(limits: Limits) -> (u16, Receiver) { let listener = TcpListener::bind(("127.0.0.1", 0)).unwrap(); let port = listener.local_addr().unwrap().port(); - (port, serve_with(listener, egui::Context::default(), KEY.to_string(), limits)) + (port, serve_with(listener, egui::Context::default(), KEY.to_string(), limits).unwrap()) } fn small(wait_ms: u64, max_unauthenticated: usize) -> Limits { diff --git a/crates/mcp/src/backend.rs b/crates/mcp/src/backend.rs index 3523d0b68d..6ceadd1a42 100644 --- a/crates/mcp/src/backend.rs +++ b/crates/mcp/src/backend.rs @@ -184,28 +184,29 @@ impl Remote { Ok(req.to_string()) } - /// Send one line and read the reply line. A failure before the whole line (with its newline) - /// reached the socket is [`Failure::NotSent`]: the app cannot have run it. Any failure after - /// that is [`Failure::Unknown`]: the app may have run the request and lost the reply. + /// Send one line and read its reply. Once a write is attempted, any failure leaves the + /// outcome unknown: even a failed write may have delivered a complete request at EOF. fn roundtrip(&mut self, line: &str) -> Result { let Some((reader, writer)) = self.conn.as_mut() else { return Err(Failure::NotSent(std::io::Error::new(std::io::ErrorKind::NotConnected, "not connected"))); }; - let mut out = Vec::with_capacity(line.len() + 1); - out.extend_from_slice(line.as_bytes()); - out.push(b'\n'); - writer.write_all(&out).and_then(|()| writer.flush()).map_err(Failure::NotSent)?; - match read_bounded_line(reader, MAX_REPLY_LINE).map_err(Failure::Unknown)? { - BoundedLine::Line(reply) => Ok(reply), - BoundedLine::Eof => Err(Failure::Unknown(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "control channel closed"))), - BoundedLine::TooLong => Err(Failure::Unknown(std::io::Error::new(std::io::ErrorKind::InvalidData, "reply from app too long"))), - } + roundtrip_io(reader, writer, line) } /// One request and its reply. A request that was not sent, or one that only reads, is tried /// once more on a new connection (the app may have restarted; a new connection also reads /// the key again). A mutation whose outcome is unknown is never sent again: it may have run. fn exchange(&mut self, id: u64, method: &str, params: &Value) -> Result { + self.exchange_with(id, method, params, Self::roundtrip) + } + + fn exchange_with( + &mut self, + id: u64, + method: &str, + params: &Value, + mut roundtrip: impl FnMut(&mut Self, &str) -> Result, + ) -> Result { let unreachable = |addr: &str, e: std::io::Error, connected: bool| { let retry = if connected { String::new() } else { "; will retry on each call".to_string() }; format!("WordCraft app at {addr} is not reachable: {e}{retry}") @@ -216,7 +217,7 @@ impl Remote { let result = match tried { Ok(()) => { let line = self.request_line(id, method, params)?; - self.roundtrip(&line) + roundtrip(self, &line) } Err(e) => Err(e), }; @@ -232,10 +233,10 @@ impl Remote { return Err(format!("bad reply from app: {e}")); } if let Failure::Unknown(e) = &f - && !is_read_only(method) + && !is_read_only(method, params) { return Err(format!( - "outcome unknown: the connection to the WordCraft app at {} failed after `{method}` was sent ({e}); it may have been executed, so it is not sent again. Inspect the document to check", + "outcome unknown: the connection to the WordCraft app at {} failed while sending `{method}` or waiting for its reply ({e}); it may have been executed, so it is not sent again. Inspect the document to check", self.addr )); } @@ -250,9 +251,22 @@ impl Remote { } } +/// Shared socket exchange, also used with a writer that fails after partial delivery in tests. +fn roundtrip_io(reader: &mut impl std::io::BufRead, writer: &mut impl Write, line: &str) -> Result { + let mut out = Vec::with_capacity(line.len() + 1); + out.extend_from_slice(line.as_bytes()); + out.push(b'\n'); + writer.write_all(&out).and_then(|()| writer.flush()).map_err(Failure::Unknown)?; + match read_bounded_line(reader, MAX_REPLY_LINE).map_err(Failure::Unknown)? { + BoundedLine::Line(reply) => Ok(reply), + BoundedLine::Eof => Err(Failure::Unknown(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "control channel closed"))), + BoundedLine::TooLong => Err(Failure::Unknown(std::io::Error::new(std::io::ErrorKind::InvalidData, "reply from app too long"))), + } +} + /// Why a round trip failed. enum Failure { - /// Before the whole request reached the socket: the app did not run it. + /// No write was attempted: the app did not run it. NotSent(std::io::Error), /// After the request was sent: the app may have run it. Unknown(std::io::Error), @@ -267,8 +281,12 @@ impl Failure { } /// Methods that only read: sending them twice does no harm. -fn is_read_only(method: &str) -> bool { - matches!(method, "document.inspect" | "engine.commands" | "ui.inspect" | "ui.parity" | "ui.render" | "ui.screenshot") +fn is_read_only(method: &str, params: &Value) -> bool { + match method { + "document.inspect" | "engine.commands" | "ui.inspect" | "ui.parity" => true, + "ui.render" | "ui.screenshot" => params.get("path").and_then(Value::as_str).is_none(), + _ => false, + } } impl Backend for Remote { @@ -557,6 +575,71 @@ mod tests { assert_eq!(seen.try_iter().count(), 2); } + #[test] + fn a_failed_write_after_delivering_json_never_replays_a_mutation() { + // Deliver a complete request, then fail either its newline write or its flush. The + // stand-in, like the production server, accepts a complete JSON body at EOF. + struct FailingWriter<'a> { + socket: &'a mut TcpStream, + fail_flush: bool, + wrote: bool, + } + impl Write for FailingWriter<'_> { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + if self.wrote { + return Err(std::io::ErrorKind::BrokenPipe.into()); + } + self.wrote = true; + let len = buf.len() - usize::from(!self.fail_flush); + self.socket.write_all(&buf[..len])?; + self.socket.shutdown(std::net::Shutdown::Write)?; + Ok(len) + } + fn flush(&mut self) -> std::io::Result<()> { + Err(std::io::ErrorKind::BrokenPipe.into()) + } + } + for fail_flush in [false, true] { + let (port, seen) = fake_app(|_| None); + let mut r = Remote::connect_with(&format!("127.0.0.1:{port}"), fixed_key("k")).unwrap(); + let mut attempts = 0; + let e = r + .exchange_with(1, "engine.execute", &json!({"command": "text.insert", "params": {"text": "once"}}), |r, line| { + attempts += 1; + let (reader, socket) = r.conn.as_mut().unwrap(); + roundtrip_io(reader, &mut FailingWriter { socket, fail_flush, wrote: false }, line) + }) + .unwrap_err(); + assert!(e.contains("outcome unknown"), "{e}"); + assert_eq!(attempts, 1, "a failed write must not trigger another exchange"); + assert_eq!(seen.recv_timeout(WAIT).unwrap()["params"]["params"]["text"], "once"); + assert!(seen.try_recv().is_err()); + } + } + + #[test] + fn image_exports_with_a_lost_reply_are_not_replayed_but_in_memory_reads_are() { + for method in ["ui.render", "ui.screenshot"] { + for path in [json!("out.png"), json!(""), Value::Null] { + let count = Arc::new(AtomicUsize::new(0)); + let n = count.clone(); + let (port, seen) = + fake_app(move |_| if n.fetch_add(1, Ordering::SeqCst) == 0 { None } else { Some((json!({"ok": true, "result": 3}), false)) }); + let mut r = Remote::connect_with(&format!("127.0.0.1:{port}"), fixed_key("k")).unwrap(); + let result = r.call(method, json!({"path": path})); + if path.is_string() { + assert!(result.unwrap_err().contains("outcome unknown")); + assert_eq!(count.load(Ordering::SeqCst), 1); + } else { + assert_eq!(result.unwrap(), json!(3)); + assert_eq!(count.load(Ordering::SeqCst), 2); + } + assert_eq!(seen.try_iter().count(), if path.is_string() { 1 } else { 2 }); + } + assert!(is_read_only(method, &json!({})), "no path means PNG in the reply"); + } + } + #[test] fn a_mutation_not_sent_goes_out_on_a_new_connection() { let (port, seen) = fake_app(|_| Some((json!({"ok": true, "result": 1}), false))); diff --git a/crates/mcp/src/server.rs b/crates/mcp/src/server.rs index b3eaf5b49a..bd9616222d 100644 --- a/crates/mcp/src/server.rs +++ b/crates/mcp/src/server.rs @@ -106,10 +106,14 @@ impl Server { /// the protocol stream). pub fn serve(&mut self, mut input: impl BufRead, mut output: impl Write) -> std::io::Result<()> { loop { - let reply = match read_bounded_line(&mut input, MAX_REQUEST_LINE)? { - BoundedLine::Eof => break, - BoundedLine::Line(line) => self.handle_line(&line), - BoundedLine::TooLong => Some(error(Value::Null, INVALID_REQUEST, "request line too long").to_string()), + let reply = match read_bounded_line(&mut input, MAX_REQUEST_LINE) { + Ok(BoundedLine::Eof) => break, + Ok(BoundedLine::Line(line)) => self.handle_line(&line), + Ok(BoundedLine::TooLong) => Some(error(Value::Null, INVALID_REQUEST, "request line too long").to_string()), + Err(e) if e.kind() == std::io::ErrorKind::InvalidData => { + Some(error(Value::Null, PARSE_ERROR, "request line is not UTF-8").to_string()) + } + Err(e) => return Err(e), }; if let Some(reply) = reply { output.write_all(reply.as_bytes())?; diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index ea7f9d5ec0..c61ec42f7d 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -367,3 +367,24 @@ fn render_page_rejects_a_page_number_that_does_not_fit() { let r = call(&mut s, 31, "tools/call", json!({"name": "render_page", "arguments": {"page": 1, "scale": 0.5}})); assert_eq!(r["result"]["isError"], false, "page 1 still renders: {r}"); } + +#[test] +fn invalid_utf8_does_not_change_arguments_or_stop_later_requests() { + let mut s = Server::new(Box::new(Headless::default())); + tool(&mut s, "new_document", json!({})); + let mut input = br#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"type_text","arguments":{"text":"bad"}}}"#.to_vec(); + let pos = input.windows(3).position(|w| w == b"bad").unwrap(); + input[pos] = 0xff; + input.push(b'\n'); + input.extend_from_slice( + b"{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"type_text\",\"arguments\":{\"text\":\"good\"}}}\n", + ); + let mut out = Vec::new(); + s.serve(std::io::Cursor::new(input), &mut out).unwrap(); + let replies: Vec = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + assert_eq!(replies.len(), 2); + assert_eq!(replies[0]["error"]["code"], -32700); + assert_eq!(replies[1]["id"], 2); + assert_eq!(replies[1]["result"]["isError"], false); + assert_eq!(tool(&mut s, "get_text", json!({}))["text"], "good", "malformed text must never reach the backend"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 25412d3882..64afe2f858 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -1,5 +1,7 @@ # Control protocol +> **Last updated:** 2026-10-31 · #2596: accept-thread startup failure disables the server and removes its key file; MCP retry policy distinguishes file exports from in-memory images. + Start the app with a control port: `wordcraft --control 7981` (or `WORDCRAFT_CONTROL_PORT=7981`). A missing or invalid port after `--control` (not 1–65535) prints an error and exits with status 2. It listens on `127.0.0.1` only. Send one JSON object per line, with the window's key (see @@ -50,6 +52,21 @@ any other host it sends no key, says so, and the app refuses its requests: to dr another machine, forward its port to `127.0.0.1` (for example `ssh -L 7981:127.0.0.1:7981 host`) and set `WORDCRAFT_CONTROL_KEY` to that app's key. +## Delivery and startup failures + +If the accept thread cannot start, startup reports that the control server is off and removes +its newly written key file; it does not report a listening server. Failure to start a worker +for one connection closes only that connection and releases its admission slot. + +The server can accept a complete JSON body at EOF even without a final newline. A client that +encounters a write error must therefore treat delivery as unknown once it has attempted to +send. The MCP bridge does not replay mutations in this case, or image exports with a string +`path`; see [delivery failures](mcp.md#delivery-failures). + +A request that times out while still queued is cancelled and cannot run later. If execution +has already started, the timeout reports an unknown outcome rather than promising cancellation. +Unauthenticated connections are limited to 64 while they wait for their first authorised request. + ## Methods | Method | Params | Result | diff --git a/docs/mcp.md b/docs/mcp.md index 09ab419c16..09583feaac 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1,5 +1,7 @@ # MCP server +> **Last updated:** 2026-10-31 · Delivery review fixes for #2596: unknown outcomes are not replayed, including image exports to a path; invalid UTF-8 returns a parse error without stopping later requests. + WordCraft speaks the [Model Context Protocol](https://modelcontextprotocol.io) over stdio, so Claude and other agents can write and edit documents. @@ -18,6 +20,22 @@ isn't open yet: tool calls return "not reachable … will retry on each call" an app's port opens (#4078), so a client that starts before WordCraft doesn't lose the server for its whole session. +## Delivery failures + +The connected bridge retries a request once if no write was attempted (for example, a failed +connection). Once sending starts, a write or flush failure can mean the app already received +the complete JSON body, even if its newline was not delivered. A lost reply has the same +uncertainty. Mutations then return an `outcome unknown` error and are never automatically +resent; inspect the document before deciding whether to repeat the operation yourself. + +Read-only inspection and in-memory `ui.render` / `ui.screenshot` calls may retry once. With a +string `path`, rendering or taking a screenshot writes a file and is not retried after an +unknown outcome. Unreadable replies are reported as errors without replaying the request. + +On stdio, an invalid UTF-8 request line returns JSON-RPC parse error `-32700`. It never reaches +the backend, and the server continues with the next line instead of substituting characters +in text or paths. + ## Scripts from the command line `wordcraft-cli run --script job.json` (`--script -` reads standard input) runs the commands in a From d94bbc8fe088e7b615d55bdc6a427a0a8b2f2296 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 16:16:20 +0100 Subject: [PATCH 5/5] Layout tests: install the pinned fonts in the layout entry points and font helpers layout, layout_para, layout_equation and mark_text_width call test_fonts() first in test builds, so the shared lay helper and everything that goes through them is covered. Tests and helpers that look up fonts directly (the Times New Roman substitute test, the Symbol bullet test, the Arabic/Myanmar/Thai face probes and the nbsp fixture) call it themselves. Audited by running every layout test in its own process with a temporary guard that panicked on any global font access before the pinned fonts were installed. Co-Authored-By: Claude Sonnet 5.5 --- crates/layout/src/display/lines.rs | 2 ++ crates/layout/src/lib.rs | 11 +++++++++-- crates/layout/src/math.rs | 2 ++ crates/layout/src/para/paragraph.rs | 2 ++ crates/layout/src/tests.rs | 2 ++ crates/layout/src/tests/bidi.rs | 1 + crates/layout/src/tests/complex.rs | 3 +++ crates/layout/src/tests/nbsp.rs | 2 ++ 8 files changed, 23 insertions(+), 2 deletions(-) diff --git a/crates/layout/src/display/lines.rs b/crates/layout/src/display/lines.rs index 0d253f9205..6b1fbd6098 100644 --- a/crates/layout/src/display/lines.rs +++ b/crates/layout/src/display/lines.rs @@ -638,6 +638,8 @@ pub fn section_break_label(start: SectionStart) -> &'static str { /// Width of a [`Draw::MarkText`] label. pub fn mark_text_width(text: &str, size: f32) -> f32 { + #[cfg(test)] + crate::test_fonts(); let face = wordcraft_fonts::word::resolve("Source Sans 3", false, false).face; let k = size / face.upem.max(1.0) as f32; text.chars().map(|c| face.advance(face.glyph_for(c)) as f32 * k).sum() diff --git a/crates/layout/src/lib.rs b/crates/layout/src/lib.rs index 6acab3d28c..504c178fa9 100644 --- a/crates/layout/src/lib.rs +++ b/crates/layout/src/lib.rs @@ -8,8 +8,13 @@ //! - [`hit`]: point ↔ position, caret geometry, line navigation, selection rectangles. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -/// Every unit test calls this before any font lookup (including its fixture construction). -/// A process-wide immutable choice keeps font and math caches consistent across test threads. +/// Installs the pinned test fonts as the process-wide font database. The layout entry points +/// (`layout`, `layout_para`, `layout_equation`, `display::mark_text_width`) call it first in test +/// builds, so the shared `lay` helper and every test that goes through them are covered; a test +/// that looks up fonts itself before any such call (fixtures, `word::resolve`, `FontDb::global`) +/// calls it at its start. It is idempotent and never calls back into layout, so it cannot recurse. +/// The choice is process-wide and immutable, which keeps font and math caches consistent across +/// test threads. #[cfg(test)] fn test_fonts() { assert!(wordcraft_fonts::FontDb::init_test_fonts(), "layout tests must initialize fixed fonts before any global font lookup"); @@ -314,6 +319,8 @@ pub struct DocLayout { /// Lay out the whole document. pub fn layout(doc: &Document, cache: &mut LayoutCache, opts: &LayoutOptions) -> DocLayout { + #[cfg(test)] + crate::test_fonts(); let t0 = now_ms(); // Page totals shown in the body (`NUMPAGES`, `SECTIONPAGES`) are known only after // paginating: lay out again with the totals found until they hold (bounded). Footnotes diff --git a/crates/layout/src/math.rs b/crates/layout/src/math.rs index 95070ecd2f..b5ba3d8897 100644 --- a/crates/layout/src/math.rs +++ b/crates/layout/src/math.rs @@ -207,6 +207,8 @@ pub fn layout_equation( props: &MathProps, counter: &mut u32, ) -> MathLayout { + #[cfg(test)] + crate::test_fonts(); let parsed; let nodes: &Arg = if math.nodes.is_empty() && !math.linear { parsed = parse_linear(linear); diff --git a/crates/layout/src/para/paragraph.rs b/crates/layout/src/para/paragraph.rs index 2c0c4e8c1e..1cd053e134 100644 --- a/crates/layout/src/para/paragraph.rs +++ b/crates/layout/src/para/paragraph.rs @@ -10,6 +10,8 @@ use super::*; /// Lay out one paragraph. pub fn layout_para(p: &Paragraph, env: &ParaEnv) -> ParaLayout { + #[cfg(test)] + crate::test_fonts(); let doc = env.doc; let mut rp = doc.styles.resolve_para_in(&p.props, env.table.map(|t| &t.para)); if let Some(spacing) = env.read_line_spacing.filter(|s| s.is_finite() && (1.0..=2.0).contains(s)) { diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index 7275046772..2e22d43630 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -1345,6 +1345,7 @@ fn a_missing_roman_font_is_drawn_as_word_draws_it() { #[test] fn a_missing_roman_font_with_its_own_substitute_keeps_it() { + crate::test_fonts(); // Times New Roman is roman in every font table. Where it isn't installed it keeps its metric // clone (Liberation Serif), not Cambria: Word, which always has it, never draws it missing. let mut d = Document::from_text("Serif"); @@ -1970,6 +1971,7 @@ fn bullet_first_line(label_font: Option<&str>) -> (f32, f32, f32, f32) { #[test] fn a_symbol_bullet_sizes_its_line_by_the_symbol_font() { + crate::test_fonts(); // Measured in Word: a Symbol bullet makes its line taller than the text alone (Calibri 11 pt // at 1.08 spacing: 15.1 pt, not 14.5 pt), the extra ascent added unscaled. Symbol isn't an open // font; without it the bullet is drawn from another face but its line keeps Symbol's height. diff --git a/crates/layout/src/tests/bidi.rs b/crates/layout/src/tests/bidi.rs index 002d0ad89f..5eae020ec5 100644 --- a/crates/layout/src/tests/bidi.rs +++ b/crates/layout/src/tests/bidi.rs @@ -314,6 +314,7 @@ fn hostile_bidi_text_never_panics() { /// A face that has Arabic letters (installed system fonts), or `None` to skip. fn arabic_face() -> Option { + crate::test_fonts(); wordcraft_fonts::FontDb::global().fallback_for('ب', 0).map(|f| wordcraft_fonts::FaceRef::of(&f)).filter(|f| f.covers('پ')) } diff --git a/crates/layout/src/tests/complex.rs b/crates/layout/src/tests/complex.rs index 01551b1a31..206f48875a 100644 --- a/crates/layout/src/tests/complex.rs +++ b/crates/layout/src/tests/complex.rs @@ -68,6 +68,7 @@ fn myanmar_without_spaces_wraps_between_syllables() { /// A face with Myanmar letters (an installed system font), or `None` to skip. fn myanmar_face() -> Option { + crate::test_fonts(); wordcraft_fonts::FontDb::global().fallback_for('\u{1000}', 0).map(|f| wordcraft_fonts::FaceRef::of(&f)).filter(|f| f.has_layout_tables()) } @@ -119,12 +120,14 @@ const THAI_RUN: &str = "[D] น้ำ ค่ำ ปั้น ฝั่ง ปู /// Is a font with Thai letters installed? `false` skips the test. fn thai_font_installed() -> bool { + crate::test_fonts(); wordcraft_fonts::FontDb::global().fallback_for('\u{0E19}', 0).is_some() } /// Is a Thai font with Latin letters and digits installed (Tahoma, Leelawadee UI, Thonburi, the /// TLWG fonts…)? Noto Sans Thai alone has none, so no face covers [`THAI_RUN`]: `false` skips. fn thai_latin_font_installed() -> bool { + crate::test_fonts(); let face = wordcraft_fonts::word::resolve("TH Sarabun New", false, false).face; THAI_RUN.chars().filter(|c| !c.is_whitespace()).all(|c| face.covers(c)) } diff --git a/crates/layout/src/tests/nbsp.rs b/crates/layout/src/tests/nbsp.rs index 36b9ccb9b1..64144585bd 100644 --- a/crates/layout/src/tests/nbsp.rs +++ b/crates/layout/src/tests/nbsp.rs @@ -6,6 +6,7 @@ use crate::{Document, LayoutCache, LayoutOptions, Placed, layout}; /// Inter with its U+00A0 glyph twice as wide as its space, under the family name "Wnbsp". /// Built from the bundled font so the test needs no installed font. fn wide_nbsp_family() -> &'static str { + crate::test_fonts(); const FAMILY: &str = "Wnbsp"; let inter = wordcraft_fonts::word::resolve("Inter", false, false).face; let mut data = inter.data().to_vec(); @@ -54,6 +55,7 @@ fn line_width(text: &str) -> f32 { #[test] fn a_no_break_space_is_as_wide_as_a_space() { + crate::test_fonts(); let face = wordcraft_fonts::word::resolve(wide_nbsp_family(), false, false).face; assert_eq!(face.family, wide_nbsp_family(), "the test font is installed under its own name"); assert!(