From 656819dee2212f324bcae42162ce7c8c983fbc29 Mon Sep 17 00:00:00 2001 From: SXP-Simon Date: Thu, 26 Nov 2026 19:36:15 +0800 Subject: [PATCH] =?UTF-8?q?feat(crates/panache-mcp):=20=E8=AE=A9=E5=AE=A2?= =?UTF-8?q?=E6=88=B7=E7=AB=AF=E6=8C=89=E9=9C=80=E5=8F=96=E5=9B=9E=E5=AF=BC?= =?UTF-8?q?=E5=87=BA=E7=9A=84=20PDF=20=E6=88=96=20ZIP?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 背景:只从 stdio 回复取文件的客户端,以前能看见路径,却拿不到生成的 PDF 或 ZIP 字节。 解决手段:导出时可设 include_file=true,从本次发布文件的句柄读取最多 512 KiB 原始内容。超过上限或读取失败时保留完整本机文件及导出回执,沿用主线 #31 的取件说明。 收益:支持内嵌文件的客户端能取回所选版本的真实内容,再通过自己的附件入口交给用户。 --- crates/panache-mcp/README.md | 2 + crates/panache-mcp/src/delivery.rs | 95 +++++++++ crates/panache-mcp/src/inputs.rs | 4 + crates/panache-mcp/src/main.rs | 15 +- crates/panache-mcp/src/storage.rs | 8 +- crates/panache-mcp/src/storage/tests.rs | 2 +- .../panache-mcp/tests/compare_export_files.py | 38 ++++ crates/panache-mcp/tests/export_file.py | 190 ++++++++++++++++++ 8 files changed, 344 insertions(+), 10 deletions(-) create mode 100644 crates/panache-mcp/src/delivery.rs create mode 100644 crates/panache-mcp/tests/compare_export_files.py create mode 100644 crates/panache-mcp/tests/export_file.py diff --git a/crates/panache-mcp/README.md b/crates/panache-mcp/README.md index e2c98e27..74bd3c72 100644 --- a/crates/panache-mcp/README.md +++ b/crates/panache-mcp/README.md @@ -104,6 +104,8 @@ uv run --script crates/panache-mcp/tests/last_page_provenance.py target/release/ 整稿上限为整理后 10 万字、200 页。完整导出只在调用导出工具时执行;客户端可以取消,提供进度令牌时可看到已完成页数。ZIP 逐页写盘,PDF 在内存中组装压缩页面后写盘。结果成功后才移入 `exports/`。稿件及历史持续保存在 `PANACHE_MCP_HOME`;Windows 默认是 `%LOCALAPPDATA%/Panache/mcp`,其他系统默认是 `$XDG_DATA_HOME/Panache/mcp` 或 `~/.local/share/Panache/mcp`。 +想在聊天里拿到文件时,能处理 MCP 内嵌文件的客户端可在导出时传 `include_file=true`,把收到的 PDF 或 ZIP 作为附件显示给用户。512 KiB 以内的完整文件可以随回复传送。更大的文件仍在运行 Panache 的电脑上;两端共用磁盘时可直接打开返回的路径。聊天客户端给出用户可打开的下载链接时,直接把原链接交给用户;确认已展示附件但没有链接时,告诉用户在聊天附件中取件。`file_transfer.status=included` 表示工具回复带有文件内容。纯文字窗口或尚无客户端确认时,说明文件已导出,并按本机路径给出取件位置;这个路径和内嵌资源 URI 都不能当作下载链接。 + ## 容量与清理 用 `storage_usage` 查询数据目录内常规文件的长度、数据库及其 WAL/SHM 大小、导出目录和所在卷剩余字节。可传 `draft_id` 查看一稿的正文历史、底纸、字体、逐页证据、评语等内容字节数。文件长度、SQLite 内容长度和磁盘分配量口径不同。跨稿复用同一字体的文件目前仍按稿保存。 diff --git a/crates/panache-mcp/src/delivery.rs b/crates/panache-mcp/src/delivery.rs new file mode 100644 index 00000000..fcb4016c --- /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", + "文件内容已写入工具回复。聊天客户端给出用户可用的下载链接时,在答复中原样贴出;只有聊天客户端确认附件已展示且未提供链接时,才请用户打开附件。没有这项确认时,请告知文件已导出,并用纯文本给出运行 Panache 的电脑上的取件路径。", + ) + } + 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 54638337..b9ae1b34 100644 --- a/crates/panache-mcp/src/inputs.rs +++ b/crates/panache-mcp/src/inputs.rs @@ -321,6 +321,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 81a4b5aa..bf81aa1f 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; @@ -619,7 +620,7 @@ impl Panache { } #[tool( - description = "Export a revision in section order as PDF (default, includes paper) or ZIP of PNGs. Return the path, page count and review.unreviewed_pages for print-and-report. To look up a listed page use read_section(view=review); only a requested new check needs preview_handwriting(view=review) at the exported revision. For transparent PNGs set transparent_background=true in the ink group before exporting ZIP. The returned path is local to the computer running Panache. With only this path, tell the user in their language: 'On the computer running Panache, open this file: '. Put the path in inline code, never in a download link. If the chat host confirms a visible attachment, point to that attachment instead; if its receipt gives a download URL, include that exact URL in the final reply." + description = "Export a revision in section order as PDF (default, includes paper) or ZIP of PNGs. Return the path, page count and review.unreviewed_pages for print-and-report. To look up a listed page use read_section(view=review); only a requested new check needs preview_handwriting(view=review) at the exported revision. For transparent PNGs set transparent_background=true in the ink group before exporting ZIP. For clients that can receive embedded files, request include_file. An embedded resource URI is not a user-visible download URL. The returned path is local to the computer running Panache. With only this path, tell the user in their language: 'On the computer running Panache, open this file: '. Put the path in inline code, never in a download link. If the chat host confirms a visible attachment, point to that attachment instead; if its receipt gives a download URL, include that exact URL in the final reply." )] async fn export_handwriting( &self, @@ -639,7 +640,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, image| { match reviewed_pages.get(&(section, page)) { @@ -699,10 +700,14 @@ impl Panache { "reviewed_pages_without_digest": without_digest, }); } - let message = format!("已导出 **{pages} 页**(版本 {})。该版已有 {reviewed}/{pages} 页复盘证据。{warning}{remaining}{pixel_warning}\n\n`{}`", draft.revision, path.display()); - Ok(reply(message, json!({ + let message = format!("已导出 **{pages} 页**(版本 {})。该版已有 {reviewed}/{pages} 页复盘证据。{warning}{remaining}{pixel_warning}\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": review, - }))) + })); + 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_export_files.py b/crates/panache-mcp/tests/compare_export_files.py new file mode 100644 index 00000000..6239f3b0 --- /dev/null +++ b/crates/panache-mcp/tests/compare_export_files.py @@ -0,0 +1,38 @@ +"""Audit two export_file.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() + + print(json.dumps({"matching_client_files": delivered, "required_files": len(samples), + "same_export_bytes": len(old)}, 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/export_file.py b/crates/panache-mcp/tests/export_file.py new file mode 100644 index 00000000..7a8ee7b1 --- /dev/null +++ b/crates/panache-mcp/tests/export_file.py @@ -0,0 +1,190 @@ +# /// script +# dependencies = ["mcp>=1.12,<2", "Pillow"] +# /// +"""Check selected revisions and embedded exports 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 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 / "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 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) + 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 + + # Export an approved revision after a newer revision exists. + 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) + + # Compare the client ZIP against the selected worksheet preview. + photo = HERE / "fixtures/ruled.png" + 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) + 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) + 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") + 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)))