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 <noreply@openai.com>
This commit is contained in:
vangel76andCodex committed 2026-10-31 22:12:18 +01:00
1 parent 837d2b0748
commit 0e7dc8da53
7 files changed
+238 -32

No files matched your search

+3 -1
View File
@@ -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, #2Line truncated
> **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; previousLine truncated
> **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) |
+70 -9
View File
@@ -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<ControlRequest>, Option<KeyFile>)> {
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<Receiver<ControlRequest>>,
) -> Option<(Receiver<ControlRequest>, Option<KeyFile>)> {
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<ControlRequest> {
fn serve_on(listener: TcpListener, ctx: egui::Context, key: String, first: Duration) -> std::io::Result<Receiver<ControlRequest>> {
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<ControlRequest> {
fn serve_with(listener: TcpListener, ctx: egui::Context, key: String, limits: Limits) -> std::io::Result<Receiver<ControlRequest>> {
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<dyn FnOnce() + Send>) -> std::io::Result<()>,
) -> std::io::Result<Receiver<ControlRequest>> {
let (tx, rx) = channel::<ControlRequest>();
let key: Arc<str> = 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<ControlRequest>) {
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<ControlRequest>) {
@@ -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<ControlRequest>) {
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 {
+101 -18
View File
@@ -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<String, Failure> {
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<Value, String> {
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<String, Failure>,
) -> Result<Value, String> {
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<String, Failure> {
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<usize> {
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)));
+8 -4
View File
@@ -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())?;
+21
View File
@@ -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<Value> = 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");
}
+17
View File
@@ -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 |
+18
View File
@@ -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