From 73f133192b3911253ea97b75dbd29736cec6edb5 Mon Sep 17 00:00:00 2001 From: Codex Date: Wed, 25 Nov 2026 10:15:07 +0000 Subject: [PATCH 01/11] =?UTF-8?q?feat(crates/panache-mcp):=20=E4=BB=8E?= =?UTF-8?q?=E9=A6=96=E6=AC=A1=E9=80=89=E6=A0=B7=E5=BC=95=E5=AF=BC=E5=88=B0?= =?UTF-8?q?=E5=8F=96=E5=9B=9E=E9=80=89=E4=B8=AD=E7=89=88=E6=9C=AC=E7=9A=84?= =?UTF-8?q?=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景: 新手往往只说想做手写作业;生成后的服务器路径也可能无法在聊天里打开。 解决手段: 按已有材料说明打印页、原纸填字和透明字迹,沿用用户选中的版号。 客户端可按需取回小型 PDF 或 ZIP 的完整内容,再通过自己的界面提供附件。 随代码记录真实 stdio 基线、改动过程和独立的文件与像素对照。 收益: 三个合成任务保留原有输出,在只读取工具回复的测试客户端均能取回文件。 超限仍保留本机成品,明确意图可以直接继续,用户无需先了解技术名词。 --- CHANGELOG.md | 2 + README.md | 2 +- README.zh-CN.md | 2 +- crates/panache-mcp/README.md | 8 +- crates/panache-mcp/src/delivery.rs | 95 +++++++++ crates/panache-mcp/src/inputs.rs | 4 + crates/panache-mcp/src/main.rs | 18 +- crates/panache-mcp/src/storage.rs | 8 +- crates/panache-mcp/src/storage/tests.rs | 2 +- crates/panache-mcp/tests/compare_first_use.py | 54 +++++ crates/panache-mcp/tests/first-use-notes.md | 58 +++++ crates/panache-mcp/tests/first_use.py | 199 ++++++++++++++++++ 12 files changed, 438 insertions(+), 14 deletions(-) create mode 100644 crates/panache-mcp/src/delivery.rs create mode 100644 crates/panache-mcp/tests/compare_first_use.py create mode 100644 crates/panache-mcp/tests/first-use-notes.md create mode 100644 crates/panache-mcp/tests/first_use.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 04712c70..3587352f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## 未发布 +- MCP 首次使用时会按材料介绍打印页、原纸填字和透明字迹。客户端可在导出时取回 512 KiB 以内的 PDF 或 ZIP,用作聊天附件。 + - 上传底纸后,纸张设置会直接显示从照片读到的制造商、设备型号、镜头和 ISO,缺少的项目仍可手动补填。 - MCP 新检查单记录首次入档时的稿件版本,历史查单会说明单据能证明的先后关系。 diff --git a/README.md b/README.md index 9393d0a0..37315d5e 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ The Windows, macOS, and Linux desktop packages include a local MCP server. Open > Write my notes and the process diagram on this photo of my stationery. Show me the first page, then export the whole draft as a PDF. -For the photo, give the client a file path accessible on the computer running Panache. A client that passes images to its model can inspect the finished page and review a selected area. In a text-only client, ask for the measurements and open the exported PDF locally to judge the appearance. [MCP tools and configuration](crates/panache-mcp/README.md) +You can also start with just text. Paste a passage and say whether you want a printable page, writing on a photo of your worksheet, or transparent ink to paste elsewhere. For a photo, the client needs a way to make it available on the computer running Panache. [MCP tools and configuration](crates/panache-mcp/README.md) | Process state diagram | Resource allocation table | | --- | --- | diff --git a/README.zh-CN.md b/README.zh-CN.md index 9d35d1ab..d8b753aa 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -28,7 +28,7 @@ Windows、macOS 和 Linux 桌面版随附本地 MCP 服务。在 **应用设置 > 用这张斜拍的信纸排我的笔记,画出进程状态转换图。先给我看第一页,确认后把整份导出成 PDF。 -请提供运行 Panache 的电脑能读取的照片路径。能向模型传递图片的客户端可以检查成品、放大复盘选区。在纯文字客户端中,可让 AI 说明测量结果,再打开导出的本地 PDF 看实际效果。[MCP 工具与配置说明](crates/panache-mcp/README.md) +只有文字时也能开始。把一段作业贴给客户端,告诉它想打印成纸页、填在自己的纸张照片上,还是只要能贴到别处的透明字迹。用照片时,客户端需要能把照片交给运行 Panache 的电脑。[MCP 工具与配置说明](crates/panache-mcp/README.md) | 进程状态转换图 | 资源分配表 | | --- | --- | diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index cc535261..fd8251ed 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -44,11 +44,15 @@ cargo build --locked --release -p panache-mcp ## 写稿、预览和复查 -第一次可以直接说:「把‘西湖春早,柳色正新。’排成一页手写稿,用默认纸张,先让我看一眼。」客户端会用 `save_section` 建稿,再把返回的 `draft_id` 和 `revision` 交给 `preview_handwriting`。满意后可以说「把刚才那一版导出成 PDF」。导出工具返回本机文件路径。 +只有一句「帮我做一份手写作业」时,先贴要写的内容。想打印,就用普通纸样做 PDF;想填在老师发的练习纸上,就用那张纸的照片;想把字放进海报,就用透明字迹,解开 ZIP 后取出 PNG。已经说清「用这段话做打印版」就可以直接开始。 + +可以先说「用这段话给我看第一页」,看过后说「字大一点」,再说「就用这一版」。客户端按同一稿件的版本号取预览和导出。查看小样使用 `preview_handwriting(view="image")`,无需创建检查单。 + +想在聊天里拿到文件时,能处理 MCP 内嵌文件的客户端可在导出时传 `include_file=true`,把收到的 PDF 或 ZIP 作为附件显示给用户。512 KiB 以内的完整文件可以随回复传送。更大的文件仍在运行 Panache 的电脑上;两端共用磁盘时可直接打开返回的路径。只有客户端已经提供可打开的附件或链接时,才告诉用户「附件在这里」。 使用自己的纸张时,在第一次调用 `save_section` 时传入 `paper_path`,例如 `{"markdown":"第一题","paper_path":"C:/作业/南昌大学横线纸.jpg"}`。路径指向运行 MCP 的电脑上的图片。默认保留原照片,按识别到的横线投影字迹和插图。`paper` 返回排版尺寸、边距、行距、识线结果,投影时另有原照尺寸。可用 `preview_handwriting(view="paper")` 单独看底纸,或在导入时通过 `paper_guides` 指定参考线。需要校平底纸时传 `paper_mode="flatten"`。无可靠横线时保留底图,使用普通行距。纸张随稿件保存一次,后续追加、回查、预览和导出可在原图移动后继续使用。 -如果照片是聊天附件,请先确认客户端能提供 MCP 进程可读的本机文件路径,必要时先把图片存到这台电脑。带视觉能力的模型可以查看客户端转交的预览图。客户端或模型只能处理文字时,可读取版面和像素测量,并请用户打开导出文件确认外观,再按反馈修改。 +如果照片是聊天附件,先用客户端支持的文件传送功能,把照片交给 Panache。云端没有这项功能时,可在照片所在电脑连接桌面版再使用。复制手机或另一台电脑上的路径不能传照片。带视觉能力的模型可以查看客户端转交的预览图。客户端或模型只能处理文字时,可读取版面和像素测量,并请用户打开导出文件确认外观,再按反馈修改。 | 工具 | 用法 | | --- | --- | diff --git a/crates/panache-mcp/src/delivery.rs b/crates/panache-mcp/src/delivery.rs new file mode 100644 index 00000000..8ebb01a9 --- /dev/null +++ b/crates/panache-mcp/src/delivery.rs @@ -0,0 +1,95 @@ +use crate::inputs::Format; +use base64::{Engine as _, engine::general_purpose::STANDARD}; +use rmcp::model::{CallToolResult, ContentBlock, ResourceContents}; +use serde_json::json; +use std::{ + fs::File, + io::{self, Read, Seek}, + path::Path, +}; + +// Applied to the file before base64 expands it by about a third. +const MAX_FILE_BYTES: u64 = 512 * 1024; + +fn file_bytes(mut file: File) -> io::Result>> { + if file.metadata()?.len() > MAX_FILE_BYTES { + return Ok(None); + } + file.rewind()?; + let mut bytes = Vec::new(); + file.take(MAX_FILE_BYTES + 1).read_to_end(&mut bytes)?; + Ok((bytes.len() as u64 <= MAX_FILE_BYTES).then_some(bytes)) +} + +pub(super) fn include_file(result: &mut CallToolResult, file: File, path: &Path, format: Format) { + // Keep the published handle. Reopening a pathname could read a replacement file. + let (status, message) = match file_bytes(file) { + Ok(Some(bytes)) => { + let mime = match format { + Format::Pdf => "application/pdf", + Format::Zip => "application/zip", + }; + let name = path.file_name().unwrap_or_default().to_string_lossy(); + let resource = + ResourceContents::blob(STANDARD.encode(bytes), format!("panache-export:///{name}")) + .with_mime_type(mime); + result.content.push(ContentBlock::resource(resource)); + ( + "included", + "文件内容已传给客户端。请由客户端提供可打开的附件。", + ) + } + Ok(None) => ( + "too_large", + "文件已生成,超过随回复传送的 512 KiB。请从运行 Panache 的电脑取回。", + ), + Err(_) => ( + "unavailable", + "文件已生成,但本次回复未能读取文件内容。请从运行 Panache 的电脑取回。", + ), + }; + result.content.push(ContentBlock::text(message)); + if let Some(metadata) = &mut result.structured_content { + metadata["file_transfer"] = json!({"status": status, "max_bytes": MAX_FILE_BYTES}); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn unreadable_bytes_preserve_export_receipt() -> io::Result<()> { + let dir = tempfile::tempdir()?; + let path = dir.path().join("sample.pdf"); + let write_only = File::create(&path)?; + let mut result = crate::reply("exported".into(), json!({"pages": 1})); + include_file(&mut result, write_only, &path, Format::Pdf); + assert_eq!( + result.structured_content.as_ref().unwrap()["file_transfer"]["status"], + "unavailable" + ); + assert_eq!(result.structured_content.as_ref().unwrap()["pages"], 1); + assert!( + result + .content + .iter() + .all(|block| matches!(block, ContentBlock::Text(_))) + ); + assert!(path.is_file()); + Ok(()) + } + + #[test] + fn attachment_size_boundary() -> io::Result<()> { + for size in [MAX_FILE_BYTES, MAX_FILE_BYTES + 1] { + let file = tempfile::tempfile()?; + file.set_len(size)?; + assert_eq!( + file_bytes(file)?.map(|b| b.len() as u64), + (size == MAX_FILE_BYTES).then_some(size) + ); + } + Ok(()) + } +} diff --git a/crates/panache-mcp/src/inputs.rs b/crates/panache-mcp/src/inputs.rs index c9f06aef..fae0638a 100644 --- a/crates/panache-mcp/src/inputs.rs +++ b/crates/panache-mcp/src/inputs.rs @@ -271,6 +271,10 @@ pub struct Export { pub revision: Option, /// PDF includes the paper. ZIP contains page PNGs and respects the transparent_background ink control. pub format: Option, + /// Include the exported bytes as an embedded MCP resource for clients that can offer attachments. + /// Up to 512 KiB before base64 encoding. Larger files stay available at the returned server path. + #[serde(default)] + pub include_file: bool, } #[derive(Clone, Copy, Deserialize, JsonSchema, PartialEq, serde::Serialize)] diff --git a/crates/panache-mcp/src/main.rs b/crates/panache-mcp/src/main.rs index 1cb85ca4..4b481891 100644 --- a/crates/panache-mcp/src/main.rs +++ b/crates/panache-mcp/src/main.rs @@ -1,4 +1,5 @@ mod controls; +mod delivery; mod drafts; mod engine; mod inputs; @@ -253,6 +254,9 @@ impl ServerHandler for Panache { fn get_info(&self) -> rmcp::model::ServerConfig { use rmcp::model::{Implementation, ServerCapabilities, ServerConfig}; let instructions = concat!( + "When someone only asks for handwriting help, use the text or photo already supplied. If the outcome is unclear, offer only relevant examples: a printable page, writing on their own sheet, or just the ink to paste elsewhere. Ask one short question, inviting them to paste missing text in the same turn. Skip this choice for a clear request. ", + "Ask for missing text or an accessible photo only when needed. For a photo attachment use a client transfer to the server, or suggest running Panache on the computer with the photo. ", + "For an undecided layout show one page with view=image. Invite a concrete change such as larger writing or lighter ink. After feedback show the revised page and export the version the user chose. ", "If a required area of a photo is outside the frame, or blur, occlusion or perspective prevents locating it, identify that area before drafting. ", "Ask for a photo clearly showing it or permission to fill only visible areas; wait before saving or trial placement. If partial work was requested, proceed there. ", "For looser, less uniform homework or lab handwriting (字稍微草一点), inspect describe_controls(group=variation). For requested crossed-out mistakes (涂改痕迹), inspect group=strike. ", @@ -572,7 +576,7 @@ impl Panache { } #[tool( - description = "Export the complete saved revision, in section order, to a local PDF (default) or ZIP of page PNGs. Returns the path, page count and review.unreviewed_pages in print order. For a print-and-report request return the file and missing pages. Only if a new check is requested, use preview_handwriting(view=review) at the exported revision. For ink-only PNG pages, set transparent_background=true with tune_handwriting (ink group) and export ZIP. PDF always includes paper. Text-only clients can give the user the PDF path for visual inspection. Use view=image to inspect the intended appearance without filing a check." + description = "Export the complete saved revision, in section order, to a local PDF (default) or ZIP of page PNGs. Returns the path, page count and review.unreviewed_pages in print order. For a print-and-report request return the file and missing pages. Only if a new check is requested, use preview_handwriting(view=review) at the exported revision. For ink-only PNG pages, set transparent_background=true with tune_handwriting (ink group) and export ZIP. PDF always includes paper. The path is on the server computer. If the client supports attachments, request include_file and use the embedded file to offer the user a download. Claim delivery only when the client makes the file available to the user. Use view=image to inspect the intended appearance without filing a check." )] async fn export_handwriting( &self, @@ -590,7 +594,7 @@ impl Panache { let params = controls::parameters(&draft, 1, &draft.controls)?; let zero_text_ink = params.ink_opacity == 0 || params.fill[3] == 0; let format = input.format.unwrap_or_default(); - let (path, pages) = state.storage.export(&state.drafts,draft.id,draft.revision,format, |writer| engine.export( + let (path, pages, file) = state.storage.export(&state.drafts,draft.id,draft.revision,format, |writer| engine.export( writer, &draft, sections, format, cancel, |pages, section, page| { match reviewed_pages.get(&(section, page)) { @@ -617,8 +621,8 @@ impl Panache { } else { format!(" 缺少整页检查单的节内页码:{}。", serde_json::to_string(&unreviewed)?) }; - let message = format!("已导出 **{pages} 页**(版本 {})。该版已有 {reviewed}/{pages} 页复盘证据。{warning}{remaining}\n\n`{}`", draft.revision, path.display()); - Ok(reply(message, json!({ + let message = format!("已导出 **{pages} 页**(版本 {})。该版已有 {reviewed}/{pages} 页复盘证据。{warning}{remaining}\n\n运行 Panache 的电脑上的文件:`{}`", draft.revision, path.display()); + let mut result = reply(message, json!({ "draft_id": input.draft_id, "revision": draft.revision, "path": path, "pages": pages, "review": { "pages_with_evidence": reviewed, @@ -627,7 +631,11 @@ impl Panache { "pages_without_visibility_evidence": unreviewed.len(), "unreviewed_pages": unreviewed, } - }))) + })); + if input.include_file { + delivery::include_file(&mut result, file, &path, format); + } + Ok(result) }).await; tool_result(result) } diff --git a/crates/panache-mcp/src/storage.rs b/crates/panache-mcp/src/storage.rs index 9cf077d6..1f405d1d 100644 --- a/crates/panache-mcp/src/storage.rs +++ b/crates/panache-mcp/src/storage.rs @@ -201,7 +201,7 @@ impl Storage { revision: u32, format: Format, render: F, - ) -> Result<(PathBuf, usize)> + ) -> Result<(PathBuf, usize, File)> where F: FnOnce(&mut BudgetWriter<'_>) -> Result, { @@ -237,15 +237,15 @@ impl Storage { }; let pages = render(&mut output)?; output.flush()?; - temp.persist_noclobber(&path)?; + let file = temp.persist_noclobber(&path)?; db.execute("UPDATE export_files SET published=1 WHERE id=?", [&id])?; - Ok(pages) + Ok((pages, file)) }; let result = publish(); if result.is_err() && metadata(&path)?.is_none() { db.execute("DELETE FROM export_files WHERE id=? AND published=0", [id])?; } - result.map(|pages| (path, pages)) + result.map(|(pages, file)| (path, pages, file)) } pub fn usage(&self, drafts: &Drafts, input: Usage) -> Result { diff --git a/crates/panache-mcp/src/storage/tests.rs b/crates/panache-mcp/src/storage/tests.rs index 74b17c3d..c2aaf9bd 100644 --- a/crates/panache-mcp/src/storage/tests.rs +++ b/crates/panache-mcp/src/storage/tests.rs @@ -44,7 +44,7 @@ fn plan_reclaims_only_selected_abandoned_writes() -> Result<()> { })?; let old = dir.path().join("exports").join("panache-old.pdf"); fs::write(&old, b"legacy")?; - let (delivered, _) = store.export(&drafts, "draft", 1, Format::Pdf, |writer| { + let (delivered, _, _) = store.export(&drafts, "draft", 1, Format::Pdf, |writer| { writer.write_all(b"delivered")?; Ok(1) })?; diff --git a/crates/panache-mcp/tests/compare_first_use.py b/crates/panache-mcp/tests/compare_first_use.py new file mode 100644 index 00000000..839b6d44 --- /dev/null +++ b/crates/panache-mcp/tests/compare_first_use.py @@ -0,0 +1,54 @@ +"""Audit two first_use.py runs. Only files in the simulated client's inbox count as handed off.""" +import argparse +import hashlib +import json +from pathlib import Path + + +def matches(inbox_file, reference): + return inbox_file.is_file() and hashlib.sha256(inbox_file.read_bytes()).hexdigest() == reference + + +def compare(baseline, candidate): + reports = [json.loads((directory / "report.json").read_text(encoding="utf-8")) + for directory in (baseline, candidate)] + assert [r["mode"] for r in reports] == ["baseline", "candidate"] + old, new = [r["exports"] for r in reports] + assert all(old[key]["sha256"] == new[key]["sha256"] for key in old) + samples = {"print-v2": "pdf", "worksheet-v1": "zip", "ink-v2": "zip"} + delivered = [] + for directory in (baseline, candidate): + inbox = directory / "client-files" + delivered.append(sum(matches(inbox / f"{name}.{ext}", old[name]["sha256"]) + for name, ext in samples.items())) + assert delivered == [0, 3] + assert not matches(candidate / "client-files/print-v2.pdf", old["print-v1-control"]["sha256"]) + assert not matches(candidate / "client-files/worksheet-v1.zip", old["ink-v2"]["sha256"]) + assert new["oversize"]["status"] == "too_large" and not (candidate / "client-files/oversize.zip").exists() + + # Text coverage is a proxy for what a connected client can learn. + # These are excerpts of guidance, not a simulated person's answers. + excerpts = { + "print, own sheet, ink only": ["a printable page", "their own sheet", "ink to paste"], + "combine the first question and missing text": ["one short question", "paste missing text in the same turn"], + "skip a redundant choice": ["Skip this choice for a clear request"], + "feedback in everyday terms": ["larger writing or lighter ink"], + "hand off the selected version": ["export the version the user chose"], + } + coverage = {} + for directory in (baseline, candidate): + instructions = (directory / "initialize.txt").read_text(encoding="utf-8") + coverage[directory.name] = {name: all(part in instructions for part in parts) + for name, parts in excerpts.items()} + assert all(coverage[candidate.name].values()) + print(json.dumps({"matching_client_files": delivered, "required_files": len(samples), + "same_export_bytes": len(old), "instruction_excerpts": coverage}, + ensure_ascii=False, indent=2)) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("baseline", type=Path) + parser.add_argument("candidate", type=Path) + args = parser.parse_args() + compare(args.baseline, args.candidate) diff --git a/crates/panache-mcp/tests/first-use-notes.md b/crates/panache-mcp/tests/first-use-notes.md new file mode 100644 index 00000000..dce6b13b --- /dev/null +++ b/crates/panache-mcp/tests/first-use-notes.md @@ -0,0 +1,58 @@ +# 从「帮我做一份手写作业」到拿到文件 + +这次沿着学生可能经历的顺序检查 Panache。问题有两个:第一次用的人能不能知道该给什么材料?导出成功以后,聊天客户端能不能真的拿到选中的那一版? + +## 先试已有功能 + +在 main 的 `f8d703cbecdae8ae3eb44f8c9bc66a2a6254178b` 上,用 Python MCP SDK 通过标准输入输出启动服务,读首次握手的说明,查工具,再实际写稿。桌面版早已有「应用设置 → 连接 AI 客户端」入口;这一步要在服务能说话之前完成。原来的握手能指导看图、用照片、调整笔迹和导出。我们用同一段合成文字实际生成了打印 PDF、原纸成品和透明字迹,三个都能打开。 + +卡住的是文件怎么从运行 Panache 的电脑到聊天里。原工具报告文件路径、版号和页数,客户端在同一台电脑上可以使用。我们让测试客户端只用工具回复做附件,它拿到了三个路径,却拿不到三份文件的内容。 + +## 沿途改了什么 + +1. 在连接前就能读到的 README 补上三种用途。连接后,先用已有文字或照片,只有用途不清时才举与材料有关的例子。照片需要由客户端传给 Panache;另一台电脑上的路径不能把照片传过来。 +2. 让首次说明把「字号」说成「字大一点」,把「降低墨迹浓度」说成「墨色淡一点」。用普通图看小样,收到反馈后再看新版。保存并使用用户选中的版号,即使后来又改了一版。 +3. 导出增加可选的 `include_file`。客户端提出请求时,512 KiB 以内的 PDF 或 ZIP 可作为 MCP 内嵌资源随回复传送,也就是直接带上文件内容。读取的是刚生成的文件句柄,避免按路径重新打开时读到别的文件。既有调用仍可只取路径。上限按原文件计算,用来限制一次回复的体积。 +4. 把「生成」和「交付」分开。客户端收到内容后,还要把它显示为可打开的附件。遇到过大的文件或传送失败,保留已生成的文件,说明应从哪台电脑取回。服务端看不到用户的聊天界面,不能据此确认用户已经打开。 + +## 先核对要问什么 + +下面是作者写的固定对话示例。把再次索要用户已经给出的文字、照片或用途算为一次多问。一条消息可同时收齐材料和用途。 + +| 已有材料和意图 | 向导示例 | 追问轮数 | 多问 | +| --- | --- | ---: | ---: | +| 只有「帮我做一份手写作业」 | 「把要写的内容贴给我。你想打印、填在自己的练习纸上,还是只留能贴到别处的字?」 | 1 | 0 | +| 已给正文,明确要打印 | 「我用这段话做打印版。」 | 0 | 0 | +| 已给正文和练习纸照片,也说明要填在照片上 | 直接用客户端能传给服务的照片;传不了就说明限制。 | 0 | 0 | +| 已给正文,明确要透明字迹 | 直接做透明稿,说明解开 ZIP 可拿到 PNG。 | 0 | 0 | + +负对照是对第二行再问「想打印还是只要字迹?」。按同一规则计一次多问。四行示例合计一次必要追问、零次多问;这是示例的话术预算。真实模型的追问次数、学生理解程度和找到附件所需的时间均未测。另一个可复核的代理指标是检查握手中是否出现五项具体表达:三种成品、合并索取缺失正文、明确请求跳过选择、用日常用语提改动、沿用选中的版本。`compare_first_use.py` 检查的是原文片段,不能判断所有同义表述或读者理解。 + +## 用真实服务复走 + +Python 固定安排用户事件,Rust 服务真实建稿、排版、调参和导出。测试客户端把内嵌数据写入自己的收件目录。另一个检查步骤才读取服务器成品,比较两端内容。两者在同一测试机上,隔离的是客户端取文件的方法。没有运行聊天模型或招募学生。 + +| 在同一份材料上做的事 | 观察结果 | +| --- | --- | +| 打印稿先看第 1 版,按「字大一点」改成第 2 版,选中第 2 版后再创建第 3 版 | 从客户端取回的第 2 版 PDF 为 32,704 字节。解出 PDF 页图,与第 2 版小样的 RGB 像素完全相同;第 1 版的平均通道误差约 1.786(0–255)。 | +| 用合成练习纸做第 1 版;另测服务器还没有收到照片 | 成品保留纸面 200,000 个像素中的 196,992 个,其余是文字区域。ZIP 中的页图与小样逐像素相同。缺图的真实请求被拒,12 张表均无变化。 | +| 直接做透明稿 | 第 2 版 ZIP 中的 PNG 同时含全透明和不透明像素;全页与预览一致。另一个合法 ZIP 不能冒充这份文件。 | +| 不共用路径,只按工具回执收文件 | 基线与候选生成的三份目标文件及一个旧版对照均逐字节相同。测试客户端能打开且与参考成品匹配的文件,从 0/3 到 3/3。这个数字衡量文件能否传到客户端。 | +| 只要路径,或请求随回复传送 1,639,341 字节的大文件 | 前者保持原回执结构,后者报告 `too_large`;两次均保留有效导出,没有附上截短的文件。另有 Rust 测试核对 524,288 与 524,289 字节的分界。 | + +所有普通预览前后都核过 SQLite 全表内容;导出只新增对应的成品记录,没有新增检查单。桌面配置界面、特定第三方客户端的附件按钮、无法显示图片时的真人判断,均未在此实验覆盖。量化结果不是耗时、转化率或用户满意度。 + +## 怎样复跑 + +需要项目指定的 Rust、官方 Markdown worker、仓库字体、Python 的 MCP SDK 和 Pillow,以及 Poppler 的 `pdfimages`。从候选源码运行以下脚本;两个输出目录须尚未存在。`BASE_BIN` 是从上面的 main 单独构建的程序,`NEW_BIN` 是候选程序,`WORKER` 指向随桌面版提供或由项目脚本构建的 `prepare-text-worker.js`。 + +```sh +cargo build --locked --release -p panache-mcp +T=crates/panache-mcp/tests +python "$T/first_use.py" "$BASE_BIN" "$WORKER" --baseline --out main-run +python "$T/first_use.py" "$NEW_BIN" "$WORKER" --out candidate-run +python "$T/compare_first_use.py" main-run candidate-run +cargo test --locked -p panache-mcp +``` + +每次会新建隔离库。报告保存握手说明、真实导出参数、版号、文件摘要、小样和客户端收到的文件。稿件 ID 每次重新生成,核对的是相同输入、版号和文件内容。 diff --git a/crates/panache-mcp/tests/first_use.py b/crates/panache-mcp/tests/first_use.py new file mode 100644 index 00000000..dc659450 --- /dev/null +++ b/crates/panache-mcp/tests/first_use.py @@ -0,0 +1,199 @@ +# /// script +# dependencies = ["mcp>=1.12,<2", "Pillow"] +# /// +"""Fixed first-use journeys over real stdio. Requires Poppler's pdfimages on PATH.""" +import argparse +import asyncio +import base64 +import hashlib +import io +import json +import os +import random +import shutil +import sqlite3 +import subprocess +from contextlib import closing +from pathlib import Path +from tempfile import TemporaryDirectory +from zipfile import ZipFile + +from PIL import Image, ImageChops, ImageStat +from mcp import ClientSession, StdioServerParameters +from mcp.client.stdio import stdio_client + +from mcp_client import call + +HERE = Path(__file__).resolve().parent +TEXT = "观察记录:水滴沿着叶尖落下。" +LIMIT = 512 * 1024 + + +def tables(home): + with closing(sqlite3.connect((home / "drafts.sqlite3").as_uri() + "?mode=ro", uri=True)) as db: + names = db.execute("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name") + return { + name: db.execute(f'SELECT * FROM "{name}" ORDER BY rowid').fetchall() + for (name,) in names + } + + +def digest(data): + return hashlib.sha256(data).hexdigest() + + +def png_image(data): + with Image.open(io.BytesIO(data)) as image: + assert image.format == "PNG" + return image.convert("RGBA") + + +def embedded(reply): + return [item.resource for item in reply.content if item.type == "resource"] + + +async def run(args, home): + out = args.out + out.mkdir(parents=True, exist_ok=False) + host = out / "client-files" + host.mkdir() + params = StdioServerParameters(command=str(args.binary.resolve()), cwd=home, env={ + **os.environ, "PANACHE_MCP_HOME": str(home), "PANACHE_USER_FONT_DIR": str(home / "fonts"), + "PANACHE_FONT_DIR": str(HERE.parents[2] / "assets/font_assets"), + "PANACHE_MARKDOWN_WORKER": str(args.worker.resolve()), "PANACHE_MCP_PRESERVE_REVIEWS": "0", + }) + report = {"mode": "baseline" if args.baseline else "candidate", "exports": {}, "calls": []} + async with stdio_client(params) as streams, ClientSession(*streams) as client: + info = await client.initialize() + assert info.serverInfo.name == "panache-mcp" + tools = {tool.name: tool for tool in (await client.list_tools()).tools} + export = tools["export_handwriting"] + assert ("include_file" in export.inputSchema["properties"]) == (not args.baseline) + (out / "initialize.txt").write_text(info.instructions, encoding="utf-8") + (out / "export-tool.json").write_text(export.model_dump_json(indent=2), encoding="utf-8") + + async def invoke(name, **kw): + report["calls"].append({"tool": name, "args": kw}) + return await call(client, name, **kw) + + async def sample(label, draft_id, revision): + before = tables(home) + res = await invoke("preview_handwriting", draft_id=draft_id, revision=revision, + view="image", section=1, page=1) + assert res.structuredContent["revision"] == revision + png = base64.b64decode(next(x.data for x in res.content if x.type == "image"), validate=True) + assert tables(home) == before + (out / (label + ".png")).write_bytes(png) + return png_image(png) + + async def generate(label, draft_id, revision, fmt, request_bytes=True, oversize=False): + opt = {"include_file": True} if request_bytes and not args.baseline else {} + before = tables(home) + res = await invoke("export_handwriting", draft_id=draft_id, revision=revision, format=fmt, **opt) + sc = res.structuredContent + assert (sc["draft_id"], sc["revision"], sc["pages"]) == (draft_id, revision, 1) + assert sc["review"]["unreviewed_pages"] == [{"section": 1, "page": 1}] + after = tables(home) + assert {t for t in before if before[t] != after[t]} == {"export_files"} + assert len(after["export_files"]) == len(before["export_files"]) + 1 + blobs = embedded(res) + status = sc.get("file_transfer", {}).get("status") + if opt and not oversize: + assert status == "included" and len(blobs) == 1 + assert blobs[0].mimeType == {"pdf":"application/pdf", "zip":"application/zip"}[fmt] + # The simulated client can use only the reply for this copy. + data = base64.b64decode(blobs[0].blob, validate=True) + target = host / f"{label}.{fmt}" + target.write_bytes(data) + assert target.read_bytes() == data + else: + assert not blobs and status == ("too_large" if opt and oversize else None) + # Separate auditor, with access to the server, checks the generated artifact. + server_bytes = Path(sc["path"]).read_bytes() + if blobs: + assert data == server_bytes + if oversize: + assert len(server_bytes) > LIMIT + report["exports"][label] = dict(revision=revision, draft_id=draft_id, pages=sc["pages"], + size=len(server_bytes), sha256=digest(server_bytes), + status=status, client_copy=bool(blobs)) + return server_bytes + + # External scripted events: ambiguous request -> printable sheet and text -> change -> approve v2. + start = tables(home) + assert not start["drafts"] + await invoke("list_fonts", source="bundled", query="霞鹜文楷.ttf", limit=1) + assert tables(home) == start + style = {"seed": 31} + saved = await invoke("save_section", markdown=TEXT, style=style) + key = saved.structuredContent["draft_id"] + first = await sample("print-v1", key, 1) + await invoke("tune_handwriting", draft_id=key, expected_revision=1, changes={"font_size": 48}) + chosen = await sample("print-v2", key, 2) + assert chosen.tobytes() != first.tobytes() + # A later version exists: export the chosen sample, even if it is no longer latest. + await invoke("tune_handwriting", draft_id=key, expected_revision=2, changes={"font_size": 24}) + pdf = await generate("print-v2", key, 2, "pdf") + pdf_path = host / "print-v2.pdf" if not args.baseline else out / "server-print-v2.pdf" + if args.baseline: + pdf_path.write_bytes(pdf) + subprocess.run(["pdfimages", "-png", str(pdf_path), str(home / "page")], check=True) + with Image.open(home / "page-000.png") as image: + assert image.size == chosen.size + errors = [sum(ImageStat.Stat(ImageChops.difference(image.convert("RGB"), ref.convert("RGB"))).mean) / 3 + for ref in (chosen, first)] + assert errors[0] == 0 and errors[1] > 0 + report["pdf_mean_absolute_channel_error_v2_v1"] = errors + old_pdf = await generate("print-v1-control", key, 1, "pdf", request_bytes=False) + assert digest(old_pdf) != digest(pdf) + + # A client staged the synthetic form on the server. Do not use a user's laptop path. + photo = home / "worksheet.png" + before = tables(home) + missing = await client.call_tool("save_section", {"markdown": TEXT, "paper_path": str(photo)}) + assert missing.isError and tables(home) == before + report["missing_photo_rejected_without_change"] = True + shutil.copyfile(HERE / "fixtures/ruled.png", photo) + saved = await invoke("save_section", markdown=TEXT, style=style, paper_path=str(photo)) + key = saved.structuredContent["draft_id"] + paper = await sample("worksheet-v1", key, 1) + with Image.open(photo) as original: + assert paper.size == original.size + delta = ImageChops.difference(paper.convert("RGB"), original.convert("RGB")) + total = paper.width * paper.height + unchanged = sum(n for n, rgb in delta.getcolors(total) if rgb == (0, 0, 0)) + assert total * 0.95 < unchanged < total + report["worksheet_pixels"] = {"total": total, "unchanged": unchanged} + archive = await generate("worksheet-v1", key, 1, "zip") + with ZipFile(io.BytesIO(archive)) as z: + assert z.namelist() == ["0.png"] and png_image(z.read("0.png")).tobytes() == paper.tobytes() + + # Explicit ink-only request. No paper import, font menu or review required. + key = (await invoke("save_section", markdown=TEXT, style=style)).structuredContent["draft_id"] + await invoke("tune_handwriting", draft_id=key, expected_revision=1, changes={"transparent_background": True}) + ink = await sample("ink-v2", key, 2) + assert ink.getchannel("A").getextrema() == (0, 255) + archive = await generate("ink-v2", key, 2, "zip") + with ZipFile(io.BytesIO(archive)) as z: + assert z.namelist() == ["0.png"] and png_image(z.read("0.png")).tobytes() == ink.tobytes() + + if not args.baseline: + # Incompressible synthetic paper exercises the real oversized export path. + noise = random.Random(31).randbytes(640 * 640 * 3) + Image.frombytes("RGB", (640, 640), noise).save(photo) + key = (await invoke("save_section", markdown=TEXT, style=style, paper_path=str(photo))).structuredContent["draft_id"] + await generate("oversize", key, 1, "zip", oversize=True) + assert not tables(home)["review_observations"] + (out / "report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8") + print(json.dumps(report["exports"], ensure_ascii=False)) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("binary", type=Path) + parser.add_argument("worker", type=Path) + parser.add_argument("--out", type=Path, required=True, help="new output directory for samples and receipts") + parser.add_argument("--baseline", action="store_true", help="exercise a build without include_file") + args = parser.parse_args() + with TemporaryDirectory(prefix="panache-first-use-") as tmp: + asyncio.run(run(args, Path(tmp))) From 312497e59a3d07595e680434eb7d070973722128 Mon Sep 17 00:00:00 2001 From: Helian Nuits Date: Wed, 25 Nov 2026 18:57:20 +0800 Subject: [PATCH 02/11] =?UTF-8?q?=E8=AF=B4=E6=98=8E=E9=A6=96=E6=AC=A1?= =?UTF-8?q?=E8=BF=9E=E6=8E=A5=E6=80=8E=E4=B9=88=E7=A1=AE=E8=AE=A4=E3=80=81?= =?UTF-8?q?=E5=85=A5=E5=8F=A3=E6=B6=88=E5=A4=B1=E6=80=8E=E4=B9=88=E6=8E=92?= =?UTF-8?q?=E6=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 复制配置不等于连上。用 Panache 实际返回字体名做一次不改稿的核对;桌面包缺关键程序导致入口消失时,指向完整安装和各平台连接说明。 独立核对:打包脚本 4/4;配置布局与 JSON 往返模拟 24/24。未运行 Flutter 或真实桌面客户端。 --- README.md | 6 +++++- README.zh-CN.md | 6 +++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 37315d5e..e3b248f6 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,11 @@ Offline downloads are available for Windows x64, macOS on Apple silicon, Linux x ## Local MCP for AI clients -The Windows, macOS, and Linux desktop packages include a local MCP server. Open **App settings → Connect AI client** and copy the configuration into a client that supports stdio MCP. Try asking: +The Windows, macOS, and Linux desktop packages include a local MCP server. In **App settings → Connect AI client**, copy the configuration, then add Panache in the MCP settings of an AI client that supports local stdio servers. Reload the client’s MCP settings and ask it to call Panache to list the installed handwriting fonts. The connection works if the Panache tool returns font names. + +**Don’t see Connect AI client?** It is not available in the web or mobile app. On a supported desktop, make sure you installed or extracted the whole desktop package, not just the app executable. See the [desktop setup notes](crates/panache-mcp/README.md) for platform details. + +Once connected, try asking: > Write my notes and the process diagram on this photo of my stationery. Show me the first page, then export the whole draft as a PDF. diff --git a/README.zh-CN.md b/README.zh-CN.md index d8b753aa..7f828885 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -24,7 +24,11 @@ Panache 能把正文、公式、表格和电路图排成手写稿。导入文档 ## 用 AI 客户端生成手写稿 -Windows、macOS 和 Linux 桌面版随附本地 MCP 服务。在 **应用设置 → 连接 AI 客户端** 复制配置,加入支持 stdio MCP 的客户端,就可以对它说: +Windows、macOS 和 Linux 桌面版随附本地 MCP 服务。在 **应用设置 → 连接 AI 客户端** 复制配置,再到支持本地 stdio 服务的 AI 客户端的 MCP 设置里添加 Panache。重新加载客户端的 MCP 配置后,对它说:「请调用 Panache 列出已安装的手写字体。」Panache 工具返回字体名,才说明连上了。 + +**设置里没有「连接 AI 客户端」?** 网页版和手机版没有这个入口。如果用的是支持的桌面版,请确认已完整安装或解压桌面包,而不是只复制了应用的可执行文件。各系统的注意事项见[桌面连接说明](crates/panache-mcp/README.md)。 + +连上后,可以对它说: > 用这张斜拍的信纸排我的笔记,画出进程状态转换图。先给我看第一页,确认后把整份导出成 PDF。 From ee2cec0bdb1f0a07ad415ef7457f8121453863c2 Mon Sep 17 00:00:00 2001 From: Helian Nuits Date: Wed, 25 Nov 2026 19:01:14 +0800 Subject: [PATCH 03/11] =?UTF-8?q?=E5=91=8A=E8=AF=89=E7=94=A8=E6=88=B7?= =?UTF-8?q?=E7=BA=B8=E7=85=A7=E5=BF=85=E9=A1=BB=E8=83=BD=E8=A2=AB=20Panach?= =?UTF-8?q?e=20=E8=AF=BB=E5=88=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 聊天里能看到照片,不代表运行 Panache 的电脑能用该文件。首次建稿的纸照字段和原本的路径报错现在都说明这一区别;不能传就明确告知,不猜路径。 真实 stdio 对照:两臂各一次合法导入,输出逐字节相同;各四种无效输入拒绝且 12 张数据库表不变。只改说明,不改导入逻辑。 --- crates/panache-mcp/src/inputs.rs | 3 ++- crates/panache-mcp/src/paper.rs | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/panache-mcp/src/inputs.rs b/crates/panache-mcp/src/inputs.rs index fae0638a..bfeee9a7 100644 --- a/crates/panache-mcp/src/inputs.rs +++ b/crates/panache-mcp/src/inputs.rs @@ -79,7 +79,8 @@ pub struct Guide { #[derive(Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct Save { - /// Optional absolute local image path for a new draft. Imports and aligns the paper once. + /// Optional absolute path to an image file readable on the computer running Panache. Imports and aligns the paper once. + /// A chat attachment or URL alone is not a file path. If the client cannot transfer the photo to that computer, explain this instead of guessing a path. /// Use with the default plain preset. All revisions share the saved image. pub paper_path: Option, /// With paper_path: photo (default) preserves camera perspective; flatten aligns the background. diff --git a/crates/panache-mcp/src/paper.rs b/crates/panache-mcp/src/paper.rs index de8858b1..0640547c 100644 --- a/crates/panache-mcp/src/paper.rs +++ b/crates/panache-mcp/src/paper.rs @@ -156,7 +156,7 @@ impl ImportedPaper { ) -> Result { ensure!( path.is_absolute() && path.is_file(), - "paper_path must be an absolute path to a local image file" + "paper_path must be an absolute path to an image file readable on the computer running Panache. A chat attachment or URL alone is not a file path. If the client cannot transfer the photo to that computer, explain this instead of guessing a path." ); let limits = Limits::default(); let file = File::open(path).context("Cannot open paper image")?; From c9901001af1b17bae4ae8667d8609f8f4fb4a044 Mon Sep 17 00:00:00 2001 From: Helian Nuits Date: Wed, 25 Nov 2026 19:11:38 +0800 Subject: [PATCH 04/11] =?UTF-8?q?=E8=AF=B4=E6=98=8E=E4=B8=8B=E8=BD=BD?= =?UTF-8?q?=E5=85=A5=E5=8F=A3=E5=BA=94=E8=AF=A5=E7=94=B1=E5=AE=A2=E6=88=B7?= =?UTF-8?q?=E7=AB=AF=E6=8F=90=E4=BE=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 模型不一定会给出可点链接。既然客户端已经收到文件,下载入口直接由客户端生成;MCP 资源 URI 不是地址,文件字节不需要走模型上下文。只改接入说明,不改变导出协议。 --- crates/panache-mcp/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index fd8251ed..e232d7de 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -50,6 +50,8 @@ cargo build --locked --release -p panache-mcp 想在聊天里拿到文件时,能处理 MCP 内嵌文件的客户端可在导出时传 `include_file=true`,把收到的 PDF 或 ZIP 作为附件显示给用户。512 KiB 以内的完整文件可以随回复传送。更大的文件仍在运行 Panache 的电脑上;两端共用磁盘时可直接打开返回的路径。只有客户端已经提供可打开的附件或链接时,才告诉用户「附件在这里」。 +客户端从内嵌资源取出文件后,应由客户端生成自己的下载入口,不依赖模型在回复里拼链接。资源里的 `panache-export:///…` 仅用于标识,不是下载地址。把交付状态和已经可用的下载入口交给模型即可,不要把文件的 Base64 内容放进模型上下文或普通日志。 + 使用自己的纸张时,在第一次调用 `save_section` 时传入 `paper_path`,例如 `{"markdown":"第一题","paper_path":"C:/作业/南昌大学横线纸.jpg"}`。路径指向运行 MCP 的电脑上的图片。默认保留原照片,按识别到的横线投影字迹和插图。`paper` 返回排版尺寸、边距、行距、识线结果,投影时另有原照尺寸。可用 `preview_handwriting(view="paper")` 单独看底纸,或在导入时通过 `paper_guides` 指定参考线。需要校平底纸时传 `paper_mode="flatten"`。无可靠横线时保留底图,使用普通行距。纸张随稿件保存一次,后续追加、回查、预览和导出可在原图移动后继续使用。 如果照片是聊天附件,先用客户端支持的文件传送功能,把照片交给 Panache。云端没有这项功能时,可在照片所在电脑连接桌面版再使用。复制手机或另一台电脑上的路径不能传照片。带视觉能力的模型可以查看客户端转交的预览图。客户端或模型只能处理文字时,可读取版面和像素测量,并请用户打开导出文件确认外观,再按反馈修改。 From a04ab7fd7dcbbbd332116f25617717247a1d60c8 Mon Sep 17 00:00:00 2001 From: Helian Nuits Date: Wed, 25 Nov 2026 19:53:30 +0800 Subject: [PATCH 05/11] =?UTF-8?q?=E6=8A=8A=E7=BA=B8=E7=85=A7=E4=BC=A0?= =?UTF-8?q?=E4=B8=8D=E5=88=B0=E5=8F=88=E6=81=A2=E5=A4=8D=E7=9A=84=E8=BF=87?= =?UTF-8?q?=E7=A8=8B=E5=9B=BA=E5=8C=96=E6=88=90=E5=9B=9E=E5=BD=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 缺图时请求完整参数,验证无数据库写入;测试客户端把合成纸照放到同一路径后原样重试。普通预览不留检查单,逐像素核对印刷姓名。四轮实验分开记真实模型与固定回放,不把复跑当新模型抽样。 已在隔离环境重跑两臂真实 stdio、导出对照和格式检查。仅测试与证据说明。 --- crates/panache-mcp/tests/first-use-notes.md | 14 +++++- crates/panache-mcp/tests/first_use.py | 47 ++++++++++++++------- 2 files changed, 44 insertions(+), 17 deletions(-) diff --git a/crates/panache-mcp/tests/first-use-notes.md b/crates/panache-mcp/tests/first-use-notes.md index dce6b13b..92f7f731 100644 --- a/crates/panache-mcp/tests/first-use-notes.md +++ b/crates/panache-mcp/tests/first-use-notes.md @@ -35,13 +35,24 @@ Python 固定安排用户事件,Rust 服务真实建稿、排版、调参和 | 在同一份材料上做的事 | 观察结果 | | --- | --- | | 打印稿先看第 1 版,按「字大一点」改成第 2 版,选中第 2 版后再创建第 3 版 | 从客户端取回的第 2 版 PDF 为 32,704 字节。解出 PDF 页图,与第 2 版小样的 RGB 像素完全相同;第 1 版的平均通道误差约 1.786(0–255)。 | -| 用合成练习纸做第 1 版;另测服务器还没有收到照片 | 成品保留纸面 200,000 个像素中的 196,992 个,其余是文字区域。ZIP 中的页图与小样逐像素相同。缺图的真实请求被拒,12 张表均无变化。 | +| 同一次原纸建稿,先缺图,再原样重试 | 首次被拒后,12 张表的内容均未变。测试客户端把印有「姓名:林禾」的合成纸照放到服务端同一路径,原参数重试得到第 1 版。普通预览前后全表相同。与输入纸照比较,姓名框内 0 像素变化,全页 200,000 像素中有 3,008 个改变。ZIP 页图与小样一致。 | | 直接做透明稿 | 第 2 版 ZIP 中的 PNG 同时含全透明和不透明像素;全页与预览一致。另一个合法 ZIP 不能冒充这份文件。 | | 不共用路径,只按工具回执收文件 | 基线与候选生成的三份目标文件及一个旧版对照均逐字节相同。测试客户端能打开且与参考成品匹配的文件,从 0/3 到 3/3。这个数字衡量文件能否传到客户端。 | | 只要路径,或请求随回复传送 1,639,341 字节的大文件 | 前者保持原回执结构,后者报告 `too_large`;两次均保留有效导出,没有附上截短的文件。另有 Rust 测试核对 524,288 与 524,289 字节的分界。 | 所有普通预览前后都核过 SQLite 全表内容;导出只新增对应的成品记录,没有新增检查单。桌面配置界面、特定第三方客户端的附件按钮、无法显示图片时的真人判断,均未在此实验覆盖。量化结果不是耗时、转化率或用户满意度。 +## 此前四组实验的分母 + +| 任务与通过条件 | 对照结果 | +| --- | --- | +| 打印,答复给出指向所选旧版 PDF 的链接 | main 0/2,#49 1/2。只算 SDK 收到文件则为 0/2、2/2。四份服务端 PDF 都选对了版。[记录](https://github.com/SXP-Simon/Panache/pull/49#issuecomment-7160655795) | +| 纸照恢复,只给当前能做的办法,建稿出样且不额外检查 | 原说明与新说明各 1/2。单看能否恢复,两组各 2/2。[记录](https://github.com/SXP-Simon/Panache/pull/49#issuecomment-7161181243) | +| 模拟下载入口,对应的文件能打开且版号正确 | 依赖模型贴链接 2/4,由客户端生成入口 4/4。另外 8 个不能交付的回放都没有误给入口。这 12 个是固定回放。[记录](https://github.com/SXP-Simon/Panache/pull/49#issuecomment-7160655795) | +| 局部改字,放大正文、保住姓名且全程不试全稿字号 | 原工具目录与多一句指引各 1/2。只算最终改对则是 2/2、1/2,未采用候选句。同四个会话遇到圈选缺失都先询问(4/4)。[记录](https://github.com/SXP-Simon/Panache/pull/49#issuecomment-7161301822) | + +三个模型对照各用四个新会话,每臂各有一个 Luna 和一个 Terra。下方命令只复跑固定的 SDK 调用。 + ## 怎样复跑 需要项目指定的 Rust、官方 Markdown worker、仓库字体、Python 的 MCP SDK 和 Pillow,以及 Poppler 的 `pdfimages`。从候选源码运行以下脚本;两个输出目录须尚未存在。`BASE_BIN` 是从上面的 main 单独构建的程序,`NEW_BIN` 是候选程序,`WORKER` 指向随桌面版提供或由项目脚本构建的 `prepare-text-worker.js`。 @@ -52,6 +63,7 @@ T=crates/panache-mcp/tests python "$T/first_use.py" "$BASE_BIN" "$WORKER" --baseline --out main-run python "$T/first_use.py" "$NEW_BIN" "$WORKER" --out candidate-run python "$T/compare_first_use.py" main-run candidate-run +python -c 'import json; print(json.load(open("candidate-run/report.json"))["worksheet_pixels"])' cargo test --locked -p panache-mcp ``` diff --git a/crates/panache-mcp/tests/first_use.py b/crates/panache-mcp/tests/first_use.py index dc659450..de6e2030 100644 --- a/crates/panache-mcp/tests/first_use.py +++ b/crates/panache-mcp/tests/first_use.py @@ -10,7 +10,6 @@ import json import os import random -import shutil import sqlite3 import subprocess from contextlib import closing @@ -18,7 +17,7 @@ from tempfile import TemporaryDirectory from zipfile import ZipFile -from PIL import Image, ImageChops, ImageStat +from PIL import Image, ImageChops, ImageDraw, ImageFont, ImageStat from mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client @@ -147,23 +146,38 @@ async def generate(label, draft_id, revision, fmt, request_bytes=True, oversize= old_pdf = await generate("print-v1-control", key, 1, "pdf", request_bytes=False) assert digest(old_pdf) != digest(pdf) - # A client staged the synthetic form on the server. Do not use a user's laptop path. + # Retry the same request after the client places the photo on the server. photo = home / "worksheet.png" before = tables(home) - missing = await client.call_tool("save_section", {"markdown": TEXT, "paper_path": str(photo)}) - assert missing.isError and tables(home) == before + request = {"markdown": TEXT, "style": style, "paper_path": str(photo)} + assert not photo.exists() + missing = await client.call_tool("save_section", request) + assert missing.isError and "paper_path" in missing.content[0].text + assert tables(home) == before + report["calls"].append({"tool": "save_section", "args": request, "error": missing.content[0].text}) report["missing_photo_rejected_without_change"] = True - shutil.copyfile(HERE / "fixtures/ruled.png", photo) - saved = await invoke("save_section", markdown=TEXT, style=style, paper_path=str(photo)) + with Image.open(HERE / "fixtures/ruled.png") as ruled: + sheet = ruled.convert("RGB") + font = ImageFont.truetype(str(HERE.parents[2] / "assets/font_assets/霞鹜文楷.ttf"), 23) + name_box = (200, 0, 397, 40) + blank_header = sheet.crop(name_box) + ImageDraw.Draw(sheet).text((205, 6), "姓名:林禾", font=font, fill=(43, 52, 68)) + assert ImageChops.difference(sheet.crop(name_box), blank_header).getbbox() + sheet.save(photo) + saved = await invoke("save_section", **request) + assert saved.structuredContent["revision"] == 1 key = saved.structuredContent["draft_id"] paper = await sample("worksheet-v1", key, 1) - with Image.open(photo) as original: - assert paper.size == original.size - delta = ImageChops.difference(paper.convert("RGB"), original.convert("RGB")) - total = paper.width * paper.height - unchanged = sum(n for n, rgb in delta.getcolors(total) if rgb == (0, 0, 0)) - assert total * 0.95 < unchanged < total - report["worksheet_pixels"] = {"total": total, "unchanged": unchanged} + assert paper.size == sheet.size + delta = ImageChops.difference(paper.convert("RGB"), sheet) + total = paper.width * paper.height + unchanged = sum(n for n, rgb in delta.getcolors(total) if rgb == (0, 0, 0)) + assert total * 0.95 < unchanged < total + name_delta = ImageChops.difference(paper.crop(name_box), sheet.crop(name_box).convert("RGBA")) + name_changed = sum(n for n, rgba in name_delta.getcolors(total) if any(rgba)) + assert name_changed == 0 + report["worksheet_pixels"] = {"total": total, "unchanged": unchanged, "name_box": name_box, + "name_changed": name_changed, "tables_checked": len(before)} archive = await generate("worksheet-v1", key, 1, "zip") with ZipFile(io.BytesIO(archive)) as z: assert z.namelist() == ["0.png"] and png_image(z.read("0.png")).tobytes() == paper.tobytes() @@ -180,8 +194,9 @@ async def generate(label, draft_id, revision, fmt, request_bytes=True, oversize= if not args.baseline: # Incompressible synthetic paper exercises the real oversized export path. noise = random.Random(31).randbytes(640 * 640 * 3) - Image.frombytes("RGB", (640, 640), noise).save(photo) - key = (await invoke("save_section", markdown=TEXT, style=style, paper_path=str(photo))).structuredContent["draft_id"] + oversize_photo = home / "oversize.png" + Image.frombytes("RGB", (640, 640), noise).save(oversize_photo) + key = (await invoke("save_section", markdown=TEXT, style=style, paper_path=str(oversize_photo))).structuredContent["draft_id"] await generate("oversize", key, 1, "zip", oversize=True) assert not tables(home)["review_observations"] (out / "report.json").write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8") From 1647a97fee6dadb4fa020f44cd720b75718eda9a Mon Sep 17 00:00:00 2001 From: Helian Nuits Date: Wed, 25 Nov 2026 20:19:27 +0800 Subject: [PATCH 06/11] =?UTF-8?q?=E6=8F=90=E5=89=8D=E8=AF=B4=E6=98=8E?= =?UTF-8?q?=E6=AD=A3=E6=96=87=E6=8F=92=E5=9B=BE=E4=BC=9A=E5=8F=98=E6=88=90?= =?UTF-8?q?=E6=89=8B=E7=BB=98=E7=BA=BF=E7=A8=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 原图仍保存在 Markdown 中,但成品正文不会保留原彩。颜色重要时先说清并看小样,不要改用整页底纸来冒充段间插图。只改工具字段说明和 MCP README,不改渲染。 真实目录只这一处稳定文案变化,原彩对照两边输出同字节,完整 SDK 冒烟通过;模型误尝试仍各 1/2。 --- crates/panache-mcp/README.md | 2 ++ crates/panache-mcp/src/inputs.rs | 2 ++ 2 files changed, 4 insertions(+) diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index e232d7de..a4f87d56 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -46,6 +46,8 @@ cargo build --locked --release -p panache-mcp 只有一句「帮我做一份手写作业」时,先贴要写的内容。想打印,就用普通纸样做 PDF;想填在老师发的练习纸上,就用那张纸的照片;想把字放进海报,就用透明字迹,解开 ZIP 后取出 PNG。已经说清「用这段话做打印版」就可以直接开始。 +稿件会原样保存嵌入的图片,正文里的插图会画成手绘线稿,无法保留原彩。颜色很重要时,请先看这一页的小样,别把插图改成整页底纸。 + 可以先说「用这段话给我看第一页」,看过后说「字大一点」,再说「就用这一版」。客户端按同一稿件的版本号取预览和导出。查看小样使用 `preview_handwriting(view="image")`,无需创建检查单。 想在聊天里拿到文件时,能处理 MCP 内嵌文件的客户端可在导出时传 `include_file=true`,把收到的 PDF 或 ZIP 作为附件显示给用户。512 KiB 以内的完整文件可以随回复传送。更大的文件仍在运行 Panache 的电脑上;两端共用磁盘时可直接打开返回的路径。只有客户端已经提供可打开的附件或链接时,才告诉用户「附件在这里」。 diff --git a/crates/panache-mcp/src/inputs.rs b/crates/panache-mcp/src/inputs.rs index bfeee9a7..97cd277f 100644 --- a/crates/panache-mcp/src/inputs.rs +++ b/crates/panache-mcp/src/inputs.rs @@ -88,6 +88,8 @@ pub struct Save { /// Optional photo-space baselines overriding auto detection on import. Give 2..32 guides, first row 0, last row the last writable line; intermediate guides refine the fit. pub paper_guides: Option>, /// Original Markdown of just this section. A new section starts on a fresh page. + /// Embedded images remain intact in the source. Pages render them as hand-drawn outlines without their original colors. + /// If color matters, explain this and offer a preview. Keep the image in the text rather than using it as the paper. pub markdown: String, /// Omit to create a draft. Supply the returned ID to append or edit. pub draft_id: Option, From e4df6b20828567c580936255d7df69e101e8bb34 Mon Sep 17 00:00:00 2001 From: Helian Nuits Date: Wed, 25 Nov 2026 20:36:53 +0800 Subject: [PATCH 07/11] =?UTF-8?q?=E9=A6=96=E6=AC=A1=E8=BF=9E=E6=8E=A5?= =?UTF-8?q?=E5=A4=B1=E8=B4=A5=E6=97=B6=E5=85=88=E5=88=86=E6=B8=85=E5=BA=94?= =?UTF-8?q?=E7=94=A8=E8=BF=98=E6=98=AF=E5=AE=A2=E6=88=B7=E7=AB=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 桌面启动失败早于设置。复制只确认剪贴板,不代表 MCP 启动成功;工具没回字体时先看客户端日志,找不到路径才重新复制,系统库报错无需反复改 JSON。仅 MCP 连接说明。 --- crates/panache-mcp/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index a4f87d56..5f482389 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -8,6 +8,8 @@ 2. 在支持**本地 stdio 服务**的 AI 客户端中注册名为 `panache` 的服务。使用 `mcpServers` 格式的 JSON 配置可直接合并其中的 `panache` 条目,保留已有服务。若客户端使用表单、TOML 或其他格式,按其格式填入复制结果中的 `command` 和可选的 `args`。程序路径填作一项,每个参数各占一项。 3. 在客户端重新加载 MCP 配置或重新连接,问它「请调用 Panache 列出可用字体」。收到本机的字体文件名就表示连接成功。若客户端只接受服务器网址,请选择能在本机启动 stdio 程序的客户端。 +**连不上时,先看卡在哪一步。** 如果桌面版一打开就提示「内置手写引擎无法运行」,这是进入设置前的启动问题,和是否在 AI 客户端填写了配置无关。记下 Panache 版本和系统版本。若配置已复制,但 AI 客户端没有收到 Panache 工具返回的字体名,请查看客户端的 MCP 启动日志。若提示找不到文件,从当前安装重新复制配置;若提示系统库版本不匹配,请记下完整错误,改 JSON 不会解决。 + 客户端通过标准输入输出启动 Panache,关闭工作台后也能使用。移动安装目录后可重新复制。 桌面包包含 MCP、字体和 Markdown 转换器,JavaScript 运行时已编入 MCP 程序。Windows 新安装使用根目录启动器,可自动跟随应用更新;从旧启动器升级的安装会使用当前版本的 MCP 路径,更新后请重新复制。 From 8f9eb02b3f98a8148d5e325b2b51652b201b235d Mon Sep 17 00:00:00 2001 From: Helian Nuits Date: Wed, 25 Nov 2026 20:43:54 +0800 Subject: [PATCH 08/11] =?UTF-8?q?=E5=8A=A0=E4=B8=80=E4=B8=AA=E5=8F=AF?= =?UTF-8?q?=E9=80=89=E7=9A=84=20Linux=20=E5=8F=91=E8=A1=8C=E5=8C=85?= =?UTF-8?q?=E6=9C=AC=E5=9C=B0=E5=85=BC=E5=AE=B9=E6=80=A7=E6=A3=80=E6=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 检查解包后二进制真实导入的 glibc 版本,目标上限需显式给出,不把检查通过等同于支持该系统。原版 1.21.0 在 2.41 上限检出两个后端,本地重建包通过,固定对照 5/5。未接入 CI 或发布流程。 --- docs/release.md | 12 ++++ scripts/check-linux-glibc.py | 106 ++++++++++++++++++++++++++++++ scripts/tests/test_linux_glibc.py | 73 ++++++++++++++++++++ 3 files changed, 191 insertions(+) create mode 100644 scripts/check-linux-glibc.py create mode 100644 scripts/tests/test_linux_glibc.py diff --git a/docs/release.md b/docs/release.md index 2c21ee1e..e15ae9f4 100644 --- a/docs/release.md +++ b/docs/release.md @@ -52,3 +52,15 @@ release-mode 调试仍可使用调试签名,调试签名包不能作为正式 macOS 桌面包使用 ad-hoc 签名,未配置 Apple Developer ID 或公证;首次使用时 可能需要在系统隐私与安全性设置中允许打开。iOS 需要分发证书与 provisioning, 未配置时不发布不可安装的 IPA。 + +## 在本地检查 Linux 包的 glibc 版本需求 + +解开最终归档后,把包含 `backend/` 的 `Panache` 目录交给脚本,并明确指定要验证的 glibc 上限。例如,在 Debian 13 上验证 2.41 可运行以下命令。 + +```sh +python3 scripts/check-linux-glibc.py /path/to/Panache --max-glibc 2.41 +``` + +脚本使用 GNU `readelf` 读取包内 ELF 的版本需求。退出码 0 表示所有读到的数字 GLIBC 需求都在上限内,1 表示至少一个文件超界,2 表示参数有误,3 表示包或版本信息无法检查,4 表示缺少必需的 Rust 后端,5 表示找不到 `readelf`。无法换算成数字的 GLIBC 需求也会报错。检查通过后,仍需在目标系统上启动桌面程序,验证图形库和真实工具调用。 + +v1.21.0 官方 Linux x64 包以 2.41 为上限时,12 个 ELF 中有两个后端要求 `GLIBC_2.43`。在 Debian 13 从同一提交重建这两个后端后,同一个检查有 0 个文件超界。2.41 仅为这次对照使用的上限。 diff --git a/scripts/check-linux-glibc.py b/scripts/check-linux-glibc.py new file mode 100644 index 00000000..09731aa6 --- /dev/null +++ b/scripts/check-linux-glibc.py @@ -0,0 +1,106 @@ +#!/usr/bin/env python3 +"""Check ELF version requirements in an unpacked Panache Linux release.""" +import argparse +import os +from pathlib import Path +import re +import shutil +import subprocess +import sys + + +BACKENDS = ('backend/handwriting-server', 'backend/panache-mcp') + + +def version(text): + if not re.fullmatch(r'[0-9]+(?:\.[0-9]+)+', text): + raise ValueError(f'expected a numeric version, got {text!r}') + parts = [int(n) for n in text.split('.')] + while len(parts) > 2 and parts[-1] == 0: + parts.pop() + return tuple(parts) + + +def requirements(output): + # readelf also prints names that the object defines or merely lists in .gnu.version. + needs = re.search(r'^Version needs section [^\n]+\n((?:[ \t]+[^\n]+\n?)*)', output, re.M) + block = needs[1] if needs else '' + if not needs and 'No version information found' not in output and not re.search( + r'^Version (?:symbols|definition) section ', output, re.M): + raise ValueError('unrecognized GNU readelf version output') + providers = re.findall(r'\bFile: \S+\s+Cnt: (\d+)', block) + names = re.findall(r'\bName: (\S+)\s+Flags:', block) + count = re.search(r'\(VERNEEDNUM\)\s+(\d+)', output) + if (' ceiling: + print(f'{relative}: requires GLIBC_{highest}') + exceeded += 1 + print(f'{checked} ELF files checked, {exceeded} above the requested ceiling') + return int(bool(exceeded)) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('bundle', type=Path, help='unpacked directory containing backend/') + parser.add_argument('--max-glibc', required=True, type=version, metavar='VERSION') + args = parser.parse_args() + tool = shutil.which('readelf') + if not tool: + print('GNU readelf not found', file=sys.stderr) + return 5 + try: + root = args.bundle.resolve(strict=True) + if not root.is_dir(): + raise ValueError('expected an unpacked bundle directory') + missing = [name for name in BACKENDS if not (root / name).exists()] + if missing: + print('missing required backend: ' + ', '.join(missing), file=sys.stderr) + return 4 + if not (root / 'handwriting_app').is_file(): + raise ValueError('missing desktop executable handwriting_app') + return scan(root, tool, args.max_glibc) + except (OSError, ValueError, RuntimeError) as error: + print(error, file=sys.stderr) + return 3 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/scripts/tests/test_linux_glibc.py b/scripts/tests/test_linux_glibc.py new file mode 100644 index 00000000..f4c1e84b --- /dev/null +++ b/scripts/tests/test_linux_glibc.py @@ -0,0 +1,73 @@ +"""Run on Linux with a C compiler and GNU binutils.""" +import os +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest + + +SCRIPT = Path(__file__).resolve().parents[1] / 'check-linux-glibc.py' + + +@unittest.skipUnless(sys.platform.startswith('linux') and shutil.which('cc') and shutil.which('readelf'), + 'requires Linux cc and GNU readelf') +class LinuxGlibcTest(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.bundle = self.root / 'Panache' + self.backend = self.bundle / 'backend' + self.backend.mkdir(parents=True) + # The provider defines a high version and contains an unrelated version string. + # Only an ELF that imports its function should count against the ceiling. + (self.root / 'provider.c').write_text('const char *probe(void) { return "GLIBC_99.99"; }') + (self.root / 'versions').write_text('GLIBC_2.10 { global: probe; };') + self.provider = self.bundle / 'provider.so' + subprocess.run(['cc', '-shared', '-fPIC', '-nostdlib', 'provider.c', + '-Wl,--version-script=versions', '-o', self.provider], cwd=self.root, check=True) + for rel in ('handwriting_app', 'backend/panache-mcp', 'backend/handwriting-server'): + shutil.copyfile(self.provider, self.bundle / rel) + + def check(self, *args, path=None): + env = os.environ.copy() + if path is not None: + env['PATH'] = path + return subprocess.run([sys.executable, SCRIPT, self.bundle, *args], + capture_output=True, text=True, env=env) + + def test_definition_string_and_real_import(self): + self.assertEqual(self.check('--max-glibc', '2.9').returncode, 0) + (self.root / 'consumer.c').write_text('extern const char *probe(void);' + 'const char *call(void) { return probe(); }') + subprocess.run(['cc', '-shared', '-fPIC', '-nostdlib', 'consumer.c', + self.provider, '-o', self.bundle / 'extra.so'], cwd=self.root, check=True) + result = self.check('--max-glibc', '2.9') + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn('extra.so: requires GLIBC_2.10', result.stdout) + self.assertEqual(self.check('--max-glibc', '2.10.0').returncode, 0) + + def test_missing_backend(self): + (self.backend / 'panache-mcp').unlink() + result = self.check('--max-glibc', '2.41') + self.assertEqual(result.returncode, 4) + self.assertIn('backend/panache-mcp', result.stderr) + + def test_damaged_elf(self): + (self.backend / 'handwriting-server').write_bytes(b'\x7fELF') + result = self.check('--max-glibc', '2.41') + self.assertEqual(result.returncode, 3) + self.assertIn('backend/handwriting-server', result.stderr) + + def test_missing_tool(self): + self.assertEqual(self.check('--max-glibc', '2.41', path=str(self.root)).returncode, 5) + + def test_ceiling_required_and_numeric(self): + self.assertEqual(self.check().returncode, 2) + self.assertEqual(self.check('--max-glibc', 'latest').returncode, 2) + + +if __name__ == '__main__': + unittest.main() From 040fdd7ba8e4c551eead37797b2fe648a703f0da Mon Sep 17 00:00:00 2001 From: Helian Nuits Date: Wed, 25 Nov 2026 21:36:17 +0800 Subject: [PATCH 09/11] =?UTF-8?q?=E8=AE=A9=E7=AC=94=E8=BF=B9=E8=B0=83?= =?UTF-8?q?=E5=8F=82=E6=8C=89=E9=9C=80=E8=BF=94=E5=9B=9E=E5=AE=9E=E9=99=85?= =?UTF-8?q?=E7=94=9F=E6=95=88=E7=9A=84=E5=89=8D=E5=90=8E=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 只在调用者主动点名本次提交的一至两个 variation 控件时给有效差异。旧值来自期望版本,清除覆盖回到继承值,等值不假报,旧版本仍拒绝。普通调用回执保持原样。 知道目标值时,用一次写入即可获得实测 0.05→0.07 rad;不省模型定目标必要的预读。真 SDK 补回归、默认回执和预览逐字节等价,Rust 11/11、格式与 Clippy 通过。 --- CHANGELOG.md | 1 + crates/panache-mcp/README.md | 2 ++ crates/panache-mcp/src/inputs.rs | 4 +++ crates/panache-mcp/src/tuning.rs | 36 +++++++++++++++++++++---- crates/panache-mcp/tests/smoke.py | 45 +++++++++++++++++++++++++++++-- 5 files changed, 81 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3587352f..fd207267 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ - MCP 新检查单记录首次入档时的稿件版本,历史查单会说明单据能证明的先后关系。 - MCP 调参兼容直接指定控件或按控件组提交。 +- MCP 客户端可在写入时按需取回一至两个笔迹变化控件的有效旧值和新值。 - 可用 `PANACHE_MCP_PRESERVE_REVIEWS=1` 在改稿和打印期间保留原有检查记录。 - MCP 在多节稿件的逐页复盘中提示节号和节内页码,方便从中断处继续核对。 - MCP 可按稿件版本、节号和页码只读找回已存的整页复盘;缺少记录时明确返回空结果。 diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index 5f482389..6b91334b 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -128,6 +128,8 @@ cargo build --locked --release -p panache-mcp 如果字像贴在照片上,在照片整页复查的 `photo_appearance` 中取 `preview_arguments` 再调用一次 `preview_handwriting`。有页内文字基线样本时,这组参数会给出该版本一处字迹附近的原像素底纸和成品裁图;也可以自己圈选。对照邻近印字或横线的边缘清晰度、墨色深浅,再看字号与可写空间是否相称。用 `describe_controls` 指定稿件、版本和 `ink`、`layout` 或 `typography` 参数组可查当前值。正文的柔化和粗细以投影前纸面像素为单位,透明度用百分比。仅修改墨迹组参数时会保留已完成的单字移位和透视调整;更换字体、字号或参考线后应在新版本重新检查选区。改一版后,对同一选区加入 `compare_revision` 比较。只有文字结果的客户端可转述测量,请用户看图判断观感。 +客户端已知目标值时,可在 `tune_handwriting` 中同时传 `changes={"perturb_theta_sigma":0.07}` 和 `readback_variation=["perturb_theta_sigma"]`。成功回执的 `effective_changes` 给出写入前后的有效值,可省去写前、写后各一次查询。最多点名本次提交的两个 `variation` 控件。提交 `null` 时读回继承值,有效值相同的键会省略。若要根据旧值决定改多少,仍应先用 `describe_controls` 读取该稿当前版本的值。 + 需要保留手动移字时,在 `tune_handwriting` 顶层传入 `preserve_local_adjustments=true`。例如,稿件中仍有字形调整时,更改 `variation.perturb_theta_sigma` 会返回一个受影响的节号,稿件停留在原版本。只更改墨迹或相机元数据仍可保存。被拒绝后应保持 `true`。只有用户明确同意新布局不再应用这些手动调整时,才可传 `false`;旧版仍可回看。 例如,先前已确认行距 56、左边距 67,后来要求恢复导入时的参考线并保留这两个数值。在同一次调用中传 `paper_guides=[]` 和 `changes={"line_spacing":56,"left_margin":67}`;想让文字重新跟随底纸时,省略相应数值。如果之前摆好的字也必须留在原位,再传 `preserve_local_adjustments=true`。补回行距和边距仍会触发重排;若保护生效,整次请求停在原版本。 diff --git a/crates/panache-mcp/src/inputs.rs b/crates/panache-mcp/src/inputs.rs index 97cd277f..73efa535 100644 --- a/crates/panache-mcp/src/inputs.rs +++ b/crates/panache-mcp/src/inputs.rs @@ -115,6 +115,10 @@ pub struct Describe { #[derive(Deserialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct Tune { + /// Request before/after values for up to two variation keys in changes. effective_changes omits keys whose effective value stayed the same. + #[serde(default)] + #[schemars(length(max = 2))] + pub readback_variation: Vec, /// Set to true only when the user wants to preserve manual glyph adjustments. Reject reflow that would stop applying them. Ink and camera changes can still be saved. #[serde(default)] pub preserve_local_adjustments: bool, diff --git a/crates/panache-mcp/src/tuning.rs b/crates/panache-mcp/src/tuning.rs index 5c256524..c8ddb1ab 100644 --- a/crates/panache-mcp/src/tuning.rs +++ b/crates/panache-mcp/src/tuning.rs @@ -72,6 +72,22 @@ pub fn apply(state: &State, mut input: Tune) -> Result { } else { controls::merge(&draft.controls, &patch, &fonts)? }; + let keys = &input.readback_variation; + let before = if keys.is_empty() { + None + } else { + ensure!( + keys.len() <= 2 + && keys.iter().all(|k| input.changes.contains_key(k) + && controls::catalog()["variation"].get(k).is_some()), + "readback_variation must name up to two variation controls in changes" + ); + Some(serde_json::to_value(controls::parameters( + &draft, + 1, + &draft.controls, + )?)?) + }; if let Some(guides) = &input.paper_guides { let paper = draft .paper @@ -99,7 +115,16 @@ pub fn apply(state: &State, mut input: Tune) -> Result { changes != draft.controls || input.paper_guides.is_some(), "No control values changed" ); - controls::parameters(&draft, 1, &changes)?; + let params = controls::parameters(&draft, 1, &changes)?; + let mut delta = controls::Changes::new(); + if let Some(before) = before { + let after = serde_json::to_value(¶ms)?; + for k in keys { + if before[k] != after[k] { + delta.insert(k.clone(), json!({"before":before[k],"after":after[k]})); + } + } + } let preserve_layout = changes.keys().chain(draft.controls.keys()).all(|key| { controls::catalog()["ink"].get(key).is_some() || controls::catalog()["camera"].get(key).is_some() @@ -123,8 +148,9 @@ pub fn apply(state: &State, mut input: Tune) -> Result { font.as_ref().map(|(k, v)| (k.as_str(), v.as_slice())), &details, )?; - Ok(reply( - format!("Saved revision {next}."), - json!({"draft_id":draft.id,"revision":next,"paper":paper.map(|p|p.summary()),"controls":changes,"fine_layout":if preserve_layout { "preserved" } else { "inspect_again" }}), - )) + let mut receipt = json!({"draft_id":draft.id,"revision":next,"paper":paper.map(|p|p.summary()),"controls":changes,"fine_layout":if preserve_layout { "preserved" } else { "inspect_again" }}); + if !keys.is_empty() { + receipt["effective_changes"] = json!(delta); + } + Ok(reply(format!("Saved revision {next}."), receipt)) } diff --git a/crates/panache-mcp/tests/smoke.py b/crates/panache-mcp/tests/smoke.py index 2bb2c069..2e0e511b 100644 --- a/crates/panache-mcp/tests/smoke.py +++ b/crates/panache-mcp/tests/smoke.py @@ -19,6 +19,7 @@ import coursework_form import review_comparison +from first_use import tables from mcp_client import call from mcp import ClientSession, StdioServerParameters @@ -143,7 +144,7 @@ async def mixed_script_sample(client): assert png(await call(client, "preview_handwriting", **key)) == primary -async def handwriting_variation_sample(client): +async def handwriting_variation_sample(client, home): markdown = "样品 A 的质量为 12.5 g。" saved = (await call(client, "save_section", markdown=markdown, style={"seed": 17})).structuredContent key = {"draft_id": saved["draft_id"]} @@ -155,6 +156,7 @@ async def handwriting_variation_sample(client): tuned = await call(client, "tune_handwriting", **key, expected_revision=1, preserve_local_adjustments=True, changes={"variation": {"perturb_theta_sigma": 0.07}}) assert tuned.structuredContent["controls"]["perturb_theta_sigma"] == 0.07 + assert "effective_changes" not in tuned.structuredContent loose = png(await call(client, "preview_handwriting", **key)) assert loose != base strike = (await call(client, "describe_controls", **key, group="strike")).structuredContent @@ -167,6 +169,45 @@ async def handwriting_variation_sample(client): source = (await call(client, "read_section", **key, view="source")).structuredContent assert source["markdown"] == markdown + async def values(revision): + response = await call(client, "describe_controls", **key, revision=revision, group="variation") + return response.structuredContent["values"] + + tilt, shift = "perturb_theta_sigma", "perturb_x_sigma" + before = await values(3) + one = await call(client, "tune_handwriting", **key, expected_revision=3, + changes={tilt: 0.09}, readback_variation=[tilt]) + after = await values(4) + assert after[tilt] > before[tilt] + assert one.structuredContent["effective_changes"] == {tilt: {"before": before[tilt], "after": after[tilt]}} + + two = await call(client, "tune_handwriting", **key, expected_revision=4, + changes={tilt: None, shift: 1.5}, readback_variation=[tilt, shift]) + reset = await values(5) + assert reset[tilt] == (await values(1))[tilt] and reset[shift] == 1.5 + assert two.structuredContent["effective_changes"] == { + k: {"before": after[k], "after": reset[k]} for k in (tilt, shift) + } + + proposed = {tilt: 0.11, shift: 2, "ink_depth_sigma": 9} + unchanged = tables(home) + for revision, keys, changes, error in ( + (4, [tilt], proposed, "Revision conflict"), + (5, [shift], {tilt: 0.11}, "readback_variation"), + (5, ["font_size"], {"font_size": 36}, "readback_variation"), + (5, list(proposed), proposed, "readback_variation"), + ): + rejected = await client.call_tool("tune_handwriting", { + **key, "expected_revision": revision, "changes": changes, "readback_variation": keys, + }) + assert rejected.isError and error in rejected.content[0].text + assert tables(home) == unchanged + + # Saving an explicit override at the inherited value does not change the effective value. + equal = await call(client, "tune_handwriting", **key, expected_revision=5, + changes={tilt: reset[tilt]}, readback_variation=[tilt]) + assert equal.structuredContent["effective_changes"] == {} + async def placement_pixels(client): saved = (await call(client, "save_section", markdown="字", style={"seed": 17})).structuredContent @@ -353,7 +394,7 @@ async def smoke(command, arguments, out): ) assert failed.isError await mixed_script_sample(client) - await handwriting_variation_sample(client) + await handwriting_variation_sample(client, Path(temp)) await placement_pixels(client) await coursework_form.exercise(client, Path(temp)) comparison_key, reviewed_id, user_quote = await review_comparison.exercise(client, Path(temp), call) From dd60477b3a8f63cf2f9e503f79fe2c7c05af05e7 Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Wed, 25 Nov 2026 22:18:33 +0800 Subject: [PATCH 10/11] =?UTF-8?q?fix(crates/panache-mcp):=20=E5=8F=AA?= =?UTF-8?q?=E6=8C=89=E8=81=8A=E5=A4=A9=E5=AE=A2=E6=88=B7=E7=AB=AF=E7=A1=AE?= =?UTF-8?q?=E8=AE=A4=E7=9A=84=E6=96=B9=E5=BC=8F=E4=BA=A4=E4=BB=98=E5=AF=BC?= =?UTF-8?q?=E5=87=BA=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:工具回复含有 PDF 或 ZIP 时,纯文字聊天仍可能没有可点击的附件,服务器路径也只在运行 Panache 的电脑上有效。 解决手段:在工具说明和导出回执中区分客户端给出下载链接、确认展示附件和未确认三种情况,并同步文档与专项回归。 收益:用户可按聊天客户端确认的链接或附件取件,纯文字窗口也能得到准确的本地取件位置。 --- crates/panache-mcp/README.md | 2 +- crates/panache-mcp/src/delivery.rs | 2 +- crates/panache-mcp/src/main.rs | 2 +- crates/panache-mcp/tests/first_use.py | 4 ++++ 4 files changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index 6b91334b..b049e44f 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -52,7 +52,7 @@ cargo build --locked --release -p panache-mcp 可以先说「用这段话给我看第一页」,看过后说「字大一点」,再说「就用这一版」。客户端按同一稿件的版本号取预览和导出。查看小样使用 `preview_handwriting(view="image")`,无需创建检查单。 -想在聊天里拿到文件时,能处理 MCP 内嵌文件的客户端可在导出时传 `include_file=true`,把收到的 PDF 或 ZIP 作为附件显示给用户。512 KiB 以内的完整文件可以随回复传送。更大的文件仍在运行 Panache 的电脑上;两端共用磁盘时可直接打开返回的路径。只有客户端已经提供可打开的附件或链接时,才告诉用户「附件在这里」。 +想在聊天里拿到文件时,能处理 MCP 内嵌文件的客户端可在导出时传 `include_file=true`,把收到的 PDF 或 ZIP 作为附件显示给用户。512 KiB 以内的完整文件可以随回复传送。更大的文件仍在运行 Panache 的电脑上;两端共用磁盘时可直接打开返回的路径。聊天客户端给出用户可打开的下载链接时,直接把原链接交给用户;确认已展示附件但没有链接时,告诉用户在聊天附件中取件。`file_transfer.status=included` 表示工具回复带有文件内容。纯文字窗口或尚无客户端确认时,说明文件已导出,并按本机路径给出取件位置;这个路径和内嵌资源 URI 都不能当作下载链接。 客户端从内嵌资源取出文件后,应由客户端生成自己的下载入口,不依赖模型在回复里拼链接。资源里的 `panache-export:///…` 仅用于标识,不是下载地址。把交付状态和已经可用的下载入口交给模型即可,不要把文件的 Base64 内容放进模型上下文或普通日志。 diff --git a/crates/panache-mcp/src/delivery.rs b/crates/panache-mcp/src/delivery.rs index 8ebb01a9..fcb4016c 100644 --- a/crates/panache-mcp/src/delivery.rs +++ b/crates/panache-mcp/src/delivery.rs @@ -36,7 +36,7 @@ pub(super) fn include_file(result: &mut CallToolResult, file: File, path: &Path, result.content.push(ContentBlock::resource(resource)); ( "included", - "文件内容已传给客户端。请由客户端提供可打开的附件。", + "文件内容已写入工具回复。聊天客户端给出用户可用的下载链接时,在答复中原样贴出;只有聊天客户端确认附件已展示且未提供链接时,才请用户打开附件。没有这项确认时,请告知文件已导出,并用纯文本给出运行 Panache 的电脑上的取件路径。", ) } Ok(None) => ( diff --git a/crates/panache-mcp/src/main.rs b/crates/panache-mcp/src/main.rs index 4b481891..5fe170d7 100644 --- a/crates/panache-mcp/src/main.rs +++ b/crates/panache-mcp/src/main.rs @@ -576,7 +576,7 @@ impl Panache { } #[tool( - description = "Export the complete saved revision, in section order, to a local PDF (default) or ZIP of page PNGs. Returns the path, page count and review.unreviewed_pages in print order. For a print-and-report request return the file and missing pages. Only if a new check is requested, use preview_handwriting(view=review) at the exported revision. For ink-only PNG pages, set transparent_background=true with tune_handwriting (ink group) and export ZIP. PDF always includes paper. The path is on the server computer. If the client supports attachments, request include_file and use the embedded file to offer the user a download. Claim delivery only when the client makes the file available to the user. Use view=image to inspect the intended appearance without filing a check." + description = "Export the complete saved revision, in section order, to a local PDF (default) or ZIP of page PNGs. Returns the path, page count and review.unreviewed_pages in print order. For a print-and-report request return the file and missing pages. Only if a new check is requested, use preview_handwriting(view=review) at the exported revision. For ink-only PNG pages, set transparent_background=true with tune_handwriting (ink group) and export ZIP. PDF always includes paper. Use include_file for attachment-capable clients. If the chat client provides a user-visible download link, copy that exact link into your reply. If it confirms a visible attachment without a link, point to the attachment. Without that confirmation (including text-only chat), report local export and give the server path as plain text. Never turn that path or an embedded resource URI into a download link. Use view=image to inspect the intended appearance without filing a check." )] async fn export_handwriting( &self, diff --git a/crates/panache-mcp/tests/first_use.py b/crates/panache-mcp/tests/first_use.py index de6e2030..79c759db 100644 --- a/crates/panache-mcp/tests/first_use.py +++ b/crates/panache-mcp/tests/first_use.py @@ -99,6 +99,10 @@ async def generate(label, draft_id, revision, fmt, request_bytes=True, oversize= status = sc.get("file_transfer", {}).get("status") if opt and not oversize: assert status == "included" and len(blobs) == 1 + assert any( + b.type == "text" and "在答复中原样贴出" in b.text and "没有这项确认" in b.text + for b in res.content + ) assert blobs[0].mimeType == {"pdf":"application/pdf", "zip":"application/zip"}[fmt] # The simulated client can use only the reply for this copy. data = base64.b64decode(blobs[0].blob, validate=True) From 7b2f59b18bca9b60cd9409f1c8712e9db6b83d98 Mon Sep 17 00:00:00 2001 From: Helian Nuits Date: Wed, 25 Nov 2026 22:56:58 +0800 Subject: [PATCH 11/11] =?UTF-8?q?docs:=20=E9=81=BF=E5=BC=80=E9=A6=96?= =?UTF-8?q?=E6=AC=A1=E4=BD=BF=E7=94=A8=E4=B8=8E=20Linux=20=E4=BF=AE?= =?UTF-8?q?=E5=A4=8D=E7=9A=84=E6=9B=B4=E6=96=B0=E8=AE=B0=E5=BD=95=E5=86=B2?= =?UTF-8?q?=E7=AA=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 主分支的 Linux 打包修复与此草稿的首次使用说明占用了同一个未发布插入位置。把草稿说明移到相邻 MCP 条目中,不改任一句,也不改代码或工作流。 本地复算与 890126c 的三方试合并无冲突;保留 Linux 修复说明和两条 MCP 更新记录。只更新草稿分支,不合并或触发 CI。 --- CHANGELOG.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fd207267..ea29c9cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,11 +2,10 @@ ## 未发布 -- MCP 首次使用时会按材料介绍打印页、原纸填字和透明字迹。客户端可在导出时取回 512 KiB 以内的 PDF 或 ZIP,用作聊天附件。 - - 上传底纸后,纸张设置会直接显示从照片读到的制造商、设备型号、镜头和 ISO,缺少的项目仍可手动补填。 - MCP 新检查单记录首次入档时的稿件版本,历史查单会说明单据能证明的先后关系。 +- MCP 首次使用时会按材料介绍打印页、原纸填字和透明字迹。客户端可在导出时取回 512 KiB 以内的 PDF 或 ZIP,用作聊天附件。 - MCP 调参兼容直接指定控件或按控件组提交。 - MCP 客户端可在写入时按需取回一至两个笔迹变化控件的有效旧值和新值。 - 可用 `PANACHE_MCP_PRESERVE_REVIEWS=1` 在改稿和打印期间保留原有检查记录。