Skip to content

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

feat(status-timer): enhance local queue animation and status display during processing

myhloli52ef85301195
diff --git a/mineru/kit/gradio/app.py b/mineru/kit/gradio/app.py
index 89c99424..5938bd8c 100644
--- a/mineru/kit/gradio/app.py
+++ b/mineru/kit/gradio/app.py
@@ -379,12 +379,16 @@ def build_gradio_app(
examples = _example_files(file_types) if enable_example else []
app_css = _resource_text("gradio_app.css") + _KIT_MENU_CSS + _download_icon_css()
i18n = gr.I18n(**translations())
- app_js = _resource_text("gradio_app.js").replace(
- "__MINERU_I18N__",
- f"({_resource_text('gradio_i18n.js')})({json.dumps(MESSAGES, ensure_ascii=False)})",
- ).replace(
- "__MINERU_STATUS_TIMER__",
- _resource_text("gradio_status_timer.js"),
+ app_js = (
+ _resource_text("gradio_app.js")
+ .replace(
+ "__MINERU_I18N__",
+ f"({_resource_text('gradio_i18n.js')})({json.dumps(MESSAGES, ensure_ascii=False)})",
+ )
+ .replace(
+ "__MINERU_STATUS_TIMER__",
+ _resource_text("gradio_status_timer.js"),
+ )
)
# 等待限制放在生成器内部,使其他会话也能立即显示本地排队状态。
conversion_slot = asyncio.Semaphore(1)
@@ -470,7 +474,12 @@ def build_gradio_app(
page_notice = gr.HTML(value="", visible=False, elem_classes=["mineru-page-notice"])
with gr.Row(elem_classes=["mineru-actions"]):
convert_button = gr.Button(
- i18n("mineru.convert"), variant="primary", scale=1, min_width=0, interactive=False
+ i18n("mineru.convert"),
+ variant="primary",
+ scale=1,
+ min_width=0,
+ interactive=False,
+ elem_classes=["mineru-convert-button"],
)
clear_button = gr.ClearButton(value=i18n("mineru.clear"), scale=1, min_width=1)
status_panel = gr.HTML(_status_html(), elem_classes=["mineru-status-panel"])
@@ -685,11 +694,19 @@ def build_gradio_app(
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:], "")
+ return (
+ _status_html(STATUS_PREPARING_REQUEST),
+ "",
+ *((None,) * count),
+ *(("",) * count * 2),
+ *_download_updates(gr, interactive=False)[1:],
+ "",
+ )
download_reset_outputs = [
+ status_panel,
active_run_id,
*download_files.values(),
*download_requests.values(),
@@ -808,6 +825,9 @@ def build_gradio_app(
if not file_path:
yield reset_result
return
+ state = StatusPanelState()
+ state.append(STATUS_PREPARING_REQUEST)
+ yield (state.render(), *reset_result[1:])
source_path = Path(file_path).resolve()
if not source_path.is_file():
yield (_status_html("Failed: input file does not exist"), *reset_result[1:])
@@ -833,9 +853,6 @@ def build_gradio_app(
except MineruError as exc:
yield (_status_html(f"Failed: {exc.code}: {exc}"), *reset_result[1:])
return
- state = StatusPanelState()
- state.append(STATUS_PREPARING_REQUEST)
- yield (state.render(), *reset_result[1:])
status_queue: asyncio.Queue[tuple[str, float]] = asyncio.Queue()
loop = asyncio.get_running_loop()
@@ -950,7 +967,10 @@ def build_gradio_app(
fn=reset_download_ui,
inputs=[],
outputs=download_reset_outputs,
- js=f"() => {{ ({pdf_preview_js('begin')})(); ({download_js('reset')})(); return []; }}",
+ js=(
+ f"() => {{ ({pdf_preview_js('begin')})(); "
+ f"return [{json.dumps(_status_html(STATUS_PREPARING_REQUEST))}, ...({download_js('reset')})()]; }}"
+ ),
**private_event_kwargs,
)
convert_event = begin_conversion.then(
diff --git a/mineru/kit/gradio/status.py b/mineru/kit/gradio/status.py
index 47d9f48a..33b6e036 100644
--- a/mineru/kit/gradio/status.py
+++ b/mineru/kit/gradio/status.py
@@ -45,10 +45,9 @@ class StatusPanelState:
step_index: int = -1
processing_elapsed: float | None = None
_processing_started: float | None = None
- _queue_started: float | None = None
def append(self, message: str, *, at: float | None = None) -> bool:
- """接收真实阶段变化;重复通知不会重置解析计时或排队动画。"""
+ """接收真实阶段变化;重复通知不会重置解析计时。"""
if not message or message == self.message:
return False
now = self.clock() if at is None else at
@@ -58,11 +57,6 @@ class StatusPanelState:
if message == STATUS_PROCESSING_ON_SERVER:
self._processing_started = now
self.processing_elapsed = 0.0
- if message in (STATUS_QUEUED_LOCALLY, STATUS_QUEUED_ON_SERVER):
- if self._queue_started is None:
- self._queue_started = now
- else:
- self._queue_started = None
self.message = message
# 本地等待可能发生在上传之前;已展示的步骤不因后续准备通知倒退。
self.step_index = max(self.step_index, _MESSAGE_STEPS.get(message, -1))
@@ -70,13 +64,6 @@ class StatusPanelState:
self.step_index = len(_STEPS) - 1
return True
- @property
- def refresh_interval(self) -> float | None:
- """只在排队期间刷新服务端动画;解析计时交由浏览器更新。"""
- if self._queue_started is not None:
- return 1.0
- return None
-
def render(self) -> str:
"""按 3.4.5 的两列卡片结构渲染当前状态,并转义外部错误文本。"""
now = self.clock()
@@ -103,11 +90,11 @@ class StatusPanelState:
elapsed = max(0.0, now - self._processing_started)
latest = f"Processing on server ({elapsed:.2f}s)"
timer_attributes = (
- f' data-mineru-processing-start="{self._processing_started:.9f}"'
- f' data-mineru-processing-elapsed="{elapsed:.6f}"'
+ f' data-mineru-processing-start="{self._processing_started:.9f}" data-mineru-processing-elapsed="{elapsed:.6f}"'
)
- elif self._queue_started is not None:
- latest += "." * (int(max(0.0, now - self._queue_started)) % 10 + 1)
+ elif self.message in (STATUS_QUEUED_LOCALLY, STATUS_QUEUED_ON_SERVER):
+ queue_key = "queued_locally" if self.message == STATUS_QUEUED_LOCALLY else "queued_on_server"
+ timer_attributes = f' data-mineru-queue-key="{queue_key}"'
elif completed:
display_elapsed = Decimal(str(self.processing_elapsed or 0.0)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
latest = f"{STATUS_COMPLETED} ({display_elapsed:.2f}s)"
@@ -137,7 +124,7 @@ async def stream_status_updates(
events: asyncio.Queue[tuple[str, float]],
state: StatusPanelState,
) -> AsyncIterator[str]:
- """同时等待任务、状态通知和本地动画时钟,并及时回收临时等待任务。"""
+ """只等待真实阶段通知或任务结束,并及时回收临时等待任务。"""
while True:
while not events.empty():
message, at = events.get_nowait()
@@ -148,13 +135,11 @@ async def stream_status_updates(
waiter = asyncio.create_task(events.get())
updated_html: str | None = None
try:
- done, _ = await asyncio.wait({task, waiter}, timeout=state.refresh_interval, return_when=asyncio.FIRST_COMPLETED)
+ done, _ = await asyncio.wait({task, waiter}, return_when=asyncio.FIRST_COMPLETED)
if waiter in done:
message, at = waiter.result()
if state.append(message, at=at):
updated_html = state.render()
- elif not done:
- updated_html = state.render()
finally:
if not waiter.done():
waiter.cancel()
diff --git a/mineru/resources/gradio_app.js b/mineru/resources/gradio_app.js
index 02ff2805..5036129d 100644
--- a/mineru/resources/gradio_app.js
+++ b/mineru/resources/gradio_app.js
@@ -1,5 +1,5 @@
() => {
- const APP_SCRIPT_VERSION = "v2-browser-status-timer";
+ const APP_SCRIPT_VERSION = "v4-local-queue-animation";
if (window.__mineruGradioAppInstalled === APP_SCRIPT_VERSION) {
return;
}
@@ -20,6 +20,7 @@
};
const i18n = window.__mineruI18n = __MINERU_I18N__;
const statusTimer = (__MINERU_STATUS_TIMER__)(i18n);
+ window.__mineruStatusPanel = statusTimer;
// HTML 回调和前端事件使用同一份词典与首选语言规则。
const localizeMineruCustomText = () => i18n.localize();
@@ -213,10 +214,10 @@
});
if (typeof MutationObserver !== "undefined") {
const uiObserver = new MutationObserver((mutations) => {
- // 本地计时的文字变化无需重新扫描整页,避免 10 毫秒刷新触发递归本地化。
+ // 本地计时与排队动画的文字变化无需重新扫描整页,避免递归本地化。
if (mutations.every(({ target }) => {
const element = target.nodeType === 1 ? target : target.parentElement;
- return element?.closest?.("[data-mineru-local-timer]");
+ return element?.closest?.("[data-mineru-local-timer], [data-mineru-local-animation]");
})) {
return;
}
@@ -233,6 +234,12 @@
if (!(target instanceof Element)) {
return;
}
+ const convertRoot = target.closest(".mineru-convert-button");
+ const convert = convertRoot?.matches("button") ? convertRoot : convertRoot?.querySelector("button");
+ if (convert && !convert.disabled && convert.getAttribute("aria-disabled") !== "true") {
+ statusTimer.showPreparing();
+ return;
+ }
if (target.closest(".office-preview-ignore-forever")) {
const notice = target.closest(".office-preview-notice");
if (setOfficePreviewNoticeIgnored()) {
diff --git a/mineru/resources/gradio_i18n.js b/mineru/resources/gradio_i18n.js
index 9e0dc8d5..e3fa25bb 100644
--- a/mineru/resources/gradio_i18n.js
+++ b/mineru/resources/gradio_i18n.js
@@ -44,7 +44,7 @@
const localize = (root = document) => {
const locale = resolveLocale();
root.querySelectorAll("[data-mineru-i18n-key]").forEach((item) => {
- if (item.hasAttribute("data-mineru-local-timer")) return;
+ if (item.hasAttribute("data-mineru-local-timer") || item.hasAttribute("data-mineru-local-animation")) return;
const key = item.getAttribute("data-mineru-i18n-key");
const value = item.getAttribute(`data-mineru-i18n-${locale}`) ?? text(key);
const attributes = item.getAttribute("data-mineru-i18n-attr");
diff --git a/mineru/resources/gradio_status_timer.js b/mineru/resources/gradio_status_timer.js
index c874fb0e..a00cfd67 100644
--- a/mineru/resources/gradio_status_timer.js
+++ b/mineru/resources/gradio_status_timer.js
@@ -3,52 +3,112 @@
let activeSpan = null;
let activeStart = null;
let startedAt = 0;
+ let activeMode = null;
+ let activeQueueKey = null;
+ let queueStartedAt = 0;
- // 结束解析或重置界面时立即停止计时,避免隐藏页面继续占用定时器。
+ // 离开排队或解析阶段时停止本地动画,避免隐藏页面继续占用定时器。
const stop = () => {
if (interval !== null) {
clearInterval(interval);
interval = null;
}
activeSpan?.removeAttribute("data-mineru-local-timer");
+ activeSpan?.removeAttribute("data-mineru-local-animation");
activeSpan = null;
activeStart = null;
+ activeMode = null;
+ activeQueueKey = null;
};
- // 使用单调时钟计算实际耗时;后台标签页暂停定时器后恢复也不会累计误差。
+ // 用单调时钟绘制解析耗时或排队圆点;后台标签页恢复后按实际时间追上。
const render = () => {
if (activeSpan?.isConnected === false) {
sync();
return;
}
if (!activeSpan) return;
+ if (activeMode === "queue") {
+ const dots = Math.floor(Math.max(0, performance.now() - queueStartedAt) / 1000) % 10 + 1;
+ const value = `${i18n.text(activeQueueKey)}${".".repeat(dots)}`;
+ if (activeSpan.textContent !== value) activeSpan.textContent = value;
+ return;
+ }
const elapsed = Math.max(0, performance.now() - startedAt);
const display = (Math.round(elapsed / 10) / 100).toFixed(2);
const value = i18n.text("processing_elapsed", { elapsed: display });
if (activeSpan.textContent !== value) activeSpan.textContent = value;
};
- // Gradio 重绘同一解析状态时续用原计时起点;新任务才重新开始。
+ // Gradio 重绘同一阶段时保留本地起点;真实阶段切换时重设动画频率。
const sync = () => {
const status = document.querySelector(".mineru-status-panel .status-latest[data-mineru-processing-start]");
const span = status?.querySelector('[data-mineru-i18n-key="status_message"]');
const start = status?.getAttribute("data-mineru-processing-start");
- if (!span || start === null) {
- stop();
+ if (span && start !== null) {
+ if (activeMode === "processing" && span === activeSpan && start === activeStart) return;
+ if (activeMode !== "processing") stop();
+ else activeSpan?.removeAttribute("data-mineru-local-timer");
+ const serverElapsed = Number(status.getAttribute("data-mineru-processing-elapsed"));
+ const serverElapsedMs = Number.isFinite(serverElapsed) ? Math.max(0, serverElapsed * 1000) : 0;
+ const observedStart = performance.now() - serverElapsedMs;
+ startedAt = activeMode === "processing" && start === activeStart
+ ? Math.min(startedAt, observedStart) : observedStart;
+ activeSpan = span;
+ activeStart = start;
+ activeMode = "processing";
+ activeSpan.setAttribute("data-mineru-local-timer", "");
+ if (interval === null) interval = setInterval(render, 10);
+ render();
return;
}
- if (span === activeSpan && start === activeStart) return;
- activeSpan?.removeAttribute("data-mineru-local-timer");
- const serverElapsed = Number(status.getAttribute("data-mineru-processing-elapsed"));
- const serverElapsedMs = Number.isFinite(serverElapsed) ? Math.max(0, serverElapsed * 1000) : 0;
- const observedStart = performance.now() - serverElapsedMs;
- startedAt = start === activeStart ? Math.min(startedAt, observedStart) : observedStart;
- activeSpan = span;
- activeStart = start;
- activeSpan.setAttribute("data-mineru-local-timer", "");
- if (interval === null) interval = setInterval(render, 10);
- render();
+ const queueStatus = document.querySelector(".mineru-status-panel .status-latest[data-mineru-queue-key]");
+ const queueSpan = queueStatus?.querySelector('[data-mineru-i18n-key="status_message"]');
+ const queueKey = queueStatus?.getAttribute("data-mineru-queue-key");
+ if (queueSpan && (queueKey === "queued_locally" || queueKey === "queued_on_server")) {
+ if (activeMode === "queue" && queueSpan === activeSpan && queueKey === activeQueueKey) {
+ render();
+ return;
+ }
+ if (activeMode !== "queue" || queueKey !== activeQueueKey) stop();
+ else activeSpan?.removeAttribute("data-mineru-local-animation");
+ if (activeMode !== "queue") queueStartedAt = performance.now();
+ activeSpan = queueSpan;
+ activeQueueKey = queueKey;
+ activeMode = "queue";
+ activeSpan.setAttribute("data-mineru-local-animation", "");
+ if (interval === null) interval = setInterval(render, 1000);
+ render();
+ return;
+ }
+ stop();
+ };
+
+ // 点击转换时直接展示准备阶段,避开 Gradio 等待服务端回调后才更新 HTML 输出的延迟。
+ const showPreparing = () => {
+ const panel = document.querySelector(".mineru-status-panel .status-steps-panel");
+ if (!panel) return;
+ stop();
+ panel.querySelectorAll(".status-step").forEach((step, index) => {
+ step.classList.toggle("is-active", index === 0);
+ step.classList.toggle("is-pending", index !== 0);
+ step.classList.remove("is-done", "is-error");
+ });
+ // 使用原有双语节点,浏览器语言变化时仍能按项目词典更新。
+ const setText = (element, key) => {
+ if (!element) return;
+ element.setAttribute("data-mineru-i18n-key", key);
+ element.setAttribute("data-mineru-i18n-en", i18n.text(key, {}, "en"));
+ element.setAttribute("data-mineru-i18n-zh", i18n.text(key, {}, "zh"));
+ element.textContent = i18n.text(key);
+ };
+ setText(panel.querySelector(".status-panel-title [data-mineru-i18n-key]"), "status_latest");
+ const latest = panel.querySelector(".status-latest");
+ latest?.removeAttribute("data-mineru-processing-start");
+ latest?.removeAttribute("data-mineru-processing-elapsed");
+ latest?.removeAttribute("data-mineru-queue-key");
+ setText(latest?.querySelector("[data-mineru-i18n-key]"), "preparing_request");
};
- return { sync };
+ return { sync, showPreparing };
}
diff --git a/tests/unittest/test_kit_gradio.py b/tests/unittest/test_kit_gradio.py
index 875e8bf1..8b771c44 100644
--- a/tests/unittest/test_kit_gradio.py
+++ b/tests/unittest/test_kit_gradio.py
@@ -1465,7 +1465,7 @@ def test_gradio_local_queue_cancellation_releases_slot_and_keeps_sessions_isolat
]
cancel_session = next(fn.fn for fn in demo.fns.values() if fn.name == "cancel_session_conversion")
await advance_until(first, "Processing on server")
- queued = await advance_until(second, "Queued locally.")
+ queued = await advance_until(second, "Queued locally")
assert all(value == {"__type__": "update"} for value in queued[1:])
assert calls == [sources[0]]
if explicit_session_cancel:
@@ -1474,7 +1474,7 @@ def test_gradio_local_queue_cancellation_releases_slot_and_keeps_sessions_isolat
await anext(second)
else:
await second.aclose()
- await advance_until(third, "Queued locally.")
+ await advance_until(third, "Queued locally")
if explicit_session_cancel:
await cancel_session(requests[0])
with pytest.raises(StopAsyncIteration):
diff --git a/tests/unittest/test_kit_gradio_download.py b/tests/unittest/test_kit_gradio_download.py
index b1d59552..0fd471b7 100644
--- a/tests/unittest/test_kit_gradio_download.py
+++ b/tests/unittest/test_kit_gradio_download.py
@@ -95,6 +95,12 @@ def test_download_event_chain_and_pdf_transport(tmp_path: Path) -> None:
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)
conversion = next(fn for fn in app.fns.values() if fn.name == "convert_handler")
+ assert (
+ "mineru-convert-button"
+ in next(
+ block for block in app.blocks.values() if block.__class__.__name__ == "Button" and "mineru.convert" in block.value
+ ).elem_classes
+ )
pdf = conversion.outputs[2]
assert pdf.__class__.__name__ == "File" and pdf.visible is False
preview = next(fn.fn for fn in app.fns.values() if fn.name == "update_file_preview")
@@ -110,6 +116,10 @@ def test_download_event_chain_and_pdf_transport(tmp_path: Path) -> None:
reset_event = app.fns[dependency["trigger_after"]]
assert reset_event.name == "reset_download_ui"
assert len(reset_event.fn()) == len(reset_event.outputs)
+ assert reset_event.outputs[0].__class__.__name__ == "HTML"
+ assert "Preparing request..." in reset_event.fn()[0]
+ reset_dependency = next(dep for dep in app.config["dependencies"] if dep["id"] == reset_event._id)
+ assert "Preparing request..." in reset_dependency["js"]
handlers = [fn for fn in app.fns.values() if fn.name == "handler"]
assert len(handlers) == 7
files = []
diff --git a/tests/unittest/test_kit_gradio_status.py b/tests/unittest/test_kit_gradio_status.py
index ebcbe4e8..54f9072b 100644
--- a/tests/unittest/test_kit_gradio_status.py
+++ b/tests/unittest/test_kit_gradio_status.py
@@ -25,7 +25,6 @@ def test_processing_clock_excludes_queue_and_download_and_keeps_completed_durati
state.append(STATUS_QUEUED_ON_SERVER)
now[0] = 100.0
state.append(STATUS_PROCESSING_ON_SERVER)
- assert state.refresh_interval is None
now[0] = 101.2
assert "Processing on server (1.20s)" in state.render()
assert 'data-mineru-processing-start="100.000000000"' in state.render()
@@ -33,7 +32,6 @@ def test_processing_clock_excludes_queue_and_download_and_keeps_completed_durati
assert not state.append(STATUS_PROCESSING_ON_SERVER)
now[0] = 104.6
state.append(STATUS_DOWNLOADING_RESULT, at=104.5)
- assert state.refresh_interval is None
assert state.processing_elapsed == pytest.approx(4.5)
assert "status-step is-active" in state.render()
assert state.render().count("status-step is-done") == 5
@@ -46,16 +44,19 @@ def test_processing_clock_excludes_queue_and_download_and_keeps_completed_durati
@pytest.mark.parametrize("message", [STATUS_QUEUED_LOCALLY, STATUS_QUEUED_ON_SERVER])
-def test_queue_animation_cycles_without_restarting_on_repeated_status(message: str) -> None:
- """验证本地和远端队列都按每秒一个圆点循环,重复轮询不重置动画。"""
+def test_queued_status_stays_stable_without_timer_updates(message: str) -> None:
+ """验证服务端排队 HTML 保持静态,并携带供浏览器绘制动画的状态标记。"""
now = [5.0]
state = StatusPanelState(clock=lambda: now[0])
state.append(message)
- assert state.refresh_interval == 1.0
- for seconds, dots in [(0, 1), (3, 4), (9, 10), (10, 1)]:
+ initial = state.render()
+ queue_key = "queued_locally" if message == STATUS_QUEUED_LOCALLY else "queued_on_server"
+ assert f'data-mineru-queue-key="{queue_key}"' in initial
+ for seconds in (0, 3, 9, 10):
now[0] = 5.0 + seconds
assert not state.append(message)
- assert f'data-mineru-i18n-en="{message}{"." * dots}"' in state.render()
+ assert state.render() == initial
+ assert f'data-mineru-i18n-en="{message}"' in state.render()
def test_fast_completion_shows_zero_elapsed_time_and_reset_has_eight_pending_steps() -> None:
@@ -95,30 +96,34 @@ def test_failure_stops_timer_and_renders_escaped_error(error: str) -> None:
state.append(f"Failed: {error}", at=3.0)
rendered = state.render()
assert state.processing_elapsed == 2.0
- assert state.refresh_interval is None
assert "status-step is-active is-error" in rendered
assert 'data-mineru-i18n-en="Failed"' in rendered
assert "<script>" not in rendered
def test_status_stream_waits_for_stage_changes_and_cleans_up_waiter() -> None:
- """验证解析期间不再发送服务端计时帧,阶段通知仍及时更新且不残留等待任务。"""
+ """验证排队和解析期间均无服务端计时帧,真实阶段仍及时更新。"""
async def scenario() -> None:
"""运行可手动推进时钟的解析等待场景。"""
now = [1.0]
state = StatusPanelState(clock=lambda: now[0])
events: asyncio.Queue[tuple[str, float]] = asyncio.Queue()
- events.put_nowait((STATUS_PROCESSING_ON_SERVER, 1.0))
+ events.put_nowait((STATUS_QUEUED_ON_SERVER, 1.0))
task = asyncio.create_task(asyncio.Event().wait())
baseline = set(asyncio.all_tasks())
async with aclosing(stream_status_updates(task, events, state)) as stream:
- assert "(0.00s)" in await anext(stream)
+ assert "Queued on server" in await anext(stream)
now[0] = 2.3
next_update = asyncio.create_task(anext(stream))
await asyncio.sleep(0.03)
assert not next_update.done()
- events.put_nowait((STATUS_DOWNLOADING_RESULT, 2.3))
+ events.put_nowait((STATUS_PROCESSING_ON_SERVER, 2.3))
+ assert "(0.00s)" in await asyncio.wait_for(next_update, timeout=1)
+ next_update = asyncio.create_task(anext(stream))
+ await asyncio.sleep(0.03)
+ assert not next_update.done()
+ events.put_nowait((STATUS_DOWNLOADING_RESULT, 2.6))
assert "Task completed, downloading result" in await asyncio.wait_for(next_update, timeout=1)
assert set(asyncio.all_tasks()) == baseline
assert set(asyncio.all_tasks()) == baseline
diff --git a/tests/unittest/test_kit_gradio_status_timer.cjs b/tests/unittest/test_kit_gradio_status_timer.cjs
index ea6bd58d..a9f96a54 100644
--- a/tests/unittest/test_kit_gradio_status_timer.cjs
+++ b/tests/unittest/test_kit_gradio_status_timer.cjs
@@ -16,21 +16,27 @@ const makeSpan = () => {
removeAttribute(name) { attributes.delete(name); },
};
};
-const makeStatus = (start, elapsed, span) => ({
+const makeStatus = (start, elapsed, span, queueKey = null) => ({
querySelector() { return span; },
getAttribute(name) {
- return name === "data-mineru-processing-start" ? start : String(elapsed);
+ if (name === "data-mineru-processing-start") return start;
+ if (name === "data-mineru-processing-elapsed") return String(elapsed);
+ if (name === "data-mineru-queue-key") return queueKey;
+ return null;
},
});
let now = 0;
let currentStatus = null;
+let currentPanel = null;
let tick = null;
let intervalMs = null;
let stopped = 0;
const document = {
title: "",
- querySelector() { return currentStatus; },
+ querySelector(selector) {
+ return selector === ".mineru-status-panel .status-steps-panel" ? currentPanel : currentStatus;
+ },
querySelectorAll() { return []; },
};
const context = vm.createContext({
@@ -92,3 +98,92 @@ assert.equal(second.textContent, "服务端解析中(0.94 秒)");
currentStatus = null;
timer.sync();
assert.equal(stopped, 2);
+
+// 排队圆点在浏览器每秒推进,不依赖 Gradio 再次发送状态;重绘后沿用旧起点。
+const queued = makeSpan();
+now = 1100;
+currentStatus = makeStatus(null, null, queued, "queued_on_server");
+timer.sync();
+assert.equal(intervalMs, 1000);
+assert.equal(queued.textContent, "服务端排队中.");
+now = 2100;
+tick();
+assert.equal(queued.textContent, "服务端排队中..");
+now = 10100;
+tick();
+assert.equal(queued.textContent, `服务端排队中${".".repeat(10)}`);
+now = 11100;
+tick();
+assert.equal(queued.textContent, "服务端排队中.");
+i18n.localize({ querySelectorAll(selector) { return selector === "[data-mineru-i18n-key]" ? [queued] : []; } });
+assert.equal(queued.textContent, "服务端排队中.");
+const remountedQueue = makeSpan();
+queued.isConnected = false;
+currentStatus = makeStatus(null, null, remountedQueue, "queued_on_server");
+now = 12100;
+tick();
+assert.equal(remountedQueue.textContent, "服务端排队中..");
+assert.equal(stopped, 2);
+assert.equal(queued.hasAttribute("data-mineru-local-animation"), false);
+
+const localQueue = makeSpan();
+currentStatus = makeStatus(null, null, localQueue, "queued_locally");
+now = 12300;
+timer.sync();
+assert.equal(localQueue.textContent, "本地排队中.");
+assert.equal(stopped, 3);
+
+// 进入解析时停止排队动画并切换到 10 毫秒计时;离开后两种定时器都停止。
+const afterQueue = makeSpan();
+currentStatus = makeStatus("400.000000000", 0.04, afterQueue);
+now = 12400;
+timer.sync();
+assert.equal(intervalMs, 10);
+assert.equal(afterQueue.textContent, "服务端解析中(0.04 秒)");
+assert.equal(localQueue.hasAttribute("data-mineru-local-animation"), false);
+currentStatus = null;
+timer.sync();
+assert.equal(tick, null);
+
+// 新任务点击时须立即切到准备阶段,并停止上一任务仍在运行的本地计时。
+const preparingSpan = makeSpan();
+const titleSpan = makeSpan();
+const latestAttributes = new Map([
+ ["data-mineru-processing-start", "300.000000000"],
+ ["data-mineru-processing-elapsed", "0.010000"],
+ ["data-mineru-queue-key", "queued_on_server"],
+]);
+const steps = Array.from({ length: 8 }, () => {
+ const values = new Set(["is-done"]);
+ return {
+ values,
+ classList: {
+ toggle(name, enabled) { if (enabled) values.add(name); else values.delete(name); },
+ remove(...names) { names.forEach((name) => values.delete(name)); },
+ },
+ };
+});
+currentPanel = {
+ querySelectorAll() { return steps; },
+ querySelector(selector) {
+ if (selector === ".status-panel-title [data-mineru-i18n-key]") return titleSpan;
+ if (selector === ".status-latest") {
+ return {
+ removeAttribute(name) { latestAttributes.delete(name); },
+ querySelector() { return preparingSpan; },
+ };
+ }
+ return null;
+ },
+};
+currentStatus = makeStatus("300.000000000", 0.01, preparingSpan);
+timer.sync();
+assert.ok(tick);
+timer.showPreparing();
+assert.equal(tick, null);
+assert.equal(titleSpan.textContent, "最新状态");
+assert.equal(preparingSpan.textContent, "正在准备请求…");
+assert.equal(preparingSpan.getAttribute("data-mineru-i18n-key"), "preparing_request");
+assert.equal(latestAttributes.size, 0);
+assert.ok(steps[0].values.has("is-active"));
+assert.ok(steps.slice(1).every((step) => step.values.has("is-pending")));