Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

feat: implement download request handling and improve PDF preview behavior

myhlolif16b99af4af6
diff --git a/docs/next/cli/mineru-kit-gradio.md b/docs/next/cli/mineru-kit-gradio.md
index 8a548da8..335530ad 100644
--- a/docs/next/cli/mineru-kit-gradio.md
+++ b/docs/next/cli/mineru-kit-gradio.md
@@ -102,6 +102,8 @@ Gradio 首先发现 `/v1/health` 和 `/v1/tiers`,然后通过 `MinerUApiParser
下载图标位于右侧结果栏的标签行最右端,鼠标悬停或键盘聚焦即可展开菜单。菜单包含 ZIP、HTML、DOCX、LaTeX bundle、EPUB 和 PDF。HTML、DOCX、EPUB、PDF 和 LaTeX 不作为 API job 输出请求,而是在用户点击菜单后从本次保存的 Middle JSON 按需渲染。LaTeX 下载包包含 `.tex` 与 `images/`,可交给 XeLaTeX 使用;Gradio 不自动执行 TeX 编译。
+每次选择格式后,按钮会显示“准备中”,文件就绪后自动开始下载,无需再次点击。再次下载同一格式复用已有文件;生成失败时显示错误并允许重试。清除、更换文件或重新解析会使旧下载请求失效。
+
每次解析的文件保存在独立的 `output-dir/gradio/<run-id>/` 目录,包含源文件、Middle JSON、基础文本产物以及可选的 `origin.pdf`、`layout.pdf` 和图片资源。路径只向 Gradio 暴露在配置的 output root 内。
## 预览与兼容边界
diff --git a/mineru/kit/gradio/app.py b/mineru/kit/gradio/app.py
index 35fa48d8..3d48aa1e 100644
--- a/mineru/kit/gradio/app.py
+++ b/mineru/kit/gradio/app.py
@@ -111,6 +111,8 @@ _KIT_MENU_CSS = """
}
.mineru-kit-download-options :is(button, a):hover { background: var(--background-fill-secondary, #f3f4f6); }
.mineru-kit-empty-preview { min-height: 160px; display: grid; place-items: center; opacity: .65; }
+/* gradio-pdf 0.0.22 的内部容器不识别 hidden,显式隐藏空组件,同时保持挂载。 */
+.mineru-kit-pdf-preview.mineru-kit-pdf-empty { display: none !important; }
.mineru-kit-image-preview img { max-height: var(--mineru-pdf-page-height, 720px); object-fit: contain; }
@media (max-width: 900px) {
.mineru-kit-workspace { flex-direction: column !important; }
@@ -196,9 +198,17 @@ def _preview_update(gr: Any, value: object, *, visible: bool) -> Any:
return gr.update(value=value, visible=visible)
-def _download_updates(gr: Any, *, interactive: bool) -> tuple[Any, ...]:
- """清空全部下载按钮的旧文件,并统一切换交互状态。"""
- return tuple(gr.update(value=None, interactive=interactive) for _format_name, _label in _DOWNLOAD_FORMATS)
+def _pdf_preview_update(gr: Any, value: str | None) -> Any:
+ """让空 PDF 保持挂载,并兼容旧版自定义组件不识别 hidden 的视觉隐藏行为。"""
+ classes = ["mineru-kit-pdf-preview"]
+ if not value:
+ classes.append("mineru-kit-pdf-empty")
+ return gr.update(value=value, visible=True if value else "hidden", elem_classes=classes)
+
+
+def _download_updates(gr: Any, *, interactive: bool, run_id: str = "") -> tuple[Any, ...]:
+ """同步当前结果标识,并恢复全部下载按钮的标签与交互状态。"""
+ return (run_id, *(gr.update(value=label, interactive=interactive) for _format_name, label in _DOWNLOAD_FORMATS))
def _latex_delimiters(delimiters_type: Literal["a", "b", "all"]) -> list[dict[str, Any]]:
@@ -325,9 +335,10 @@ def build_gradio_app(
pdf_preview = PDF(
label="文档预览",
interactive=False,
- visible=False,
+ # 预先挂载空组件,避免 gradio-pdf 首次带值挂载时漏掉文件加载。
+ visible="hidden",
height=720,
- elem_classes=["mineru-kit-pdf-preview"],
+ elem_classes=["mineru-kit-pdf-preview", "mineru-kit-pdf-empty"],
)
image_preview = gr.Image(
label="文档预览",
@@ -385,13 +396,14 @@ def build_gradio_app(
):
download_buttons: dict[str, Any] = {}
for format_name, label in _DOWNLOAD_FORMATS:
- download_buttons[format_name] = gr.DownloadButton(
+ download_buttons[format_name] = gr.Button(
label,
visible=True,
interactive=False,
size="sm",
elem_classes=[f"mineru-kit-download-{format_name}"],
)
+ download_notice = gr.HTML(value="", elem_classes=["mineru-kit-download-notice"])
if enable_example:
examples = _example_files(file_types)
@@ -399,6 +411,10 @@ def build_gradio_app(
gr.Examples(examples=examples, inputs=input_file, label="示例", elem_id="mineru-kit-examples")
artifact_state = gr.State(value=None)
+ active_run_id = gr.Textbox(value="", visible=False)
+ download_files = {name: gr.File(visible=False, interactive=False) for name, _label in _DOWNLOAD_FORMATS}
+ download_requests = {name: gr.Textbox(value="", visible=False) for name, _label in _DOWNLOAD_FORMATS}
+ download_receipts = {name: gr.Textbox(value="", visible=False) for name, _label in _DOWNLOAD_FORMATS}
clear_button.add(
[
input_file,
@@ -420,7 +436,7 @@ def build_gradio_app(
reset_result = (_status_html(_DEFAULT_STATUS), "", "", "", None, *_download_updates(gr, interactive=False))
if not file_path:
return (
- _preview_update(gr, None, visible=False),
+ _pdf_preview_update(gr, None),
_preview_update(gr, None, visible=False),
_preview_update(gr, "", visible=False),
_preview_update(gr, '<div class="mineru-kit-empty-preview">暂无源文档预览</div>', visible=True),
@@ -429,7 +445,7 @@ def build_gradio_app(
suffix = _file_suffix(file_path)
if suffix in PDF_EXTENSIONS:
return (
- _preview_update(gr, file_path, visible=True),
+ _pdf_preview_update(gr, file_path),
_preview_update(gr, None, visible=False),
_preview_update(gr, "", visible=False),
_preview_update(gr, '<div class="mineru-kit-empty-preview">源文档预览</div>', visible=False),
@@ -437,7 +453,7 @@ def build_gradio_app(
)
if suffix in IMAGE_EXTENSIONS:
return (
- _preview_update(gr, None, visible=False),
+ _pdf_preview_update(gr, None),
_preview_update(gr, file_path, visible=True),
_preview_update(gr, "", visible=False),
_preview_update(gr, '<div class="mineru-kit-empty-preview">源文档预览</div>', visible=False),
@@ -445,7 +461,7 @@ def build_gradio_app(
)
if _is_office(file_path):
return (
- _preview_update(gr, None, visible=False),
+ _pdf_preview_update(gr, None),
_preview_update(gr, None, visible=False),
_preview_update(
gr,
@@ -456,7 +472,7 @@ def build_gradio_app(
*reset_result,
)
return (
- _preview_update(gr, None, visible=False),
+ _pdf_preview_update(gr, None),
_preview_update(gr, None, visible=False),
_preview_update(gr, "", visible=False),
_preview_update(gr, '<div class="mineru-kit-empty-preview">该格式暂无源文档预览</div>', visible=True),
@@ -465,6 +481,38 @@ def build_gradio_app(
private_event_kwargs = _private_event_kwargs(gr)
+ download_script = _resource_text("gradio_download.js")
+
+ def download_js(action: str, format_name: str = "", label: str = "") -> str:
+ """为下载事件绑定明确的动作与格式,复用同一份前端状态处理脚本。"""
+ arguments = ", ".join(json.dumps(value) for value in (action, _DOWNLOAD_FORMATS, format_name, label))
+ return f"(...args) => ({download_script})({arguments}, ...args)"
+
+ def reset_download_ui() -> tuple[Any, ...]:
+ """返回下载组件的初始状态,为转换提供可可靠串联的完成事件。"""
+ count = len(_DOWNLOAD_FORMATS)
+ return ("", *((None,) * count), *(("",) * count * 2), *_download_updates(gr, interactive=False)[1:], "")
+
+ download_reset_outputs = [
+ active_run_id,
+ *download_files.values(),
+ *download_requests.values(),
+ *download_receipts.values(),
+ *download_buttons.values(),
+ download_notice,
+ ]
+
+ # 先在前端失效旧请求,再等待上传/清除/转换的 Python 回调,防止迟到的下载被触发。
+ gr.on(
+ triggers=[input_file.change, clear_button.click],
+ fn=None,
+ inputs=[],
+ outputs=download_reset_outputs,
+ js=download_js("reset"),
+ **private_event_kwargs,
+ )
+ active_run_id.change(fn=None, inputs=active_run_id, outputs=[], js=download_js("activate"), **private_event_kwargs)
+
def update_ocr_control(file_path: str | None) -> Any:
"""仅为原始 PDF 显示开关,并在更换或清除文件时重置为自动判断。"""
return gr.update(value=False, visible=_file_suffix(file_path) in PDF_EXTENSIONS)
@@ -499,6 +547,7 @@ def build_gradio_app(
markdown_source,
structured_source,
artifact_state,
+ active_run_id,
*download_buttons.values(),
]
@@ -557,7 +606,7 @@ def build_gradio_app(
"",
"",
"",
- gr.update(value=None, visible=False),
+ _pdf_preview_update(gr, None),
gr.update(value=None, visible=False),
gr.update(value="", visible=False),
gr.update(value='<div class="mineru-kit-empty-preview">暂无源文档预览</div>', visible=True),
@@ -637,12 +686,12 @@ def build_gradio_app(
markdown_for_gradio(markdown_text, artifacts),
markdown_text,
structured_text,
- gr.update(value=str(preview_path) if preview_path else None, visible=preview_path is not None),
+ _pdf_preview_update(gr, str(preview_path) if preview_path else None),
gr.update(value=str(source_path) if show_image_preview else None, visible=show_image_preview),
gr.update(value=office_html, visible=bool(office_html)),
gr.update(value=generic_html, visible=bool(generic_html)),
artifacts.as_state(),
- *_download_updates(gr, interactive=True),
+ *_download_updates(gr, interactive=True, run_id=artifacts.root.name),
)
task = asyncio.create_task(run_conversion())
@@ -689,6 +738,7 @@ def build_gradio_app(
office_preview,
generic_preview,
artifact_state,
+ active_run_id,
*download_buttons.values(),
]
# Gradio 在读取函数签名时需要真实的 Request 类型对象;注解在运行时补回以保持延迟导入。
@@ -698,7 +748,15 @@ def build_gradio_app(
event_kwargs["api_visibility"] = "public" if enable_api else "private"
else:
event_kwargs["api_name"] = "to_markdown" if enable_api else False
- convert_event = convert_button.click(
+ # 重置与转换必须显式串联;独立 click 监听可能在转换完成后才执行重置。
+ begin_conversion = convert_button.click(
+ fn=reset_download_ui,
+ inputs=[],
+ outputs=download_reset_outputs,
+ js=f"() => {{ ({download_js('reset')})(); return []; }}",
+ **private_event_kwargs,
+ )
+ convert_event = begin_conversion.then(
fn=convert_handler,
inputs=[input_file, tier, page_range, force_ocr],
outputs=convert_outputs,
@@ -723,6 +781,7 @@ def build_gradio_app(
office_preview,
generic_preview,
artifact_state,
+ active_run_id,
*download_buttons.values(),
]
@@ -733,7 +792,7 @@ def build_gradio_app(
"",
"",
"",
- gr.update(value=None, visible=False),
+ _pdf_preview_update(gr, None),
gr.update(value=None, visible=False),
gr.update(value="", visible=False),
gr.update(value='<div class="mineru-kit-empty-preview">暂无源文档预览</div>', visible=True),
@@ -744,14 +803,37 @@ def build_gradio_app(
clear_button.click(fn=reset_ui, inputs=[], outputs=reset_outputs, cancels=[convert_event], queue=False)
clear_button.click(fn=cancel_session_conversion, inputs=[], outputs=[], **private_event_kwargs)
- for format_name, _label in _DOWNLOAD_FORMATS:
- download_buttons[format_name].click(
+ for format_name, label in _DOWNLOAD_FORMATS:
+ begin_download = download_buttons[format_name].click(
+ fn=_download_request_handler,
+ inputs=active_run_id,
+ outputs=download_requests[format_name],
+ js=f"(...args) => [({download_js('begin', format_name, label)})(...args)[0]]",
+ **private_event_kwargs,
+ )
+ # 开始回执也必须经过前端令牌校验,避免慢请求在清除后重新显示旧的“准备中”。
+ begin_download.success(
+ fn=None,
+ inputs=[download_requests[format_name], active_run_id],
+ outputs=[download_buttons[format_name], download_notice],
+ js=download_js("busy", format_name, label),
+ **private_event_kwargs,
+ )
+ prepare_download = begin_download.then(
fn=_download_handler(format_name, output_root),
- inputs=artifact_state,
- outputs=download_buttons[format_name],
+ inputs=[artifact_state, download_requests[format_name]],
+ outputs=[download_files[format_name], download_receipts[format_name]],
queue=True,
+ show_progress="hidden",
api_name=False,
)
+ prepare_download.success(
+ fn=None,
+ inputs=[download_files[format_name], download_receipts[format_name], active_run_id],
+ outputs=[download_buttons[format_name], download_notice],
+ js=download_js("complete", format_name, label),
+ **private_event_kwargs,
+ )
demo._mineru_kit_css = app_css
demo._mineru_kit_js = app_js
@@ -882,12 +964,27 @@ def _private_event_kwargs(gr: Any) -> dict[str, Any]:
return {"queue": False, "api_name": False}
-def _download_handler(format_name: str, output_root: Path) -> Callable[[object], str]:
+def _download_request_handler(request_token: str) -> str:
+ """传回前端下载令牌以可靠触发后续事件,不直接修改可能已属于新文档的按钮。"""
+ return request_token if isinstance(request_token, str) else ""
+
+
+def _download_handler(format_name: str, output_root: Path) -> Callable[[object, str], tuple[str | None, str]]:
"""创建一个绑定格式和 output root 的 Gradio 下载回调。"""
- def handler(state: object) -> str:
- """从当前任务 State 生成或读取指定格式的下载文件。"""
- return render_download(state, format_name, allowed_root=output_root)
+ def handler(state: object, request_token: str) -> tuple[str | None, str]:
+ """校验请求所属结果,返回文件与回执;生成失败也交给前端按请求标识恢复按钮。"""
+ receipt = {"request": request_token, "error": ""}
+ try:
+ request = json.loads(request_token)
+ artifacts = RunArtifacts.from_state(state)
+ if request["run_id"] != artifacts.root.name:
+ raise ValueError("解析结果已变更,请重新下载。")
+ path = render_download(state, format_name, allowed_root=output_root)
+ return path, json.dumps(receipt, ensure_ascii=False)
+ except Exception as exc:
+ receipt["error"] = str(exc)
+ return None, json.dumps(receipt, ensure_ascii=False)
return handler
diff --git a/mineru/resources/gradio_download.js b/mineru/resources/gradio_download.js
new file mode 100644
index 00000000..0c018fff
--- /dev/null
+++ b/mineru/resources/gradio_download.js
@@ -0,0 +1,60 @@
+// 按结果标识协调下载请求、按钮状态和浏览器下载,丢弃旧文档的回执。
+(action, formats, format, label, ...args) => {
+ const state = window.__mineruGradioDownloads ??= { runId: "", sequence: 0, pending: new Map() };
+ // 用标准组件更新对象兼容 Gradio 5/6;空更新不会覆盖新文档的按钮状态。
+ const skip = () => ({ __type__: "update" });
+ const button = (value, interactive) => ({ __type__: "update", value, interactive });
+ // 下载失败文案仅作为文本展示,不能把服务端错误插入为活动 HTML。
+ const escapeHtml = (value) => String(value).replace(/[&<>"']/g, (char) => ({
+ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;",
+ })[char]);
+
+ if (action === "reset") {
+ state.runId = "";
+ state.pending.clear();
+ return [
+ "", ...formats.map(() => null), ...formats.map(() => ""), ...formats.map(() => ""),
+ ...formats.map(([, name]) => button(name, false)), "",
+ ];
+ }
+ if (action === "activate") {
+ if (state.runId !== args[0]) state.pending.clear();
+ state.runId = args[0] || "";
+ return [];
+ }
+ if (action === "begin") {
+ const [runId] = args;
+ if (!runId || state.runId !== runId || state.pending.has(format)) return [skip(), skip(), skip()];
+ const token = JSON.stringify({ run_id: runId, sequence: ++state.sequence });
+ state.pending.set(format, token);
+ return [token, button(`${label} · 准备中…`, false), ""];
+ }
+ if (action === "busy") {
+ const [token, runId] = args;
+ // 即使开始回执晚于换文件或清除,也只能修改当前仍在等待的同一个请求。
+ if (!token || state.pending.get(format) !== token || !runId || state.runId !== runId) return [skip(), skip()];
+ return [button(`${label} · 准备中…`, false), ""];
+ }
+ if (action === "complete") {
+ const [file, receiptText, runId] = args;
+ const receipt = JSON.parse(receiptText || "{}");
+ const token = state.pending.get(format);
+ // 已清除、已换文档或已消费的回执不得再次下载,也不得恢复旧按钮。
+ if (!token || token !== receipt.request || !runId || state.runId !== runId) return [skip(), skip()];
+ const request = JSON.parse(token);
+ if (request.run_id !== runId) return [skip(), skip()];
+ state.pending.delete(format);
+ if (receipt.error || !file?.url) {
+ const message = receipt.error || "未获得下载文件,请重试。";
+ return [button(label, true), `<div role="alert">${escapeHtml(label)} 下载失败:${escapeHtml(message)}</div>`];
+ }
+ const anchor = document.createElement("a");
+ anchor.href = file.url;
+ anchor.download = file.orig_name || "download";
+ document.body.appendChild(anchor);
+ anchor.click();
+ anchor.remove();
+ return [button(label, true), ""];
+ }
+ return [];
+}
diff --git a/tests/unittest/test_kit_gradio.py b/tests/unittest/test_kit_gradio.py
index a6985a46..812e1ddf 100644
--- a/tests/unittest/test_kit_gradio.py
+++ b/tests/unittest/test_kit_gradio.py
@@ -1046,17 +1046,29 @@ def test_build_gradio_app_exposes_three_tabs_and_download_menu(tmp_path: Path) -
)
tab_labels = [component.label for component in app.blocks.values() if component.__class__.__name__ == "Tab"]
assert tab_labels == ["Markdown 渲染", "Markdown 源码", "Structured Content 源码"]
- download_labels = [component.label for component in app.blocks.values() if component.__class__.__name__ == "DownloadButton"]
- assert download_labels == ["ZIP", "HTML", "DOCX", "LaTeX bundle", "EPUB", "PDF"]
- download_buttons = [component for component in app.blocks.values() if component.__class__.__name__ == "DownloadButton"]
+ download_buttons = [
+ component
+ for component in app.blocks.values()
+ if component.__class__.__name__ == "Button"
+ and any(name.startswith("mineru-kit-download-") for name in (component.elem_classes or []))
+ ]
+ assert [component.value for component in download_buttons] == ["ZIP", "HTML", "DOCX", "LaTeX bundle", "EPUB", "PDF"]
+ assert not any(component.__class__.__name__ == "DownloadButton" for component in app.blocks.values())
assert all(component.interactive is False for component in download_buttons)
- file_inputs = [component for component in app.blocks.values() if component.__class__.__name__ == "File"]
+ file_inputs = [
+ component for component in app.blocks.values() if component.__class__.__name__ == "File" and component.visible
+ ]
assert len(file_inputs) == 1
assert file_inputs[0].file_count == "single"
assert set(file_inputs[0].file_types) == {f".{extension}" for extension in PARSEABLE_EXTENSIONS}
preview_handler = next(fn.fn for fn in app.fns.values() if fn.name == "update_file_preview")
- assert preview_handler("report.pdf")[0] == {"__type__": "update", "value": "report.pdf", "visible": True}
- assert preview_handler("report.docx")[0]["visible"] is False
+ assert preview_handler("report.pdf")[0] == {
+ "__type__": "update",
+ "value": "report.pdf",
+ "visible": True,
+ "elem_classes": ["mineru-kit-pdf-preview"],
+ }
+ assert preview_handler("report.docx")[0]["visible"] == "hidden"
range_group = next(block for block in app.blocks.values() if "mineru-kit-page-range" in (block.elem_classes or []))
assert range_group.visible is True
assert '[data-range-visible="true"]' in app._mineru_kit_css
@@ -1151,7 +1163,7 @@ def test_gradio_flash_only_input_requires_available_flash(tmp_path: Path, tiers:
assert "tier_unavailable" in updates[-1][0]
assert "该格式仅支持 Flash,当前服务不可用" in updates[-1][0]
assert updates[-1][8] is None
- assert all(item["interactive"] is False and item["value"] is None for item in updates[-1][-6:])
+ assert all(item["interactive"] is False for item in updates[-1][-6:])
client.parse_file.assert_not_called()
@@ -1214,10 +1226,11 @@ def test_gradio_conversion_forwards_page_range_and_enables_fresh_downloads(
updates = asyncio.run(collect_updates(convert_handler))
assert client.calls == [(source.resolve(), expected_tier, "" if expected_tier == "flash" else "1")]
- assert len(updates[-1]) == 15
+ assert len(updates[-1]) == 16
+ assert updates[-1][9] == Path(updates[-1][8]["root"]).name
assert updates[-1][8] is not None
- assert all(update["interactive"] is True and update["value"] is None for update in updates[-1][-6:])
- assert all(update["interactive"] is False and update["value"] is None for update in updates[0][-6:])
+ assert all(update["interactive"] is True for update in updates[-1][-6:])
+ assert all(update["interactive"] is False for update in updates[0][-6:])
@pytest.mark.parametrize(
@@ -1247,7 +1260,7 @@ def test_gradio_conversion_rejects_invalid_tier_position(tmp_path: Path, tiers:
updates = asyncio.run(collect_updates())
assert "Failed: Invalid tier slider position" in updates[-1][0]
assert updates[-1][8] is None
- assert all(item["interactive"] is False and item["value"] is None for item in updates[-1][-6:])
+ assert all(item["interactive"] is False for item in updates[-1][-6:])
client.parse_file.assert_not_called()
@@ -1280,7 +1293,7 @@ def test_gradio_conversion_failure_clears_previous_downloads(tmp_path: Path) ->
assert "Failed: boom" in update[0]
assert update[8] is None
- assert all(item["interactive"] is False and item["value"] is None for item in update[-6:])
+ assert all(item["interactive"] is False for item in update[-6:])
@pytest.mark.parametrize("explicit_session_cancel", [False, True])
diff --git a/tests/unittest/test_kit_gradio_download.cjs b/tests/unittest/test_kit_gradio_download.cjs
new file mode 100644
index 00000000..3c6b6a14
--- /dev/null
+++ b/tests/unittest/test_kit_gradio_download.cjs
@@ -0,0 +1,57 @@
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const path = require("node:path");
+const vm = require("node:vm");
+const downloads = [];
+global.window = {};
+global.document = {
+ body: { appendChild() { /* 模拟临时下载链接挂载。 */ } },
+ createElement() {
+ // 记录真实脚本发起的下载,重复成功事件不得重复触发链接。
+ return { click() { downloads.push([this.href, this.download]); }, remove() {} };
+ },
+};
+const reduce = vm.runInThisContext(fs.readFileSync(path.join(__dirname, "../../mineru/resources/gradio_download.js"), "utf8"));
+const formats = [["zip", "ZIP"], ["html", "HTML"], ["docx", "DOCX"], ["latex", "LaTeX bundle"], ["epub", "EPUB"], ["pdf", "PDF"]];
+// 调用实际产品脚本,保持 DOM 替身只负责记录下载行为。
+const step = (action, format = "", ...args) => reduce(action, formats, format, formats.find(([name]) => name === format)?.[1], ...args);
+const receipt = (request, error = "") => JSON.stringify({ request, error });
+const file = { url: "/gradio_api/file=/cache/test.html", orig_name: "含 空格.html" };
+step("activate", "", "run-a");
+for (const [format, label] of formats) {
+ for (let click = 0; click < 2; click++) {
+ const [token, busy] = step("begin", format, "run-a");
+ assert.equal(busy.interactive, false);
+ assert.match(busy.value, /准备中/);
+ assert.deepEqual(step("begin", format, "run-a"), [{ __type__: "update" }, { __type__: "update" }, { __type__: "update" }]);
+ const count = downloads.length;
+ const [ready, notice] = step("complete", format, file, receipt(token), "run-a");
+ assert.equal(downloads.length, count + 1);
+ assert.deepEqual(downloads.at(-1), [file.url, file.orig_name]);
+ assert.equal(ready.value, label);
+ assert.equal(ready.interactive, true);
+ assert.equal(notice, "");
+ step("complete", format, file, receipt(token), "run-a");
+ assert.equal(downloads.length, count + 1);
+ }
+}
+const [failed] = step("begin", "pdf", "run-a");
+const [restored, error] = step("complete", "pdf", null, receipt(failed, "<bad> & failed"), "run-a");
+assert.equal(restored.interactive, true);
+assert.ok(error.includes("&lt;bad&gt; &amp; failed"));
+assert.ok(!error.includes("<bad>"));
+const [retry] = step("begin", "pdf", "run-a");
+const count = downloads.length;
+const reset = step("reset");
+assert.equal(reset[0], "");
+assert.deepEqual(reset.slice(1, 7), Array(6).fill(null));
+assert.ok(reset.slice(-7, -1).every(update => update.interactive === false));
+step("activate", "", "run-b");
+const [current] = step("begin", "pdf", "run-b");
+assert.deepEqual(step("busy", "pdf", retry, "run-b"), [{ __type__: "update" }, { __type__: "update" }]);
+assert.equal(step("busy", "pdf", current, "run-b")[0].interactive, false);
+assert.deepEqual(step("complete", "pdf", file, receipt(retry), "run-b"), [{ __type__: "update" }, { __type__: "update" }]);
+assert.equal(downloads.length, count);
+step("complete", "pdf", file, receipt(current), "run-b");
+assert.equal(downloads.length, count + 1);
+console.log("download lifecycle passed");
diff --git a/tests/unittest/test_kit_gradio_download.py b/tests/unittest/test_kit_gradio_download.py
new file mode 100644
index 00000000..c99d0335
--- /dev/null
+++ b/tests/unittest/test_kit_gradio_download.py
@@ -0,0 +1,83 @@
+"""下载请求与前端首次点击、缓存、错误和过期响应的回归。"""
+
+from __future__ import annotations
+
+import json
+import shutil
+import subprocess
+from pathlib import Path
+from unittest.mock import Mock
+
+import pytest
+
+from mineru.kit.gradio import app as gradio_app
+from mineru.kit.gradio.artifacts import create_run_artifacts
+from mineru.kit.gradio.client import V1ServerCapabilities
+
+
+def test_download_receipt_keeps_request_on_success_and_failure(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """真实结果标识校验覆盖正常生成、缓存复用及渲染异常,并在错误回执中保留请求标识。"""
+ source = tmp_path / "source.pdf"
+ source.write_bytes(b"test")
+ artifacts = create_run_artifacts(source, tmp_path / "output")
+ token = json.dumps({"run_id": artifacts.root.name, "sequence": 1})
+ target = artifacts.downloads_dir / "source.html"
+ render = Mock(return_value=str(target))
+ monkeypatch.setattr(gradio_app, "render_download", render)
+ handler = gradio_app._download_handler("html", tmp_path / "output")
+ for sequence in (1, 2):
+ token = json.dumps({"run_id": artifacts.root.name, "sequence": sequence})
+ path, receipt = handler(artifacts.as_state(), token)
+ assert path == str(target)
+ assert json.loads(receipt) == {"request": token, "error": ""}
+ render.side_effect = RuntimeError("render failed")
+ path, receipt = handler(artifacts.as_state(), token)
+ assert path is None
+ assert json.loads(receipt) == {"request": token, "error": "render failed"}
+ render.reset_mock()
+ path, receipt = handler(artifacts.as_state(), json.dumps({"run_id": "old-run", "sequence": 3}))
+ assert path is None and "已变更" in json.loads(receipt)["error"]
+ render.assert_not_called()
+
+
+def test_download_event_chain_and_pdf_mount(tmp_path: Path) -> None:
+ """每种格式使用独立文件与成功事件,所有空 PDF 预览状态保持挂载。"""
+ cap = V1ServerCapabilities("http://127.0.0.1:1", ("flash",), ("zip",), ("file_id",))
+ app = gradio_app.build_gradio_app(Mock(), cap, output_root=tmp_path, enable_example=False)
+ pdf = next(component for component in app.blocks.values() if component.__class__.__name__ == "PDF")
+ assert pdf.visible == "hidden"
+ preview = next(fn.fn for fn in app.fns.values() if fn.name == "update_file_preview")
+ for source in (None, "photo.png", "book.docx", "book.epub"):
+ assert preview(source)[0]["value"] is None
+ assert preview(source)[0]["visible"] == "hidden"
+ assert "mineru-kit-pdf-empty" in preview(source)[0]["elem_classes"]
+ reset = next(fn.fn for fn in app.fns.values() if fn.name == "reset_ui")
+ assert reset()[4]["visible"] == "hidden"
+ assert reset()[9] == ""
+ conversion = next(fn for fn in app.fns.values() if fn.name == "convert_handler")
+ dependency = next(dep for dep in app.config["dependencies"] if dep["id"] == conversion._id)
+ # 转换必须等待真正的重置完成事件,纯 JS 事件的 then 在支持版本中不会可靠触发。
+ reset_event = app.fns[dependency["trigger_after"]]
+ assert reset_event.name == "reset_download_ui"
+ assert len(reset_event.fn()) == len(reset_event.outputs)
+ handlers = [fn for fn in app.fns.values() if fn.name == "handler"]
+ assert len(handlers) == 6
+ files = []
+ for handler in handlers:
+ file, receipt = handler.outputs
+ assert file.__class__.__name__ == "File" and file.visible is False
+ files.append(file._id)
+ success = next(dep for dep in app.config["dependencies"] if dep.get("trigger_after") == handler._id)
+ assert success["trigger_only_on_success"] is True
+ assert success["backend_fn"] is False and success["queue"] is False
+ assert success["inputs"][:2] == [file._id, receipt._id]
+ assert len(set(files)) == 6
+
+
+def test_frontend_download_lifecycle() -> None:
+ """运行真实前端脚本,验证恰好一次下载、失败重试和跨文档失效。"""
+ node = shutil.which("node")
+ if node is None:
+ pytest.skip("Node.js is required for frontend state tests")
+ result = subprocess.run([node, str(Path(__file__).with_suffix(".cjs"))], capture_output=True, text=True, check=False)
+ assert result.returncode == 0, result.stdout + result.stderr