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
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@

## 未发布

- MCP 新检查单记录首次入档时的稿件版本,历史查单会说明单据能证明的先后关系。
- MCP 调参兼容直接指定控件或按控件组提交。
- 可用 `PANACHE_MCP_PRESERVE_REVIEWS=1` 在改稿和打印期间保留原有检查记录。
- MCP 在多节稿件的逐页复盘中提示节号和节内页码,方便从中断处继续核对。
- MCP 可按稿件版本、节号和页码只读找回已存的整页复盘;缺少记录时明确返回空结果。
- MCP 客户端指南增加只翻旧检查记录的工具选择和调用示例。
- MCP 查旧检查单时可按新增原文定位上一版,并按该版实际排版查询指定节的末页。
- MCP 在作业和实验报告的笔迹建议中区分松散笔迹与偶发涂改,指明对应调节项和预览方法。

## v1.21.0 (2026-11-24)

- 在「关于与反馈 → 支持作者」可查看随应用提供的微信赞赏码。官网首页也可直接扫码支持 Simon。
Expand Down
9 changes: 7 additions & 2 deletions crates/handwriting-core/src/fine_edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ pub fn inspect_page(
return Err(Error::new("invalid_parameter", "Invalid fine edit page"));
}
let mut geometry = None;
crate::render::render_pages(request, cancel, page, |i, _, ink| {
let pages = crate::render::render_pages(request, cancel, page, |i, _, ink| {
if i + 1 == page
&& let Some(crate::render::PageInk::Fine(tiles)) = ink
{
Expand All @@ -73,7 +73,12 @@ pub fn inspect_page(
})?;
Ok((
document_key(&request.text, &request.params),
geometry.ok_or_else(|| Error::new("invalid_page", "Page not found"))?,
geometry.ok_or_else(|| {
Error::new(
"invalid_page",
format!("Page {page} not found; available page count: {pages}"),
)
})?,
))
}

Expand Down
5 changes: 5 additions & 0 deletions crates/handwriting-core/src/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,11 @@ pub(crate) fn render_output<F: FnMut(usize, RgbaImage) -> Result<()>>(
})
}

/// Run the normal pagination pass, discarding each page before compositing or encoding.
pub fn count_pages(request: &RenderRequest, cancel: &Cancellation) -> Result<usize> {
render_pages(request, cancel, usize::MAX, |_, _, _| Ok(()))
}

pub(crate) fn render_pages(
r: &RenderRequest,
cancel: &Cancellation,
Expand Down
12 changes: 10 additions & 2 deletions crates/panache-mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,21 +57,29 @@ cargo build --locked --release -p panache-mcp
| `list_drafts` | 找回本地稿件和最新版本。每批 20 条,可传 `offset`。 |
| `read_section` | `summary` 取版本、长度和样式;默认 `excerpt` 隐去正文中已识别的内嵌图片数据;`source` 读取精确 Markdown。后两种视图按字符分页,默认 1000 字,单次最多 4000 字。 |
| `preview_handwriting` | 默认返回首页 PNG。用 `section`、`page` 查看指定节中的一页,两者从 1 开始。 |
| `export_handwriting` | 按节顺序导出整份稿件,返回绝对路径、版本和实际页数。格式可选 `pdf` 或 `zip`,ZIP 从 `0.png` 开始编号。 |
| `describe_controls` | 先列参数组,再按 `group` 查看单位、范围和枚举值。附上 `draft_id` 和 `revision` 可读取该版的实际值。 |
| `export_handwriting` | 按节顺序导出整份稿件,返回绝对路径、版本和实际页数。格式可选 `pdf` 或 `zip`,ZIP 从 `0.png` 开始编号。导出结果的 `review.unreviewed_pages` 按打印顺序列出缺少整页复盘的 `section`、`page`。将这些坐标与导出的版本号传给 `preview_handwriting(view="review")` 可逐张补看。 |
| `describe_controls` | 调参时可将参数直接放在 `changes` 内,也可写成 `{"changes":{"variation":{"perturb_theta_sigma":0.07}}}`。先列参数组,再按 `group` 查看单位、范围和枚举值。附上 `draft_id` 和 `revision` 可读取该版的实际值。 |
| `tune_handwriting` | 可在原稿上更新参考线、导入本机字体,并一次提交多项全稿参数,如 `{"ink_opacity":85,"word_spacing":2}`。`null` 恢复建稿时的设置。 |
| `storage_usage` | 查询目录和逐稿用量,以及当前预算。 |
| `plan_cleanup` | 按稿列出废弃临时文件和受保护的已交付导出。 |
| `apply_cleanup` | 复核计划,仅清理选中的废弃临时文件。 |
| `annotate_review` | 将用户原话或模型观察挂到指定复盘 ID,保持稿件版本号。 |
| `adjust_glyphs` | 先用 `preview_handwriting(view="layout")` 取编号和坐标,再按同一节、页和版本调整选中字形。 |

若本次只改稿、打印和统计缺单页,可在客户端的 MCP 服务配置中设置 `PANACHE_MCP_PRESERVE_REVIEWS=1`。该连接仍可正常调参、看图和导出,完整检查单与评语会保留原样。

例如用 `list_fonts(query="楷", source="system", limit=8)` 检索系统字体。把 `entries[].id` 用于建稿的 `style.font` 或调稿的 `changes.font`。随包字体继续接受原文件名。个人和系统字体会随稿保存,删除源文件后仍可预览历史版本。TTF、OTF 和 TTC/OTC 中带轮廓、单个字面大小不超过 32 MiB 的字体可供选择。

桌面与 MCP 共享“我的字体”目录,`list_fonts` 的 `user_dir` 给出绝对路径。Windows 使用 `%LOCALAPPDATA%/Panache/fonts`,macOS 使用 `~/Library/Application Support/Panache/fonts`,Linux 使用 `$XDG_DATA_HOME/Panache/fonts`(默认 `~/.local/share/Panache/fonts`)。可通过 `PANACHE_USER_FONT_DIR` 指定绝对路径。把字体放入后调用 `list_fonts(source="user", refresh=true)`。

面向 AI 客户端的调用示例、披露边界和测量口径见[工具设计](tool-design.md)。

查归属某版、某节、某一页的整页复盘,可用 `read_section(view="review", revision=3, section=2, page=1, draft_id=…)`。返回最近记录在这个位置的测量值、原检查单编号及注明来源的评语。该位置没有记录时返回 `status="no_recorded_review"`;直接按数字页码查单不会排版,也不判断该页是否实际存在。已知检查单编号时仍可按 `review_id` 精确读取。

如果用户问“增加某段话以前,某一节最后那张验过吗”,把新增段落中独有的原文字串传给 `before_text`,目标节传 `section`,页码传 `page="last"`。服务端在该字串首次出现的前一版排出目标节的实际末页,只读取该位置的检查单。返回的 `before_text_match` 标明新增文字所在节和引入版本,顶层的 `revision`、`section`、`page` 标明查单位置。字串跨节重复或同节删后重加时,结果列出最早两个加入时点及对应的前一版。可查的正文节附有简短开头,便于区分补记所在节和实际要查的节。请用户选择,也可分版回答。按补记或末页查多节稿时需明确待查节号。无匹配或首次建稿就存在时,请核对原文或提供明确版本。末页定位会按该版字体和版式分页,不返回图片,也不会新增检查单。单据的 `revision` 表示受检版本,`filed_at_revision` 表示首次入档时稿件的最新版本。旧库没有保存这一信息的单据返回 `null`。回答“补记前验过吗”时请同时转述 `receipt_summary` 中的时间结论。

预览的页码在每一节内从 1 开始。翻过一节末页时,错误信息给出这节的实际页数,以及所查版本中下一节的起始页;历史版本已到末节时会提示到此为止。

长作业可以按题组或章节分次传入,每节从新页开始。需要连续排版的段落放在同一节,公式、表格、代码块也应完整放在一节内。追加时带上 `draft_id` 和上次返回的 `expected_revision`;修改已有节时再给出 `section`。另一位客户端抢先保存后,用 `read_section` 复核最新内容再提交。

每次保存只转换这一节,Markdown 原文和整理结果存入本地 SQLite。预览某节第 N 页时,引擎从该节开头排到第 N 页,只编码选中的一页。进程内保留最近生成的四张预览,修改其他节仍可复用。预览和导出传相同的 `revision` 可锁定稿件。种子和样式随稿保存,复现时需使用相同字体和引擎。
Expand Down
6 changes: 3 additions & 3 deletions crates/panache-mcp/src/controls.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,14 @@
"word_spacing_sigma": {"type":"number","min":0,"max":100,"unit":"px"},
"perturb_x_sigma": {"type":"number","min":0,"max":100,"unit":"px"},
"perturb_y_sigma": {"type":"number","min":0,"max":100,"unit":"px"},
"perturb_theta_sigma": {"type":"number","min":0,"max":3.14,"unit":"rad"},
"perturb_theta_sigma": {"type":"number","min":0,"max":3.14,"unit":"rad","description":"Variation in glyph tilt. For a slightly hurried hand keep the font and seed; try increasing the current value by 0.02 rad, then preview the same line and check digits, units and alignment. perturb_x_sigma and perturb_y_sigma vary position in paper-space pixels."},
"ink_depth_sigma": {"type":"number","min":0,"max":255,"unit":"intensity"}
},
"strike": {
"strikethrough_probability": {"type":"number","min":0,"max":1,"unit":"probability"},
"strikethrough_probability": {"type":"number","min":0,"max":1,"unit":"probability","description":"For requested occasional corrections: randomly insert a crossed-out extra character before the intended text when monospaced=false. Try 0.005 for a sparse sample; a short page may have none. Compare the same line with only probability changed; confirm a visible crossed-out character before reporting one. Check reflow and numbers. For a looser hand alone, leave this unchanged. Exact placement on a chosen word is unsupported; Markdown ~~text~~ is stripped to text."},
"strikethrough_width": {"type":"number","min":0,"max":100,"unit":"px"},
"strikethrough_length_sigma": {"type":"number","min":0,"max":100,"unit":"px"},
"strikethrough_width_sigma": {"type":"number","min":0,"max":100,"unit":"px"},
"strikethrough_angle_sigma": {"type":"number","min":0,"max":3.14,"unit":"rad"}
"strikethrough_angle_sigma": {"type":"number","min":0,"max":3.14,"unit":"deg"}
}
}
27 changes: 27 additions & 0 deletions crates/panache-mcp/src/controls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,33 @@ pub fn catalog() -> &'static Changes {
})
}

/// Normalize catalog groups at the input boundary. A scalar control (e.g. ink)
/// can share its name with a group; only an object selects the grouped syntax.
pub fn flatten_patch(changes: Changes) -> Result<Changes> {
let mut patch = Changes::new();
for (key, value) in changes {
if let (Some(group), Value::Object(fields)) = (catalog().get(&key), &value) {
ensure!(!fields.is_empty(), "Empty control group {key}");
for (field, setting) in fields {
ensure!(
group.get(field).is_some(),
"Unknown control {field} in group {key}"
);
ensure!(
patch.insert(field.clone(), setting.clone()).is_none(),
"Duplicate control {field}"
);
}
} else {
ensure!(
patch.insert(key.clone(), value).is_none(),
"Duplicate control {key}"
);
}
}
Ok(patch)
}

pub fn merge(current: &Changes, patch: &Changes, fonts: &[String]) -> Result<Changes> {
ensure!(!patch.is_empty(), "Supply at least one control");
let mut next = current.clone();
Expand Down
153 changes: 153 additions & 0 deletions crates/panache-mcp/src/drafts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ fn concurrent_first_opens_share_a_complete_schema() -> Result<()> {
}

pub struct Snapshot<'a> {
pub latest_revision: u32,
pub revision: u32,
pub style: Style,
pub controls: crate::controls::Changes,
Expand All @@ -55,6 +56,59 @@ pub struct Snapshot<'a> {
}

impl Snapshot<'_> {
pub fn review_section(&self, requested: Option<u32>) -> Result<u32> {
if let Some(section) = requested {
ensure!(section > 0, "section starts at 1");
let exists: bool = self.drafts.connect()?.query_row(
"SELECT EXISTS(SELECT 1 FROM sections WHERE draft=? AND number=? AND revision<=?)",
params![self.id, section, self.revision],
|row| row.get(0),
)?;
ensure!(
exists,
"第 {} 版还没有第 {section} 节。请保留所查版本和页码,按待查正文选择已有的节:{}",
self.revision,
self.drafts
.review_section_choices(self.id, self.revision)?
.join(" · ")
);
return Ok(section);
}
let choices = self.drafts.review_section_choices(self.id, self.revision)?;
ensure!(
choices.len() == 1,
"请按待查的正文选择 section。第 {} 版可查的节:{}",
self.revision,
choices.join(" · ")
);
Ok(1)
}

pub fn page_error(&self, section: u32, mut error: handwriting_core::Error) -> anyhow::Error {
if error.code != "invalid_page" {
return error.into();
}
let next = self.drafts.connect().and_then(|db| {
Ok(db.query_row(
"SELECT MIN(number) FROM sections WHERE draft=? AND number>? AND revision<=?",
params![self.id, section, self.revision],
|row| row.get::<_, Option<u32>>(0),
)?)
});
let hint = match next {
Ok(Some(next)) => {
format!("To continue after this section, use section={next}, page=1.")
}
Ok(None) => "This is the last section at this revision.".to_owned(),
Err(_) => "Check the available sections before continuing.".to_owned(),
};
error.message = format!(
"{} (revision {}, section {section}). Pages start at 1 within each section. {hint}",
error.message, self.revision
);
error.into()
}

pub fn has_font(&self, handle: &str) -> Result<bool> {
Ok(self.drafts.connect()?.query_row(
"SELECT EXISTS(SELECT 1 FROM draft_fonts WHERE draft=? AND handle=?)",
Expand Down Expand Up @@ -308,6 +362,104 @@ impl Drafts {
.collect::<rusqlite::Result<Vec<_>>>()?;
Ok(json!({"drafts":entries,"offset":offset}))
}
// Bound the source prefix in SQLite, including when a section starts with an inline photo.
fn review_section_choices(&self, id: &str, revision: u32) -> Result<Vec<String>> {
let db = self.connect()?;
let mut stmt = db.prepare(
"SELECT number, substr(source,1,48) FROM sections JOIN (
SELECT number, max(revision) AS revision FROM sections
WHERE draft=?1 AND revision<=?2 GROUP BY number ORDER BY number LIMIT 5
) USING(number,revision) WHERE draft=?1 ORDER BY number",
)?;
let mut choices = Vec::new();
let mut rows = stmt.query(params![id, revision])?;
while let Some(row) = rows.next()? {
if choices.len() == 4 {
choices.push("其余节可用 view=excerpt 查阅".to_owned());
break;
}
let number: u32 = row.get(0)?;
let prefix: String = row.get(1)?;
let before_image = prefix
.find("![")
.into_iter()
.chain(prefix.find("data:"))
.min()
.unwrap_or(prefix.len());
let text = prefix[..before_image]
.split_whitespace()
.collect::<Vec<_>>()
.join(" ");
choices.push(format!("section={number} {}", json!(text)));
}
Ok(choices)
}

/// Find a single transition from absent to present across all versions of all sections.
pub fn text_introduction(&self, id: &str, text: &str) -> Result<(u32, u32)> {
ensure!(
!text.trim().is_empty() && text.chars().count() <= 160,
"before_text needs 1..160 characters from the saved Markdown"
);
let db = self.connect()?;
let mut statement = db.prepare(
"WITH versions AS (
SELECT number,revision,instr(source,?2)>0 AS present
FROM sections WHERE draft=?1
), changes AS (
SELECT number,revision,present,
lag(present,1,0) OVER (PARTITION BY number ORDER BY revision) AS previously_present
FROM versions
)
SELECT number,revision FROM changes WHERE present AND NOT previously_present
ORDER BY revision,number LIMIT 3",
)?;
let matches = statement
.query_map(params![id, text], |row| {
Ok((row.get::<_, u32>(0)?, row.get::<_, u32>(1)?))
})?
.collect::<rusqlite::Result<Vec<_>>>()?;
let &(section, revision) = matches.first().context(
"No section contains before_text. Read the source for a literal fragment or specify a revision."
)?;
if matches.len() > 1 {
let mut message = String::from(
"这段原文有多个加入时点。请让用户确认是首次加入之前,还是后来再次加入之前;也可分别核对并逐版列出,未确认时不要代选。",
);
let same_section = matches[0].0 == matches[1].0;
for (number, added) in matches.iter().take(2) {
if same_section {
message.push_str(&format!("\n第 {added} 版加入了这段原文。"));
} else {
message.push_str(&format!("\n第 {added} 版在第 {number} 节加入了这段原文。"));
}
if *added == 1 {
message.push_str("这是初稿,之前没有稿件。");
} else {
let before = added - 1;
let choices = self.review_section_choices(id, before)?;
message.push_str(&format!(
"加入前查 revision={before};该版可查的正文:{}",
choices.join(" · ")
));
}
}
if matches.len() > 2 {
message.push_str(
"\n这里只列最早两次,另有加入时点。可通过 trajectory 和 source 核对。",
);
}
anyhow::bail!(
"{message}\n所补文字只用来认版本。请按用户要查的正文选择 section,保留 page,移除 before_text 后按明确版本查单。"
);
}
ensure!(
revision > 1,
"before_text already occurs in the first revision; no earlier draft exists."
);
Ok((section, revision))
}

pub fn snapshot<'a>(&'a self, id: &'a str, requested: Option<u32>) -> Result<Snapshot<'a>> {
let (latest, style, layout): (u32, String, Option<String>) = self
.connect()?
Expand Down Expand Up @@ -339,6 +491,7 @@ impl Drafts {
"SELECT layout FROM paper_layouts WHERE draft=? AND revision<=? ORDER BY revision DESC LIMIT 1",
params![id,revision], |r| r.get(0)).optional()?;
Ok(Snapshot {
latest_revision: latest,
controls,
settings_revision,
layout_revision,
Expand Down
Loading
Loading