From 0e7dc8da5312f1247dfd82e15ba6284097aef09b Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 31 Oct 2026 22:12:18 +0100 Subject: [PATCH] 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