Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crates/panache-mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 内容长度和磁盘分配量口径不同。跨稿复用同一字体的文件目前仍按稿保存。
Expand Down
95 changes: 95 additions & 0 deletions crates/panache-mcp/src/delivery.rs
Original file line number Diff line number Diff line change
@@ -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<Option<Vec<u8>>> {
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(())
}
}
4 changes: 4 additions & 0 deletions crates/panache-mcp/src/inputs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,10 @@ pub struct Export {
pub revision: Option<u32>,
/// PDF includes the paper. ZIP contains page PNGs and respects the transparent_background ink control.
pub format: Option<Format>,
/// 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)]
Expand Down
15 changes: 10 additions & 5 deletions crates/panache-mcp/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
mod controls;
mod delivery;
mod drafts;
mod engine;
mod inputs;
Expand Down Expand Up @@ -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: <path>'. 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: <path>'. 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,
Expand All @@ -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)) {
Expand Down Expand Up @@ -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)
}
Expand Down
8 changes: 4 additions & 4 deletions crates/panache-mcp/src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<usize>,
{
Expand Down Expand Up @@ -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<Value> {
Expand Down
2 changes: 1 addition & 1 deletion crates/panache-mcp/src/storage/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})?;
Expand Down
38 changes: 38 additions & 0 deletions crates/panache-mcp/tests/compare_export_files.py
Original file line number Diff line number Diff line change
@@ -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)
Loading