Skip to content

Fast, accurate OCR with correctness assessment.

Document the local Web Demo API and translate its comments to English.

hezhihuie548d3c48955
diff --git a/docs/SKILL.md b/docs/SKILL.md
index e683ec6..21319c9 100644
--- a/docs/SKILL.md
+++ b/docs/SKILL.md
@@ -1,6 +1,6 @@
---
name: minicpmvocr-sdk
-description: 安装、部署和验证 MiniCPM-OCR 1.0 文档解析 SDK 与 vLLM、SGLang 或 llama.cpp 推理服务,包括 DSpark、PDF/图片转 Markdown 和安装排错。Jev 打分服务使用 SKILL_jev.md。
+description: 安装、部署和验证 MiniCPM-OCR 1.0 文档解析 SDK 与 vLLM、SGLang 或 llama.cpp 推理服务,包括 DSpark、PDF/图片转 Markdown、本地 Web Demo 和安装排错。Jev 打分服务使用 SKILL_jev.md。
---
# MiniCPM-OCR 1.0 安装、部署与验证
@@ -17,6 +17,7 @@ SDK(命令 `minicpmvocr`,发行包 `minicpm-ocr`)负责版面检测、切
| Linux x86_64 + NVIDIA,选择 SGLang | `.venv-sglang`,可用 DSpark | `sglang` | [SGLang 指南](./sglang_deploy_zh.md) |
| CPU、本地 GPU 或 Apple Silicon,选择 llama.cpp | `sources/llama.cpp/build`,使用 GGUF,可用 DSpark | `llamacpp` | [llama.cpp 指南](./llamacpp_deploy_zh.md) |
| 已有兼容推理服务 | 复用服务,只装 SDK | 按服务协议选择 | 本文第 7 节 |
+| 第 7 节已跑通全页解析,要开本地页面 | 复用 `.minicpm-ocr` 和已有识别服务 | 按识别服务 | [Web Demo 部署教程](./webdemo_deploy_zh.md) 与本文第 9 节 |
- SGLang 使用 `--backend sglang`;SDK 内部将 `sglang` 映射到 `openai` 兼容客户端,`list-backends` 不单独列出 SGLang。llama.cpp 用 `llamacpp`,不要复用 vLLM 特有请求字段。
- llama.cpp 的 Metal 服务不要求 CUDA;完整解析还需要能运行 PP-DocLayoutV3 的 SDK 环境。若本机没有对应 PaddlePaddle wheel,单独安排兼容的 SDK 主机,不把 Metal 服务可用当成整个 SDK 已可用。
@@ -415,3 +416,30 @@ curl --noproxy 127.0.0.1 -fsS http://127.0.0.1:18499/metrics | grep spec_decode_
汇报实际使用的后端、源码 SHA/包版本、模型文件、设备、地址,以及安装检查、健康检查、带图请求、单页解析分别通过与否。安装成功、服务就绪、识别正确、DSpark 生效是不同结论。不要在排错时删除用户环境、重置源码或用未核实的临时补丁掩盖版本不匹配。
参数与 API 细节见 [SDK 配置说明](./minicpm_ocr_sdk_api.md);Jev 打分服务使用 [Jev Skill](./SKILL_jev.md),不混用其权重、分类架构和验证标准。
+
+## 9. 可选:本地 Web Demo
+
+第 7 节全页解析已经通过后,才启动本地页面。命令和注释以 [Web Demo 部署教程](./webdemo_deploy_zh.md) 为准,不要另写一套启动方式。
+
+在已经跑通的 `.minicpm-ocr` 环境里补页面服务,并准备旋转自适应模型:
+
+```bash
+source .minicpm-ocr/bin/activate
+python -m pip install fastapi uvicorn python-multipart
+bash webdemo/backend/prepare_upright_models.sh
+```
+
+识别服务沿用第 4–6 节已经在跑的 `minicpm-ocr`,地址是 `http://127.0.0.1:18499`。后端的 `OCR_ENGINE_TYPE` 按实际服务填写:vLLM 为 `vllm`,SGLang 为 `openai`,llama.cpp 为 `llamacpp`。Ollama 见部署教程。后端默认端口 `8966`,旋转自适应默认打开,模型目录是 `models/paddle_upright`。`curl -f http://127.0.0.1:8966/health` 返回 `{"status":"ok"}` 只说明进程已起来。
+
+前端需要 Node.js 22 或更高版本。在 `webdemo/frontend` 用 Corepack 安装依赖并启动后,打开 `http://localhost:5173/playground/document-parse`。关键信息抽取页是 `http://localhost:5173/playground/field-extract`。
+
+后端同样也提供了 API 服务,以下是相关的 API 接口。
+
+| 接口 | 用途 |
+|---|---|
+| `POST /api/document-parse/jobs` | 异步图片或 PDF,HTTP 200 返回任务 |
+| `GET /api/document-parse/jobs/{id}` | HTTP 200 返回进度与结果 |
+| `DELETE /api/document-parse/jobs/{id}` | 取消任务,HTTP 200 返回任务状态 |
+| `POST /api/kie` | 同步单图,HTTP 200 返回单页响应 |
+
+文档解析的图片和 PDF 都创建任务,响应里 `status` 为 `Running`。关键信息抽取走 `POST /api/kie`,只接受单张图片:JSON 请求体带 `image` 和 `fields`。这一路不创建任务,也不接收 PDF。关键信息抽取的异步形式可以参照文档解析进行改造。
diff --git a/docs/SKILL_en.md b/docs/SKILL_en.md
index 0546e04..c49a5cc 100644
--- a/docs/SKILL_en.md
+++ b/docs/SKILL_en.md
@@ -1,6 +1,6 @@
---
name: minicpmvocr-sdk
-description: Install, deploy and verify the MiniCPM-OCR 1.0 document parsing SDK with vLLM, SGLang or llama.cpp, including DSpark, PDF/image to Markdown and installation troubleshooting. Use SKILL_jev_en.md for Jev scoring services.
+description: Install, deploy and verify the MiniCPM-OCR 1.0 document parsing SDK with vLLM, SGLang or llama.cpp, including DSpark, PDF/image to Markdown, the local Web Demo and installation troubleshooting. Use SKILL_jev_en.md for Jev scoring services.
---
# MiniCPM-OCR 1.0 installation, deployment and verification
@@ -17,6 +17,7 @@ The SDK (command `minicpmvocr`, distribution `minicpm-ocr`) detects layout, crop
| Linux x86_64 + NVIDIA, SGLang selected | `.venv-sglang`, DSpark available | `sglang` | [SGLang guide](./sglang_deploy.md) |
| CPU, local GPU or Apple Silicon, llama.cpp selected | `sources/llama.cpp/build`, GGUF weights, DSpark available | `llamacpp` | [llama.cpp guide](./llamacpp_deploy.md) |
| Existing compatible inference service | Reuse it; install only the SDK | Select by protocol | Section 7 below |
+| Section 7 full-page parse already works, and a local page is needed | Reuse `.minicpm-ocr` and the running recognition service | Match the recognition service | [Web Demo deployment tutorial](./webdemo_deploy.md) and section 9 below |
- Use `--backend sglang` for SGLang. The SDK internally maps `sglang` to the `openai`-compatible client; `list-backends` does not list SGLang separately. Select `llamacpp` for llama.cpp and avoid vLLM-specific request fields.
- A llama.cpp Metal server does not require CUDA. Full parsing also needs an SDK environment that can run PP-DocLayoutV3. If PaddlePaddle has no matching local wheel, use a compatible SDK host; a working Metal server alone does not validate the entire SDK.
@@ -415,3 +416,30 @@ Report vLLM DSpark as active only when draft / accepted-token metrics increase w
Report the actual backend, source SHAs/package versions, model files, device, endpoint and the separate outcomes of installation checks, health checks, image requests and one-page parsing. Installation success, service readiness, correct recognition and active DSpark are distinct conclusions. Do not delete user environments, reset source or conceal version mismatches with unverified temporary patches.
See [SDK configuration](./minicpm_ocr_sdk_api_en.md) for parameter and API details. For Jev scoring, use the [Jev Skill](./SKILL_jev_en.md); its weights, classification architecture and validation criteria are separate.
+
+## 9. Optional: local Web Demo
+
+Start the local page only after the full-page parse in section 7 has passed. Follow the commands and comments in the [Web Demo deployment tutorial](./webdemo_deploy.md). Do not invent a second startup procedure.
+
+On the `.minicpm-ocr` environment that already parses pages, add the page server packages and prepare the rotation-adaptation models:
+
+```bash
+source .minicpm-ocr/bin/activate
+python -m pip install fastapi uvicorn python-multipart
+bash webdemo/backend/prepare_upright_models.sh
+```
+
+Keep the `minicpm-ocr` recognition service from sections 4–6 running at `http://127.0.0.1:18499`. Set the backend `OCR_ENGINE_TYPE` from that service: `vllm` for vLLM, `openai` for SGLang, and `llamacpp` for llama.cpp. Ollama is covered in the deployment tutorial. The backend listens on `8966` by default. Rotation adaptation is on by default and uses `models/paddle_upright`. `curl -f http://127.0.0.1:8966/health` returning `{"status":"ok"}` means the process is up.
+
+The frontend needs Node.js 22 or later. After installing dependencies with Corepack and starting the dev server in `webdemo/frontend`, open `http://localhost:5173/playground/document-parse`. Key information extraction is at `http://localhost:5173/playground/field-extract`.
+
+The backend also provides an API. The endpoints are listed below.
+
+| Endpoint | Purpose |
+|---|---|
+| `POST /api/document-parse/jobs` | Async image or PDF. HTTP 200 returns a job |
+| `GET /api/document-parse/jobs/{id}` | HTTP 200 returns progress and results |
+| `DELETE /api/document-parse/jobs/{id}` | Cancel the job. HTTP 200 returns the job status |
+| `POST /api/kie` | Sync single image. HTTP 200 returns one page |
+
+Document parsing creates a job for both images and PDFs. The response `status` is `Running`. Key information extraction uses `POST /api/kie` and accepts one image: a JSON body with `image` and `fields`. That call does not create a job and does not accept a PDF. The async form of key information extraction can be adapted by following document parsing.
diff --git a/docs/webdemo_deploy.md b/docs/webdemo_deploy.md
index c1b429e..975e369 100644
--- a/docs/webdemo_deploy.md
+++ b/docs/webdemo_deploy.md
@@ -77,3 +77,16 @@ VITE_OCR_TARGET=http://127.0.0.1:8966 corepack pnpm dev --host --port 5173 --str
```
Open **`http://localhost:5173/playground/document-parse`** to try the local Web Demo.
+
+## 5. API
+
+The backend also provides an API. The endpoints are listed below.
+
+| Endpoint | Purpose |
+|---|---|
+| `POST /api/document-parse/jobs` | Async image or PDF. HTTP 200 returns a job |
+| `GET /api/document-parse/jobs/{id}` | HTTP 200 returns progress and results |
+| `DELETE /api/document-parse/jobs/{id}` | Cancel the job. HTTP 200 returns the job status |
+| `POST /api/kie` | Sync single image. HTTP 200 returns one page |
+
+Document parsing creates a job for both images and PDFs. The response `status` is `Running`. Key information extraction uses `POST /api/kie` and accepts one image: a JSON body with `image` and `fields`. That call does not create a job and does not accept a PDF. The async form of key information extraction can be adapted by following document parsing.
diff --git a/docs/webdemo_deploy_zh.md b/docs/webdemo_deploy_zh.md
index c170b2d..3760cce 100644
--- a/docs/webdemo_deploy_zh.md
+++ b/docs/webdemo_deploy_zh.md
@@ -77,3 +77,16 @@ VITE_OCR_TARGET=http://127.0.0.1:8966 corepack pnpm dev --host --port 5173 --str
```
打开 **`http://localhost:5173/playground/document-parse`**,即可开始体验本地的 WebDemo!
+
+## 5. 接口
+
+后端同样也提供了 API 服务,以下是相关的 API 接口。
+
+| 接口 | 用途 |
+|---|---|
+| `POST /api/document-parse/jobs` | 异步图片或 PDF,HTTP 200 返回任务 |
+| `GET /api/document-parse/jobs/{id}` | HTTP 200 返回进度与结果 |
+| `DELETE /api/document-parse/jobs/{id}` | 取消任务,HTTP 200 返回任务状态 |
+| `POST /api/kie` | 同步单图,HTTP 200 返回单页响应 |
+
+文档解析的图片和 PDF 都创建任务,响应里 `status` 为 `Running`。关键信息抽取走 `POST /api/kie`,只接受单张图片:JSON 请求体带 `image` 和 `fields`。这一路不创建任务,也不接收 PDF。关键信息抽取的异步形式可以参照文档解析进行改造。
diff --git a/webdemo/backend/README.md b/webdemo/backend/README.md
deleted file mode 100644
index 3e9d7e7..0000000
--- a/webdemo/backend/README.md
+++ /dev/null
@@ -1,62 +0,0 @@
-# MiniCPM-OCR webdemo 后端
-
-文档解析页的工人进程。版面检测在本进程里完成,旋转自适应默认打开,识别发给已经在跑的推理服务。部署步骤见 [中文指南](../../docs/webdemo_deploy_zh.md) 和 [English guide](../../docs/webdemo_deploy.md)。页面实际调用的接口见 [`SERVICE.md`](SERVICE.md)。
-
-```
-浏览器 → 前端(VITE_OCR_TARGET)
- → 本进程
- ├── 旋转自适应:本进程里的模型
- ├── 版面:本进程里的检测器
- └── 识别:OCR_SERVER_URL 上已经在跑的服务
-```
-
-本进程不启动识别服务。识别可以是 vLLM、SGLang、llama.cpp、Ollama,或其它 OpenAI 兼容服务,由 `OCR_ENGINE_TYPE` 和 `OCR_SERVER_URL` 指定。
-
-## 启动
-
-在仓库根目录按部署指南准备环境和模型,然后:
-
-```bash
-export OCRWEB_PYTHON=python
-export OCR_ENGINE_TYPE=vllm
-export OCR_SERVER_URL=http://127.0.0.1:18499
-export OCR_SERVED_NAME=minicpm-ocr
-export OCR_LAYOUT_MODEL_DIR="$PWD/models/PP-DocLayoutV3_infer"
-export OCR_LAYOUT_DEVICE=cuda
-export OCR_LAYOUT_WORKERS=1
-bash start_local_worker.sh
-```
-
-脚本默认监听 `8966`,默认模型名是 `minicpm-ocr`,与前端代理和识别指南一致。`--workers` 固定为 1:任务表在这个进程的内存里。
-
-旋转自适应默认打开,模型目录是仓库里的 `models/paddle_upright`,设备是 `cpu`。`OCR_UPRIGHT_WORKERS=0` 时本进程不加载模型。
-
-路径和解释器都从环境变量传入。`env.sh` 只根据脚本自身的位置找到仓库和 `sdk/`。
-
-## 环境变量
-
-| 变量 | 作用 | 不设时 |
-|---|---|---|
-| `OCRWEB_PYTHON` | 本进程的解释器 | 启动脚本要求必填 |
-| `OCR_SDK_DIR` | `PYTHONPATH` 里的 SDK | 本仓库的 `sdk/` |
-| `OCR_LAYOUT_MODEL_DIR` | 版面模型目录 | 启动脚本要求必填 |
-| `OCR_LAYOUT_PROVIDER` | 版面实现 | `ppdoclayout3_paddlex`。safetensors 用 `ppdoclayout3_torch` |
-| `OCR_LAYOUT_DEVICE` | 版面设备 | `cuda` |
-| `OCR_LAYOUT_DEVICES` | 每套检测器的设备 | 按可见 GPU 或 `OCR_LAYOUT_DEVICE` |
-| `OCR_LAYOUT_WORKERS` | 版面检测器数量 | `4` |
-| `OCR_ENGINE_TYPE` | 识别后端 | `vllm`。还可设 `llamacpp`、`ollama`、`openai` |
-| `OCR_SERVER_URL` | 识别服务地址 | 启动脚本要求必填。`VLLM_URL` 是同一项 |
-| `OCR_SERVED_NAME` | 识别服务上的模型名 | `minicpm-ocr` |
-| `OCR_UPRIGHT_DIR` | 旋转自适应模型的父目录 | `models/paddle_upright` |
-| `OCR_UPRIGHT_WORKERS` | 本进程里的模型数量 | `1`。`0` 表示不加载 |
-| `OCR_UPRIGHT_DEVICE` | 旋转自适应设备 | `cpu` |
-| `OCR_UPRIGHT_REGISTRY` | 摆正服务登记目录 | `backend/data/upright-workers`。空字符串表示不找远程摆正 |
-| `PORT` | 本进程端口 | `8966` |
-| `VITE_OCR_TARGET` | 前端把解析请求转到这里 | `http://127.0.0.1:8966` |
-
-## 已知限制
-
-- 文档解析接口没有鉴权。对外发布页面,不要把工人端口暴露到公网。
-- 任务目录写在 `backend/data/jobs/`,进程不会删除。
-- 版面和摆正模型在第一次解析时加载。之后改环境变量要重启本进程。
-- 重启后,内存里的任务 id 不再有效。
diff --git a/webdemo/backend/SERVICE.md b/webdemo/backend/SERVICE.md
deleted file mode 100644
index a346603..0000000
--- a/webdemo/backend/SERVICE.md
+++ /dev/null
@@ -1,69 +0,0 @@
-# Webdemo 服务说明
-
-部署步骤见 [中文指南](../../docs/webdemo_deploy_zh.md) 和 [English guide](../../docs/webdemo_deploy.md)。本文只说明这个进程怎么接页面。
-
-## 进程
-
-入口是 `server.py`。`start_local_worker.sh` 用一个进程启动它,默认端口 `8966`:
-
-```bash
-python -s -m uvicorn server:app --host 0.0.0.0 --port "${PORT:-8966}" --workers 1
-```
-
-解释器由 `OCRWEB_PYTHON` 指定。必须加 `-s`,并设置 `PYTHONNOUSERSITE=1`,避免加载用户目录里的另一套包。`backend/env.sh` 把 `PYTHONPATH` 指到本仓库的 `sdk/`。
-
-```
-浏览器
- → 前端(VITE_OCR_TARGET,默认 http://127.0.0.1:8966)
- → 本进程
- → 摆正:OCR_UPRIGHT_WORKERS > 0 时用本进程的模型;
- 为 0 时使用 OCR_UPRIGHT_REGISTRY 里 90 秒内更新过的摆正服务
- → 版面:本进程的检测器,数量由 OCR_LAYOUT_WORKERS 决定
- → 识别:OCR_SERVER_URL 上已经在跑的服务,类型是 OCR_ENGINE_TYPE,
- 模型名是 OCR_SERVED_NAME
-```
-
-本进程不加载识别模型,也不启动识别服务。识别服务按对应的部署指南单独运行。
-
-不要把工人端口直接暴露到公网。页面没有登录和 API Key。
-
-## 启动后检查
-
-```bash
-curl --noproxy 127.0.0.1 -f http://127.0.0.1:8966/health
-```
-
-`{"status":"ok"}` 只说明进程在。版面模型在第一份文档时加载,所以第一次解析更慢。
-
-`/ready` 还会请求 `{OCR_SERVER_URL}/v1/models`,并检查其中是否有 `OCR_SERVED_NAME`。Ollama 列出的名称是 `minicpm-ocr:latest`,这时 `/ready` 可能报告名称不一致,解析仍然使用 `OCR_SERVED_NAME`。
-
-## 页面用的接口
-
-`POST /api/document-parse/jobs`
-
-| 字段 | 含义 |
-|---|---|
-| `file` | `pdf`、`png`、`jpg`、`jpeg`、`bmp`、`webp`、`tif`、`tiff` |
-| `upright` | 默认 `true`。本进程没有摆正模型、登记目录里也没有新的摆正服务时,这一项会被忽略 |
-| `page_index` | 可选。只解析 PDF 的这一页,从 0 开始 |
-
-返回 `id`、`status`、`pages_done`、`pages_total` 和 `pages`。
-
-`GET /api/document-parse/jobs/{id}` 轮询进度。做完的页会出现在 `pages` 里。状态为 `Running`、`Success`、`Failed`、`Cancelled`。
-
-`DELETE /api/document-parse/jobs/{id}` 把任务标成 `Cancelled`。已经在跑的那一页会跑完。
-
-任务表只在这个进程的内存里。重启之后,旧的任务地址返回 404。磁盘上的文件还在 `backend/data/jobs/<id>/`:
-
-| 路径 | 内容 |
-|---|---|
-| `input/` | 上传的原文件 |
-| `runtime/intermediate/layouts/` | 版面框 |
-| `results_json/` | 这一页的识别结果 |
-| `output/` | 拼好的 Markdown |
-
-## 一次解析
-
-一页依次进入摆正、版面和识别。版面检测器一次服务一页,切完归还。切出的图块发给识别服务。印章和图表会送去识别。页面上的展示开关不重新发请求。
-
-改了 `webdemo/backend/` 或 `sdk/minicpmvocr/` 之后,用同一组环境变量重启这一个进程。识别服务可以继续运行。
diff --git a/webdemo/backend/document_jobs.py b/webdemo/backend/document_jobs.py
index 5a6c9b5..7d225bf 100644
--- a/webdemo/backend/document_jobs.py
+++ b/webdemo/backend/document_jobs.py
@@ -1,6 +1,7 @@
-"""把上传的图片或 PDF 交给本机 page-worker 解析。
+"""Hand an uploaded image or PDF to the local page worker.
-前端按页轮询。检测器仍只在切页时占用,摆正和识别走各自的队列。
+The frontend polls page by page. A detector is held only while that page is
+being cut. Rotation adaptation and recognition each have their own queue.
"""
from __future__ import annotations
@@ -46,7 +47,7 @@ def _extract_page(src: Path, index: int, dest: Path) -> None:
def _layout_page_index(layout: Dict, stem: str) -> int:
- """PDF 页码写在 source.page_index,文件名 document_page_001 从 1 计。"""
+ """The PDF page number is source.page_index. A name like document_page_001 counts from 1."""
source = layout.get("source") if isinstance(layout.get("source"), dict) else {}
page_index = source.get("page_index", layout.get("page_index"))
if isinstance(page_index, int) and not isinstance(page_index, bool) and page_index >= 0:
diff --git a/webdemo/backend/model_manager.py b/webdemo/backend/model_manager.py
index 0094667..185e6af 100644
--- a/webdemo/backend/model_manager.py
+++ b/webdemo/backend/model_manager.py
@@ -1,14 +1,18 @@
#!/usr/bin/env python3
-"""模型资源管理。
-
-负责:
- 1. 模型资源懒加载(layout detector、upright corrector、vLLM backend)
- 2. 构建每次请求的 SDK 配置(build_cfg)
-并发模型:摆正、版面、分块识别各有一条队列。
-请求先进入摆正队列;摆正结束才从版面池借一套检测器,这一页切完立刻归还;
-切出来的块进入共享识别队列。检测器不会在等摆正或等 vLLM 时空占着。
-layout detector 是 paddle predictor,不能多线程共用,所以按 LAYOUT_WORKERS
-建池,一页借一套。多张卡时按 OCR_LAYOUT_DEVICES 把副本摊到各卡上,池子仍是一条。
+"""Model resource manager.
+
+It does two things:
+ 1. Load model resources lazily (layout detector, rotation-adaptation corrector, vLLM backend)
+ 2. Build the SDK config for each request (build_cfg)
+Rotation adaptation, layout, and crop recognition each have their own queue.
+A request enters the rotation-adaptation queue first. Only after that finishes
+does it borrow a detector from the layout pool, and the detector is returned
+as soon as this page is cut. The crops then enter the shared recognition queue.
+A detector is not held while waiting on rotation adaptation or vLLM.
+The layout detector is a Paddle predictor and cannot be shared across threads,
+so the pool has LAYOUT_WORKERS copies and one page borrows one copy. With
+several GPUs, OCR_LAYOUT_DEVICES spreads the copies across cards. The pool
+itself stays one queue.
"""
from __future__ import annotations
@@ -41,14 +45,14 @@ CONFIG_PATH = Path(os.environ.get(
DATA_DIR = Path(os.environ.get("OCRWEB_DATA_DIR", BASE / "data"))
JOBS_DIR = DATA_DIR / "jobs"
-# 版面池大小。每套检测器同一时刻只服务一页,页切完就归还。
+# Layout pool size. Each detector serves one page at a time and is returned when that page is cut.
LAYOUT_WORKERS = int(os.environ.get("OCR_LAYOUT_WORKERS", "3"))
-# 摆正队列的工人数。每个工人一套模型,页可以来自不同请求、不同文件。
+# Workers on the rotation-adaptation queue. Each worker has its own model. Pages may come from different requests and files.
UPRIGHT_WORKERS = int(os.environ.get("OCR_UPRIGHT_WORKERS", "8"))
-# pipeline 级别的固定覆盖:人在等,所以版面与识别重叠。
-# 整页图和 crop 默认不落盘(大图 PNG 编码是版面阶段的大头);
-# 只有单块重算要从磁盘读 crop,由 build_cfg(save_crops=True) 单独打开。
+# Fixed pipeline overrides: a person is waiting, so layout and recognition overlap.
+# Full-page images and crops are not written to disk by default. Encoding a large PNG dominates the layout stage.
+# Only a single-block rerun reads crops from disk, and build_cfg(save_crops=True) turns that on by itself.
WEBUI_OVERRIDES: Dict = {
"pipeline": {
"overlap_layout": True,
@@ -58,8 +62,8 @@ WEBUI_OVERRIDES: Dict = {
"logging": {"progress_log_every": 5},
}
-# RM/TTS 配方(见 docs/rm-tts-pipeline.md)
-# rm_url / rm_input_form 通过 ${VAR:-fallback} 语法在 load_config 时展开
+# RM/TTS recipes (see docs/rm-tts-pipeline.md)
+# rm_url / rm_input_form expand through ${VAR:-fallback} when load_config runs.
RM_URL = "${OCR_RM_URL:-http://127.0.0.1:8000}"
RM_INPUT_FORM = "${OCR_RM_INPUT_FORM:-}"
@@ -96,16 +100,16 @@ SUPPORTED_SUFFIXES = {".pdf", ".png", ".jpg", ".jpeg", ".bmp", ".webp", ".tif",
# ===================================================================
-# 工具函数
+# Helpers
# ===================================================================
def new_job_id() -> str:
- """生成唯一 job id,同时也用作 request_id(32 位小写 hex)。"""
+ """A unique job id, also used as request_id (32 lowercase hex characters)."""
return hashlib.md5(os.urandom(16) + str(time.time()).encode()).hexdigest()
def _fresh_upright_registry() -> bool:
- """登记目录里有一份 90 秒内更新过的工人记录,才算有远程摆正。"""
+ """Remote rotation adaptation is available only when the registry has a worker record updated within 90 seconds."""
registry = os.environ.get("OCR_UPRIGHT_REGISTRY", "").strip()
if not registry:
return False
@@ -123,10 +127,10 @@ def _fresh_upright_registry() -> bool:
def layout_devices(count: int) -> list:
- """每套版面模型放哪张卡。池子仍是一条,空闲的那套接下一个页。
+ """Which GPU each layout model uses. The pool is still one queue, and the idle copy takes the next page.
- OCR_LAYOUT_DEVICES=cuda:0,cuda:0,cuda:1,cuda:1 时按列出的顺序。
- 没写时,可见卡多于一张就轮流放;只有一张卡就全部用 OCR_LAYOUT_DEVICE。
+ OCR_LAYOUT_DEVICES=cuda:0,cuda:0,cuda:1,cuda:1 follows the listed order.
+ When unset, more than one visible GPU rotates the copies. A single GPU uses OCR_LAYOUT_DEVICE for all of them.
"""
count = max(1, int(count))
spec = os.environ.get("OCR_LAYOUT_DEVICES", "").strip()
@@ -144,7 +148,7 @@ def layout_devices(count: int) -> list:
def _webui_overrides(**sections) -> Dict:
- """把 WEBUI_OVERRIDES 和本次请求的覆盖合并,浅合并一层。"""
+ """Merge WEBUI_OVERRIDES with this request's overrides, one level deep."""
merged = {key: dict(value) for key, value in WEBUI_OVERRIDES.items()}
for key, value in sections.items():
merged.setdefault(key, {}).update(value)
@@ -152,11 +156,11 @@ def _webui_overrides(**sections) -> Dict:
# ===================================================================
-# Runner — 模型资源管理 + 单块重算
+# Runner — model resources and single-block rerun
# ===================================================================
class Runner:
- """模型只加载一次,跨请求复用。线程安全。"""
+ """Models load once and are reused across requests. Thread-safe."""
def __init__(self) -> None:
JOBS_DIR.mkdir(parents=True, exist_ok=True)
@@ -168,12 +172,12 @@ class Runner:
self._upright_loaded = False
# ----------------------------------------------------------------
- # 配置构建
+ # Config building
# ----------------------------------------------------------------
def build_cfg(self, job_id: str, upright: bool,
mode: str = DEFAULT_MODE, save_crops: bool = False) -> Dict:
- """构建一次请求的完整 SDK 配置。"""
+ """Build the full SDK config for one request."""
job_dir = JOBS_DIR / job_id
if upright and UPRIGHT_WORKERS <= 0 and not _fresh_upright_registry():
upright = False
@@ -191,23 +195,23 @@ class Runner:
"limit": 0,
},
upright={"enabled": bool(upright)},
- # 工作台的印章/图表开关只改展示。识别侧始终打开,否则这两类块会被跳过。
+ # The seal and chart switches on the page only change what is shown. Recognition stays on, or those blocks are skipped.
layout={
"use_chart_recognition": True,
"use_seal_recognition": True,
},
pipeline={"save_crops": bool(save_crops)},
- # 配方里有嵌套 dict,并发请求之间不能共享同一份
+ # A recipe holds nested dicts, so concurrent requests cannot share one copy.
tts=copy.deepcopy(TTS_RECIPES[mode]),
)
return load_config(str(CONFIG_PATH), overrides)
# ----------------------------------------------------------------
- # 模型资源
+ # Model resources
# ----------------------------------------------------------------
def _ensure_started(self, cfg: Dict) -> None:
- """模型懒加载:第一次调用时建 engine 和 LAYOUT_WORKERS 套版面资源。"""
+ """Lazy load: the first call builds the engine and LAYOUT_WORKERS layout copies."""
with self._res_lock:
if self._engine is not None:
return
@@ -245,7 +249,7 @@ class Runner:
return {"detector": detector, "device": layout_cfg.get("device", "")}
def staged_resources(self, cfg: Dict) -> Dict:
- """准备三条队列,但不借出版面检测器。"""
+ """Prepare the three queues without borrowing a layout detector."""
self._ensure_started(cfg)
return {
"layout_pool": self._slots,
@@ -255,7 +259,7 @@ class Runner:
}
def borrow(self, cfg: Dict) -> Dict:
- """借一套版面模型。用完调用 release,不必等到这一页的切片结束。"""
+ """Borrow one layout model. Call release when finished. Do not wait for this page's crops to finish."""
self._ensure_started(cfg)
return self._slots.get()
@@ -268,7 +272,7 @@ class Runner:
@contextlib.contextmanager
def acquire(self, cfg: Dict) -> Iterator[Dict]:
- """借一套版面模型;摆正队列是所有请求共用的。"""
+ """Borrow one layout model. The rotation-adaptation queue is shared by every request."""
slot = self.borrow(cfg)
try:
yield self.resources_for(slot)
diff --git a/webdemo/backend/page_fleet.py b/webdemo/backend/page_fleet.py
index 2ddda79..06dff23 100644
--- a/webdemo/backend/page_fleet.py
+++ b/webdemo/backend/page_fleet.py
@@ -1,8 +1,9 @@
#!/usr/bin/env python3
-"""按页把解析分到本机和远程 8 卡机器。
+"""Split a parse across this machine and remote 8-GPU machines, one page at a time.
-本机负责把 PDF 拆成页。每一页要么在本机做版面和 vLLM,要么交给一台远程机器,
-由它自己做版面、再打到它自己的 vLLM,把这一页的 markdown 还回来。
+This machine splits the PDF into pages. Each page is either laid out and
+recognized here, or sent to a remote machine that runs its own layout and its
+own vLLM, then returns that page's markdown.
"""
from __future__ import annotations
@@ -26,26 +27,26 @@ PAGE_REGISTRY = Path(os.environ.get(
def page_slots() -> int:
- """一台机器同时能收下多少页。版面模型检测完就还,这个数按 vLLM 积压来定。"""
+ """How many pages one machine accepts at once. The layout model is returned after detection, so this limit follows the vLLM backlog."""
return max(1, int(os.environ.get("OCR_PAGE_SLOTS", "64") or 64))
def page_window() -> int:
- """一本书同时发出去的页数。上一页的版面还没回来,下一页也可以先送。"""
+ """How many pages of one document are in flight at once. The next page can leave before the previous page's layout comes back."""
return max(1, int(os.environ.get("OCR_PAGE_WINDOW", "8") or 8))
def fleet_enabled() -> bool:
- """远程机器登记之后,新的整本解析才按页分发。工人进程自己不再往外分。"""
+ """Once remote machines register, a new document is dispatched page by page. A worker process does not dispatch further."""
if os.environ.get("OCR_PAGE_ROLE") == "worker":
return False
return bool(_read_remotes())
def dispatch_file(job_id: str, local_path: str, runner, upright=None) -> None:
- """一本书同时送出多页。某一页的版面还没结束,后面的页也可以先发出去。
+ """Send several pages of one document at once. Later pages can leave before an earlier page finishes layout.
- 结果仍按页写进这个任务自己的 results_json,进度查询才能看到。
+ Results are still written per page into this job's results_json, so progress queries can see them.
"""
fleet = get_fleet()
pages = _iter_pages(local_path)
@@ -96,7 +97,7 @@ def dispatch_file(job_id: str, local_path: str, runner, upright=None) -> None:
class PageHandle:
- """一页的两段:版面结束就可以收下一块模型,markdown 要等切片队列。"""
+ """Two stages of one page: the model can be reclaimed when layout finishes. Markdown waits on the crop queue."""
def __init__(self) -> None:
self.layout_done = threading.Event()
@@ -113,9 +114,9 @@ class PageHandle:
def run_releasing_layout(runner, cfg, on_layout_idle=None):
- """摆正、版面、分块识别分三段排队。
+ """Rotation adaptation, layout, and crop recognition each wait in their own queue.
- 检测器只在这一页做版面和切块时借出,切完就回到池里。切片识别继续在共享队列里跑。
+ A detector is borrowed only while this page is laid out and cut, then returned to the pool. Crop recognition continues on the shared queue.
"""
from minicpmvocr import pipelined_run
return pipelined_run(
@@ -126,7 +127,7 @@ def run_releasing_layout(runner, cfg, on_layout_idle=None):
def launch_local_page(runner, png_bytes: bytes, upright=None) -> PageHandle:
- """后台识别一页。版面结束时 handle.layout_done 置位,整页结束时 handle.done 置位。"""
+ """Recognize one page in the background. handle.layout_done is set when layout finishes, and handle.done when the whole page finishes."""
handle = PageHandle()
def work() -> None:
@@ -170,7 +171,7 @@ def launch_local_page(runner, png_bytes: bytes, upright=None) -> PageHandle:
def run_local_page(runner, png_bytes: bytes) -> str:
- """同步识别一页。远程接口改走票据,这里留给需要整页结果的调用。"""
+ """Recognize one page synchronously. Remote calls now use a ticket; this remains for callers that need the whole page."""
handle = launch_local_page(runner, png_bytes)
handle.done.wait()
if handle.error is not None:
@@ -190,7 +191,7 @@ def remember(handle: PageHandle) -> str:
def take_markdown(ticket: str):
- """解码没完返回 None。完成则取出这一页的正文和切片,失败则抛出。"""
+ """Return None while decoding is unfinished. When it finishes, return this page's text and crops, or raise on failure."""
with _TICKET_LOCK:
item = _TICKETS.get(ticket)
if item is None:
@@ -206,7 +207,7 @@ def take_markdown(ticket: str):
def coerce_upright(value):
- """请求里的摆正开关。缺省是 None,由解析端按现有配置决定。"""
+ """Rotation-adaptation switch from the request. The default is None, and the parser decides from its current config."""
if value is None:
return None
if isinstance(value, bool):
@@ -215,7 +216,7 @@ def coerce_upright(value):
def resolve_upright(choice) -> bool:
- """显式 false 时跳过摆正。其余情况仍要本机有摆正模型才开启。"""
+ """Skip rotation adaptation when this is explicitly false. Otherwise it stays on only if this machine has the model."""
if choice is False:
return False
upright_dir = os.environ.get("OCR_UPRIGHT_DIR", "")
@@ -233,7 +234,7 @@ class _Slot:
class PageFleet:
def __init__(self) -> None:
- # 分发进程自己不做版面。本机工人和其他副本一样,靠登记目录进来。
+ # The dispatcher does not run layout. The local worker joins through the registry, the same way other replicas do.
local_cap = 0 if os.environ.get("OCR_PAGE_ROLE") == "dispatcher" else page_slots()
self._local = _Slot("local", local_cap)
self._remotes: Dict[str, _Slot] = {}
@@ -242,7 +243,7 @@ class PageFleet:
self._turn = 0
def start(self, runner, png_bytes: bytes, upright=None) -> "_Inflight":
- """占一个页名额,等到这一页的摆正和版面结束就返回。切片还在解码。"""
+ """Take one page slot and return when this page's rotation adaptation and layout finish. Crops are still decoding."""
tried: List[str] = []
last = "没有可以关闭摆正的解析机器" if upright is False else "没有可用的解析机器"
while len(tried) < 6:
@@ -280,7 +281,7 @@ class PageFleet:
slot for slot in [self._local] + list(self._remotes.values())
if slot.name not in exclude and slot.down_until <= now
]
- # 关掉摆正的页只送给登记了这个开关的机器,避免旧进程仍去摆正。
+ # A page with rotation adaptation off goes only to a machine that registered that switch, so an old process does not still rotate it.
if upright is False:
capable = [slot for slot in choices if slot.upright_choice]
if not capable:
@@ -290,7 +291,7 @@ class PageFleet:
return None
free = [slot for slot in choices if slot.inflight < slot.capacity]
if free:
- # 空位一样多时轮流分,本机不再因为排在前面而总是先拿到。
+ # When free slots are equal, take turns. The local machine is no longer always first just because it is listed first.
best = max(slot.capacity - slot.inflight for slot in free)
tied = [slot for slot in free if slot.capacity - slot.inflight == best]
tied.sort(key=lambda item: item.name)
@@ -350,7 +351,7 @@ def _read_remotes() -> Dict[str, tuple]:
except Exception:
continue
url = str(row.get("url") or "").rstrip("/")
- # 旧进程只回 markdown。slices 缺了就不再把页分过去,避免成功结果里坐标是空的。
+ # An old process returns markdown only. Skip it when slices is missing, so a successful result is not left with empty coordinates.
if url and int(row.get("slices") or 0) >= 1:
found[url] = (max(1, int(row.get("slots") or 8)), bool(row.get("upright_choice")))
return found
@@ -361,7 +362,7 @@ def _opener():
def _remote_layout(url: str, png_bytes: bytes, upright=None) -> str:
- """送到远程做摆正和版面。返回票据,切片还在对方的队列里。"""
+ """Send the page to a remote machine for rotation adaptation and layout. Returns a ticket; crops stay on that machine's queue."""
headers = {"Content-Type": "image/png"}
if upright is False:
headers["X-OCR-Upright"] = "0"
@@ -398,7 +399,7 @@ def _remote_markdown(url: str, ticket: str) -> str:
class _Inflight:
- """页名额一直占到 markdown 回来。"""
+ """The page slot stays taken until the markdown comes back."""
def __init__(self, fleet: "PageFleet", slot: _Slot, payload) -> None:
self._fleet = fleet
@@ -464,7 +465,7 @@ def _payload_from_body(body: Dict) -> Dict:
def _public_slices(result: Dict, layout: Dict) -> Dict:
- """页结果收成对外的切片。图块没有识别文本,坐标就是这块图在页面上的框。"""
+ """Turn a page result into the public crops. A figure block has no recognized text; its coordinates are that figure's box on the page."""
layout = layout or {}
by_crop = {
block.get("crop_filename", ""): block
@@ -502,7 +503,7 @@ def _public_slices(result: Dict, layout: Dict) -> Dict:
def _png_size(png_bytes: bytes):
- """摆正前那张图的像素。只读文件头。"""
+ """Pixel size of the image before rotation adaptation. Reads the file header only."""
import io
from PIL import Image
with Image.open(io.BytesIO(png_bytes)) as image:
@@ -510,7 +511,7 @@ def _png_size(png_bytes: bytes):
def _public_rotation(layout: Dict):
- """摆正记录收成客户端能复现的角度。没有记录时返回 None。"""
+ """Turn the rotation-adaptation record into angles the client can reproduce. Returns None when there is no record."""
raw = (layout or {}).get("upright")
if not raw:
return None
@@ -562,7 +563,7 @@ def _own_ip() -> str:
def advertise(port: int) -> None:
- """工人进程把地址写到共享目录,本机按这个目录发现它。"""
+ """A worker writes its address into the shared directory, and this machine discovers it from there."""
PAGE_REGISTRY.mkdir(parents=True, exist_ok=True)
host = socket.gethostname()
path = PAGE_REGISTRY / f"{host}-{port}.json"
diff --git a/webdemo/backend/recognition_client.py b/webdemo/backend/recognition_client.py
index ce889fa..d425572 100644
--- a/webdemo/backend/recognition_client.py
+++ b/webdemo/backend/recognition_client.py
@@ -1,14 +1,14 @@
#!/usr/bin/env python3
-"""VLM 识别服务 — HTTP 客户端,封装 vLLM / LIS 的 OpenAI Chat Completions 接口。
+"""VLM recognition client. Wraps the OpenAI Chat Completions API of vLLM or LIS.
-职责:
- - 从 `prompt_map` 按 label 选 prompt
- - 把 PIL.Image 编码为 data URI
- - 拼 vLLM payload(含 TTS 的 decode_overrides / n)
- - 解析响应,归一化为 {"text": ..., "texts": [...], "output_token_count": ...}
- - 健康检查 /v1/models,验证模型名是否匹配
+It does this:
+ - Pick a prompt from `prompt_map` by label
+ - Encode a PIL.Image as a data URI
+ - Build the vLLM payload, including TTS decode_overrides and n
+ - Parse the response into {"text": ..., "texts": [...], "output_token_count": ...}
+ - Check /v1/models and whether the model name matches
-不持有任何任务状态;线程安全(urllib.request 本身是无状态的)。
+It holds no job state. Thread-safe, because urllib.request itself is stateless.
"""
from __future__ import annotations
@@ -22,10 +22,10 @@ from typing import Dict, List, Optional
from PIL import Image
-# 不走系统代理,避免容器内 proxy 配置干扰本地 vLLM
+# Skip the system proxy so a container proxy does not divert the local vLLM.
_OPENER = urllib.request.build_opener(urllib.request.ProxyHandler({}))
-# 与 SDK 配置(minicpmvocr.yaml 的 engine 段)读同一组变量,部署时只设一次
+# Read the same variables as the SDK config (the engine section of minicpmvocr.yaml). Set them once at deploy time.
VLLM_URL = (os.environ.get("OCR_VLLM_URL") or os.environ.get("VLLM_URL")
or "http://127.0.0.1:18499").rstrip("/")
SERVED_MODEL = (os.environ.get("OCR_SERVED_MODEL_NAME") or os.environ.get("OCR_SERVED_NAME")
@@ -51,9 +51,9 @@ def _post(url: str, payload: Dict, timeout: int = 240) -> Dict:
class OcrService:
- """OpenAI Chat Completions 客户端,对接 vLLM 或 LIS。
+ """OpenAI Chat Completions client for vLLM or LIS.
- 所有方法都是无状态的,可以从多个线程并发调用。
+ Every method is stateless and can be called from several threads at once.
"""
def __init__(self, vllm_url: str = VLLM_URL,
@@ -73,7 +73,7 @@ class OcrService:
}
# ------------------------------------------------------------------
- # 对外接口
+ # Public API
# ------------------------------------------------------------------
def recognize(
@@ -85,7 +85,7 @@ class OcrService:
n: int = 1,
decode_overrides: Optional[Dict] = None,
) -> Dict:
- """识别一张块图。
+ """Recognize one crop.
n=1 → {"text": str, "output_token_count": int, "finish_reason": str}
n>1 → {"texts": list[str], "output_token_count": int}
@@ -102,7 +102,7 @@ class OcrService:
return self._parse_response(raw, n)
def health(self) -> Dict:
- """探活:检查 vLLM 是否可达,以及模型名是否匹配。
+ """Liveness: whether vLLM is reachable, and whether the model name matches.
Returns {"reachable": bool, "model_match": bool,
"served": list[str], "error": str|None}
@@ -119,7 +119,7 @@ class OcrService:
"error": f"{type(exc).__name__}: {exc}"}
# ------------------------------------------------------------------
- # 内部实现
+ # Internals
# ------------------------------------------------------------------
def _build_payload(
@@ -159,10 +159,10 @@ class OcrService:
}
if slice_nums is not None:
payload["mm_processor_kwargs"]["max_slice_nums"] = int(slice_nums)
- # TTS 时 n>1,seed 由调用方在 decode_overrides 里传入
+ # For TTS, n>1. The caller passes seed inside decode_overrides.
if n > 1:
payload["n"] = int(n)
- # 把 decode_overrides 里除了已处理键之外的其他采样参数透传
+ # Pass through sampling parameters in decode_overrides other than the keys already applied.
handled = {"temperature", "top_p", "top_k", "repetition_penalty",
"no_repeat_ngram_size"}
if decode_overrides:
diff --git a/webdemo/backend/server.py b/webdemo/backend/server.py
index e5ca06e..d4f14a0 100644
--- a/webdemo/backend/server.py
+++ b/webdemo/backend/server.py
@@ -1,9 +1,11 @@
#!/usr/bin/env python3
-"""MiniCPM-V-OCR 解析后端 — 对外唯一入口。
+"""MiniCPM-V-OCR parse backend. The only public entry.
-工作台接口见同目录 SERVICE.md。纯内部服务,无鉴权。
-用 FastAPI + uvicorn。pipeline 是阻塞的,一律丢进线程池跑,事件循环只做收发;
-摆正、版面、分块识别各走各的队列。版面池的大小是 model_manager.LAYOUT_WORKERS,检测器只在切这一页时占着。
+Deployment and the API are in docs/webdemo_deploy_zh.md. Internal service, no auth.
+FastAPI and uvicorn. The pipeline blocks, so it always runs in a thread pool and
+the event loop only receives and sends. Rotation adaptation, layout, and crop
+recognition each have their own queue. The layout pool size is
+model_manager.LAYOUT_WORKERS. A detector is held only while this page is being cut.
"""
from __future__ import annotations
@@ -38,14 +40,14 @@ import urllib.request
import uvicorn
PORT = int(os.environ.get("PORT", "8966"))
-# source_token 就是整页请求的 job id(32 位小写 hex),据此定位原 job 目录
+# source_token is the full-page job id (32 lowercase hex characters). It locates the original job directory.
SOURCE_TOKEN = re.compile(r"^[a-f\d]{32}$")
-# 上传图原样落盘,不解码重编码;只认这些格式(PIL format → 后缀)
+# Store the uploaded image as-is, without decoding and re-encoding. Only these formats are accepted (PIL format → suffix).
IMAGE_SUFFIX = {"PNG": ".png", "JPEG": ".jpg", "BMP": ".bmp", "WEBP": ".webp", "TIFF": ".tif"}
# -------------------------------------------------------------------
-# 全局单例 — 在 lifespan 里初始化
+# Process-wide singletons, created in the lifespan.
# -------------------------------------------------------------------
RUNNER: Runner = None # type: ignore[assignment]
OCR_SVC: OcrService = None # type: ignore[assignment]
@@ -54,7 +56,7 @@ app = FastAPI(title="minicpmvocr-webdemo", version="1.0")
def _proxy_to_worker(request: Request):
- """用户进程不跑模型。页面解析转到本机工人。"""
+ """The user process does not run models. Page parsing is forwarded to the local worker."""
base = os.environ.get("OCR_LOCAL_WORKER_URL", "http://127.0.0.1:8966").rstrip("/")
url = base + request.url.path
if request.url.query:
@@ -96,7 +98,7 @@ async def _gateway_split(request: Request, call_next):
# ===================================================================
-# 工具函数(与旧版完全一致,保持逻辑不变)
+# Helpers. Same behavior as the previous version.
# ===================================================================
def _make_request_id() -> str:
@@ -153,7 +155,7 @@ def _best_score(block: Dict) -> Optional[float]:
def _block_to_api(lb: Dict, rb: Dict) -> Dict:
- """layout 块 + 识别结果块 → API 块对象。"""
+ """A layout block plus a recognition block becomes one API block."""
regions = lb.get("regions") or [lb.get("bbox", [0, 0, 0, 0])]
tts = rb.get("tts") or {}
score = _best_score(rb)
@@ -171,7 +173,7 @@ def _block_to_api(lb: Dict, rb: Dict) -> Dict:
block["rounds_used"] = tts["rounds_used"]
block["stop_reason"] = tts.get("stop_reason")
block["exhausted"] = bool(tts.get("exhausted"))
- # 跨页合并(见 /api/image-parse/merge):分数只代表合并前的半张表
+ # Cross-page merge (see /api/image-parse/merge): a score only covers the half table from before the merge.
if rb.get("tts_invalid"):
block["tts_invalid"] = True
if rb.get("merged_into_previous_page"):
@@ -192,8 +194,8 @@ def _build_page_response(image_id, layout, result, request_id, mode,
mode_str = {"standard": "ocr_only", "scored": "stp",
"high-precision": "tts"}.get(mode, mode)
- # page_index 原样回填请求值:前端按它校验响应属于哪一页。
- # (单图输入时版面结果里的 source.page_index 恒为空,不能用。)
+ # Echo the request's page_index. The frontend uses it to check which page a response belongs to.
+ # A single-image layout always leaves source.page_index empty, so that field cannot be used.
resp: Dict = {
"metadata": {"page_index": page_index},
@@ -206,7 +208,7 @@ def _build_page_response(image_id, layout, result, request_id, mode,
"blocks": blocks,
},
}
- # 没开摆正就不带 rotation(前端按字段缺失处理为未摆正)
+ # Omit rotation when rotation adaptation is off. The frontend treats a missing field as not adapted.
if upright_enabled:
resp["minicpm_ocr"]["rotation"] = rotation
@@ -234,7 +236,7 @@ def _build_page_response(image_id, layout, result, request_id, mode,
JOB_META = "webdemo_meta.json"
-# 同一个 job 的单块重算会原地改 results_json,按 job 串行
+# A single-block rerun rewrites results_json in place, so reruns of one job run one at a time.
_JOB_LOCKS: Dict[str, threading.Lock] = {}
_JOB_LOCKS_GUARD = threading.Lock()
@@ -245,7 +247,7 @@ def _job_lock(job_id: str) -> threading.Lock:
def _decode_upload(image_b64: str):
- """base64 → (原始字节, 后缀)。只读文件头判断格式,不做整图解码。"""
+ """base64 → (raw bytes, suffix). The format comes from the file header, without decoding the whole image."""
from PIL import Image
_, _, b64data = image_b64.partition(",")
raw = base64.b64decode(b64data or image_b64)
@@ -261,7 +263,7 @@ def _err(code: int, msg: str) -> JSONResponse:
# ===================================================================
-# 路由
+# Routes
# ===================================================================
@app.get("/health")
@@ -298,7 +300,7 @@ def capabilities():
@app.get("/metrics")
def metrics():
- """转发 OCR vLLM 的 Prometheus 指标:LIS 每 15s 抓一次(没有它就是 404)。"""
+ """Forward the OCR vLLM Prometheus metrics. LIS scrapes them every 15s, and a missing endpoint is a 404."""
import urllib.request
try:
with urllib.request.urlopen(VLLM_URL + "/metrics", timeout=5) as r:
@@ -308,12 +310,13 @@ def metrics():
# ===================================================================
-# LIS 入口:OpenAI Chat Completions 形状
+# LIS entry: OpenAI Chat Completions shape.
# ===================================================================
-# LIS 网关按 `model`=服务名(--served-model-name)路由到 /v1/chat/completions,
-# 所以经 LIS 调用时档位不能再放在 `model` 里,改从 `minicpm_ocr.mode` 读。
-# 四个档位名直接当 `model` 也照旧可用。业务字段既可放在 `minicpm_ocr` 里,也可以按
-# /api/image-parse 的写法放在顶层(image / page_index / order / source_token / pages)。
+# The LIS gateway routes by `model` equal to the service name (--served-model-name)
+# to /v1/chat/completions, so a call through LIS cannot put the tier in `model`.
+# Read it from `minicpm_ocr.mode` instead. The four tier names still work as `model`.
+# Business fields can sit inside `minicpm_ocr`, or at the top level the same way as
+# /api/image-parse (image / page_index / order / source_token / pages).
LIS_SERVED_MODEL_NAME = os.environ.get("LIS_SERVED_MODEL_NAME", "").strip()
PAGE_MODELS = ("minicpm-ocr", "minicpm-ocr-stp", "minicpm-ocr-tts")
BLOCK_MODEL = "minicpm-ocr-tts-block"
@@ -346,7 +349,7 @@ def _image_from_messages(messages) -> str:
def _chat_envelope(content: Dict, model: str) -> Dict:
- """在业务响应外补齐 OpenAI chat.completion 的必需字段(业务字段原样保留)。"""
+ """Add the OpenAI chat.completion fields around the business response. Business fields stay as they are."""
choices = content.get("choices") or [{"message": {"content": ""}}]
for i, choice in enumerate(choices):
choice.setdefault("index", i)
@@ -363,7 +366,7 @@ def _chat_response(resp: JSONResponse, model: str, stream: bool):
body = _chat_envelope(json.loads(resp.body), model)
if not stream:
return JSONResponse(content=body)
- # 流式只是把整份结果作为一个 chunk 发出去:识别是整页一次完成的
+ # Streaming sends the whole result as one chunk. Recognition finishes a page in one pass.
chunk = dict(body, object="chat.completion.chunk",
choices=[{"index": 0, "finish_reason": "stop",
"delta": {"role": "assistant",
@@ -399,7 +402,7 @@ async def chat_completions(request: Request):
if target is None:
return _err(400, f"未知 minicpm_ocr.mode: {mode!r},可选 {' / '.join(LIS_MODES)}")
- # 顶层字段 < minicpm_ocr 里的字段
+ # A top-level field loses to the same field inside minicpm_ocr.
merged = {k: body[k] for k in ("image", "page_index", "order", "source_token", "pages") if k in body}
merged.update({k: v for k, v in params.items() if k != "mode"})
if "source_token" not in merged and merged.get("request_id"):
@@ -412,7 +415,7 @@ async def chat_completions(request: Request):
merged["image"] = merged.get("image") or _image_from_messages(body.get("messages"))
if not merged["image"]:
- # LIS 的「Chat Completions 自测」发纯文本;回 4xx 服务就过不了自测
+ # LIS's Chat Completions self-test sends plain text. A 4xx response fails that check.
return _chat_response(JSONResponse(content={"choices": [{"message": {"content": LIS_USAGE_TEXT}}]}),
model, stream)
return _chat_response(await run_in_threadpool(_handle_full_page, merged, target), model, stream)
@@ -426,7 +429,7 @@ async def image_parse_merge(request: Request):
@app.post("/api/page-parse")
async def page_parse(request: Request):
- """摆正和版面做完就返回票据。切片在这台机器的队列里继续解码。"""
+ """Return a ticket once rotation adaptation and layout finish. Crops keep decoding on this machine's queue."""
raw = await request.body()
if not raw:
return _err(400, "缺少页面图片")
@@ -454,7 +457,7 @@ async def page_parse(request: Request):
@app.get("/api/page-markdown/{ticket}")
def page_markdown(ticket: str):
- """票据对应的页还在解码时 ready 为 false。"""
+ """ready is false while the page for this ticket is still decoding."""
import page_fleet
try:
page = page_fleet.take_markdown(ticket)
@@ -467,6 +470,12 @@ def page_markdown(ticket: str):
return {"ready": True, **page}
[email protected]("/api/kie")
+async def kie(request: Request):
+ body = await request.json()
+ return await run_in_threadpool(_handle_kie, body)
+
+
@app.post("/api/image-parse")
async def image_parse(request: Request):
body = await request.json()
@@ -524,7 +533,7 @@ def _handle_full_page(body: Dict, model: str) -> JSONResponse:
try:
upright_on = page_fleet.resolve_upright(upright_choice)
- # 有分数的两档要支持单块重算,而重算从磁盘读 crop,所以落 crop
+ # The two scored tiers must support a single-block rerun, and a rerun reads the crop from disk, so those crops are saved.
cfg = RUNNER.build_cfg(job_id, upright=upright_on,
mode=_mode_to_recipe(mode),
save_crops=mode != "standard")
@@ -537,13 +546,13 @@ def _handle_full_page(body: Dict, model: str) -> JSONResponse:
layout = _read_json(inter / "layouts" / f"{img_stem}.json")
result = _read_json(job_dir / "results_json" / f"{img_stem}.json")
- # request_id 即 job id:单块重算 / 跨页合并凭它找回这次的结果
+ # request_id is the job id. A single-block rerun and a cross-page merge find this result with it.
request_id = job_id
created_at = int(time.time())
source_token = request_id
upright_enabled = bool(cfg.get("upright", {}).get("enabled", True))
- # 跨页合并时要按原样重建这一页的响应
+ # A cross-page merge rebuilds this page's response from the saved fields.
(job_dir / JOB_META).write_text(json.dumps({
"mode": mode, "page_index": page_index, "created_at": created_at,
"upright_enabled": upright_enabled, "image_id": img_stem,
@@ -559,7 +568,7 @@ def _handle_full_page(body: Dict, model: str) -> JSONResponse:
def _handle_seal(body: Dict) -> JSONResponse:
- """整张图当作印章,直接送给识别模型。不摆正,不检测版面,不落 job。"""
+ """Treat the whole image as a seal and send it straight to the recognition model. No rotation adaptation, no layout, and no job on disk."""
image_b64 = body.get("image", "")
if not image_b64:
return _err(400, "缺少 image 字段")
@@ -614,7 +623,7 @@ _KIE_FENCE = re.compile(r"^```(?:json)?\s*([\s\S]*?)\s*```$", re.IGNORECASE)
def kie_prompt(fields: List[str]) -> str:
- """按训练里的英文抽字段句式拼提示。字段名原样放进引号。"""
+ """Build the prompt with the English extract-fields sentence used in training. Field names go inside quotes unchanged."""
quoted = ", ".join(f'"{name}"' for name in fields)
return (
f'Extract the {quoted}. Format the output as a JSON object with keys: {quoted}. '
@@ -623,7 +632,7 @@ def kie_prompt(fields: List[str]) -> str:
def normalize_kie_fields(value) -> List[str]:
- """校验字段名。空串、引号、换行、重名和超长列表都拒绝。"""
+ """Check field names. Empty strings, quotes, newlines, duplicates, and lists that are too long are rejected."""
if not isinstance(value, list) or not value:
raise ValueError("缺少 fields")
if len(value) > KIE_MAX_FIELDS:
@@ -644,14 +653,14 @@ def normalize_kie_fields(value) -> List[str]:
def strip_kie_fence(text: str) -> str:
- """去掉首尾空白和包住整段的 json 围栏,不改字段内容。"""
+ """Strip surrounding whitespace and a json fence around the whole text. Field contents stay unchanged."""
stripped = (text or "").strip()
fenced = _KIE_FENCE.match(stripped)
return fenced.group(1).strip() if fenced else stripped
def _handle_kie(body: Dict) -> JSONResponse:
- """整图按字段抽取。不摆正,不检测版面,不落 job。"""
+ """Extract fields from the whole image. No rotation adaptation, no layout, and no job on disk."""
image_b64 = body.get("image", "")
if not image_b64:
return _err(400, "缺少 image 字段")
@@ -703,10 +712,10 @@ def _handle_kie(body: Dict) -> JSONResponse:
def _handle_merge(body: Dict) -> JSONResponse:
- """跨页表格合并:一份 PDF 的各页都识别完后调用一次。
+ """Cross-page table merge. Call it once after every page of a PDF has been recognized.
- 只读不写——逐页结果保持原样(单块重算仍基于原页),合并结果只在响应里。
- 页码不连续处(中间有失败页)断开,不跨缺口合并。只返回有变化的页。
+ Read only. Each page's result stays as it was, so a single-block rerun still uses the original page. The merge exists only in the response.
+ A gap in page numbers, such as a failed page in the middle, breaks the run. Nothing merges across that gap. Only changed pages are returned.
"""
from minicpmvocr import load_prompt_map
from minicpmvocr.postprocess.crosspage import apply_cross_page_merge
@@ -730,13 +739,13 @@ def _handle_merge(body: Dict) -> JSONResponse:
layout = _read_json(job_dir / "runtime" / "intermediate" / "layouts" / f"{image_id}.json")
if not result or not layout:
return _err(404, f"识别结果已过期:{rid}")
- # image_id 在每个 job 里都是 page_xxxx,用 request_id 做键才不会撞
+ # image_id is page_xxxx inside every job. Key by request_id so they do not collide.
pages.append({"image_id": rid, "page_index": int(meta["page_index"]),
"markdown": result.get("markdown", ""),
"blocks": result.get("crop_blocks") or []})
ctx[rid] = {"meta": meta, "result": result, "layout": layout}
- # 页码连续的一段算一个 document,缺口处断开
+ # A run of consecutive page numbers is one document. A gap starts a new run.
pages.sort(key=lambda p: p["page_index"])
run = 0
for i, page in enumerate(pages):
@@ -774,7 +783,7 @@ def _handle_merge(body: Dict) -> JSONResponse:
created_at=int(meta["created_at"]), source_token=rid,
page_index=page["page_index"],
)
- # absorbed:页首的续表并到了上一页;extended:页尾的表接上了下一页(可同时为真)
+ # absorbed: the continued table at the top of the page was merged into the previous page. extended: the table at the bottom continues onto the next page. Both can be true.
resp["minicpm_ocr"]["cross_page"] = {"absorbed": absorbed, "extended": extended}
out.append(resp)
return JSONResponse(content={"merged_pages": len(out), "pages": out})
@@ -786,7 +795,7 @@ def _handle_rerun_block(body: Dict) -> JSONResponse:
# ===================================================================
-# 入口
+# Entry
# ===================================================================
from document_jobs import router as document_job_router # noqa: E402
diff --git a/webdemo/backend/upright_server.py b/webdemo/backend/upright_server.py
index 6e83fc7..ec6ee2d 100644
--- a/webdemo/backend/upright_server.py
+++ b/webdemo/backend/upright_server.py
@@ -1,8 +1,10 @@
#!/usr/bin/env python3
-"""无卡机器上的摆正服务。
+"""Rotation-adaptation service for a machine without a GPU.
-本机解析进程把页面 PNG 发到 POST /v1/upright。没旋转时只回记录,不回图片。
-服务起来后把地址写到 OCR_UPRIGHT_REGISTRY,解析进程按这个目录来发现工人。
+The local parse process posts a page PNG to POST /v1/upright. When the page
+is not rotated, the response is the record only, with no image. After startup
+the address is written to OCR_UPRIGHT_REGISTRY, and the parse process finds
+workers from that directory.
"""
from __future__ import annotations
diff --git a/webdemo/frontend/README.md b/webdemo/frontend/README.md
deleted file mode 100644
index ddbc0bf..0000000
--- a/webdemo/frontend/README.md
+++ /dev/null
@@ -1,18 +0,0 @@
-# MiniCPM-OCR 文档解析页
-
-本地文档解析页面。页面把文件发给本机工人,工人地址由 `VITE_OCR_TARGET` 指定,默认 `http://127.0.0.1:8966`。工人的启动方式见 [中文部署指南](../../docs/webdemo_deploy_zh.md)。
-
-打开后进入 `/playground/document-parse`。
-
-## 运行
-
-需要 Node.js 22 或更高版本。pnpm 版本由 `package.json` 锁定为 10.32.1,用 Corepack 安装。
-
-```bash
-corepack pnpm install
-VITE_OCR_TARGET=http://127.0.0.1:8966 corepack pnpm dev --host --port 5173 --strictPort
-```
-
-打开 <http://localhost:5173/playground/document-parse>。
-
-开发服务器把 `/api/document-parse` 和 `/v1` 转到 `VITE_OCR_TARGET`。
diff --git a/webdemo/frontend/index.html b/webdemo/frontend/index.html
index f43ec37..c5052f8 100644
--- a/webdemo/frontend/index.html
+++ b/webdemo/frontend/index.html
@@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
- <!-- 标题在构建期写入静态 HTML,链接预览不执行脚本。 -->
+ <!-- Title is written into static HTML at build time; link previews do not execute scripts. -->
<title>%VITE_APP_TITLE%</title>
<meta property="og:title" content="%VITE_APP_TITLE%" />
<meta property="og:site_name" content="MiniCPM-OCR" />
diff --git a/webdemo/frontend/packages/store/src/useAppStore.ts b/webdemo/frontend/packages/store/src/useAppStore.ts
index 0b95f2b..f6af7c4 100644
--- a/webdemo/frontend/packages/store/src/useAppStore.ts
+++ b/webdemo/frontend/packages/store/src/useAppStore.ts
@@ -3,56 +3,56 @@ import { persist } from 'zustand/middleware';
export type LayoutMode = 'sidebar' | 'top' | 'mixed';
-/** MAP 支持的界面语言。 */
+/** UI languages supported by MAP. */
export const SUPPORTED_LOCALES = ['zh-CN', 'en-US'] as const;
-/** MAP 支持的界面语言类型。 */
+/** UI language type supported by MAP. */
export type AppLocale = (typeof SUPPORTED_LOCALES)[number];
/**
- * 体验中心对话参数(按模型分别持久化)。
- * 字段与 portal 的 PlaygroundParams 对齐;放在 store 以便按 modelId 记忆。
+ * Playground chat parameters (persisted per model).
+ * Fields match the portal PlaygroundParams; they live in the store so each modelId is remembered.
*/
export interface PlaygroundParamValues {
temperature?: number;
topP?: number;
maxTokens?: number;
- /** 用户显式选择的 v4.7 图片压缩比例;未设置时不发送。 */
+ /** v4.7 image compression ratio the user explicitly chose; omitted when unset. */
imageDownsampleMode?: '4x' | '16x';
thinkingDepth?: 'off' | 'on';
thinkingStyle?: 'reasoning_effort' | 'thinking' | 'both';
stream?: boolean;
- /** 是否开启联网搜索(走 L3 Playground BFF) */
+ /** Whether web search is on (goes through the L3 Playground BFF). */
webSearch?: boolean;
- /** 联网模式下启用的工具名称列表 */
+ /** Tool names enabled in web-search mode. */
enabledTools?: string[];
- /** 用户手动设置的当前位置(用于 datetime 工具) */
+ /** Location the user set manually (used by the datetime tool). */
userLocation?: string;
}
-/** 体验中心(Playground)UI 偏好——非敏感项,可持久化(绝不含 API Key 明文) */
+/** Playground UI preferences — non-sensitive, safe to persist (never includes an API key in plaintext). */
export interface PlaygroundPrefs {
- /** 上次选中的模型 id */
+ /** Last selected model id. */
lastModelId: string;
- /** 上次选中的语音合成模型 id(与语言对话各自记忆) */
+ /** Last selected speech-synthesis model id (remembered separately from language chat). */
lastTtsModelId: string;
- /** 上次选中的实时对话模型 id(与语言对话各自记忆) */
+ /** Last selected realtime-conversation model id (remembered separately from language chat). */
lastRealtimeModelId: string;
- /** 上次选中的图像解析模型 id(与语言对话各自记忆) */
+ /** Last selected image-parse model id (remembered separately from language chat). */
lastImageParseModelId: string;
- /** 上次选中的 API Key id */
+ /** Last selected API key id. */
lastKeyId: string;
- /** 思考深度档位:off | on */
+ /** Reasoning depth level: off | on. */
thinkingDepth: 'off' | 'on';
- /** 左侧栏是否收起 */
+ /** Whether the left sidebar is collapsed. */
sidebarCollapsed: boolean;
- /** 各模型独立的对话参数(key=modelId),切换模型时各自记忆 */
+ /** Per-model chat parameters (key = modelId), remembered independently when switching models. */
paramsByModel: Record<string, PlaygroundParamValues>;
- /** 已看过的界面引导 id(含版本号),避免同一引导反复弹出 */
+ /** UI guide ids already seen (including a version), so the same guide does not pop up again. */
seenTours: string[];
- /** 文档解析:结果里屏蔽页眉 / 页脚 / 页码 */
+ /** Document parsing: hide headers, footers, and page numbers in the result. */
imageParseHideHeaderFooter: boolean;
- /** 文档解析:版面框上显示阅读顺序序号(排查是版面问题还是识别问题) */
+ /** Document parsing: show reading-order numbers on layout boxes (to tell a layout problem from a recognition problem). */
imageParseShowOrder: boolean;
}
@@ -61,18 +61,18 @@ interface AppState {
theme: 'light' | 'dark' | 'system';
locale: AppLocale;
layoutMode: LayoutMode;
- /** 体验中心 UI 偏好 */
+ /** Playground UI preferences. */
playground: PlaygroundPrefs;
toggleSidebar: () => void;
setTheme: (theme: AppState['theme']) => void;
setLocale: (locale: AppState['locale']) => void;
setLayoutMode: (mode: LayoutMode) => void;
- /** 增量更新体验中心偏好 */
+ /** Incrementally update Playground preferences. */
setPlaygroundPrefs: (patch: Partial<PlaygroundPrefs>) => void;
- /** 设置某模型的对话参数(增量合并,按 modelId 持久化) */
+ /** Set chat parameters for one model (merged incrementally, persisted by modelId). */
setModelParams: (modelId: string, patch: Partial<PlaygroundParamValues>) => void;
- /** 删除某模型的全部用户参数覆盖,恢复模型配置或空值。 */
+ /** Delete all user parameter overrides for one model, restoring the model config or empty values. */
clearModelParams: (modelId: string) => void;
}
@@ -136,18 +136,18 @@ export const useAppStore = create<AppState>()(
version < APP_STORE_VERSION
? migrateLegacyPlaygroundParams(persistedState)
: persistedState,
- // 兼容旧持久化结构:缺 playground 字段时补默认值
+ // Compatible with the old persisted shape: fill defaults when the playground field is missing.
merge: (persisted, current) => {
const p = (persisted ?? {}) as Partial<AppState>;
const playground: Partial<PlaygroundPrefs> & Record<string, unknown> = {
...p.playground,
};
- // 已移除的显示偏好不再恢复,避免旧浏览器状态重新启用置信度。
+ // Removed display preferences are not restored, so old browser state does not turn confidence back on.
delete playground.imageParseShowScore;
return {
...current,
...p,
- // 仅接收受支持的持久化语言,避免历史异常值破坏界面初始化。
+ // Accept only supported persisted languages, so a historical bad value cannot break UI initialization.
locale: isAppLocale(p.locale) ? p.locale : current.locale,
playground: { ...DEFAULT_PLAYGROUND_PREFS, ...playground },
};
@@ -157,11 +157,11 @@ export const useAppStore = create<AppState>()(
);
/**
- * 清理旧版 Playground 自动写入的默认值。
- * 旧版的 maxTokens=0 是“不下发”的哨兵值,因此可安全移除;其他数值缺少来源标记,
- * 仅在采样参数同时等于历史默认值时清理,避免覆盖能够识别出的用户自定义值。
- * @param persistedState Zustand 持久化的旧状态。
- * @returns 可由新版 store 合并的迁移后状态。
+ * Clear defaults that an older Playground wrote automatically.
+ * The old maxTokens = 0 was a sentinel for "do not send", so it can be removed safely; other numbers have no source mark,
+ * and are cleared only when the sampling parameters all equal the historical defaults, so recognized user customizations are not overwritten.
+ * @param persistedState Old state persisted by Zustand.
+ * @returns Migrated state the new store can merge.
*/
export function migrateLegacyPlaygroundParams(persistedState: unknown): unknown {
if (!isRecord(persistedState) || !isRecord(persistedState.playground)) return persistedState;
@@ -197,15 +197,15 @@ export function migrateLegacyPlaygroundParams(persistedState: unknown): unknown
}
/**
- * 判断持久化值是否为 MAP 支持的界面语言。
- * @param value 待验证的持久化值。
- * @returns 值是否可作为 AppLocale 使用。
+ * Whether a persisted value is a UI language MAP supports.
+ * @param value Persisted value to check.
+ * @returns Whether the value can be used as an AppLocale.
*/
function isAppLocale(value: unknown): value is AppLocale {
return typeof value === 'string' && SUPPORTED_LOCALES.includes(value as AppLocale);
}
-/** 判断未知值是否为可安全展开的普通记录。 */
+/** Whether an unknown value is a plain record that can be spread safely. */
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
diff --git a/webdemo/frontend/packages/types/src/api.ts b/webdemo/frontend/packages/types/src/api.ts
index 2b0632b..3d98b73 100644
--- a/webdemo/frontend/packages/types/src/api.ts
+++ b/webdemo/frontend/packages/types/src/api.ts
@@ -1,5 +1,5 @@
export interface ApiResponse<T = unknown> {
- /** 平台链路 ID(req_xxx),同时在响应头 X-Request-Id 回写 */
+ /** Platform trace id (req_xxx), also written back on the X-Request-Id response header. */
requestId: string;
code: number | string;
data: T;
@@ -20,28 +20,28 @@ export interface PageParams {
}
/**
- * 业务错误码(与后端 internal/app/errcode.go 保持一致,此处仅声明前端需判定的子集)。
+ * Business error codes (kept in line with backend internal/app/errcode.go; only the subset the frontend must branch on is declared here).
*/
export const BIZ_CODE = {
- /** 成功 */
+ /** Success. */
OK: 0,
- /** 未登录 / 登录态失效 */
+ /** Not logged in, or the login session is no longer valid. */
UNAUTHORIZED: 10001,
- /** 账号被停用 */
+ /** Account disabled. */
ACCOUNT_DISABLED: 10003,
- /** 邮箱认证账号必须先绑定中国大陆手机号 */
+ /** An email-authenticated account must bind a mainland China mobile number first. */
PHONE_BINDING_REQUIRED: 10011,
- /** 权限不足 */
+ /** Insufficient permission. */
FORBIDDEN: 10010,
- /** 高权限本地密码已过期 */
+ /** The high-privilege local password has expired. */
PASSWORD_EXPIRED: 10007,
- /** 账号被要求重置本地密码 */
+ /** The account is required to reset its local password. */
PASSWORD_RESET_REQUIRED: 10009,
} as const;
/**
- * 需清除登录态并跳转登录页的错误码集合(对齐后端 logoutCodes)。
- * 前端响应拦截器据此统一判定登出。
+ * Error codes that must clear the login session and redirect to the login page (aligned with backend logoutCodes).
+ * The frontend response interceptor uses this set to decide logout in one place.
*/
export const LOGOUT_CODES: readonly number[] = [BIZ_CODE.UNAUTHORIZED, BIZ_CODE.ACCOUNT_DISABLED];
diff --git a/webdemo/frontend/packages/types/src/captcha.ts b/webdemo/frontend/packages/types/src/captcha.ts
index cb8776c..f326f1d 100644
--- a/webdemo/frontend/packages/types/src/captcha.ts
+++ b/webdemo/frontend/packages/types/src/captcha.ts
@@ -1,11 +1,11 @@
/**
- * 人机验证相关共享类型。
+ * Shared captcha types.
*
- * 用途:portal 与 admin 登录页均使用同一套后端滑块验证契约,类型在此集中声明,
- * 避免两 app 各自重复定义导致字段漂移。
+ * Purpose: the portal and admin login pages share one backend slide-captcha contract, so the types are declared here
+ * to avoid field drift from defining them separately in each app.
*/
-/** 滑块人机验证题目(后端 snake_case 原样)。坐标系与图片原始尺寸 300×220 一致。 */
+/** Slide captcha challenge (backend snake_case, unchanged). The coordinate system matches the original image size of 300×220. */
export interface CaptchaChallengeDTO {
id: string;
master_b64: string;
diff --git a/webdemo/frontend/packages/types/src/router.ts b/webdemo/frontend/packages/types/src/router.ts
index 34492c7..ab5ba46 100644
--- a/webdemo/frontend/packages/types/src/router.ts
+++ b/webdemo/frontend/packages/types/src/router.ts
@@ -11,7 +11,7 @@ export interface AppRoute {
export interface RouteMeta {
title: string;
icon?: string;
- /** 外部链接:设置后该导航项不走内部路由,点击在新标签页打开此 URL */
+ /** External link: when set, this nav item skips internal routing and opens this URL in a new tab. */
external?: string;
hidden?: boolean;
keepAlive?: boolean;
diff --git a/webdemo/frontend/packages/ui/src/__tests__/pro-table.test.tsx b/webdemo/frontend/packages/ui/src/__tests__/pro-table.test.tsx
index 7ae93aa..88d5dd0 100644
--- a/webdemo/frontend/packages/ui/src/__tests__/pro-table.test.tsx
+++ b/webdemo/frontend/packages/ui/src/__tests__/pro-table.test.tsx
@@ -189,7 +189,7 @@ describe('ProTable', () => {
/>,
);
- // ProTable 同时保留桌面端和移动端 DOM,各自只为可展开行渲染一个按钮。
+ // ProTable keeps both the desktop and mobile DOM, and each renders one button only for expandable rows.
expect(screen.getAllByRole('button', { name: '展开行' })).toHaveLength(2);
});
});
diff --git a/webdemo/frontend/packages/ui/src/__tests__/search-select.test.tsx b/webdemo/frontend/packages/ui/src/__tests__/search-select.test.tsx
index 589a6b7..f2fcdf9 100644
--- a/webdemo/frontend/packages/ui/src/__tests__/search-select.test.tsx
+++ b/webdemo/frontend/packages/ui/src/__tests__/search-select.test.tsx
@@ -10,7 +10,7 @@ const options = [
{ value: 'user-c', label: '其他用户' },
];
-/** 受控测试入口:区分输入关键词与按身份保存的已选项。 */
+/** Controlled test entry: distinguishes the typed keyword from the selected item saved by identity. */
function Field({ multiple = true, maxSelected }: { multiple?: boolean; maxSelected?: number }) {
const [search, setSearch] = useState('');
const [selected, setSelected] = useState<SearchSelectOption[]>([]);
diff --git a/webdemo/frontend/packages/ui/src/__tests__/tabs.test.tsx b/webdemo/frontend/packages/ui/src/__tests__/tabs.test.tsx
index c53a948..3c22528 100644
--- a/webdemo/frontend/packages/ui/src/__tests__/tabs.test.tsx
+++ b/webdemo/frontend/packages/ui/src/__tests__/tabs.test.tsx
@@ -22,7 +22,7 @@ describe('Tabs', () => {
const indicator = document.querySelector('[data-map-tabs-indicator]');
expect(document.querySelectorAll('[data-map-tabs-indicator]')).toHaveLength(1);
expect(indicator).toHaveAttribute('aria-hidden', 'true');
- // 首帧先就位再开过渡,所以过渡类要等下一帧
+ // The first frame settles in place before the transition starts, so the transition class waits until the next frame.
await waitFor(() => {
expect(indicator?.className).toContain('transition-[transform,width,height]');
});
diff --git a/webdemo/frontend/packages/ui/src/components/SiteFooter.tsx b/webdemo/frontend/packages/ui/src/components/SiteFooter.tsx
index 4de33d9..b9ed548 100644
--- a/webdemo/frontend/packages/ui/src/components/SiteFooter.tsx
+++ b/webdemo/frontend/packages/ui/src/components/SiteFooter.tsx
@@ -1,28 +1,28 @@
import { requestCookieSettings } from './CookieConsent';
/**
- * 站点页脚:展示版权与按环境控制的合规信息。
+ * Site footer: copyright and compliance details controlled by environment.
*
- * 用途:满足中国大陆网站合规要求,在登录页与主界面底部显著位置展示备案号,
- * 并提供工信部与公安备案查询链接。备案号文本为主体备案信息,作为唯一可信来源集中维护于此,
- * 由 portal 与 admin 共用,请勿在各 app 内重复硬编码。
+ * Purpose: meet mainland China website compliance rules by showing the ICP filing number prominently at the bottom of the login page and the main UI,
+ * with links to look it up at MIIT and in the public-security filing. The filing-number text is the entity filing record, maintained here as the only source of truth,
+ * shared by portal and admin. Do not hard-code it again inside each app.
*
- * @param className 额外的容器类名,便于在不同布局中微调间距/背景。
- * @param variant 排版变体:`stacked` 多行居中(登录页),`inline` 水平单行(主界面页脚)。
+ * @param className Extra container classes, for tweaking spacing or background in different layouts.
+ * @param variant Layout variant: `stacked` is centered on several lines (login page), `inline` is one horizontal line (main UI footer).
*/
interface SiteFooterProps {
className?: string;
variant?: 'stacked' | 'inline';
- /** 默认跟随构建 profile;legacy 显示,gcp 隐藏。 */
+ /** Follows the build profile by default; shown for legacy, hidden for gcp. */
showFiling?: boolean;
- /** 默认仅在启用 GCP Cookie Consent 时显示。 */
+ /** Shown by default only when GCP Cookie Consent is enabled. */
showCookieSettings?: boolean;
}
-// 公安备案标准图标(公安部下发)。各 app 将其放在自身 public 根,用 BASE_URL 自适应
-// 子路径前缀(portal /console/、admin /admin-console/),与 logo 的引用方式一致。
-// 注:本共享包内缺少 vite/client 全局类型(vite 仅为根构建依赖,pnpm 隔离下无法解析),
-// 故以 unknown 中转安全读取 BASE_URL;运行时由各 app 的 vite 注入为编译期常量。
+// Standard public-security filing icon (issued by the Ministry of Public Security). Each app puts it at its own public root and uses BASE_URL to adapt
+// to the subpath prefix (portal /console/, admin /admin-console/), the same way the logo is referenced.
+// Note: this shared package has no vite/client global types (vite is only a root build dependency and cannot be resolved under pnpm isolation),
+// so BASE_URL is read safely through unknown; at runtime each app’s vite injects it as a compile-time constant.
const baseUrl = (import.meta as unknown as { env: { BASE_URL: string } }).env.BASE_URL;
const gonganIcon = `${baseUrl}gongan-beian.png`;
@@ -88,7 +88,7 @@ export function SiteFooter({
</>
) : null;
- // 主界面:所有合规信息水平排成一行,小屏才换行
+ // Main UI: all compliance details sit on one horizontal line, and wrap only on a small screen.
if (variant === 'inline') {
return (
<footer
@@ -103,7 +103,7 @@ export function SiteFooter({
);
}
- // 登录页:版权与合规信息分两行居中
+ // Login page: copyright and compliance details are centered on two lines.
return (
<footer
className={`flex flex-col items-center gap-1.5 px-4 py-5 text-center text-xs leading-relaxed text-muted-foreground ${className}`}
diff --git a/webdemo/frontend/packages/ui/src/components/SlideCaptcha.tsx b/webdemo/frontend/packages/ui/src/components/SlideCaptcha.tsx
index 7a1e772..4d25c36 100644
--- a/webdemo/frontend/packages/ui/src/components/SlideCaptcha.tsx
+++ b/webdemo/frontend/packages/ui/src/components/SlideCaptcha.tsx
@@ -1,43 +1,43 @@
import { useMemo, type CSSProperties } from 'react';
import GoCaptcha from 'go-captcha-react';
-/** 后端下发的滑块题目(不含答案)。坐标系与图片原始尺寸(300×220)一致。 */
+/** Slide challenge from the backend (no answer). The coordinate system matches the original image size (300×220). */
export interface SlideCaptchaChallenge {
- /** 带缺口的背景大图(data URI) */
+ /** Background image with the gap (data URI). */
masterB64: string;
- /** 拼图块(data URI) */
+ /** Puzzle piece (data URI). */
tileB64: string;
- /** 拼图块初始展示 x */
+ /** Initial display x of the puzzle piece. */
tileX: number;
- /** 拼图块展示 y(与缺口同高) */
+ /** Display y of the puzzle piece (same height as the gap). */
tileY: number;
- /** 拼图块宽 */
+ /** Puzzle piece width. */
tileWidth: number;
- /** 拼图块高 */
+ /** Puzzle piece height. */
tileHeight: number;
}
-/** SlideCaptcha 入参 */
+/** SlideCaptcha props. */
export interface SlideCaptchaProps {
- /** 题目;为 null 时渲染空白占位(加载中) */
+ /** Challenge; when null, render an empty placeholder (loading). */
challenge: SlideCaptchaChallenge | null;
- /** 用户释放滑块时回调,point 为拼图落点;reset 可将滑块复位 */
+ /** Called when the user releases the slider; point is where the piece lands. reset can move the slider back. */
onConfirm: (point: { x: number; y: number }, reset: () => void) => void;
- /** 点击刷新换一题 */
+ /** Refresh click loads a new challenge. */
onRefresh: () => void;
- /** 点击 go-captcha 标题栏关闭图标时回调(用于取消验证、关闭弹窗) */
+ /** Called when the go-captcha title-bar close icon is clicked (cancel verification and close the dialog). */
onClose?: () => void;
- /** 提示文案 */
+ /** Hint copy. */
title?: string;
- /** 状态:success 滑块停留并转绿;error 闪红;default 品牌蓝 */
+ /** Status: success leaves the slider in place and turns it green; error flashes red; default is brand blue. */
status?: 'default' | 'success' | 'error';
}
-// 与后端 go-captcha 默认出题尺寸保持一致,确保前端落点坐标系与服务端答案坐标系对齐。
+// Match the backend go-captcha default challenge size so the frontend drop-point coordinates line up with the server answer coordinates.
const MASTER_WIDTH = 300;
const MASTER_HEIGHT = 220;
-// 不同状态下滑块(dragBlock/圆点)的主色:default 主色 / success 绿 / error 红。
+// Slider (dragBlock / dot) primary color by status: default is the brand color, success is green, error is red.
const STATUS_COLOR: Record<NonNullable<SlideCaptchaProps['status']>, string> = {
default: 'hsl(var(--primary))',
success: 'hsl(var(--success))',
@@ -45,11 +45,11 @@ const STATUS_COLOR: Record<NonNullable<SlideCaptchaProps['status']>, string> = {
};
/**
- * 滑块人机验证(拼图)。基于 go-captcha-react 的 Slide 模式封装为纯展示组件:
- * 只负责渲染题目、把用户落点/刷新事件回调出去,不做任何数据请求(取题/校验由调用方编排)。
+ * Slide captcha (puzzle). A presentational wrapper around go-captcha-react Slide mode:
+ * it only renders the challenge and forwards the drop point and refresh events. It makes no requests (the caller fetches and checks the challenge).
*
- * 关键:data/config/events 均 useMemo 固定引用,避免父组件因状态变更重渲染时
- * 生成新 data 触发 go-captcha 内部「data 变化即复位」的 effect(否则成功后滑块会回退)。
+ * Important: data, config, and events are all stable useMemo references, so a parent re-render from a status change
+ * does not create new data and trip go-captcha’s "data changed, so reset" effect (otherwise the slider jumps back after success).
*/
export function SlideCaptcha({
challenge,
@@ -59,7 +59,7 @@ export function SlideCaptcha({
title = '向右拖动滑块完成拼图',
status = 'default',
}: SlideCaptchaProps) {
- // 仅当题目变化时才生成新的 data 引用,状态变更(变色)不触发 go-captcha 复位。
+ // Create a new data reference only when the challenge changes; a status change (color) does not reset go-captcha.
const data = useMemo(
() => ({
thumbX: challenge?.tileX ?? 0,
@@ -82,7 +82,7 @@ export function SlideCaptcha({
[onConfirm, onRefresh, onClose],
);
- // 用设计系统主色覆盖 go-captcha 主题变量;按状态切换滑块颜色(Slide 不消费 type,颜色只能走 CSS 变量)。
+ // Override go-captcha theme variables with the design-system primary color; the slider color follows status (Slide does not consume type, so color can only go through CSS variables).
const themeVars = useMemo(
() =>
({
@@ -100,7 +100,7 @@ export function SlideCaptcha({
{challenge ? (
<GoCaptcha.Slide data={data} config={config} events={events} />
) : (
- // 取题中:渲染等尺寸占位,避免 go-captcha 在空图(image='')时的「黑屏一闪」与布局跳动。
+ // While the challenge is loading, render a same-size placeholder so go-captcha does not flash black or jump the layout on an empty image (image='').
<div
className="flex items-center justify-center rounded-md bg-muted/50"
style={{ width: MASTER_WIDTH, height: MASTER_HEIGHT }}
diff --git a/webdemo/frontend/packages/ui/src/components/Tooltip/Tooltip.tsx b/webdemo/frontend/packages/ui/src/components/Tooltip/Tooltip.tsx
index c55a63c..9edd9f9 100644
--- a/webdemo/frontend/packages/ui/src/components/Tooltip/Tooltip.tsx
+++ b/webdemo/frontend/packages/ui/src/components/Tooltip/Tooltip.tsx
@@ -3,7 +3,7 @@ import * as TooltipPrimitive from '@radix-ui/react-tooltip';
import { VariantProps, cva } from 'class-variance-authority';
import { cn } from '../../utils';
-// Trigger 样式(按钮/可触发元素)
+// Trigger styles (button or other trigger element).
const tooltipTriggerVariants = cva(
'inline-flex items-center justify-center rounded-full focus:outline-none focus:ring-2 focus:ring-offset-2',
{
@@ -27,7 +27,7 @@ const tooltipTriggerVariants = cva(
},
);
-// Tooltip 内容样式(气泡)
+// Tooltip content styles (the bubble).
const tooltipContentVariants = cva(
'z-[70] overflow-hidden rounded-lg border px-3 py-1.5 text-sm shadow-[0_4px_16px_-2px_rgba(0,0,0,0.1),0_2px_4px_-1px_rgba(0,0,0,0.06)] data-[state=delayed-open]:[animation:map-tooltip-in_150ms_ease-out] data-[state=closed]:[animation:map-tooltip-out_100ms_ease-in]',
{
@@ -44,7 +44,7 @@ const tooltipContentVariants = cva(
},
);
-// Props 类型
+// Props types.
interface TooltipTriggerProps
extends
React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Trigger>,
@@ -58,12 +58,12 @@ interface TooltipContentProps
align?: 'start' | 'center' | 'end';
}
-// 组件实现
+// Component implementation.
const TooltipProvider = TooltipPrimitive.Provider;
/**
- * Tooltip 根组件。
- * 将 Radix 默认的 700ms 悬浮延迟收敛到 200ms,让提示更跟手(仍可通过 delayDuration 覆盖)。
+ * Tooltip root.
+ * Pulls Radix’s default 700ms hover delay down to 200ms so the hint feels more responsive (delayDuration can still override it).
*/
function Tooltip({
delayDuration = 200,
diff --git a/webdemo/frontend/packages/ui/src/components/ui/badge.tsx b/webdemo/frontend/packages/ui/src/components/ui/badge.tsx
index b954a09..11be7ce 100644
--- a/webdemo/frontend/packages/ui/src/components/ui/badge.tsx
+++ b/webdemo/frontend/packages/ui/src/components/ui/badge.tsx
@@ -10,7 +10,7 @@ const badgeVariants = cva(
default: 'border-transparent bg-primary text-primary-foreground',
secondary: 'border-transparent bg-secondary text-secondary-foreground',
outline: 'text-foreground',
- // 状态类语义色统一为「15% 透明底 + 实色文字」;default 保留实心供强调标签
+ // Status semantic colors use a 15% transparent background plus solid text; default stays solid for emphasis tags.
info: 'border-transparent bg-info/15 text-info',
destructive: 'border-transparent bg-destructive/15 text-destructive',
success: 'border-transparent bg-success/15 text-success',
diff --git a/webdemo/frontend/packages/ui/src/components/ui/checkbox.tsx b/webdemo/frontend/packages/ui/src/components/ui/checkbox.tsx
index a568ecd..2587f64 100644
--- a/webdemo/frontend/packages/ui/src/components/ui/checkbox.tsx
+++ b/webdemo/frontend/packages/ui/src/components/ui/checkbox.tsx
@@ -6,14 +6,14 @@ export interface CheckboxProps extends Omit<InputHTMLAttributes<HTMLInputElement
}
/**
- * 复选框原语。
+ * Checkbox primitive.
*
- * 用途:提供平台统一的 checkbox 外观与可访问状态。保留原生 input 语义,便于表单、
- * 键盘操作和屏幕阅读器直接识别;原生 accent-color 无法定制未选中态,视觉层隐藏
- * 外观后按语义 token 自绘:默认描边、hover 主色边、选中主色底加白勾。
+ * Purpose: the platform’s unified checkbox look and accessible state. Native input semantics stay, so forms,
+ * keyboard use, and screen readers can recognize it directly. Native accent-color cannot style the unchecked state, so the visual layer hides
+ * that appearance and paints from semantic tokens: a default stroke, a primary border on hover, and a primary fill with a white check when selected.
*
- * @param className 额外样式类,作用于外层容器(如对齐用的 margin)
- * @returns 语义化 checkbox 输入框
+ * @param className Extra classes, applied to the outer container (for example margin used for alignment).
+ * @returns A semantic checkbox input.
*/
function Checkbox({ className, ref, ...props }: CheckboxProps) {
return (
diff --git a/webdemo/frontend/packages/ui/src/components/ui/chip-multi-select.tsx b/webdemo/frontend/packages/ui/src/components/ui/chip-multi-select.tsx
index 1e0cea7..d6ff6cf 100644
--- a/webdemo/frontend/packages/ui/src/components/ui/chip-multi-select.tsx
+++ b/webdemo/frontend/packages/ui/src/components/ui/chip-multi-select.tsx
@@ -15,18 +15,18 @@ export interface ChipMultiSelectProps {
}
/**
- * Chip 多选组件。
+ * Chip multi-select.
*
- * 用途:以可点选标签形式选择多个有限选项,适合模型、数据集、标签过滤等短文本选项。
- * 组件保持受控,选中值由调用方持有;内部只负责切换并返回下一组选中值。
+ * Purpose: pick several finite options as clickable tags, suited to short labels such as models, datasets, and tag filters.
+ * The component stays controlled; the caller owns the selected values. Internally it only toggles and returns the next selection.
*
- * @param options 可选项列表
- * @param value 当前选中的 value 列表
- * @param onChange 选中变更回调
- * @param emptyText 空选项文案
- * @param ariaLabel 多选区域的无障碍名称
- * @param className 外层样式类
- * @returns chip 多选控件
+ * @param options Option list.
+ * @param value Currently selected values.
+ * @param onChange Selection change callback.
+ * @param emptyText Copy shown when there are no options.
+ * @param ariaLabel Accessible name for the multi-select region.
+ * @param className Outer style classes.
+ * @returns The chip multi-select control.
*/
function ChipMultiSelect({
options,
diff --git a/webdemo/frontend/packages/ui/src/components/ui/confirm.tsx b/webdemo/frontend/packages/ui/src/components/ui/confirm.tsx
index 12e1677..d1ef84f 100644
--- a/webdemo/frontend/packages/ui/src/components/ui/confirm.tsx
+++ b/webdemo/frontend/packages/ui/src/components/ui/confirm.tsx
@@ -35,7 +35,7 @@ function confirm(options: ConfirmOptions): Promise<boolean> {
* Renders inside the existing React tree — no createRoot needed.
*/
function ConfirmRenderer() {
- // 懒初始化:挂载前若已有排队的 confirm(跨 MFE 场景),直接取最后一个,避免在 effect 里 setState
+ // Lazy init: if a confirm is already queued before mount (cross-MFE), take the last one, so setState is not called inside the effect.
const [current, setCurrent] = useState<ConfirmPayload | null>(() =>
pendingQueue.length > 0 ? pendingQueue[pendingQueue.length - 1]! : null,
);
@@ -93,7 +93,7 @@ function ConfirmDialog({
}: ConfirmDialogProps) {
const [closing, setClosing] = useState(false);
- // 关闭前先播放退出动画(180ms)再回调;用 useCallback 保证 effect 依赖稳定
+ // Play the exit animation (180ms) before closing, then call back; useCallback keeps the effect dependencies stable.
const handleCancel = useCallback(() => {
setClosing(true);
setTimeout(onCancel, 180);
@@ -163,8 +163,8 @@ function ConfirmDialog({
{/* Overlay */}
<div
className={cn(
- // Radix modal Dialog 打开时会给 body 置 pointer-events:none;confirm 渲染在普通
- // React 树里会继承该值导致整层不可点,必须显式恢复 pointer-events。
+ // An open Radix modal Dialog sets pointer-events:none on body; confirm renders in the normal
+ // React tree and would inherit that, making the whole layer unclickable, so pointer-events must be restored explicitly.
'pointer-events-auto fixed inset-0 z-[80] bg-black/40 backdrop-blur-[2px]',
closing
? '[animation:map-confirm-overlay-out_180ms_ease-in_forwards]'
diff --git a/webdemo/frontend/packages/ui/src/components/ui/date-picker.tsx b/webdemo/frontend/packages/ui/src/components/ui/date-picker.tsx
index 6aa23ce..5e5edb2 100644
--- a/webdemo/frontend/packages/ui/src/components/ui/date-picker.tsx
+++ b/webdemo/frontend/packages/ui/src/components/ui/date-picker.tsx
@@ -22,19 +22,19 @@ import {
import { cn } from '../../utils';
export interface DatePickerProps {
- /** 受控值,格式 YYYY-MM-DD;空字符串表示未选择 */
+ /** Controlled value, format YYYY-MM-DD; an empty string means nothing is selected. */
value?: string;
- /** 选择变更回调,回传 YYYY-MM-DD(清除时回传空字符串) */
+ /** Selection change callback; returns YYYY-MM-DD (an empty string when cleared). */
onChange?: (value: string) => void;
- /** 可选最小日期(含),YYYY-MM-DD */
+ /** Earliest selectable date (inclusive), YYYY-MM-DD. */
min?: string;
- /** 可选最大日期(含),YYYY-MM-DD */
+ /** Latest selectable date (inclusive), YYYY-MM-DD. */
max?: string;
placeholder?: string;
disabled?: boolean;
className?: string;
id?: string;
- /** 触发器无障碍名称 */
+ /** Accessible name for the trigger. */
ariaLabel?: string;
}
@@ -50,7 +50,7 @@ function pad(n: number): string {
return n < 10 ? `0${n}` : String(n);
}
-/** 解析 YYYY-MM-DD,避免 new Date(string) 的 UTC 时区偏移 */
+/** Parse YYYY-MM-DD, avoiding the UTC offset of new Date(string). */
function parse(value?: string): YMD | null {
if (!value) return null;
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value.trim());
@@ -70,12 +70,12 @@ function display({ y, m, d }: YMD): string {
return `${y}/${pad(m + 1)}/${pad(d)}`;
}
-/** 仅按年月日比较,忽略时分秒 */
+/** Compare year, month, and day only, ignoring the time of day. */
function sameDay(a: YMD, b: YMD): boolean {
return a.y === b.y && a.m === b.m && a.d === b.d;
}
-/** 返回 < 0 表示 a 早于 b */
+/** Returns < 0 when a is earlier than b. */
function compare(a: YMD, b: YMD): number {
if (a.y !== b.y) return a.y - b.y;
if (a.m !== b.m) return a.m - b.m;
@@ -88,14 +88,14 @@ function todayYMD(): YMD {
}
/**
- * 日期选择器(@map/ui)。
+ * Date picker (@map/ui).
*
- * 用途:替代浏览器原生 <input type="date">,提供与设计系统一致的触发器与日历浮层。
- * 受控组件:值由调用方持有,内部只负责解析、渲染日历与回传 YYYY-MM-DD。
+ * Purpose: replace the browser’s native <input type="date"> with a trigger and calendar popover that match the design system.
+ * Controlled: the caller owns the value. Internally it only parses, renders the calendar, and returns YYYY-MM-DD.
*
- * @param value 当前值 YYYY-MM-DD
- * @param onChange 选择/清除回调
- * @param min/max 可选的可选范围边界(含)
+ * @param value Current value, YYYY-MM-DD.
+ * @param onChange Select or clear callback.
+ * @param min/max Optional range bounds (inclusive).
*/
function DatePicker({
value,
@@ -113,13 +113,13 @@ function DatePicker({
const minYMD = React.useMemo(() => parse(min), [min]);
const maxYMD = React.useMemo(() => parse(max), [max]);
- // 当前显示的年月:优先选中值,否则今天
+ // Year and month currently shown: the selected value if any, otherwise today.
const [view, setView] = React.useState<{ y: number; m: number }>(() => {
const base = selected ?? todayYMD();
return { y: base.y, m: base.m };
});
- // 打开时把视图对齐到选中值(或今天)
+ // On open, align the view to the selected value (or today).
React.useEffect(() => {
if (open) {
const base = selected ?? todayYMD();
@@ -143,7 +143,7 @@ function DatePicker({
const today = todayYMD();
- // 生成 6 行 × 7 列日历网格(含上/下月补位)
+ // Build a 6×7 calendar grid (including leading and trailing days from the adjacent months).
const cells = React.useMemo(() => {
const firstWeekday = new Date(view.y, view.m, 1).getDay();
const start = new Date(view.y, view.m, 1 - firstWeekday);
@@ -214,7 +214,7 @@ function DatePicker({
)}
{...getFloatingProps()}
>
- {/* 头部:年/月导航 */}
+ {/* Header: year and month navigation */}
<div className="mb-2 flex items-center justify-between">
<div className="flex items-center gap-0.5">
<NavButton ariaLabel="上一年" onClick={() => shiftYear(-1)}>
@@ -237,7 +237,7 @@ function DatePicker({
</div>
</div>
- {/* 星期表头 */}
+ {/* Weekday header */}
<div className="grid grid-cols-7 gap-0.5">
{WEEKDAYS.map((w) => (
<div
@@ -249,7 +249,7 @@ function DatePicker({
))}
</div>
- {/* 日期网格 */}
+ {/* Date grid */}
<div className="grid grid-cols-7 gap-0.5">
{cells.map((cell) => {
const inMonth = cell.m === view.m;
@@ -278,7 +278,7 @@ function DatePicker({
})}
</div>
- {/* 底部操作 */}
+ {/* Footer actions */}
<div className="mt-2 flex items-center justify-between border-t border-border/60 pt-2">
<button
type="button"
diff --git a/webdemo/frontend/packages/ui/src/components/ui/datetime-range-picker.tsx b/webdemo/frontend/packages/ui/src/components/ui/datetime-range-picker.tsx
index eb6212b..7fe506e 100644
--- a/webdemo/frontend/packages/ui/src/components/ui/datetime-range-picker.tsx
+++ b/webdemo/frontend/packages/ui/src/components/ui/datetime-range-picker.tsx
@@ -21,7 +21,7 @@ import {
} from 'lucide-react';
import { cn } from '../../utils';
-/** 快捷预设项:可选择指定日期范围,或通过全部项清空时间筛选。 */
+/** Shortcut preset: pick a date range, or clear the time filter with the All item. */
export type DateRangePreset = DateRangeValuePreset | DateRangeAllPreset;
interface DateRangeValuePreset {
@@ -35,21 +35,21 @@ interface DateRangeAllPreset {
}
export interface DateTimeRangePickerProps {
- /** 起始时间;datetime 模式为 YYYY-MM-DD HH:mm:ss,date 模式为 YYYY-MM-DD;空表示未选 */
+ /** Start time; YYYY-MM-DD HH:mm:ss in datetime mode, YYYY-MM-DD in date mode; empty means unset. */
start?: string;
- /** 结束时间;格式同 start;空表示未选 */
+ /** End time; same format as start; empty means unset. */
end?: string;
- /** 确定时回调,回传 (start, end);清除时回传 ('', '') */
+ /** Called on confirm with (start, end); called with ('', '') when cleared. */
onChange?: (start: string, end: string) => void;
- /** 点击“全部”时回调;未提供时与清除行为一致 */
+ /** Called when "All" is clicked; when omitted, behaves the same as clear. */
onSelectAll?: () => void;
- /** 是否处于“全部”状态,用于受控展示 */
+ /** Whether the "All" state is active, for controlled display. */
allSelected?: boolean;
- /** 输入内容有效性变化回调;输入非法时为 false */
+ /** Called when input validity changes; false when the input is invalid. */
onValidityChange?: (valid: boolean) => void;
- /** 'datetime'(默认,带时分秒列)或 'date'(纯日期,无时间列,输出 YYYY-MM-DD) */
+ /** 'datetime' (default, with hour-minute-second columns) or 'date' (date only, no time columns, output YYYY-MM-DD). */
mode?: 'datetime' | 'date';
- /** 左侧快捷预设;省略用内置(全部/今天/昨天/最近 7 天/最近 30 天),传 [] 则不显示预设栏 */
+ /** Shortcuts on the left; omit them to use the built-ins (All / today / yesterday / last 7 days / last 30 days), or pass [] to hide the preset bar. */
presets?: DateRangePreset[];
placeholder?: string;
disabled?: boolean;
@@ -77,7 +77,7 @@ function pad(n: number): string {
return n < 10 ? `0${n}` : String(n);
}
-/** 解析 "YYYY-MM-DD HH:mm:ss" 或 "YYYY-MM-DDTHH:mm[:ss]";解析失败时间部分回退 0。 */
+/** Parse "YYYY-MM-DD HH:mm:ss" or "YYYY-MM-DDTHH:mm[:ss]"; on failure the time part falls back to 0. */
function parse(value?: string): Parts {
const empty: Parts = { ymd: null, h: 0, mi: 0, s: 0 };
if (!value) return empty;
@@ -108,7 +108,7 @@ function formatOut(p: Parts): string {
return `${p.ymd.y}-${pad(p.ymd.m + 1)}-${pad(p.ymd.d)} ${pad(p.h)}:${pad(p.mi)}:${pad(p.s)}`;
}
-/** 纯日期输出 YYYY-MM-DD(date 模式用)。 */
+/** Date-only output YYYY-MM-DD (used in date mode). */
function formatDate(p: Parts): string {
if (!p.ymd) return '';
return `${p.ymd.y}-${pad(p.ymd.m + 1)}-${pad(p.ymd.d)}`;
@@ -118,7 +118,7 @@ function sameDay(a: YMD | null, b: YMD | null): boolean {
return !!a && !!b && a.y === b.y && a.m === b.m && a.d === b.d;
}
-/** < 0 表示 a 早于 b(仅比较年月日) */
+/** < 0 means a is earlier than b (year, month, and day only). */
function compareDay(a: YMD, b: YMD): number {
if (a.y !== b.y) return a.y - b.y;
if (a.m !== b.m) return a.m - b.m;
@@ -199,8 +199,8 @@ function formatEditableRange(start: Parts, end: Parts, isDate: boolean): string
}
/**
- * 解析输入框中的完整区间。仅接受明确的日期格式,避免浏览器自动修正
- * 2026-02-31 这类无效日期后提交错误查询。
+ * Parse a complete range from the input. Only explicit date formats are accepted, so the browser cannot
+ * auto-correct an invalid date such as 2026-02-31 and submit a wrong query.
*/
function parseEditableRange(
value: string,
@@ -252,7 +252,7 @@ function parseEditableRange(
return { start, end };
}
-/** 判断输入是否已经达到完整区间格式,供输入过程中区分“未输完”和“输入错误”。 */
+/** Whether the input has reached a complete range format, so typing can tell "not finished" from "invalid". */
function isCompleteEditableRange(value: string, mode: 'datetime' | 'date'): boolean {
const match =
value.trim().match(/^(.+?)\s+(?:→|->|to|至)\s+(.+)$/i) ??
@@ -264,7 +264,7 @@ function isCompleteEditableRange(value: string, mode: 'datetime' | 'date'): bool
return partPattern.test(match[1].trim()) && partPattern.test(match[2].trim());
}
-/** 仅保留日期区间输入允许的字符,避免无关文本进入控件状态。 */
+/** Keep only characters allowed in a date-range input, so unrelated text never enters the control state. */
function sanitizeEditableInput(value: string): string {
return value.replace(/[^\d\-: Tto至→>]/g, '');
}
@@ -342,11 +342,11 @@ const DEFAULT_PRESETS: DateRangePreset[] = [
];
/**
- * 日期时间区间选择器(@map/ui)。
+ * Date-time range picker (@map/ui).
*
- * 用途:统一替代「两个日期框 + 手填时间」的零散筛选,提供与设计系统一致的浮层:
- * 左侧快捷预设(全部/今天/昨天/最近 7 天/最近 30 天)、中间区间日历、右侧时/分/秒列,底部确定。
- * 基座为 @floating-ui/react(与本库 DatePicker 同源),受控:值由调用方持有,确定时回传。
+ * Purpose: replace the loose "two date fields plus a hand-typed time" filter with one popover that matches the design system:
+ * shortcuts on the left (All / today / yesterday / last 7 days / last 30 days), a range calendar in the middle, hour/minute/second columns on the right, and confirm at the bottom.
+ * Built on @floating-ui/react (same base as this library’s DatePicker). Controlled: the caller owns the value, and it is returned on confirm.
*/
function DateTimeRangePicker({
start,
@@ -365,10 +365,10 @@ function DateTimeRangePicker({
}: DateTimeRangePickerProps) {
const isDate = mode === 'date';
const presetList = presets ?? DEFAULT_PRESETS;
- // date 模式输出 YYYY-MM-DD,datetime 输出含时分秒。
+ // Date mode outputs YYYY-MM-DD; datetime includes hours, minutes, and seconds.
const emit = isDate ? formatDate : formatOut;
const [open, setOpen] = React.useState(false);
- // 草稿:打开后在面板内编辑,点「确定」才回写
+ // Draft: edit inside the panel after open, and write back only when "Confirm" is clicked.
const [draftStart, setDraftStart] = React.useState<Parts>({ ymd: null, h: 0, mi: 0, s: 0 });
const [draftEnd, setDraftEnd] = React.useState<Parts>({ ymd: null, h: 23, mi: 59, s: 59 });
const [active, setActive] = React.useState<'start' | 'end'>('start');
@@ -414,8 +414,8 @@ function DateTimeRangePicker({
React.useEffect(() => {
const formatted = formatTriggerText(start, end, allSelected, mode);
- // onChange 是受控回调,父组件可能在下一次 render 才回传新值;在此期间保留
- // 刚刚确认的输入,避免同步 effect 把它闪回旧区间。
+ // onChange is a controlled callback, and the parent may pass the new value back only on the next render; until then, keep
+ // the value just confirmed, so a sync effect does not flash the old range back.
if (pendingInputValueRef.current !== null) {
if (pendingInputValueRef.current !== formatted) return;
pendingInputValueRef.current = null;
@@ -450,7 +450,7 @@ function DateTimeRangePicker({
const today = todayYMD();
const cells = React.useMemo(() => {
- // 周一为一周起点:getDay() 周日=0 → 映射为 6
+ // Monday is the start of the week: getDay() Sunday = 0 maps to 6.
const firstWeekday = (new Date(view.y, view.m, 1).getDay() + 6) % 7;
const startDate = new Date(view.y, view.m, 1 - firstWeekday);
return Array.from({ length: 42 }, (_, i) => {
@@ -540,7 +540,7 @@ function DateTimeRangePicker({
const sHas = !!draftStart.ymd;
const eHas = !!draftEnd.ymd;
if (!sHas || (sHas && eHas)) {
- // 起一段新区间
+ // Start a new range.
const nextStart = { ...draftStart, ymd: cell };
const nextEnd = { ...draftEnd, ymd: null };
setDraftStart(nextStart);
@@ -551,7 +551,7 @@ function DateTimeRangePicker({
setInputError('');
return;
}
- // 已有起点、待选终点
+ // A start is set; waiting for the end.
if (compareDay(cell, draftStart.ymd!) < 0) {
const nextStart = { ...draftStart, ymd: cell };
setDraftStart(nextStart);
@@ -635,7 +635,7 @@ function DateTimeRangePicker({
setTime(target.side, target.field, next, caret);
}
- // 快捷预设:属于「快速选择」,点击即回填并收起浮层,无需再点「确定」。
+ // Shortcuts are "quick picks": a click fills the range and closes the popover, with no extra "Confirm".
function applyPreset(startYMD: YMD, endYMD: YMD) {
const s: Parts = { ymd: startYMD, h: 0, mi: 0, s: 0 };
const e: Parts = { ymd: endYMD, h: 23, mi: 59, s: 59 };
@@ -688,8 +688,8 @@ function DateTimeRangePicker({
applyInput(inputValue);
return;
}
- // 只选了一端(含日历里只点一天)也算单日区间:用已选的那天补齐另一端,
- // 起点保留其时间(默认 00:00:00)、终点保留其时间(默认 23:59:59)。
+ // Selecting only one end (including a single day click on the calendar) still counts as a one-day range: fill the other end with that day,
+ // keeping the start’s time (default 00:00:00) and the end’s time (default 23:59:59).
if (!draftStart.ymd && !draftEnd.ymd) return;
const s: Parts = draftStart.ymd ? draftStart : { ...draftStart, ymd: draftEnd.ymd };
const e: Parts = draftEnd.ymd ? draftEnd : { ...draftEnd, ymd: draftStart.ymd };
@@ -861,7 +861,7 @@ function DateTimeRangePicker({
getInsideElements={() => (inputRef.current ? [inputRef.current] : [])}
>
<div
- // eslint-disable-next-line react-hooks/refs -- Floating UI 的回调 ref 必须在渲染时传入。
+ // eslint-disable-next-line react-hooks/refs -- Floating UI’s callback ref must be passed during render.
ref={floatingRefs.setFloating}
style={floatingStyles}
className={cn(
@@ -872,7 +872,7 @@ function DateTimeRangePicker({
{...getFloatingProps()}
>
<div className="flex">
- {/* 左:快捷预设(传入空数组则不显示) */}
+ {/* Left: shortcuts (hidden when an empty array is passed) */}
{presetList.length > 0 && (
<div className="flex w-28 shrink-0 flex-col gap-1 border-r border-border/60 p-2">
{presetList.map((preset) => (
@@ -904,7 +904,7 @@ function DateTimeRangePicker({
</div>
)}
- {/* 中:区间日历 */}
+ {/* Middle: range calendar */}
<div className="min-w-0 flex-1 p-3">
<div className="mb-2 flex items-center justify-between">
<div className="flex items-center gap-0.5">
@@ -984,7 +984,7 @@ function DateTimeRangePicker({
</div>
</div>
- {/* 右:时分秒(date 模式隐藏) */}
+ {/* Right: hours, minutes, and seconds (hidden in date mode) */}
{!isDate && (
<div className="flex w-[15.5rem] shrink-0 flex-col border-l border-border/60">
<div className="flex items-center gap-2 border-b border-border/60 px-3 py-2 text-[13px]">
@@ -1032,7 +1032,7 @@ function DateTimeRangePicker({
)}
</div>
- {/* 底部操作 */}
+ {/* Footer actions */}
<div className="flex items-center justify-between border-t border-border/60 px-3 py-2">
<button
type="button"
diff --git a/webdemo/frontend/packages/ui/src/components/ui/dialog.tsx b/webdemo/frontend/packages/ui/src/components/ui/dialog.tsx
index 067a792..196fe4f 100644
--- a/webdemo/frontend/packages/ui/src/components/ui/dialog.tsx
+++ b/webdemo/frontend/packages/ui/src/components/ui/dialog.tsx
@@ -48,9 +48,9 @@ interface DialogContentProps extends React.ComponentPropsWithoutRef<
> {
onClose?: () => void;
closeLabel?: string;
- /** 居中弹窗或右侧抽屉。 */
+ /** Centered dialog or right-side drawer. */
variant?: 'dialog' | 'sheet-right';
- /** 覆盖遮罩样式;右侧抽屉可在桌面端弱化遮罩。 */
+ /** Override overlay styles; a right-side drawer can soften the overlay on desktop. */
overlayClassName?: string;
}
@@ -90,12 +90,12 @@ const DialogContent = React.forwardRef<HTMLDivElement, DialogContentProps>(
'motion-reduce:animate-none',
]
: [
- // 移动端:底部抽屉
+ // Mobile: bottom drawer.
'inset-x-0 bottom-0 max-h-[85vh] w-full rounded-t-2xl',
'shadow-[0_-8px_30px_-4px_rgba(0,0,0,0.12)]',
'[animation:map-sheet-in_250ms_ease-out]',
'data-[state=closed]:[animation:map-sheet-out_200ms_ease-in]',
- // 桌面端(≥sm):居中弹窗。
+ // Desktop (≥sm): centered dialog.
'sm:inset-x-auto sm:bottom-auto sm:left-1/2 sm:top-1/2 sm:max-h-[85vh]',
'sm:w-full sm:max-w-md sm:-translate-x-1/2 sm:-translate-y-1/2',
'sm:rounded-xl sm:border sm:border-border/40',
@@ -110,11 +110,11 @@ const DialogContent = React.forwardRef<HTMLDivElement, DialogContentProps>(
{!isRightSheet && (
<div className="mx-auto mt-3 h-1 w-10 shrink-0 rounded-full bg-muted-foreground/20 sm:hidden" />
)}
- {/* 内层滚动区:长内容在此纵向滚动;DialogHeader 用 sticky 钉在顶部,关闭键固定在 Content 角上。
- 注意:这里不能有 pt——sticky top-0 在带 padding-top 的滚动容器里会吸附到 padding 边而非顶边,
- 把头部整体下压,导致标题与关闭键错位、顶部露白。顶部留白改由 DialogHeader 自己的 pt 提供。
- scroll-pt-16 给 scroll-into-view(如 autoFocus 输入框)留出 sticky 头部高度,
- 避免聚焦时把首个字段标签滚到头部下方被裁切。 */}
+ {/* Inner scroll region: long content scrolls vertically here; DialogHeader sticks to the top, and the close button stays fixed on the Content corner.
+ Do not add pt here — sticky top-0 inside a scroll container with padding-top sticks to the padding edge rather than the top edge,
+ which pushes the whole header down, misaligns the title and the close button, and leaves a white gap at the top. Top spacing comes from DialogHeader’s own pt.
+ scroll-pt-16 reserves the sticky header height for scroll-into-view (for example an autoFocus input),
+ so focus does not scroll the first field’s label under the header and clip it. */}
<div
data-slot="dialog-scroll-body"
className="min-h-0 flex-1 scroll-pt-16 overflow-y-auto overscroll-contain px-5 pb-[calc(1.25rem+env(safe-area-inset-bottom))] sm:px-6 sm:pb-6"
@@ -149,10 +149,10 @@ const DialogContent = React.forwardRef<HTMLDivElement, DialogContentProps>(
DialogContent.displayName = 'DialogContent';
function DialogHeader({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
- // sticky 钉在内层滚动区顶部:用 -mx 把 bg-card 铺满 Content 宽度(抵消滚动区的 px),
- // 右侧 pr-12 给关闭键(X,绝对定位于 Content 的 top-5/6、right-5/6)留位,bg-card 遮挡下方滚动内容。
- // 关键:不要再加 -mt 抵消滚动区 pt——滚动区已无 pt,顶部留白由本头部自己的 pt-5/pt-6 提供,
- // 这样标题文字中心与关闭键中心对齐;负 mt 会被 sticky 夹回 padding 边,反而把标题压低、与 X 错位。
+ // Stick to the top of the inner scroll region: -mx spreads bg-card across the Content width (cancelling the scroll region’s px),
+ // pr-12 on the right leaves room for the close button (X, absolutely positioned at Content top-5/6 and right-5/6), and bg-card covers content scrolling underneath.
+ // Important: do not add -mt to cancel the scroll region’s pt — the scroll region has no pt, and top spacing comes from this header’s own pt-5/pt-6,
+ // so the title text center lines up with the close button center; a negative mt is clamped by sticky back to the padding edge, which drops the title and misaligns it with X.
return (
<div
className={cn(
@@ -164,8 +164,8 @@ function DialogHeader({ className, ...props }: React.HTMLAttributes<HTMLDivEleme
);
}
-// 接到 Radix 原语:DialogPrimitive.Title 会生成 id 并让 Content 自动 aria-labelledby,
-// 否则 Radix 会对每个 DialogContent 报「requires a DialogTitle」无障碍告警。
+// Wired to the Radix primitive: DialogPrimitive.Title generates an id and Content sets aria-labelledby automatically,
+// otherwise Radix warns on every DialogContent that it "requires a DialogTitle" for accessibility.
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
@@ -191,13 +191,13 @@ const DialogDescription = React.forwardRef<
DialogDescription.displayName = DialogPrimitive.Description.displayName;
function DialogFooter({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) {
- // sticky 钉在内层滚动区底部,与 DialogHeader 的 sticky top 对称:长表单时操作按钮始终吸底,不随内容滚走。
- // -mx 全宽铺 bg-card 盖住下方滚动内容;顶部 border + bg-card 与内容分隔,footer 自身 pb 提供底部留白(含移动端安全区)。
+ // Stick to the bottom of the inner scroll region, mirroring DialogHeader’s sticky top: on a long form the actions stay pinned and do not scroll away.
+ // -mx spreads bg-card full width over content scrolling underneath; a top border plus bg-card separates it from the content, and the footer’s own pb supplies bottom spacing (including the mobile safe area).
//
- // 关键:滚动区带有底部 padding(供无 footer 的弹窗留白),而 `position:sticky` 的吸附基准是滚动容器的
- // content-box(padding 内侧)——若用 `bottom-0`,footer 会停在 padding 上沿,其下方露出与 pb 等高的空白,
- // 按钮看起来“没贴到右下角”。这里把吸附点 `bottom` 设为负的 pb(-mb 同步抵消该段对滚动高度的占用),
- // 使 footer 真正贴到卡片底边,短表单与长表单滚动到底时都无留白。
+ // Important: the scroll region has bottom padding (spacing for dialogs with no footer), and the sticky offset for `position:sticky` is the scroll container’s
+ // content-box (inside the padding) — with `bottom-0`, the footer stops at the top of that padding and leaves a gap as tall as pb underneath,
+ // so the buttons look like they never reach the bottom-right corner. Set the sticky `bottom` to the negative pb (-mb cancels that span’s share of the scroll height),
+ // so the footer actually sits on the card’s bottom edge, with no leftover gap for a short form or when a long form is scrolled to the end.
return (
<div
className={cn(
diff --git a/webdemo/frontend/packages/ui/src/components/ui/dropdown-menu.tsx b/webdemo/frontend/packages/ui/src/components/ui/dropdown-menu.tsx
index 1b6bea3..a878dd4 100644
--- a/webdemo/frontend/packages/ui/src/components/ui/dropdown-menu.tsx
+++ b/webdemo/frontend/packages/ui/src/components/ui/dropdown-menu.tsx
@@ -3,12 +3,12 @@ import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu';
import { cn } from '../../utils';
-/** 可通过鼠标、触屏与键盘操作的命令菜单根节点。 */
+/** Command menu root that can be used with mouse, touch, and keyboard. */
export const DropdownMenu = DropdownMenuPrimitive.Root;
-/** 菜单触发器;asChild 复用现有按钮并保留其焦点与事件。 */
+/** Menu trigger; asChild reuses an existing button and keeps its focus and events. */
export const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;
-/** 可选菜单项;受控状态和键盘交互由 Radix 统一处理。 */
+/** Selectable menu item; controlled state and keyboard interaction are handled by Radix. */
export function DropdownMenuCheckboxItem({
className,
...props
@@ -25,9 +25,9 @@ export function DropdownMenuCheckboxItem({
}
/**
- * 菜单浮层:通过 Portal 避免工作台裁剪,并在视口边缘自动调整位置。
- * @param props Radix 菜单内容属性
- * @returns 使用设计 token 的命令菜单
+ * Menu popover: a Portal keeps the workbench from clipping it, and it repositions at the viewport edge.
+ * @param props Radix menu content props.
+ * @returns A command menu that uses design tokens.
*/
export function DropdownMenuContent({
className,
@@ -49,9 +49,9 @@ export function DropdownMenuContent({
}
/**
- * 菜单命令项:统一触控尺寸、键盘高亮和禁用状态。
- * @param props 菜单项与选择回调
- * @returns 支持键盘导航的命令项
+ * Menu command item: shared touch size, keyboard highlight, and disabled state.
+ * @param props Menu item and selection callback.
+ * @returns A command item that supports keyboard navigation.
*/
export function DropdownMenuItem({
className,
diff --git a/webdemo/frontend/packages/ui/src/components/ui/multi-select.tsx b/webdemo/frontend/packages/ui/src/components/ui/multi-select.tsx
index 090178b..47a1045 100644
--- a/webdemo/frontend/packages/ui/src/components/ui/multi-select.tsx
+++ b/webdemo/frontend/packages/ui/src/components/ui/multi-select.tsx
@@ -17,20 +17,20 @@ export interface MultiSelectProps {
}
/**
- * 下拉多选组件。
+ * Dropdown multi-select.
*
- * 用途:以下拉浮层 + 可勾选列表的形式选择多个选项,trigger 内以小标签回显已选项(可单独移除)。
- * 相比平铺的 {@link ChipMultiSelect},更适合候选项较多、不宜全部铺开的场景(如模型多选)。
- * 组件受控,选中值由调用方持有;内部只负责切换并返回下一组选中值,并处理浮层开合与外部点击关闭。
+ * Purpose: pick several options from a popover with a checkable list, and echo the selection as small tags inside the trigger (each tag can be removed on its own).
+ * Compared with the flat {@link ChipMultiSelect}, it fits a longer option list that should not all be laid out (for example multi-selecting models).
+ * The component is controlled; the caller owns the selected values. Internally it only toggles and returns the next selection, and it handles opening, closing, and outside clicks.
*
- * @param options 可选项列表
- * @param value 当前选中的 value 列表
- * @param onChange 选中变更回调
- * @param placeholder 未选中时的占位文案
- * @param emptyText 无可选项时的文案
- * @param ariaLabel trigger 的无障碍名称
- * @param className 外层容器样式类
- * @returns 下拉多选控件
+ * @param options Option list.
+ * @param value Currently selected values.
+ * @param onChange Selection change callback.
+ * @param placeholder Placeholder when nothing is selected.
+ * @param emptyText Copy when there are no options.
+ * @param ariaLabel Accessible name for the trigger.
+ * @param className Outer container classes.
+ * @returns The dropdown multi-select control.
*/
function MultiSelect({
options,
@@ -44,7 +44,7 @@ function MultiSelect({
const [open, setOpen] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);
- // 浮层展开期间监听外部点击与 Esc 关闭;@map/ui 暂无 Popover/click-outside 原语,内联实现即可。
+ // While the popover is open, listen for outside clicks and Esc to close it; @map/ui has no Popover or click-outside primitive yet, so this is inline.
useEffect(() => {
if (!open) return;
function handlePointerDown(event: PointerEvent) {
@@ -75,7 +75,7 @@ function MultiSelect({
onChange(value.filter((item) => item !== next));
}
- // 仅回显仍存在于 options 中的已选项,避免过滤后残留无效标签。
+ // Echo only selected items that are still in options, so a filter does not leave stale tags behind.
const selected = value
.map((item) => options.find((option) => option.value === item))
.filter((option): option is MultiSelectOption => Boolean(option));
diff --git a/webdemo/frontend/packages/ui/src/components/ui/pagination.tsx b/webdemo/frontend/packages/ui/src/components/ui/pagination.tsx
index 62ec24c..3dae4c2 100644
--- a/webdemo/frontend/packages/ui/src/components/ui/pagination.tsx
+++ b/webdemo/frontend/packages/ui/src/components/ui/pagination.tsx
@@ -18,15 +18,15 @@ export interface PaginationProps {
total: number;
onChange?: (page: number, pageSize: number) => void;
className?: string;
- /** 每页条数可选项;传空数组或 showSizeChanger=false 时隐藏选择器。默认 [20, 50, 100]。 */
+ /** Page-size options; an empty array or showSizeChanger=false hides the selector. Default [20, 50, 100]. */
pageSizeOptions?: number[];
- /** 是否展示「每页条数」选择器(默认 true) */
+ /** Whether to show the "per page" selector (default true). */
showSizeChanger?: boolean;
- /** 是否展示「跳至 X 页」快捷跳转(默认 true) */
+ /** Whether to show the "go to page X" jump (default true). */
showQuickJump?: boolean;
- /** 是否展示页码按钮(默认 true);关闭后仅保留左右翻页按钮。 */
+ /** Whether to show page-number buttons (default true); when off, only the previous and next buttons remain. */
showPageNumbers?: boolean;
- /** 分页文案,未传入时使用中文默认文案以兼容现有调用方。 */
+ /** Pagination copy. When omitted, Chinese defaults are used so existing callers stay compatible. */
labels?: Partial<PaginationLabels>;
}
@@ -66,7 +66,7 @@ function Pagination({
onChange?.(page, pageSize);
};
- // 改每页条数后回到第 1 页,避免越界到空页。
+ // After the page size changes, go back to page 1 so the view does not land on an empty page.
const changeSize = (size: number) => {
if (size === pageSize) return;
onChange?.(1, size);
diff --git a/webdemo/frontend/packages/ui/src/components/ui/pro-form.tsx b/webdemo/frontend/packages/ui/src/components/ui/pro-form.tsx
index 35df97f..7f3a6eb 100644
--- a/webdemo/frontend/packages/ui/src/components/ui/pro-form.tsx
+++ b/webdemo/frontend/packages/ui/src/components/ui/pro-form.tsx
@@ -27,7 +27,7 @@ function ProForm({ columns = 1, className, children, ...props }: ProFormProps) {
export interface ProFormFieldProps {
label: string;
- /** 在标签旁展示的可选操作,保持在 label 元素之外。 */
+ /** Optional action shown beside the label, kept outside the label element. */
labelAction?: ReactNode;
name?: string;
required?: boolean;
diff --git a/webdemo/frontend/packages/ui/src/components/ui/pro-table-parts.tsx b/webdemo/frontend/packages/ui/src/components/ui/pro-table-parts.tsx
index 476aa84..0aa9b6f 100644
--- a/webdemo/frontend/packages/ui/src/components/ui/pro-table-parts.tsx
+++ b/webdemo/frontend/packages/ui/src/components/ui/pro-table-parts.tsx
@@ -83,7 +83,7 @@ function ExpandButton({
);
}
-/** 渲染桌面端数据行和可选的展开内容。 */
+/** Render a desktop data row and optional expanded content. */
export function DesktopRows<T extends object>({
record,
rowKey,
@@ -151,7 +151,7 @@ export function DesktopRows<T extends object>({
);
}
-/** 渲染移动端卡片和可选的展开内容。 */
+/** Render a mobile card and optional expanded content. */
export function MobileCard<T extends object>({
record,
columns,
@@ -258,7 +258,7 @@ export function MobileCard<T extends object>({
);
}
-/** 渲染桌面端表格骨架屏。 */
+/** Render the desktop table skeleton. */
export function TableSkeleton<T>({
columns,
rows,
@@ -294,7 +294,7 @@ export function TableSkeleton<T>({
);
}
-/** 渲染移动端卡片骨架屏。 */
+/** Render the mobile card skeleton. */
export function MobileCardSkeleton({ rows }: { rows: number }) {
return (
<>
@@ -317,7 +317,7 @@ export function MobileCardSkeleton({ rows }: { rows: number }) {
);
}
-/** 渲染 ProTable 的默认空状态。 */
+/** Render ProTable’s default empty state. */
export function EmptyState({ children }: { children?: ReactNode }) {
if (children) return <>{children}</>;
return (
diff --git a/webdemo/frontend/packages/ui/src/components/ui/pro-table.tsx b/webdemo/frontend/packages/ui/src/components/ui/pro-table.tsx
index 5df6245..2645546 100644
--- a/webdemo/frontend/packages/ui/src/components/ui/pro-table.tsx
+++ b/webdemo/frontend/packages/ui/src/components/ui/pro-table.tsx
@@ -19,15 +19,15 @@ export interface ProColumnDef<T> {
render?: (value: unknown, record: T, index: number) => ReactNode;
className?: string;
hideOnMobile?: boolean;
- /** 固定到右侧:横向滚动时该列(通常是「操作」列)保持可见,常配 text-right 使用。 */
+ /** Pin to the right: this column (usually the "Actions" column) stays visible while scrolling horizontally, often with text-right. */
fixed?: 'right';
cardTitle?: boolean;
cardDesc?: boolean;
cardTag?: boolean;
}
-/** 右固定列的粘性样式:吸附右侧、盖住下层内容,左侧加细阴影提示可滚动。
- * 背景需与所在行一致——表头用 bg-muted(同表头底色),表体用 bg-card——否则固定列底色会突兀。 */
+/** Sticky styles for a right-pinned column: stick to the right, cover content underneath, and add a thin shadow on the left to show that it can scroll.
+ * The background must match the row — bg-muted on the header (same as the header fill), bg-card on the body — or the pinned column’s fill looks out of place. */
function fixedCellClass<T>(col: ProColumnDef<T>, isHeader = false): string | undefined {
if (col.fixed !== 'right') return undefined;
return cn(
@@ -43,17 +43,17 @@ export interface ProTablePagination {
pageSize: number;
total: number;
onChange?: (page: number, pageSize: number) => void;
- /** 每页条数选项;缺省沿用 Pagination 的默认选项。 */
+ /** Page-size options; when omitted, Pagination’s defaults are used. */
pageSizeOptions?: number[];
- /** 是否展示每页条数选择器;默认 true。 */
+ /** Whether to show the page-size selector; default true. */
showSizeChanger?: boolean;
- /** 是否展示快捷跳页;默认 true。 */
+ /** Whether to show the quick page jump; default true. */
showQuickJump?: boolean;
- /** 是否展示页码按钮;默认 true。 */
+ /** Whether to show page-number buttons; default true. */
showPageNumbers?: boolean;
}
-/** ProTable 展开按钮渲染参数。 */
+/** Render props for a ProTable expand button. */
export interface ProTableExpandButtonProps {
record: unknown;
expanded: boolean;
@@ -67,47 +67,47 @@ export interface ProTableProps<T extends object> {
dataSource: T[];
rowKey: keyof T | ((record: T) => string);
loading?: boolean;
- /** 顶部裸工具栏(不带卡片背景),用于标题/按钮等。与 filters 互斥使用,优先用 filters。 */
+ /** Bare toolbar at the top (no card background), for a title, buttons, and similar. Mutually exclusive with filters; prefer filters. */
toolbar?: ReactNode;
/**
- * 筛选区:渲染为独立的「筛选卡片」置于表格卡片上方(两段式排版)。
- * 传入筛选控件(搜索框 + 下拉 + 动作按钮)即可获得统一的「筛选卡片 + 表格卡片」布局。
+ * Filter region: rendered as its own "filter card" above the table card (two-part layout).
+ * Pass filter controls (search box, dropdowns, and action buttons) to get the shared "filter card + table card" layout.
*/
filters?: ReactNode;
- /** 结果卡片头部右侧插槽:放视图切换、导出等动作。 */
+ /** Right slot in the result-card header: view switches, export, and similar actions. */
tableHeader?: ReactNode;
- /** 结果总数:显式传入则在结果卡片头部展示「共 N 条」;缺省时回退到 pagination.total。 */
+ /** Result total: when passed explicitly, the result-card header shows "N total"; otherwise it falls back to pagination.total. */
total?: number;
- /** 计数名词,拼在「共 N 条」之后,如「数据集」「调用」。 */
+ /** Count noun appended after "N total", for example "datasets" or "calls". */
countNoun?: string;
- /** 是否展示「共 N 条」计数(默认 true)。分页总数为估算值时可关闭,避免误导。 */
+ /** Whether to show the "N total" count (default true). Turn it off when the page total is an estimate, so it does not mislead. */
showCount?: boolean;
empty?: ReactNode;
className?: string;
/**
- * 桌面端表格最小宽度(px):列多时给足固定宽度,超出容器即横向滚动,
- * 避免列被压缩成多行折行。缺省则表格自适应容器宽度(原行为)。
+ * Minimum desktop table width (px): when there are many columns, give them a fixed width and scroll horizontally past the container,
+ * instead of squeezing columns into wrapped lines. When omitted, the table sizes to the container (previous behavior).
*/
minWidth?: number;
skeletonRows?: number;
forceMobile?: boolean;
- /** 桌面端是否填满所在网格行高度,并将分页器贴到底部。 */
+ /** On desktop, fill the grid row height and pin the paginator to the bottom. */
fillHeight?: boolean;
pagination?: ProTablePagination | false;
- /** 可选展开行:展开内容由业务页按行提供,展开状态由业务页管理。 */
+ /** Optional expandable rows: the page supplies expanded content per row and owns the expanded state. */
expandable?: {
expandedRowKeys: string[];
onExpandedChange: (keys: string[]) => void;
renderExpandedRow: (record: T) => ReactNode;
- /** 展开控制列的表头文案,默认不显示。 */
+ /** Header copy for the expand-control column; hidden by default. */
columnTitle?: string;
- /** 展开控制列的附加样式,适用于带文字的展开控件。 */
+ /** Extra styles for the expand-control column, for expand controls that include text. */
columnClassName?: string;
- /** 按行控制是否显示展开按钮;不可展开的行仍保留空白控制列以保持表格对齐。 */
+ /** Per row, whether to show the expand button; rows that cannot expand still keep a blank control cell so the table stays aligned. */
isRowExpandable?: (record: T) => boolean;
- /** 按行控制展开后是否渲染详情内容;可用于将展开状态复用于树形数据。 */
+ /** Per row, whether expanded state renders detail content; the expanded state can also be reused for tree data. */
hasExpandedContent?: (record: T) => boolean;
- /** 自定义展开按钮,用于区分不同展开语义。 */
+ /** Custom expand button, to distinguish different expand meanings. */
renderExpandButton?: (props: ProTableExpandButtonProps) => ReactNode;
};
}
diff --git a/webdemo/frontend/packages/ui/src/components/ui/progress.tsx b/webdemo/frontend/packages/ui/src/components/ui/progress.tsx
index aa21bca..531ba2c 100644
--- a/webdemo/frontend/packages/ui/src/components/ui/progress.tsx
+++ b/webdemo/frontend/packages/ui/src/components/ui/progress.tsx
@@ -3,25 +3,25 @@ import * as ProgressPrimitive from '@radix-ui/react-progress';
import { cn } from '../../utils';
/**
- * 进度条。
+ * Progress bar.
*
- * 用途:表示一个 0–100 的完成度(如评测任务进度、调度序列完成率)。
- * 轨道用 `bg-muted`,已完成段默认 `bg-primary`;可通过 `indicatorClassName`
- * 换成语义色(如 `bg-success`/`bg-destructive`)以表达不同状态,颜色全走 token。
+ * Purpose: a 0–100 completion level (for example an evaluation task or a schedule sequence).
+ * The track uses `bg-muted`, and the filled part defaults to `bg-primary`; `indicatorClassName`
+ * can switch it to a semantic color (such as `bg-success` or `bg-destructive`) for a different state. Colors all come from tokens.
*
- * @param value 当前进度值(0–100),传入 undefined/null 视为 0
- * @param indicatorClassName 覆盖已完成段的样式(用于换语义色)
+ * @param value Current progress (0–100); undefined or null is treated as 0.
+ * @param indicatorClassName Styles that override the filled part (used to change the semantic color).
*/
interface ProgressProps extends React.ComponentPropsWithoutRef<typeof ProgressPrimitive.Root> {
value?: number | null;
indicatorClassName?: string;
- /** 没有真实百分比时展示持续运动的处理中状态。 */
+ /** When there is no real percentage, show a continuously moving in-progress state. */
indeterminate?: boolean;
}
const Progress = React.forwardRef<React.ElementRef<typeof ProgressPrimitive.Root>, ProgressProps>(
({ className, value, indicatorClassName, indeterminate = false, ...props }, ref) => {
- // 约束到 [0,100],避免越界值把指示条推出轨道
+ // Clamp to [0, 100] so an out-of-range value cannot push the indicator out of the track.
const clamped = Math.max(0, Math.min(100, value ?? 0));
return (
<ProgressPrimitive.Root
diff --git a/webdemo/frontend/packages/ui/src/components/ui/search-select.tsx b/webdemo/frontend/packages/ui/src/components/ui/search-select.tsx
index a344c1e..395aca4 100644
--- a/webdemo/frontend/packages/ui/src/components/ui/search-select.tsx
+++ b/webdemo/frontend/packages/ui/src/components/ui/search-select.tsx
@@ -9,9 +9,9 @@ import type { SearchSelectProps } from './search-select.types';
export type { SearchSelectOption, SearchSelectProps } from './search-select.types';
/**
- * 可搜索单选/多选:清除按钮与输入同行,已选项按身份回显,浮层支持键盘和远程分页。
- * @param props 搜索、候选、已选项及状态文案
- * @returns 可访问的组合框与独立定位的候选浮层
+ * Searchable single or multi select: the clear button sits on the same row as the input, selected items are echoed by identity, and the popover supports keyboard use and remote paging.
+ * @param props Search, candidates, selected items, and status copy.
+ * @returns An accessible combobox and an independently positioned candidate popover.
*/
export function SearchSelect({
clearLabel = '清除',
diff --git a/webdemo/frontend/packages/ui/src/components/ui/search-select.types.ts b/webdemo/frontend/packages/ui/src/components/ui/search-select.types.ts
index 22d2b20..9e59a1c 100644
--- a/webdemo/frontend/packages/ui/src/components/ui/search-select.types.ts
+++ b/webdemo/frontend/packages/ui/src/components/ui/search-select.types.ts
@@ -1,11 +1,11 @@
-/** 可搜索选项使用稳定身份,允许展示名称相同或候选来自不同服务端分页。 */
+/** A searchable option has a stable identity, so display names may match or candidates may come from different server pages. */
export interface SearchSelectOption {
value: string;
label: string;
description?: string;
}
-/** 搜索关键词与已选身份分开受控,单选和多选共享同一浮层交互。 */
+/** The search keyword and the selected identity are controlled separately; single and multi select share the same popover interaction. */
export interface SearchSelectProps {
options: readonly SearchSelectOption[];
selectedOptions: readonly SearchSelectOption[];
diff --git a/webdemo/frontend/packages/ui/src/components/ui/select.tsx b/webdemo/frontend/packages/ui/src/components/ui/select.tsx
index 010eed4..45c73f0 100644
--- a/webdemo/frontend/packages/ui/src/components/ui/select.tsx
+++ b/webdemo/frontend/packages/ui/src/components/ui/select.tsx
@@ -18,9 +18,9 @@ const SelectTrigger = React.forwardRef<
'placeholder:text-muted-foreground/60',
'hover:border-primary/30',
'focus:outline-none',
- // 仅键盘聚焦时高亮;鼠标点选关闭后不留紫框(与 Input/Button 一致)
+ // Highlight only for keyboard focus; a mouse selection that closes the menu leaves no purple ring (same as Input and Button).
'focus-visible:border-primary/50 focus-visible:ring-1 focus-visible:ring-primary/20',
- // 展开中保留轻微边框提示,收起后恢复默认
+ // Keep a light border hint while open, and return to the default once closed.
'data-[state=open]:border-primary/30',
'disabled:cursor-not-allowed disabled:opacity-50',
'[&>span]:line-clamp-1',
@@ -104,7 +104,7 @@ const SelectScrollDownButton = React.forwardRef<
));
SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName;
-// Popper 定位依赖 transform,入场动画只用 opacity,避免与 Radix 定位/transform 冲突导致「跳一下」
+// Popper positioning depends on transform, so the enter animation uses opacity only and does not fight Radix positioning or transform and cause a jump.
const selectContentStyles = `
@keyframes map-select-in {
from { opacity: 0; }
@@ -147,7 +147,7 @@ function ensureSelectKeyframes() {
interface SelectContentProps extends React.ComponentPropsWithoutRef<
typeof SelectPrimitive.Content
> {
- /** 列表滚动方式:buttons 保持 Radix 默认箭头;native 使用系统原生滚动条。 */
+ /** List scrolling: buttons keeps the Radix default arrows; native uses the system scrollbar. */
scrollMode?: 'buttons' | 'native';
}
@@ -165,7 +165,7 @@ const SelectContent = React.forwardRef<HTMLDivElement, SelectContentProps>(
ref={ref}
sideOffset={sideOffset}
className={cn(
- // 浮层层级须高于 Dialog(overlay/content 均为 z-50),否则在弹窗内打开下拉会被盖住
+ // The popover must stack above Dialog (overlay and content are both z-50), or a dropdown opened inside a dialog is covered.
'map-select-content relative z-[60] max-h-72 min-w-[8rem] overflow-hidden rounded-lg border border-border/60 bg-card text-card-foreground',
scrollMode === 'native' && 'map-select-native-scroll',
'shadow-[0_8px_30px_-4px_rgba(0,0,0,0.1),0_2px_8px_-2px_rgba(0,0,0,0.06)]',
diff --git a/webdemo/frontend/packages/ui/src/components/ui/switch.tsx b/webdemo/frontend/packages/ui/src/components/ui/switch.tsx
index f6eac07..94d18ac 100644
--- a/webdemo/frontend/packages/ui/src/components/ui/switch.tsx
+++ b/webdemo/frontend/packages/ui/src/components/ui/switch.tsx
@@ -2,31 +2,31 @@ import type { Ref } from 'react';
import { cn } from '../../utils';
export interface SwitchProps {
- /** 是否开启(受控) */
+ /** Whether it is on (controlled). */
checked: boolean;
- /** 开关切换回调;disabled 时不触发 */
+ /** Toggle callback; not fired when disabled. */
onCheckedChange?: (checked: boolean) => void;
- /** 是否禁用(仅展示、不可操作) */
+ /** Whether it is disabled (display only, not interactive). */
disabled?: boolean;
- /** 无可见文案时的可访问名称 */
+ /** Accessible name when there is no visible copy. */
'aria-label'?: string;
- /** 额外样式类 */
+ /** Extra style classes. */
className?: string;
ref?: Ref<HTMLButtonElement>;
}
/**
- * 开关原语。
+ * Switch primitive.
*
- * 用途:提供平台统一的开/关切换外观,语义等价单个布尔项(对应「是否展示思考」这类
- * 二态设置)。以 role="switch" 的 button 实现,键盘/屏幕阅读器可直接识别;disabled
- * 时仅展示当前态、不响应点击。视觉层统一走语义 token,暗色模式自动适配。
+ * Purpose: the platform’s unified on/off appearance, semantically one boolean (the kind of two-state setting
+ * as "whether to show reasoning"). Implemented as a button with role="switch", so keyboard and screen readers can recognize it directly; when disabled
+ * it only shows the current state and ignores clicks. Visuals use semantic tokens and adapt to dark mode.
*
- * @param checked 当前是否开启
- * @param onCheckedChange 切换回调(disabled 时不触发)
- * @param disabled 是否禁用
- * @param className 额外样式类
- * @returns 语义化开关按钮
+ * @param checked Whether it is currently on.
+ * @param onCheckedChange Toggle callback (not fired when disabled).
+ * @param disabled Whether it is disabled.
+ * @param className Extra style classes.
+ * @returns A semantic switch button.
*/
function Switch({ checked, onCheckedChange, disabled, className, ref, ...props }: SwitchProps) {
return (
diff --git a/webdemo/frontend/packages/ui/src/components/ui/tabs.tsx b/webdemo/frontend/packages/ui/src/components/ui/tabs.tsx
index b8141cf..a56a855 100644
--- a/webdemo/frontend/packages/ui/src/components/ui/tabs.tsx
+++ b/webdemo/frontend/packages/ui/src/components/ui/tabs.tsx
@@ -3,10 +3,10 @@ import * as TabsPrimitive from '@radix-ui/react-tabs';
import { cn } from '../../utils';
/**
- * 标签页根容器。
+ * Tabs root.
*
- * 用途:在同一视图内切换多组互斥内容(如任务看板的「全部/运行中/排队/完成/失败」筛选)。
- * 受控用 `value` + `onValueChange`,非受控用 `defaultValue`,行为由 Radix 处理。
+ * Purpose: switch among mutually exclusive groups in one view (for example a task board’s All / running / queued / done / failed filters).
+ * Controlled with `value` plus `onValueChange`, uncontrolled with `defaultValue`; Radix handles the behavior.
*/
const Tabs = TabsPrimitive.Root;
@@ -17,7 +17,7 @@ interface IndicatorRect {
height: number;
}
-/** 量出当前选中 trigger 相对标签条的几何位置;没有选中项时返回 null */
+/** Measure the selected trigger’s geometry relative to the tab bar; returns null when nothing is selected. */
function measureActive(list: HTMLElement): IndicatorRect | null {
const active = list.querySelector<HTMLElement>('[role="tab"][data-state="active"]');
if (!active) return null;
@@ -30,15 +30,15 @@ function measureActive(list: HTMLElement): IndicatorRect | null {
}
/**
- * 标签条:segmented(分段控件)风格容器。
+ * Tab bar: a segmented-control container.
*
- * 设计意图:用背景色差(bg-muted 底)+ 选中项阴影来区分,不依赖边框分隔,贴合平台
- * 「以阴影/背景色差代替 border」的视觉偏好。
+ * Intent: separate items with a background difference (bg-muted base) plus a shadow on the selected item, not with borders, matching the platform
+ * preference to use shadow and background contrast instead of a border.
*
- * 选中态由一个绝对定位的指示器承载而不是画在 trigger 上,这样切换时它是「滑过去」
- * 而不是两块背景硬跳。位置靠测量 DOM 得到,因此纵向标签条、grid/flex-1 等布局、
- * 以及运行时增减标签都不用额外适配。要换指示器配色就覆盖
- * `[data-map-tabs-indicator]`(见 docs.css 的文档代码块标签)。
+ * The selected state is an absolutely positioned indicator rather than paint on the trigger, so a switch slides
+ * instead of two backgrounds jumping. Position comes from measuring the DOM, so a vertical tab bar, grid or flex-1 layouts,
+ * and tabs added or removed at runtime need no extra adaptation. To recolor the indicator, override
+ * `[data-map-tabs-indicator]` (see the docs code-block tabs in docs.css).
*/
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
@@ -46,7 +46,7 @@ const TabsList = React.forwardRef<
>(({ className, children, ...props }, ref) => {
const listRef = React.useRef<HTMLDivElement | null>(null);
const [rect, setRect] = React.useState<IndicatorRect | null>(null);
- // 首帧只就位、不过渡,否则指示器会从左上角滑向初始选中项
+ // The first frame only settles in place, with no transition, or the indicator slides from the top-left toward the initial selection.
const [animated, setAnimated] = React.useState(false);
const attachList = React.useCallback(
@@ -69,7 +69,7 @@ const TabsList = React.forwardRef<
sync();
const frame = requestAnimationFrame(() => setAnimated(true));
- // data-state 变化=切了标签;childList 变化=标签本身增减
+ // A data-state change means the tab changed; a childList change means tabs were added or removed.
const mutation = new MutationObserver(sync);
mutation.observe(list, {
attributes: true,
@@ -77,7 +77,7 @@ const TabsList = React.forwardRef<
childList: true,
subtree: true,
});
- // 尺寸变化(响应式、文案换语言、字体加载完成)后重新贴合
+ // After a size change (responsive layout, copy language, or fonts finishing load), fit the indicator again.
const resize = new ResizeObserver(sync);
resize.observe(list);
@@ -123,8 +123,8 @@ const TabsList = React.forwardRef<
TabsList.displayName = TabsPrimitive.List.displayName;
/**
- * 单个标签触发器。选中态只改文字色,背景与阴影交给标签条的滑动指示器;
- * `relative` 是必需的——要让文字叠在指示器上面。
+ * One tab trigger. The selected state only changes the text color; the background and shadow belong to the tab bar’s sliding indicator.
+ * `relative` is required so the text stacks above the indicator.
*/
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
@@ -145,7 +145,7 @@ const TabsTrigger = React.forwardRef<
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;
/**
- * 标签内容面板。仅在对应标签选中时渲染其子内容。
+ * Tab content panel. Renders its children only while the matching tab is selected.
*/
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
diff --git a/webdemo/frontend/packages/ui/src/components/ui/useSearchSelect.ts b/webdemo/frontend/packages/ui/src/components/ui/useSearchSelect.ts
index ebef704..530d876 100644
--- a/webdemo/frontend/packages/ui/src/components/ui/useSearchSelect.ts
+++ b/webdemo/frontend/packages/ui/src/components/ui/useSearchSelect.ts
@@ -12,7 +12,7 @@ import {
} from '@floating-ui/react';
import type { SearchSelectOption, SearchSelectProps } from './search-select.types';
-/** 管理可搜索选择器的浮层、虚拟键盘焦点和独立的搜索/选择状态。 */
+/** Manages the searchable select’s popover, virtual keyboard focus, and separate search and selection state. */
export function useSearchSelect(props: SearchSelectProps) {
const { search, selectedOptions, multiple, remote, disabled } = props;
const [open, setOpen] = useState(false);
@@ -98,7 +98,7 @@ export function useSearchSelect(props: SearchSelectProps) {
function remove(option: SearchSelectOption) {
props.onSelectionChange(selectedOptions.filter((selected) => selected.value !== option.value));
inputRef.current?.focus();
- // 移除操作只恢复输入焦点,不应把原本关闭的候选浮层重新打开。
+ // A remove action only restores input focus, and must not reopen a candidate popover that was closed.
setOpen(open);
}
diff --git a/webdemo/frontend/packages/ui/src/theme.css b/webdemo/frontend/packages/ui/src/theme.css
index 5130911..02d414c 100644
--- a/webdemo/frontend/packages/ui/src/theme.css
+++ b/webdemo/frontend/packages/ui/src/theme.css
@@ -1,16 +1,16 @@
/**
- * MAP 设计系统 — 主题 Token 单一来源
+ * MAP design system — single source of theme tokens
*
- * 所有应用通过 `@import '@map/ui/theme.css';` 引入。
- * 改颜色 / 圆角 / 字体只改这里一处,全平台生效。
- * 颜色为 HSL 通道值(不含 hsl()),供 tailwind.config.js 的 `hsl(var(--token) / <alpha-value>)` 消费。
+ * Every app imports it with `@import '@map/ui/theme.css';`.
+ * Color, radius, and type change in this one place and apply across the platform.
+ * Colors are HSL channels (without hsl()), consumed by tailwind.config.js as `hsl(var(--token) / <alpha-value>)`.
*/
-/* Inter 用于英文/数字; Noto Sans SC + 系统中文字体用于中文界面 */
+/* Inter is for English and digits; Noto Sans SC plus system Chinese fonts are for the Chinese UI. */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500;600&family=Noto+Sans+SC:wght@400;500;600;700&display=swap');
@layer base {
:root {
- /* ---- 颜色(亮色) ---- */
+ /* ---- Color (light) ---- */
--background: 230 100% 99%;
--foreground: 226 32% 17%;
--card: 0 0% 100%;
@@ -30,31 +30,31 @@
--destructive: 0 84% 60%;
--destructive-foreground: 0 0% 100%;
- /* ---- 状态色(语义 token,亮/暗自动切换) ---- */
- --success: 160 84% 39%; /* emerald-500 — 通过/在线/健康 */
+ /* ---- Status colors (semantic tokens; light and dark switch automatically) ---- */
+ --success: 160 84% 39%; /* emerald-500 — pass / online / healthy */
--success-foreground: 0 0% 100%;
- --warning: 38 92% 50%; /* amber-500 — 降级/待处理 */
+ --warning: 38 92% 50%; /* amber-500 — degraded / pending */
--warning-foreground: 38 92% 12%;
- --info: 217 91% 60%; /* blue-500 — 中性提示 */
+ --info: 217 91% 60%; /* blue-500 — neutral notice */
--info-foreground: 0 0% 100%;
- /* ---- OCR 置信度:独立于全站状态色,保持原图可读与分级一致 ---- */
+ /* ---- OCR confidence: independent of site-wide status colors, so the source image stays readable and the scale stays consistent ---- */
--ocr-confidence-high: 142 71% 45%;
--ocr-confidence-low: 24 95% 53%;
--ocr-confidence-error: 0 84% 60%;
--ocr-confidence-neutral: 220 9% 46%;
- --ocr-link: var(--primary); /* 双栏定位跟随主题色,不改变置信度分级 */
+ --ocr-link: var(--primary); /* Two-column positioning follows the theme color and does not change the confidence scale. */
- /* ---- 图表色板(榜单/指标可视化,色盲友好且区分度高) ---- */
- --chart-1: 239 84% 67%; /* indigo(主色系列) */
+ /* ---- Chart palette (leaderboards and metric visuals; colorblind-friendly and easy to tell apart) ---- */
+ --chart-1: 239 84% 67%; /* indigo (primary series) */
--chart-2: 173 80% 40%; /* teal */
--chart-3: 38 92% 50%; /* amber */
--chart-4: 330 81% 60%; /* pink */
- --annotation-foreground: 226 32% 17%; /* 图上粉色标签始终使用深色文字 */
+ --annotation-foreground: 226 32% 17%; /* Pink labels on charts always use dark text. */
--chart-5: 217 91% 60%; /* blue */
--chart-6: 142 71% 45%; /* green */
- /* ---- 圆角(shadcn 标准:单一基准值,派生 sm/md/lg) ---- */
+ /* ---- Radius (shadcn standard: one base value, sm/md/lg derived) ---- */
--radius: 0.5rem;
}
@@ -78,7 +78,7 @@
--destructive: 0 63% 31%;
--destructive-foreground: 0 0% 100%;
- /* ---- 状态色:暗色下调亮以保证对比度 ---- */
+ /* ---- Status colors: brightened in dark mode so contrast holds ---- */
--success: 158 64% 52%; /* emerald-400 */
--warning: 43 96% 56%; /* amber-400 */
--info: 213 94% 68%; /* blue-400 */
@@ -87,7 +87,7 @@
--ocr-confidence-error: 0 84% 60%;
--ocr-confidence-neutral: 218 11% 65%;
--ocr-link: var(--primary);
- /* 图表色板沿用 :root 定义,如需暗色微调可在此覆盖 */
+ /* The chart palette keeps the :root definition; override here if dark mode needs a tweak. */
}
body {
diff --git a/webdemo/frontend/packages/ui/tailwind.config.js b/webdemo/frontend/packages/ui/tailwind.config.js
index ca3170f..0abc117 100644
--- a/webdemo/frontend/packages/ui/tailwind.config.js
+++ b/webdemo/frontend/packages/ui/tailwind.config.js
@@ -47,7 +47,7 @@ export default {
DEFAULT: 'hsl(var(--destructive) / <alpha-value>)',
foreground: 'hsl(var(--destructive-foreground) / <alpha-value>)',
},
- // ---- 状态色:引用 theme.css 的 HSL token,亮/暗自动切换 ----
+ // ---- Status colors: HSL tokens from theme.css; light and dark switch automatically ----
success: {
DEFAULT: 'hsl(var(--success) / <alpha-value>)',
foreground: 'hsl(var(--success-foreground) / <alpha-value>)',
@@ -60,7 +60,7 @@ export default {
DEFAULT: 'hsl(var(--info) / <alpha-value>)',
foreground: 'hsl(var(--info-foreground) / <alpha-value>)',
},
- // ---- 图表色板:图表统一用 chart-1..6,禁止写死 hex ----
+ // ---- Chart palette: charts use chart-1..6 only; do not hard-code hex ----
chart: {
1: 'hsl(var(--chart-1) / <alpha-value>)',
2: 'hsl(var(--chart-2) / <alpha-value>)',
@@ -81,7 +81,7 @@ export default {
'ocr-link': 'hsl(var(--ocr-link) / <alpha-value>)',
},
fontFamily: {
- // Inter 负责英文/数字,Noto Sans SC + 系统中文字体保证中文在各平台一致、不生硬
+ // Inter handles English and digits; Noto Sans SC plus system Chinese fonts keep Chinese consistent and natural on every platform.
sans: [
'Inter',
'Noto Sans SC',
@@ -91,26 +91,26 @@ export default {
'Microsoft YaHei',
'sans-serif',
],
- // 数字/分数/延迟/JSON/代码用等宽,配 tabular-nums 对齐
+ // Numbers, scores, latency, JSON, and code use monospace, with tabular-nums for alignment.
mono: ['JetBrains Mono', 'Fira Code', 'monospace'],
},
- // ---- 圆角:基于 --radius 单一基准,sm/md/lg 自动派生(shadcn 标准) ----
+ // ---- Radius: one --radius base; sm/md/lg are derived (shadcn standard) ----
borderRadius: {
lg: 'var(--radius)',
md: 'calc(var(--radius) - 2px)',
sm: 'calc(var(--radius) - 4px)',
},
- // ---- 间距:补齐 Tailwind 缺失的数值 + 布局语义尺寸 ----
+ // ---- Spacing: fill in Tailwind’s missing numeric steps plus layout semantic sizes ----
spacing: {
4.5: '1.125rem', // 18px
13: '3.25rem', // 52px
15: '3.75rem', // 60px
18: '4.5rem', // 72px
- header: '3.5rem', // 顶栏高度 (h-header)
- sidebar: '15rem', // 侧边栏展开宽度 (w-sidebar)
- 'sidebar-collapsed': '4rem', // 侧边栏收起宽度 (w-sidebar-collapsed)
+ header: '3.5rem', // Top bar height (h-header)
+ sidebar: '15rem', // Expanded sidebar width (w-sidebar)
+ 'sidebar-collapsed': '4rem', // Collapsed sidebar width (w-sidebar-collapsed)
},
- // ---- 阴影:卡片用阴影代替 border 营造层级,hover 加深 ----
+ // ---- Shadow: cards use shadow instead of a border for depth, and hover deepens it ----
boxShadow: {
card: '0 2px 8px 0 rgb(0 0 0 / 0.04)',
'card-hover': '0 8px 24px -4px rgb(0 0 0 / 0.12), 0 2px 6px -2px rgb(0 0 0 / 0.06)',
diff --git a/webdemo/frontend/src/__tests__/AuthGuard.test.tsx b/webdemo/frontend/src/__tests__/AuthGuard.test.tsx
index 507d661..e9645a4 100644
--- a/webdemo/frontend/src/__tests__/AuthGuard.test.tsx
+++ b/webdemo/frontend/src/__tests__/AuthGuard.test.tsx
@@ -3,7 +3,7 @@ import { render, screen } from '@testing-library/react';
import { MemoryRouter, Routes, Route } from 'react-router-dom';
import { AuthGuard } from '../router/guard';
-// 守卫以 getToken()(localStorage['map_token']) 是否有值判断登录态,mock 之以控制场景。
+// The guard treats a non-empty getToken() (localStorage['map_token']) as logged in; mock it to control the scenario.
const { getTokenMock } = vi.hoisted(() => ({ getTokenMock: vi.fn() }));
vi.mock('@/api/map', () => ({
getToken: getTokenMock,
diff --git a/webdemo/frontend/src/__tests__/modelExperience.test.ts b/webdemo/frontend/src/__tests__/modelExperience.test.ts
index 4c73ec3..5478f0d 100644
--- a/webdemo/frontend/src/__tests__/modelExperience.test.ts
+++ b/webdemo/frontend/src/__tests__/modelExperience.test.ts
@@ -1,5 +1,5 @@
/**
- * modelExperience 分类单测:分流只认管理端勾选的 capabilities,不再按模型名关键词猜测。
+ * modelExperience classification tests: routing trusts only the capabilities checked in admin, and no longer guesses from model-name keywords.
*/
import { describe, it, expect } from 'vitest';
@@ -11,7 +11,7 @@ import {
modelsByExperience,
} from '../utils/modelExperience';
-/** 构造最小可用模型,只关心 id / display_name / capabilities 三个判定输入 */
+/** Build a minimal usable model; only id, display_name, and capabilities matter for the decision. */
function model(id: string, capabilities: Record<string, boolean> = {}, displayName = ''): MapModel {
return {
id,
diff --git a/webdemo/frontend/src/api/example.query.ts b/webdemo/frontend/src/api/example.query.ts
index 615e177..688b910 100644
--- a/webdemo/frontend/src/api/example.query.ts
+++ b/webdemo/frontend/src/api/example.query.ts
@@ -2,21 +2,21 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import type { UseQueryOptions } from '@tanstack/react-query';
/**
- * 服务端状态查询范式(团队复制模板)。
+ * Server-state query pattern (team copy template).
*
- * 用途:演示「服务端可缓存数据」的标准写法——用 TanStack Query,而非 useState+useEffect
- * 手撸(硬规则 #4)。新功能域照此文件复制:定义 queryKey 工厂 + useXxxQuery/useXxxMutation。
+ * Purpose: show the standard way to write server-cacheable data — TanStack Query, rather than useState+useEffect
+ * hand-written (hard rule #4). Copy this file for a new feature area: define a queryKey factory plus useXxxQuery/useXxxMutation.
*
- * 与 ahooks useApi 的分工(重要,避免两套方案混用):
- * - TanStack Query(本文件):服务端「可缓存状态」——列表、详情、Leaderboard 等读多写少、
- * 需要缓存 / 自动失效 / 跨组件共享的数据。
- * - ahooks useApi(hooks/useApi.ts):命令式「一次性动作」——登录、提交表单、上传等
- * 不进缓存、手动触发的副作用。
+ * Division of work with ahooks useApi (important, so the two approaches are not mixed):
+ * - TanStack Query (this file): server cacheable state — lists, details, leaderboards, and other read-heavy data
+ * that needs caching, automatic invalidation, or sharing across components.
+ * - ahooks useApi (hooks/useApi.ts): imperative one-shot actions — login, form submit, upload, and similar
+ * side effects that are not cached and are triggered manually.
*
- * queryKey 约定:用工厂函数集中管理,避免散落的字符串数组拼写漂移,便于精确失效缓存。
+ * queryKey convention: manage keys in factory functions so scattered string arrays do not drift, and so caches can be invalidated precisely.
*/
-/** queryKey 工厂:集中管理某功能域的所有缓存键 */
+/** queryKey factory: centralize every cache key for a feature area */
export const exampleKeys = {
all: ['example'] as const,
lists: () => [...exampleKeys.all, 'list'] as const,
@@ -37,13 +37,13 @@ export interface ExampleItem {
}
/**
- * 查询列表(演示)。
+ * Query a list (demo).
*
- * 真实接入时把 queryFn 换成 `() => request.get<PageResult<ExampleItem>>('/xxx', { params })`,
- * 请求层已做解包,直接返回数据。此处用 mock Promise 占位,保证无后端也能跑通范式。
+ * When wiring a real API, replace queryFn with `() => request.get<PageResult<ExampleItem>>('/xxx', { params })`.
+ * The request layer already unwraps the payload and returns data directly. A mock Promise stands in here so the pattern runs without a backend.
*
- * @param params 分页与筛选参数
- * @param options 透传给 useQuery 的额外配置(如 enabled 控制依赖查询)
+ * @param params Pagination and filter parameters
+ * @param options Extra config passed through to useQuery (for example enabled, to control dependent queries)
*/
export function useExampleListQuery(
params: ExampleListParams,
@@ -52,7 +52,7 @@ export function useExampleListQuery(
return useQuery({
queryKey: exampleKeys.list(params),
queryFn: async (): Promise<ExampleItem[]> => {
- // TODO(接真实接口): return request.get<ExampleItem[]>('/example/list', { params });
+ // TODO(wire the real API): return request.get<ExampleItem[]>('/example/list', { params });
return [{ id: '1', name: '示例条目' }];
},
...options,
@@ -60,21 +60,21 @@ export function useExampleListQuery(
}
/**
- * 提交并使列表缓存失效(演示 mutation + 缓存失效)。
+ * Submit and invalidate the list cache (demo mutation plus cache invalidation).
*
- * 成功后用 invalidateQueries 让相关列表自动重拉,保证「写后读一致」,
- * 这是相对手撸方案最大的收益点:无需手动同步本地状态。
+ * On success, invalidateQueries refetches the related lists so reads after writes stay consistent.
+ * This is the main gain over a hand-written approach: local state does not have to be synced by hand.
*/
export function useCreateExampleMutation() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (input: { name: string }): Promise<ExampleItem> => {
- // TODO(接真实接口): return request.post<ExampleItem>('/example', input);
+ // TODO(wire the real API): return request.post<ExampleItem>('/example', input);
return { id: '2', name: input.name };
},
onSuccess: () => {
- // 让该功能域所有列表查询失效 → 自动重新获取
+ // Invalidate every list query in this feature area so they refetch automatically
queryClient.invalidateQueries({ queryKey: exampleKeys.lists() });
},
});
diff --git a/webdemo/frontend/src/api/map/__tests__/audio.test.ts b/webdemo/frontend/src/api/map/__tests__/audio.test.ts
index 6399ac5..d95685f 100644
--- a/webdemo/frontend/src/api/map/__tests__/audio.test.ts
+++ b/webdemo/frontend/src/api/map/__tests__/audio.test.ts
@@ -2,13 +2,13 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { synthesizeSpeech } from '../audio';
/**
- * synthesizeSpeech 的请求体组装与错误映射测试:
- * 对齐 LIS voxcpm_speech@2——体验中心固定请求 WAV SSE,聚合当前 `audio` 字段,兼容历史
- * `delta` 字段,并仅在 audio.done 完成时返回播放器所需 Blob。契约外字段
- * (cfg/denoise/normalize)仅在用户显式调整时才下发。
+ * Request-body assembly and error-mapping test for synthesizeSpeech:
+ * Aligned with LIS voxcpm_speech@2 — the experience center always requests WAV SSE, aggregates the current `audio` field, and still accepts the historical
+ * `delta` field, and returns the Blob the player needs only when audio.done completes. Extra-contract fields
+ * (cfg/denoise/normalize) are sent only when the user changes them explicitly.
*/
-/** 构造一个成功的 SSE 音频响应。 */
+/** Build a successful SSE audio response. */
function speechResponse(events?: string): Response {
return new Response(
events ??
@@ -27,7 +27,7 @@ function speechResponse(events?: string): Response {
);
}
-/** 构造一个 OpenAI 风格的错误响应 */
+/** Build an OpenAI-style error response */
function errorResponse(status: number, message?: string, code?: string): Response {
return new Response(JSON.stringify({ error: { code, message } }), {
status,
@@ -35,9 +35,9 @@ function errorResponse(status: number, message?: string, code?: string): Respons
});
}
-/** 取出 mock fetch 最近一次调用的请求体与 init */
+/** Read the request body and init from the latest mock fetch call */
function lastCall(fetchMock: ReturnType<typeof vi.fn>) {
- // 仓库 target 是 ES2020,不能用 Array.prototype.at
+ // The repo target is ES2020, so Array.prototype.at cannot be used
const calls = fetchMock.mock.calls;
const [, init] = calls[calls.length - 1] as [string, RequestInit];
return { init, body: JSON.parse(init.body as string) as Record<string, unknown> };
@@ -48,7 +48,7 @@ const base = { model: 'tts-1', secret: 'lis_sk_x', text: '你好' };
let fetchMock: ReturnType<typeof vi.fn>;
beforeEach(() => {
- // 每次调用现造一个 Response:Response body 只能读一次,复用同一实例会在第二次调用时报 unusable
+ // Build a new Response on every call: a Response body can be read only once, and reusing the same instance reports unusable on the second call
fetchMock = vi.fn().mockImplementation(() => Promise.resolve(speechResponse()));
vi.stubGlobal('fetch', fetchMock);
vi.stubGlobal('URL', { ...URL, createObjectURL: () => 'blob:x' });
diff --git a/webdemo/frontend/src/api/map/__tests__/chat-profile-base-url.test.ts b/webdemo/frontend/src/api/map/__tests__/chat-profile-base-url.test.ts
index 66be565..abd670d 100644
--- a/webdemo/frontend/src/api/map/__tests__/chat-profile-base-url.test.ts
+++ b/webdemo/frontend/src/api/map/__tests__/chat-profile-base-url.test.ts
@@ -1,8 +1,8 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
/**
- * 验证不同部署 profile 下 Playground 直连 L2 的 API 域名。
- * GCP 构建曾遗漏 VITE_CHAT_BASE_URL,导致空值回落到华为云 .cn 域名。
+ * Verify the Playground direct-to-L2 API hostname under different deploy profiles.
+ * A GCP build once omitted VITE_CHAT_BASE_URL, so an empty value fell back to the Huawei Cloud .cn hostname.
*/
describe('Playground API 域名 profile 回退', () => {
afterEach(() => {
@@ -44,7 +44,7 @@ describe('Playground API 域名 profile 回退', () => {
});
});
-/** 构造一个立即结束的 SSE 响应。 */
+/** Build an SSE response that ends immediately. */
function sseResponse(chunks: string[]): Response {
const encoder = new TextEncoder();
const stream = new ReadableStream<Uint8Array>({
diff --git a/webdemo/frontend/src/api/map/__tests__/chat.test.ts b/webdemo/frontend/src/api/map/__tests__/chat.test.ts
index cf6a486..1e9e34a 100644
--- a/webdemo/frontend/src/api/map/__tests__/chat.test.ts
+++ b/webdemo/frontend/src/api/map/__tests__/chat.test.ts
@@ -10,11 +10,11 @@ import {
} from '../chat';
/**
- * streamPlaygroundWebSearch 的 SSE frame 分发测试:
- * 用 mock fetch 返回一段 SSE 字节流,验证 tool_status / citations / content / usage / [DONE] 与带内 error 帧的处理。
+ * SSE frame dispatch test for streamPlaygroundWebSearch:
+ * Use mock fetch to return an SSE byte stream, and verify handling of tool_status / citations / content / usage / [DONE] and in-band error frames.
*/
-/** 用给定文本片段构造一个 SSE 流式 Response(片段可跨 frame 边界,用于验证 buffer 拼接)。 */
+/** Build a streaming SSE Response from the given text chunks (chunks may cross frame boundaries, to verify buffer joining). */
function sseResponse(chunks: string[], status = 200): Response {
const encoder = new TextEncoder();
const stream = new ReadableStream<Uint8Array>({
@@ -145,7 +145,7 @@ describe('streamPlaygroundWebSearch', () => {
expect(capturedUrl).toBe('/api/playground/chat/completions');
expect(capturedInit?.method).toBe('POST');
- // 请求体只带 api_key_id,不含明文 secret,且 stream 强制为 true
+ // The request body carries only api_key_id, not the plaintext secret, and stream is forced to true
const body = JSON.parse(capturedInit?.body as string);
expect(body.api_key_id).toBe('key-1');
expect(body.client_request_id).toBe('map_playground_0123456789abcdef0123456789abcdef');
@@ -160,7 +160,7 @@ describe('streamPlaygroundWebSearch', () => {
});
it('跨读取边界的 frame 能被正确拼接', async () => {
- // 把一个 content frame 拆成两段字节,验证 buffer 拼接
+ // Split one content frame into two byte chunks to verify buffer joining
const frames = ['data: {"choices":[{"delta":{"con', 'tent":"Hi"}}]}\n\n', 'data: [DONE]\n\n'];
vi.stubGlobal('fetch', vi.fn(async () => sseResponse(frames)));
@@ -331,7 +331,7 @@ describe('streamChat', () => {
await expect(streamChat({ model: 'm', messages: [] }, 'secret', callbacks)).rejects.toMatchObject(
{ code: 'content_policy_violation', message: '内容不合规,本次回答已撤回' },
);
- // 撤回后不得再触发正常收尾,否则上层会把被撤回的正文当作完成态落库。
+ // After revoke, normal completion must not fire, or the caller would persist the revoked body as a completed state.
expect(cap.done).toBe(false);
});
diff --git a/webdemo/frontend/src/api/map/__tests__/imageParseCompatibility.test.tsx b/webdemo/frontend/src/api/map/__tests__/imageParseCompatibility.test.tsx
index f7145c3..55da5c0 100644
--- a/webdemo/frontend/src/api/map/__tests__/imageParseCompatibility.test.tsx
+++ b/webdemo/frontend/src/api/map/__tests__/imageParseCompatibility.test.tsx
@@ -17,7 +17,7 @@ interface BlockInput {
status?: string;
}
-/** 构造正文与结构化块不一致的服务响应,覆盖真实适配与渲染链路。 */
+/** Build a service response whose body and structured blocks disagree, covering the real adapt and render path. */
function adapt(content: string, inputs: BlockInput[]) {
return adaptImageParseV2({
choices: [{ message: { content } }],
diff --git a/webdemo/frontend/src/api/map/__tests__/imageParseRegenerateBoundaries.test.ts b/webdemo/frontend/src/api/map/__tests__/imageParseRegenerateBoundaries.test.ts
index 2225d1b..9d0d488 100644
--- a/webdemo/frontend/src/api/map/__tests__/imageParseRegenerateBoundaries.test.ts
+++ b/webdemo/frontend/src/api/map/__tests__/imageParseRegenerateBoundaries.test.ts
@@ -67,7 +67,7 @@ interface Boundary {
mutate: (value: ReturnType<typeof fixture>) => void;
}
-// 记录现有拒绝行为用于排查,不代表这些边界都是合理的产品要求。
+// Record the current rejection behavior for debugging; it does not mean every boundary is a reasonable product requirement.
const rejected: Boundary[] = [
{
name: '聚合 Markdown 为空但块正文非空',
@@ -315,7 +315,7 @@ describe('单块重生成红字的诊断边界', () => {
).rejects.toThrow('imageParseInvalidResult');
expect(onApply).not.toHaveBeenCalled();
expect(mocks.request).toHaveBeenCalledOnce();
- // 只修改聚合 Markdown 即可通过,隔离空正文与分数、轮次、身份校验的影响。
+ // Changing only the aggregated Markdown is enough to pass, isolating the effects of an empty body and of score, round, and identity checks.
value.response.choices[0].message.content = '优化后的文字';
await expect(
regenerateImageParseV4(source, target, signal, 'minicpm-ocr-aio', 'plain-secret'),
diff --git a/webdemo/frontend/src/api/map/__tests__/imageParseV2.test.ts b/webdemo/frontend/src/api/map/__tests__/imageParseV2.test.ts
index e987a52..be3a7e0 100644
--- a/webdemo/frontend/src/api/map/__tests__/imageParseV2.test.ts
+++ b/webdemo/frontend/src/api/map/__tests__/imageParseV2.test.ts
@@ -68,7 +68,7 @@ describe('页图解析 v3 契约', () => {
expect(imageParseQuality(result.blocks).suggested.map((item) => item.order)).toEqual([2]);
expect(imageParseQuality(result.blocks).skipped).toHaveLength(1);
expect(imageParseQuality(result.blocks).failed).toHaveLength(1);
- // 图片与空印章各有一个占位符,标题和正文也都能定位。
+ // The image and the empty seal each have one placeholder, and the title and body can both be located.
expect([...imageParseBlockRanges(result.markdown, result.blocks)]).toHaveLength(4);
});
diff --git a/webdemo/frontend/src/api/map/__tests__/request.test.ts b/webdemo/frontend/src/api/map/__tests__/request.test.ts
index 7a63bec..2b84ca5 100644
--- a/webdemo/frontend/src/api/map/__tests__/request.test.ts
+++ b/webdemo/frontend/src/api/map/__tests__/request.test.ts
@@ -1,5 +1,5 @@
/**
- * MAP 请求器 token 工具单测:JWT subject 仅用于客户端数据隔离。
+ * MAP request-client token unit test: the JWT subject is used only for client-side data isolation.
*/
import { afterEach, describe, expect, it, vi } from 'vitest';
@@ -7,7 +7,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { setApplicationLocale } from '@/i18n';
import { clearToken, getTokenSubject, mapRequest, mapUpload, setToken } from '../request';
-/** 构造无需签名的测试 JWT;生产鉴权仍由服务端校验真实签名。 */
+/** Build an unsigned test JWT; production auth still has the server verify the real signature. */
function testToken(payload: Record<string, unknown>): string {
const encoded = btoa(JSON.stringify(payload))
.replace(/\+/g, '-')
diff --git a/webdemo/frontend/src/api/map/audio.ts b/webdemo/frontend/src/api/map/audio.ts
index 834519a..7101512 100644
--- a/webdemo/frontend/src/api/map/audio.ts
+++ b/webdemo/frontend/src/api/map/audio.ts
@@ -1,100 +1,100 @@
/**
- * MAP 体验中心「语音合成(TTS)」API。
+ * MAP experience center speech synthesis (TTS) API.
*
- * 用途:TTS 合成走 L2 的 OpenAI 兼容 `/v1/audio/speech`(对接 LIS VoxCPM2,契约 voxcpm_speech@2),
- * 体验中心请求 WAV;L2 会强制注入 stream=true 并以 SSE 返回。前端逐段聚合
- * `speech.audio.delta` 中现网的 `audio` 字段,兼容历史 `delta` 字段,在 `speech.audio.done` 后生成
- * 可播放的音频 Blob。该终态同时是 LIS 返回权威 token usage 的唯一计量点,因此不再使用无 usage 的
- * unary 路径。
+ * Purpose: TTS synthesis uses L2’s OpenAI-compatible `/v1/audio/speech` (LIS VoxCPM2, contract voxcpm_speech@2).
+ * The experience center requests WAV; L2 forces stream=true and returns SSE. The frontend aggregates
+ * the live `audio` field in `speech.audio.delta`, still accepts the historical `delta` field, and after `speech.audio.done` builds
+ * a playable audio Blob. That terminal event is also the only metering point where LIS returns authoritative token usage, so the usage-less
+ * unary path is no longer used.
*
- * 音色:VoxCPM 无命名音色库、上游对未知 voice 直接 4xx,故 `voice` 恒发 `default`,音色差异一律由
- * `ref_audio` 参考音频承载(零样本克隆)。参考音频出于安全只接受内联 Base64 WAV
- * (`data:audio/wav;base64,...`),不支持任何 URL,解码后上限 5 MiB。
+ * Voice: VoxCPM has no named voice library, and upstream returns 4xx for an unknown voice, so `voice` is always `default`. Voice differences come only from
+ * `ref_audio` reference audio (zero-shot cloning). For safety, reference audio accepts only inline Base64 WAV
+ * (`data:audio/wav;base64,...`), no URL of any kind, with a 5 MiB limit after decoding.
*
- * 声音描述(control,Control Instruction)以 `(描述)` 前缀注入 input,VoxCPM 原生解析:无参考音频
- * 即「声音设计」,有参考音频即在克隆基础上叠加情绪/语速/风格。引导强度(cfg → cfg_value)、参考音频
- * 降噪(denoise)、文本规范化(do_normalize)按需下发——契约未列这三个字段,我方作透传,是否生效
- * 取决于上游 LIS 能力(M0 契约项),故仅在用户显式调整时才带上,默认路径不携带契约外字段。
- * 实时全双工语音对话不走本模块,改由 realtime WS 通道(utils/realtimeConnection.ts)承载。
+ * The voice description (control, Control Instruction) is injected into input as a `(description)` prefix. VoxCPM parses it natively: with no reference audio
+ * it is voice design; with reference audio it layers emotion, pace, and style on the clone. Guidance strength (cfg → cfg_value), reference-audio
+ * denoising (denoise), and text normalization (do_normalize) are sent only when needed. The contract does not list these three fields; we pass them through, and whether they take effect
+ * depends on upstream LIS capability (M0 contract item). They are sent only when the user changes them explicitly; the default path carries no extra-contract fields.
+ * Realtime full-duplex voice conversation does not use this module; the realtime WebSocket channel (utils/realtimeConnection.ts) carries it.
*
- * L2 用 map[string]any 原样透传 body 到 LIS。**不复用** mapRequest(后者解 L3 信封),
- * 以明文 API Key 作 Bearer。
+ * L2 passes the body through to LIS as map[string]any. Do **not** reuse mapRequest (that one unwraps the L3 envelope);
+ * use the plaintext API Key as the Bearer token.
*
- * 安全:secret(明文 lis_sk_xxx)仅由调用方内存传入,本模块不持久化、不打印。
+ * Security: secret (plaintext lis_sk_xxx) is passed in memory by the caller only. This module does not persist or print it.
*/
import { CHAT_API_BASE } from './chat';
import { createPlaygroundClientRequestID } from './chat';
import { getToken } from './request';
-/** 体验中心使用的输出格式(平台强制 SSE,仅支持 WAV) */
+/** Output format used by the experience center (the platform forces SSE and supports only WAV) */
export type TtsFormat = 'wav';
-/** TTS 合成结果:可直接播放/下载的 Object URL(调用方负责 revoke) */
+/** TTS synthesis result: an object URL that can be played or downloaded directly (the caller must revoke it) */
export interface TtsResult {
- /** 由二进制音频 blob 生成的 Object URL */
+ /** Object URL created from the binary audio blob */
objectUrl: string;
- /** 实际输出格式,用于派生下载文件名 */
+ /** Actual output format, used to derive the download filename */
format: TtsFormat;
}
-/** TTS 合成入参(私有音色使用 voice_xxx;临时参考音频使用 refAudio) */
+/** TTS synthesis input (private voices use voice_xxx; temporary reference audio uses refAudio) */
export interface SynthesizeParams {
model: string;
secret: string;
- /** 待合成文本(Target Text) */
+ /** Text to synthesize (Target Text) */
text: string;
- /** 平台私有音色 ID;voice_xxx 由 MAP 校验归属后解析 */
+ /** Platform private-voice ID; MAP checks ownership of voice_xxx and then resolves it */
voice?: string;
/**
- * 声音描述 / 风格控制(Control Instruction,可选)。非空时以 `(描述)` 前缀注入 input,
- * VoxCPM 原生解析:无参考音频即凭描述造声(声音设计),有参考音频即叠加风格。
+ * Voice description / style control (Control Instruction, optional). When non-empty, inject it into input as a `(description)` prefix.
+ * VoxCPM parses it natively: with no reference audio it builds a voice from the description (voice design); with reference audio it layers style on top.
*/
control?: string;
/**
- * 参考音频 data URI(`data:audio/wav;base64,...`),用于语音复刻;缺省则不克隆。
- * 契约只允许内联 Base64 WAV,不接受 http/https/file URL;解码后不得超过 5 MiB。
+ * Reference-audio data URI (`data:audio/wav;base64,...`), used for voice cloning; omit it to skip cloning.
+ * The contract allows only inline Base64 WAV and rejects http/https/file URLs; decoded size must not exceed 5 MiB.
*/
refAudio?: string;
- /** 引导强度 cfg_value(越高越贴合提示/参考音色)。缺省则不下发,沿用上游默认 */
+ /** Guidance strength cfg_value (higher values follow the prompt or reference voice more closely). Omit it to keep the upstream default */
cfg?: number;
/**
- * 参考音频降噪增强(denoise)。仅在为 true 时下发 denoise=true;官方 demo 侧为独立预处理,
- * 我方作为字段透传给上游,是否真正生效取决于 LIS 能力(M0 契约项)。
+ * Reference-audio denoise enhancement (denoise). Send denoise=true only when this is true. The official demo treats it as a separate preprocess;
+ * we pass the field through to upstream, and whether it actually takes effect depends on LIS capability (M0 contract item).
*/
denoise?: boolean;
/**
- * 文本规范化(do_normalize)。仅在为 true 时下发 do_normalize=true;同为透传字段,
- * 生效与否取决于上游(M0 契约项)。
+ * Text normalization (do_normalize). Send do_normalize=true only when this is true. This is also a pass-through field,
+ * and whether it takes effect depends on upstream (M0 contract item).
*/
normalize?: boolean;
- /** 体验中心关联 ID;未传时自动生成 */
+ /** Experience-center correlation ID; generated automatically when omitted */
clientRequestID?: string;
signal?: AbortSignal;
}
/**
- * 文本转语音(TTS)。走 L2 `/v1/audio/speech`;平台强制 SSE,并在浏览器内聚合为完整音频。
- * @returns 可播放/下载的 Object URL 与实际格式(调用方用完须 URL.revokeObjectURL)
- * @throws Error 上游非 2xx 或未返回音频(含可读文案)
+ * Text to speech (TTS). Uses L2 `/v1/audio/speech`; the platform forces SSE, and the browser aggregates it into a complete audio file.
+ * @returns A playable/downloadable object URL and the actual format (the caller must URL.revokeObjectURL when finished)
+ * @throws Error when upstream is not 2xx or returns no audio (includes readable copy)
*/
export async function synthesizeSpeech(params: SynthesizeParams): Promise<TtsResult> {
- // 声音描述以 `(描述)文本` 前缀注入 input(对齐 VoxCPM `f"({control}){text}"` 约定)
+ // Inject the voice description into input as a `(description)text` prefix (aligned with the VoxCPM `f"({control}){text}"` convention)
const control = params.control?.trim();
const input = control ? `(${control})${params.text}` : params.text;
const format: TtsFormat = 'wav';
const body: Record<string, unknown> = {
model: params.model,
input,
- // 私有 voice_xxx 由 MAP 解析;临时上传/预置音色仍使用 default + ref_audio。
+ // Private voice_xxx is resolved by MAP; temporary uploads and preset voices still use default + ref_audio.
voice: params.voice?.trim() || 'default',
response_format: format,
};
- // 语音复刻:带参考音频时透传 ref_audio,上游 VoxCPM 据此克隆音色
+ // Voice cloning: when reference audio is present, pass ref_audio through and upstream VoxCPM clones the voice from it
if (params.refAudio) body.ref_audio = params.refAudio;
- // 引导强度:仅在调用方明确传入时下发(默认路径不带,保护既有可用合成不受上游字段兼容性影响)
+ // Guidance strength: send it only when the caller passes it explicitly (the default path omits it, so existing synthesis is not affected by upstream field compatibility)
if (typeof params.cfg === 'number') body.cfg_value = params.cfg;
- // 降噪 / 文本规范化:仅在开启时下发(官方为 demo 侧预处理,我方作透传字段,生效取决于上游能力)
+ // Denoise / text normalization: send only when enabled (officially a demo-side preprocess; we pass the fields through, and effect depends on upstream capability)
if (params.denoise) body.denoise = true;
if (params.normalize) body.do_normalize = true;
const clientRequestID = params.clientRequestID?.trim() || createPlaygroundClientRequestID();
@@ -112,7 +112,7 @@ export async function synthesizeSpeech(params: SynthesizeParams): Promise<TtsRes
body: JSON.stringify(body),
signal: params.signal,
});
- // 成功契约:2xx + text/event-stream;否则读 JSON 错误正文映射为可读文案。
+ // Success contract: 2xx + text/event-stream; otherwise read the JSON error body and map it to readable copy.
const contentType = res.headers.get('Content-Type') ?? '';
if (!res.ok || !contentType.toLowerCase().startsWith('text/event-stream')) {
const text = await res.text().catch(() => '');
@@ -122,7 +122,7 @@ export async function synthesizeSpeech(params: SynthesizeParams): Promise<TtsRes
return { objectUrl: URL.createObjectURL(blob), format };
}
-/** 从 LIS `speech.audio.delta` 事件聚合 WAV 字节;`audio` 为现网字段,兼容历史 `delta`。 */
+/** Aggregate WAV bytes from LIS `speech.audio.delta` events; `audio` is the live field, and historical `delta` is still accepted. */
async function collectSpeechSSE(response: Response): Promise<Blob> {
if (!response.body) throw new Error('语音服务未返回可读取的流');
@@ -226,7 +226,7 @@ function decodeBase64Audio(value: string): Uint8Array {
}
}
-/** 把上游错误响应映射为用户可读文案(优先按 OpenAI error.code,再回退到状态码)。 */
+/** Map an upstream error response to user-readable copy (prefer OpenAI error.code, then fall back to the status code). */
function mapAudioError(status: number, rawText: string): string {
let detail: string;
let errorCode = '';
@@ -245,9 +245,9 @@ function mapAudioError(status: number, rawText: string): string {
}
if (status === 401) return 'API Key 无效或已失效,请重试';
if (status === 404) return '模型不可用或不支持该能力';
- // 409:目标服务与语音合成 profile 不匹配(契约 §4.6)
+ // 409: the target service does not match the speech-synthesis profile (contract §4.6)
if (status === 409) return '所选模型不是语音合成服务,请在模型管理中确认其能力配置';
- // 413:请求体或参考音频超过限制(契约 §4.5:body 8 MiB / ref_audio 解码后 5 MiB)
+ // 413: the request body or reference audio exceeds the limit (contract §4.5: body 8 MiB / ref_audio 5 MiB after decoding)
if (status === 413) return detail || '参考音频或合成文本过大,请缩短后重试';
if (status === 429) return '请求过于频繁,请稍后再试';
if (status === 502) return detail || '上游返回的语音流不符合预期,请稍后重试';
diff --git a/webdemo/frontend/src/api/map/auth.ts b/webdemo/frontend/src/api/map/auth.ts
index 9370d47..e0d49e3 100644
--- a/webdemo/frontend/src/api/map/auth.ts
+++ b/webdemo/frontend/src/api/map/auth.ts
@@ -2,14 +2,14 @@ import { mapRequest } from './request';
import type { CaptchaChallengeDTO, MapAuthResponse, MapPortalUser } from './types';
/**
- * MAP 认证 API。
+ * MAP auth API.
*
- * 用途:开发者门户的注册 / 登录 / 验证码 / 找回密码等认证动作,全部由 `mapRequest` 直发
- * MAP 后端(裸 JSON)。这些是命令式一次性动作,调用方用 ahooks/useApi 或 mutation 触发,
- * 不进 TanStack Query 缓存。由原 `web/portal/src/api.ts` 的 `client` 认证段迁移而来。
+ * Purpose: developer-portal auth actions such as register, login, verification code, and password recovery are all sent by `mapRequest`
+ * directly to the MAP backend (raw JSON). These are imperative one-shot actions. Callers trigger them with ahooks/useApi or a mutation,
+ * and they do not enter the TanStack Query cache. Migrated from the `client` auth section of the original `web/portal/src/api.ts`.
*/
export const mapAuthApi = {
- /** 探测公共配置(是否启用人机验证、门户飞连登录、第三方登录等),无需鉴权 */
+ /** Probe public config (whether human verification, portal Feilian login, third-party login, and similar are enabled); no auth required */
publicConfig: () =>
mapRequest<{
feilian_enabled: boolean;
@@ -24,38 +24,38 @@ export const mapAuthApi = {
wechat_enabled: boolean;
}>('/auth/config'),
- /** 获取一道滑块人机验证题(答案只存服务端) */
+ /** Fetch one slider human-verification challenge (the answer is stored only on the server) */
getCaptcha: () => mapRequest<CaptchaChallengeDTO>('/auth/captcha', { method: 'POST' }),
- /** 校验滑块落点,通过后服务端写一次性通行凭证(用题目 id 作为凭证 id) */
+ /** Check the slider drop point; on success the server writes a one-time pass (the challenge id is the pass id) */
verifyCaptcha: (payload: { id: string; x: number; y: number }) =>
mapRequest<{ id: string; passed: boolean }>('/auth/captcha/verify', {
method: 'POST',
body: JSON.stringify(payload),
}),
- /** 注册(手机号 + 验证码 + 密码) */
+ /** Register (phone number + verification code + password) */
register: (payload: { phone: string; code: string; name?: string; password: string; referral_code?: string }) =>
mapRequest<MapAuthResponse>('/auth/register', {
method: 'POST',
body: JSON.stringify(payload),
}),
- /** 校验邮箱验证令牌 */
+ /** Verify an email verification token */
verifyEmail: (token: string) =>
mapRequest<{ token: string; user: MapPortalUser }>('/auth/verify-email', {
method: 'POST',
body: JSON.stringify({ token }),
}),
- /** 重发邮箱验证邮件 */
+ /** Resend the email verification message */
resendVerification: (email: string) =>
mapRequest<MapAuthResponse>('/auth/resend-verification', {
method: 'POST',
body: JSON.stringify({ email }),
}),
- /** 账号密码登录(账号支持手机号或邮箱)。captchaId 为人机验证通行凭证 */
+ /** Account and password login (the account may be a phone number or an email). captchaId is the human-verification pass */
login: (payload: { account: string; password: string; captchaId?: string }) =>
mapRequest<MapAuthResponse>('/auth/login', {
method: 'POST',
@@ -66,121 +66,121 @@ export const mapAuthApi = {
}),
}),
- /** 密码登录的新 IP 二次验证通过后签发登录态 */
+ /** Issue a login session after the new-IP second verification for password login succeeds */
verifyPasswordLogin: (payload: { challenge_token: string; code: string }) =>
mapRequest<MapAuthResponse>('/auth/password-login/verify', {
method: 'POST',
body: JSON.stringify(payload),
}),
- /** 重发密码登录的新 IP 二次验证码 */
+ /** Resend the new-IP second verification code for password login */
resendPasswordLogin: (payload: { challenge_token: string }) =>
mapRequest<MapAuthResponse>('/auth/password-login/resend', {
method: 'POST',
body: JSON.stringify(payload),
}),
- /** 发送短信验证码。captchaId 为人机验证通行凭证 */
+ /** Send an SMS verification code. captchaId is the human-verification pass */
sendSMSCode: (phone: string, captchaId?: string) =>
mapRequest<MapAuthResponse>('/auth/sms-code', {
method: 'POST',
body: JSON.stringify({ phone, captcha_id: captchaId }),
}),
- /** 发送邮箱验证码(注册/登录/找回密码共用,验证码只通过邮件发送)。captchaId 为人机验证通行凭证 */
+ /** Send an email verification code (shared by register/login/password recovery; the code is sent only by email). captchaId is the human-verification pass */
sendEmailCode: (email: string, captchaId?: string) =>
mapRequest<MapAuthResponse>('/auth/email-code', {
method: 'POST',
body: JSON.stringify({ email, captcha_id: captchaId }),
}),
- /** 邮箱 + 验证码登录(未注册邮箱将自动注册) */
+ /** Email + verification code login (an unregistered email is registered automatically) */
emailLogin: (payload: { email: string; code: string; name?: string; referral_code?: string }) =>
mapRequest<MapAuthResponse>('/auth/email-login', {
method: 'POST',
body: JSON.stringify(payload),
}),
- /** 邮箱 + 验证码 + 密码注册 */
+ /** Register with email + verification code + password */
emailRegister: (payload: { email: string; code: string; name?: string; password: string; referral_code?: string }) =>
mapRequest<MapAuthResponse>('/auth/email-register', {
method: 'POST',
body: JSON.stringify(payload),
}),
- /** 手机号 + 验证码登录(未注册手机号将自动注册) */
+ /** Phone + verification code login (an unregistered phone number is registered automatically) */
phoneLogin: (payload: { phone: string; code: string; name?: string; referral_code?: string }) =>
mapRequest<MapAuthResponse>('/auth/phone-login', {
method: 'POST',
body: JSON.stringify(payload),
}),
- /** 发起找回密码,返回重置令牌。captchaId 为人机验证通行凭证 */
+ /** Start password recovery and return a reset token. captchaId is the human-verification pass */
forgotPassword: (email: string, captchaId?: string) =>
mapRequest<MapAuthResponse>('/auth/forgot-password', {
method: 'POST',
body: JSON.stringify({ email, captcha_id: captchaId }),
}),
- /** 用重置令牌设置新密码(邮箱找回) */
+ /** Set a new password with the reset token (email recovery) */
resetPassword: (payload: { token: string; password: string }) =>
mapRequest<{ status: string }>('/auth/reset-password', {
method: 'POST',
body: JSON.stringify(payload),
}),
- /** 手机号 + 短信验证码重置密码(短信找回,复用 /auth/sms-code 下发的验证码) */
+ /** Reset the password with phone + SMS verification code (SMS recovery, reusing the code issued by /auth/sms-code) */
resetPasswordBySms: (payload: { phone: string; code: string; password: string }) =>
mapRequest<{ status: string }>('/auth/reset-password', {
method: 'POST',
body: JSON.stringify(payload),
}),
- /** 邮箱 + 验证码重置密码(邮箱找回,复用 /auth/email-code 下发的验证码,与手机找回对称) */
+ /** Reset the password with email + verification code (email recovery, reusing the code issued by /auth/email-code, symmetric with phone recovery) */
resetPasswordByEmailCode: (payload: { email: string; code: string; password: string }) =>
mapRequest<{ status: string }>('/auth/reset-password', {
method: 'POST',
body: JSON.stringify(payload),
}),
- /** 退出登录 */
+ /** Log out */
logout: () => mapRequest<{ status: string }>('/auth/logout', { method: 'POST' }),
- /** 获取当前登录用户信息 */
+ /** Fetch the currently logged-in user */
me: () => mapRequest<MapPortalUser>('/me'),
- /** 注销(软删除)当前账号 */
+ /** Delete (soft-delete) the current account */
deleteAccount: () => mapRequest<{ status: string }>('/me', { method: 'DELETE' }),
- /** 登录态设置或修改密码;提供 current_password 时校验旧密码 */
+ /** Set or change the password while logged in; when current_password is provided, verify the old password */
updatePassword: (payload: { current_password?: string; password: string }) =>
mapRequest<{ status: string; token?: string }>('/me/password', {
method: 'POST',
body: JSON.stringify(payload),
}),
- /** 登录态修改昵称(name)与/或用户名(username) */
+ /** Change the nickname (name) and/or username (username) while logged in */
updateProfile: (payload: { name?: string; username?: string }) =>
mapRequest<MapPortalUser>('/me', {
method: 'PATCH',
body: JSON.stringify(payload),
}),
- /** 登录态绑定邮箱(需先经 sendEmailCode 拿验证码) */
+ /** Bind an email while logged in (get a verification code from sendEmailCode first) */
bindEmail: (payload: { email: string; code: string }) =>
mapRequest<MapPortalUser>('/me/email', {
method: 'POST',
body: JSON.stringify(payload),
}),
- /** 登录态发送手机号绑定验证码;captchaId 为人机验证通行凭证 */
+ /** Send a phone-binding verification code while logged in; captchaId is the human-verification pass */
sendPhoneBindCode: (phone: string, captchaId?: string) =>
mapRequest<MapAuthResponse>('/me/phone/code', {
method: 'POST',
body: JSON.stringify({ phone, captcha_id: captchaId }),
}),
- /** 登录态绑定手机号(需先经 sendPhoneBindCode 获取专用验证码) */
+ /** Bind a phone number while logged in (get the dedicated code from sendPhoneBindCode first) */
bindPhone: (payload: { phone: string; code: string }) =>
mapRequest<MapPortalUser>('/me/phone', {
method: 'POST',
@@ -189,30 +189,30 @@ export const mapAuthApi = {
};
/**
- * 飞连(Feilian)SSO 门户登录入口(仅测试环境启用,由后端 feilian_enabled 开关驱动)。
+ * Feilian SSO portal login entry (enabled only in the test environment, driven by the backend feilian_enabled switch).
*
- * 整页跳转到后端 `/auth/feilian/login?target=portal`,后端 302 跳飞连授权页;授权后飞连
- * 回调后端 `/admin/auth/callback`(与管理台复用同一 redirect_uri,靠 state 里的 target 区分),
- * 后端按邮箱 upsert 门户用户并签发用户 JWT,以 URL fragment(`#token=...`)回跳门户登录页。
+ * Navigate the whole page to backend `/auth/feilian/login?target=portal`. The backend 302s to the Feilian authorization page; after authorization Feilian
+ * calls back to backend `/admin/auth/callback` (the same redirect_uri as the admin console, distinguished by target in state),
+ * the backend upserts the portal user by email and issues a user JWT, then redirects back to the portal login page with a URL fragment (`#token=...`).
*
- * 路径前缀与 mapRequest 对齐:dev 走 `/api`(Vite 代理去前缀转发到后端),生产同源直连
- * 网关 `/auth` 路由。飞连是整页导航,不走 fetch,故此处单独拼前缀而非用 mapRequest。
+ * The path prefix matches mapRequest: dev uses `/api` (the Vite proxy strips the prefix and forwards to the backend), and production calls the same origin directly
+ * at the gateway `/auth` route. Feilian is a full-page navigation and does not use fetch, so the prefix is assembled here instead of using mapRequest.
*/
export function feilianLogin(): void {
const base = import.meta.env.DEV ? '/api' : '';
window.location.assign(`${base}/auth/feilian/login?target=portal`);
}
-/** 第三方登录提供方标识:与后端 /auth/oauth/{provider}/login 的 path 参数一致。 */
+/** Third-party login provider id: matches the path parameter of backend /auth/oauth/{provider}/login. */
export type OAuthProvider = 'google' | 'github' | 'wechat';
/**
- * 第三方(社会化)登录入口:Google / GitHub / 微信。
+ * Third-party (social) login entry: Google / GitHub / WeChat.
*
- * 整页跳转到后端 `/auth/oauth/{provider}/login?target=portal`,后端 302 跳对应授权页;
- * 授权后回调后端 `/auth/oauth/{provider}/callback`,后端换 token、拉 userinfo、幂等建号/绑定,
- * 并以 URL fragment(`#token=...`)把用户 JWT 回跳门户登录页(与飞连回跳同构,前端复用同一处理)。
- * 路径前缀与 feilianLogin 对齐:dev 走 `/api`(Vite 代理去前缀),生产同源直连网关 `/auth`。
+ * Navigate the whole page to backend `/auth/oauth/{provider}/login?target=portal`. The backend 302s to the matching authorization page;
+ * after authorization it calls back to backend `/auth/oauth/{provider}/callback`, which exchanges the token, loads userinfo, and idempotently creates or binds the account,
+ * then redirects the user JWT back to the portal login page in a URL fragment (`#token=...`) (same shape as the Feilian return, and the frontend reuses the same handling).
+ * The path prefix matches feilianLogin: dev uses `/api` (the Vite proxy strips the prefix), and production calls the gateway `/auth` on the same origin.
*/
export function oauthLogin(provider: OAuthProvider): void {
const base = import.meta.env.DEV ? '/api' : '';
diff --git a/webdemo/frontend/src/api/map/chat.ts b/webdemo/frontend/src/api/map/chat.ts
index 95216a8..fd9997c 100644
--- a/webdemo/frontend/src/api/map/chat.ts
+++ b/webdemo/frontend/src/api/map/chat.ts
@@ -1,10 +1,10 @@
/**
- * MAP 体验中心(Playground)的流式对话 API。
+ * Streaming chat API for the MAP experience center (Playground).
*
- * 用途:直连 L2 的 OpenAI 兼容 `/v1/chat/completions`(SSE 流式),以用户明文 API Key 作
- * `Bearer` 鉴权。**不复用** `mapRequest`:后者解 L3 统一信封并抛 BizError,不适合 SSE 原始流。
+ * Purpose: call L2’s OpenAI-compatible `/v1/chat/completions` directly (SSE streaming), using the user’s plaintext API Key as
+ * `Bearer` auth. Do **not** reuse `mapRequest`: it unwraps the L3 envelope and throws BizError, which does not fit a raw SSE stream.
*
- * 安全:secret(明文 lis_sk_xxx)仅由调用方内存传入,本模块不持久化、不打印。
+ * Security: secret (plaintext lis_sk_xxx) is passed in memory by the caller only. This module does not persist or print it.
*/
import { getToken } from './request';
@@ -20,10 +20,10 @@ import {
} from '@/pages/playground/utils/sse';
/**
- * chat 端点基址:部署时优先使用 `VITE_CHAT_BASE_URL` 按环境注入。
- * 该值缺失时按 `VITE_AUTH_PROFILE` 回退:GCP 使用 `https://api.modelbest.ai`,
- * legacy 使用 `https://api.modelbest.cn`,避免两套云环境域名交叉。
- * 注意 `/api` 是 L3 控制面前缀(无 `/v1/chat/completions`,直连会 405),对话必须走 L2。
+ * Chat endpoint base URL: at deploy time prefer `VITE_CHAT_BASE_URL` injected per environment.
+ * When that value is missing, fall back by `VITE_AUTH_PROFILE`: GCP uses `https://api.modelbest.ai`,
+ * and legacy uses `https://api.modelbest.cn`, so the two cloud hostnames do not cross.
+ * Note that `/api` is the L3 control-plane prefix (it has no `/v1/chat/completions`, and a direct call returns 405). Chat must go through L2.
*/
const configuredChatAPIBase = import.meta.env.VITE_CHAT_BASE_URL?.trim();
export const CHAT_API_BASE =
@@ -32,7 +32,7 @@ export const CHAT_API_BASE =
? 'https://api.modelbest.ai'
: 'https://api.modelbest.cn');
-/** token 用量 */
+/** Token usage */
export interface TokenUsage {
prompt_tokens: number;
completion_tokens: number;
@@ -40,10 +40,10 @@ export interface TokenUsage {
}
/**
- * OpenAI 兼容的多模态 content 分段。媒体类优先使用对象存储 URL,兼容保留 data URL/file_data。
- * - image_url / video_url:URL 形态(Qwen-VL 等 OpenAI 兼容视觉模型用 video_url 承载视频)
- * - input_audio:OpenAI Chat Completions 音频入参(data 为**去前缀**的裸 base64 + format)
- * - file:OpenAI 文件入参(file_data 为完整 data URL,filename 供上游识别类型)
+ * OpenAI-compatible multimodal content parts. Media prefers object-storage URLs, and data URL/file_data remain for compatibility.
+ * - image_url / video_url: URL form (OpenAI-compatible vision models such as Qwen-VL carry video in video_url)
+ * - input_audio: OpenAI Chat Completions audio input (data is raw base64 **without** the prefix, plus format)
+ * - file: OpenAI file input (file_data is a full data URL; filename is for upstream type recognition)
*/
export type ChatContentPart =
| { type: 'text'; text: string }
@@ -52,15 +52,15 @@ export type ChatContentPart =
| { type: 'input_audio'; input_audio: { data: string; format: string } }
| { type: 'file'; file: { filename: string; file_data?: string; file_url?: string } };
-/** 发往后端的一条对话消息;content 为字符串或多模态分段数组 */
+/** One chat message sent to the backend; content is a string or an array of multimodal parts */
export interface ChatRequestMessage {
role: 'system' | 'user' | 'assistant';
content: string | ChatContentPart[];
}
/**
- * 对话补全参数。除 model/messages 外均为可选,后端原样透传到 LIS。
- * 用索引签名预留 tools / web_search / response_format 等未显式声明字段。
+ * Chat completion parameters. Everything except model/messages is optional, and the backend passes them through to LIS as-is.
+ * An index signature reserves undeclared fields such as tools / web_search / response_format.
*/
export interface ChatCompletionParams {
model: string;
@@ -70,56 +70,56 @@ export interface ChatCompletionParams {
max_tokens?: number;
reasoning_effort?: 'low' | 'medium' | 'high';
thinking?: { type: 'enabled' | 'disabled' } | Record<string, unknown>;
- /** MiniCPM/LIS 思考开关:chat_template_kwargs.enable_thinking(默认 true) */
+ /** MiniCPM/LIS reasoning switch: chat_template_kwargs.enable_thinking (default true) */
chat_template_kwargs?: { enable_thinking?: boolean } & Record<string, unknown>;
- /** MiniCPM-V-4.7 图片压缩参数;仅用户显式选择时发送。 */
+ /** MiniCPM-V-4.7 image compression parameters; sent only when the user selects them explicitly. */
mm_processor_kwargs?: { downsample_mode?: '4x' | '16x' } & Record<string, unknown>;
- /** 保留兼容字段类型;Playground hosted web search 不再由前端下发该字段 */
+ /** Kept as a compatibility field type; Playground hosted web search no longer sends this field from the frontend */
web_search_options?: Record<string, unknown>;
[key: string]: unknown;
}
-/** 联网搜索引用来源(归一化后的 url_citation) */
+/** Web-search citation source (normalized url_citation) */
export interface Citation {
- /** 后端分配的全局来源编号(1 起);见 pages/playground/types.ts 的同名字段。 */
+ /** Global source number assigned by the backend (starting at 1); see the field of the same name in pages/playground/types.ts. */
ref?: number;
url: string;
title?: string;
snippet?: string;
}
-/** Playground 请求携带的浏览器运行时上下文提示。 */
+/** Browser runtime context hints carried on a Playground request. */
export interface PlaygroundRuntimeContext {
timezone?: string;
locale: 'zh-CN' | 'en-US';
utc_offset_minutes: number;
- /** 用户手动设置的当前位置(如"北京市"),用于 datetime 工具回答地点相关问题。 */
+ /** Current location set manually by the user (for example "Beijing"), used by the datetime tool to answer location questions. */
location?: string;
}
-/** 流式回调集合 */
+/** Streaming callback set */
export interface StreamCallbacks {
- /** 正文增量(choices[].delta.content) */
+ /** Body delta (choices[].delta.content) */
onContent: (delta: string) => void;
- /** 思考增量(reasoning_content / reasoning / thinking) */
+ /** Reasoning delta (reasoning_content / reasoning / thinking) */
onReasoning?: (delta: string) => void;
- /** 联网搜索引用来源(url_citation annotations,流式下可能多次到达,取并集) */
+ /** Web-search citation sources (url_citation annotations; they may arrive more than once while streaming, so take the union) */
onCitations?: (citations: Citation[]) => void;
- /** hosted web search 工具状态事件 */
+ /** Hosted web search tool status event */
onToolStatus?: (status: ToolStatusEvent) => void;
- /** 当前回答对应的平台 L2 请求 ID */
+ /** Platform L2 request ID for the current answer */
onRequestId?: (requestId: string) => void;
- /** 当前回答由输入安审服务代答,当前问答轮不得再进入后续模型上下文。 */
+ /** The current answer was produced by the input content-safety service, and this turn must not enter later model context. */
onModerationAnswer?: () => void;
- /** 尾块 usage(后端已强制注入 include_usage) */
+ /** Trailing usage chunk (the backend already forces include_usage) */
onUsage?: (usage: TokenUsage) => void;
- /** 上游结束原因,供文档识别区分完整结果与输出限长。 */
+ /** Upstream finish reason, so document recognition can tell a complete result from an output-length limit. */
onFinishReason?: (reason: string) => void;
- /** 正常收尾(收到 [DONE]) */
+ /** Normal completion (received [DONE]) */
onDone?: () => void;
}
-/** hosted web search 工具状态事件 */
+/** Hosted web search tool status event */
export interface ToolStatusEvent {
event_id?: string;
step?: number;
@@ -133,10 +133,10 @@ export interface ToolStatusEvent {
}
/**
- * 生成体验中心对话的客户端关联 ID。
+ * Generate the client correlation ID for an experience-center conversation.
*
- * 用途:直连调用经 `X-Request-Id` 传入 L2,联网调用传给 L3 记录最终调用映射;
- * 两者都只作为 `client_request_id`。平台仍自行生成并返回权威的 `req_xxx`。
+ * Purpose: direct calls pass it to L2 via `X-Request-Id`, and web calls pass it to L3 to record the final call mapping;
+ * both are only a `client_request_id`. The platform still generates and returns the authoritative `req_xxx` itself.
*/
export function createPlaygroundClientRequestID(): string {
const bytes = new Uint8Array(16);
@@ -144,7 +144,7 @@ export function createPlaygroundClientRequestID(): string {
return `map_playground_${Array.from(bytes, (value) => value.toString(16).padStart(2, '0')).join('')}`;
}
-/** 携带 HTTP 状态码的对话错误,便于上层区分 401/404/429 */
+/** Chat error that carries an HTTP status code, so the caller can distinguish 401/404/429 */
export class ChatError extends Error {
status: number;
code?: string;
@@ -156,14 +156,14 @@ export class ChatError extends Error {
}
}
-/** 读取当前登录 token(用于走 /api 同源代理时附带门户登录态,不影响 L2 的 Bearer 鉴权语义) */
+/** Read the current login token (attach portal auth when going through the /api same-origin proxy, without changing L2 Bearer auth) */
function buildUrl(): string {
return `${CHAT_API_BASE}/v1/chat/completions`;
}
/**
- * 把正文增量经 `<think>` 拆分后分发:think 段落改路由到思考通道,正文保持干净。
- * 见 sse.ts:部分模型(联网路径带 tools 时上游不再分离 reasoning)把思考内联在 content。
+ * Split a body delta on `<think>` and dispatch it: route think segments to the reasoning channel and keep the body clean.
+ * See sse.ts: some models (on the web path with tools, upstream no longer separates reasoning) inline reasoning in content.
*/
function emitContentDelta(
state: ThinkSplitState,
@@ -175,7 +175,7 @@ function emitContentDelta(
if (split.reasoning) callbacks.onReasoning?.(split.reasoning);
}
-/** 流结束时清空 `<think>` 拆分残留,兜底分发,避免半标签或未闭合 think 吞字。 */
+/** When the stream ends, flush leftover `<think>` split state and dispatch it, so a partial tag or an unclosed think does not swallow text. */
function drainThink(state: ThinkSplitState, callbacks: StreamCallbacks): void {
const rest = flushThinkDelta(state);
if (rest.content) callbacks.onContent(rest.content);
@@ -183,14 +183,14 @@ function drainThink(state: ThinkSplitState, callbacks: StreamCallbacks): void {
}
/**
- * 发起一次流式对话,逐块回调。
+ * Start one streaming chat and callback chunk by chunk.
*
- * @param params 对话参数(本函数内部强制置 stream=true)
- * @param secret 明文 API Key(Bearer),仅内存传入,不落盘
- * @param callbacks 流式回调
- * @param signal AbortController.signal,用于「停止生成」
- * @throws ChatError 当上游返回非 2xx(含 401 key 失效 / 404 链路问题 / 429 限流)
- * @throws DOMException(AbortError) 当调用方主动中断——上层应视为正常停止,不报错
+ * @param params Chat parameters (this function forces stream=true)
+ * @param secret Plaintext API Key (Bearer), passed in memory only and not written to disk
+ * @param callbacks Streaming callbacks
+ * @param signal AbortController.signal, used for Stop generating
+ * @throws ChatError when upstream returns non-2xx (including 401 for an invalid key, 404 for a path problem, and 429 for rate limiting)
+ * @throws DOMException(AbortError) when the caller aborts — the caller should treat that as a normal stop, not an error
*/
export async function streamChat(
params: ChatCompletionParams,
@@ -256,8 +256,8 @@ export async function streamChat(
continue;
}
if (event.type === 'moderation') {
- // 撤回帧必须立即中断本轮:抛出后上层会取消打字机队列并清空已渲染内容,
- // 保证 revoke 之后不再有任何模型正文上屏。
+ // A revoke frame must interrupt this turn immediately: after the throw, the caller cancels the typewriter queue and clears rendered content,
+ // so no model body appears on screen after revoke.
if (isModerationRevokeEvent(event.data)) {
throw new ChatError(0, moderationRevokeMessage(event.data), 'content_policy_violation');
}
@@ -285,12 +285,12 @@ export async function streamChat(
}
throw new ChatError(0, '对话流意外中断,请重试');
} finally {
- // 中断/异常时取消底层读取,避免连接泄漏
+ // On abort or error, cancel the underlying read to avoid a connection leak
void reader.cancel().catch(() => undefined);
}
}
-/** 透传上游真实结束原因,不改变既有聊天完成语义。 */
+/** Pass through the real upstream finish reason without changing existing chat-completion semantics. */
function emitFinishReason(data: unknown, callbacks: StreamCallbacks): void {
if (!data || typeof data !== 'object' || !('choices' in data)) return;
if (!Array.isArray(data.choices)) return;
@@ -302,10 +302,10 @@ function emitFinishReason(data: unknown, callbacks: StreamCallbacks): void {
}
/**
- * 发起一次 Playground hosted web search 流式对话。
- * @param params 对话参数(本函数内部强制置 stream=true)
- * @param apiKeyId 服务端可校验的 API Key ID;为空时后端按默认规则选择
- * @param callbacks 流式回调
+ * Start one Playground hosted web search streaming chat.
+ * @param params Chat parameters (this function forces stream=true)
+ * @param apiKeyId API Key ID the server can verify; when empty, the backend chooses by its default rule
+ * @param callbacks Streaming callbacks
* @param signal AbortController.signal
*/
export async function streamPlaygroundWebSearch(
@@ -324,7 +324,7 @@ export async function streamPlaygroundWebSearch(
Authorization: token ? `Bearer ${token}` : '',
'Content-Type': 'application/json',
Accept: 'text/event-stream',
- // 与直连链路一致:运行时上下文走受限请求头,不暴露在托管请求体里。
+ // Same as the direct path: runtime context goes in restricted request headers and is not exposed in the hosted request body.
...playgroundRuntimeContextHeaders(runtimeContext, { includeLocation: true }),
},
body: JSON.stringify({
@@ -366,8 +366,8 @@ export async function streamPlaygroundWebSearch(
callbacks.onDone?.();
return;
}
- // 带内错误帧:BFF 在 SSE 已开始后无法改 HTTP 状态码,用 event: error 承载。
- // 抛出交由上层 catch 落错误态,避免被当作普通状态在 [DONE] 后被清除。
+ // In-band error frame: after SSE has started the BFF cannot change the HTTP status, so it carries the error in event: error.
+ // Throw so the caller’s catch records the error state, instead of treating it as ordinary status that is cleared after [DONE].
if (event.type === 'error') {
const failure = hostedErrorDetails(event.data);
throw new ChatError(0, failure.message, failure.code);
@@ -382,8 +382,8 @@ export async function streamPlaygroundWebSearch(
continue;
}
if (event.type === 'moderation') {
- // 撤回帧必须立即中断本轮:抛出后上层会取消打字机队列并清空已渲染内容,
- // 保证 revoke 之后不再有任何模型正文上屏。
+ // A revoke frame must interrupt this turn immediately: after the throw, the caller cancels the typewriter queue and clears rendered content,
+ // so no model body appears on screen after revoke.
if (isModerationRevokeEvent(event.data)) {
throw new ChatError(0, moderationRevokeMessage(event.data), 'content_policy_violation');
}
@@ -408,7 +408,7 @@ export async function streamPlaygroundWebSearch(
}
}
-/** 非流式对话结果:完整正文 + 可选思考 + 可选 usage + 可选引用来源 */
+/** Non-streaming chat result: full body plus optional reasoning, optional usage, and optional citation sources */
export interface ChatCompletionResult {
content: string;
reasoning: string;
@@ -419,13 +419,13 @@ export interface ChatCompletionResult {
}
/**
- * 发起一次非流式对话,一次性返回完整结果(stream=false)。
+ * Start one non-streaming chat and return the full result at once (stream=false).
*
- * @param params 对话参数(本函数内部强制置 stream=false)
- * @param secret 明文 API Key(Bearer),仅内存传入,不落盘
- * @param signal AbortController.signal,用于「停止生成」
- * @throws ChatError 当上游返回非 2xx
- * @throws DOMException(AbortError) 当调用方主动中断
+ * @param params Chat parameters (this function forces stream=false)
+ * @param secret Plaintext API Key (Bearer), passed in memory only and not written to disk
+ * @param signal AbortController.signal, used for Stop generating
+ * @throws ChatError when upstream returns non-2xx
+ * @throws DOMException(AbortError) when the caller aborts
*/
export async function requestChat(
params: ChatCompletionParams,
@@ -462,7 +462,7 @@ export async function requestChat(
return result;
}
-/** 将 Playground 运行时上下文转换为直连 L2 的受限请求头。 */
+/** Convert Playground runtime context into restricted request headers for a direct L2 call. */
function playgroundRuntimeContextHeaders(
runtimeContext?: PlaygroundRuntimeContext,
options?: { includeLocation?: boolean },
@@ -478,14 +478,14 @@ function playgroundRuntimeContextHeaders(
};
}
-/** 从 L2 响应头读取平台元数据。 */
+/** Read platform metadata from L2 response headers. */
function emitResponseMetadata(res: Response, callbacks: StreamCallbacks): void {
const requestID = platformRequestID(res.headers.get('X-Request-Id'));
if (requestID) callbacks.onRequestId?.(requestID);
if (isModerationAnswerResponse(res)) callbacks.onModerationAnswer?.();
}
-/** 从 hosted web search 的专用 SSE 事件读取最终模型调用 request_id。 */
+/** Read the final model-call request_id from the hosted web search SSE event. */
function extractRequestID(data: unknown): string {
if (!data || typeof data !== 'object') return '';
const value = (data as Record<string, unknown>).request_id;
@@ -503,10 +503,10 @@ function isModerationAnswerEvent(data: unknown): boolean {
}
/**
- * 判定输出安审撤回帧。
+ * Detect an output content-safety-review revoke frame.
*
- * 背景:L2 对流式输出按分片审核,分片过审即下发以保证流式观感;若全文终审判违规,
- * 会补发 `event: moderation` + `action: revoke`,要求客户端撤回本轮已渲染的全部内容。
+ * Background: L2 reviews streaming output in chunks and forwards a chunk once it passes, to keep streaming responsive; if the final full-text review finds a violation,
+ * it sends `event: moderation` + `action: revoke`, telling the client to revoke everything already rendered for this turn.
*/
function isModerationRevokeEvent(data: unknown): boolean {
return Boolean(
@@ -514,20 +514,20 @@ function isModerationRevokeEvent(data: unknown): boolean {
);
}
-/** 撤回帧的用户可见文案,缺省回退通用提示。 */
+/** User-visible copy for a revoke frame; fall back to the generic notice when absent. */
function moderationRevokeMessage(data: unknown): string {
const fallback = '内容不合规,本次回答已撤回';
if (!data || typeof data !== 'object') return fallback;
return pickString(data as Record<string, unknown>, 'message') || fallback;
}
-/** 仅接受 MAP 平台生成的 request_id 格式,避免把未知事件或客户端标识写入会话。 */
+/** Accept only the request_id format generated by the MAP platform, so an unknown event or a client id is not written into the conversation. */
function platformRequestID(value: string | null): string {
const requestID = value?.trim() ?? '';
return requestID.startsWith('req_') ? requestID : '';
}
-/** 从未知值安全取字符串字段 */
+/** Safely read a string field from an unknown value */
function pickString(obj: Record<string, unknown>, key: string): string {
const v = obj[key];
return typeof v === 'string' ? v : '';
@@ -591,14 +591,14 @@ function normalizeToolStatus(data: unknown): ToolStatusEvent {
};
}
-/** 判断响应是否为 SSE;L3 统一信封即使 HTTP 200 也不能进入流式解析。 */
+/** Decide whether the response is SSE; an L3 envelope must not enter streaming parse even on HTTP 200. */
function isEventStreamResponse(res: Response): boolean {
return res.headers.get('Content-Type')?.toLowerCase().includes('text/event-stream') ?? false;
}
/**
- * 从非流式 OpenAI 兼容响应抽取正文/思考/usage。
- * 正文取 `choices[0].message.content`;思考按 reasoning_content → reasoning → thinking 兜底。
+ * Extract body, reasoning, and usage from a non-streaming OpenAI-compatible response.
+ * The body is `choices[0].message.content`; reasoning falls back through reasoning_content → reasoning → thinking.
*/
function extractCompletion(data: unknown): ChatCompletionResult {
const out: ChatCompletionResult = { content: '', reasoning: '' };
@@ -619,7 +619,7 @@ function extractCompletion(data: unknown): ChatCompletionResult {
pickString(m, 'reasoning_content') ||
pickString(m, 'reasoning') ||
pickString(m, 'thinking');
- // 正文可能内联 <think>…</think>(见 sse.ts):一次性拆出,思考并入 reasoning 通道。
+ // The body may inline <think>…</think> (see sse.ts): split it once and merge reasoning into the reasoning channel.
const think = createThinkSplitState();
const split = splitThinkDelta(think, pickString(m, 'content'));
const tail = flushThinkDelta(think);
@@ -646,7 +646,7 @@ function extractCompletion(data: unknown): ChatCompletionResult {
return out;
}
-/** 把上游状态码与原始文本映射为可读中文错误 */
+/** Map an upstream status code and raw text to a readable Chinese error */
function mapErrorMessage(status: number, raw: string): string {
const detail = extractUpstreamMessage(raw);
if (status === 401) return detail || '密钥无效或已过期,请重新选择 API Key';
@@ -658,7 +658,7 @@ function mapErrorMessage(status: number, raw: string): string {
return detail || `请求失败(HTTP ${status})`;
}
-/** 尝试从 OpenAI 风格错误体 `{error:{message}}` 取出可读信息 */
+/** Try to read a readable message from an OpenAI-style error body `{error:{message}}` */
function extractUpstreamMessage(raw: string): string {
if (!raw) return '';
try {
@@ -670,7 +670,7 @@ function extractUpstreamMessage(raw: string): string {
}
}
-/** 提取 OpenAI 风格错误码,用于将内容安全拦截渲染为普通助手回复。 */
+/** Extract an OpenAI-style error code so a content-safety block can be rendered as a normal assistant reply. */
function extractUpstreamCode(raw: string): string | undefined {
if (!raw) return undefined;
try {
@@ -681,7 +681,7 @@ function extractUpstreamCode(raw: string): string | undefined {
}
}
-/** Playground 可用工具描述。 */
+/** Description of a tool available in Playground. */
export interface PlaygroundTool {
name: string;
description: string;
@@ -689,7 +689,7 @@ export interface PlaygroundTool {
kind: 'search' | 'reader' | 'generic';
}
-/** 获取 Playground 可用工具列表(含内置 + MCP generic 工具)。 */
+/** Fetch the Playground tool list (built-in tools plus MCP generic tools). */
export async function getPlaygroundTools(): Promise<PlaygroundTool[]> {
const token = getToken();
const res = await fetch('/api/playground/tools', {
diff --git a/webdemo/frontend/src/api/map/demoStore.ts b/webdemo/frontend/src/api/map/demoStore.ts
index 9af71c6..06e80e7 100644
--- a/webdemo/frontend/src/api/map/demoStore.ts
+++ b/webdemo/frontend/src/api/map/demoStore.ts
@@ -1,14 +1,14 @@
-/** 免登录演示的本地文件元数据;只在当前页面会话内保存,不上传远端。 */
+/** Local file metadata for the login-free demo; kept only in the current page session and not uploaded remotely. */
const uploads = new Map<string, File>();
-/** 公网 http 页面不是安全上下文,crypto.randomUUID 会抛错,改用可在该页面使用的编号。 */
+/** A public http page is not a secure context, so crypto.randomUUID throws. Use an id that works on that page instead. */
function demoFileId(): string {
const cryptoApi = globalThis.crypto;
if (cryptoApi && typeof cryptoApi.randomUUID === 'function') {
try {
return `demo-${cryptoApi.randomUUID()}`;
} catch {
- // 非安全上下文会抛错,落到下面的备用编号。
+ // A non-secure context throws, and execution falls through to the fallback id below.
}
}
const bytes = new Uint8Array(8);
diff --git a/webdemo/frontend/src/api/map/fileUploads.ts b/webdemo/frontend/src/api/map/fileUploads.ts
index bd48563..f3a71f3 100644
--- a/webdemo/frontend/src/api/map/fileUploads.ts
+++ b/webdemo/frontend/src/api/map/fileUploads.ts
@@ -5,12 +5,12 @@ interface FileUploadConfig {
project_id?: string;
}
-/** 免登录演示:默认项目始终可用。 */
+/** Login-free demo: the default project is always available. */
export async function fileUploadConfig(): Promise<FileUploadConfig> {
return { enabled: true, project_id: 'demo-project' };
}
-/** 生成本地 fileId,并保留文件对象供演示识别结果生成使用。 */
+/** Generate a local fileId and keep the file object for generating demo recognition results. */
export async function uploadPlaygroundFile(
file: File,
projectId: string,
@@ -21,7 +21,7 @@ export async function uploadPlaygroundFile(
return rememberDemoUpload(file);
}
-/** 用本地 Object URL 作为短时读取链接。 */
+/** Use a local object URL as a short-lived read link. */
export async function linkPlaygroundFile(
fileId: string,
signal?: AbortSignal,
diff --git a/webdemo/frontend/src/api/map/imageParseExamples.ts b/webdemo/frontend/src/api/map/imageParseExamples.ts
index 8b929c4..5dd03bc 100644
--- a/webdemo/frontend/src/api/map/imageParseExamples.ts
+++ b/webdemo/frontend/src/api/map/imageParseExamples.ts
@@ -1,7 +1,7 @@
import { mapRequest } from './request';
import type { ImageParseExampleType } from '@/pages/playground/utils/imageParseExamples';
-/** 数据库预采集的共享案例单页结果。 */
+/** One pre-captured page result for a shared example stored in the database. */
export interface ImageParseExampleCapture {
resultIndex: number;
sourcePage: number;
@@ -11,7 +11,7 @@ export interface ImageParseExampleCapture {
response: unknown;
}
-/** 单个共享案例的全部预采集页。 */
+/** Every pre-captured page of one shared example. */
export interface ImageParseExample {
type: ImageParseExampleType;
captures: ImageParseExampleCapture[];
@@ -41,11 +41,11 @@ function isCapture(value: unknown): value is ImageParseExampleCapture {
}
/**
- * 读取并校验数据库预采集结果;不触发 OCR,也不回退为前端演示数据。
- * @param type 固定案例类型
- * @param version 原件版本,避免使用旧图的缓存结果
- * @param signal 切换案例、账号或项目时的取消信号
- * @returns 该案例全部页的服务端识别结果
+ * Read and validate pre-captured database results; do not trigger OCR, and do not fall back to frontend demo data.
+ * @param type Fixed example type
+ * @param version Original-file version, so a cached result for an old image is not used
+ * @param signal Abort signal used when switching example, account, or project
+ * @returns Server recognition results for every page of this example
*/
export async function getImageParseExample(
type: ImageParseExampleType,
diff --git a/webdemo/frontend/src/api/map/imageParseHistory.ts b/webdemo/frontend/src/api/map/imageParseHistory.ts
index 881222b..524c486 100644
--- a/webdemo/frontend/src/api/map/imageParseHistory.ts
+++ b/webdemo/frontend/src/api/map/imageParseHistory.ts
@@ -10,10 +10,10 @@ import type {
} from '@/pages/playground/utils/imageParseHistoryTypes';
import { sanitizeImageParseSnapshot } from '@/pages/playground/utils/imageParseHistorySnapshot';
-/** 单次历史存档上限;fileId 记录不再包含原始 base64。 */
+/** Per-save history size limit; fileId records no longer include the original base64. */
export const IMAGE_PARSE_HISTORY_MAX_BODY_BYTES = 128 * 1024 * 1024;
-/** 已登录用户的轻量分页历史。 */
+/** Lightweight paged history for a logged-in user. */
export interface ImageParseHistoryPage {
list: ImageParseHistorySummary[];
hasMore: boolean;
@@ -54,7 +54,7 @@ function isImageParseMode(value: unknown): value is ImageParseMode {
);
}
-/** 校验云端分页响应,防止网关异常数据进入组件后破坏历史列表。 */
+/** Validate the cloud page response so bad gateway data cannot enter a component and break the history list. */
function parseImageParseHistoryPage(value: unknown): ImageParseHistoryPage {
if (
!isRecord(value) ||
@@ -84,7 +84,7 @@ function historyPath(
return `/image-parse/history${id ? `/${encodeURIComponent(id)}` : ''}?${query}`;
}
-/** 用户 ID 只用于客户端隔离;服务端从登录态决定实际归属,不接收 owner 参数。 */
+/** The user ID is only for client-side isolation; the server decides real ownership from the login session and does not accept an owner parameter. */
export function listImageParseHistory(
scope: ImageParseHistoryScope,
offset = 0,
@@ -105,7 +105,7 @@ function isSignedFileURL(value: string): boolean {
}
}
-/** 打开 fileId 历史时重新鉴权签链,原件下载由预览处理,不阻塞已保存结果。 */
+/** When opening fileId history, re-authenticate and sign the link. Original-file download is handled by preview and does not block the saved result. */
async function hydrateImageParseSnapshot(
snapshot: ImageParseSnapshot,
signal?: AbortSignal,
@@ -121,7 +121,7 @@ async function hydrateImageParseSnapshot(
}
}
-/** 获取本人记录并重新校验完整快照,不信任网络返回的附件扩展字段。 */
+/** Fetch the current user's record and re-validate the full snapshot; do not trust attachment extension fields returned over the network. */
export async function getImageParseHistory(
scope: ImageParseHistoryScope,
id: string,
@@ -154,7 +154,7 @@ export async function getImageParseHistory(
};
}
-/** 幂等保存完成结果;恢复记录用 PUT,旧缓存迁移只插入、不覆盖云端版本。 */
+/** Idempotently save a finished result; restored records use PUT, and old-cache migration only inserts and does not overwrite the cloud version. */
export function saveImageParseHistory(
scope: ImageParseHistoryScope,
value: ImageParseSnapshot,
@@ -178,7 +178,7 @@ export function saveImageParseHistory(
return mapRequest(historyPath(scope, id), { method: id ? 'PUT' : 'POST', body });
}
-/** 删除只能作用于当前登录用户的记录,公开案例不调用此接口。 */
+/** Delete applies only to the currently logged-in user's records; public examples do not call this API. */
export async function deleteImageParseHistory(
scope: ImageParseHistoryScope,
id: string,
diff --git a/webdemo/frontend/src/api/map/imageParseJobs.ts b/webdemo/frontend/src/api/map/imageParseJobs.ts
index d36749c..0b72a77 100644
--- a/webdemo/frontend/src/api/map/imageParseJobs.ts
+++ b/webdemo/frontend/src/api/map/imageParseJobs.ts
@@ -12,7 +12,7 @@ export type ImageParseJobTask = 'standard' | 'seal' | 'kie';
export type ImageParseJobStatus = 'Running' | 'Success' | 'Failed' | 'Cancelled';
export type ImageParseJobPage = Parameters<typeof adaptImageParseV2>[0];
-/** MAP 持有的异步 OCR 任务;运行中的 pages 是已完成页面的前缀。 */
+/** Async OCR job owned by MAP; while running, pages is the prefix of pages already finished. */
export interface ImageParseJob {
id: string;
status: ImageParseJobStatus;
@@ -23,7 +23,7 @@ export interface ImageParseJob {
error?: string | { message?: string; code?: string };
}
-/** 文件服务原件引用;pageIndex 只用于原 PDF 的单页重试。 */
+/** File-service reference to the original file; pageIndex is used only to retry one page of the original PDF. */
export interface ImageParseJobInput {
task: ImageParseJobTask;
model: string;
@@ -171,9 +171,9 @@ async function observeJob(
}
/**
- * 创建 MAP OCR 任务并通过 TanStack Query 每秒观察进度,终态停止并清理查询。
- * @param input 原件 fileId、执行选项、QueryClient 与取消/进度回调
- * @returns 成功任务;失败使用稳定文案键,取消时 DELETE 已创建任务
+ * Create a MAP OCR job and watch progress once a second with TanStack Query; stop and clear the query at a terminal state.
+ * @param input Original-file fileId, execution options, QueryClient, and cancel/progress callbacks
+ * @returns The successful job; failure uses a stable copy key, and cancel DELETEs the job that was created
*/
export async function runImageParseJob(input: ImageParseJobInput): Promise<ImageParseJob> {
input.signal.throwIfAborted();
@@ -187,7 +187,7 @@ export async function runImageParseJob(input: ImageParseJobInput): Promise<Image
input.signal.throwIfAborted();
};
try {
- // 创建不能绑定页面的 abort:先拿到任务 ID,才能可靠取消创建期间产生的任务。
+ // Create must not bind the page abort: the job ID has to be obtained first so a job created during create can be cancelled reliably.
const raw = await mapRequest<unknown>('/image-parse/jobs', {
method: 'POST',
body,
@@ -208,7 +208,7 @@ export async function runImageParseJob(input: ImageParseJobInput): Promise<Image
return jobResult(job);
} catch (error) {
if (id && (input.signal.aborted || !job || job.status === 'Running')) {
- // 清理必须使用独立请求;取消失败不能覆盖原始错误或启动新的识别。
+ // Cleanup must use a separate request; a failed cancel must not overwrite the original error or start a new recognition.
await mapRequest(`/image-parse/jobs/${encodeURIComponent(id)}`, {
method: 'DELETE',
}).catch(() => undefined);
diff --git a/webdemo/frontend/src/api/map/imageParsePipeline.ts b/webdemo/frontend/src/api/map/imageParsePipeline.ts
index 665463b..c4870b5 100644
--- a/webdemo/frontend/src/api/map/imageParsePipeline.ts
+++ b/webdemo/frontend/src/api/map/imageParsePipeline.ts
@@ -1,8 +1,8 @@
/**
- * 算法侧图像解析流水线的前端适配层。
+ * Frontend adapter for the algorithm image-parsing pipeline.
*
- * 浏览器只调用 MAP L3 的同源接口;流水线地址、无鉴权上游接口与任务归属
- * 均由后端持有。印章/关键信息抽取不沿用 L2 API Key 链路。
+ * The browser calls only MAP L3 same-origin APIs. The pipeline address, unauthenticated upstream APIs, and task ownership
+ * are all held by the backend. Seal recognition and key information extraction do not reuse the L2 API Key path.
*/
import { BizError } from '@map/types';
@@ -38,8 +38,8 @@ function parseCapabilities(value: unknown): ImageParsePipelineCapabilities {
const modes = Array.isArray(raw.modes)
? raw.modes.filter((mode): mode is string => typeof mode === 'string')
: [];
- // 兼容算法文档的 enabled/modes 契约。旧版 MAP 只返回 enabled,
- // 不能仅凭它开放流水线入口;必须看到 modes 声明。
+ // Compatible with the enabled/modes contract in the algorithm docs. Older MAP returns only enabled,
+ // which is not enough to open the pipeline entry; a modes declaration is required.
const enabled =
raw.pipeline === true ||
(raw.pipeline === undefined &&
@@ -56,9 +56,9 @@ function parseCapabilities(value: unknown): ImageParsePipelineCapabilities {
}
/**
- * 探测流水线能力。缓存与重试由调用方的 TanStack Query 负责,失败时向上抛出。
- * @param signal 页面或查询生命周期信号
- * @returns 归一化能力;响应结构不合法时安全降级为不可用
+ * Probe pipeline capabilities. The caller’s TanStack Query owns caching and retries; failures are thrown upward.
+ * @param signal Page or query lifecycle signal
+ * @returns Normalized capabilities; an invalid response shape safely degrades to unavailable
*/
export async function loadImageParsePipelineCapabilities(
signal?: AbortSignal,
@@ -88,8 +88,8 @@ interface ImageParsePipelineBaseInput {
}
/**
- * 工作台仅传文件服务 fileId,经 MAP 异步任务执行。
- * fileUrl 和 inline image 仅兼容旧调用方,不是工作台回退路径。
+ * The workbench sends only a file-service fileId and runs it through a MAP async job.
+ * fileUrl and inline image remain only for older callers; they are not a workbench fallback path.
*/
export type ImageParsePipelineInput = ImageParsePipelineBaseInput &
(
@@ -98,7 +98,7 @@ export type ImageParsePipelineInput = ImageParsePipelineBaseInput &
| { image: string; fileId?: never; fileUrl?: never }
);
-/** 单图 fileId 走异步任务;旧 URL/内联调用保留同步契约,均由 L3 校验。 */
+/** A single-image fileId goes through an async job; older URL and inline calls keep the sync contract. L3 validates both. */
export async function parseImagePipeline(
input: ImageParsePipelineInput,
): Promise<ImageParseSdkResult> {
@@ -165,7 +165,7 @@ export async function parseImagePipeline(
)
throw new Error('imageParseInvalidResult');
const result = adaptImageParseV2(response);
- // 算法流水线不提供重算凭据,旧历史来源不能被新响应重新启用。
+ // The algorithm pipeline does not provide recompute credentials, so an old history source must not be re-enabled by a new response.
delete result.source;
return validateImageParseSdkResult(result, {
allowEmptyMarkdown: input.mode === 'seal',
diff --git a/webdemo/frontend/src/api/map/imageParseSdk.ts b/webdemo/frontend/src/api/map/imageParseSdk.ts
index 5548da8..ebe654d 100644
--- a/webdemo/frontend/src/api/map/imageParseSdk.ts
+++ b/webdemo/frontend/src/api/map/imageParseSdk.ts
@@ -6,9 +6,9 @@ import type {
import type { ImageParseSource } from './imageParseSource';
/**
- * 工作台识别档位。
- * 新识别统一使用算法流水线。scored/high-precision 只为历史快照保留,
- * 不代表当前支持评分或高精度。
+ * Workbench recognition tier.
+ * New recognition always uses the algorithm pipeline. scored/high-precision are kept only for historical snapshots,
+ * and do not mean scoring or high precision is supported now.
*/
export type ImageParseMode =
| 'standard'
@@ -18,39 +18,39 @@ export type ImageParseMode =
| 'seal'
| 'kie';
-/** 算法流水线档位均由 L3 代理,不依赖浏览器持有的 L2 API Key。 */
+/** Algorithm pipeline tiers are all proxied by L3 and do not depend on an L2 API Key held in the browser. */
export function isImageParsePipelineMode(
mode: ImageParseMode,
): mode is 'standard-pipeline' | 'seal' | 'kie' {
return mode === 'standard-pipeline' || mode === 'seal' || mode === 'kie';
}
-/** 印章识别只接受单张图片;关键信息抽取支持图片与 PDF 逐页链路。 */
+/** Seal recognition accepts only a single image; key information extraction supports image and per-page PDF paths. */
export function isImageParsePipelineImageMode(
mode: ImageParseMode,
): mode is 'seal' | 'kie' {
return mode === 'seal' || mode === 'kie';
}
-/** 图片、PDF 与缓存恢复共用的工作台识别默认档位。 */
+/** Default workbench recognition tier shared by images, PDFs, and cache restore. */
export const IMAGE_PARSE_DEFAULT_MODE: ImageParseMode = 'standard';
-/** 门户消费的结构化结果,由服务适配层统一生成。 */
+/** Structured result consumed by the portal, produced uniformly by the service adapter. */
export interface ImageParseSdkResult {
markdown: string;
blocks: readonly ImageParseLayoutBlock[];
- /** 本页识别的 request_id;跨页表格合并按它找回各页结果。 */
+ /** request_id of this page’s recognition; cross-page table merge uses it to find each page’s result. */
requestId?: string;
source?: ImageParseSource;
- /** 服务端摆正信息;缺省表示旧响应未开启旋转。 */
+ /** Server rotation-adaptation info; when absent, the old response did not enable rotation. */
rotation?: ImageParseRotationInfo;
}
-/** 单块重算结果;分数必须与基础识别使用相同评分尺度。 */
+/** Single-block recompute result; the score must use the same scale as the base recognition. */
export interface ImageParseRegenerateResult {
markdown: string;
confidence: number;
- /** v4 的实际模型轮次;存在时代表服务端已完成整次优化,不再在前端重试。 */
+ /** Actual model rounds for v4; when present, the server has finished the whole optimization and the frontend does not retry. */
roundsUsed?: number;
text?: string;
requestId?: string;
@@ -60,7 +60,7 @@ export interface ImageParseRegenerateResult {
exhausted?: boolean;
}
-/** 校验 SDK 返回的坐标与分数;未知分数保留 null,不在前端估算。 */
+/** Validate coordinates and scores returned by the SDK; keep unknown scores as null and do not estimate them on the frontend. */
export function validateImageParseSdkResult(
result: ImageParseSdkResult,
options: { allowEmptyMarkdown?: boolean } = {},
@@ -121,13 +121,13 @@ export function validateImageParseSdkResult(
return result;
}
-/** 清洗服务端旋转元数据;缺失或非法时返回 null,不伪造摆正角度。 */
+/** Sanitize server rotation metadata; return null when it is missing or invalid, and do not fabricate a rotation-adaptation angle. */
export function sanitizeImageParseRotation(value: unknown): ImageParseRotationInfo | null {
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
const rotation = value as Record<string, unknown>;
const numbers = [rotation.totalAngle, rotation.orientationAngle, rotation.deskewAngle];
const isNumber = (value: unknown) => typeof value === 'number' && Number.isFinite(value);
- // 预测字段只在摆正真正跑过时才有;未启用 / gated 时后端给 null。
+ // Predicted fields are present only when rotation adaptation actually ran; the backend sends null when it is disabled or gated.
const optional = (value: unknown) => value === null || isNumber(value);
if (
typeof rotation.enabled !== 'boolean' ||
@@ -155,7 +155,7 @@ export function sanitizeImageParseRotation(value: unknown): ImageParseRotationIn
};
}
-/** 清洗归一化多区域;非法区域返回 null,避免合并块只画出错误局部。 */
+/** Sanitize normalized multi-regions; return null for an invalid region so a merged block does not draw only a wrong fragment. */
export function sanitizeImageParseRegions(
value: unknown,
): readonly ImageParseLayoutRegion[] | null {
diff --git a/webdemo/frontend/src/api/map/imageParseSource.ts b/webdemo/frontend/src/api/map/imageParseSource.ts
index 861fc0b..120f05e 100644
--- a/webdemo/frontend/src/api/map/imageParseSource.ts
+++ b/webdemo/frontend/src/api/map/imageParseSource.ts
@@ -1,18 +1,18 @@
-/** 整页识别的可验证引用;时间为 Unix 秒,仅授权该用户/项目的 OCR 块重算。 */
+/** Verifiable reference for a full-page recognition; times are Unix seconds, and it authorizes OCR block recompute only for that user/project. */
export interface ImageParseSource {
requestId: string;
- /** 来源证明绑定的模型列表模型 ID。 */
+ /** Model-list model ID bound to the source proof. */
model: string;
pageIndex: number;
- /** 服务端签发时间,Unix 秒。 */
+ /** Server issue time, Unix seconds. */
createdAt: number;
- /** 兼容历史快照保留,不再用于禁用重算。 */
+ /** Kept for historical snapshot compatibility, and no longer used to disable recompute. */
expiresAt: number;
token: string;
inputImageSha256?: string;
}
-/** 白名单重建可缓存的来源;历史引用仍可随记录恢复并用于块级重算。 */
+/** Rebuild a cacheable source from the allowlist; historical references can still be restored with the record and used for block-level recompute. */
export function sanitizeImageParseSource(value: unknown): ImageParseSource | undefined {
if (!value || typeof value !== 'object') return undefined;
const item = value as Record<string, unknown>;
@@ -48,7 +48,7 @@ export function sanitizeImageParseSource(value: unknown): ImageParseSource | und
return source;
}
-/** 旧缓存与新解析结果分别提供可恢复的提示;expires_at 仅保留兼容历史快照。 */
+/** Old cache and new parse results each provide a recoverable hint; expires_at is kept only for historical snapshot compatibility. */
export function imageParseSourceUnavailable(source?: ImageParseSource): string | undefined {
if (!source) return 'imageParseRegenerateSourceMissing';
return undefined;
diff --git a/webdemo/frontend/src/api/map/imageParseV2.ts b/webdemo/frontend/src/api/map/imageParseV2.ts
index 3b01bd9..b3df906 100644
--- a/webdemo/frontend/src/api/map/imageParseV2.ts
+++ b/webdemo/frontend/src/api/map/imageParseV2.ts
@@ -40,8 +40,8 @@ interface OcrBlock {
interface OcrPageData {
request_id?: string;
/**
- * 当前算法只声明 standard / ocr_only。保留 stp / tts 以读取历史结果,
- * 新请求不再发送这两个已下线的档位。
+ * The current algorithm declares only standard / ocr_only. stp / tts are kept so historical results can still be read,
+ * and new requests no longer send these two retired tiers.
*/
mode: 'ocr_only' | 'standard' | 'stp' | 'tts' | 'seal' | 'kie';
image_width: number;
@@ -74,9 +74,9 @@ export function imageParseOCRData(response: OcrResponse | undefined): OcrPageDat
}
/**
- * 工作台档位到当前上游 ocr.mode 的映射。
- * 算法能力接口当前只返回 standard;scored 与 high-precision 仅作为历史模式名
- * 保留,实际都使用不带评分的 standard 契约。
+ * Mapping from workbench tiers to the current upstream ocr.mode.
+ * The algorithm capability API currently returns only standard; scored and high-precision remain only as historical mode names
+ * and both actually use the unscored standard contract.
*/
const OCR_MODE: Record<'standard' | 'scored' | 'high-precision', 'ocr_only' | 'standard'> = {
standard: 'ocr_only',
@@ -99,7 +99,7 @@ function blockKind(label: string): ImageParseBlockKind {
return 'text';
}
-/** 校验并归一化服务端像素区域;主 bbox 仍单独保留作为兼容坐标。 */
+/** Validate and normalize server pixel regions; the primary bbox is still kept separately as a compatibility coordinate. */
function normalizeRegions(
value: unknown,
width: number,
@@ -129,7 +129,7 @@ function normalizeRegions(
});
}
-/** 将上游 snake_case 旋转字段映射为工作台字段后再做统一校验。 */
+/** Map upstream snake_case rotation fields to workbench fields, then run the shared validation. */
function normalizeRotation(value: unknown) {
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
const raw = value as Record<string, unknown>;
@@ -146,7 +146,7 @@ function normalizeRotation(value: unknown) {
});
}
-/** 将服务端像素 bbox、0 起始 order 与可选 score 映射到工作台。 */
+/** Map the server pixel bbox, 0-based order, and optional score onto the workbench. */
export function adaptImageParseV2(response: OcrResponse): ImageParseSdkResult {
const markdown = response?.choices?.[0]?.message?.content;
const ocr = imageParseOCRData(response);
@@ -178,7 +178,7 @@ export function adaptImageParseV2(response: OcrResponse): ImageParseSdkResult {
(block.score !== undefined &&
block.score !== -1 &&
(!Number.isFinite(block.score) || block.score < 0 || block.score > 1)) ||
- // 新版合并表格可能携带合并前分数;字段本身仍必须是布尔值。
+ // A newly merged table may carry the pre-merge score; the field itself must still be a boolean.
(block.tts_invalid !== undefined && typeof block.tts_invalid !== 'boolean')
) {
throw new Error('imageParseInvalidResult');
@@ -206,15 +206,15 @@ export function adaptImageParseV2(response: OcrResponse): ImageParseSdkResult {
...(regions ? { regions } : {}),
text: block.content ?? '',
markdown: '',
- // 上游会用 -1 表示未给出置信度;工作台统一归一为 null,不伪造分数。
+ // Upstream uses -1 when no confidence was given; the workbench normalizes that to null and does not invent a score.
confidence: block.score === -1 ? null : (block.score ?? null),
...(block.tts_invalid === true ? { ttsInvalid: true } : {}),
...(block.merged_into_previous_page === true ? { mergedIntoPreviousPage: true } : {}),
};
});
blocks.sort((a, b) => a.order! - b.order!);
- // 服务正文是排版后的权威结果:保留标题、列表、表格和公式语法,只补回遗漏的块。
- // 个别流水线响应没有聚合正文时,才按块生成预览;空印章用原图占位符保留位置。
+ // The service body is the authoritative typeset result: keep heading, list, table, and formula syntax, and only fill in missing blocks.
+ // Only when a pipeline response has no aggregated body is a preview built from blocks; an empty seal keeps its place with an original-image placeholder.
let result: ImageParseSdkResult;
if (!blocks.length) result = { markdown, blocks };
else if (markdown.trim()) result = reconcileImageParseMarkdown(markdown, blocks);
@@ -222,7 +222,7 @@ export function adaptImageParseV2(response: OcrResponse): ImageParseSdkResult {
if (ocr.request_id && /^[a-f\d]{32}$/.test(ocr.request_id)) {
result.requestId = ocr.request_id;
}
- // 旋转信息只用于展示:字段缺失或不合法时不显示,不让整页识别失败。
+ // Rotation info is for display only: hide it when fields are missing or invalid, without failing the whole-page recognition.
const rotation = normalizeRotation(ocr.rotation);
if (rotation) result.rotation = rotation;
const reference = response.map_ocr_source;
@@ -236,7 +236,7 @@ export function adaptImageParseV2(response: OcrResponse): ImageParseSdkResult {
token: reference.token,
inputImageSha256: ocr.input_image?.sha256,
});
- // 来源凭据只用于后续单块重算;无效或不匹配时丢弃即可,不影响已识别的正文与坐标。
+ // Source credentials are only for a later single-block recompute; drop them when invalid or mismatched, without affecting the recognized body or coordinates.
if (
source &&
source.requestId === ocr.request_id &&
@@ -250,7 +250,7 @@ export function adaptImageParseV2(response: OcrResponse): ImageParseSdkResult {
return result;
}
-/** 从 L2 错误体提取平台错误码;非 JSON 或非预期结构时返回 undefined。 */
+/** Extract the platform error code from an L2 error body; return undefined when it is not JSON or not the expected shape. */
function extractImageParseErrorCode(raw: string): string | undefined {
if (!raw) return undefined;
try {
@@ -261,9 +261,9 @@ function extractImageParseErrorCode(raw: string): string | undefined {
}
}
-/** 将 L2 状态码映射为工作台稳定错误键,不透出上游原文。 */
+/** Map an L2 status code to a stable workbench error key, without passing through the upstream text. */
function imageParseL2ErrorKey(status: number, errorCode?: string): string {
- // 文件引用错误由 L2 以稳定错误键返回,直接交给界面本地化。
+ // File-reference errors are returned by L2 as stable error keys and handed to the UI for localization.
if (errorCode && /^imageParse[A-Z]/.test(errorCode)) return errorCode;
if (
status === 402 &&
@@ -278,7 +278,7 @@ function imageParseL2ErrorKey(status: number, errorCode?: string): string {
return 'imageParseRequestFailed';
}
-/** 以 API Key 直连 L2;明文密钥仅内存传递,并同时携带 Portal 身份用于调用记录归属。 */
+/** Call L2 directly with an API Key; the plaintext secret stays in memory only, and the Portal identity is sent along so call records can be attributed. */
async function requestImageParseL2(
body: unknown,
secret: string,
@@ -311,14 +311,14 @@ async function requestImageParseL2(
return res.json();
}
-/** L2 单图输入三选一:OBS file_id、平台签名资产链接或内联 data URI。 */
+/** L2 single-image input is one of three: an OBS file_id, a platform-signed asset URL, or an inline data URI. */
export interface ImageParseV2Input {
fileId?: string;
fileUrl?: string;
image?: string;
}
-/** 单张图通过 L2 API Key 链路调用 OCR,保证 request_logs 与 usage_records 真实落账。 */
+/** A single image calls OCR through the L2 API Key path so request_logs and usage_records are actually recorded. */
export async function parseImageV2(
input: string | ImageParseV2Input,
mode: ImageParseMode,
@@ -360,20 +360,20 @@ export async function parseImageV2(
if (raw.metadata?.page_index !== undefined && raw.metadata.page_index !== pageIndex)
throw new Error('imageParseInvalidResult');
const result = adaptImageParseV2(raw);
- // 上游可能附带自身模型的来源字段;模型不匹配时禁用重算,但保留本次识别结果。
+ // Upstream may attach its own model source fields; when the model does not match, disable recompute but keep this recognition result.
if (result.source && result.source.model !== selectedModel) delete result.source;
return result;
}
-/** 跨页表格合并请求里的一页:本页识别的 request_id 与页码(0 起始)。 */
+/** One page in a cross-page table merge request: the request_id of this page’s recognition and the page index (0-based). */
export interface ImageParseMergePage {
requestId: string;
pageIndex: number;
}
/**
- * LIS 是否支持经 L3 合并跨页表格。
- * 能力探测失败时返回 false,由调用方回退到本地合并。
+ * Whether LIS supports cross-page table merge through L3.
+ * Return false when capability probing fails, and let the caller fall back to a local merge.
*/
export async function crossPageMergeAvailable(signal?: AbortSignal): Promise<boolean> {
try {
@@ -387,8 +387,8 @@ export async function crossPageMergeAvailable(signal?: AbortSignal): Promise<boo
}
/**
- * 一份 PDF 的各页都识别完后,请求 L3 通过 LIS 做跨页表格合并。
- * 只返回有变化的页(页码 → 合并后的整页结果),响应与整页识别同构,走同一套校验。
+ * After every page of a PDF has been recognized, ask L3 to merge cross-page tables through LIS.
+ * Return only pages that changed (page index to the merged full-page result). The response matches full-page recognition and uses the same validation.
*/
export async function mergeImageParseCrossPage(
pages: readonly ImageParseMergePage[],
@@ -453,7 +453,7 @@ interface OcrBlockResponse {
minicpm_ocr?: OcrBlockData;
}
-/** 一次 L2 请求完成服务端块优化;原图与永久服务 Key 均不进入浏览器请求。 */
+/** One L2 request finishes server-side block optimization; neither the original image nor a permanent service key enters the browser request. */
export async function regenerateImageParseV4(
source: ImageParseSource,
original: ImageParseLayoutBlock,
diff --git a/webdemo/frontend/src/api/map/queries.ts b/webdemo/frontend/src/api/map/queries.ts
index dea3a7b..86a5847 100644
--- a/webdemo/frontend/src/api/map/queries.ts
+++ b/webdemo/frontend/src/api/map/queries.ts
@@ -8,14 +8,14 @@ import {
import { mapResourcesApi } from './resources';
/**
- * MAP 资源域的 TanStack Query 封装。
+ * TanStack Query wrappers for the MAP resource domain.
*
- * 用途:把「服务端可缓存状态」(项目/Key/模型/用量/日志/限额)统一收敛为 query/mutation hooks,
- * 遵循 MAP 的 `example.query.ts` 范式(queryKey 工厂 + useXxxQuery/useXxxMutation),
- * 避免页面里散写 useState+useEffect 取数(AGENTS 硬规则 #4)。
+ * Purpose: gather server cacheable state (projects, keys, models, usage, logs, quotas) into query/mutation hooks,
+ * following the MAP `example.query.ts` pattern (queryKey factory plus useXxxQuery/useXxxMutation),
+ * so pages do not scatter useState+useEffect data fetching (AGENTS hard rule #4).
*/
-/** queryKey 工厂:集中管理 MAP 资源域的所有缓存键 */
+/** queryKey factory: centralize every cache key in the MAP resource domain */
export const mapKeys = {
all: ['map'] as const,
me: () => [...mapKeys.all, 'me'] as const,
@@ -44,12 +44,12 @@ export const mapKeys = {
conversation: (id: string) => [...mapKeys.all, 'conversation', id] as const,
};
-/** 项目列表查询 */
+/** Project list query */
export function useProjectsQuery() {
return useQuery({ queryKey: mapKeys.projects(), queryFn: mapResourcesApi.projects });
}
-/** 某项目下的 API Key 列表查询(projectId 为空时不发起) */
+/** API Key list query for a project (not sent when projectId is empty) */
export function useKeysQuery(projectId: string) {
return useQuery({
queryKey: mapKeys.keys(projectId),
@@ -58,22 +58,22 @@ export function useKeysQuery(projectId: string) {
});
}
-/** 当前组织名下所有项目的 API Key 列表查询(跨项目,用于接入引导选 Key) */
+/** API Key list query for every project in the current organization (cross-project, used by onboarding to pick a key) */
export function useAllKeysQuery() {
return useQuery({
queryKey: mapKeys.keysAll(),
queryFn: mapResourcesApi.keysAll,
- // 用户从 Keys 页创建后返回 Playground(或刷新)时必须重新读取,才能自动选中新 Key。
+ // After the user creates a key on the Keys page and returns to Playground (or refreshes), this must be read again so the new key can be selected automatically.
staleTime: 0,
refetchOnMount: 'always',
});
}
/**
- * 某 API Key 的完整明文查询(后端 AES-GCM 解密)。
+ * Full plaintext query for an API Key (backend AES-GCM decrypt).
*
- * 用途:接入示例按选中的 Key 回显真实明文。keyId 为空时不发起;明文敏感,不长期缓存
- * (staleTime/gcTime 设 0),且旧 Key 无密文时后端 409、query 进入 error 态供 UI 回退占位符。
+ * Purpose: onboarding examples echo the real plaintext of the selected key. Not sent when keyId is empty. The plaintext is sensitive and is not cached for long
+ * (staleTime/gcTime are 0). When an old key has no ciphertext the backend returns 409 and the query enters the error state so the UI can fall back to a placeholder.
*/
export function useKeySecretQuery(keyId: string, enabled = true) {
return useQuery({
@@ -87,10 +87,10 @@ export function useKeySecretQuery(keyId: string, enabled = true) {
}
/**
- * Playground 免费体验状态查询。
+ * Playground free-trial status query.
*
- * 返回值包含仅在内存中使用的体验 Key 明文;为避免敏感凭据跨页面残留,
- * 缓存策略与 Key 明文一致(staleTime/gcTime=0),失败不自动重试。
+ * The result includes the trial key plaintext, which is used in memory only. To avoid leaving sensitive credentials across pages,
+ * the cache policy matches key plaintext (staleTime/gcTime=0), and failures are not retried automatically.
*/
export function usePlaygroundTrialQuery() {
return useQuery({
@@ -102,17 +102,17 @@ export function usePlaygroundTrialQuery() {
});
}
-/** 可调用模型列表查询 */
+/** Callable model list query */
export function useModelsQuery() {
return useQuery({
queryKey: mapKeys.models(),
queryFn: mapResourcesApi.models,
- // 管理台与 Portal 是独立应用;切回 Playground 时刷新,及时获取模型能力开关变更。
+ // The admin console and Portal are separate apps; refresh when returning to Playground so model capability switches are picked up promptly.
refetchOnWindowFocus: true,
});
}
-/** 当前用户私有音色列表查询。 */
+/** Current user's private voice list query. */
export function useVoicesQuery(enabled = true) {
return useQuery({
queryKey: mapKeys.voices(),
@@ -121,7 +121,7 @@ export function useVoicesQuery(enabled = true) {
});
}
-/** 当前登录用户的产品功能权限查询。 */
+/** Product feature permission query for the currently logged-in user. */
export function useFeatureAccessQuery() {
return useQuery({
queryKey: mapKeys.featureAccess(),
@@ -129,7 +129,7 @@ export function useFeatureAccessQuery() {
});
}
-/** 上传私有音色并刷新音色列表 */
+/** Upload a private voice and refresh the voice list */
export function useCreateVoiceMutation() {
const queryClient = useQueryClient();
return useMutation({
@@ -139,7 +139,7 @@ export function useCreateVoiceMutation() {
});
}
-/** 删除私有音色并刷新音色列表 */
+/** Delete a private voice and refresh the voice list */
export function useDeleteVoiceMutation() {
const queryClient = useQueryClient();
return useMutation({
@@ -148,7 +148,7 @@ export function useDeleteVoiceMutation() {
});
}
-/** 用量汇总查询 */
+/** Usage summary query */
export function useUsageSummaryQuery(start?: string, end?: string) {
return useQuery({
queryKey: mapKeys.usageSummary(start, end),
@@ -156,7 +156,7 @@ export function useUsageSummaryQuery(start?: string, end?: string) {
});
}
-/** 调用日志查询(服务端分页,按 request_id / 模型 / 结果过滤;翻页时保留上一页数据避免闪烁) */
+/** Call-log query (server pagination, filtered by request_id / model / outcome; keep the previous page while paging to avoid flicker) */
export function useLogsQuery(
requestId: string,
publicModel: string,
@@ -171,22 +171,22 @@ export function useLogsQuery(
});
}
-/** 公开配置查询 */
+/** Public config query */
export function usePublicConfigQuery() {
return useQuery({ queryKey: mapKeys.publicConfig(), queryFn: mapResourcesApi.publicConfig });
}
-/** 本人计费账户查询 */
+/** Current user's billing account query */
export function useBillingAccountQuery() {
return useQuery({ queryKey: mapKeys.billingAccount(), queryFn: mapResourcesApi.billingAccount });
}
-/** 本人体验额度包查询 */
+/** Current user's trial credit package query */
export function useCreditPackagesQuery() {
return useQuery({ queryKey: mapKeys.creditPackages(), queryFn: mapResourcesApi.creditPackages });
}
-/** 本人充值流水查询 */
+/** Current user's top-up history query */
export function useRechargesQuery() {
return useQuery({ queryKey: mapKeys.recharges(), queryFn: mapResourcesApi.recharges });
}
@@ -207,7 +207,7 @@ export function useClaimDailyCheckinMutation() {
});
}
-/** 本人花费统计查询(按区间) */
+/** Current user's spend statistics query (by range) */
export function useSpendQuery(start: string, end: string) {
return useQuery({
queryKey: mapKeys.spend(start, end),
@@ -216,7 +216,7 @@ export function useSpendQuery(start: string, end: string) {
});
}
-/** 调用详情查询(含正文,requestId 为空时不发起) */
+/** Call detail query (including body; not sent when requestId is empty) */
export function useCallLogDetailQuery(requestId: string, enabled: boolean) {
return useQuery({
queryKey: mapKeys.callLogDetail(requestId),
@@ -225,17 +225,17 @@ export function useCallLogDetailQuery(requestId: string, enabled: boolean) {
});
}
-/** 本人月账单查询 */
+/** Current user's monthly bill query */
export function useMonthlyBillsQuery() {
return useQuery({ queryKey: mapKeys.monthlyBills(), queryFn: mapResourcesApi.monthlyBills });
}
-/** 预警配置查询 */
+/** Alert config query */
export function useAlertConfigsQuery() {
return useQuery({ queryKey: mapKeys.alertConfigs(), queryFn: mapResourcesApi.alertConfigs });
}
-/** 创建项目(成功后失效项目列表缓存) */
+/** Create a project (invalidate the project list cache on success) */
export function useCreateProjectMutation() {
const queryClient = useQueryClient();
return useMutation({
@@ -244,7 +244,7 @@ export function useCreateProjectMutation() {
});
}
-/** 更新预警配置(成功后失效预警配置缓存) */
+/** Update alert config (invalidate the alert config cache on success) */
export function useUpsertAlertConfigMutation() {
const queryClient = useQueryClient();
return useMutation({
@@ -253,26 +253,26 @@ export function useUpsertAlertConfigMutation() {
});
}
-/** 提交充值申请 */
+/** Submit a top-up request */
export function useRechargeRequestMutation() {
return useMutation({ mutationFn: mapResourcesApi.rechargeRequest });
}
-/** 提交体验中心对话反馈(点赞/点踩),fire-and-forget,无需刷新缓存 */
+/** Submit experience-center conversation feedback (like/dislike); fire-and-forget, no cache refresh */
export function useSubmitFeedbackMutation() {
return useMutation({ mutationFn: mapResourcesApi.submitFeedback });
}
-/** 发起易宝在线支付下单(成功后前端跳转 cashier_url,无需刷新本地缓存) */
+/** Start a Yeepay online payment order (on success the frontend redirects to cashier_url; no local cache refresh) */
export function useYeepayOrderMutation() {
return useMutation({ mutationFn: mapResourcesApi.yeepayOrder });
}
-// ===== Playground 历史对话 =====
+// ===== Playground history conversations =====
/**
- * 历史对话分页查询:每页 20 条,由侧栏「加载更多对话」显式追加下一页。
- * 列表可能很多,一次性加载会卡顿/崩溃,故分页累积。
+ * Paged history-conversation query: 20 items per page, and the sidebar Load more conversations control explicitly appends the next page.
+ * The list can be very long, and loading it all at once can stall or crash, so pages are accumulated.
*/
export function useInfiniteConversationsQuery() {
const pageSize = 20;
@@ -281,7 +281,7 @@ export function useInfiniteConversationsQuery() {
queryFn: ({ pageParam }) => mapResourcesApi.conversations({ page: pageParam, pageSize }),
initialPageParam: 1,
getNextPageParam: (last) => {
- // 后端未部署/异常返回时字段可能缺失,做防御:拿不到合法分页信息即停止翻页
+ // When the backend is not deployed or returns an error, fields may be missing. Defend by stopping paging when valid page info is absent
if (!last || typeof last.total !== 'number' || typeof last.page !== 'number')
return undefined;
const loaded = last.page * (last.page_size || pageSize);
@@ -290,7 +290,7 @@ export function useInfiniteConversationsQuery() {
});
}
-/** 单个会话详情查询(id 为空时不发起) */
+/** Single conversation detail query (not sent when id is empty) */
export function useConversationQuery(id: string) {
return useQuery({
queryKey: mapKeys.conversation(id),
@@ -299,7 +299,7 @@ export function useConversationQuery(id: string) {
});
}
-/** 新建会话(成功后失效列表缓存) */
+/** Create a conversation (invalidate the list cache on success) */
export function useCreateConversationMutation() {
const queryClient = useQueryClient();
return useMutation({
@@ -309,7 +309,7 @@ export function useCreateConversationMutation() {
});
}
-/** 保存会话消息(整段覆盖;成功后失效列表缓存以刷新标题/排序) */
+/** Save conversation messages (full overwrite; invalidate the list cache on success to refresh title and sort order) */
export function useSaveConversationMutation() {
const queryClient = useQueryClient();
return useMutation({
@@ -321,7 +321,7 @@ export function useSaveConversationMutation() {
});
}
-/** 删除会话(成功后失效列表缓存) */
+/** Delete a conversation (invalidate the list cache on success) */
export function useDeleteConversationMutation() {
const queryClient = useQueryClient();
return useMutation({
diff --git a/webdemo/frontend/src/api/map/request.ts b/webdemo/frontend/src/api/map/request.ts
index d86ebff..995c2b2 100644
--- a/webdemo/frontend/src/api/map/request.ts
+++ b/webdemo/frontend/src/api/map/request.ts
@@ -1,9 +1,9 @@
import { getDemoUpload } from './demoStore';
/**
- * 免登录演示请求器。
+ * Login-free demo request client.
*
- * 文档解析页在浏览器里保留一份本地会话。解析请求发给本机工人,不发给云端。
+ * The document-parsing page keeps a local session in the browser. Parse requests go to the local worker, not to the cloud.
*/
const TOKEN_KEY = 'map_token';
@@ -322,8 +322,68 @@ function ocrResponse(
};
}
+function fileToBase64(file: File): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => {
+ const result = reader.result;
+ if (typeof result !== 'string') {
+ reject(new Error('imageParseRequestFailed'));
+ return;
+ }
+ const comma = result.indexOf(',');
+ resolve(comma >= 0 ? result.slice(comma + 1) : result);
+ };
+ reader.onerror = () => reject(new Error('imageParseRequestFailed'));
+ reader.readAsDataURL(file);
+ });
+}
+
+async function createKieJob(body: Record<string, unknown>): Promise<DemoJob> {
+ const upload = getDemoUpload(typeof body.file_id === 'string' ? body.file_id : undefined);
+ if (!upload) throw new Error('imageParseFileReferenceRequired');
+ const fields = Array.isArray(body.fields)
+ ? body.fields.filter((item): item is string => typeof item === 'string')
+ : [];
+ const response = await fetch('/api/kie', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
+ body: JSON.stringify({
+ image: await fileToBase64(upload),
+ fields,
+ }),
+ });
+ const payload = (await response.json().catch(() => ({}))) as {
+ error?: unknown;
+ choices?: DemoOcrResponse['choices'];
+ minicpm_ocr?: DemoOcrResponse['ocr'];
+ };
+ if (!response.ok) {
+ const message = typeof payload.error === 'string' ? payload.error : 'imageParseRequestFailed';
+ throw new Error(message);
+ }
+ if (!payload.minicpm_ocr || !payload.choices?.length) {
+ throw new Error('imageParseInvalidResult');
+ }
+ return {
+ id: crypto.randomUUID().replace(/-/g, ''),
+ task: 'kie',
+ status: 'Success',
+ pages_done: 1,
+ pages_total: 1,
+ pages: [
+ {
+ metadata: { page_index: 0 },
+ choices: payload.choices,
+ ocr: payload.minicpm_ocr,
+ },
+ ],
+ };
+}
+
function createJob(init: RequestInit): Promise<DemoJob> {
const body = parseBody(init);
+ if (body.task === 'kie') return createKieJob(body);
const upload = getDemoUpload(typeof body.file_id === 'string' ? body.file_id : undefined);
if (!upload) throw new Error('imageParseFileReferenceRequired');
const form = new FormData();
@@ -480,7 +540,7 @@ export async function mapUpload<T>(
}
export async function mapDownload(_path: string, _filename: string): Promise<void> {
- // 免登录演示不提供远端下载接口。
+ // The login-free demo does not provide a remote download API.
}
export async function mapBlobUrl(_path: string): Promise<string> {
diff --git a/webdemo/frontend/src/api/map/resources.ts b/webdemo/frontend/src/api/map/resources.ts
index 7f0de0d..d8674bf 100644
--- a/webdemo/frontend/src/api/map/resources.ts
+++ b/webdemo/frontend/src/api/map/resources.ts
@@ -27,64 +27,64 @@ import type {
} from './types';
/**
- * MAP 资源 API。
+ * MAP resource API.
*
- * 用途:开发者门户的项目 / API Key / 模型 / 用量 / 日志 / 限额等资源读写,统一经 `mapRequest`
- * 直发 MAP 后端(裸 JSON)。这些是「服务端可缓存状态」,页面侧用 TanStack Query 包裹获取。
- * 由原 `web/portal/src/api.ts` 的 `client` 资源段迁移而来。
+ * Purpose: read and write developer-portal resources such as projects, API keys, models, usage, logs, and quotas, all through `mapRequest`
+ * directly to the MAP backend (raw JSON). This is server cacheable state, and pages fetch it wrapped in TanStack Query.
+ * Migrated from the `client` resource section of the original `web/portal/src/api.ts`.
*/
export const mapResourcesApi = {
- /** 项目列表 */
+ /** Project list */
projects: () => mapRequest<{ list: MapProject[] }>('/projects'),
- /** 创建项目 */
+ /** Create a project */
createProject: (name: string) =>
mapRequest<MapProject>('/projects', { method: 'POST', body: JSON.stringify({ name }) }),
- /** 某项目下的 API Key 列表 */
+ /** API Key list under a project */
keys: (projectId: string) => mapRequest<{ list: MapApiKey[] }>(`/projects/${projectId}/keys`),
- /** 当前组织名下所有项目的 API Key(跨项目,带 project_name 标注归属) */
+ /** API keys for every project in the current organization (cross-project, with project_name marking ownership) */
keysAll: () => mapRequest<{ list: MapApiKey[] }>('/keys'),
- /** 在某项目下创建 API Key(返回明文 secret,仅此一次) */
+ /** Create an API Key under a project (returns the plaintext secret, once only) */
createKey: (projectId: string, payload: { name: string; expires_at?: string }) =>
mapRequest<{ api_key: MapApiKey; secret: string }>(`/projects/${projectId}/keys`, {
method: 'POST',
body: JSON.stringify(payload),
}),
- /** 启用 / 禁用某 API Key */
+ /** Enable / disable an API Key */
setKeyStatus: (keyId: string, status: 'active' | 'disabled') =>
mapRequest<{ status: string }>(`/keys/${keyId}`, {
method: 'PATCH',
body: JSON.stringify({ status }),
}),
- /** 删除某 API Key */
+ /** Delete an API Key */
deleteKey: (keyId: string) =>
mapRequest<{ status: string }>(`/keys/${keyId}`, { method: 'DELETE' }),
- /** 轮换某 API Key(旧密钥立即失效,返回新明文 secret) */
+ /** Rotate an API Key (the old secret expires immediately and a new plaintext secret is returned) */
rotateKey: (keyId: string) =>
mapRequest<{ secret: string; prefix: string }>(`/keys/${keyId}/rotate`, { method: 'POST' }),
- /** 取某 API Key 的完整明文(后端 AES-GCM 解密;旧 Key 无密文时返回 409) */
+ /** Fetch the full plaintext of an API Key (backend AES-GCM decrypt; 409 when an old key has no ciphertext) */
revealKeySecret: (keyId: string) => mapRequest<{ secret: string }>(`/keys/${keyId}/secret`),
- /** 可调用模型列表 */
+ /** Callable model list */
models: () => mapRequest<{ list: MapModel[] }>('/models'),
- /** 当前用户 Playground 四类免费体验剩余次数与内部体验凭据 */
+ /** Remaining counts and internal trial credentials for the current user's four Playground free trials */
playgroundTrial: () => mapRequest<MapPlaygroundTrial>('/playground/trial'),
- /** 当前用户的私有音色列表 */
+ /** Current user's private voice list */
voices: () => mapRequest<{ list: MapVoiceResource[] }>('/voices'),
- /** 当前登录用户可使用的产品功能 */
+ /** Product features available to the currently logged-in user */
featureAccess: () => mapRequest<MapFeatureAccess>('/feature-access'),
- /** 上传并保存一条私有 WAV 音色 */
+ /** Upload and save one private WAV voice */
createVoice: (file: File, name?: string, idempotencyKey = crypto.randomUUID()) => {
const form = new FormData();
form.append('file', file);
@@ -92,13 +92,13 @@ export const mapResourcesApi = {
return mapUpload<MapVoiceResource>('/voices', form, { 'Idempotency-Key': idempotencyKey });
},
- /** 删除当前用户自己的音色 */
+ /** Delete a voice owned by the current user */
deleteVoice: (voiceId: string) =>
mapRequest<{ status: string }>(`/voices/${encodeURIComponent(voiceId)}`, {
method: 'DELETE',
}),
- /** 用量汇总(可指定区间) */
+ /** Usage summary (an optional range may be given) */
usageSummary: (start?: string, end?: string) => {
const sp = new URLSearchParams();
if (start) sp.set('start', start);
@@ -107,10 +107,10 @@ export const mapResourcesApi = {
return mapRequest<MapUsageSummary>(`/usage/summary${qs ? `?${qs}` : ''}`);
},
- /** 导出用量 CSV */
+ /** Export usage CSV */
exportUsage: () => mapDownload('/usage/export', 'usage.csv'),
- /** 调用日志(服务端分页,可按 request_id / 模型 / 结果过滤;page 从 1 起,pageSize 上限 200) */
+ /** Call logs (server pagination, filterable by request_id / model / outcome; page starts at 1, pageSize max 200) */
logs: (
params: {
requestId?: string;
@@ -134,31 +134,31 @@ export const mapResourcesApi = {
}>(`/request-logs?${sp.toString()}`);
},
- /** 公开配置(对外 Base URL 等) */
+ /** Public config (external base URL and similar) */
publicConfig: () => mapRequest<MapPublicConfig>('/config/public'),
- // ===== 计费(本人视角)=====
+ // ===== Billing (current user) =====
- /** 本人计费账户(余额/额度/财务状态) */
+ /** Current user's billing account (balance / quota / financial status) */
billingAccount: () => mapRequest<MapBillingAccount>('/billing/account'),
- /** 本人可消费体验额度包与其它可用积分 */
+ /** Trial credit packages the current user can spend, and other available credits */
creditPackages: () => mapRequest<MapCreditPackageSnapshot>('/billing/credit-packages'),
- /** 本人充值流水 */
+ /** Current user's top-up history */
recharges: () => mapRequest<{ list: MapRechargeRecord[] }>('/billing/recharges'),
- /** 每日签到、邀请码和成功邀请数 */
+ /** Daily check-in, invite code, and successful invite count */
rewards: () => mapRequest<MapRewardStatus>('/rewards'),
- /** 领取当天签到奖励;后端按业务日和唯一索引保证幂等 */
+ /** Claim today's check-in reward; the backend keeps it idempotent by business day and a unique index */
claimDailyCheckin: () =>
mapRequest<{ claimed: boolean; reward_points: string; balance: string }>(
'/rewards/daily-checkins',
{ method: 'POST' },
),
- /** 本人花费统计(按模型/趋势,可指定区间) */
+ /** Current user's spend statistics (by model / trend, optional range) */
spend: (start?: string, end?: string) => {
const sp = new URLSearchParams();
if (start) sp.set('start', start);
@@ -167,40 +167,40 @@ export const mapResourcesApi = {
return mapRequest<MapSpendStats>(`/billing/spend${qs ? `?${qs}` : ''}`);
},
- /** 调用详情(含请求/响应正文与计量) */
+ /** Call detail (including request/response body and metering) */
callLogDetail: (requestId: string) =>
mapRequest<MapCallLogDetail>(`/call-logs/${encodeURIComponent(requestId)}`),
- /** 本人月账单(按月本人花费明细快照) */
+ /** Current user's monthly bills (monthly snapshot of the current user's spend details) */
monthlyBills: () => mapRequest<{ list: MapPortalMonthlyBill[] }>('/billing/monthly-bills'),
- /** 预警配置列表 */
+ /** Alert config list */
alertConfigs: () => mapRequest<{ list: MapAlertConfig[] }>('/billing/alert-configs'),
- /** 新增/更新某 scope 预警配置 */
+ /** Create or update the alert config for a scope */
upsertAlertConfig: (payload: MapAlertConfigInput) =>
mapRequest<{ status: string }>('/billing/alert-configs', {
method: 'PUT',
body: JSON.stringify(payload),
}),
- /** 提交充值申请(无在线支付,记审计供管理员处理) */
+ /** Submit a top-up request (no online payment; recorded for audit so an admin can handle it) */
rechargeRequest: (payload: { amount: string; remark?: string; contact?: string }) =>
mapRequest<{ status: string }>('/billing/recharge-request', {
method: 'POST',
body: JSON.stringify(payload),
}),
- /** 发起易宝在线支付下单:返回收银台 URL,前端跳转付款(1 元 = 1 余额) */
+ /** Start a Yeepay online payment order: returns the cashier URL, and the frontend redirects to pay (1 CNY = 1 balance unit) */
yeepayOrder: (payload: { amount: string }) =>
mapRequest<MapYeepayOrder>('/billing/yeepay/order', {
method: 'POST',
body: JSON.stringify(payload),
}),
- // ===== Playground 历史对话(每用户私有)=====
+ // ===== Playground history conversations (private per user) =====
- /** 历史对话列表(服务端分页;page 从 1 起,pageSize 上限 100) */
+ /** History conversation list (server pagination; page starts at 1, pageSize max 100) */
conversations: (params: { page?: number; pageSize?: number } = {}) => {
const sp = new URLSearchParams();
sp.set('page', String(params.page ?? 1));
@@ -213,31 +213,31 @@ export const mapResourcesApi = {
}>(`/conversations?${sp.toString()}`);
},
- /** 新建空会话(返回会话元信息,含 id) */
+ /** Create an empty conversation (returns conversation metadata, including id) */
createConversation: (payload: { title?: string; model?: string } = {}) =>
mapRequest<MapConversation>('/conversations', {
method: 'POST',
body: JSON.stringify(payload),
}),
- /** 取会话详情(元信息 + 消息明细) */
+ /** Fetch conversation detail (metadata plus message details) */
getConversation: (id: string) =>
mapRequest<MapConversationDetail>(`/conversations/${encodeURIComponent(id)}`),
- /** 整段覆盖式保存会话消息 */
+ /** Save conversation messages by full overwrite */
saveConversation: (id: string, payload: MapSaveConversationInput) =>
mapRequest<{ status: string }>(`/conversations/${encodeURIComponent(id)}/messages`, {
method: 'PUT',
body: JSON.stringify(payload),
}),
- /** 删除会话(软删) */
+ /** Delete a conversation (soft-delete) */
deleteConversation: (id: string) =>
mapRequest<{ status: string }>(`/conversations/${encodeURIComponent(id)}`, {
method: 'DELETE',
}),
- /** 提交体验中心对话反馈(点赞/点踩) */
+ /** Submit experience-center conversation feedback (like/dislike) */
submitFeedback: (payload: MapFeedbackInput) =>
mapRequest<MapFeedback>('/feedback', {
method: 'POST',
diff --git a/webdemo/frontend/src/api/map/types.conversations.ts b/webdemo/frontend/src/api/map/types.conversations.ts
index a5dce4b..1ffe6d3 100644
--- a/webdemo/frontend/src/api/map/types.conversations.ts
+++ b/webdemo/frontend/src/api/map/types.conversations.ts
@@ -1,11 +1,11 @@
/**
- * Playground 历史对话的后端存储形态(每用户私有)。
+ * Backend storage shape for Playground history conversations (private per user).
*
- * 用途:与前端 ChatMessage 互转的 DTO 集合。从 types.ts 拆出来是为了让两边都留在
- * 类型文件 500 行的硬上限内;对外仍由 types.ts 统一再导出,调用方 import 路径不变。
+ * Purpose: DTOs converted to and from the frontend ChatMessage. Split out of types.ts so both files stay
+ * within the 500-line hard limit for type files. types.ts still re-exports them, so caller import paths stay the same.
*/
-/** 历史对话(列表项 / 元信息,不含消息明细) */
+/** History conversation (list item / metadata, without message details) */
export interface MapConversation {
id: string;
title: string;
@@ -14,7 +14,7 @@ export interface MapConversation {
updated_at: string;
}
-/** 历史对话中的一条消息(后端存储形态,与前端 ChatMessage 互转) */
+/** One message in a history conversation (backend storage shape, converted to and from the frontend ChatMessage) */
export interface MapStoredMessage {
id: string;
role: 'system' | 'user' | 'assistant';
@@ -23,41 +23,41 @@ export interface MapStoredMessage {
prompt_tokens?: number;
completion_tokens?: number;
total_tokens?: number;
- /** 首 token 延迟(ms,前端埋点实测) */
+ /** Time to first token (ms, measured by frontend instrumentation) */
first_token_ms?: number;
- /** 本轮总耗时(ms,前端埋点实测) */
+ /** Total duration of this turn (ms, measured by frontend instrumentation) */
duration_ms?: number;
- /** 当前选中回答版本对应的平台 L2 请求 ID */
+ /** Platform L2 request ID for the currently selected answer version */
request_id?: string;
- /** 当前选中回答版本对应的客户端关联 ID */
+ /** Client correlation ID for the currently selected answer version */
client_request_id?: string;
- /** 当前选中回答版本实际使用的 API Key ID */
+ /** API Key ID actually used by the currently selected answer version */
api_key_id?: string;
- /** 多版本回答的全部版本(仅重新生成过的 assistant 有值;单版本为空) */
+ /** Every version of a multi-version answer (set only for a regenerated assistant message; empty for a single version) */
alt_versions?: MapStoredVersion[];
- /** 当前选中版本索引(0 起;空=单版本) */
+ /** Index of the currently selected version (0-based; empty means a single version) */
active_version?: number;
- /** 反馈高亮(当前选中版本的点赞/点踩) */
+ /** Feedback highlight (like/dislike of the currently selected version) */
feedback?: 'up' | 'down';
- /** 联网搜索引用来源(单版本 assistant 消息) */
+ /** Web-search citation sources (single-version assistant message) */
citations?: Array<{ url: string; title?: string; snippet?: string }>;
- /** 联网工具状态文本(单版本消息顶层;用于刷新后重绘过程区) */
+ /** Web-tool status text (top level of a single-version message; redraws the process area after refresh) */
search_status?: string;
- /** 联网检索当前阶段(单版本消息顶层) */
+ /** Current web-retrieval stage (top level of a single-version message) */
search_step?: string;
- /** 联网检索到的网页数量(单版本消息顶层) */
+ /** Number of web pages retrieved (top level of a single-version message) */
search_result_count?: number;
- /** 当前正在执行或最近完成的联网工具(单版本消息顶层) */
+ /** Web tool currently running or most recently finished (top level of a single-version message) */
search_active_tool?: string;
- /** 网页读取工具准备浏览或成功浏览的页面数量(单版本消息顶层) */
+ /** Number of pages the web reader is about to browse or has browsed (top level of a single-version message) */
search_browse_count?: number;
- /** 联网搜索实际使用的查询词(单版本消息顶层) */
+ /** Query terms actually used by web search (top level of a single-version message) */
search_queries?: string[];
- /** 本轮实际调用过的工具名称(单版本消息顶层) */
+ /** Tool names actually invoked this turn (top level of a single-version message) */
search_tools?: string[];
- /** 本轮工具调用事件摘要(单版本消息顶层) */
+ /** Tool-call event summary for this turn (top level of a single-version message) */
tool_events?: ToolEventDTO[];
- /** 用户消息附件元信息;只保存对象存储 URL/key 与展示元数据,不保存 base64 */
+ /** User-message attachment metadata; store only the object-storage URL/key and display metadata, not base64 */
attachments?: Array<{
id: string;
kind: 'image' | 'video' | 'audio' | 'file';
@@ -70,12 +70,12 @@ export interface MapStoredMessage {
objectKey?: string;
dataUrl?: string;
}>;
- /** 安审拦截消息仍可展示,但不会重新带入后续模型上下文。 */
+ /** A content-safety-review blocked message can still be shown, but is not fed back into later model context. */
context_excluded?: boolean;
created_at: string;
}
-/** 单个回答版本的存储形态(后端以 jsonb 原样往返,不解释内容) */
+/** Storage shape of one answer version (the backend round-trips jsonb as-is and does not interpret the content) */
export interface MapStoredVersion {
content: string;
reasoning?: string;
@@ -84,65 +84,65 @@ export interface MapStoredVersion {
total_tokens?: number;
first_token_ms?: number;
duration_ms?: number;
- /** 该回答版本对应的平台 L2 请求 ID */
+ /** Platform L2 request ID for this answer version */
request_id?: string;
- /** 该回答版本对应的客户端关联 ID */
+ /** Client correlation ID for this answer version */
client_request_id?: string;
- /** 该回答版本实际使用的 API Key ID */
+ /** API Key ID actually used by this answer version */
api_key_id?: string;
- /** 该版本的联网引用来源 */
+ /** Web citation sources for this version */
citations?: Array<{ url: string; title?: string; snippet?: string }>;
- /** 该版本的反馈高亮(点赞/点踩) */
+ /** Feedback highlight for this version (like/dislike) */
feedback?: 'up' | 'down';
- /** 该版本是否因页面刷新等客户端生命周期中断而不完整 */
+ /** Whether this version is incomplete because a client lifecycle event such as a page refresh interrupted it */
interrupted?: boolean;
- /** 该版本联网工具状态文本(用于过程区重绘) */
+ /** Web-tool status text for this version (used to redraw the process area) */
search_status?: string;
- /** 该版本联网检索当前阶段 */
+ /** Current web-retrieval stage for this version */
search_step?: string;
- /** 该版本联网检索到的网页数量 */
+ /** Number of web pages retrieved for this version */
search_result_count?: number;
- /** 该版本当前正在执行或最近完成的联网工具 */
+ /** Web tool currently running or most recently finished for this version */
search_active_tool?: string;
- /** 该版本网页读取工具准备浏览或成功浏览的页面数量 */
+ /** Number of pages the web reader is about to browse or has browsed for this version */
search_browse_count?: number;
- /** 该版本联网搜索实际使用的查询词 */
+ /** Query terms actually used by web search for this version */
search_queries?: string[];
- /** 该版本本轮实际调用过的工具名称 */
+ /** Tool names actually invoked this turn for this version */
search_tools?: string[];
- /** 该版本工具调用事件摘要 */
+ /** Tool-call event summary for this version */
tool_events?: ToolEventDTO[];
}
-/** Playground 历史消息中的工具事件摘要。 */
+/** Tool-event summary in a Playground history message. */
export interface ToolEventDTO {
eventId: string;
step: number;
tool: string;
status: 'running' | 'success' | 'failed' | 'interrupted';
queryCount?: number;
- /** 该工具实际使用的查询词。 */
+ /** Query terms this tool actually used. */
queries?: string[];
resultCount?: number;
pageCount?: number;
durationMs?: number;
message?: string;
- /** 该工具涉及的来源地址,用于在过程时间线上就地展示站点图标与页面标题。 */
+ /** Source URLs involved in this tool, shown in place on the process timeline with site icons and page titles. */
citationUrls?: string[];
/**
- * 该工具首帧到达时已产出的思考字符数,作为思考文本的切分点。
- * 由前端在流式期间推导,后端不下发;历史消息与非流式回答没有该字段。
+ * Reasoning character count already produced when this tool’s first frame arrived, used as the split point in the reasoning text.
+ * Derived on the frontend during streaming; the backend does not send it. History messages and non-streaming answers do not have this field.
*/
reasoningOffset?: number;
}
-/** 历史对话详情(元信息 + 消息明细) */
+/** History conversation detail (metadata plus message details) */
export interface MapConversationDetail {
conversation: MapConversation;
messages: MapStoredMessage[];
}
-/** 保存对话的请求体(整段覆盖式) */
+/** Request body for saving a conversation (full overwrite) */
export interface MapSaveConversationInput {
title?: string;
model?: string;
@@ -162,21 +162,21 @@ export interface MapSaveConversationInput {
active_version?: number;
feedback?: 'up' | 'down';
citations?: Array<{ url: string; title?: string; snippet?: string }>;
- /** 联网工具状态文本(单版本消息顶层;用于刷新后重绘过程区) */
+ /** Web-tool status text (top level of a single-version message; redraws the process area after refresh) */
search_status?: string;
- /** 联网检索当前阶段(单版本消息顶层) */
+ /** Current web-retrieval stage (top level of a single-version message) */
search_step?: string;
- /** 联网检索到的网页数量(单版本消息顶层) */
+ /** Number of web pages retrieved (top level of a single-version message) */
search_result_count?: number;
- /** 当前正在执行或最近完成的联网工具(单版本消息顶层) */
+ /** Web tool currently running or most recently finished (top level of a single-version message) */
search_active_tool?: string;
- /** 网页读取工具准备浏览或成功浏览的页面数量(单版本消息顶层) */
+ /** Number of pages the web reader is about to browse or has browsed (top level of a single-version message) */
search_browse_count?: number;
- /** 联网搜索实际使用的查询词(单版本消息顶层) */
+ /** Query terms actually used by web search (top level of a single-version message) */
search_queries?: string[];
- /** 本轮实际调用过的工具名称(单版本消息顶层) */
+ /** Tool names actually invoked this turn (top level of a single-version message) */
search_tools?: string[];
- /** 本轮工具调用事件摘要 */
+ /** Tool-call event summary for this turn */
tool_events?: ToolEventDTO[];
attachments?: MapStoredMessage['attachments'];
context_excluded?: boolean;
diff --git a/webdemo/frontend/src/api/map/types.ts b/webdemo/frontend/src/api/map/types.ts
index 0c6f28d..6e510a4 100644
--- a/webdemo/frontend/src/api/map/types.ts
+++ b/webdemo/frontend/src/api/map/types.ts
@@ -1,11 +1,11 @@
/**
- * MAP(ModelBest API Platform)业务域类型。
+ * MAP (ModelBest API Platform) domain types.
*
- * 用途:集中声明开发者门户用到的资源与认证相关类型,供 `api/map/*` 与各页面共享。
- * 由原 `web/portal/src/api.ts` 的类型迁移而来,字段与 MAP 后端契约保持一致。
+ * Purpose: declare the resource and auth types used by the developer portal, shared by `api/map/*` and the pages.
+ * Migrated from the types in the original `web/portal/src/api.ts`. Fields stay aligned with the MAP backend contract.
*/
-/** 项目(隶属某组织,API Key 绑定到项目而非用户) */
+/** Project (belongs to an organization; an API Key is bound to a project, not a user) */
export interface MapProject {
id: string;
org_id: string;
@@ -14,11 +14,11 @@ export interface MapProject {
created_at: string;
}
-/** API Key(仅返回前缀与元信息,明文 secret 仅创建/轮换时返回一次) */
+/** API Key (only the prefix and metadata are returned; the plaintext secret is returned once, on create or rotate) */
export interface MapApiKey {
id: string;
project_id: string;
- /** 归属项目名,仅跨项目聚合查询(/keys)返回,用于在接入引导中标注 Key 所属项目 */
+ /** Owning project name, returned only by the cross-project aggregate query (/keys), used in onboarding to label which project a key belongs to */
project_name?: string;
name: string;
prefix: string;
@@ -29,36 +29,36 @@ export interface MapApiKey {
created_at: string;
}
-/** 模型显式配置的接入协议。 */
+/** Access protocol explicitly configured for a model. */
export type MapModelProtocol = 'openai' | 'anthropic' | 'document_parse';
-/** 可调用的公开模型 */
+/** Public model that can be called */
export interface MapModel {
id: string;
display_name: string;
- /** 管理侧自定义模型参数量展示,例如 7B、1.5B、70B MoE */
+ /** Admin-defined parameter-count display, for example 7B, 1.5B, 70B MoE */
parameter_count?: string;
context_window: number;
max_output_tokens: number;
capabilities: Record<string, boolean>;
- /** 管理端配置的模型级默认请求参数;空对象表示不注入默认值。 */
+ /** Model-level default request parameters configured in admin; an empty object means no defaults are injected. */
parameter_config?: Record<string, unknown>;
- /** 输入价/1M(高精度 decimal 字符串);未配置定价时缺省 */
+ /** Input price per 1M (high-precision decimal string); omitted when pricing is not configured */
input_pricing?: string;
- /** 输出价/1M(高精度 decimal 字符串);未配置定价时缺省 */
+ /** Output price per 1M (high-precision decimal string); omitted when pricing is not configured */
output_pricing?: string;
- /** 限时免费:true 表示当前时间落在生效窗内、该模型按 0 计费(后端已按当前时间求值) */
+ /** Limited-time free: true means the current time is inside the effective window and the model is billed at 0 (the backend already evaluated the current time) */
is_free?: boolean;
- /** 是否支持 Anthropic Messages 协议(/v1/messages 透传),供接入示例展示协议切换 */
+ /** Whether Anthropic Messages is supported (/v1/messages pass-through), so onboarding examples can show the protocol switch */
supports_anthropic?: boolean;
- /** 模型显式配置的接入协议;空数组表示未定义标准接入协议 */
+ /** Access protocols explicitly configured for the model; an empty array means no standard access protocol is defined */
protocols?: MapModelProtocol[];
}
-/** Playground 免费体验类型;每类独立计数,用完后回退用户自有 API Key。 */
+/** Playground free-trial type; each type is counted separately, and after it is used up the flow falls back to the user's own API Key. */
export type PlaygroundTrialExperience = 'language' | 'tts' | 'realtime' | 'image-parse';
-/** Playground 免费体验状态;secret 仅内存使用,不持久化。 */
+/** Playground free-trial status; secret is used in memory only and is not persisted. */
export interface MapPlaygroundTrial {
remaining: Record<PlaygroundTrialExperience, number>;
api_key_id?: string;
@@ -66,7 +66,7 @@ export interface MapPlaygroundTrial {
secret?: string;
}
-/** 单条调用日志(请求级审计记录) */
+/** One call log (request-level audit record) */
export interface MapRequestLog {
request_id: string;
public_model: string;
@@ -78,17 +78,17 @@ export interface MapRequestLog {
completion_tokens?: number;
cache_tokens?: number;
total_tokens: number;
- /** 本次调用费用快照(decimal 字符串) */
+ /** Cost snapshot for this call (decimal string) */
cost?: string;
created_at: string;
}
-/** 公开配置(无需鉴权即可获取,如对外 Base URL) */
+/** Public config (available without auth, such as the external base URL) */
export interface MapPublicConfig {
api_base_url: string;
}
-/** 当前登录用户拥有的私有音色资源。 */
+/** Private voice resource owned by the currently logged-in user. */
export interface MapVoiceResource {
id: string;
name: string;
@@ -100,65 +100,65 @@ export interface MapVoiceResource {
updated_at: string;
}
-/** 当前登录用户可访问的产品功能。 */
+/** Product features the currently logged-in user can access. */
export interface MapFeatureAccess {
voice_clone: boolean;
}
-/** 门户用户信息 */
+/** Portal user info */
export interface MapPortalUser {
id: string;
email: string;
phone: string;
- /** 唯一登录用户名(可作登录标识之一);name 为可改的展示昵称、不唯一 */
+ /** Unique login username (one possible login identifier); name is a changeable display nickname and is not unique */
username: string;
name: string;
org_type: string;
- /** 组织状态:pending(待审核)/ active(已启用)/ disabled(已禁用) */
+ /** Organization status: pending (awaiting review) / active (enabled) / disabled (disabled) */
org_status: 'pending' | 'active' | 'disabled';
- /** 账号是否启用;false 时无法登录(正常不会出现在已登录态) */
+ /** Whether the account is enabled; false cannot log in (it normally does not appear in a logged-in session) */
account_enabled: boolean;
- /** 组织角色(external_owner 等),用于门户内项目/Key 写权限 */
+ /** Organization role (external_owner and others), used for project/key write permission inside the portal */
role: string;
- /** 平台角色:user(仅 Portal)/ admin / operator(可进 Admin 后台),决定是否显示「进入管理台」 */
+ /** Platform role: user (Portal only) / admin / operator (can enter the Admin console), which decides whether Enter admin console is shown */
platform_role: string;
default_project_id: string;
email_verified: boolean;
phone_verified: boolean;
- /** 是否已设置登录密码;未设置时账号安全页显示「设置密码」且无需当前密码 */
+ /** Whether a login password has been set; when it has not, the account security page shows Set password and does not ask for the current password */
has_password: boolean;
- /** 当前登录会话是否要求先绑定中国大陆手机号 */
+ /** Whether the current login session requires binding a mainland China phone number first */
phone_binding_required?: boolean;
}
-/** 认证响应(登录/注册/找回等共用,按场景返回不同字段) */
+/** Auth response (shared by login, register, recovery, and similar; fields vary by scenario) */
export interface MapAuthResponse {
token?: string;
user?: MapPortalUser;
- /** 密码登录的新 IP 需要二次验证时返回 true;此时不会下发 token。 */
+ /** True when a new IP for password login needs a second verification; no token is issued in that case. */
step_up_required?: boolean;
- /** 一次性密码登录二次验证令牌。 */
+ /** One-time second-verification token for password login. */
challenge_token?: string;
- /** 二次验证验证码发送渠道。 */
+ /** Channel used to send the second-verification code. */
verification_channel?: 'phone' | 'email';
- /** 二次验证验证码投递状态:queued 表示已入队等待发送,sent 表示已同步发送。 */
+ /** Second-verification code delivery status: queued means waiting to send, sent means it was sent synchronously. */
notification_status?: 'queued' | 'sent' | 'failed';
verification_required?: boolean;
verification_token?: string;
reset_token?: string;
- /** 非生产环境回显的短信验证码 */
+ /** SMS verification code echoed in non-production */
code?: string;
expires_in_seconds?: number;
is_new_user?: boolean;
}
-/** 用量汇总(各维度 token 与请求数,键为后端动态返回的指标名) */
+/** Usage summary (token and request counts by dimension; keys are metric names returned dynamically by the backend) */
export type MapUsageSummary = Record<string, number>;
-// 滑块人机验证题目为 portal/admin 共享契约,统一收口到 @map/types。
+// The slider human-verification challenge is a shared portal/admin contract, consolidated in @map/types.
export type { CaptchaChallengeDTO } from '@map/types';
-/** 本人计费账户(余额 / 额度 / 财务状态) */
+/** Current user's billing account (balance / quota / financial status) */
export interface MapBillingAccount {
billing_enabled: boolean;
balance: string;
@@ -167,13 +167,13 @@ export interface MapBillingAccount {
overdraft_limit?: string;
monthly_quota?: { Decimal: string; Valid: boolean } | null;
daily_quota?: { Decimal: string; Valid: boolean } | null;
- /** 本月已用花费(decimal 字符串) */
+ /** Spend used this month (decimal string) */
month_spend?: string;
- /** 今日已用花费(decimal 字符串) */
+ /** Spend used today (decimal string) */
today_spend?: string;
}
-/** 本人体验额度包;当前仅返回带有效期的注册赠送积分。 */
+/** Current user's trial credit package; currently only signup grant credits with an expiry are returned. */
export interface MapCreditPackage {
id: string;
source_type: 'SIGNUP_GRANT';
@@ -185,13 +185,13 @@ export interface MapCreditPackage {
created_at: string;
}
-/** 本人额度快照:新用户体验额度包与其它可用积分。 */
+/** Current user's credit snapshot: the new-user trial credit package and other available credits. */
export interface MapCreditPackageSnapshot {
list: MapCreditPackage[];
other_available_balance: string;
}
-/** 额度/余额预警配置(每用户每 scope 一条) */
+/** Quota/balance alert config (one per user per scope) */
export interface MapAlertConfig {
id?: string;
scope: 'BALANCE' | 'MONTHLY' | 'DAILY';
@@ -203,7 +203,7 @@ export interface MapAlertConfig {
updated_at?: string;
}
-/** 预警配置写入参数 */
+/** Alert config write parameters */
export interface MapAlertConfigInput {
scope: 'BALANCE' | 'MONTHLY' | 'DAILY';
enabled: boolean;
@@ -213,7 +213,7 @@ export interface MapAlertConfigInput {
channel?: string;
}
-/** 本人月账单明细快照 */
+/** Current user's monthly bill detail snapshot */
export interface MapPortalMonthlyBill {
bill_month: string;
status: string;
@@ -227,8 +227,8 @@ export interface MapPortalMonthlyBill {
cost: string;
}
-/** 充值流水 */
-/** 积分流水记录类型:管理员赠送 / 注册赠送 / 活动奖励 / 管理员扣减冲正 / 用户自助充值 */
+/** Top-up history */
+/** Credit ledger record type: admin grant / signup grant / campaign reward / admin deduction reversal / user self-service top-up */
export type MapRechargeRecordType =
| 'ADMIN_GRANT'
| 'SIGNUP_GRANT'
@@ -259,13 +259,13 @@ export interface MapRechargeRecord {
recharge_time: string;
}
-/** 易宝在线支付下单结果:cashier_url 为收银台跳转地址,order_id 为商户订单号 */
+/** Yeepay online payment order result: cashier_url is the cashier redirect URL, and order_id is the merchant order id */
export interface MapYeepayOrder {
cashier_url: string;
order_id: string;
}
-/** 按模型花费 */
+/** Spend by model */
export interface MapModelSpend {
public_model: string;
cost: string;
@@ -273,7 +273,7 @@ export interface MapModelSpend {
call_count: number;
}
-/** 按日花费 */
+/** Spend by day */
export interface MapDailySpend {
stat_date: string;
cost: string;
@@ -281,13 +281,13 @@ export interface MapDailySpend {
call_count: number;
}
-/** 按模型聚合的日趋势 */
+/** Daily trend aggregated by model */
export interface MapModelSpendTrend {
public_model: string;
trend: MapDailySpend[];
}
-/** 本人花费统计总览 */
+/** Current user's spend statistics overview */
export interface MapSpendSummary {
total_cost: string;
total_tokens: number;
@@ -305,7 +305,7 @@ export interface MapSpendSummary {
output_cost: string;
}
-/** 本人花费统计响应 */
+/** Current user's spend statistics response */
export interface MapSpendStats {
start: string;
end: string;
@@ -315,7 +315,7 @@ export interface MapSpendStats {
model_trends?: MapModelSpendTrend[];
}
-/** 调用计量明细 */
+/** Call metering detail */
export interface MapCallMetering {
request_id: string;
public_model: string;
@@ -333,7 +333,7 @@ export interface MapCallMetering {
cost: string;
}
-/** 调用详情(含请求/响应正文与计量) */
+/** Call detail (including request/response body and metering) */
export interface MapCallLogDetail extends MapRequestLog {
prompt_tokens?: number;
completion_tokens?: number;
@@ -344,9 +344,9 @@ export interface MapCallLogDetail extends MapRequestLog {
metering?: MapCallMetering | null;
}
-// ===== Playground 历史对话(每用户私有)=====
-// 这组 DTO 拆到 types.conversations.ts,两个文件才都在类型文件 500 行的硬上限内;
-// 在此原样再导出,调用方无论走 './types' 还是 '@/api/map' 都不受影响。
+// ===== Playground history conversations (private per user) =====
+// These DTOs were split into types.conversations.ts so both files stay within the 500-line hard limit for type files;
+// they are re-exported here unchanged, so callers of './types' or '@/api/map' are unaffected.
export type {
MapConversation,
@@ -357,31 +357,31 @@ export type {
ToolEventDTO,
} from './types.conversations';
-/** 提交对话反馈的请求体(点赞/点踩) */
+/** Request body for submitting conversation feedback (like/dislike) */
export interface MapFeedbackInput {
- /** 关联会话 id(新对话未保存时可省略) */
+ /** Related conversation id (may be omitted when a new conversation has not been saved) */
conversation_id?: string;
- /** 被反馈回答对应的平台 L2 请求 ID */
+ /** Platform L2 request ID of the answer being rated */
request_id?: string;
- /** 被反馈回答对应的客户端关联 ID,用于服务端精确回查平台请求 ID */
+ /** Client correlation ID of the answer being rated, used by the server to look up the platform request ID precisely */
client_request_id?: string;
- /** 被反馈回答实际使用的 API Key ID,用于限定关联范围 */
+ /** API Key ID actually used by the answer being rated, used to limit the correlation scope */
api_key_id?: string;
- /** 反馈时所用模型(= MapModel.id / public_model) */
+ /** Model used when the feedback was submitted (= MapModel.id / public_model) */
public_model: string;
- /** 反馈类型:赞 up / 踩 down */
+ /** Feedback type: like is up / dislike is down */
feedback_type: 'up' | 'down';
- /** 原因标签(点踩可选,点赞为空数组) */
+ /** Reason tags (optional for dislike, empty array for like) */
reasons: string[];
- /** 反馈正文(点踩可选填写) */
+ /** Feedback body (optional text for dislike) */
comment?: string;
- /** 问题快照(该回答对应的用户提问) */
+ /** Question snapshot (the user question for this answer) */
question: string;
- /** 回答快照(被反馈的助手正文) */
+ /** Answer snapshot (the assistant body being rated) */
answer: string;
}
-/** 提交反馈的返回(落库后的记录元信息) */
+/** Feedback submit response (record metadata after it is stored) */
export interface MapFeedback {
id: string;
feedback_type: 'up' | 'down';
diff --git a/webdemo/frontend/src/components/BillingAlertBanner.tsx b/webdemo/frontend/src/components/BillingAlertBanner.tsx
index 6ba5875..32f03e7 100644
--- a/webdemo/frontend/src/components/BillingAlertBanner.tsx
+++ b/webdemo/frontend/src/components/BillingAlertBanner.tsx
@@ -4,7 +4,7 @@ import { useAlertConfigsQuery, useBillingAccountQuery, type MapAlertConfig } fro
import { formatPoints } from '@/utils/money';
import { useAppStore } from '@map/store';
-/** NullDecimal → number(未设置时返回 null 表示「不限」) */
+/** NullDecimal → number (returns null when unset, meaning "unlimited"). */
function quotaNum(q?: { Decimal: string; Valid: boolean } | null): number | null {
if (!q || !q.Valid) return null;
const n = Number(q.Decimal);
@@ -16,7 +16,7 @@ interface Alert {
text: string;
}
-/** 依据账户状态与预警配置,计算需要展示的最高优先级提醒 */
+/** From account status and alert settings, pick the highest-priority notice to show. */
function evaluate(
account: ReturnType<typeof useBillingAccountQuery>['data'],
configs: MapAlertConfig[],
@@ -26,7 +26,7 @@ function evaluate(
if (!account?.billing_enabled) return null;
const balance = Number(account.balance ?? 0);
- // 关键级:欠费或余额耗尽。
+ // Critical: overdue or balance exhausted.
if (account.financial_status === 'ARREARS') {
return { level: 'error', text: t('billingAlert.inArrears') };
}
@@ -37,7 +37,7 @@ function evaluate(
const cfg = (scope: MapAlertConfig['scope']) =>
configs.find((c) => c.scope === scope && c.enabled);
- // 余额预警(金额阈值)。阈值存储为元,对外统一以积分展示。
+ // Balance alert (amount threshold). The threshold is stored in yuan and shown to users as points.
const bal = cfg('BALANCE');
if (bal?.threshold_amount?.Valid) {
const threshold = Number(bal.threshold_amount.Decimal);
@@ -51,7 +51,7 @@ function evaluate(
}
}
- // 月额度用量百分比预警。
+ // Monthly quota usage-percentage alert.
const monthQuota = quotaNum(account.monthly_quota);
const month = cfg('MONTHLY');
if (month?.threshold_percent != null && monthQuota && monthQuota > 0) {
@@ -64,7 +64,7 @@ function evaluate(
}
}
- // 日额度用量百分比预警。
+ // Daily quota usage-percentage alert.
const dayQuota = quotaNum(account.daily_quota);
const day = cfg('DAILY');
if (day?.threshold_percent != null && dayQuota && dayQuota > 0) {
@@ -81,10 +81,10 @@ function evaluate(
}
/**
- * 顶部计费预警横幅(全局)。
+ * Global billing alert banner at the top.
*
- * 触发:账户已开通计费且处于欠费/余额耗尽(error)或命中用户配置的余额/额度预警阈值(warning)。
- * 视觉:error 用 destructive 色、warning 用 warning 色;附「前往总览」入口。
+ * Trigger: billing is enabled and the account is overdue or out of balance (error), or a user-configured balance or quota alert threshold is hit (warning).
+ * Visual: error uses the destructive color, warning uses the warning color, with a "Go to overview" entry.
*/
export function BillingAlertBanner() {
const { t } = useTranslation('shell');
diff --git a/webdemo/frontend/src/components/CaptchaDialog.tsx b/webdemo/frontend/src/components/CaptchaDialog.tsx
index 2c51d98..4a0a73c 100644
--- a/webdemo/frontend/src/components/CaptchaDialog.tsx
+++ b/webdemo/frontend/src/components/CaptchaDialog.tsx
@@ -9,7 +9,7 @@ import {
} from '@map/ui';
import { useTranslation } from 'react-i18next';
-/** CaptchaDialog 入参(由 useCaptchaGate 的 dialogProps 提供) */
+/** CaptchaDialog props (supplied by dialogProps from useCaptchaGate). */
export interface CaptchaDialogProps {
open: boolean;
challenge: SlideCaptchaChallenge | null;
@@ -22,8 +22,8 @@ export interface CaptchaDialogProps {
}
/**
- * 人机验证弹窗(拼图滑块)。纯展示:渲染标题 + SlideCaptcha,事件透传给 useCaptchaGate。
- * 用途:登录/发码前置的安全验证弹层,与 useCaptchaGate 配套使用。
+ * Captcha dialog (slide puzzle). Presentation only: renders the title and SlideCaptcha, and forwards events to useCaptchaGate.
+ * Purpose: the security check shown before login or sending a code, used together with useCaptchaGate.
*/
export function CaptchaDialog({
open,
diff --git a/webdemo/frontend/src/components/ErrorBoundary.tsx b/webdemo/frontend/src/components/ErrorBoundary.tsx
index 84c9083..720c11d 100644
--- a/webdemo/frontend/src/components/ErrorBoundary.tsx
+++ b/webdemo/frontend/src/components/ErrorBoundary.tsx
@@ -31,11 +31,11 @@ interface ErrorBoundaryViewProps extends Props {
}
/**
- * 国际化错误边界。
+ * Internationalized error boundary.
*
- * 用途:在路由或应用渲染异常时保留重试入口,并让已显示的降级界面响应语言切换。
- * @param props 子节点、可选自定义降级界面与渲染级别。
- * @returns 捕获子树渲染异常的边界组件。
+ * Purpose: keep a retry entry when a route or the app fails to render, and let an already shown fallback respond to language changes.
+ * @param props Children, an optional custom fallback, and the render level.
+ * @returns A boundary that catches render errors in its subtree.
*/
export function ErrorBoundary({ children, fallback, level }: Props) {
const { t } = useTranslation('status');
diff --git a/webdemo/frontend/src/components/LimitedFreeTag.tsx b/webdemo/frontend/src/components/LimitedFreeTag.tsx
index 4421c6d..2ec7af3 100644
--- a/webdemo/frontend/src/components/LimitedFreeTag.tsx
+++ b/webdemo/frontend/src/components/LimitedFreeTag.tsx
@@ -2,10 +2,10 @@ import { Badge } from '@map/ui';
import { useTranslation } from 'react-i18next';
/**
- * 「免费调用」标签:模型当前落在定价免费时间窗内时紧跟模型名展示。
- * 门户下拉(顶栏)与模型列表页共用一份,保证文案与样式一致;容器侧用 items-center 令其与名字垂直居中。
- * @param className 额外类名(如列表项内的行内对齐间距)
- * @returns 免费调用小徽标
+ * "Free calls" tag: shown next to the model name while the model is inside its free pricing window.
+ * The portal dropdown (top bar) and the model list share one component so the copy and style stay consistent; the container uses items-center so it lines up with the name.
+ * @param className Extra classes (for example inline spacing inside a list item).
+ * @returns The small free-calls badge.
*/
export function LimitedFreeTag({ className }: { className?: string }) {
const { t } = useTranslation('models');
diff --git a/webdemo/frontend/src/components/LocaleSwitcher.tsx b/webdemo/frontend/src/components/LocaleSwitcher.tsx
index dc02af9..4aa4aa8 100644
--- a/webdemo/frontend/src/components/LocaleSwitcher.tsx
+++ b/webdemo/frontend/src/components/LocaleSwitcher.tsx
@@ -10,11 +10,11 @@ interface LocaleSwitcherProps {
}
/**
- * 门户语言切换控件。
- * 用途:在不刷新页面的前提下切换中英文界面,并保证鼠标、触摸和键盘均可操作。
- * @param variant 控件呈现形式;文档页使用文字形式避免孤立图标难以辨识。
- * @param className 追加到按钮的样式类。
- * @returns 语言切换按钮与说明 Tooltip。
+ * Portal language switcher.
+ * Purpose: switch the Chinese and English UI without reloading the page, and keep it usable with mouse, touch, and keyboard.
+ * @param variant How the control is presented; docs pages use text so a lone icon is not hard to recognize.
+ * @param className Classes appended to the button.
+ * @returns The language button and its explanatory tooltip.
*/
export function LocaleSwitcher({ variant = 'icon', className }: LocaleSwitcherProps) {
const locale = useAppStore((state) => state.locale);
diff --git a/webdemo/frontend/src/components/ModelbestMark.tsx b/webdemo/frontend/src/components/ModelbestMark.tsx
index dc812d5..4a8949d 100644
--- a/webdemo/frontend/src/components/ModelbestMark.tsx
+++ b/webdemo/frontend/src/components/ModelbestMark.tsx
@@ -4,13 +4,13 @@ interface ModelbestMarkProps {
}
/**
- * ModelBest 品牌图标(仅图形 M 标,不含文字)。
+ * ModelBest brand mark (the M graphic only, no wordmark).
*
- * 用途:用于侧栏 / 顶栏的方形品牌位、折叠态等需要纯图标的场景(横版字标见 BrandLogo)。
- * path 取自官方 logo 的蓝色图形部分;颜色用 currentColor 继承,便于在 primary 底色块上反白。
+ * Purpose: square brand slots in the sidebar and top bar, and other places that need an icon alone (see BrandLogo for the horizontal wordmark).
+ * The path is the blue graphic from the official logo; color inherits currentColor so it can reverse to white on a primary background.
*
- * @param size 像素尺寸(宽高一致)
- * @param className 附加样式(如 text-primary-foreground 控制颜色)
+ * @param size Size in pixels (width and height match).
+ * @param className Extra styles (for example text-primary-foreground to set the color).
*/
export function ModelbestMark({ size = 20, className }: ModelbestMarkProps) {
return (
diff --git a/webdemo/frontend/src/components/PageLoading.tsx b/webdemo/frontend/src/components/PageLoading.tsx
index c97dec7..842e47c 100644
--- a/webdemo/frontend/src/components/PageLoading.tsx
+++ b/webdemo/frontend/src/components/PageLoading.tsx
@@ -1,13 +1,13 @@
import { useTranslation } from 'react-i18next';
/**
- * 页面级加载占位。
+ * Page-level loading placeholder.
*
- * 用途:作为受保护路由(AdminLayout 内)懒加载页面的 Suspense fallback,
- * 在 chunk 拉取期间填充内容区,避免布局塌陷与白屏闪烁。
+ * Purpose: Suspense fallback for lazy pages inside protected routes (AdminLayout),
+ * filling the content area while the chunk loads so the layout does not collapse or flash white.
*
- * 设计:纯语义 token(不写裸色值),仅三个呼吸点,与登录页 LoginFallback 风格统一;
- * 尊重 prefers-reduced-motion 由全局动画策略兜底。
+ * Design: semantic tokens only (no raw color values), just three breathing dots, matching the login page LoginFallback;
+ * prefers-reduced-motion is handled by the global motion policy.
*/
export function PageLoading() {
const { t } = useTranslation('status');
diff --git a/webdemo/frontend/src/components/PageTransition.tsx b/webdemo/frontend/src/components/PageTransition.tsx
index 2b35048..8a947af 100644
--- a/webdemo/frontend/src/components/PageTransition.tsx
+++ b/webdemo/frontend/src/components/PageTransition.tsx
@@ -5,10 +5,10 @@ interface PageTransitionProps {
}
/**
- * 顶层页面入场过渡容器。
+ * Top-level page entrance container.
*
- * 用途:承接 AdminLayout 的内容区域布局。这里不再挂载入场动画,避免路由型 tab
- * 或内容重挂载时出现整块页面闪烁。
+ * Purpose: holds the AdminLayout content region. It no longer mounts an entrance animation, so route-style tabs
+ * or remounted content do not flash the whole page.
*/
export function PageTransition({ children }: PageTransitionProps) {
return <div className="min-h-0 flex-1">{children}</div>;
diff --git a/webdemo/frontend/src/config/brand.ts b/webdemo/frontend/src/config/brand.ts
index 37d95a8..b36837b 100644
--- a/webdemo/frontend/src/config/brand.ts
+++ b/webdemo/frontend/src/config/brand.ts
@@ -1,13 +1,13 @@
-/** 应用品牌常量——用户可见文案的单一来源(内部包名 @map/* 保持不变)。 */
+/** App brand constants — the single source of user-visible copy (internal package names @map/* stay unchanged). */
-/** 产品名 */
+/** Product name. */
export const APP_NAME = 'MiniCPM-OCR';
-/** 浏览器标签页默认标题 */
+/** Default browser tab title. */
export const APP_TITLE = APP_NAME;
-/** 页面标语 */
+/** Page tagline. */
export const APP_TAGLINE = 'Document parse';
-/** 页脚版权文案 */
+/** Footer copyright copy. */
export const APP_COPYRIGHT = `© 2026 OpenBMB.`;
diff --git a/webdemo/frontend/src/config/env.ts b/webdemo/frontend/src/config/env.ts
index 3ed96dc..789758a 100644
--- a/webdemo/frontend/src/config/env.ts
+++ b/webdemo/frontend/src/config/env.ts
@@ -6,7 +6,7 @@ const clientEnvSchema = z.object({
VITE_APP_TITLE: z.string().optional(),
VITE_API_TIMEOUT_MS: z.coerce.number().positive().optional(),
VITE_API_DEBUG: z.enum(['true', 'false']).optional(),
- // MAP 后端基路径(裸 JSON,独立于通用 /api),默认 /map-api 由 Vite/Nginx 代理
+ // MAP backend base path (raw JSON, separate from the generic /api). Defaults to /map-api, proxied by Vite or Nginx.
VITE_MAP_API_BASE_URL: z.string().default('/map-api'),
VITE_DEFAULT_LOCALE: z.enum(['zh-CN', 'en-US']).default('zh-CN'),
VITE_AUTH_PROFILE: z.enum(['legacy', 'gcp']).default('legacy'),
@@ -16,8 +16,8 @@ const clientEnvSchema = z.object({
export type ClientEnv = z.infer<typeof clientEnvSchema>;
/**
- * 启动时校验与 import.meta.env 同步的 VITE_* 变量,避免部署后才发现配置错误。
- * 校验失败会抛出带可读信息的 Error。
+ * Validate VITE_* variables against import.meta.env at startup, so misconfiguration is not discovered only after deploy.
+ * A failed check throws an Error with a readable message.
*/
export function validateClientEnv(): ClientEnv {
return clientEnvSchema.parse({
diff --git a/webdemo/frontend/src/hooks/__tests__/useCaptchaGate.test.tsx b/webdemo/frontend/src/hooks/__tests__/useCaptchaGate.test.tsx
index 4e89e47..2721e66 100644
--- a/webdemo/frontend/src/hooks/__tests__/useCaptchaGate.test.tsx
+++ b/webdemo/frontend/src/hooks/__tests__/useCaptchaGate.test.tsx
@@ -5,7 +5,7 @@ import type { ReactNode } from 'react';
import { setApplicationLocale } from '@/i18n';
import { useCaptchaGate } from '../useCaptchaGate';
-// mock 认证 API,隔离网络
+// Mock the auth API so the test stays off the network.
const publicConfig = vi.fn();
const getCaptcha = vi.fn();
const verifyCaptcha = vi.fn();
@@ -66,7 +66,7 @@ describe('useCaptchaGate', () => {
void result.current.runWithCaptcha(action);
});
- // 弹窗打开、取题被调用,但动作在验证通过前不执行
+ // The dialog opens and a challenge is fetched, but the action does not run until verification passes.
await waitFor(() => expect(result.current.dialogProps.open).toBe(true));
await waitFor(() => expect(getCaptcha).toHaveBeenCalledTimes(1));
expect(action).not.toHaveBeenCalled();
@@ -111,7 +111,7 @@ describe('useCaptchaGate', () => {
});
await waitFor(() => expect(result.current.dialogProps.open).toBe(true));
- // 模拟用户拖动释放
+ // Simulate the user releasing the drag.
await act(async () => {
result.current.dialogProps.onConfirm({ x: 100, y: 2 }, () => {});
await pending;
diff --git a/webdemo/frontend/src/hooks/useCaptchaGate.ts b/webdemo/frontend/src/hooks/useCaptchaGate.ts
index 20b9c3e..59d3f58 100644
--- a/webdemo/frontend/src/hooks/useCaptchaGate.ts
+++ b/webdemo/frontend/src/hooks/useCaptchaGate.ts
@@ -4,17 +4,17 @@ import type { SlideCaptchaChallenge } from '@map/ui';
import { useTranslation } from 'react-i18next';
import { mapAuthApi } from '@/api/map';
-/** 等待人机验证结果的 resolver */
+/** Resolver waiting for the captcha result. */
interface Resolver {
resolve: (captchaId: string) => void;
reject: (err: unknown) => void;
}
-/** useCaptchaGate 返回值 */
+/** Return value of useCaptchaGate. */
export interface CaptchaGate {
- /** 是否启用人机验证(后端配置探测) */
+ /** Whether captcha is enabled (probed from backend config). */
enabled: boolean;
- /** 传给 CaptchaDialog 的受控属性 */
+ /** Controlled props passed to CaptchaDialog. */
dialogProps: {
open: boolean;
challenge: SlideCaptchaChallenge | null;
@@ -26,17 +26,17 @@ export interface CaptchaGate {
onOpenChange: (open: boolean) => void;
};
/**
- * 用人机验证「门」包裹一个动作:未启用时直接执行(captchaId='');
- * 启用时弹出滑块,验证通过后用拿到的一次性凭证执行 action;用户取消则 reject。
+ * Wrap an action in a captcha gate: when captcha is off, run it directly (captchaId='');
+ * when it is on, open the slider, and after verification run the action with the one-time token; if the user cancels, reject.
*/
runWithCaptcha: <T>(action: (captchaId: string) => Promise<T>) => Promise<T>;
}
/**
- * 人机验证编排 hook(发码/登录前置)。
+ * Captcha orchestration hook (before sending a code or logging in).
*
- * 用途:把「取题 → 弹窗滑块 → 校验落点 → 拿一次性凭证 → 执行受保护动作」的流程收敛到一处,
- * 供登录、找回密码、绑定邮箱等发码/登录调用点复用。仅编排逻辑,不渲染 UI(视图见 CaptchaDialog)。
+ * Purpose: gather "fetch a challenge → show the slider → check the drop point → take a one-time token → run the protected action" in one place,
+ * for login, password recovery, email binding, and other code or login call sites. Logic only; it does not render UI (see CaptchaDialog).
*/
export function useCaptchaGate(): CaptchaGate {
const { t } = useTranslation('status');
@@ -60,7 +60,7 @@ export function useCaptchaGate(): CaptchaGate {
const challengeRequestRef = useRef(0);
const completionTimerRef = useRef<number | null>(null);
- /** 取一道新题并填充到弹窗 */
+ /** Fetch a new challenge and fill it into the dialog. */
const loadChallenge = useCallback(async (session: number) => {
const request = ++challengeRequestRef.current;
setStatus('default');
@@ -110,7 +110,7 @@ export function useCaptchaGate(): CaptchaGate {
async <T,>(action: (captchaId: string) => Promise<T>): Promise<T> => {
if (!enabled) return action('');
if (resolverRef.current) {
- // 已有验证流程进行中,避免重复弹窗
+ // A verification flow is already in progress; do not open another dialog.
return Promise.reject(new Error('captcha in progress'));
}
const captchaId = await new Promise<string>((resolve, reject) => {
@@ -124,7 +124,7 @@ export function useCaptchaGate(): CaptchaGate {
[enabled, loadChallenge],
);
- /** 用户拖动释放:校验落点。通过则保持滑块停留并短暂展示成功态后再关闭放行;失败则换一题重试。 */
+ /** User releases the drag: check the drop point. On success, leave the slider in place, show the success state briefly, then close and continue; on failure, load a new challenge and retry. */
const onConfirm = useCallback(
async (point: { x: number; y: number }, reset: () => void) => {
if (verifyingRef.current || completingRef.current) return;
@@ -133,7 +133,7 @@ export function useCaptchaGate(): CaptchaGate {
try {
const res = await mapAuthApi.verifyCaptcha({ id: idRef.current, x: point.x, y: point.y });
if (session !== sessionRef.current || !resolverRef.current) return;
- // 成功:标记成功态,滑块停在缺口处不复位,停留约 0.6s 让用户看到反馈后再关闭放行。
+ // Success: mark the success state, leave the slider in the gap without resetting, wait about 0.6s so the user sees the feedback, then close and continue.
completingRef.current = true;
setStatus('success');
completionTimerRef.current = window.setTimeout(() => {
@@ -147,7 +147,7 @@ export function useCaptchaGate(): CaptchaGate {
}, 600);
} catch {
if (session !== sessionRef.current || !resolverRef.current) return;
- // 校验失败(落点不对/题目过期):先闪红,短暂停留后复位并换一道新题。
+ // Check failed (wrong drop point or expired challenge): flash red, pause briefly, then reset and load a new challenge.
setStatus('error');
window.setTimeout(() => {
if (session !== sessionRef.current || !resolverRef.current) return;
@@ -166,7 +166,7 @@ export function useCaptchaGate(): CaptchaGate {
void loadChallenge(sessionRef.current);
}, [loadChallenge]);
- /** 关闭弹窗视为取消,reject 等待中的动作 */
+ /** Closing the dialog counts as cancel and rejects the waiting action. */
const onOpenChange = useCallback((next: boolean) => {
if (next) return;
sessionRef.current += 1;
diff --git a/webdemo/frontend/src/hooks/useThemeSync.ts b/webdemo/frontend/src/hooks/useThemeSync.ts
index a0bf379..342ff07 100644
--- a/webdemo/frontend/src/hooks/useThemeSync.ts
+++ b/webdemo/frontend/src/hooks/useThemeSync.ts
@@ -78,13 +78,13 @@ function applyFallbackDark(isDark: boolean) {
}
/**
- * 应用明暗主题。
+ * Apply the light or dark theme.
*
- * 用途:首屏直接同步主题;后续切换优先使用 View Transition 做合成层淡入淡出,
- * 避免给全量 DOM 注入 transition 导致长表格/大量卡片一起重算而卡顿。降级路径只给
- * 主要布局与控件做短色彩过渡,并尊重 reduced motion。
+ * Purpose: the first screen syncs the theme directly. Later switches prefer a View Transition cross-fade on the compositor,
+ * so a transition is not injected on the whole DOM, which would restyle long tables and many cards together and stutter. The fallback only gives
+ * the main layout and controls a short color transition, and it respects reduced motion.
*
- * @param instant 首屏初始化时直接应用,不放动画。
+ * @param instant On first-screen init, apply directly with no animation.
*/
function applyDark(isDark: boolean, instant: boolean) {
if (instant || prefersReducedMotion()) {
diff --git a/webdemo/frontend/src/i18n/format.ts b/webdemo/frontend/src/i18n/format.ts
index 532c311..cdc1d91 100644
--- a/webdemo/frontend/src/i18n/format.ts
+++ b/webdemo/frontend/src/i18n/format.ts
@@ -12,30 +12,30 @@ const DATE_TIME_FORMAT_OPTIONS: Intl.DateTimeFormatOptions = {
};
/**
- * 按当前界面语言格式化数值。
- * @param value 待格式化数值。
- * @param locale 当前界面语言。
- * @returns 面向界面展示的本地化数值。
+ * Format a number for the current UI language.
+ * @param value Number to format.
+ * @param locale Current UI language.
+ * @returns Localized number for display.
*/
export function formatNumber(value: number, locale: AppLocale): string {
return new Intl.NumberFormat(locale, { maximumFractionDigits: 6 }).format(value);
}
/**
- * 按当前界面语言格式化日期。
- * @param value 待格式化日期。
- * @param locale 当前界面语言。
- * @returns 面向界面展示的本地化日期。
+ * Format a date for the current UI language.
+ * @param value Date to format.
+ * @param locale Current UI language.
+ * @returns Localized date for display.
*/
export function formatDate(value: Date, locale: AppLocale): string {
return new Intl.DateTimeFormat(locale, DATE_FORMAT_OPTIONS).format(value);
}
/**
- * 按当前界面语言和平台业务时区格式化日期时间。
- * @param value 待格式化日期。
- * @param locale 当前界面语言。
- * @returns 面向界面展示的本地化日期时间。
+ * Format a date and time for the current UI language and the platform business timezone.
+ * @param value Date to format.
+ * @param locale Current UI language.
+ * @returns Localized date and time for display.
*/
export function formatDateTime(value: Date, locale: AppLocale): string {
return new Intl.DateTimeFormat(locale, DATE_TIME_FORMAT_OPTIONS).format(value);
diff --git a/webdemo/frontend/src/i18n/index.ts b/webdemo/frontend/src/i18n/index.ts
index ac826a3..a600530 100644
--- a/webdemo/frontend/src/i18n/index.ts
+++ b/webdemo/frontend/src/i18n/index.ts
@@ -6,7 +6,7 @@ import { i18nResources } from './resources';
const configuredDefaultLocale: AppLocale =
import.meta.env.VITE_DEFAULT_LOCALE === 'en-US' ? 'en-US' : 'zh-CN';
-// 仅在当前站点没有持久化偏好时应用部署默认语言;已有用户选择不被环境切换覆盖。
+// Apply the deploy default language only when this site has no persisted preference; an existing user choice is not overwritten by an environment switch.
if (typeof window !== 'undefined' && !window.localStorage.getItem('map-app')) {
useAppStore.getState().setLocale(configuredDefaultLocale);
}
@@ -17,7 +17,7 @@ i18n.use(initReactI18next).init({
fallbackLng: 'zh-CN',
defaultNS: 'shell',
interpolation: { escapeValue: false },
- // 资源随前端 bundle 一同加载,可同步初始化以避免首帧出现翻译键。
+ // Resources ship in the frontend bundle and can be initialized synchronously so the first frame does not show translation keys.
initAsync: false,
});
@@ -28,9 +28,9 @@ i18n.on('languageChanged', (language) => {
syncDocumentLanguage(i18n.language);
/**
- * 切换门户界面语言并同步持久化偏好。
- * @param locale 目标界面语言。
- * @returns 语言资源完成切换后的 Promise。
+ * Switch the portal UI language and persist the preference.
+ * @param locale Target UI language.
+ * @returns Promise that resolves when the language resources have switched.
*/
export async function setApplicationLocale(locale: AppLocale): Promise<void> {
useAppStore.getState().setLocale(locale);
@@ -40,8 +40,8 @@ export async function setApplicationLocale(locale: AppLocale): Promise<void> {
export default i18n;
/**
- * 将当前语言同步到文档根节点,供浏览器与辅助技术识别内容语言。
- * @param locale i18next 当前语言。
+ * Sync the current language onto the document root so browsers and assistive technologies can recognize the content language.
+ * @param locale Current i18next language.
*/
function syncDocumentLanguage(locale: string): void {
document.documentElement.lang = locale === 'en-US' ? 'en-US' : 'zh-CN';
diff --git a/webdemo/frontend/src/i18n/messages/playground.ts b/webdemo/frontend/src/i18n/messages/playground.ts
index 0f9f57d..97108ea 100644
--- a/webdemo/frontend/src/i18n/messages/playground.ts
+++ b/webdemo/frontend/src/i18n/messages/playground.ts
@@ -6,6 +6,7 @@ const zhCN = {
tts: '语音合成',
realtime: '实时音视频',
imageParse: '图片文档解析',
+ fieldExtract: '关键信息抽取',
selectModel: '选择模型',
newConversation: '新建对话',
send: '发送',
@@ -878,6 +879,7 @@ const enUS = {
tts: 'Text to Speech',
realtime: 'Realtime Audio & Video',
imageParse: 'Image Document Parsing',
+ fieldExtract: 'Key information extraction',
selectModel: 'Select model',
newConversation: 'New conversation',
send: 'Send',
diff --git a/webdemo/frontend/src/i18n/resources.ts b/webdemo/frontend/src/i18n/resources.ts
index fbce471..0507693 100644
--- a/webdemo/frontend/src/i18n/resources.ts
+++ b/webdemo/frontend/src/i18n/resources.ts
@@ -11,10 +11,10 @@ import { docsMessages } from './messages/docs';
import { voicesMessages } from './messages/voices';
/**
- * 门户全部本地化资源的纯数据导出。
+ * Pure-data export of every portal localization resource.
*
- * 用途:供 i18next 初始化与仓库根目录的文案审核脚本直接导入。
- * 该模块刻意不依赖 React、Zustand 或浏览器 API,以确保 Node 环境可稳定读取。
+ * Purpose: imported by i18next initialization and by the copy-review script at the repo root.
+ * This module deliberately avoids React, Zustand, and browser APIs so Node can read it reliably.
*/
export const i18nResources = {
'zh-CN': {
diff --git a/webdemo/frontend/src/i18n/types.ts b/webdemo/frontend/src/i18n/types.ts
index fc98b17..60417da 100644
--- a/webdemo/frontend/src/i18n/types.ts
+++ b/webdemo/frontend/src/i18n/types.ts
@@ -1,6 +1,6 @@
/**
- * 将基准语言资源映射为值均为字符串的同构资源类型。
- * @template T 基准语言资源的结构。
+ * Map a base-language resource to an isomorphic resource type whose values are all strings.
+ * @template T Structure of the base-language resource.
*/
export type TranslationShape<T> = T extends string
? string
diff --git a/webdemo/frontend/src/index.css b/webdemo/frontend/src/index.css
index 53b3650..a80eab8 100644
--- a/webdemo/frontend/src/index.css
+++ b/webdemo/frontend/src/index.css
@@ -162,8 +162,8 @@
}
}
-/* 图像解析扫描带:自身高度为容器 14%,714% 位移刚好把它推到容器底部。
- 下行再上行构成一个来回,像扫描头而不是每轮硬跳回顶部。 */
+/* Image-parse scan band: its own height is 14% of the container, and a 714% translation pushes it exactly to the container bottom.
+ Down then up makes one round trip, like a scan head, rather than jumping hard back to the top each cycle. */
@keyframes map-image-scan {
0% {
transform: translateY(-100%);
@@ -176,7 +176,7 @@
}
}
-/* 版面框检出:逐个出现,200ms 落在项目规范的入场区间内 */
+/* Layout boxes appearing: they show up one by one; 200ms sits inside the project entrance-motion range. */
@keyframes map-layout-box-in {
from {
opacity: 0;
diff --git a/webdemo/frontend/src/layouts/AdminLayout.tsx b/webdemo/frontend/src/layouts/AdminLayout.tsx
index dc51d1c..bc00253 100644
--- a/webdemo/frontend/src/layouts/AdminLayout.tsx
+++ b/webdemo/frontend/src/layouts/AdminLayout.tsx
@@ -49,7 +49,7 @@ export function AdminLayout() {
}, ANIM_MS);
}, []);
- // 视口从移动端切回桌面端时,重置移动抽屉状态(同步外部视口条件,需在 effect 内 setState)
+ // When the viewport switches from mobile back to desktop, reset the mobile drawer state (syncing an external viewport condition; setState must run inside the effect).
useEffect(() => {
if (!isMobile && mounted) {
/* eslint-disable react-hooks/set-state-in-effect */
@@ -157,7 +157,7 @@ export function AdminLayout() {
{(effectiveMode === 'top' || effectiveMode === 'mixed') && (
<InlineBreadcrumb pathname={pathname} />
)}
- {/* 计费预警横幅:欠费/余额耗尽或命中用户配置的预警阈值时提醒 */}
+ {/* Billing alert banner: shown when the account is overdue, out of balance, or hits a user-configured alert threshold. */}
<BillingAlertBanner />
<PageTransition key={routeKey}>
<Outlet />
@@ -165,7 +165,7 @@ export function AdminLayout() {
</div>
</OverlayScrollArea>
</div>
- {/* 备案/版权:仅在总览页(/)展示,合规上首页可见即可,其余内页隐藏保持简洁 */}
+ {/* Filing and copyright: shown only on the overview page (/). Compliance only needs the home page; other inner pages stay hidden to keep them simple. */}
{pathname === '/' && <SiteFooter variant="inline" className="shrink-0" />}
</div>
</div>
diff --git a/webdemo/frontend/src/layouts/BlankLayout.tsx b/webdemo/frontend/src/layouts/BlankLayout.tsx
index bd735b5..db5b59b 100644
--- a/webdemo/frontend/src/layouts/BlankLayout.tsx
+++ b/webdemo/frontend/src/layouts/BlankLayout.tsx
@@ -2,13 +2,13 @@ import { Outlet, useLocation } from 'react-router-dom';
import { LocaleSwitcher } from '@/components/LocaleSwitcher';
/**
- * 门户空白布局。
- * 用途:为登录、错误和公开页面保留统一的语言切换入口,不干预各页面自己的内容布局。
- * @returns 带语言切换入口的子路由容器。
+ * Blank portal layout.
+ * Purpose: keep one language switcher on login, error, and public pages without changing each page's own content layout.
+ * @returns A child-route container with a language switcher.
*/
export function BlankLayout() {
const { pathname } = useLocation();
- // 协议页和体验中心都有自己的顶栏控件,避免全局浮层覆盖页面内容。
+ // Agreement pages and the Playground have their own top-bar controls, so a global overlay does not cover page content.
const showFloatingLocaleSwitcher =
!pathname.startsWith('/playground') && !pathname.startsWith('/legal');
diff --git a/webdemo/frontend/src/layouts/components/DailyCheckinCard.tsx b/webdemo/frontend/src/layouts/components/DailyCheckinCard.tsx
index 8996c8c..d2814d2 100644
--- a/webdemo/frontend/src/layouts/components/DailyCheckinCard.tsx
+++ b/webdemo/frontend/src/layouts/components/DailyCheckinCard.tsx
@@ -11,10 +11,10 @@ interface DailyCheckinCardProps {
}
/**
- * 用户门户侧边栏的每日签到入口:展示今日奖励,并以现有幂等接口领取积分。
+ * Daily check-in entry in the user portal sidebar: shows today's reward and claims points through the existing idempotent API.
*
- * @param props 签到状态、侧边栏状态与领取回调
- * @returns 可领取、领取中、已领取或隐藏状态对应的权益卡
+ * @param props Check-in status, sidebar state, and the claim callback.
+ * @returns The benefit card for claimable, claiming, claimed, or hidden.
*/
export function DailyCheckinCard({
collapsed,
@@ -102,7 +102,7 @@ export function DailyCheckinCard({
);
}
-/** 将签到积分展示为紧凑整数;若活动配置了小数奖励则保留最多两位有效小数。 */
+/** Show check-in points as a compact integer; if the campaign configured a fractional reward, keep at most two significant decimal places. */
function formatDailyPoints(value: string, locale: string): string {
const amount = Number(value);
if (!Number.isFinite(amount)) return value;
diff --git a/webdemo/frontend/src/layouts/components/Header.tsx b/webdemo/frontend/src/layouts/components/Header.tsx
index 41f6f83..2d64f34 100644
--- a/webdemo/frontend/src/layouts/components/Header.tsx
+++ b/webdemo/frontend/src/layouts/components/Header.tsx
@@ -20,9 +20,9 @@ interface HeaderProps {
export function Header({ isMobile, onMenuToggle, topNav, showLogo }: HeaderProps) {
const { t } = useTranslation('shell');
- // 首帧即可从 localStorage 同步读出登录态,据此决定右侧渲染,避免刷新时先闪「登录」按钮
+ // The first frame can read login state synchronously from localStorage and decide the right-side render, so a refresh does not flash the "Log in" button first.
const hasToken = Boolean(getToken());
- // 当前用户信息:照搬老 portal,登录后查 /me(仅在有 token 时启用)
+ // Current user: mirrors the old portal, and queries /me after login (enabled only when a token exists).
const meQuery = useQuery({
queryKey: mapKeys.me(),
queryFn: mapAuthApi.me,
@@ -82,7 +82,7 @@ export function Header({ isMobile, onMenuToggle, topNav, showLogo }: HeaderProps
</button>
)}
- {/* Logo — top 模式始终显示;mixed 模式在无侧栏时显示(有二级菜单时 Logo 在侧栏) */}
+ {/* Logo — always shown in top mode; in mixed mode, shown when there is no sidebar (when there is a second-level menu, the logo is in the sidebar). */}
{!isMobile && showLogo && (
<Link to="/" className="flex items-center gap-2 shrink-0 mr-1">
<div className="flex h-8 w-8 items-center justify-center rounded-lg bg-primary shadow-sm shadow-primary/25">
@@ -144,7 +144,7 @@ export function Header({ isMobile, onMenuToggle, topNav, showLogo }: HeaderProps
{/* Right */}
<div className="flex items-center gap-1">
<LocaleSwitcher />
- {/* 三态:已拿到用户 → 用户菜单;有 token 且 /me 未失败 → 骨架占位(无抖动,不闪登录);否则 → 登录按钮 */}
+ {/* Three states: user loaded → user menu; token present and /me has not failed → skeleton (no jump, no login flash); otherwise → Log in button. */}
{renderUserSlot()}
</div>
</div>
@@ -152,7 +152,7 @@ export function Header({ isMobile, onMenuToggle, topNav, showLogo }: HeaderProps
</>
);
- /** 用户区三态渲染:用户菜单 / 占位骨架 / 登录按钮(抽出避免 JSX 内嵌套三元) */
+ /** Three-state render for the user area: user menu, placeholder skeleton, or Log in button (pulled out so JSX does not nest ternaries). */
function renderUserSlot() {
if (user) {
return (
@@ -178,7 +178,7 @@ export function Header({ isMobile, onMenuToggle, topNav, showLogo }: HeaderProps
}
/**
- * 用户区占位骨架:在 /me 返回前展示,尺寸与 UserDropdown 触发器一致,避免登录态切换时的布局抖动与「登录」闪烁。
+ * Placeholder skeleton for the user area: shown until /me returns, sized like the UserDropdown trigger, so login-state changes do not shift the layout or flash "Log in".
*/
function UserPlaceholder() {
return (
@@ -283,7 +283,7 @@ function UserDropdown({
type="button"
onClick={() => {
closeDropdown();
- // 管理台是独立部署于 /admin-console/ 的 SPA,整页跳转而非 SPA 路由
+ // The admin console is a separately deployed SPA at /admin-console/, so this is a full page navigation rather than an SPA route.
window.location.assign('/admin-console/');
}}
className="flex w-full items-center gap-2.5 rounded-lg px-2.5 py-2 text-sm text-muted-foreground transition-colors hover:bg-muted/60 hover:text-foreground cursor-pointer"
diff --git a/webdemo/frontend/src/layouts/components/Sidebar.tsx b/webdemo/frontend/src/layouts/components/Sidebar.tsx
index 7e92d73..bf3663a 100644
--- a/webdemo/frontend/src/layouts/components/Sidebar.tsx
+++ b/webdemo/frontend/src/layouts/components/Sidebar.tsx
@@ -22,12 +22,12 @@ interface SidebarProps {
}
/**
- * 主侧边栏:渲染导航树(叶子项 / 可折叠父级 / 收起态飞出菜单),并管理父级菜单展开态。
+ * Main sidebar: renders the nav tree (leaf items, collapsible parents, and a collapsed flyout) and manages which parent menus are open.
*
- * @param collapsed 是否收起(收起时父级用 hover 飞出菜单)
- * @param onNavigate 导航后的回调(移动端关闭抽屉)
- * @param onToggle 折叠/展开切换回调
- * @param routes 自定义路由(默认取 staticRoutes 中未隐藏项)
+ * @param collapsed Whether it is collapsed (collapsed parents use a hover flyout).
+ * @param onNavigate Callback after navigation (closes the drawer on mobile).
+ * @param onToggle Collapse or expand toggle callback.
+ * @param routes Custom routes (defaults to non-hidden items in staticRoutes).
*/
export function Sidebar({ collapsed, onNavigate, onToggle, routes }: SidebarProps) {
const { t } = useTranslation('shell');
@@ -50,8 +50,8 @@ export function Sidebar({ collapsed, onNavigate, onToggle, routes }: SidebarProp
const [openMenus, setOpenMenus] = useState<string[]>(getActiveParents);
const [manualClosed, setManualClosed] = useState<string[]>([]);
- // 切换父级菜单:已开则收起并记入 manualClosed;展开则只保留当前父级,
- // 且若父级当前未激活,顺带跳转到首个子路由。
+ // Toggle a parent menu: if it is open, collapse it and record it in manualClosed; if expanding, keep only the current parent,
+ // and if that parent is not currently active, also navigate to its first child route.
function toggleMenu(route: AppRoute) {
const path = route.path;
const isCurrentlyOpen = openMenus.includes(path) && !manualClosed.includes(path);
@@ -174,7 +174,7 @@ export function Sidebar({ collapsed, onNavigate, onToggle, routes }: SidebarProp
onNavigate={onNavigate}
/>
)}
- {/* 个人设置:侧栏与顶栏用户菜单提供一致的入口 */}
+ {/* Personal settings: the sidebar and the top-bar user menu share the same entry. */}
<button
type="button"
onClick={() => {
diff --git a/webdemo/frontend/src/layouts/components/SidebarFlyoutGroup.tsx b/webdemo/frontend/src/layouts/components/SidebarFlyoutGroup.tsx
index 468a74b..fc73c64 100644
--- a/webdemo/frontend/src/layouts/components/SidebarFlyoutGroup.tsx
+++ b/webdemo/frontend/src/layouts/components/SidebarFlyoutGroup.tsx
@@ -14,14 +14,14 @@ interface SidebarFlyoutGroupProps {
}
/**
- * 收起态侧栏的悬浮飞出菜单(hover 触发,子菜单浮层显示)。
+ * Hover flyout for the collapsed sidebar (the submenu floats open).
*
- * 内部维护 open 态与浮层定位:根据触发器位置与视口高度,
- * 避免子菜单超出视口底部;离开时延迟 120ms 关闭以容许鼠标移动。
- * @param route 父路由
- * @param isActive 父级是否激活
- * @param pathname 当前路径,用于子项高亮
- * @param onNavigate 点击子项后的回调
+ * Tracks open state and flyout position from the trigger and the viewport height,
+ * so the submenu does not run past the bottom of the viewport; closing is delayed 120ms on leave so the pointer can move.
+ * @param route Parent route.
+ * @param isActive Whether the parent is active.
+ * @param pathname Current path, used to highlight children.
+ * @param onNavigate Callback after a child is clicked.
*/
export function SidebarFlyoutGroup({
route,
diff --git a/webdemo/frontend/src/layouts/components/SidebarNavGroup.tsx b/webdemo/frontend/src/layouts/components/SidebarNavGroup.tsx
index d1ef3cb..eeeb21c 100644
--- a/webdemo/frontend/src/layouts/components/SidebarNavGroup.tsx
+++ b/webdemo/frontend/src/layouts/components/SidebarNavGroup.tsx
@@ -16,15 +16,15 @@ interface SidebarNavGroupProps {
}
/**
- * 展开态侧栏的可折叠父级菜单(带子菜单)。
+ * Collapsible parent menu (with children) for the expanded sidebar.
*
- * @param route 父路由(children 为子菜单项)
- * @param isOpen 子菜单是否展开
- * @param isActive 父级是否激活
- * @param collapsed 侧栏是否收起
- * @param onToggle 点击父级标题时切换展开/折叠
- * @param onNavigate 点击子项后的回调
- * @param pathname 当前路径,用于子项高亮
+ * @param route Parent route (children are the submenu items).
+ * @param isOpen Whether the submenu is expanded.
+ * @param isActive Whether the parent is active.
+ * @param collapsed Whether the sidebar is collapsed.
+ * @param onToggle Toggle expand or collapse when the parent title is clicked.
+ * @param onNavigate Callback after a child is clicked.
+ * @param pathname Current path, used to highlight children.
*/
export function SidebarNavGroup({
route,
diff --git a/webdemo/frontend/src/layouts/components/SidebarNavItem.tsx b/webdemo/frontend/src/layouts/components/SidebarNavItem.tsx
index 45b9bd2..29d17c1 100644
--- a/webdemo/frontend/src/layouts/components/SidebarNavItem.tsx
+++ b/webdemo/frontend/src/layouts/components/SidebarNavItem.tsx
@@ -13,12 +13,12 @@ interface SidebarNavItemProps {
}
/**
- * 侧栏叶子导航项(无子菜单)。
+ * Sidebar leaf nav item (no children).
*
- * @param route 路由数据(取 meta.title / meta.icon 渲染)
- * @param isActive 是否当前激活
- * @param collapsed 侧栏是否收起(收起时隐藏文字)
- * @param onNavigate 点击后的回调(移动端用于关闭抽屉)
+ * @param route Route data (rendered from meta.title and meta.icon).
+ * @param isActive Whether it is currently active.
+ * @param collapsed Whether the sidebar is collapsed (hides the label when collapsed).
+ * @param onNavigate Callback after click (used on mobile to close the drawer).
*/
export function SidebarNavItem({ route, isActive, collapsed, onNavigate }: SidebarNavItemProps) {
const locale = useAppStore((state) => state.locale);
diff --git a/webdemo/frontend/src/layouts/components/TopNav.tsx b/webdemo/frontend/src/layouts/components/TopNav.tsx
index fce374f..188a86d 100644
--- a/webdemo/frontend/src/layouts/components/TopNav.tsx
+++ b/webdemo/frontend/src/layouts/components/TopNav.tsx
@@ -8,7 +8,7 @@ import { NavItemButton } from './nav-item-button';
import type { AppRoute } from '@map/types';
interface TopNavProps {
- /** top:纯顶部导航,带图标与 hover 下拉;mixed:仅一级切换,二级由侧栏承担 */
+ /** top: top navigation only, with icons and a hover dropdown; mixed: first level only, and the second level lives in the sidebar. */
variant?: 'top' | 'mixed';
onRouteClick?: (route: AppRoute) => void;
}
@@ -24,7 +24,7 @@ const navItemClass = (active: boolean) => `
`;
/**
- * 顶部导航图标容器,固定 16px 不参与行高计算。
+ * Top-nav icon container, fixed at 16px and excluded from line-height.
*/
function NavIcon({ icon, active }: { icon?: string; active: boolean }) {
const renderIcon = getIcon(icon);
@@ -38,7 +38,7 @@ function NavIcon({ icon, active }: { icon?: string; active: boolean }) {
}
/**
- * 顶部一级导航:top 模式带图标与 hover 下拉;mixed 模式仅文字 tab,二级走侧栏。
+ * Top-level navigation: top mode has icons and a hover dropdown; mixed mode is a text tab only, and the second level lives in the sidebar.
*/
export function TopNav({ variant = 'top', onRouteClick }: TopNavProps) {
const location = useLocation();
diff --git a/webdemo/frontend/src/layouts/components/comp-icons.tsx b/webdemo/frontend/src/layouts/components/comp-icons.tsx
index b2ab9f4..3813046 100644
--- a/webdemo/frontend/src/layouts/components/comp-icons.tsx
+++ b/webdemo/frontend/src/layouts/components/comp-icons.tsx
@@ -1,10 +1,10 @@
import type React from 'react';
/**
- * 组件库演示图标集合(搜索/组件总览里展示 @map/ui 各组件用)。
+ * Demo icon set for the component library (used when search or the component overview shows each @map/ui component).
*
- * 用途:从 nav-icons 中拆出体量较大的 `Comp*` 图标,避免单文件超过 400 行上限。
- * 这些图标与侧栏导航无关,仅用于组件检索类场景,故独立成表。
+ * Purpose: split the larger `Comp*` icons out of nav-icons so a single file stays under the 400-line limit.
+ * These icons are unrelated to sidebar navigation and are only for component lookup, so they live in their own table.
*/
export const compIconMap: Record<string, (props: { className?: string }) => React.ReactNode> = {
CompButton: ({ className }) => (
diff --git a/webdemo/frontend/src/layouts/components/nav-icons.tsx b/webdemo/frontend/src/layouts/components/nav-icons.tsx
index 9824480..79ed648 100644
--- a/webdemo/frontend/src/layouts/components/nav-icons.tsx
+++ b/webdemo/frontend/src/layouts/components/nav-icons.tsx
@@ -3,9 +3,9 @@ import { AudioLines, BookOpen } from 'lucide-react';
import { compIconMap } from './comp-icons';
/**
- * 导航/页面图标注册表(侧栏、面包屑等按 meta.icon 名称取用)。
+ * Nav and page icon registry (sidebar, breadcrumbs, and others look up meta.icon by name).
*
- * 体量较大的组件演示图标已拆至 `comp-icons.tsx`,此处合并两表对外提供统一查询。
+ * The larger component-demo icons live in `comp-icons.tsx`; this file merges both tables into one lookup.
*/
const navIconMap: Record<string, (props: { className?: string }) => React.ReactNode> = {
AudioLines: ({ className }) => <AudioLines className={className} size={18} strokeWidth={1.8} />,
@@ -314,15 +314,15 @@ const navIconMap: Record<string, (props: { className?: string }) => React.ReactN
),
};
-/** 导航图标 + 组件演示图标合并后的统一注册表 */
+/** Unified registry of nav icons plus component-demo icons. */
export const iconMap: Record<string, (props: { className?: string }) => React.ReactNode> = {
...navIconMap,
...compIconMap,
};
/**
- * 按名称取图标渲染函数;名称缺失或未注册时回退到 Fallback。
- * @param name meta.icon 中声明的图标名
+ * Look up an icon render function by name; fall back to Fallback when the name is missing or unregistered.
+ * @param name Icon name declared in meta.icon.
*/
export function getIcon(name?: string) {
return iconMap[name ?? 'Fallback'] ?? iconMap.Fallback;
diff --git a/webdemo/frontend/src/layouts/components/nav-item-button.tsx b/webdemo/frontend/src/layouts/components/nav-item-button.tsx
index 5b1388a..708e8dc 100644
--- a/webdemo/frontend/src/layouts/components/nav-item-button.tsx
+++ b/webdemo/frontend/src/layouts/components/nav-item-button.tsx
@@ -5,13 +5,13 @@ import { cn } from '@map/ui';
interface NavItemButtonProps extends HTMLAttributes<HTMLElement> {
to: string;
children: ReactNode;
- /** 外部链接:设置后渲染为锚点,点击在新标签页打开,不走内部路由 */
+ /** External link: when set, render an anchor that opens in a new tab and does not use internal routing. */
external?: string;
}
/**
- * 导航按钮:内部路由用编程式跳转,避免 hover 时浏览器左下角显示链接地址;
- * 传入 external 时渲染为锚点,在新标签页打开外部地址。
+ * Nav button: internal routes use a programmatic jump so hover does not show the URL in the browser status bar;
+ * when external is passed, render an anchor that opens the external address in a new tab.
*/
export function NavItemButton({
to,
@@ -23,7 +23,7 @@ export function NavItemButton({
}: NavItemButtonProps) {
const navigate = useNavigate();
- // 外部链接:新标签页打开,rel 阻断 opener 引用泄露。
+ // External link: open in a new tab, and use rel to block opener leaks.
if (external) {
return (
<a
diff --git a/webdemo/frontend/src/layouts/components/sidebar-utils.ts b/webdemo/frontend/src/layouts/components/sidebar-utils.ts
index d30e8f8..525dcb9 100644
--- a/webdemo/frontend/src/layouts/components/sidebar-utils.ts
+++ b/webdemo/frontend/src/layouts/components/sidebar-utils.ts
@@ -1,13 +1,13 @@
import type { AppRoute } from '@map/types';
/**
- * 判断路由是否处于激活态。
+ * Decide whether a route is active.
*
- * 通配父路由(`/*`)用前缀匹配;叶子路由仅精确匹配,
- * 避免 `/eval` 在 `/eval/create` 下被误高亮。
- * @param route 待判断的路由
- * @param pathname 当前 location.pathname
- * @returns 是否激活
+ * Wildcard parents (`/*`) match by prefix; leaf routes match exactly,
+ * so `/eval` is not highlighted under `/eval/create`.
+ * @param route Route to test.
+ * @param pathname Current location.pathname.
+ * @returns Whether it is active.
*/
export function isRouteActive(route: AppRoute, pathname: string): boolean {
const basePath = route.path.replace('/*', '');
diff --git a/webdemo/frontend/src/main.tsx b/webdemo/frontend/src/main.tsx
index 4b24482..11c901d 100644
--- a/webdemo/frontend/src/main.tsx
+++ b/webdemo/frontend/src/main.tsx
@@ -36,10 +36,6 @@ function App() {
path="/playground/image-parse"
element={<Navigate to="/playground/document-parse" replace />}
/>
- <Route
- path="/playground/field-extract"
- element={<Navigate to="/playground/document-parse" replace />}
- />
<Route
path="/playground/tts"
element={<Navigate to="/playground/document-parse" replace />}
diff --git a/webdemo/frontend/src/pages/models/components/modelCapabilities.ts b/webdemo/frontend/src/pages/models/components/modelCapabilities.ts
index cb27eb5..d2ad0bb 100644
--- a/webdemo/frontend/src/pages/models/components/modelCapabilities.ts
+++ b/webdemo/frontend/src/pages/models/components/modelCapabilities.ts
@@ -1,4 +1,4 @@
-/** 模型控制台已不在这个演示里。这里只留下游乐场还在用的能力判断。 */
+/** The model console is not part of this demo. Only the capability checks the playground still uses remain here. */
export const PLAYGROUND_TOGGLE_KEYS = {
showReasoning: 'show_reasoning',
diff --git a/webdemo/frontend/src/pages/playground/components/AnswerProcessDisclosure.tsx b/webdemo/frontend/src/pages/playground/components/AnswerProcessDisclosure.tsx
index ae835d5..4eed50c 100644
--- a/webdemo/frontend/src/pages/playground/components/AnswerProcessDisclosure.tsx
+++ b/webdemo/frontend/src/pages/playground/components/AnswerProcessDisclosure.tsx
@@ -8,13 +8,12 @@ import type { Citation } from '../types';
import { MarkdownRenderer } from './MarkdownRenderer';
/**
- * 渲染回答过程折叠区的标题行。
+ * Renders the title row of the answer-process disclosure.
*
- * 整行就是折叠开关:过程区顶部只表达「思考了多久」,来源统一由回答下方的胶囊通往抽屉,
- * 标题不再兼任第二个跳转入口——一行两个动作,用户分不清点哪儿会发生什么。
+ * The whole row is the disclosure toggle: the top of the process area only states how long reasoning took. Sources reach the drawer through the chip under the answer, and the title is no longer a second jump target — two actions on one row leave users unsure what a click will do.
*
- * @param props 标题、图标、展开状态与内容
- * @returns 可键盘操作的折叠区
+ * @param props Title, icon, expanded state, and content
+ * @returns A keyboard-operable disclosure
*/
export function ProcessDisclosure({
id,
@@ -42,11 +41,9 @@ export function ProcessDisclosure({
const head = (
<>
{/*
- 图标格子只负责对齐,不铺底色。时间线里的 marker 要用 bg-background 在连接线上开一个口
- (见 ProcessRailItem),顶行没有线穿过,同样铺底就只剩副作用:整行 hover 变色时,
- 这块不透明的底会在 hover 色里挖出一个圆洞,看着像图标自带背景。
+ The icon cell only aligns; it does not paint a background. Timeline markers use bg-background to punch a gap in the connector (see ProcessRailItem). The top row has no line through it, so the same fill is only a side effect: when the row hover color changes, this opaque fill cuts a round hole out of the hover color, as if the icon brought its own background.
*/}
- {/* 保留标题列宽,图标左对齐回答正文,避免居中产生额外内缩。 */}
+ {/* Keep the title column width and left-align the icon with the answer body, so centering does not add extra inset. */}
<span className="flex size-6 shrink-0 items-center justify-start">{icon}</span>
<span className="min-w-0 truncate">{title}</span>
</>
@@ -54,7 +51,7 @@ export function ProcessDisclosure({
const chevron = (
<ChevronDown
className={cn(
- // 箭头跟随 expanded 旋转,用 ease-out 曲线与 max-height 展开速度匹配
+ // The arrow rotates with expanded, using an ease-out curve matched to the max-height expand speed
'size-4 shrink-0 transition-transform duration-[250ms] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none',
expanded && 'rotate-180',
)}
@@ -89,13 +86,12 @@ export function ProcessDisclosure({
}
/**
- * 渲染可自动跟随输出的过程滚动区。
+ * Renders a process scroller that can follow output automatically.
*
- * 滚动必须由整条时间线统一承载:交错之后思考被切成若干段,每段各自一个滚动条既滚不动
- * 也读不出先后。属性名沿用 data-reasoning-scroll,外部(含测试)据此定位这块滚动区。
+ * Scrolling has to be carried by the whole timeline: after interleaving, reasoning is split into segments, and a scrollbar on each segment neither scrolls nor shows order. The attribute name stays data-reasoning-scroll so callers (including tests) can find this scroller.
*
- * @param props 展开态、流式状态、触发重新贴底的内容指纹、跟随控制与时间线内容
- * @returns 过程内容滚动区
+ * @param props Expanded state, streaming state, content fingerprint that re-pins to the bottom, follow control, and timeline content
+ * @returns The process content scroller
*/
export function ProcessScrollArea({
expanded,
@@ -113,7 +109,7 @@ export function ProcessScrollArea({
const scrollRef = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
- // 跟随状态只在这里问一次:用户中途往回翻过,就不再把滚动位置抢回底部
+ // Ask the follow state only here: once the user has scrolled back, do not yank the scroll position to the bottom
if (!follow.shouldFollow()) return;
const element = scrollRef.current;
if (!element) return;
@@ -125,11 +121,9 @@ export function ProcessScrollArea({
const element = scrollRef.current;
if (!element) return;
/*
- 收起时把阅读位置归零,下一次展开从头读。
+ On collapse, reset the read position to zero so the next expand starts from the top.
- 收起态不可见,归零在这里没有视觉代价;不归零的话,流式期间一路跟到底的 scrollTop
- 会原样留着,用户再点开看到的是思考的**尾巴**——内容凭空从中间开始,像是随机停位。
- 流式期间收起再展开也不受影响:下一帧增量到达时跟随会把它重新贴回底部。
+ The collapsed state is invisible, so resetting here has no visual cost. Without it, the scrollTop that followed to the end during streaming stays put, and the next open shows the **tail** of the reasoning — content starts in the middle, as if it stopped at random. Collapsing and expanding during streaming is unaffected: the next incremental frame pins it back to the bottom.
*/
element.scrollTop = 0;
}, [expanded]);
@@ -145,10 +139,7 @@ export function ProcessScrollArea({
className={cn(
'max-w-2xl overflow-y-auto overscroll-contain pb-1 pr-2',
/*
- 流式期间压到 48(不占太多屏),结束后放到 96。直接切换是一次硬跳:实测 300px
- 高的过程区会在一帧内从 192px 长到 300px,把下方正文整块顶下去——回答刚写完那一
- 瞬间页面抖一下,就是这里。过渡让它长出来;与折叠动画同时发生也不打架(1fr 的
- 目标值随内容走,实测无二次动画)。
+ During streaming, cap at 48 (so it does not take much of the screen); after streaming, raise it to 96. Switching directly is a hard jump: a 300px-tall process area grows from 192px to 300px in one frame and shoves the body below it down — that is the page twitch the instant an answer finishes. The transition lets it grow; running it together with the disclosure animation does not fight (the 1fr target follows the content, and there is no second animation in practice).
*/
'transition-[max-height] duration-300 ease-out motion-reduce:transition-none',
streaming ? 'max-h-48' : 'max-h-96',
@@ -160,13 +151,12 @@ export function ProcessScrollArea({
}
/**
- * 时间线上的一段思考文本。
+ * One reasoning segment on the timeline.
*
- * 思考里同样会出现 `[ref_N]` 角标——模型是一边读搜索结果一边想的,引用编号自然写进思考。
- * 不把来源传进去,这些角标既变不成链接,还会被裸数学识别当成下标公式渲染成一串斜体。
+ * Reasoning can also contain `[ref_N]` badges — the model thinks while reading search results, so citation numbers land in the reasoning. Without passing sources in, those badges neither become links nor stay text; bare-math recognition treats them as subscript formulas and renders a run of italics.
*
- * @param props 思考文本、流式状态与本轮来源
- * @returns 走统一 Markdown 管线渲染的思考段
+ * @param props Reasoning text, streaming state, and this turn's sources
+ * @returns A reasoning segment rendered through the shared Markdown pipeline
*/
export function ReasoningSegment({
reasoning,
@@ -188,26 +178,22 @@ export function ReasoningSegment({
}
/*
- 展开与收起用不同的曲线,这不是装饰。
+ Expand and collapse use different curves. That is not decoration.
- cubic-bezier(0.22,1,0.36,1) 极度前置:用在展开上是「迅速揭开、末端稳住」,手感利落;
- 用在收起上就成了塌陷——实测一个 300px 高的过程区,头 30ms 就掉到 133px,下方正文被
- 猛地拽上来一大截,看着正是「排版闪动一下」。收起换标准 ease-out,同样 220ms 收完,
- 但前 30ms 只走 20px,读起来是收拢而不是被抽走。
+ cubic-bezier(0.22,1,0.36,1) is extremely front-loaded: on expand it means "open quickly, then settle," which feels crisp; on collapse it becomes a cave-in — a 300px-tall process area drops to 133px in the first 30ms, and the body below is yanked up a long way, which reads as a layout flash. Collapse uses a standard ease-out, still finishing in 220ms, but the first 30ms only travel 20px, so it reads as gathering rather than being pulled away.
- opacity 跟高度同曲线、同时长、不带延时:两层各走各的节奏时,内容会在容器还没收完时
- 就已经透明,留一块空白在原地坍缩——那是同一个问题的另一半。
+ Opacity shares the height curve, grows at the same time, and has no delay: if the two layers keep their own timing, the content is already transparent before the container has finished closing, leaving a blank that collapses in place — the other half of the same problem.
*/
const PANEL_DURATION_MS = 220;
const PANEL_EXPAND_CURVE = 'cubic-bezier(0.22,1,0.36,1)';
const PANEL_COLLAPSE_CURVE = 'cubic-bezier(0.4,0,0.2,1)';
/**
- * 折叠内容面板。
+ * Collapsible content panel.
*
- * 动画策略:grid-template-rows 0fr → 1fr。
- * - 比 max-height 方案更精确:高度精确等于内容高度,无「9999px → 0」的冗余计算;
- * - 配合 overflow-hidden 保证内容在折叠期间不外溢。
+ * Animation strategy: grid-template-rows 0fr → 1fr.
+ * - More precise than max-height: the height equals the content height, with no redundant "9999px → 0" calculation;
+ * - overflow-hidden keeps the content from spilling while collapsed.
*/
export function DisclosurePanel({
id,
diff --git a/webdemo/frontend/src/pages/playground/components/AnswerProcessSteps.tsx b/webdemo/frontend/src/pages/playground/components/AnswerProcessSteps.tsx
index a38a89a..2369b1f 100644
--- a/webdemo/frontend/src/pages/playground/components/AnswerProcessSteps.tsx
+++ b/webdemo/frontend/src/pages/playground/components/AnswerProcessSteps.tsx
@@ -1,8 +1,7 @@
/**
- * 回答过程时间线的行基元。
+ * Row primitive for the answer-process timeline.
*
- * 用途:思考段落与工具行共用同一条 marker 列(思考是项目符号、工具是工具图标),
- * 并在 marker 下方画出连接到下一项的竖线,让一次回答的过程读起来是一条线而不是几块卡片。
+ * Purpose: reasoning paragraphs and tool rows share one marker column (a bullet for reasoning, a tool icon for tools), and a vertical line under the marker connects to the next item, so one answer's process reads as a line rather than several cards.
*/
import { type ReactNode } from 'react';
@@ -10,35 +9,32 @@ import { type ReactNode } from 'react';
import { cn } from '@map/ui';
interface ProcessRailItemProps {
- /** marker 列里的内容:项目符号或工具图标;传 null 只占位不画(整条时间线只有一行时)。 */
+ /** Content in the marker column: a bullet or a tool icon; pass null to reserve the slot without drawing (when the timeline has only one row). */
marker: ReactNode;
- /** 是否为最后一项;最后一项不画向下的连接线。 */
+ /** Whether this is the last item; the last item does not draw a connector downward. */
last?: boolean;
- /** 失败态整行转红。 */
+ /** Failure state turns the whole row red. */
tone?: 'default' | 'destructive';
children: ReactNode;
}
/*
- 每一项自带入场动画。流式期间时间线是一项一项长出来的,不给过渡的话新的一行会"啪"地
- 顶在原位上——尤其搜索行只有一枚图标加一句话,凭空出现时观感最硬。
- keyed 元素只在首次挂载时跑一次,已有项继续追加文字不会重播;无延时,所以不需要
- fill-mode(那是 STAGGER_CLASS_NAME 给带延时的图标用的)。
+ Each item has its own entrance animation. During streaming the timeline grows one item at a time; without a transition a new row snaps into place — especially a search row, which is only an icon plus a sentence and looks hardest when it appears from nowhere.
+ A keyed element runs only on first mount; appending text to an existing item does not replay it. There is no delay, so fill-mode is unnecessary (that is what STAGGER_CLASS_NAME is for, on delayed icons).
*/
const ROW_ENTER_CLASS_NAME =
'motion-safe:animate-in motion-safe:fade-in-0 motion-safe:slide-in-from-bottom-1 motion-safe:duration-300';
/**
- * 渲染时间线上的一行(marker + 正文 + 向下的连接线)。
+ * Renders one timeline row (marker + body + downward connector).
*
- * 连接线是每项各画一段(marker 下方到本行底部),而不是一条贯穿全高的轨道:
- * 这样它天然在每个 marker 处断开,marker 才像是"挂"在线上而不是被线穿过。
+ * The connector is one segment per item (from under the marker to the bottom of the row), not a track through the full height: it naturally breaks at each marker, so the marker looks hung on the line rather than pierced by it.
*
- * @param marker marker 列内容
- * @param last 是否为最后一项
- * @param tone 文字色调
- * @param children 行正文
- * @returns 时间线行
+ * @param marker Marker-column content
+ * @param last Whether this is the last item
+ * @param tone Text tone
+ * @param children Row body
+ * @returns A timeline row
*/
export function ProcessRailItem({
marker,
@@ -70,7 +66,7 @@ export function ProcessRailItem({
);
}
-/** 思考段落的 marker:一个安静的小圆点,与工具图标同宽同列。 */
+/** Marker for a reasoning paragraph: a quiet dot, the same width and column as the tool icons. */
export function ProcessBullet() {
return <span className="size-1.5 rounded-full bg-muted-foreground/50" aria-hidden="true" />;
}
diff --git a/webdemo/frontend/src/pages/playground/components/AnswerProcessTimeline.test.tsx b/webdemo/frontend/src/pages/playground/components/AnswerProcessTimeline.test.tsx
index b57409f..43358e0 100644
--- a/webdemo/frontend/src/pages/playground/components/AnswerProcessTimeline.test.tsx
+++ b/webdemo/frontend/src/pages/playground/components/AnswerProcessTimeline.test.tsx
@@ -118,7 +118,7 @@ describe('AnswerProcessTimeline', () => {
);
expect(screen.getByText('搜索到 23 个网页')).toBeVisible();
- // 完成后不再重复查询词,位置让给叠放的站点图标
+ // After completion, do not repeat the query; that space goes to the stacked site icons
expect(screen.queryByText('MiniCPM 最新进展')).not.toBeInTheDocument();
const row = screen.getByText(/搜索到 23 个网页/).closest('li');
expect(row?.querySelectorAll('img')).toHaveLength(2);
@@ -129,12 +129,12 @@ describe('AnswerProcessTimeline', () => {
<AnswerProcessTimeline reasoning="只有一段思考。" streaming={false} />,
);
- // 纯思考完成态默认收起,面板是 inert 的,按 role 取不到 → 直接查 DOM
+ // A finished reasoning-only state is collapsed by default and the panel is inert, so a role query misses it → query the DOM directly
const row = container.querySelector('li');
expect(row).not.toBeNull();
- // 圆点是 marker 列里唯一的装饰元素;只剩一行时它指向空处,没有第二项可对齐
+ // The dot is the only decoration in the marker column; with one row left it points at empty space, with no second item to align to
expect(row?.querySelector('span[class*="size-1.5"]')).toBeNull();
- // 列本身要留着:去掉会让正文左移到图标那一列,读起来像与顶行平级
+ // Keep the column itself: removing it shifts the body left into the icon column, so it reads as a peer of the top row
expect(row).toHaveClass('grid-cols-[1.5rem_minmax(0,1fr)]');
expect(screen.getByText('只有一段思考。')).toBeInTheDocument();
});
@@ -149,7 +149,7 @@ describe('AnswerProcessTimeline', () => {
/>,
);
- // 开了联网但首个工具帧还没到:此刻 items 也只有一项,按当下项数判定就会闪一下圆点
+ // Web search is on but the first tool frame has not arrived: items has only one entry then, and deciding by the current count flashes the dot
expect(container.querySelector('li span[class*="size-1.5"]')).not.toBeNull();
});
@@ -172,8 +172,8 @@ describe('AnswerProcessTimeline', () => {
expect(screen.getByRole('button', { name: '已思考' })).toBeVisible();
/*
- 图标刻意保持一枚:一列回答里每条顶行换一个图标会让这竖排变成杂色噪点。
- 按 class 比"两者相同"而不是硬断言某个 lucide 名,是为了图标改名时不假失败。
+ The icon is deliberately kept to one: a different icon on every top row in a column of answers turns the stack into colored noise.
+ Compare by class that "the two match" rather than hard-asserting a lucide name, so a rename does not fail falsely.
*/
const reasonedIcon = document.querySelector('svg')?.getAttribute('class');
expect(searchedIcon).toBeTruthy();
@@ -217,7 +217,7 @@ describe('AnswerProcessTimeline', () => {
/>,
);
- // 开关只代表"允许联网"。标成已联网会让用户以为答案有外部依据,比不标更糟。
+ // The switch only means "web search is allowed." Marking it as already searched makes users think the answer has external evidence, which is worse than no mark.
expect(screen.getByRole('button', { name: '已思考' })).toBeVisible();
});
@@ -261,7 +261,7 @@ describe('AnswerProcessTimeline', () => {
const row = screen.getByText(/搜索到 10 个网页/).closest('li');
expect(row?.querySelectorAll('img')).toHaveLength(4);
- // 那一叠是拿整条消息的来源兜底的近似值,+26 会与「搜索到 10 个网页」直接矛盾
+ // That stack is an approximation filled from the whole message's sources; +26 would directly contradict "found 10 pages"
expect(row?.textContent).not.toContain('+');
});
@@ -306,12 +306,12 @@ describe('AnswerProcessTimeline', () => {
await user.click(trigger);
expect(screen.getByText('搜索到 2 个网页')).toBeVisible();
- // 只剩折叠头那一个按钮
+ // Only the disclosure-header button is left
expect(screen.getAllByRole('button')).toHaveLength(1);
});
it('顶行的搜索词:还没到就退回静态文案,多个用顿号连,过长截断', () => {
- // 查询词要等模型把 tool_call 参数生成完才随 running 帧到达,这段空档只能报静态文案
+ // The query waits until the model finishes generating tool_call arguments and arrives with the running frame; that gap can only show static copy
const { rerender } = render(
<AnswerProcessTimeline
reasoning=""
@@ -340,7 +340,7 @@ describe('AnswerProcessTimeline', () => {
expect(screen.getByRole('button', { name: '正在搜索 北京天气、上海天气' })).toBeVisible();
- // 模型偶尔把整句话塞进 query:顶行只有一行,不截断会把它挤没
+ // The model sometimes stuffs a whole sentence into query: the top row is a single line, and without truncation the sentence crowds it out
rerender(
<AnswerProcessTimeline
reasoning=""
@@ -378,9 +378,8 @@ describe('AnswerProcessTimeline', () => {
);
/*
- 思考只播到第 6 个字,切点在第 10 个字:工具行先押着。
- 顶行不跟着押——押的是时间线内部的先后顺序,顶行报的是此刻的真实状态,
- 而「正在搜哪个词」越早出现越有用。所以查询词此时只在顶行,不在展开区。
+ Reasoning has only played to character 6, and the cut is at character 10: hold the tool row.
+ The top row is not held with it — what is held is order inside the timeline; the top row reports the real state right now, and "which query is being searched" is more useful the earlier it appears. So the query is only on the top row at this moment, not in the expanded area.
*/
expect(screen.getByRole('button', { name: '正在搜索 MiniCPM 最新进展' })).toBeVisible();
expect(screen.queryByText('MiniCPM 最新进展')).not.toBeInTheDocument();
@@ -421,7 +420,7 @@ describe('AnswerProcessTimeline', () => {
const hit = screen.getByRole('link', { name: '技术报告,打开原文' });
expect(hit).toHaveAttribute('href', 'https://one.example.com/a');
expect(hit).toHaveAttribute('target', '_blank');
- // 没在 citations 里命中的地址不编标题,用域名代替
+ // Addresses that miss citations get no invented title; use the domain instead
expect(screen.getByRole('link', { name: 'untitled.example.com,打开原文' })).toBeVisible();
});
@@ -462,7 +461,7 @@ describe('AnswerProcessTimeline', () => {
/>,
);
- // 合并后只有 1 个折叠按钮,思考与工具同属其中
+ // After the merge there is only 1 disclosure button; reasoning and tools both belong to it
const trigger = screen.getByRole('button', { name: '工具调用中' });
expect(trigger).toHaveAttribute('aria-expanded', 'true');
expect(screen.getAllByRole('button')).toHaveLength(1);
@@ -498,7 +497,7 @@ describe('AnswerProcessTimeline', () => {
/>,
);
- // 完成 + 仅工具(无思考内容):退回工具数,否则收起态是一行空白
+ // Done + tools only (no reasoning): fall back to the tool count, otherwise the collapsed state is a blank line
expect(screen.getByRole('button', { name: '使用 1 个工具' })).toHaveClass(
'w-full',
'max-w-3xl',
@@ -580,7 +579,7 @@ describe('AnswerProcessTimeline', () => {
await user.click(screen.getByRole('button', { name: '正在思考中' }));
- // 收起态不可见,归零没有视觉代价;不归零的话再点开会停在思考的尾巴上
+ // The collapsed state is invisible, so resetting to zero has no visual cost; without it, the next open stops on the tail of the reasoning
expect(reasoningScroll?.scrollTop).toBe(0);
});
@@ -642,7 +641,7 @@ describe('AnswerProcessTimeline', () => {
const trigger = screen.getByRole('button', { name: '已思考' });
expect(trigger).toHaveAttribute('aria-expanded', 'false');
expect(screen.getByText('查询当前时间')).not.toBeVisible();
- // 未收录的工具名原样展示,不伪造中文文案
+ // Unknown tool names are shown as-is; do not invent Chinese copy
expect(screen.getByText('calculator')).not.toBeVisible();
const panel = document.getElementById(trigger.getAttribute('aria-controls') ?? '');
expect(panel?.firstElementChild).toHaveProperty('inert', true);
@@ -651,7 +650,7 @@ describe('AnswerProcessTimeline', () => {
expect(trigger).toHaveAttribute('aria-expanded', 'true');
expect(panel?.firstElementChild).toHaveProperty('inert', false);
- // 单步耗时照竞品砍掉;总耗时也不在这条时间线上报,正文下方的指标行已有一份
+ // Per-step duration is cut, matching competitors; total duration is not reported on this timeline either, because the metrics row under the body already has a copy
expect(screen.queryByText('用时 0.8 秒')).not.toBeInTheDocument();
expect(screen.queryByText('用时 1.2 秒')).not.toBeInTheDocument();
});
@@ -695,7 +694,7 @@ describe('AnswerProcessTimeline', () => {
const trigger = screen.getByRole('button', { name: '使用 1 个工具' });
expect(trigger).toHaveAttribute('aria-expanded', 'true');
- // 子步骤挂了不代表回答不可信,标题不标红也不换成联网失败
+ // A failed sub-step does not mean the answer is untrustworthy; the title is not turned red and is not replaced with a web-search failure
expect(trigger).not.toHaveClass('text-destructive');
expect(screen.getByText('时间服务不可用')).toBeVisible();
});
diff --git a/webdemo/frontend/src/pages/playground/components/AnswerProcessTimeline.tsx b/webdemo/frontend/src/pages/playground/components/AnswerProcessTimeline.tsx
index 025fdad..b54c5e6 100644
--- a/webdemo/frontend/src/pages/playground/components/AnswerProcessTimeline.tsx
+++ b/webdemo/frontend/src/pages/playground/components/AnswerProcessTimeline.tsx
@@ -1,11 +1,9 @@
/**
- * 回答过程时间线。
+ * Answer-process timeline.
*
- * 用途:把一次回答的全过程——思考、联网搜索、读网页、查时间——还原成**一条**交错的时间线。
- * 模型的真实执行是「思考 → 调工具 → 继续思考」的单一流程,界面也就只给一个折叠区:
- * 顶行报「已思考(用时 N 秒)」,展开后思考段与工具行按发生顺序穿插在同一条 marker 列上。
+ * Purpose: restore one answer's whole process — reasoning, web search, reading pages, checking the time — as **one** interleaved timeline. The model's real execution is a single flow of "reason → call a tool → keep reasoning," so the UI gives only one disclosure: the top row reports "reasoned (N seconds)," and when expanded the reasoning segments and tool rows interleave in occurrence order on the same marker column.
*
- * 来源不在这里收口:正文下方的来源胶囊统一通往来源抽屉,顶行不再兼任第二个跳转入口。
+ * Sources are not closed out here: the source chip under the body is the single path to the source drawer, and the top row is no longer a second jump target.
*/
import { useId, useMemo } from 'react';
@@ -29,36 +27,36 @@ import { ProcessDisclosure, ProcessScrollArea, ReasoningSegment } from './Answer
import { ProcessToolRow } from './ProcessToolRow';
interface AnswerProcessTimelineProps {
- /** 模型思考内容(已过展示层改写)。 */
+ /** Model reasoning content (already rewritten by the display layer). */
reasoning: string;
- /** 当前模型是否允许展示思考内容。 */
+ /** Whether the current model is allowed to show reasoning content. */
showReasoning?: boolean;
- /** 展示层是否改写过思考文本;改写过就无法交错,退化为思考整块置顶。 */
+ /** Whether the display layer rewrote the reasoning text; if it did, interleaving is impossible and reasoning falls back to one block on top. */
reasoningRewritten?: boolean;
- /** 是否仍在流式生成。 */
+ /** Whether generation is still streaming. */
streaming?: boolean;
- /** 本轮全部工具调用事件,按到达顺序。 */
+ /** All tool-call events for this turn, in arrival order. */
toolEvents?: ToolEvent[];
- /** 整条消息的来源,供工具行就地展示站点图标与页面标题。 */
+ /** Sources for the whole message, so a tool row can show site icons and page titles in place. */
citations?: Citation[];
- /** 是否已开启联网但还没有任何工具事件(首帧之前的空档)。 */
+ /** Whether web search is on but there are still no tool events (the gap before the first frame). */
searching?: boolean;
- /** 后端下发的过程阶段,失败态可能先于工具事件到达。 */
+ /** Process phase from the backend; a failure state may arrive before tool events. */
searchStep?: SearchProgressStep;
- /** 最近一次执行的工具名,用于判定失败归属。 */
+ /** Name of the most recently run tool, used to attribute a failure. */
searchActiveTool?: string;
- /** 后端下发的失败原因,失败态直接当标题用。 */
+ /** Failure reason from the backend; used directly as the title in the failure state. */
searchStatus?: string;
- /** 打开来源抽屉;给了才把搜索行做成可点。 */
+ /** Opens the source drawer; only when provided is the search row made clickable. */
onOpenSources?: () => void;
- /** 是否已经有回答正文,用于绘制过程与答案的分隔。 */
+ /** Whether answer body text already exists, used to draw the separator between process and answer. */
hasAnswer?: boolean;
}
/**
- * 渲染回答的过程时间线。
- * @param props 思考内容、工具事件、来源与流式状态
- * @returns 可折叠的过程时间线;没有过程数据时不渲染
+ * Renders the process timeline for an answer.
+ * @param props Reasoning content, tool events, sources, and streaming state
+ * @returns A collapsible process timeline; renders nothing when there is no process data
*/
export function AnswerProcessTimeline({
reasoning,
@@ -78,27 +76,22 @@ export function AnswerProcessTimeline({
const panelId = useId();
/*
- 交给时间线的是**未 trim 的原文**:工具事件的 reasoningOffset 按原文字符数累加,先 trim
- 再按 offset 切会整体错位——模型惯常在调工具前留一个换行,trim 掉之后显示长度反而短于
- offset,下面「等播到再出行」的判断就永远等不到。段内空白由 buildProcessTimeline 逐段收拾。
+ What is handed to the timeline is the **untrimmed original**: a tool event's reasoningOffset is accumulated in original characters, and trimming before cutting by offset shifts everything — the model usually leaves a newline before calling a tool, and after trim the displayed length is shorter than the offset, so the "wait until playback reaches it before showing the row" check never arrives. Whitespace inside a segment is cleaned up segment by segment in buildProcessTimeline.
*/
const rawReasoning = showReasoning ? reasoning : '';
const hasReasoning = Boolean(rawReasoning.trim());
const failedEvents = toolEvents.filter((event) => event.status === 'failed');
/*
- 只有联网工具失败才让整行转红、标题换成失败原因。datetime 这类工具挂掉只是思考里的一个
- 子步骤没成,回答本身照常生成——整条标红会让用户以为整个回答都不可信。
+ Only a web-search tool failure turns the whole row red and replaces the title with the failure reason. A tool such as datetime failing is just one sub-step inside reasoning that did not succeed; the answer itself is still generated — marking the whole thing red makes users think the entire answer is untrustworthy.
- searchStep / searchActiveTool 是全工具共用字段,失败帧可能先于工具事件到达(甚至在
- 「刚开联网就失败」时根本没有工具事件,所以它也要计入 hasProcess)。归属以最近一次
- 工具为准,否则「查时间失败」会被报成「联网搜索失败」。
+ searchStep / searchActiveTool are fields shared by every tool. A failure frame may arrive before tool events (and when web search fails the moment it is turned on there are no tool events at all, so it still has to count toward hasProcess). Attribute the failure to the most recent tool; otherwise "time lookup failed" is reported as "web search failed."
*/
const stepFailedIsWeb =
searchStep === 'failed' && (!searchActiveTool || WEB_TOOLS.has(searchActiveTool));
const webFailed = stepFailedIsWeb || failedEvents.some((event) => WEB_TOOLS.has(event.tool));
const anyFailed = webFailed || failedEvents.length > 0;
const interrupted = toolEvents.some((event) => event.status === 'interrupted');
- // 已经报失败就不再转圈:失败帧到达后 searching 常常还挂着,图标会一直转
+ // Once a failure is reported, stop spinning: after the failure frame arrives, searching is often still set, and the icon would spin forever
const running =
!webFailed &&
(toolEvents.some((event) => event.status === 'running') || (searching && streaming));
@@ -106,9 +99,7 @@ export function AnswerProcessTimeline({
toolEvents.some((event) => event.status === 'running' && WEB_TOOLS.has(event.tool)) ||
(searching && streaming && !toolEvents.some((event) => event.status === 'running'));
/*
- 本轮是否真的联网取回了证据。判据是「有成功的联网工具调用」,而不是「联网开关开着」:
- 开关只代表用户允许联网,模型完全可以判断不需要而一次都不调,那种回答与纯思考没有区别,
- 却会被标成「已联网」——这比不标更糟,用户会以为答案有外部依据。
+ Whether this turn actually retrieved evidence from the web. The criterion is "a successful web-search tool call," not "the web-search switch is on": the switch only means the user allowed web search. The model may decide it is unnecessary and never call it. That answer is no different from reasoning alone, yet it would be labeled "searched the web" — worse than no label, because users would think the answer has external evidence.
*/
const webSearched = toolEvents.some(
(event) => WEB_TOOLS.has(event.tool) && event.status === 'success',
@@ -130,16 +121,11 @@ export function AnswerProcessTimeline({
);
const index = useMemo(() => citationIndex(citations), [citations]);
/*
- 整个过程只有一段思考、且不会再长出别的行时不画项目符号。marker 列的意义是让多行对齐成
- 一条线;只剩一行时它退化成「一个元素的项目符号」——没有下一项可对齐,也没有连接线可挂,
- 剩下的只是一个指向空处的圆点。
+ Do not draw a bullet when the whole process is a single reasoning segment and no other row will grow. The marker column exists to align multiple rows into a line; with one row left it degrades into a "bullet for a single element" — nothing below to align to, no connector to hang, only a dot pointing at empty space.
- 判据里带上 toolEvents / searching:流式期间工具行可能正被播放队列押着(见
- buildProcessTimeline 的 holdUnplayed),此刻 items 也只有一项,但行马上就会出现——
- 按当下项数决定就会让圆点凭空冒出来一次。
+ The criterion includes toolEvents / searching: during streaming a tool row may be held by the playback queue (see holdUnplayed in buildProcessTimeline). items has only one entry at that moment, but the row is about to appear — deciding by the current count makes the dot pop in once from nowhere.
- 列宽保留(marker 传 null,而不是绕开 ProcessRailItem):正文要继续与顶行标题左对齐,
- 去掉这一列会让它整块左移到图标那一列,读起来像与顶行平级,而不是顶行展开出的内容。
+ Keep the column width (pass null for the marker, rather than bypassing ProcessRailItem): the body must stay left-aligned with the top-row title. Removing the column shifts the whole block left into the icon column, so it reads as a peer of the top row rather than content the top row expanded.
*/
const soleReasoning =
timeline.items.length === 1 &&
@@ -232,18 +218,13 @@ export function AnswerProcessTimeline({
}
/**
- * 顶行图标。
+ * Top-row icon.
*
- * 它与标题分开着色:标题是 muted 的状态说明,图标用 primary 把「这里发生过一段过程」
- * 标出来——整行都灰下去的话,折叠状态下过程区会整个从视野里消失。
+ * It is colored separately from the title: the title is a muted status note, and the icon uses primary to mark "a process happened here" — if the whole row goes gray, the process area disappears from view while collapsed.
*
- * 转圈只有这一枚:顶行在收起态也在场,且「开了联网到首个工具帧到达」之间还有一段
- * 时间线为空的空档,动效必须由它承担。工具行因此不转圈(见 ProcessToolRow.ToolMarker),
- * 两处同时转是同一件事报两遍,各转各的更乱。
+ * Only this one spins: the top row is present even when collapsed, and there is a gap between "web search turned on" and "the first tool frame arrives" when the timeline is empty, so the motion has to be carried here. Tool rows therefore do not spin (see ProcessToolRow.ToolMarker). Spinning in both places reports the same thing twice, and spinning independently is more confusing.
*
- * 完成态不按「联网过没有」换图标:一列回答里每条顶行的图标都不同会让这一竖排变成
- * 杂色噪点,反而更难扫。联不联网由标题的文字区分(见 timelineTitle),那是同一行里
- * 本来就要读的内容,不必再占一个视觉通道。
+ * The finished state does not swap the icon based on "whether web search happened": a different icon on every top row in a column of answers turns the stack into colored noise and is harder to scan. Whether web search happened is distinguished by the title text (see timelineTitle), which is content on that same row that has to be read anyway, so it does not need another visual channel.
*/
function TimelineIcon({
running,
@@ -277,23 +258,16 @@ function TimelineIcon({
}
/**
- * 生成顶行标题。
+ * Builds the top-row title.
*
- * 完成态只报「做了什么」,不带耗时:总耗时在正文下方的指标行里已经有一份(见
- * utils/metrics.ts),顶行再报一遍是同一个数出现两处,而且它是这一行里唯一会变的字,
- * 眼睛会先去读那个数字,反而盖住「做了什么」。总工具数同理不报;但成功搜索超过一次时
- * 报搜索次数,用户不需要展开就能知道模型分几轮取证。一次搜索本身无需重复“1 次”。
+ * The finished state only reports "what was done," without duration: total duration already appears in the metrics row under the body (see utils/metrics.ts). Reporting it again on the top row puts the same number in two places, and it is the only text on that row that changes, so the eye reads the number first and covers "what was done." The total tool count is omitted for the same reason; but when successful searches exceed one, report the search count so the user can tell how many rounds of evidence the model took without expanding. A single search does not need a redundant "1 time."
*
- * 进行中的联网则相反,顶行要带上当前的查询词:它在这一档里是唯一会变的字,而这正是需要的——
- * 一轮搜索几秒起步,收起态除了顶行没有别的进度通道,静态文案挂在那里与卡死无从区分。
- * 完成态忌讳「唯一会变的数字」是因为那时已无进度可言,两者不冲突。
+ * In-progress web search is the opposite: the top row should carry the current query. In this phase it is the only text that changes, and that is what is needed — a search round starts at several seconds, and while collapsed there is no progress channel besides the top row. Static copy sitting there cannot be told apart from a hang. The finished state avoids "the only number that changes" because there is no progress left then; the two do not conflict.
*
- * 联网与纯思考必须分开报,这不是措辞偏好:纯思考是模型拿自己权重里的知识作答,联网是它
- * 真去外部取了证据回来,两者的可信度来源不同。都写成「已思考」会让用户无法判断这个答案
- * 该不该自己再核一遍——而这恰恰是他看过程区的原因。
+ * Web search and reasoning-only must be reported separately. This is not a wording preference: reasoning-only means the model answered from knowledge in its weights, while web search means it actually fetched external evidence. Their sources of trust differ. Writing both as "reasoned" leaves the user unable to judge whether to check the answer again — which is exactly why they look at the process area.
*
- * @param searchQueries 进行中的搜索查询词(已截断),空数组表示还没拿到
- * @returns 顶行标题文案
+ * @param searchQueries In-progress search queries (already truncated); an empty array means they have not arrived yet
+ * @returns Top-row title copy
*/
function timelineTitle({
t,
@@ -323,19 +297,19 @@ function timelineTitle({
if (webFailed) return searchStatus || t('searchStepFailed');
if (running) {
if (!webRunning) return t('toolsInProgress');
- // 查询词要到模型把 tool_call 参数生成完才随 running 帧到达,在那之前只能报静态文案。
+ // The query arrives with the running frame only after the model finishes generating tool_call arguments; before that, only static copy can be shown.
if (searchQueries.length === 0) return t('searchingPages');
return t('searchingPagesQuery', { query: searchQueries.join(t('queryJoiner')) });
}
if (streaming) return t('reasoningInProgress');
if (webSearched) {
- // 多轮搜索时报次数;单轮保持原文案,避免收起态被无信息量的“1 次”占宽。
+ // Report the count for multi-round search; keep the original copy for a single round so the collapsed state is not taken up by an uninformative "1 time."
if (webSearchCount > 1) {
return t(hasReasoning ? 'searchedAndReasonedCount' : 'searchedCompleteCount', {
count: webSearchCount,
});
}
- // 联网了但没思考(思考深度关闭)仍要报联网:证据来源比「思考过」更值得留在收起态。
+ // If web search ran but there was no reasoning (reasoning depth off), still report web search: the evidence source is more worth keeping in the collapsed state than "reasoned."
return t(hasReasoning ? 'searchedAndReasoned' : 'searchedComplete');
}
if (hasReasoning) return t('reasoningComplete');
diff --git a/webdemo/frontend/src/pages/playground/components/AttachmentPreview.tsx b/webdemo/frontend/src/pages/playground/components/AttachmentPreview.tsx
index 42f58dc..8fa4dfe 100644
--- a/webdemo/frontend/src/pages/playground/components/AttachmentPreview.tsx
+++ b/webdemo/frontend/src/pages/playground/components/AttachmentPreview.tsx
@@ -1,9 +1,9 @@
/**
- * 附件预览列表(待发送态与消息气泡只读态共用)。
+ * Attachment preview list (shared by the pending-send state and the read-only state in a message bubble).
*
- * 用途:把用户上传的多模态附件按类别渲染为缩略图/播放器/文件卡片。
- * - 传入 `onRemove` 视为「待发送态」:紧凑瓦片 + 右上角移除按钮,不内联播放。
- * - 不传 `onRemove` 视为「只读展示态」:图片可点击放大,视频/音频内联播放,文件可下载。
+ * Purpose: render uploaded multimodal attachments by category as thumbnails, players, or file cards.
+ * - Passing `onRemove` is the "pending-send" state: compact tiles + a remove button at the top right, no inline playback.
+ * - Omitting `onRemove` is the "read-only" state: images can be clicked to enlarge, video/audio play inline, and files can be downloaded.
*/
import { useEffect, useState } from 'react';
@@ -14,20 +14,20 @@ import { formatBytes } from '../utils/attachments';
interface AttachmentPreviewProps {
attachments: Attachment[];
- /** 提供则进入待发送态并渲染移除按钮 */
+ /** When provided, enter the pending-send state and render the remove button */
onRemove?: (id: string) => void;
- /** 只读态点击图片放大 */
+ /** Click an image to enlarge it in the read-only state */
onImageClick?: (src: string) => void;
- /** 靠右对齐(用户气泡场景) */
+ /** Align to the right (user-bubble case) */
align?: 'start' | 'end';
}
/**
- * 渲染附件列表。
- * @param attachments 附件数组
- * @param onRemove 移除回调(存在则为待发送态)
- * @param onImageClick 图片放大回调(只读态)
- * @param align 对齐方向
+ * Renders the attachment list.
+ * @param attachments Attachment array
+ * @param onRemove Remove callback (present means the pending-send state)
+ * @param onImageClick Image-enlarge callback (read-only state)
+ * @param align Alignment direction
*/
export function AttachmentPreview({
attachments,
@@ -59,7 +59,7 @@ export function AttachmentPreview({
);
}
-/** 单个附件:按 kind 分支渲染 */
+/** A single attachment: render by kind */
function AttachmentItem({
att,
readOnly,
@@ -85,7 +85,7 @@ function AttachmentItem({
);
}
- // 只读态:视频/音频内联播放
+ // Read-only state: play video/audio inline
if (readOnly && att.kind === 'video') {
return <video src={src} controls className="max-h-44 rounded-xl border border-border/60" />;
}
@@ -98,7 +98,7 @@ function AttachmentItem({
);
}
- // 其余(待发送态的视频/音频,以及任意态的文件)统一用文件卡片
+ // Everything else (pending-send video/audio, and files in any state) uses a file card
return <FileChip att={att} readOnly={readOnly} />;
}
@@ -136,7 +136,7 @@ function useProtectedAssetSrc(att: Attachment): string {
return src;
}
-/** 文件/媒体的卡片式展示:图标 + 名称 + 大小;只读态可下载 */
+/** Card display for a file or media item: icon + name + size; downloadable in the read-only state */
function FileChip({ att, readOnly }: { att: Attachment; readOnly: boolean }) {
const { t } = useTranslation('playground');
const inner = (
@@ -167,7 +167,7 @@ function FileChip({ att, readOnly }: { att: Attachment; readOnly: boolean }) {
return inner;
}
-/** 按 kind 的图标 */
+/** Icon by kind */
function KindIcon({ kind }: { kind: Attachment['kind'] }) {
if (kind === 'video') {
return (
@@ -221,7 +221,7 @@ function KindIcon({ kind }: { kind: Attachment['kind'] }) {
);
}
-/** 移除按钮的叉号 */
+/** The X on the remove button */
function CloseIcon() {
return (
<svg
diff --git a/webdemo/frontend/src/pages/playground/components/ChatComposer.test.tsx b/webdemo/frontend/src/pages/playground/components/ChatComposer.test.tsx
index 7a67364..00ef141 100644
--- a/webdemo/frontend/src/pages/playground/components/ChatComposer.test.tsx
+++ b/webdemo/frontend/src/pages/playground/components/ChatComposer.test.tsx
@@ -66,7 +66,7 @@ describe('ChatComposer', () => {
const toggle = screen.getByRole('switch', { name: '联网搜索' });
expect(toggle).toHaveAttribute('aria-checked', 'true');
- // 联网与思考是同级能力开关,开启态统一走弱底;实底只留给发送按钮
+ // Web search and reasoning are peer capability switches; the on state uses the same weak fill, and a solid fill is reserved for the send button
expect(toggle).toHaveClass('bg-primary/10', 'text-primary');
expect(toggle).not.toHaveClass('text-primary-foreground');
expect(
diff --git a/webdemo/frontend/src/pages/playground/components/ChatComposer.tsx b/webdemo/frontend/src/pages/playground/components/ChatComposer.tsx
index b49ab8f..d8500f3 100644
--- a/webdemo/frontend/src/pages/playground/components/ChatComposer.tsx
+++ b/webdemo/frontend/src/pages/playground/components/ChatComposer.tsx
@@ -1,8 +1,7 @@
/**
- * 对话输入框(含底部工具行 + 发送/停止按钮)。
+ * Chat input (bottom tool row + send/stop button).
*
- * 用途:火山方舟风格的大圆角输入框。Enter 发送、Shift+Enter 换行;流式生成时发送键变停止键。
- * 文本域随内容自适应高度(上限受控)。
+ * Purpose: a large rounded input in the Volcano Ark style. Enter sends, Shift+Enter inserts a newline; while streaming, the send key becomes a stop key. The textarea grows with content (capped).
*/
import { useEffect, useRef, useState } from 'react';
@@ -23,26 +22,26 @@ import {
interface ChatComposerProps {
thinkingDepth: ThinkingDepth;
onThinkingDepthChange: (depth: ThinkingDepth) => void;
- /** 当前模型是否允许展示思考(false 时隐藏思考开关) */
+ /** Whether the current model may show reasoning (when false, hide the reasoning switch) */
showReasoning: boolean;
- /** 当前模型是否允许展示联网搜索入口 */
+ /** Whether the current model may show the web-search entry */
webSearchAvailable: boolean;
- /** 当前模型允许的输入模态,来自模型 capabilities.input_* */
+ /** Input modalities the current model allows, from model capabilities.input_* */
attachmentCapabilities?: Record<string, boolean>;
- /** 联网搜索开关 */
+ /** Web-search switch */
webSearch: boolean;
onWebSearchChange: (webSearch: boolean) => void;
- /** 是否正在流式生成 */
+ /** Whether generation is currently streaming */
loading: boolean;
- /** 是否禁用发送(如无模型/无密钥) */
+ /** Whether sending is disabled (for example, no model or no secret) */
disabled?: boolean;
- /** 禁用发送时的用户可读原因 */
+ /** User-readable reason when sending is disabled */
disabledReason?: string;
- /** 发送(带可选多模态附件) */
+ /** Send (with optional multimodal attachments) */
onSend: (text: string, attachments?: Attachment[]) => void;
- /** 停止生成 */
+ /** Stop generation */
onStop: () => void;
- /** 受控输入值(供任务卡片填充) */
+ /** Controlled input value (filled by task cards) */
value: string;
onValueChange: (v: string) => void;
}
@@ -50,7 +49,7 @@ interface ChatComposerProps {
const MAX_TEXTAREA_HEIGHT = 200;
/**
- * 输入框组件。
+ * Input component.
*/
export function ChatComposer({
thinkingDepth,
@@ -72,23 +71,23 @@ export function ChatComposer({
const taRef = useRef<HTMLTextAreaElement>(null);
const fileRef = useRef<HTMLInputElement>(null);
const { toast } = useToast();
- // 待发送附件(base64 data URL),仅会话内存,发送后清空
+ // Pending attachments (base64 data URL), held only in session memory and cleared after send
const [attachments, setAttachments] = useState<Attachment[]>([]);
const submittingRef = useRef(false);
const [submitting, setSubmitting] = useState(false);
const [uploadingCount, setUploadingCount] = useState(0);
const reservedRef = useRef(0);
- // 拖拽悬停高亮
+ // Drag-hover highlight
const [dragging, setDragging] = useState(false);
- // 点击放大预览的图片
+ // Image opened in the enlarge preview
const [preview, setPreview] = useState<string | null>(null);
const attachmentAccept = attachmentAcceptForCapabilities(attachmentCapabilities);
const attachmentKinds = supportedAttachmentKinds(attachmentCapabilities);
const canAttach = attachmentKinds.length > 0;
useEffect(() => {
- // 模型能力切换需要同步清理已选附件,避免把不支持的输入带进下一次请求。
- // 这里是受控的状态归一化,不是异步数据获取。
+ // Switching model capabilities must also clear selected attachments, so an unsupported input is not carried into the next request.
+ // This is controlled state normalization, not an async data fetch.
// eslint-disable-next-line react-hooks/set-state-in-effect
setAttachments((current) => {
const compatible = current.filter(
@@ -101,7 +100,7 @@ export function ChatComposer({
});
}, [attachmentCapabilities, t, toast]);
- // 自适应高度:内容变化时按 scrollHeight 调整(上限封顶后转内部滚动)
+ // Auto height: on content change, adjust by scrollHeight (once capped, switch to internal scrolling)
useEffect(() => {
const el = taRef.current;
if (!el) return;
@@ -109,9 +108,9 @@ export function ChatComposer({
el.style.height = `${Math.min(el.scrollHeight, MAX_TEXTAREA_HEIGHT)}px`;
}, [value]);
- // 外部把文案填入输入框(如点击「试试以下任务」卡片)后,焦点并不在输入框,导致回车发送失效。
- // 若已有内容但焦点不在输入框,则自动聚焦并把光标移到末尾,保证「填入即可回车发送」。
- // 正常打字时焦点已在输入框,activeElement 判断会跳过,不会重复抢焦。
+ // After outside copy is filled into the input (for example, clicking a "try these tasks" card), focus is not in the input, so Enter-to-send fails.
+ // If there is already content but focus is not in the input, focus it and move the caret to the end, so "fill in and press Enter to send" works.
+ // During normal typing focus is already in the input, so the activeElement check skips and does not steal focus again.
useEffect(() => {
const el = taRef.current;
if (!el || !value || document.activeElement === el) return;
@@ -120,7 +119,7 @@ export function ChatComposer({
el.setSelectionRange(end, end);
}, [value]);
- // 读取并追加附件:超出总数上限截断,逐个校验,失败项弹 toast
+ // Read and append attachments: truncate past the total cap, validate one by one, and toast the failures
async function addFiles(files: File[]) {
if (files.length === 0 || !canAttach) {
if (files.length > 0) toast({ title: t('modelDoesNotSupportAttachments'), variant: 'error' });
@@ -161,10 +160,10 @@ export function ChatComposer({
function handlePickFiles(files: FileList | null) {
if (files) void addFiles(Array.from(files));
- if (fileRef.current) fileRef.current.value = ''; // 允许重复选同一文件
+ if (fileRef.current) fileRef.current.value = ''; // Allow selecting the same file again
}
- // 粘贴含文件时(截图/复制文件)自动加入,并阻止把文件名当文本贴入
+ // When a paste contains files (screenshot / copied file), add them automatically and do not paste the file name as text
function handlePaste(e: React.ClipboardEvent<HTMLTextAreaElement>) {
const files = Array.from(e.clipboardData.files);
if (files.length === 0) return;
@@ -176,14 +175,14 @@ export function ChatComposer({
void addFiles(files);
}
- // 拖拽上传:仅在真正含文件时高亮/接收,避免拖拽文本触发
+ // Drag-and-drop upload: highlight and accept only when there are real files, so dragging text does not trigger it
function handleDragOver(e: React.DragEvent) {
if (!canAttach || !Array.from(e.dataTransfer.types).includes('Files')) return;
e.preventDefault();
setDragging(true);
}
function handleDragLeave(e: React.DragEvent) {
- // 仅当离开整个容器(而非子元素间移动)时取消高亮
+ // Cancel the highlight only when leaving the whole container, not when moving between child elements
if (e.currentTarget.contains(e.relatedTarget as Node)) return;
setDragging(false);
}
@@ -257,7 +256,7 @@ export function ChatComposer({
dragging ? 'ring-2 ring-primary/60' : 'ring-border/60'
}`}
>
- {/* 拖拽悬停提示 */}
+ {/* Drag-hover hint */}
{dragging && (
<div className="pointer-events-none absolute inset-0 z-10 flex items-center justify-center rounded-2xl bg-primary/5 text-sm font-medium text-primary">
{t('releaseToUpload')}
@@ -269,7 +268,7 @@ export function ChatComposer({
</p>
)}
- {/* 待发送附件预览 */}
+ {/* Pending-attachment preview */}
{attachments.length > 0 && (
<div className="mb-1.5 px-1">
<AttachmentPreview
@@ -325,7 +324,7 @@ export function ChatComposer({
);
}
-/** 发送/停止按钮:流式时显示停止方块,否则显示上箭头 */
+/** Send/stop button: a stop square while streaming, otherwise an up arrow */
function SendButton({
loading,
disabled,
diff --git a/webdemo/frontend/src/pages/playground/components/CitationBadge.test.tsx b/webdemo/frontend/src/pages/playground/components/CitationBadge.test.tsx
index 41a4ac4..a3ac875 100644
--- a/webdemo/frontend/src/pages/playground/components/CitationBadge.test.tsx
+++ b/webdemo/frontend/src/pages/playground/components/CitationBadge.test.tsx
@@ -14,7 +14,7 @@ const citation = {
snippet: '这里是来源摘要,用于在不离开回答时快速判断来源是否相关。',
};
-/** 替身弹窗:记录 openCitationWindow 最终跳到哪个地址。 */
+/** Stand-in window: records which address openCitationWindow finally navigates to. */
function stubPopup() {
const replace = vi.fn();
const popup = { opener: {}, location: { replace } } as unknown as Window;
@@ -45,7 +45,7 @@ describe('CitationBadge', () => {
expect(badge).toHaveTextContent('2');
expect(badge).toHaveAttribute('data-citation-badge');
expect(badge).toHaveAttribute('data-citation-url', citation.url);
- // 相对定位上移而非 <sup>:不参与行盒计算,正文行高不被撑开
+ // Shift up with relative positioning rather than <sup>: it does not join line-box layout, so the body line height is not stretched
expect(badge).toHaveClass('relative', '-top-[0.3em]');
});
diff --git a/webdemo/frontend/src/pages/playground/components/CitationBadge.tsx b/webdemo/frontend/src/pages/playground/components/CitationBadge.tsx
index 75929ad..ca2e942 100644
--- a/webdemo/frontend/src/pages/playground/components/CitationBadge.tsx
+++ b/webdemo/frontend/src/pages/playground/components/CitationBadge.tsx
@@ -1,12 +1,10 @@
/**
- * 正文内的引用角标。
+ * Citation badge inside the body.
*
- * 用途:把命中来源的 Markdown 链接渲染成与来源列表同号的上标数字,
- * 悬浮出预览卡、点击唤起右侧来源面板并定位到该条(未接 onActivate 时退回新窗口打开原文)。
+ * Purpose: render a Markdown link that matches a source as a superscript number with the same index as the source list. Hover shows a preview card; click opens the source panel on the right and scrolls to that item (when onActivate is not wired, fall back to opening the original in a new window).
*
- * 为什么用 `relative + top` 而不是 `<sup>` / `vertical-align: super`:
- * 后两者会抬高行内盒并撑高整行行高,正文读起来忽上忽下;相对定位不参与行盒计算,
- * 角标视觉上升但版面完全不动。
+ * Why `relative + top` instead of `<sup>` / `vertical-align: super`:
+ * the latter two raise the inline box and stretch the whole line height, so the body reads as jumping up and down. Relative positioning does not join line-box layout, so the badge rises visually but the layout does not move at all.
*/
import { useTranslation } from 'react-i18next';
@@ -18,28 +16,28 @@ import { isNativeOpenIntent, openCitationWindow, safeCitationHref } from '../uti
import { CitationPreviewCard } from './CitationPreview';
interface CitationBadgeProps {
- /** 角标对应的来源。 */
+ /** Source this badge corresponds to. */
citation: Citation;
- /** 来源序号(从 1 起,与底部参考资料、来源面板同号)。 */
+ /** Source index (starting at 1, the same number as the references at the bottom and the source panel). */
index: number;
- /** 点击角标时的接管动作(打开来源面板并定位);不传则维持新窗口打开原文。 */
+ /** Takeover action when the badge is clicked (open the source panel and locate the item); when omitted, keep opening the original in a new window. */
onActivate?: () => void;
}
/**
- * 渲染一个可预览、可跳转的引用角标。
- * @param citation 角标对应的来源
- * @param index 来源序号(从 1 起)
- * @param onActivate 点击时的接管动作,缺省为新窗口打开原文
- * @returns 上标数字角标;地址非法时退化为不可点的纯数字
+ * Renders a citation badge that can be previewed and followed.
+ * @param citation Source this badge corresponds to
+ * @param index Source index (starting at 1)
+ * @param onActivate Takeover action on click; default is to open the original in a new window
+ * @returns A superscript number badge; an illegal address degrades to a non-clickable plain number
*/
export function CitationBadge({ citation, index, onActivate }: CitationBadgeProps) {
const { t } = useTranslation('playground');
const href = safeCitationHref(citation.url);
const label = t('citationIndexLabel', { index });
- // data-citation-badge 让 MarkdownRenderer 的 `[&_a]` 基础样式跳过角标,
- // 否则正文链接的下划线与主色会盖掉角标自身的配色。
+ // data-citation-badge makes MarkdownRenderer's `[&_a]` base styles skip the badge,
+ // otherwise the body link's underline and primary color cover the badge's own colors.
const badgeClassName = cn(
'relative -top-[0.3em] mx-[0.1em] inline-flex h-[1.15em] min-w-[1.15em] items-center justify-center',
'rounded-[0.35em] bg-muted px-[0.28em] align-baseline text-[0.7em] font-medium leading-none',
@@ -66,11 +64,11 @@ export function CitationBadge({ citation, index, onActivate }: CitationBadgeProp
data-citation-url={href}
aria-label={label}
onClick={(event) => {
- // Cmd/Ctrl/中键仍按浏览器原生语义直接开新标签,不抢高级用户的习惯
+ // Cmd/Ctrl/middle-click still opens a new tab with native browser semantics, and does not override that habit for advanced users
if (isNativeOpenIntent(event)) return;
event.preventDefault();
event.stopPropagation();
- // 接了面板就交给面板定位高亮;没接(如独立预览场景)才退回打开原文
+ // When a panel is wired, hand highlighting and scrolling to the panel; only when it is not (for example, a standalone preview) fall back to opening the original
if (onActivate) onActivate();
else openCitationWindow(href);
}}
diff --git a/webdemo/frontend/src/pages/playground/components/CitationDrawer.test.tsx b/webdemo/frontend/src/pages/playground/components/CitationDrawer.test.tsx
index 607c442..bd06ab9 100644
--- a/webdemo/frontend/src/pages/playground/components/CitationDrawer.test.tsx
+++ b/webdemo/frontend/src/pages/playground/components/CitationDrawer.test.tsx
@@ -17,14 +17,14 @@ function renderDrawer(activeUrl?: string) {
);
}
-/** jsdom 不实现 scrollIntoView,逐例装桩并返回它便于断言定位行为。 */
+/** jsdom does not implement scrollIntoView; install a stub per case and return it so location behavior can be asserted. */
function stubScrollIntoView() {
const scrollIntoView = vi.fn();
Element.prototype.scrollIntoView = scrollIntoView;
return scrollIntoView;
}
-/** 带后端编号的来源:编号刻意与数组下标错开。 */
+/** Source with a backend number: the number is deliberately offset from the array index. */
const refCitations = [
{ ref: 2, url: 'https://www.openbmb.cn/news', title: 'MiniCPM 官方说明' },
{ ref: 5, url: 'https://example.com/a', title: '示例来源' },
@@ -41,14 +41,14 @@ describe('CitationDrawer', () => {
const links = screen.getAllByRole('link');
expect(links).toHaveLength(3);
expect(links[0]).toHaveAccessibleName(/MiniCPM 官方说明/);
- // 没有 activeUrl 时不该有任何一条被标为当前项
+ // Without activeUrl, no item should be marked current
expect(document.querySelector('[aria-current="true"]')).toBeNull();
});
it('列表序号取后端下发的 ref,与正文角标同号', () => {
render(<CitationDrawer citations={refCitations} onClose={() => undefined} />);
- // 数组下标会给出 01、02;正文角标写的是 02、05,两处不同号就等于点不回去。
+ // Array indexes would yield 01 and 02; the body badges say 02 and 05. Different numbers in the two places means you cannot click back.
expect(screen.getByText('02')).toBeInTheDocument();
expect(screen.getByText('05')).toBeInTheDocument();
expect(screen.queryByText('01')).toBeNull();
@@ -60,7 +60,7 @@ describe('CitationDrawer', () => {
const active = screen.getByRole('link', { name: /第三个来源/ });
expect(active).toHaveAttribute('aria-current', 'true');
expect(active).toHaveClass('bg-primary/[0.12]', 'ring-1', 'ring-primary/30');
- // 只有命中那条是当前项
+ // Only the matching item is current
expect(document.querySelectorAll('[aria-current="true"]')).toHaveLength(1);
});
diff --git a/webdemo/frontend/src/pages/playground/components/CitationDrawer.tsx b/webdemo/frontend/src/pages/playground/components/CitationDrawer.tsx
index 624ee4a..1d9ed2b 100644
--- a/webdemo/frontend/src/pages/playground/components/CitationDrawer.tsx
+++ b/webdemo/frontend/src/pages/playground/components/CitationDrawer.tsx
@@ -1,9 +1,7 @@
/**
- * 回答引用来源面板。
+ * Source panel for an answer's citations.
*
- * 用途:集中浏览本轮回答的全部来源;点击任一来源在新窗口打开原文。
- * 桌面端由 PlaygroundLayout 以非模态并排形式呈现(正文仍可读可点),窄屏退化为覆盖式抽屉。
- * 正文角标点击后会带着 activeUrl 进来,本组件负责把那一条滚入视野并保持选中态。
+ * Purpose: browse every source used by this answer in one place; clicking a source opens the original in a new window. On desktop, PlaygroundLayout presents it as a non-modal side-by-side pane (the body stays readable and clickable); on a narrow screen it degrades to an overlay drawer. After a body badge is clicked, activeUrl comes in with it, and this component scrolls that item into view and keeps it selected.
*/
import { useEffect, useRef } from 'react';
@@ -22,25 +20,25 @@ import {
import { CitationFavicon } from './CitationFavicon';
interface CitationDrawerProps {
- /** 回答使用的全部来源。 */
+ /** All sources used by the answer. */
citations: Citation[];
- /** 需要定位并高亮的来源地址;来自正文角标点击,缺省表示不高亮任何一条。 */
+ /** Source address to locate and highlight; comes from a body-badge click. Omitted means highlight nothing. */
activeUrl?: string;
- /** 关闭面板。 */
+ /** Close the panel. */
onClose: () => void;
}
/**
- * 渲染 Playground 主布局内的引用来源工作区。
- * @param citations 回答使用的全部来源
- * @param activeUrl 需要定位并高亮的来源地址
- * @param onClose 关闭面板
- * @returns 来源面板内容
+ * Renders the citation workspace inside the Playground main layout.
+ * @param citations All sources used by the answer
+ * @param activeUrl Source address to locate and highlight
+ * @param onClose Close the panel
+ * @returns Source panel content
*/
export function CitationDrawer({ citations, activeUrl, onClose }: CitationDrawerProps) {
const { t } = useTranslation('playground');
const title = t('referencesTitle', { count: citations.length });
- // 用归一化后的 key 比对:模型正文里的链接常与来源数据差一个末尾斜杠或查询参数顺序。
+ // Compare with the normalized key: links in the model body often differ from source data by a trailing slash or query-parameter order.
const activeKey = activeUrl ? citationURLKey(activeUrl) : undefined;
const itemRefs = useRef(new Map<string, HTMLLIElement>());
@@ -48,7 +46,7 @@ export function CitationDrawer({ citations, activeUrl, onClose }: CitationDrawer
if (!activeKey) return;
const node = itemRefs.current.get(activeKey);
if (!node) return;
- // block:'nearest' —— 目标已在视野内时不滚动,避免每点一个角标列表都弹一下。
+ // block:'nearest' — do not scroll when the target is already in view, so the list does not jump on every badge click.
const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
node.scrollIntoView({ block: 'nearest', behavior: reduceMotion ? 'auto' : 'smooth' });
}, [activeKey]);
@@ -88,7 +86,7 @@ export function CitationDrawer({ citations, activeUrl, onClose }: CitationDrawer
<span
className={cn(
'pt-0.5 text-xs font-medium tabular-nums',
- // 序号跟着变色:选中态不能只靠背景色传达(颜色不是唯一信号)
+ // The index changes color with the selection: the selected state cannot be conveyed by background color alone (color is not the only signal)
isActive ? 'text-primary' : 'text-muted-foreground/60',
)}
>
@@ -105,9 +103,7 @@ export function CitationDrawer({ citations, activeUrl, onClose }: CitationDrawer
{sourceTitle}
</span>
{/*
- 同 CitationPreview:摘要不能带 block 等 display 工具类,Tailwind 3.4 的
- display 排在 line-clamp 之后会把 display:-webkit-box 覆盖掉,clamp 失效后
- 每条来源都会展开成整篇网页正文。line-clamp-2 自身即块级盒。
+ Same as CitationPreview: the summary must not carry display utilities such as block. In Tailwind 3.4, display comes after line-clamp and overrides display:-webkit-box. Once clamp fails, every source expands into the full page body. line-clamp-2 is itself a block box.
*/}
{citation.snippet ? (
<span className="mt-0.5 line-clamp-2 text-xs leading-5 text-muted-foreground/90">
@@ -125,9 +121,7 @@ export function CitationDrawer({ citations, activeUrl, onClose }: CitationDrawer
const rowClassName = cn(
'grid min-h-16 grid-cols-[1.5rem_minmax(0,1fr)_1rem] gap-2.5 rounded-xl px-2.5 py-2.5 sm:px-3',
/*
- 选中态用 primary 淡染 + 内描边,不把底色加深:同 SourcesChip 的推导,
- muted 系混进面板底色会掉饱和、显脏。比 hover 重一档,才分得清「我点中的是这条」
- 和「鼠标正掠过这条」。
+ The selected state uses a light primary wash plus an inner stroke, and does not darken the background: same reasoning as SourcesChip, mixing the muted family into the panel background drops saturation and looks dirty. One step heavier than hover, so "the one I clicked" is distinct from "the one the pointer is passing over."
*/
isActive ? 'bg-primary/[0.12] ring-1 ring-inset ring-primary/30' : 'bg-background/20',
);
diff --git a/webdemo/frontend/src/pages/playground/components/CitationFavicon.tsx b/webdemo/frontend/src/pages/playground/components/CitationFavicon.tsx
index ef7270b..155e836 100644
--- a/webdemo/frontend/src/pages/playground/components/CitationFavicon.tsx
+++ b/webdemo/frontend/src/pages/playground/components/CitationFavicon.tsx
@@ -1,7 +1,7 @@
/**
- * 引用来源站点图标。
+ * Site icon for a citation source.
*
- * 用途:统一来源列表、引用标签、过程时间线、来源胶囊和预览浮层的 favicon 加载与失败回退。
+ * Purpose: one favicon load and failure fallback for the source list, citation label, process timeline, source chip, and preview popover.
*/
import { useState } from 'react';
@@ -12,31 +12,29 @@ import { cn } from '@map/ui';
import { citationFavicon } from '../utils/citations';
/*
- 失败记录必须是模块级的:同一个站点在一条消息里会同时出现在工具行、来源胶囊、抽屉和
- hover 卡上,失败态若只存在组件内,没有根路径 favicon.ico 的站点每处都要各自失败一次。
- 只记失败不记成功——成功的图片由浏览器 HTTP 缓存兜住,这里不需要再存一份。
+ Failure records must be module-level: the same site can appear at once on a tool row, the source chip, the drawer, and the hover card in one message. If the failure state lives only inside the component, a site with no root favicon.ico fails once in every place. Record only failures, not successes — a successful image is covered by the browser HTTP cache, so there is no need to store another copy here.
*/
const failedFavicons = new Set<string>();
interface CitationFaviconProps {
- /** 来源地址。 */
+ /** Source address. */
url: string;
- /** 图标容器样式。 */
+ /** Icon container styles. */
className?: string;
- /** 图片样式。 */
+ /** Image styles. */
imageClassName?: string;
}
/**
- * 显示来源 favicon;加载失败或 URL 无效时显示通用网页图标。
- * @param url 来源地址
- * @param className 图标容器样式
- * @param imageClassName 图片样式
- * @returns 来源站点图标
+ * Shows the source favicon; on load failure or an invalid URL, shows a generic web icon.
+ * @param url Source address
+ * @param className Icon container styles
+ * @param imageClassName Image styles
+ * @returns Source site icon
*/
export function CitationFavicon({ url, className, imageClassName }: CitationFaviconProps) {
const favicon = citationFavicon(url);
- // 初值读缓存,让后挂载的同域图标直接走兜底图标,不再发一次注定失败的请求
+ // The initial value reads the cache, so a later-mounted same-origin icon goes straight to the fallback and does not send a request that is bound to fail
const [failed, setFailed] = useState(() => (favicon ? failedFavicons.has(favicon) : false));
const broken = failed || (favicon ? failedFavicons.has(favicon) : false);
diff --git a/webdemo/frontend/src/pages/playground/components/CitationPreview.tsx b/webdemo/frontend/src/pages/playground/components/CitationPreview.tsx
index 3c3f8c0..6049cb5 100644
--- a/webdemo/frontend/src/pages/playground/components/CitationPreview.tsx
+++ b/webdemo/frontend/src/pages/playground/components/CitationPreview.tsx
@@ -1,8 +1,7 @@
/**
- * 引用来源的悬浮预览卡片。
+ * Hover preview card for a citation source.
*
- * 用途:正文角标(CitationBadge)与其他来源入口 hover 时的统一预览,
- * 用户无需离开回答即可判断来源;卡片自身也可点击,在新窗口打开原文。
+ * Purpose: the shared preview when hovering a body badge (CitationBadge) or another source entry, so the user can judge the source without leaving the answer. The card itself is also clickable and opens the original in a new window.
*/
import { ExternalLink } from 'lucide-react';
@@ -18,14 +17,14 @@ import {
import { CitationFavicon } from './CitationFavicon';
interface CitationPreviewCardProps {
- /** 要预览的来源。 */
+ /** Source to preview. */
citation: Citation;
}
/**
- * 渲染单条来源的标题、域名和摘要。
- * @param citation 来源数据
- * @returns 来源预览内容
+ * Renders the title, domain, and summary of one source.
+ * @param citation Source data
+ * @returns Source preview content
*/
export function CitationPreviewCard({ citation }: CitationPreviewCardProps) {
const { t } = useTranslation('playground');
@@ -43,9 +42,7 @@ export function CitationPreviewCard({ citation }: CitationPreviewCardProps) {
<ExternalLink className="size-3.5 shrink-0 text-muted-foreground/70" aria-hidden="true" />
</div>
{/*
- 标题与摘要都不能再加 block/flex 等 display 工具类:Tailwind 3.4 把 display 排在
- line-clamp 之后,display:block 会覆盖 line-clamp 依赖的 display:-webkit-box,
- -webkit-line-clamp 随即失效,整段网页正文铺开会把预览卡撑出视口。
+ Neither the title nor the summary may add display utilities such as block/flex: Tailwind 3.4 places display after line-clamp, and display:block overrides the display:-webkit-box that line-clamp depends on. -webkit-line-clamp then fails, and the full page body spreads out and pushes the preview card out of the viewport.
*/}
<p className="mt-3 line-clamp-2 text-sm font-semibold leading-5 text-foreground">{title}</p>
{citation.snippet ? (
@@ -57,7 +54,7 @@ export function CitationPreviewCard({ citation }: CitationPreviewCardProps) {
</>
);
- // 预览卡片本身也可点击打开原文:避免 Tooltip 内部的非交互卡片让用户感到"点不动"。
+ // The preview card itself can be clicked to open the original: avoid a non-interactive card inside the Tooltip that feels like it "cannot be clicked."
if (!href) {
return <div className="w-[min(22rem,calc(100vw-2rem))] p-3.5 text-left">{inner}</div>;
}
@@ -70,7 +67,7 @@ export function CitationPreviewCard({ citation }: CitationPreviewCardProps) {
data-citation-url={href}
aria-label={`${title},${t('openSource')}`}
onClick={(event) => {
- // 修饰键 + 中键 → 让原生"在新标签页打开"行为继续生效
+ // Modifier key + middle click → let the native "open in a new tab" behavior keep working
if (isNativeOpenIntent(event)) return;
event.preventDefault();
event.stopPropagation();
diff --git a/webdemo/frontend/src/pages/playground/components/ComposerSlot.tsx b/webdemo/frontend/src/pages/playground/components/ComposerSlot.tsx
index 898cf9a..7a7dd51 100644
--- a/webdemo/frontend/src/pages/playground/components/ComposerSlot.tsx
+++ b/webdemo/frontend/src/pages/playground/components/ComposerSlot.tsx
@@ -1,7 +1,7 @@
/**
- * 语言模型输入槽:欢迎态与对话态共用的输入框 + 密钥状态行。
+ * Language-model input slot: the input plus the key-status row, shared by the welcome state and the conversation state.
*
- * 用途:避免 Playground 入口重复装配 ChatComposer 与 KeyStatusBar。
+ * Purpose: avoid assembling ChatComposer and KeyStatusBar twice at the Playground entry.
*/
import { ChatComposer } from './ChatComposer';
@@ -19,16 +19,16 @@ interface ComposerSlotProps {
chat: ReturnType<typeof useChat>;
canSend: boolean;
disabledReason?: string;
- /** 当前模型是否允许展示思考(false 时隐藏思考开关) */
+ /** Whether the current model may show reasoning (when false, hide the reasoning switch) */
showReasoning: boolean;
- /** 当前模型是否允许展示联网搜索入口 */
+ /** Whether the current model may show the web-search entry */
webSearchAvailable: boolean;
- /** 当前模型允许的输入模态,来自模型 capabilities.input_* */
+ /** Input modalities the current model allows, from model capabilities.input_* */
attachmentCapabilities?: Record<string, boolean>;
}
/**
- * 输入框槽位。
+ * Input slot.
*/
export function ComposerSlot({
input,
@@ -64,7 +64,7 @@ export function ComposerSlot({
}
/**
- * 输入框下方的会话状态行(密钥自动取默认项目,不再展示选择器)。
+ * Session status row under the input (the key is taken automatically from the default project; the selector is no longer shown).
*/
export function KeyHint({ model }: { model: ReturnType<typeof usePlaygroundModel> }) {
return (
diff --git a/webdemo/frontend/src/pages/playground/components/ComposerToolbar.tsx b/webdemo/frontend/src/pages/playground/components/ComposerToolbar.tsx
index 95aa8fc..c0751ac 100644
--- a/webdemo/frontend/src/pages/playground/components/ComposerToolbar.tsx
+++ b/webdemo/frontend/src/pages/playground/components/ComposerToolbar.tsx
@@ -1,8 +1,7 @@
/**
- * 输入框底部工具行。
+ * Tool row at the bottom of the input.
*
- * 用途:呈现输入框底部的工具按钮组。附件上传(图像/视频/音频/文件)、联网搜索与思考深度均为真功能,
- * 点击切换开/关(联网 → L3 Playground BFF,思考 → reasoning_effort/enable_thinking)。
+ * Purpose: present the tool button group under the input. Attachment upload (image/video/audio/file), web search, and reasoning depth are all real features. Click toggles them on/off (web search → L3 Playground BFF, reasoning → reasoning_effort/enable_thinking).
*/
import { useTranslation } from 'react-i18next';
@@ -15,30 +14,30 @@ import type { AttachmentKind, ThinkingDepth } from '../types';
interface ComposerToolbarProps {
thinkingDepth: ThinkingDepth;
onThinkingDepthChange: (depth: ThinkingDepth) => void;
- /** 当前模型是否允许展示思考(false 时隐藏思考开关) */
+ /** Whether the current model may show reasoning (when false, hide the reasoning switch) */
showReasoning: boolean;
- /** 当前模型是否允许展示联网搜索入口 */
+ /** Whether the current model may show the web-search entry */
webSearchAvailable: boolean;
- /** 联网搜索开关 */
+ /** Web-search switch */
webSearch: boolean;
onWebSearchChange: (webSearch: boolean) => void;
- /** 点击附件按钮(上传图像/视频/音频/文件) */
+ /** Click the attachment button (upload image/video/audio/file) */
onAttach: () => void;
- /** 当前模型是否支持至少一种附件模态 */
+ /** Whether the current model supports at least one attachment modality */
canAttach: boolean;
- /** 当前模型允许上传的附件模态 */
+ /** Attachment modalities the current model allows uploading */
attachmentKinds: AttachmentKind[];
}
/**
- * 工具行。
- * @param thinkingDepth 当前思考深度(off/on)
- * @param onThinkingDepthChange 思考深度变更回调
- * @param showReasoning 当前模型是否允许展示思考(false 时不渲染思考按钮)
- * @param webSearchAvailable 当前模型是否允许展示联网搜索入口
- * @param webSearch 是否开启联网搜索
- * @param onWebSearchChange 联网开关变更回调
- * @param onAttach 附件上传触发
+ * Tool row.
+ * @param thinkingDepth Current reasoning depth (off/on)
+ * @param onThinkingDepthChange Reasoning-depth change callback
+ * @param showReasoning Whether the current model may show reasoning (when false, do not render the reasoning button)
+ * @param webSearchAvailable Whether the current model may show the web-search entry
+ * @param webSearch Whether web search is on
+ * @param onWebSearchChange Web-search switch change callback
+ * @param onAttach Attachment-upload trigger
*/
export function ComposerToolbar({
thinkingDepth,
@@ -57,7 +56,7 @@ export function ComposerToolbar({
const enabled = thinkingDepth !== 'off';
return (
<div className="flex items-center gap-1.5">
- {/* 附件 +:上传图像/视频/音频/文件 */}
+ {/* Attachment +: upload image/video/audio/file */}
{canAttach && (
<Tooltip>
<TooltipTrigger asChild>
@@ -92,7 +91,7 @@ export function ComposerToolbar({
</Tooltip>
)}
- {/* 联网搜索:入口与后端部署开关保持一致。 */}
+ {/* Web search: the entry stays consistent with the backend deployment switch. */}
{webSearchAvailable ? (
<Tooltip>
<TooltipTrigger asChild>
@@ -124,7 +123,7 @@ export function ComposerToolbar({
</Tooltip>
) : null}
- {/* 思考深度:仅支持深度思考的模型展示,默认关闭仍可手动开启。 */}
+ {/* Reasoning depth: shown only for models that support deep reasoning; off by default and can still be turned on manually. */}
{showReasoning && (
<Tooltip>
<TooltipTrigger asChild>
@@ -161,12 +160,10 @@ export function ComposerToolbar({
}
/**
- * 工具行开关按钮的样式。
+ * Styles for a tool-row toggle button.
*
- * 联网搜索与思考深度共用同一套视觉:两者都是「给本次回答附加一种能力」的同级开关,
- * 早先联网用实底、思考用弱底,并排时视觉权重打架。统一取思考深度的弱底方案
- * (实底在输入框里只留给发送按钮)。抽成一处也避免两个开关日后再次漂移。
- * @param active 开关是否处于开启态
+ * Web search and reasoning depth share one visual treatment: both are peer switches that "add a capability to this answer." Earlier, web search used a solid fill and reasoning a weak fill, and side by side their visual weights fought. Use the reasoning-depth weak fill for both (a solid fill inside the input is reserved for the send button). Pulling it into one place also keeps the two switches from drifting apart later.
+ * @param active Whether the switch is on
*/
function toolbarToggleClassName(active: boolean): string {
return cn(
diff --git a/webdemo/frontend/src/pages/playground/components/ExperienceTopBar.tsx b/webdemo/frontend/src/pages/playground/components/ExperienceTopBar.tsx
index 84c1dab..eeb8f94 100644
--- a/webdemo/frontend/src/pages/playground/components/ExperienceTopBar.tsx
+++ b/webdemo/frontend/src/pages/playground/components/ExperienceTopBar.tsx
@@ -1,8 +1,7 @@
/**
- * 体验中心「语音合成 / 实时音视频」顶栏。
+ * Experience-center top bar for "speech synthesis / realtime audio-video."
*
- * 用途:语音合成 / 实时语音共用的轻量顶栏——移动端汉堡键 + 图标 + 标题 + 副标题。
- * 图像解析自带文档工作台顶栏,不走这里。区别于语言模型顶栏(含模型选择器等真功能)。
+ * Purpose: a light top bar shared by speech synthesis and realtime voice — mobile hamburger + icon + title + subtitle. Image parse has its own document-workspace top bar and does not come through here. Distinct from the language-model top bar (which has real features such as the model selector).
*/
import { Link } from 'react-router-dom';
import { AudioWaveform, BookOpen, Phone } from 'lucide-react';
@@ -13,21 +12,21 @@ import { getPortalRouteTitle } from '@/router/routeCopy';
import { experienceDocsPath, type ExperienceKey } from '../utils/experienceRoute';
interface ExperienceTopBarProps {
- /** 顶栏标题(如「语音合成」「实时音视频」) */
+ /** Top-bar title (for example, "Speech synthesis" or "Realtime audio-video") */
title: string;
- /** 副标题,一句话说明能力 */
+ /** Subtitle, one sentence describing the capability */
subtitle?: string;
- /** 标题前图标 */
+ /** Icon before the title */
icon: React.ReactNode;
- /** 当前体验,用于跳转对应模型文档 */
+ /** Current experience, used to jump to the matching model docs */
experience: Exclude<ExperienceKey, 'language'>;
- /** 移动端:显示汉堡键以唤出侧栏抽屉 */
+ /** Mobile: show the hamburger to summon the sidebar drawer */
showMenuButton?: boolean;
onOpenSidebar?: () => void;
}
/**
- * 语音体验顶栏。
+ * Voice-experience top bar.
*/
export function ExperienceTopBar({
title,
@@ -100,8 +99,8 @@ export function ExperienceTopBar({
}
/**
- * 非语言体验顶栏图标。语言对话走独立顶栏,不经过这里。
- * @param experience 当前体验键
+ * Top-bar icon for non-language experiences. Language chat uses its own top bar and does not come through here.
+ * @param experience Current experience key
*/
export function experienceIcon(experience: ExperienceKey): React.ReactNode {
if (experience === 'tts') return <AudioWaveform className="h-4 w-4" />;
diff --git a/webdemo/frontend/src/pages/playground/components/FeedbackDialog.tsx b/webdemo/frontend/src/pages/playground/components/FeedbackDialog.tsx
index 3947f30..1e6bd7d 100644
--- a/webdemo/frontend/src/pages/playground/components/FeedbackDialog.tsx
+++ b/webdemo/frontend/src/pages/playground/components/FeedbackDialog.tsx
@@ -1,13 +1,12 @@
/**
- * 点踩反馈弹窗。
+ * Thumbs-down feedback dialog.
*
- * 用途:用户点踩助手回答后弹出,可多选原因标签 + 填写可选正文,提交上报后端。
- * 点赞不弹此框(直接静默上报),故本组件仅服务点踩场景。
+ * Purpose: after the user thumbs-down an assistant answer, this opens so they can select several reason tags and optionally write a body, then submit it to the backend. A thumbs-up does not open this dialog (it is reported silently), so this component serves only the thumbs-down case.
*
- * @param open 是否打开
- * @param onOpenChange 开合回调
- * @param submitting 提交中(禁用提交按钮)
- * @param onSubmit 提交回调,回传选中原因与正文
+ * @param open Whether it is open
+ * @param onOpenChange Open/close callback
+ * @param submitting Submitting (disables the submit button)
+ * @param onSubmit Submit callback; returns the selected reasons and body
*/
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -36,7 +35,7 @@ export function FeedbackDialog({ open, onOpenChange, submitting, onSubmit }: Fee
const [reasons, setReasons] = useState<string[]>([]);
const [comment, setComment] = useState('');
- // 每次打开重置,避免上次选择残留
+ // Reset on every open so the previous selection does not linger
useEffect(() => {
if (open) {
setReasons([]);
diff --git a/webdemo/frontend/src/pages/playground/components/ImageLightbox.tsx b/webdemo/frontend/src/pages/playground/components/ImageLightbox.tsx
index 492faff..7cd13bd 100644
--- a/webdemo/frontend/src/pages/playground/components/ImageLightbox.tsx
+++ b/webdemo/frontend/src/pages/playground/components/ImageLightbox.tsx
@@ -1,16 +1,11 @@
/**
- * 图片全屏预览(lightbox)。
+ * Full-screen image preview (lightbox).
*
- * 用途:点击原图或对话里的缩略图后放大核对。createPortal 到 body,点遮罩 / 关闭键 / Esc 关闭。
- * 受控:src 为空时不渲染。
+ * Purpose: enlarge an original image or a chat thumbnail for checking. createPortal to body; click the mask, the close key, or Esc to close. Controlled: render nothing when src is empty.
*
- * 校对场景要求能凑近看:滚轮缩放(锚在光标)、拖拽平移、90° 旋转、双击放大。
- * 视图换算全在 useImageZoom 里,和内嵌原图栏共用同一套手感与边界。
- * 遮罩整体作为缩放视口,滚轮落在图外也能缩放;指针手势只挂在图上,
- * 否则在遮罩上拖完松手会被当成「点遮罩关闭」。
+ * Proofreading needs a close look: wheel zoom (anchored at the cursor), drag to pan, 90° rotation, double-click to enlarge. View math all lives in useImageZoom, sharing one feel and the same bounds with the embedded original-image column. The mask as a whole is the zoom viewport, so a wheel event outside the image still zooms; pointer gestures are attached only to the image, otherwise dragging on the mask and releasing is treated as "click the mask to close."
*
- * 无障碍上补齐了模态该有的东西——aria-modal、Tab 焦点不逸出、关闭后焦点还给来源元素。
- * 层级用 z-50(模态层);此前误用 z-[100],那是 toast 的层,会压住提示。
+ * Accessibility fills in what a modal should have — aria-modal, Tab focus that does not escape, and focus returned to the source element on close. The layer is z-50 (the modal layer); z-[100] was used by mistake before, and that is the toast layer, which would cover toasts.
*/
import { useCallback, useEffect, useRef } from 'react';
@@ -21,7 +16,7 @@ import { cn } from '@map/ui';
import { useImageZoom, type ImageZoom } from '../hooks/useImageZoom';
interface ImageLightboxProps {
- /** 预览图片地址;为空表示关闭 */
+ /** Preview image address; empty means closed */
src: string | null;
onClose: () => void;
}
@@ -29,20 +24,20 @@ interface ImageLightboxProps {
const FOCUSABLE = 'button:not([disabled])';
/**
- * 图片预览遮罩。
- * @param src 图片地址,为空则不渲染
- * @param onClose 关闭回调
+ * Image preview mask.
+ * @param src Image address; render nothing when empty
+ * @param onClose Close callback
*/
export function ImageLightbox({ src, onClose }: ImageLightboxProps) {
const { t } = useTranslation('playground');
const zoom = useImageZoom();
const dialogRef = useRef<HTMLDivElement>(null);
const restoreFocusRef = useRef<HTMLElement | null>(null);
- // ref 回调先解构出来:把 zoom 的属性直接塞进 ref 属性,lint 会把整个 zoom 当成 ref。
+ // Destructure the ref callback first: stuffing zoom's properties straight into the ref prop makes lint treat the whole zoom object as the ref.
const { reset, setViewport, setContent } = zoom;
- // 遮罩既要留给键盘/焦点逻辑用,又要交给 zoom 当缩放视口,所以这里合并两个 ref。
- // 回调体必须用花括号:React 19 会把 ref 回调的返回值当成清理函数。
+ // The mask is used both by keyboard/focus logic and by zoom as the zoom viewport, so the two refs are merged here.
+ // The callback body must use braces: React 19 treats a ref callback's return value as a cleanup function.
const attachDialog = useCallback(
(node: HTMLDivElement | null) => {
dialogRef.current = node;
@@ -51,7 +46,7 @@ export function ImageLightbox({ src, onClose }: ImageLightboxProps) {
[setViewport],
);
- // Esc 关闭 + Tab 循环。模态不锁 Tab,焦点会跑到背后的页面上去。
+ // Esc closes and Tab cycles. If a modal does not trap Tab, focus runs off onto the page behind it.
useEffect(() => {
if (!src) return undefined;
function onKey(event: KeyboardEvent) {
@@ -77,7 +72,7 @@ export function ImageLightbox({ src, onClose }: ImageLightboxProps) {
return () => window.removeEventListener('keydown', onKey);
}, [src, onClose]);
- // 打开时记住来源元素并把焦点收进来,关闭时还回去。
+ // On open, remember the source element and pull focus in; on close, give it back.
useEffect(() => {
if (!src) return undefined;
restoreFocusRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
@@ -85,7 +80,7 @@ export function ImageLightbox({ src, onClose }: ImageLightboxProps) {
return () => restoreFocusRef.current?.focus();
}, [src]);
- // 换图时回到初始视图,避免带着上一张的缩放和角度。
+ // On image change, return to the initial view so the previous image's zoom and angle are not carried over.
useEffect(() => {
if (src) reset();
}, [src, reset]);
@@ -120,10 +115,10 @@ export function ImageLightbox({ src, onClose }: ImageLightboxProps) {
onPointerCancel={zoom.onPointerUp}
style={{ transform: zoom.transform }}
className={cn(
- // touch-none:触屏上要拿到 pointermove 才能平移
- // 不加圆角:原图是直角,削角等于改了用户的图;边界靠投影而不是裁切
+ // touch-none: on a touch screen, pointermove has to be received before panning works
+ // No border radius: the original image has square corners, and clipping the corners changes the user's image; the boundary comes from shadow, not clipping
'max-h-full max-w-full touch-none select-none object-contain shadow-2xl will-change-transform',
- // 滚轮与拖拽期间关掉过渡才跟手,按钮与旋转这类离散操作仍然走动画
+ // Turn transitions off during wheel and drag so they track the hand; discrete actions such as buttons and rotation still animate
zoom.animated && 'transition-transform duration-150 ease-out motion-reduce:transition-none',
cursorClass(zoom),
)}
@@ -161,12 +156,12 @@ export function ImageLightbox({ src, onClose }: ImageLightboxProps) {
);
}
-/** 光标:任何倍数都能拖,拖到哪停哪,所以只分抓着与没抓着。 */
+/** Cursor: it can be dragged at any scale and stops where it is released, so the only distinction is grabbing versus not grabbing. */
function cursorClass(zoom: ImageZoom): string {
return zoom.dragging ? 'cursor-grabbing' : 'cursor-grab';
}
-/** 预览工具按钮:反色圆形图标键,触摸目标不小于 44px。 */
+/** Preview tool button: an inverted circular icon key, with a touch target no smaller than 44px. */
function ToolButton({
label,
onClick,
diff --git a/webdemo/frontend/src/pages/playground/components/InlineSourceLinks.tsx b/webdemo/frontend/src/pages/playground/components/InlineSourceLinks.tsx
index d727f5a..1927b29 100644
--- a/webdemo/frontend/src/pages/playground/components/InlineSourceLinks.tsx
+++ b/webdemo/frontend/src/pages/playground/components/InlineSourceLinks.tsx
@@ -1,8 +1,7 @@
/**
- * 过程时间线上内联的来源标题链接。
+ * Inline source-title links on the process timeline.
*
- * 用途:网页读取行就地列出「读了哪几篇」,让展开过程看到的是内容而不是元数据。
- * 链接随工具行主文案同行流动并自动换行,不单独占一行。
+ * Purpose: a page-read row lists "which pages were read" in place, so the expanded process shows content rather than metadata. Links flow on the same line as the tool row's main copy and wrap automatically; they do not take a line of their own.
*/
import { ArrowUpRight } from 'lucide-react';
@@ -19,27 +18,26 @@ import {
} from '../utils/citations';
interface InlineSourceLinksProps {
- /** 该工具行涉及的来源。 */
+ /** Sources involved in this tool row. */
citations: Citation[];
- /** 最多内联几条,超出部分计入 +N。 */
+ /** How many to inline at most; the overflow counts toward +N. */
max?: number;
- /** 单条链接的无障碍文案,需说清点下去会打开什么。 */
+ /** Accessible label for one link; it must say what a click will open. */
linkLabel: (title: string) => string;
- /** 溢出计数的无障碍文案。 */
+ /** Accessible label for the overflow count. */
overflowLabel: (count: number) => string;
}
/**
- * 渲染内联的来源标题链接。
+ * Renders inline source-title links.
*
- * 宽度预算按「抽屉推开主区后」的窄布局取:单条最宽 12rem 截断,这样面板开合两种状态下
- * 都不会把工具行撑出横向滚动。
+ * The width budget is taken from the narrow layout "after the drawer pushes the main area open": a single item truncates at 12rem, so in both the open and closed panel states the tool row is not forced into horizontal scrolling.
*
- * @param citations 来源列表
- * @param max 最多内联数量,默认 MAX_ROW_TITLES
- * @param linkLabel 单条链接的无障碍文案
- * @param overflowLabel 溢出计数的无障碍文案
- * @returns 内联链接;没有可安全打开的来源时不渲染
+ * @param citations Source list
+ * @param max Maximum inline count; default MAX_ROW_TITLES
+ * @param linkLabel Accessible label for one link
+ * @param overflowLabel Accessible label for the overflow count
+ * @returns Inline links; render nothing when no source can be opened safely
*/
export function InlineSourceLinks({
citations,
@@ -71,7 +69,7 @@ export function InlineSourceLinks({
'transition-colors hover:text-foreground focus-visible:text-foreground',
)}
onClick={(event) => {
- // 修饰键点击、中键等交回浏览器;其余走统一的新窗口打开,行为与角标、抽屉一致
+ // Modifier-clicks, middle-click, and the like are handed back to the browser; everything else uses the shared new-window open, consistent with badges and the drawer
if (isNativeOpenIntent(event)) return;
event.preventDefault();
openCitationWindow(citation.url);
diff --git a/webdemo/frontend/src/pages/playground/components/KeyStatusBar.tsx b/webdemo/frontend/src/pages/playground/components/KeyStatusBar.tsx
index bfb191f..e864972 100644
--- a/webdemo/frontend/src/pages/playground/components/KeyStatusBar.tsx
+++ b/webdemo/frontend/src/pages/playground/components/KeyStatusBar.tsx
@@ -1,9 +1,7 @@
/**
- * 会话密钥状态条。
+ * Session key status bar.
*
- * 用途:Playground 不暴露 API Key 选择器——密钥自动取「默认项目」下的 key(见
- * usePlaygroundModel)。本组件只在「免费次数 / 加载中 / 无 Key / 密钥不可用」时给出提示;
- * 免费额度优先展示;全部用完且无用户 Key 时提供「去创建 API Key」引导。
+ * Purpose: Playground does not expose an API Key selector — the secret is taken automatically from the key under the "default project" (see usePlaygroundModel). This component prompts only for "free quota / loading / no Key / secret unavailable." Free quota is shown first; when it is used up and there is no user Key, it offers a "go create an API Key" guide.
*/
import { useNavigate } from 'react-router-dom';
@@ -11,22 +9,22 @@ import { Badge, Button } from '@map/ui';
import { useTranslation } from 'react-i18next';
interface KeyStatusBarProps {
- /** 密钥列表是否加载中 */
+ /** Whether the key list is loading */
loading: boolean;
- /** 是否存在可用 Key */
+ /** Whether a usable Key exists */
hasKeys: boolean;
- /** 明文密钥解密中 */
+ /** Whether the plaintext secret is being decrypted */
secretLoading: boolean;
- /** 明文密钥不可用 */
+ /** Whether the plaintext secret is unavailable */
secretError: boolean;
- /** 当前体验剩余免费次数;undefined 表示状态不可用 */
+ /** Remaining free uses for the current experience; undefined means the status is unavailable */
trialRemaining?: number;
- /** 免费体验状态是否获取失败 */
+ /** Whether fetching the free-trial status failed */
trialError?: boolean;
}
/**
- * 密钥状态指示;无 Key 时引导去创建。
+ * Key status indicator; when there is no Key, guide the user to create one.
*/
export function KeyStatusBar({
loading,
@@ -63,7 +61,7 @@ export function KeyStatusBar({
);
}
- // 账号下无可用 Key:引导去 API Keys 页创建
+ // No usable Key on the account: guide the user to the API Keys page to create one
if (!hasKeys) {
return (
<div className="flex items-center gap-2 text-xs text-muted-foreground">
@@ -89,6 +87,6 @@ export function KeyStatusBar({
</Badge>
);
}
- // 就绪态不展示标记(避免冗余的「会话就绪」),仅在加载/无 Key/出错时给出提示
+ // Do not show a mark in the ready state (avoid a redundant "session ready"); prompt only while loading, with no Key, or on error
return null;
}
diff --git a/webdemo/frontend/src/pages/playground/components/MarkdownRenderer.htmlMath.test.tsx b/webdemo/frontend/src/pages/playground/components/MarkdownRenderer.htmlMath.test.tsx
index 01a51b5..45a9320 100644
--- a/webdemo/frontend/src/pages/playground/components/MarkdownRenderer.htmlMath.test.tsx
+++ b/webdemo/frontend/src/pages/playground/components/MarkdownRenderer.htmlMath.test.tsx
@@ -77,7 +77,7 @@ describe('OCR HTML 表格内公式', () => {
content={`<table><tr>${formulas.map((formula) => `<td>${formula}</td>`).join('')}</tr></table>`}
/>,
);
- // tag 仅适用于 displayMode;行内模式仍保留源码和安全回退。
+ // tag applies only in displayMode; inline mode still keeps the source and the safe fallback.
const expectedErrors = latex.includes('\\tag') ? 2 : 0;
expect(container.querySelectorAll('.katex')).toHaveLength(4 - expectedErrors);
expect(container.querySelectorAll('.katex-error')).toHaveLength(expectedErrors);
diff --git a/webdemo/frontend/src/pages/playground/components/MarkdownRenderer.test.tsx b/webdemo/frontend/src/pages/playground/components/MarkdownRenderer.test.tsx
index fd99da8..d8d6b72 100644
--- a/webdemo/frontend/src/pages/playground/components/MarkdownRenderer.test.tsx
+++ b/webdemo/frontend/src/pages/playground/components/MarkdownRenderer.test.tsx
@@ -335,12 +335,12 @@ describe('shouldDeferMarkdown', () => {
</TooltipProvider>,
);
- // 角标数字 = 来源在 citations 中的下标 + 1,与底部参考资料、来源面板同号
+ // Badge number = the source's index in citations + 1, the same number as the references at the bottom and the source panel
const badge = screen.getByRole('link', { name: '第 2 个来源' });
expect(badge).toHaveTextContent('2');
expect(badge).toHaveAttribute('href', 'https://www.openbmb.cn/news');
expect(badge).toHaveAttribute('target', '_blank');
- // 打上标记位,正文链接的下划线/主色基础样式才会跳过角标
+ // Set the marker bit, or the body link's underline/primary base styles will not skip the badge
expect(badge).toHaveAttribute('data-citation-badge');
await user.hover(badge);
@@ -375,7 +375,7 @@ describe('shouldDeferMarkdown', () => {
</TooltipProvider>,
);
- // 数组下标 +1 会是 1;后端编号是 5,多轮搜索下只有后者指得对。
+ // Array index + 1 would be 1; the backend number is 5. Across multiple search rounds only the latter points at the right source.
const badge = screen.getByRole('link', { name: '第 5 个来源' });
expect(badge).toHaveTextContent('5');
expect(badge).toHaveAttribute('href', 'https://www.openbmb.cn/news');
@@ -394,12 +394,12 @@ describe('shouldDeferMarkdown', () => {
</TooltipProvider>,
);
- // 角标仍在(与来源面板同号),但标题不能被吞掉——否则整行只剩一个灰色数字
+ // The badge stays (same number as the source panel), but the title must not be swallowed — otherwise the whole line is only a gray number
expect(screen.getByRole('link', { name: '第 1 个来源' })).toHaveTextContent('1');
const title = screen.getByRole('link', { name: '百度百科 - 一元三次方程求根公式' });
expect(title).toHaveAttribute('href', 'https://baike.baidu.com/item/x');
expect(title).toHaveAttribute('target', '_blank');
- // 标记位让正文链接的主色下划线样式跳过来源行,行内配色仍跟随引用块
+ // The marker bit makes the body link's primary underline style skip the source row; inline color still follows the quote block
expect(title).toHaveAttribute('data-citation-source');
});
@@ -436,7 +436,7 @@ describe('shouldDeferMarkdown', () => {
await user.click(screen.getByRole('link', { name: '第 2 个来源' }));
- // 回传的是从 1 起的展示序号,与角标数字、来源面板同号
+ // What is passed back is the display index starting at 1, the same number as the badge and the source panel
expect(onCitationActivate).toHaveBeenCalledWith(citations[1], 2);
});
@@ -449,9 +449,7 @@ describe('shouldDeferMarkdown', () => {
const classes = root.className.split(/\s+/);
/*
- react-markdown 会在相邻块级元素之间输出一个换行文本节点。容器级 pre-wrap 会把它当成
- 硬换行,于是每个段落间凭空多出一整行高的空白;pre-wrap 必须只作用在段落内部,
- 那里才是模型单换行分行需要保留的地方。
+ react-markdown emits a newline text node between adjacent block elements. Container-level pre-wrap treats it as a hard break, so each paragraph gains a full line of blank space from nowhere; pre-wrap must apply only inside paragraphs, which is where the model's single-newline breaks need to be kept.
*/
expect(classes).not.toContain('whitespace-pre-wrap');
expect(classes).toContain('[&_p]:whitespace-pre-wrap');
diff --git a/webdemo/frontend/src/pages/playground/components/MarkdownRenderer.tsx b/webdemo/frontend/src/pages/playground/components/MarkdownRenderer.tsx
index b8510bd..6166b8c 100644
--- a/webdemo/frontend/src/pages/playground/components/MarkdownRenderer.tsx
+++ b/webdemo/frontend/src/pages/playground/components/MarkdownRenderer.tsx
@@ -1,9 +1,7 @@
/**
- * Markdown 渲染组件。
+ * Markdown renderer.
*
- * 用途:渲染助手回复的 markdown 正文,支持 GFM(表格/删除线/任务列表)、代码块语法高亮,
- * 以及数学公式(`$...$` 行内 / `$$...$$` 块级,经 remark-math + KaTeX 渲染)。
- * 高亮用 highlight.js(同步、与 rehype 管线天然集成,流式 re-render 无异步闪烁)。
+ * Purpose: render an assistant reply's markdown body, with GFM (tables/strikethrough/task lists), syntax highlighting for code blocks, and math (`$...$` inline / `$$...$$` display, via remark-math + KaTeX). Highlighting uses highlight.js (synchronous and naturally integrated with the rehype pipeline, so streaming re-renders do not flash asynchronously).
*/
import { memo, useEffect, useMemo, useRef, useState, type AriaRole, type ReactNode } from 'react';
@@ -40,35 +38,35 @@ import { CitationBadge } from './CitationBadge';
import { ImageParseMarkdownBlock } from './experiences/ImageParseMarkdownBlock';
interface MarkdownRendererProps {
- /** markdown 源文本 */
+ /** markdown source text */
content: string;
/**
- * 渲染场景。
- * - `default`:对话正文;
- * - `reasoning`:思考过程,更紧凑的字号、间距和弱化配色;
- * - `document`:整页文档结果(图像解析),表格使用单层矩形网格,任务列表自绘复选框。
+ * Render scene.
+ * - `default`: conversation body;
+ * - `reasoning`: reasoning, with tighter type size, spacing, and muted color;
+ * - `document`: a full-page document result (image parse). Tables use a single-layer rectangular grid, and task lists draw their own checkboxes.
*/
variant?: 'default' | 'reasoning' | 'document';
- /** 是否仍在流式生成;流式期间仅渲染显式且已闭合的数学定界符。 */
+ /** Whether generation is still streaming; while streaming, render only explicit and already-closed math delimiters. */
streaming?: boolean;
- /** OCR 选中块的源范围,供文档预览高亮。 */
+ /** Source range of the selected OCR block, for highlighting in the document preview. */
highlightRange?: ImageParseTextRange;
- /** 当前回答的联网引用,用于把命中的 Markdown 链接增强为来源标签。 */
+ /** Web citations for the current answer, used to enhance matching Markdown links into source labels. */
citations?: Citation[];
/**
- * 点击正文角标时的回调(序号从 1 起,与来源面板同号)。
- * 必须是稳定引用:它进 `createMarkdownComponents` 的 useMemo 依赖,每渲染新建会让整篇正文重渲。
+ * Callback when a body badge is clicked (index starting at 1, the same number as the source panel).
+ * It must be a stable reference: it is a useMemo dependency of `createMarkdownComponents`, and a new one on every render re-renders the whole body.
*/
onCitationActivate?: (citation: Citation, index: number) => void;
- /** 可定位到原图的 OCR 块;只有服务提供有效映射时传入。 */
+ /** OCR blocks that can be located on the original image; pass them only when the service provides a valid mapping. */
linkedRanges?: readonly ImageParseLinkedRange[];
- /** OCR 原图裁出的占位符图片,仅用于文档预览,不写回 Markdown。 */
+ /** Placeholder images cropped from the OCR original, used only in the document preview and not written back into Markdown. */
imageCrops?: readonly string[];
- /** 在消毒后的顶层节点添加双击编辑入口。 */
+ /** Add a double-click edit entry on sanitized top-level nodes. */
editableBlocks?: boolean;
}
-/** 超过该长度的已完成回答才延迟解析,避免短回答出现可感知的加载占位。 */
+/** Only completed answers longer than this are parsed lazily, so short answers do not show a perceptible loading placeholder. */
export const LAZY_MARKDOWN_THRESHOLD = 12_000;
const MARKDOWN_BASE_CLASSES = `
@@ -90,10 +88,7 @@ const MARKDOWN_BASE_CLASSES = `
`;
/*
- 尾元素清掉下边距([&>*:last-child]:mb-0):块级兄弟之间外边距会合并,这 8px 平时被后面
- 元素的 mt 吃掉、看不出来;但来源胶囊是 inline-flex(要收窄成药丸),行内级盒子不参与合并,
- 于是它上方白白多出一截——同一段正文,后面跟什么就给出两种间距。间距该由父容器决定,
- 渲染器只负责内部节奏。
+ Clear the bottom margin on the last element ([&>*:last-child]:mb-0): margins between block siblings collapse, so this 8px is normally eaten by the following element's mt and is invisible. The source chip is inline-flex (it has to shrink into a pill), and an inline-level box does not participate in collapsing, so a stretch of space appears above it for nothing — the same body gives two spacings depending on what follows. Spacing should be decided by the parent; the renderer is only responsible for its internal rhythm.
*/
const DEFAULT_MARKDOWN_CLASSES = `
text-[14px] leading-7 text-foreground
@@ -108,14 +103,12 @@ const DEFAULT_MARKDOWN_CLASSES = `
`;
/*
- pre-wrap 必须下沉到 `p` 内部,不能挂在容器上。两件事都要成立:
+ pre-wrap must sink into `p` and must not hang on the container. Both of these have to hold:
- - 思考文本里模型常用单换行分行,那些软换行落在段落内部,得靠 pre-wrap 保住;
- - react-markdown 会在相邻块级元素之间输出一个换行文本节点(`</p>` 与 `<p>` 之间)。
- 容器一旦 pre-wrap,这个分隔符就成了真实硬换行——段落之间凭空多出一个空行(leading-6
- 即 24px),把 my-1.5 的 6px 间距顶到 30px,读起来像每段都被隔开成了独立的块。
+ - In reasoning text the model often breaks lines with a single newline. Those soft breaks land inside paragraphs and have to be kept with pre-wrap;
+ - react-markdown emits a newline text node between adjacent block elements (between `</p>` and `<p>`). Once the container is pre-wrap, that separator becomes a real hard break — an empty line appears between paragraphs from nowhere (leading-6 is 24px), pushing the 6px of my-1.5 up to 30px, so it reads as if every paragraph were separated into its own block.
- 容器保持默认的空白折叠,分隔符不可见;pre-wrap 只管段落内部。
+ The container keeps the default whitespace collapse, so the separator is invisible; pre-wrap only covers the inside of paragraphs.
*/
const REASONING_MARKDOWN_CLASSES = `
break-words text-[13px] leading-6 text-foreground/70
@@ -131,11 +124,11 @@ const REASONING_MARKDOWN_CLASSES = `
`;
/**
- * 文档型排版。与对话正文的三处关键差别,都是为了让整页 OCR 结果读起来像一份文档而不是一条回复:
+ * Document typography. The three key differences from conversation body are all so a full-page OCR result reads as a document rather than a reply:
*
- * 1. 标题靠字号与留白分层,不再画分隔线——h1/h2 各带一条线再叠上原文的 `---`,整页会被横线切碎;
- * 2. 正文压到 80% 前景色,标题与加粗保持纯前景色——层级由明度差承担;
- * 3. 表格使用完整单元格网格、表头铺浅底(见 DOCUMENT_COMPONENTS),合并行列沿用 HTML 结构。
+ * 1. Headings layer by type size and whitespace, and no longer draw rules — an h1/h2 each carrying a line, stacked on the original `---`, would slice the page into strips;
+ * 2. Body text is pressed to 80% foreground, while headings and bold stay pure foreground — hierarchy is carried by the lightness difference;
+ * 3. Tables use a full cell grid with a light header background (see DOCUMENT_COMPONENTS). Merged rows and columns keep the HTML structure.
*/
const DOCUMENT_MARKDOWN_CLASSES = `
text-sm leading-[1.85] text-foreground/80
@@ -170,11 +163,10 @@ const DOCUMENT_MARKDOWN_CLASSES = `
`;
/**
- * 文档型表格滚动容器:网格边线由单元格统一绘制,避免外框叠加。
+ * Document table scroll container: grid borders are drawn by the cells, so an outer frame is not stacked on top.
*
- * 包一层而不是让 table 自己滚——table 的 overflow 按规范就是 visible,
- * 宽表格会直接撑破对照栏。选中使用外轮廓,不改变网格尺寸或遮挡单元格。
- * @param children 表格行内容
+ * Wrap a layer instead of letting the table scroll itself — a table's overflow is visible by spec, and a wide table would burst the comparison column. Selection uses an outer outline and does not change the grid size or cover cells.
+ * @param children Table row content
*/
function DocumentTable({
children,
@@ -216,12 +208,11 @@ function DocumentTable({
}
/**
- * 文档型任务列表复选框。
+ * Document task-list checkbox.
*
- * GFM 产出的是 `disabled` 原生 input,浏览器会把它画成灰勾——结果页里那是一份识别结果,
- * 不是一个坏掉的表单控件,所以改成自绘方框。保留 checkbox 语义供读屏使用。
- * @param type 原 input 类型;Markdown 只会生成 checkbox
- * @param checked 是否已勾选
+ * GFM produces a `disabled` native input, and the browser paints it as a gray check — on the result page that is a recognition result, not a broken form control, so it is drawn as a custom box. Checkbox semantics are kept for screen readers.
+ * @param type Original input type; Markdown only generates checkbox
+ * @param checked Whether it is checked
*/
function DocumentCheckbox({ type, checked }: { type?: string; checked?: boolean }) {
if (type !== 'checkbox') return null;
@@ -240,14 +231,14 @@ function DocumentCheckbox({ type, checked }: { type?: string; checked?: boolean
);
}
-/** 仅文档型排版启用的节点覆盖;对话正文保持原生渲染,避免影响既有气泡样式。 */
+/** Node overrides enabled only for document typography; conversation body keeps native rendering so existing bubble styles are unaffected. */
const DOCUMENT_COMPONENTS: Components = {
table: DocumentTable,
input: DocumentCheckbox,
div: ImageParseMarkdownBlock,
};
-/** OCR HTML 先过滤再添加定位标记;保留合并单元格和供 KaTeX 解析的公式类名。 */
+/** Filter OCR HTML first, then add location markers; keep merged cells and the formula class names KaTeX parses. */
const DOCUMENT_HTML_SCHEMA: typeof defaultSchema = {
...defaultSchema,
attributes: {
@@ -276,16 +267,16 @@ const DOCUMENT_HTML_PLUGINS: NonNullable<Parameters<typeof ReactMarkdown>[0]['re
];
/**
- * 判断回答是否需要按滚动位置延迟渲染。
- * @param contentLength markdown 字符数
- * @param streaming 是否仍在流式生成
- * @returns 是否应该延迟渲染
+ * Decides whether an answer should be rendered lazily by scroll position.
+ * @param contentLength markdown character count
+ * @param streaming Whether generation is still streaming
+ * @returns Whether rendering should be deferred
*/
export function shouldDeferMarkdown(contentLength: number, streaming: boolean): boolean {
return !streaming && contentLength > LAZY_MARKDOWN_THRESHOLD;
}
-/** 场景 → 排版类映射。 */
+/** Scene → typography class map. */
const VARIANT_CLASSES = {
default: DEFAULT_MARKDOWN_CLASSES,
reasoning: REASONING_MARKDOWN_CLASSES,
@@ -293,13 +284,13 @@ const VARIANT_CLASSES = {
} as const;
/**
- * 渲染 markdown。用 prose 排版类 + 语义 token 控制配色。
- * memo:流式高频更新时,仅 content 变化才重渲染。
- * @param content markdown 源文本
- * @param variant 正文或思考过程样式
- * @param streaming 是否仍在流式生成
- * @param citations 当前回答的联网引用
- * @param onCitationActivate 点击正文角标时的回调
+ * Renders markdown. Prose typography classes plus semantic tokens control color.
+ * memo: on high-frequency streaming updates, re-render only when content changes.
+ * @param content markdown source text
+ * @param variant Body or reasoning style
+ * @param streaming Whether generation is still streaming
+ * @param citations Web citations for the current answer
+ * @param onCitationActivate Callback when a body badge is clicked
*/
export const MarkdownRenderer = memo(function MarkdownRenderer({
content,
@@ -312,14 +303,14 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({
imageCrops,
editableBlocks = false,
}: MarkdownRendererProps) {
- // 先把模型偶尔输出的裸角标 `[1]` 改写成 Markdown 链接,正文渲染侧就只需处理 `a` 一种情况。
- // 文档型排版必须保持原文:OCR 的块位置和图片占位符都依赖原始偏移量,不能被角标改写改变长度。
+ // First rewrite a bare badge such as `[1]` that the model occasionally emits into a Markdown link, so the body renderer only has to handle `a`.
+ // Document typography must keep the original text: OCR block positions and image placeholders depend on the original offsets, and a badge rewrite must not change the length.
const linkified = useMemo(
() => (variant === 'document' ? content : linkifyCitationMarkers(content, citations)),
[citations, content, variant],
);
- // 流式前缀会不断变化,禁止对未标记文本猜测公式,避免 KaTeX 节点短暂挂载后又被卸载。
- // OCR 忠实展示文档;电话号码和编号不得由聊天场景的裸公式推断改写。
+ // A streaming prefix keeps changing. Do not guess formulas in unmarked text, or a KaTeX node mounts briefly and is then unmounted.
+ // OCR displays the document faithfully; phone numbers and identifiers must not be rewritten by the chat scene's bare-formula inference.
const detectBareMath = variant !== 'document' && !streaming;
const { normalized, editBlocks, normalizedRange, normalizedLinkedRanges, placeholderOffsets } =
useMarkdownPreparation({
@@ -330,18 +321,18 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({
highlightRange,
linkedRanges,
});
- // 角标增强只用于对话正文;文档型排版继续使用忠实原文的节点覆盖。
+ // Badge enhancement is only for conversation body; document typography keeps using the node overrides that stay faithful to the original.
const baseComponents = useMemo(
() => createMarkdownComponents(citations, onCitationActivate),
[citations, onCitationActivate],
);
- // 文档型排版不继承角标增强:OCR 文档不带引用,链接必须保持消毒后的原样渲染
- // (角标渲染会把 <a> 变成来源标签,破坏“忠实展示文档”的语义)。
+ // Document typography does not inherit badge enhancement: an OCR document has no citations, and links must keep rendering as sanitized originals
+ // (badge rendering turns <a> into a source label and breaks the meaning of "display the document faithfully").
const documentComponents = useMemo<Components>(
() => ({
...DOCUMENT_COMPONENTS,
- // 显式兜底:文档预览里的链接只放行 http/https,其余协议一律去掉 href。
- // react-markdown 的 defaultUrlTransform 与 rehype-sanitize 仍是第一道防线,这里不依赖它们。
+ // Explicit fallback: links in the document preview allow only http/https, and every other protocol has its href removed.
+ // react-markdown's defaultUrlTransform and rehype-sanitize are still the first line of defense; this does not depend on them.
a: ({ href, children }) => {
const safe = href && /^https?:\/\//i.test(href) ? href : undefined;
return (
@@ -370,12 +361,12 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({
components={variant === 'document' ? documentComponents : baseComponents}
remarkPlugins={[remarkGfm, remarkMath]}
rehypePlugins={[
- // 只在 OCR 文档预览解析 HTML;不信任模型提供的脚本、属性或定位标记。
+ // Parse HTML only in the OCR document preview; do not trust scripts, attributes, or location markers supplied by the model.
...(variant === 'document' ? DOCUMENT_HTML_PLUGINS : []),
[() => imageParseDocumentBlockMarkers(editBlocks)],
[imageParseHighlight, normalizedRange, normalizedLinkedRanges, variant === 'document'],
[rehypeHighlight, { detect: true }],
- // KaTeX 对模型输入禁用受信任命令并限制资源消耗;插件自身负责解析失败回退。
+ // KaTeX disables trusted commands for model input and limits resource use; the plugin itself is responsible for falling back when parsing fails.
[rehypeKatex, SAFE_KATEX_OPTIONS],
]}
>
@@ -386,23 +377,23 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({
});
interface LazyMarkdownRendererProps {
- /** markdown 源文本 */
+ /** markdown source text */
content: string;
- /** 是否仍在流式生成;流式回答必须立即渲染。 */
+ /** Whether generation is still streaming; a streaming answer must render immediately. */
streaming?: boolean;
- /** 当前回答的联网引用。 */
+ /** Web citations for the current answer. */
citations?: Citation[];
- /** 点击正文角标时的回调,需为稳定引用,透传给 MarkdownRenderer。 */
+ /** Callback when a body badge is clicked. It must be a stable reference and is passed through to MarkdownRenderer. */
onCitationActivate?: (citation: Citation, index: number) => void;
}
/**
- * 长回答懒渲染器:进入视口前只保留估算高度,接近视口时再运行 Markdown、代码高亮和公式解析。
- * @param content markdown 源文本
- * @param streaming 是否仍在流式生成
- * @param citations 当前回答的联网引用
- * @param onCitationActivate 点击正文角标时的回调
- * @returns 延迟渲染的 Markdown 内容
+ * Lazy renderer for long answers: before entering the viewport it keeps only an estimated height, and near the viewport it runs Markdown, code highlighting, and formula parsing.
+ * @param content markdown source text
+ * @param streaming Whether generation is still streaming
+ * @param citations Web citations for the current answer
+ * @param onCitationActivate Callback when a body badge is clicked
+ * @returns Lazily rendered Markdown content
*/
export function LazyMarkdownRenderer({
content,
@@ -458,14 +449,14 @@ export function LazyMarkdownRenderer({
);
}
-/** 估算未渲染 Markdown 的占位高度,降低滚动过程中布局跳动。 */
+/** Estimates the placeholder height of unrendered Markdown, reducing layout shift while scrolling. */
function estimateMarkdownHeight(content: string): number {
const lineCount = content.split(/\r?\n/).length;
const wrappedLineCount = Math.ceil(content.length / 72);
return Math.min(2_400, Math.max(240, Math.max(lineCount, wrappedLineCount) * 28));
}
-/** 独占一行的来源链接样式:跟着上下文取色(引用块里即为弱化色),只用点线下划线提示可跳转。 */
+/** Style for a source link that occupies its own line: take color from context (muted inside a quote), and use only a dotted underline to show it can be followed. */
const CITATION_SOURCE_LINK_CLASSES = `
inline-flex items-baseline gap-0.5 align-baseline
underline decoration-dotted decoration-from-font underline-offset-4
@@ -473,9 +464,8 @@ const CITATION_SOURCE_LINK_CLASSES = `
`;
/**
- * hast 子树的最小节点形状。
- * 本仓没有装 `@types/hast` 的顶层软链,`import type { Element } from 'hast'` 解析不到;
- * 这里只用到判定来源行需要的几个字段,结构化匹配 react-markdown 传进来的 `node`。
+ * Minimal node shape for a hast subtree.
+ * This repo has no top-level symlink for `@types/hast`, so `import type { Element } from 'hast'` does not resolve; only the few fields needed to decide a source row are used here, structurally matching the `node` passed in by react-markdown.
*/
interface MarkdownNode {
type: string;
@@ -485,7 +475,7 @@ interface MarkdownNode {
children?: MarkdownNode[];
}
-/** 收集 hast 子树里的可见文字,用于取回链接的原始标题。 */
+/** Collect visible text in a hast subtree, used to recover a link's original title. */
function collectNodeText(nodes: readonly MarkdownNode[]): string {
return nodes
.map((node) =>
@@ -495,11 +485,11 @@ function collectNodeText(nodes: readonly MarkdownNode[]): string {
}
/**
- * 判断一个段落是否整段只有一条命中来源的链接,并取出渲染来源行所需的信息。
+ * Decide whether a paragraph is entirely one link that matches a source, and take the information needed to render a source row.
*
- * @param nodes 段落的 hast 子节点
- * @param citationByURL 归一化 URL → 来源与下标
- * @returns 来源行信息;段落还有别的内容或链接没命中来源时返回 undefined
+ * @param nodes The paragraph's hast child nodes
+ * @param citationByURL Normalized URL → source and index
+ * @returns Source-row information; undefined when the paragraph has other content or the link misses a source
*/
function soleCitationSource(
nodes: readonly MarkdownNode[] | undefined,
@@ -523,23 +513,21 @@ function soleCitationSource(
};
}
-/** 为 Markdown 链接增加安全跳转,并把命中 citations 的链接渲染为同号数字角标。 */
+/** Add a safe navigation to Markdown links, and render links that match citations as same-number digit badges. */
function createMarkdownComponents(
citations: Citation[],
onCitationActivate?: (citation: Citation, index: number) => void,
): Components {
- // 连带下标一起存:后端未下发 ref 的老数据要靠它回退出编号(见 citationDisplayIndex)。
+ // Store the index along with it: old data that never received a ref from the backend falls back to a number from it (see citationDisplayIndex).
const citationByURL = new Map(
citations.map((citation, index) => [citationURLKey(citation.url), { citation, index }]),
);
return {
/*
- 整段只有一条来源链接时保留标题,不压成裸角标。
+ When a whole paragraph is only one source link, keep the title and do not compress it into a bare badge.
- 提示词要求模型把链接跟在它支撑的论断后面,但模型常常改成单独列一行来源
- (实测多为 `> [标题](url)`)。这种独占一行的链接若照行内规则压成角标,整行就只剩一个
- 灰色数字,标题和可读信息全丢;此时把角标提到行首、标题照原样展示。
+ The prompt asks the model to put the link right after the claim it supports, but the model often lists the source on its own line instead (in practice usually `> [title](url)`). If that full-line link is compressed into a badge by the inline rule, the line is left with only a gray number, and the title and readable information are all lost; in that case move the badge to the start of the line and show the title as-is.
*/
p({ node, children, ...props }) {
const source = soleCitationSource(node?.children, citationByURL);
diff --git a/webdemo/frontend/src/pages/playground/components/MessageActions.tsx b/webdemo/frontend/src/pages/playground/components/MessageActions.tsx
index 871707e..bd70ccc 100644
--- a/webdemo/frontend/src/pages/playground/components/MessageActions.tsx
+++ b/webdemo/frontend/src/pages/playground/components/MessageActions.tsx
@@ -1,16 +1,14 @@
/**
- * 助手消息操作栏(复制 / 重新生成 / 点赞 / 点踩)。
+ * Assistant message action bar (copy / regenerate / thumbs-up / thumbs-down).
*
- * 用途:挂在每条已完成的 assistant 消息下方。复制正文到剪贴板;重新生成截断重发;
- * 点赞/点踩切换本地高亮并触发 /feedback 上报(二者互斥、可再次点击取消)。
- * 联网来源不在这里:由回答正文下方的来源胶囊 SourcesChip 通往来源抽屉。
+ * Purpose: hangs under every completed assistant message. Copy the body to the clipboard; regenerate truncates and resends; thumbs-up/thumbs-down toggle the local highlight and report to /feedback (the two are mutually exclusive, and clicking again cancels). Web sources are not here: the SourcesChip under the answer body is the path to the source drawer.
*
- * @param content 待复制的助手正文
- * @param feedback 当前反馈态('up' | 'down' | undefined)
- * @param showRegenerate 是否展示「重新生成」(仅最后一条 assistant 为真,避免中间轮次重发误删后续对话)
- * @param onRegenerate 重新生成回调
- * @param onFeedback 切换反馈态回调(传入点击的类型,由上层做互斥/取消)
- * @param disableRegenerate 生成中禁用重新生成
+ * @param content Assistant body to copy
+ * @param feedback Current feedback state ('up' | 'down' | undefined)
+ * @param showRegenerate Whether to show "regenerate" (true only for the last assistant message, so resending a middle turn does not delete the conversation after it)
+ * @param onRegenerate Regenerate callback
+ * @param onFeedback Toggle-feedback callback (the clicked type is passed in; the parent does mutual exclusion / cancel)
+ * @param disableRegenerate Disable regenerate while generating
*/
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -36,11 +34,11 @@ interface MessageActionsProps {
onRegenerate: () => void;
onFeedback: (kind: MessageFeedback) => void;
disableRegenerate?: boolean;
- /** 版本总数(>1 时显示 ‹n/N› 翻页器) */
+ /** Version count (show the ‹n/N› pager when >1) */
versionCount?: number;
- /** 当前版本索引(0 起) */
+ /** Current version index (starting at 0) */
activeVersion?: number;
- /** 切换到指定版本 */
+ /** Switch to the given version */
onSwitchVersion?: (index: number) => void;
}
@@ -57,9 +55,9 @@ export function MessageActions({
}: MessageActionsProps) {
const { toast } = useToast();
const { t } = useTranslation('playground');
- // 复制成功后短暂把图标切成对勾,给出即时反馈
+ // After a successful copy, briefly switch the icon to a check for immediate feedback
const [copied, setCopied] = useState(false);
- // 定时器 ref:组件卸载(切换会话等)时清理,避免卸载后 setState
+ // Timer ref: clear it when the component unmounts (switching sessions and the like) so setState does not run after unmount
const copiedTimerRef = useRef<number | undefined>(undefined);
useEffect(() => () => window.clearTimeout(copiedTimerRef.current), []);
@@ -78,13 +76,13 @@ export function MessageActions({
versionCount && versionCount > 1 && onSwitchVersion && activeVersion !== undefined,
);
- // 无「重新生成」、无正文、无多版本则整栏不渲染
+ // Render nothing for the whole bar when there is no "regenerate," no body, and no multiple versions
if (!showRegenerate && !content && !showVersions) return null;
return (
<div className="mt-2">
<div className="flex flex-wrap items-center gap-0.5">
- {/* 版本翻页器:仅多版本回答显示 ‹ n/N › */}
+ {/* Version pager: show ‹ n/N › only for multi-version answers */}
{showVersions && (
<VersionSwitcher
count={versionCount!}
@@ -103,7 +101,7 @@ export function MessageActions({
</ActionButton>
)}
- {/* 复制/点赞/点踩仅在有正文时有意义;失败消息(无正文)只保留「重新生成」。 */}
+ {/* Copy / thumbs-up / thumbs-down are meaningful only when there is a body; a failed message (no body) keeps only "regenerate." */}
{content && (
<>
<ActionButton label={copied ? t('copied') : t('copy')} onClick={handleCopy}>
@@ -144,7 +142,7 @@ export function MessageActions({
);
}
-/** 版本翻页器:‹ 2/3 ›,左右箭头切换回答版本;到头/到尾时对应箭头禁用 */
+/** Version pager: ‹ 2/3 ›. Left and right arrows switch the answer version; the matching arrow is disabled at the start or the end */
function VersionSwitcher({
count,
active,
@@ -182,7 +180,7 @@ function VersionSwitcher({
);
}
-/** 单个图标按钮:带 Tooltip、hover 高亮、激活态(点赞/点踩选中)配色 */
+/** A single icon button: Tooltip, hover highlight, and active-state color (thumbs-up / thumbs-down selected) */
function ActionButton({
label,
onClick,
diff --git a/webdemo/frontend/src/pages/playground/components/MessageBubble.test.tsx b/webdemo/frontend/src/pages/playground/components/MessageBubble.test.tsx
index 55ce049..eb438da 100644
--- a/webdemo/frontend/src/pages/playground/components/MessageBubble.test.tsx
+++ b/webdemo/frontend/src/pages/playground/components/MessageBubble.test.tsx
@@ -5,7 +5,7 @@ import { ToastProvider, TooltipProvider } from '@map/ui';
import '@/i18n';
import { MessageBubble } from './MessageBubble';
-/** 助手消息气泡的渲染测试。 */
+/** Render tests for the assistant message bubble. */
describe('MessageBubble', () => {
it('不展示用户消息的上下文隔离提示文案', () => {
render(
@@ -71,7 +71,7 @@ describe('MessageBubble', () => {
/>,
);
- // 过程区只剩一个开关:思考与联网同属一条时间线,顶行只报「做了什么」
+ // The process area has only one toggle left: reasoning and web search share one timeline, and the top row only reports "what was done"
const trigger = screen.getByTestId('process-toggle');
expect(trigger).toHaveAccessibleName('已联网检索并思考');
expect(screen.getAllByTestId('process-toggle')).toHaveLength(1);
@@ -80,10 +80,10 @@ describe('MessageBubble', () => {
await user.click(trigger);
- // 一次展开同时看到思考与联网,不用再分别点两处
+ // One expand shows reasoning and web search together; there is no need to click two places separately
expect(screen.getByText('先检索天气,再核对多个来源。')).toBeVisible();
expect(screen.getByText(/搜索到 4 个网页/)).toBeVisible();
- // 来源统一收在正文下方的胶囊里
+ // Sources are collected in the chip under the body
expect(screen.getByTestId('sources-chip')).toHaveTextContent('4 个网页');
});
@@ -112,12 +112,12 @@ describe('MessageBubble', () => {
);
const trigger = screen.getByTestId('process-toggle');
- // 顶行带上当前搜的词:收起时它是唯一的进度通道,静态文案挂几秒与卡死无从区分
+ // The top row carries the query currently being searched: while collapsed it is the only progress channel, and static copy sitting for several seconds cannot be told apart from a hang
expect(trigger).toHaveAccessibleName('正在搜索 MiniCPM 最新进展');
expect(trigger).toHaveAttribute('aria-expanded', 'true');
- // 查询词同时是进行中工具行的行内后缀,完成后会被「搜索到 N 个网页」取代
+ // The query is also the inline suffix of the in-progress tool row, and after completion it is replaced by "found N pages"
expect(screen.getByText('MiniCPM 最新进展')).toBeVisible();
- // 过程区本身就是状态反馈,其下方不再出现悬空的等待点
+ // The process area itself is the status feedback, so a floating waiting dot no longer appears under it
expect(screen.queryByLabelText('正在生成')).not.toBeInTheDocument();
});
@@ -163,7 +163,7 @@ describe('MessageBubble', () => {
await new Promise((resolve) => setTimeout(resolve, 20));
});
- // 思考区是同一个 DOM 节点在原地改标题,不重新挂载 → 不会有一次视觉跳动
+ // The reasoning area is the same DOM node changing its title in place and is not remounted → there is no visual jump
expect(screen.getByRole('region', { name: '已思考' })).toBe(processSection);
expect(screen.getByRole('button', { name: '已思考' })).toHaveAttribute('aria-expanded', 'true');
expect(screen.getByText('已完成分析。')).toBeVisible();
@@ -184,7 +184,7 @@ describe('MessageBubble', () => {
/>,
);
- // 失败标题直接用后端原因,比"联网搜索失败"更具体
+ // The failure title uses the backend reason directly, which is more specific than "web search failed"
const trigger = screen.getByRole('button', { name: '搜索服务暂时不可用' });
expect(trigger).toHaveAttribute('aria-expanded', 'true');
expect(trigger).toHaveClass('text-destructive');
@@ -218,7 +218,7 @@ describe('MessageBubble', () => {
);
const chip = screen.getByTestId('sources-chip');
- // 标题、摘要、序号全部让给抽屉,胶囊只报个数
+ // Title, summary, and index are all left to the drawer; the chip only reports the count
expect(chip).toHaveTextContent('2 个网页');
expect(chip).toHaveAccessibleName('2 个网页,查看来源');
expect(chip).toHaveAttribute('aria-expanded', 'false');
@@ -226,7 +226,7 @@ describe('MessageBubble', () => {
await user.click(chip);
- // 不带第三参:只开面板,不定位到某一条
+ // No third argument: only open the panel, do not locate a particular item
expect(onOpenCitations).toHaveBeenCalledWith('citation-actions', citations);
});
@@ -255,7 +255,7 @@ describe('MessageBubble', () => {
await user.click(screen.getByRole('link', { name: '第 2 个来源' }));
- // 第三参是被点那条的地址;「查看全部」不带它,两条入口语义由此区分
+ // The third argument is the address of the clicked item; "view all" omits it, which is how the two entries' meanings are distinguished
expect(onOpenCitations).toHaveBeenCalledWith(
'citation-badge-activate',
citations,
diff --git a/webdemo/frontend/src/pages/playground/components/MessageBubble.tsx b/webdemo/frontend/src/pages/playground/components/MessageBubble.tsx
index d99990b..0d97667 100644
--- a/webdemo/frontend/src/pages/playground/components/MessageBubble.tsx
+++ b/webdemo/frontend/src/pages/playground/components/MessageBubble.tsx
@@ -1,8 +1,7 @@
/**
- * 单条对话消息气泡。
+ * A single conversation message bubble.
*
- * 用途:用户消息右对齐实心气泡;助手消息左对齐,自上而下为过程时间线(思考与工具交错的
- * 单一折叠区)+ markdown 正文 + 来源胶囊 + 流式光标 + usage/错误标注 + 操作栏。
+ * Purpose: user messages are a right-aligned solid bubble; assistant messages are left-aligned, top to bottom: process timeline (one disclosure where reasoning and tools interleave) + markdown body + source chip + streaming cursor + usage/error marks + action bar.
*/
import { useCallback, useMemo, useState } from 'react';
@@ -19,36 +18,36 @@ import { normalizeAssistantReply } from '../utils/thinkSplit';
interface MessageBubbleProps {
message: ChatMessage;
- /** 重新生成该条 assistant 消息(截断重发) */
+ /** Regenerate this assistant message (truncate and resend) */
onRegenerate?: (assistantId: string) => void;
- /** 切换该条 assistant 消息的反馈态(赞/踩) */
+ /** Toggle this assistant message's feedback state (up/down) */
onFeedback?: (assistantId: string, kind: MessageFeedback) => void;
- /** 切换该条 assistant 消息显示的回答版本(‹n/N› 翻页) */
+ /** Switch the answer version shown for this assistant message (‹n/N› paging) */
onSwitchVersion?: (assistantId: string, index: number) => void;
- /** 是否正在生成(生成中禁用重新生成按钮) */
+ /** Whether generation is in progress (the regenerate button is disabled while generating) */
loading?: boolean;
- /** 是否为最后一条 assistant 消息:仅此条展示「重新生成」,避免对中间轮次重发误删其后对话 */
+ /** Whether this is the last assistant message: only this one shows "regenerate," so resending a middle turn does not delete the conversation after it */
isLastAssistant?: boolean;
- /** 当前模型是否允许展示思考(false 时不渲染思考折叠区,含历史会话已存的 reasoning) */
+ /** Whether the current model may show reasoning (when false, do not render the reasoning disclosure, including reasoning already stored on historical sessions) */
showReasoning?: boolean;
/**
- * 打开布局级引用侧栏。
- * 第三参 activeUrl 由正文角标点击带上,让面板滚到该条并高亮;「查看全部」不带,表示只开面板。
+ * Open the layout-level citation sidebar.
+ * The third argument, activeUrl, is carried by a body-badge click so the panel scrolls to that item and highlights it; "view all" omits it, meaning only open the panel.
*/
onOpenCitations?: (messageId: string, citations: Citation[], activeUrl?: string) => void;
- /** 当前消息是否正在展示引用侧栏。 */
+ /** Whether this message is currently showing the citation sidebar. */
citationsOpen?: boolean;
}
/**
- * 渲染一条消息。
- * @param message 消息数据
- * @param onRegenerate 重新生成回调
- * @param onFeedback 反馈回调
- * @param onSwitchVersion 版本切换回调
- * @param loading 是否生成中
- * @param isLastAssistant 是否为最后一条 assistant
- * @param showReasoning 是否允许展示思考
+ * Renders one message.
+ * @param message Message data
+ * @param onRegenerate Regenerate callback
+ * @param onFeedback Feedback callback
+ * @param onSwitchVersion Version-switch callback
+ * @param loading Whether generation is in progress
+ * @param isLastAssistant Whether this is the last assistant message
+ * @param showReasoning Whether reasoning may be shown
*/
export function MessageBubble({
message,
@@ -62,19 +61,19 @@ export function MessageBubble({
citationsOpen = false,
}: MessageBubbleProps) {
const { t } = useTranslation('playground');
- // 点击放大预览的图片(用户消息内)
+ // Image opened in the enlarge preview (inside a user message)
const [preview, setPreview] = useState<string | null>(null);
- // 展示层兜底:剥离正文中残留的内联 think 标签,合并进 reasoning 折叠区
+ // Display-layer fallback: strip leftover inline think tags from the body and merge them into the reasoning disclosure
const display = useMemo(
() => normalizeAssistantReply(message.content, message.reasoning),
[message.content, message.reasoning],
);
- // 改写过的思考与工具事件里记的字符偏移对不上,时间线要据此退化为「思考整块置顶」
+ // Rewritten reasoning does not match the character offsets recorded on tool events, so the timeline falls back to "reasoning as one block on top"
const reasoningRewritten = display.reasoning !== (message.reasoning ?? '');
- // 必须 useCallback:这个回调会进 MarkdownRenderer 的 memo 比较与 components 的 useMemo 依赖,
- // 每渲染新建会让流式期间每一帧都重解析整篇 Markdown。
+ // Must be useCallback: this callback enters MarkdownRenderer's memo comparison and the components useMemo dependencies,
+ // and a new one on every render re-parses the whole Markdown on every streaming frame.
const activateCitation = useCallback(
(citation: Citation) => {
onOpenCitations?.(message.id, message.citations ?? [], citation.url);
@@ -104,9 +103,9 @@ export function MessageBubble({
);
}
- // 等待首增量:已有过程区(联网块或思考块)时由它承担状态反馈,避免其下方重复出现悬空等待点。
+ // Waiting for the first increment: when a process area already exists (a web-search block or a reasoning block), it carries the status feedback, so a floating waiting dot is not repeated under it.
const showCursor = message.streaming && !display.content && !display.reasoning;
- // 与 AnswerProcessTimeline 的渲染条件保持一致:过程区在场就由它承担等待反馈
+ // Stay consistent with AnswerProcessTimeline's render condition: when the process area is present, it carries the waiting feedback
const hasAnswerProcess = Boolean(
(showReasoning && display.reasoning.trim()) ||
message.toolEvents?.length ||
@@ -129,7 +128,7 @@ export function MessageBubble({
searchStep={message.searchStep}
searchActiveTool={message.searchActiveTool}
searchStatus={message.searchStatus}
- /* 过程里的搜索行与回答末尾的胶囊通往同一个抽屉,不带 activeUrl 表示只开面板 */
+ /* The search row in the process and the chip at the end of the answer lead to the same drawer; omitting activeUrl means only open the panel */
onOpenSources={onOpenCitations ? () => onOpenCitations(message.id, citations) : undefined}
hasAnswer={Boolean(display.content)}
/>
@@ -144,7 +143,7 @@ export function MessageBubble({
)}
{!display.content && !hasAnswerProcess && showCursor && <ThinkingDots />}
- {/* 来源胶囊:正文落地后再出现,避免流式期间反复重排 */}
+ {/* Source chip: appear only after the body has landed, so streaming does not reflow repeatedly */}
{!message.streaming && (
<SourcesChip
citations={citations}
@@ -171,8 +170,8 @@ export function MessageBubble({
<MessageMetrics metrics={message.metrics} usage={message.usage} />
)}
- {/* 操作栏:已完成的 assistant 消息展示。失败(仅 error 无正文)时只保留「重新生成」,
- 由 MessageActions 内部按 content 是否为空决定是否渲染复制/点赞/点踩;多版本消息显示 ‹n/N›。 */}
+ {/* Action bar: shown for a completed assistant message. On failure (error only, no body) keep only "regenerate."
+ MessageActions decides from whether content is empty whether to render copy / thumbs-up / thumbs-down; multi-version messages show ‹n/N›. */}
{!message.streaming &&
!message.contextExcluded &&
(display.content || message.error || message.interrupted) &&
@@ -195,7 +194,7 @@ export function MessageBubble({
);
}
-/** 等待首个增量时的「正在生成」动画 */
+/** "Generating" animation while waiting for the first increment */
function ThinkingDots() {
const { t } = useTranslation('playground');
return (
diff --git a/webdemo/frontend/src/pages/playground/components/MessageList.tsx b/webdemo/frontend/src/pages/playground/components/MessageList.tsx
index 202e076..1f40245 100644
--- a/webdemo/frontend/src/pages/playground/components/MessageList.tsx
+++ b/webdemo/frontend/src/pages/playground/components/MessageList.tsx
@@ -1,8 +1,7 @@
/**
- * 消息流容器。
+ * Message-stream container.
*
- * 用途:渲染消息气泡列表并自动吸底(流式增量时滚到底,用户上滚阅读时停止吸底)。
- * 用原生滚动容器(而非 OverlayScrollArea),以便 useAutoScroll 直接控制 scrollTop。
+ * Purpose: render the message-bubble list and stick to the bottom (scroll to the bottom on streaming increments; stop sticking when the user scrolls up to read). Use a native scroll container (rather than OverlayScrollArea) so useAutoScroll can control scrollTop directly.
*/
import { useAutoScroll } from '../hooks/useAutoScroll';
@@ -12,30 +11,30 @@ import { MessageBubble } from './MessageBubble';
interface MessageListProps {
messages: ChatMessage[];
- /** 重新生成某条 assistant 消息 */
+ /** Regenerate an assistant message */
onRegenerate?: (assistantId: string) => void;
- /** 切换某条 assistant 消息的反馈态 */
+ /** Toggle an assistant message's feedback state */
onFeedback?: (assistantId: string, kind: MessageFeedback) => void;
- /** 切换某条 assistant 消息显示的回答版本 */
+ /** Switch the answer version shown for an assistant message */
onSwitchVersion?: (assistantId: string, index: number) => void;
- /** 是否正在生成(透传给操作栏禁用重新生成) */
+ /** Whether generation is in progress (passed through to the action bar to disable regenerate) */
loading?: boolean;
- /** 当前模型是否允许展示思考(false 时不渲染任何消息的思考区,含历史会话) */
+ /** Whether the current model may show reasoning (when false, do not render any message's reasoning area, including historical sessions) */
showReasoning?: boolean;
- /** 打开布局级引用侧栏。 */
+ /** Open the layout-level citation sidebar. */
onOpenCitations?: (messageId: string, citations: Citation[], activeUrl?: string) => void;
- /** 当前正在展示引用侧栏的消息 ID。 */
+ /** ID of the message currently showing the citation sidebar. */
openCitationsMessageId?: string;
}
/**
- * 滚动消息流。
- * @param messages 消息列表
- * @param onRegenerate 重新生成回调
- * @param onFeedback 反馈回调
- * @param onSwitchVersion 版本切换回调
- * @param loading 是否生成中
- * @param showReasoning 是否允许展示思考
+ * Scrolling message stream.
+ * @param messages Message list
+ * @param onRegenerate Regenerate callback
+ * @param onFeedback Feedback callback
+ * @param onSwitchVersion Version-switch callback
+ * @param loading Whether generation is in progress
+ * @param showReasoning Whether reasoning may be shown
*/
export function MessageList({
messages,
@@ -48,7 +47,7 @@ export function MessageList({
openCitationsMessageId,
}: MessageListProps) {
const { t } = useTranslation('playground');
- // 工具状态与引用也会改变消息高度;内容容器的 ResizeObserver 负责兜住异步排版变化。
+ // Tool status and citations also change message height; the content container's ResizeObserver covers async layout changes.
const last = messages[messages.length - 1];
const updateKey = [
messages.length,
@@ -66,7 +65,7 @@ export function MessageList({
last?.streaming ? 'streaming' : 'idle',
].join(':');
- // 最后一条 assistant 消息用于操作栏;最后一条 user 消息作为“新一轮”滚动重置标识。
+ // The last assistant message is for the action bar; the last user message is the "new turn" marker that resets scrolling.
let lastAssistantId: string | undefined;
let lastUserId: string | undefined;
for (let i = messages.length - 1; i >= 0; i--) {
@@ -88,7 +87,7 @@ export function MessageList({
onWheel={onWheel}
onTouchMove={onTouchMove}
onKeyDown={onKeyDown}
- /* 点击引起的高度变化(展开思考过程、切换版本)不吸底,见 useAutoScroll 里的说明 */
+ /* Height changes caused by clicks (expanding reasoning, switching versions) do not stick to the bottom; see the note in useAutoScroll */
onPointerDown={onPointerDown}
className="h-full overflow-y-auto"
>
@@ -116,7 +115,7 @@ export function MessageList({
);
}
-/** 上下文分隔线:一条带「上下文已清除」居中文案的横线,标记此后对话不再携带其上历史 */
+/** Context divider: a horizontal rule with centered "context cleared" copy, marking that conversation after this no longer carries the history above it */
function ContextDivider({ label }: { label: string }) {
return (
<div
diff --git a/webdemo/frontend/src/pages/playground/components/MessageMetrics.tsx b/webdemo/frontend/src/pages/playground/components/MessageMetrics.tsx
index 82d4c44..ccc41d0 100644
--- a/webdemo/frontend/src/pages/playground/components/MessageMetrics.tsx
+++ b/webdemo/frontend/src/pages/playground/components/MessageMetrics.tsx
@@ -1,9 +1,7 @@
/**
- * 助手消息底部的性能指标行。
+ * Performance-metrics row at the bottom of an assistant message.
*
- * 用途:把一轮生成的计时与用量(首 token / 总耗时 / 输出速率 / 共调用 tokens)
- * 呈现为一行带竖线分隔的紧凑指标;数值高亮、指标名弱化,部分项带 info 悬浮说明。
- * 纯展示组件:不含状态与副作用,数据经 buildMetricItems 派生后由父组件传入。
+ * Purpose: present one generation's timing and usage (first token / total duration / output rate / total tokens called) as one compact row separated by vertical rules; values are highlighted, metric names are muted, and some items have an info hover. Pure display component: no state or side effects. Data is derived by buildMetricItems and passed in by the parent.
*/
import { Tooltip, TooltipContent, TooltipTrigger } from '@map/ui';
@@ -18,9 +16,9 @@ interface MessageMetricsProps {
}
/**
- * 渲染一条消息的指标行;无任何可展示指标时不渲染。
- * @param metrics 前端计时指标
- * @param usage 尾块 token 用量
+ * Renders the metrics row for one message; render nothing when there is no metric to show.
+ * @param metrics Frontend timing metrics
+ * @param usage Trailing-chunk token usage
*/
export function MessageMetrics({ metrics, usage }: MessageMetricsProps) {
const items = buildMetricItems(metrics, usage);
@@ -38,7 +36,7 @@ export function MessageMetrics({ metrics, usage }: MessageMetricsProps) {
);
}
-/** 单个指标单元:指标名 + 高亮数值 + 单位 +(可选)info 悬浮 */
+/** One metric unit: metric name + highlighted value + unit + (optional) info hover */
function MetricCell({ item }: { item: MetricItem }) {
const { t } = useTranslation('playground');
return (
diff --git a/webdemo/frontend/src/pages/playground/components/ModelSelector.tsx b/webdemo/frontend/src/pages/playground/components/ModelSelector.tsx
index 16ed738..704c9b0 100644
--- a/webdemo/frontend/src/pages/playground/components/ModelSelector.tsx
+++ b/webdemo/frontend/src/pages/playground/components/ModelSelector.tsx
@@ -1,7 +1,7 @@
/**
- * 模型选择器(顶栏)。
+ * Model selector (top bar).
*
- * 用途:从可调用模型列表中选择对话模型(真功能)。
+ * Purpose: choose the chat model from the callable model list (a real feature).
*/
import { Select, SelectContent, SelectItem, SelectTrigger } from '@map/ui';
@@ -19,11 +19,11 @@ interface ModelSelectorProps {
}
/**
- * 模型下拉。
- * @param models 模型列表
- * @param loading 列表加载态
- * @param value 当前选中 id
- * @param onChange 选择回调
+ * Model dropdown.
+ * @param models Model list
+ * @param loading List loading state
+ * @param value Currently selected id
+ * @param onChange Selection callback
*/
export function ModelSelector({ models, loading, value, onChange }: ModelSelectorProps) {
const { t } = useTranslation('playground');
@@ -33,12 +33,12 @@ export function ModelSelector({ models, loading, value, onChange }: ModelSelecto
return (
<div className="flex min-w-0 max-w-full items-center gap-2">
<Select value={value} onValueChange={onChange} disabled={loading || models.length === 0}>
- {/* 触发器单行横排展示(名字 + 上下文),不用 SelectValue,避免镜像下拉项的两行布局造成「换行」观感 */}
- {/* 顶栏内的「裸」触发器:显式清掉基础组件的聚焦/展开态边框与 ring,切换后不残留紫框 */}
+ {/* The trigger shows a single horizontal row (name + context). Do not use SelectValue, so mirroring the dropdown item's two-line layout does not look like a "line wrap" */}
+ {/* A "bare" trigger inside the top bar: explicitly clear the base component's focus/open border and ring so no purple frame lingers after switching */}
<SelectTrigger className="h-9 w-auto min-w-0 max-w-full gap-2 border-0 bg-transparent px-2 shadow-none hover:bg-muted/60 hover:border-0 focus-visible:border-0 focus-visible:ring-0 data-[state=open]:border-0">
{selected ? (
- // 用 div 包裹:避开 SelectTrigger 的 [&>span]:line-clamp-1 把 display 改成 -webkit-box,
- // 否则 flex/gap 会被覆盖、名字与上下文会贴在一起。
+ // Wrap with a div: avoid SelectTrigger's [&>span]:line-clamp-1 changing display to -webkit-box,
+ // otherwise flex/gap are overridden and the name sticks to the context.
<div className="flex min-w-0 items-center gap-2.5">
<span className="truncate font-semibold">{selected.display_name || selected.id}</span>
{isFreeModel(selected) && <LimitedFreeTag />}
@@ -62,9 +62,9 @@ export function ModelSelector({ models, loading, value, onChange }: ModelSelecto
<SelectContent side={isMobile ? 'top' : undefined} scrollMode="native">
{models.map((m) => {
const name = m.display_name || m.id;
- // 仅当 id 与展示名不同才在副标题展示 id,避免「名字 + 名字·上下文」重复
+ // Show the id in the subtitle only when it differs from the display name, so "name + name · context" is not repeated
const showId = Boolean(m.display_name) && m.display_name !== m.id;
- // 副标题按「id · 上下文」拼装,缺项自动省略——没有上下文窗口时不留下孤零零的「—」
+ // The subtitle is assembled as "id · context," and a missing piece is omitted — when there is no context window, do not leave a lone "—"
const subtitle = [
showId ? m.id : '',
m.parameter_count || '',
@@ -90,7 +90,7 @@ export function ModelSelector({ models, loading, value, onChange }: ModelSelecto
);
}
-/** 上下文窗口友好显示(如 128K) */
+/** Friendly display of the context window (for example, 128K) */
function formatWindow(
n: number,
t: (key: string, options: { count: string | number }) => string,
diff --git a/webdemo/frontend/src/pages/playground/components/PlaygroundFooter.tsx b/webdemo/frontend/src/pages/playground/components/PlaygroundFooter.tsx
index 3f24b95..4061a63 100644
--- a/webdemo/frontend/src/pages/playground/components/PlaygroundFooter.tsx
+++ b/webdemo/frontend/src/pages/playground/components/PlaygroundFooter.tsx
@@ -1,11 +1,9 @@
/**
- * 体验中心底部免责声明栏。
+ * Disclaimer bar at the bottom of the experience center.
*
- * 用途:提示试用内容由 AI 生成、不代表平台立场,并给出免责声明 / 测试协议 / 隐私政策入口。
- * 体验中心为独立全屏壳,不展示备案(备案已在登录页与 AdminLayout 下的业务页常驻),故此处
- * 只承担「AI 生成免责 + 协议链接」职责。链接目标复用现有 legal 文档(terms/privacy)。
+ * Purpose: note that trial content is generated by AI and does not represent the platform's position, and offer entries for the disclaimer / test agreement / privacy policy. The experience center is an independent full-screen shell and does not show the filing record (the filing record already stays on the login page and on business pages under AdminLayout), so this only carries "AI-generated disclaimer + agreement links." Link targets reuse the existing legal documents (terms/privacy).
*
- * @param className 额外容器类名,便于在布局中微调间距/背景。
+ * @param className Extra container class name, for fine-tuning spacing/background in the layout.
*/
import { useTranslation } from 'react-i18next';
@@ -27,7 +25,7 @@ export function PlaygroundFooter({ className = '' }: PlaygroundFooterProps) {
);
}
-/** 协议链接:新标签打开对应 legal 文档 */
+/** Agreement link: open the matching legal document in a new tab */
function LegalLink({ href, children }: { href: string; children: string }) {
return (
<a
diff --git a/webdemo/frontend/src/pages/playground/components/PlaygroundHistoryList.tsx b/webdemo/frontend/src/pages/playground/components/PlaygroundHistoryList.tsx
index de1d528..6914f0f 100644
--- a/webdemo/frontend/src/pages/playground/components/PlaygroundHistoryList.tsx
+++ b/webdemo/frontend/src/pages/playground/components/PlaygroundHistoryList.tsx
@@ -2,26 +2,26 @@ import { ChevronDown, LoaderCircle, Plus, Trash2 } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button, cn, Tooltip, TooltipContent, TooltipTrigger } from '@map/ui';
-/** 历史列表只消费轻量标题与身份,不持有文档或对话正文。 */
+/** The history list consumes only a lightweight title and identity; it does not hold document or conversation body text. */
export interface SidebarSession {
id: string;
title: string;
- /** 内置 OCR 案例与用户上传历史分开展示,不改变本地记录身份。 */
+ /** Built-in OCR examples and user-upload history are shown separately, without changing the local record identity. */
category?: 'example';
}
-/** 各体验提供自己的数据与行为,历史展示共用同一组件。 */
+/** Each experience supplies its own data and behavior; history display shares one component. */
export interface PlaygroundSidebarHistory {
sessions: readonly SidebarSession[];
activeSessionId?: string;
- /** 正在恢复的云端记录;仅当前行显示状态,不禁止用户切换其他记录。 */
+ /** Cloud record being restored; only the current row shows status, and the user is not blocked from switching to other records. */
pendingSessionId?: string;
onSelectSession: (id: string) => void;
onDeleteSession: (id: string) => void;
onNewChat: () => void;
loading?: boolean;
storageError?: string;
- /** 临时保存等非阻断提示,与真正的数据错误区分。 */
+ /** Non-blocking hints such as a temporary save, distinguished from a real data error. */
storageNotice?: string;
hasMore?: boolean;
loadingMore?: boolean;
@@ -30,9 +30,9 @@ export interface PlaygroundSidebarHistory {
interface PlaygroundHistoryListProps extends PlaygroundSidebarHistory {
kind: 'language' | 'image-parse' | 'image-parse-cases';
- /** 分组后仍按完整缓存判断首次加载,避免空分组在后台刷新时改变高度。 */
+ /** After grouping, still judge the first load from the full cache, so an empty group does not change height during a background refresh. */
hasCachedSessions?: boolean;
- /** 多个分组共用父级滚动容器时,内部不创建会阻断滚动链的滚动区域。 */
+ /** When several groups share the parent scroll container, do not create an inner scroll region that would break the scroll chain. */
scrollMode?: 'self' | 'parent';
}
@@ -42,7 +42,7 @@ const LIST_LABELS = {
'image-parse-cases': { title: 'imageParseCases', region: 'imageParseCasesList' },
} as const;
-/** 语言对话与 OCR 共用的左侧历史:独立或随父级滚动、当前条目、新建、删除和分页。 */
+/** Left history shared by language chat and OCR: scroll on its own or with the parent, current item, new, delete, and paging. */
export function PlaygroundHistoryList({
kind,
sessions,
@@ -119,7 +119,7 @@ export function PlaygroundHistoryList({
{t(storageNotice)}
</p>
) : null}
- {/* 已有条目时后台刷新不插入占位行,避免切换历史引发整列位移。 */}
+ {/* When entries already exist, a background refresh does not insert a placeholder row, so switching history does not shift the whole column. */}
{initialLoading && !sessions.length ? (
<p
role="status"
diff --git a/webdemo/frontend/src/pages/playground/components/PlaygroundLayout.test.tsx b/webdemo/frontend/src/pages/playground/components/PlaygroundLayout.test.tsx
index eab0e4a..44bf514 100644
--- a/webdemo/frontend/src/pages/playground/components/PlaygroundLayout.test.tsx
+++ b/webdemo/frontend/src/pages/playground/components/PlaygroundLayout.test.tsx
@@ -67,7 +67,7 @@ describe('PlaygroundLayout', () => {
callbacks.forEach((callback) => callback(0));
}
- /** 双帧入场:提交收起态后跨两帧才进入终态,跑完这两帧面板才算完全展开。 */
+ /** Two-frame entrance: after committing the collapsed state, the final state is entered across two frames; the panel counts as fully expanded only after those two frames. */
function enterPanel() {
act(flushAnimationFrame);
act(flushAnimationFrame);
@@ -83,14 +83,14 @@ describe('PlaygroundLayout', () => {
await user.click(screen.getByRole('button', { name: '打开引用' }));
const panel = screen.getByTestId('playground-right-panel');
- // 在文档流里占位(主区让出宽度),而不是脱离文档流盖在正文上
+ // Occupy space in document flow (the main area gives up width) rather than leaving document flow and covering the body
expect(panel).toHaveClass('relative', 'shrink-0');
expect(panel).not.toHaveClass('fixed');
expect(panel).toHaveAttribute('aria-hidden', 'true');
expect(panel).toHaveAttribute('data-state', 'opening');
expect(panel).toHaveClass('w-0');
- // 外层管宽度、内层管位移,滑入的是内层
+ // The outer layer owns width and the inner layer owns translation; what slides in is the inner layer
const surface = panel.firstElementChild as HTMLElement;
expect(surface).toHaveClass('translate-x-6');
@@ -121,10 +121,10 @@ describe('PlaygroundLayout', () => {
await user.click(screen.getByRole('button', { name: '打开引用' }));
enterPanel();
- // 全屏遮罩会把并排面板变成事实上的模态,压暗并锁死正文——桌面端必须没有它
+ // A full-screen mask would turn the side-by-side panel into a modal in practice, dimming and locking the body — desktop must not have it
expect(container.querySelector('.fixed.inset-0')).toBeNull();
- // 正文按钮仍能点到:userEvent 会因 pointer-events: none 而报错,等于替我们守住了可交互性
+ // Body buttons can still be clicked: userEvent errors on pointer-events: none, which guards interactivity for us
await user.click(screen.getByRole('button', { name: /正文按钮/ }));
expect(screen.getByRole('button', { name: '正文按钮 1' })).toBeInTheDocument();
});
@@ -155,7 +155,7 @@ describe('PlaygroundLayout', () => {
enterPanel();
expect(panel).toHaveAttribute('data-state', 'open');
expect(panel).toHaveClass('translate-x-0');
- // 窄屏没有并排空间,面板脱离文档流,主区宽度从头到尾不变
+ // A narrow screen has no side-by-side space; the panel leaves document flow, and the main-area width never changes
expect(screen.getByRole('main').className).toBe(mainClass);
});
@@ -168,7 +168,7 @@ describe('PlaygroundLayout', () => {
enterPanel();
const panel = screen.getByTestId('playground-right-panel');
- // 按 testid 取,别按 .fixed.inset-0.z-40 取:移动端侧栏遮罩同形,会先被选中
+ // Query by testid, not by .fixed.inset-0.z-40: the mobile sidebar mask has the same shape and would be selected first
await user.click(screen.getByTestId('playground-right-panel-overlay'));
expect(onClose).toHaveBeenCalledTimes(1);
diff --git a/webdemo/frontend/src/pages/playground/components/PlaygroundLayout.tsx b/webdemo/frontend/src/pages/playground/components/PlaygroundLayout.tsx
index 80b8d6f..1fa2b24 100644
--- a/webdemo/frontend/src/pages/playground/components/PlaygroundLayout.tsx
+++ b/webdemo/frontend/src/pages/playground/components/PlaygroundLayout.tsx
@@ -1,12 +1,9 @@
/**
- * 体验中心全屏外壳。
+ * Full-screen shell of the experience center.
*
- * 用途:左侧栏 + 右侧主区(顶栏 + 内容 + 底部免责声明)的全屏布局。
- * 桌面端(≥lg)侧栏常驻并排;移动端侧栏改为抽屉(fixed 滑出 + 遮罩),主区占满全宽。
- * 纯结构组件,不含业务逻辑。
+ * Purpose: a full-screen layout of the left sidebar + the right main area (top bar + content + bottom disclaimer). On desktop (≥lg) the sidebar stays side by side; on mobile the sidebar becomes a drawer (fixed slide-out + mask) and the main area takes the full width. A pure structure component, with no business logic.
*
- * 备案说明:体验中心用独立全屏壳,底部不放备案(备案已在登录页与 AdminLayout 下的
- * 全部业务页常驻展示),此处改为「AI 生成内容免责声明 + 协议入口」。
+ * Filing-record note: the experience center uses an independent full-screen shell and does not put the filing record at the bottom (the filing record already stays on the login page and on every business page under AdminLayout). This is changed to "AI-generated-content disclaimer + agreement entry."
*/
import { useEffect, useState } from 'react';
@@ -19,24 +16,24 @@ interface PlaygroundLayoutProps {
sidebar: React.ReactNode;
topBar: React.ReactNode;
children: React.ReactNode;
- /** 是否为移动端(<lg):侧栏转抽屉,右侧工作区转覆盖式 */
+ /** Whether this is mobile (<lg): the sidebar becomes a drawer, and the right workspace becomes an overlay */
isMobile: boolean;
- /** 移动端抽屉是否打开 */
+ /** Whether the mobile drawer is open */
mobileSidebarOpen: boolean;
- /** 关闭移动端抽屉(点遮罩) */
+ /** Close the mobile drawer (click the mask) */
onCloseMobileSidebar: () => void;
- /** 语言模型主区右侧的非模态工作区。 */
+ /** Non-modal workspace on the right of the language-model main area. */
rightPanel?: React.ReactNode;
- /** 右侧工作区是否展开。 */
+ /** Whether the right workspace is expanded. */
rightPanelOpen?: boolean;
- /** 关闭右侧工作区;桌面端非模态不需要,仅移动端点遮罩时触发。 */
+ /** Close the right workspace; desktop non-modal mode does not need this, and it fires only when the mobile mask is clicked. */
onCloseRightPanel?: () => void;
- /** 图像解析等工作台自带顶栏时,不再叠体验中心免责条 */
+ /** When a workspace such as image parse brings its own top bar, do not stack the experience-center disclaimer bar */
hideFooter?: boolean;
}
/**
- * 全屏外壳。用 h-dvh + 100vh 回退适配移动端地址栏。
+ * Full-screen shell. Use h-dvh with a 100vh fallback to fit the mobile address bar.
*/
export function PlaygroundLayout({
sidebar,
@@ -54,7 +51,7 @@ export function PlaygroundLayout({
<div className="flex h-screen h-[100dvh] w-full overflow-hidden bg-muted/30">
{isMobile ? (
<>
- {/* 遮罩 */}
+ {/* Mask */}
<div
className={`fixed inset-0 z-40 bg-black/40 transition-opacity duration-200 ${
mobileSidebarOpen ? 'opacity-100' : 'pointer-events-none opacity-0'
@@ -62,7 +59,7 @@ export function PlaygroundLayout({
onClick={onCloseMobileSidebar}
aria-hidden
/>
- {/* 抽屉 */}
+ {/* Drawer */}
<div
className={`fixed inset-y-0 left-0 z-50 transition-transform duration-200 ease-out ${
mobileSidebarOpen ? 'translate-x-0' : '-translate-x-full'
@@ -78,8 +75,7 @@ export function PlaygroundLayout({
{topBar}
<div className="flex min-h-0 min-w-0 flex-1">
{/*
- 桌面端面板在文档流里占位,主区让出宽度,所以要 overflow-hidden 兜住收窄瞬间
- 可能横向溢出的宽表格/长代码块;移动端面板是覆盖式,主区宽度不变,无需裁剪。
+ The desktop panel occupies space in document flow and the main area gives up width, so overflow-hidden covers wide tables / long code blocks that may overflow horizontally the instant it narrows. The mobile panel is an overlay, the main-area width does not change, and clipping is unnecessary.
*/}
<main
className={cn('min-h-0 min-w-0 flex-1', !isMobile && rightPanel && 'overflow-hidden')}
@@ -90,7 +86,7 @@ export function PlaygroundLayout({
{rightPanel}
</AnimatedRightPanel>
</div>
- {/* 免责声明 + 协议入口:固定贴在主区底部,不随内容滚动。备案见登录页/AdminLayout */}
+ {/* Disclaimer + agreement entry: pinned to the bottom of the main area and does not scroll with content. Filing record: see the login page / AdminLayout */}
{hideFooter ? null : (
<PlaygroundFooter className="shrink-0 bg-background/55 py-2 backdrop-blur-sm" />
)}
@@ -99,38 +95,36 @@ export function PlaygroundLayout({
);
}
-/** Drawer 统一的时长与缓动,宽度、位移、遮罩三者共用,让位与滑入才不会脱节。 */
+/** Shared duration and easing for the Drawer. Width, translation, and mask all use it, so making room and sliding in do not fall out of step. */
const PANEL_MOTION = 'duration-300 [transition-timing-function:cubic-bezier(0.32,0.72,0,1)]';
-/** 桌面端面板宽度:26rem 打底,窄屏按 36vw 收,避免把正文挤得过窄。 */
+/** Desktop panel width: 26rem as the base, shrinking to 36vw on a narrow screen so the body is not squeezed too narrow. */
const PANEL_WIDTH = 'w-[min(26rem,36vw)]';
interface AnimatedRightPanelProps {
children?: React.ReactNode;
open: boolean;
- /** 窄屏(<lg)没有并排空间,退化为覆盖式抽屉 + 遮罩。 */
+ /** A narrow screen (<lg) has no side-by-side space and degrades to an overlay drawer + mask. */
isMobile: boolean;
- /** 移动端点遮罩关闭。 */
+ /** On mobile, click the mask to close. */
onClose?: () => void;
}
/**
- * 布局级右侧工作区,带对称的进入与退出动画。
+ * Layout-level right workspace, with symmetric enter and exit animations.
*
- * 桌面端是**非模态并排**:面板在文档流里占位、主区让出宽度,左右两侧同时可点击 / 滚动 /
- * 输入——这正是来源面板要的(边对着来源边继续追问)。所以桌面端**不渲染遮罩**:遮罩会把
- * 面板变成事实上的模态,压暗并锁死正文。
+ * Desktop is **non-modal side by side**: the panel occupies space in document flow, the main area gives up width, and both sides can be clicked / scrolled / typed in at once — which is what the source panel needs (keep following up while looking at sources). So desktop **does not render a mask**: a mask would turn the panel into a modal in practice, dimming and locking the body.
*
- * 窄屏没有并排的宽度,只能退化成覆盖式抽屉 + 遮罩,此时遮罩同时是最顺手的关闭落点。
+ * A narrow screen has no side-by-side width and can only degrade to an overlay drawer + mask. The mask is then also the most convenient close target.
*
- * 首次挂载时先提交收起态,再跨两个动画帧进入终态,避免 React 批量更新让面板直接出现。
+ * On first mount, commit the collapsed state first, then enter the final state across two animation frames, so a React batched update does not make the panel appear directly.
*/
function AnimatedRightPanel({ children, open, isMobile, onClose }: AnimatedRightPanelProps) {
const [entered, setEntered] = useState(false);
useEffect(() => {
if (!open) {
- // 关闭态先复位,后续快速重新打开仍能从明确的起始帧进入。
+ // Reset the closed state first, so a later quick reopen can still enter from a definite starting frame.
// eslint-disable-next-line react-hooks/set-state-in-effect
setEntered(false);
return;
@@ -156,7 +150,7 @@ function AnimatedRightPanel({ children, open, isMobile, onClose }: AnimatedRight
if (isMobile) {
return (
<>
- {/* 遮罩:非模态浮层停在 z-40(dropdown 层),留在 dialog(z-50) / toast(z-100) 之下 */}
+ {/* Mask: the non-modal overlay stays at z-40 (the dropdown layer), under dialog (z-50) / toast (z-100) */}
<div
className={cn(
'fixed inset-0 z-40 bg-foreground/20 backdrop-blur-[1px]',
@@ -190,8 +184,7 @@ function AnimatedRightPanel({ children, open, isMobile, onClose }: AnimatedRight
}
/*
- 桌面端:外层管宽度(把主区推开)、内层管位移与淡入(滑进来)。分两层是因为宽度动画会
- 连带压缩内容、让文字在过渡期抖动;内层固定住最终宽度再整体平移,观感才干净。
+ Desktop: the outer layer owns width (pushing the main area open), and the inner layer owns translation and fade-in (sliding in). Two layers, because a width animation also compresses content and makes text jitter during the transition; the inner layer locks the final width and then translates as a whole, which looks clean.
*/
return (
<div
diff --git a/webdemo/frontend/src/pages/playground/components/PlaygroundSidebar.test.tsx b/webdemo/frontend/src/pages/playground/components/PlaygroundSidebar.test.tsx
index 0aa6694..8818417 100644
--- a/webdemo/frontend/src/pages/playground/components/PlaygroundSidebar.test.tsx
+++ b/webdemo/frontend/src/pages/playground/components/PlaygroundSidebar.test.tsx
@@ -100,17 +100,10 @@ describe('PlaygroundSidebar 最近对话分页', () => {
expect(props.onSelectExperience).toHaveBeenCalledWith('image-parse');
});
- it('不提供关键信息抽取入口', () => {
- renderSidebar({
- hasImageParseModels: true,
- imageParseHistory: {
- sessions: [...SHARED_EXAMPLES, { id: 'kie-history', title: '发票字段' }],
- onSelectSession: vi.fn(),
- onDeleteSession: vi.fn(),
- onNewChat: vi.fn(),
- },
- });
- expect(screen.queryByRole('button', { name: '关键信息抽取' })).not.toBeInTheDocument();
+ it('有文档解析模型权限时展示关键信息抽取入口', () => {
+ const props = renderSidebar({ hasImageParseModels: true });
+ fireEvent.click(screen.getByRole('button', { name: '关键信息抽取' }));
+ expect(props.onSelectExperience).toHaveBeenCalledWith('field-extract');
});
it('实时音视频入口使用电话图标', () => {
diff --git a/webdemo/frontend/src/pages/playground/components/PlaygroundSidebar.tsx b/webdemo/frontend/src/pages/playground/components/PlaygroundSidebar.tsx
index 26def2e..9033924 100644
--- a/webdemo/frontend/src/pages/playground/components/PlaygroundSidebar.tsx
+++ b/webdemo/frontend/src/pages/playground/components/PlaygroundSidebar.tsx
@@ -1,11 +1,10 @@
/**
- * 体验中心左侧栏。
+ * Left sidebar of the experience center.
*
- * 用途:顶部「返回 + 折叠」;「模型体验」分组按当前用户可见模型动态展示;底部历史列表按当前体验
- * 使用对应的数据和操作。
+ * Purpose: "back + collapse" at the top; the "model experiences" group is shown dynamically from the models visible to the current user; the history list at the bottom uses the data and actions for the current experience.
*/
-import { ScanText } from 'lucide-react';
+import { ListChecks, ScanText } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { isDocumentExperience, type ExperienceKey } from '../utils/experienceRoute';
@@ -21,37 +20,37 @@ export type { ExperienceKey, SidebarSession };
interface PlaygroundSidebarProps {
collapsed: boolean;
onToggle: () => void;
- /** 模型体验当前激活项 */
+ /** Currently active item in model experiences */
activeExperience: ExperienceKey;
onSelectExperience: (key: ExperienceKey) => void;
- /** 最近对话 */
+ /** Recent conversations */
sessions: SidebarSession[];
activeSessionId?: string;
onSelectSession: (id: string) => void;
onDeleteSession: (id: string) => void;
onNewChat: () => void;
- /** 当前用户是否有语音合成模型(无则不渲染该入口) */
+ /** Whether the current user has a speech-synthesis model (otherwise do not render that entry) */
hasTtsModels?: boolean;
- /** 当前用户是否有实时音视频模型(无则不渲染该入口) */
+ /** Whether the current user has a realtime audio-video model (otherwise do not render that entry) */
hasRealtimeModels?: boolean;
- /** 当前用户是否有文档解析模型(无则不渲染该入口) */
+ /** Whether the current user has a document-parse model (otherwise do not render that entry) */
hasImageParseModels?: boolean;
- /** 是否还有更多历史可加载 */
+ /** Whether more history can be loaded */
hasMore?: boolean;
- /** 正在加载更多 */
+ /** Loading more */
loadingMore?: boolean;
- /** 显式加载下一页 */
+ /** Explicitly load the next page */
onLoadMore?: () => void;
- /** OCR 云端个人历史;正文由 OCR 工作台按需读取。 */
+ /** OCR cloud personal history; the body is read on demand by the OCR workspace. */
imageParseHistory?: PlaygroundSidebarHistory;
}
/**
- * 模型体验分组项。语言模型恒在;语音合成 / 实时音视频 / 文档解析均按当前用户可见模型动态增减。
- * @param hasTts 是否有语音合成模型
- * @param hasRealtime 是否有实时音视频模型
- * @param hasImageParse 是否有文档解析模型
- * @returns 可展示的体验入口列表
+ * Items in the model-experiences group. The language model is always present; speech synthesis / realtime audio-video / document parse are added or removed from the models visible to the current user.
+ * @param hasTts Whether there is a speech-synthesis model
+ * @param hasRealtime Whether there is a realtime audio-video model
+ * @param hasImageParse Whether there is a document-parse model
+ * @returns Experience entries that can be shown
*/
function experienceItems(
hasTts: boolean,
@@ -62,6 +61,7 @@ function experienceItems(
tts: string;
realtime: string;
imageParse: string;
+ fieldExtract: string;
},
): SidebarItem[] {
if (hasImageParse) {
@@ -71,13 +71,18 @@ function experienceItems(
label: labels.imageParse,
icon: <ScanText className="h-4 w-4" aria-hidden="true" />,
},
+ {
+ key: 'field-extract',
+ label: labels.fieldExtract,
+ icon: <ListChecks className="h-4 w-4" aria-hidden="true" />,
+ },
];
}
return [];
}
/**
- * 左侧栏。
+ * Left sidebar.
*/
export function PlaygroundSidebar({
collapsed,
@@ -108,7 +113,7 @@ export function PlaygroundSidebar({
collapsed ? 'w-16' : 'w-60'
}`}
>
- {/* 顶部:返回 + 折叠 */}
+ {/* Top: back + collapse */}
<div className="flex h-14 shrink-0 items-center justify-between px-3">
<button
type="button"
@@ -149,6 +154,7 @@ export function PlaygroundSidebar({
tts: t('tts'),
realtime: t('realtime'),
imageParse: t('imageParse'),
+ fieldExtract: t('fieldExtract'),
})}
activeKey={activeExperience}
collapsed={collapsed}
@@ -185,7 +191,7 @@ export function PlaygroundSidebar({
);
}
-/* —— 内联图标(保持与门户一致的细线风格,避免新增依赖) —— */
+/* —— Inline icons (keep the same thin-line style as the portal, and avoid a new dependency) —— */
function IconText() {
return (
<svg
diff --git a/webdemo/frontend/src/pages/playground/components/PlaygroundTopBar.tsx b/webdemo/frontend/src/pages/playground/components/PlaygroundTopBar.tsx
index dcb9e8c..3198cdf 100644
--- a/webdemo/frontend/src/pages/playground/components/PlaygroundTopBar.tsx
+++ b/webdemo/frontend/src/pages/playground/components/PlaygroundTopBar.tsx
@@ -1,7 +1,7 @@
/**
- * 体验中心顶栏。
+ * Experience-center top bar.
*
- * 用途:左侧模型选择器;右侧参数设置 / 清空对话(真功能)+ 「API 接入」(打开接入抽屉)。
+ * Purpose: model selector on the left; parameter settings / clear conversation (real features) on the right + "API access" (opens the access drawer).
*/
import { Link } from 'react-router-dom';
@@ -22,13 +22,13 @@ interface PlaygroundTopBarProps {
onOpenSettings: () => void;
onClear: () => void;
canClear: boolean;
- /** 移动端:显示汉堡键以唤出侧栏抽屉 */
+ /** Mobile: show the hamburger to summon the sidebar drawer */
showMenuButton?: boolean;
onOpenSidebar?: () => void;
}
/**
- * 顶栏。
+ * Top bar.
*/
export function PlaygroundTopBar({
models,
@@ -113,7 +113,7 @@ export function PlaygroundTopBar({
<TooltipContent>{t('parameterSettings')}</TooltipContent>
</Tooltip>
- {/* 真功能:清除上下文(开启全新对话,旧对话保留在「最近对话」) */}
+ {/* Real feature: clear context (start a fresh conversation; the old conversation stays in "recent conversations") */}
<Tooltip>
<TooltipTrigger asChild>
<button
diff --git a/webdemo/frontend/src/pages/playground/components/ProcessToolRow.tsx b/webdemo/frontend/src/pages/playground/components/ProcessToolRow.tsx
index 5983515..2f31d23 100644
--- a/webdemo/frontend/src/pages/playground/components/ProcessToolRow.tsx
+++ b/webdemo/frontend/src/pages/playground/components/ProcessToolRow.tsx
@@ -1,9 +1,7 @@
/**
- * 过程时间线上的一次工具调用。
+ * One tool call on the process timeline.
*
- * 用途:把工具行从「元数据清单」改成「内容行」——搜索行报搜到了多少网页并叠放站点图标,
- * 读页行就地列出读了哪几篇,进行中就地显示正在搜什么。单步耗时与关键词计数一律不展示:
- * 它们对用户没有决策价值,耗时只在过程区顶部报一次总数。
+ * Purpose: turn a tool row from a "metadata list" into a "content row" — a search row reports how many pages were found and stacks site icons, a page-read row lists which pages were read in place, and while in progress it shows what is being searched in place. Per-step duration and keyword counts are never shown: they have no decision value for the user, and duration is reported once as a total at the top of the process area.
*/
import { useTranslation } from 'react-i18next';
@@ -23,23 +21,23 @@ import { InlineSourceLinks } from './InlineSourceLinks';
import { StackedFavicons } from './StackedFavicons';
interface ProcessToolRowProps {
- /** 本次工具调用。 */
+ /** This tool call. */
event: ToolEvent;
- /** 该行要就地展示的来源(已由 toolRowCitations 解析好)。 */
+ /** Sources this row should show in place (already resolved by toolRowCitations). */
citations: Citation[];
- /** 打开来源抽屉;给了才把搜索行的「搜索到 N 个网页 + 站点图标」整块做成可点。 */
+ /** Open the source drawer; only when provided is the search row's whole "found N pages + site icons" block made clickable. */
onOpenSources?: () => void;
- /** 是否为时间线最后一项。 */
+ /** Whether this is the last item on the timeline. */
last?: boolean;
}
/**
- * 渲染一条工具行。
- * @param event 工具事件
- * @param citations 该行的来源
- * @param onOpenSources 打开来源抽屉
- * @param last 是否为时间线最后一项
- * @returns 工具行
+ * Renders one tool row.
+ * @param event Tool event
+ * @param citations Sources for this row
+ * @param onOpenSources Open the source drawer
+ * @param last Whether this is the last item on the timeline
+ * @returns A tool row
*/
export function ProcessToolRow({
event,
@@ -51,7 +49,7 @@ export function ProcessToolRow({
const failed = event.status === 'failed';
const running = event.status === 'running';
const label = toolLabel(event, citations, t);
- // 搜索完成的那一行:文案与图标合成一个通往来源抽屉的入口
+ // The row for a finished search: copy and icons form one entry to the source drawer
const searchDone = isSearchTool(event.tool) && !running && !failed;
return (
@@ -83,11 +81,9 @@ export function ProcessToolRow({
}
/**
- * 搜索行的可点区域:主文案 + 那一叠站点图标整块通往来源抽屉。
+ * Clickable region of a search row: the main copy plus the stack of site icons, as one block leading to the source drawer.
*
- * 这一行本来就是「这一步碰了这些网页」的摘要,点它去看是哪些网页是最短的路径——否则用户
- * 得先无视眼前这一叠图标,再翻到回答末尾去找胶囊。没有来源或上层没给回调时退回纯文本,
- * 不做一个点了没反应的按钮。
+ * This row is already a summary of "the pages this step touched," and clicking it to see which pages is the shortest path — otherwise the user has to ignore the stack of icons in front of them and then scroll to the end of the answer to find the chip. When there are no sources or the parent did not pass a callback, fall back to plain text, and do not make a button that does nothing when clicked.
*/
function SourcesTrigger({
label,
@@ -113,16 +109,14 @@ function SourcesTrigger({
<button
type="button"
onClick={onOpen}
- /* 图标是 aria-hidden 的装饰,可读名字只能由文案给,再补一句去向 */
+ /* The icon is aria-hidden decoration; a readable name can come only from the copy, plus one phrase about where it goes */
aria-label={`${label},${t('openReferences')}`}
data-testid="tool-row-sources"
className={cn(
'-mx-1 -my-0.5 inline-flex max-w-full items-center rounded px-1 py-0.5 text-left align-middle',
'transition-colors duration-200',
/*
- hover 只让文字变深,不铺背景:这一行是时间线里的一段行内文字,给它一块底色会在
- marker 列旁边凭空多出一个方块,把「一条线」读成「一张卡片」。文字由 muted 提到
- foreground 已经足够表明可点,负边距与 px/py 留着是给 focus ring 让位。
+ Hover only darkens the text and does not paint a background: this row is a stretch of inline text in the timeline, and giving it a fill would add a square from nowhere beside the marker column, reading "a line" as "a card." Raising the text from muted to foreground is enough to show it is clickable. The negative margin and px/py stay to make room for the focus ring.
*/
'hover:text-foreground',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40',
@@ -134,7 +128,7 @@ function SourcesTrigger({
);
}
-/** 进行中的搜索词:紧跟主文案逐个淡入,完成后被「搜索到 N 个网页」取代。 */
+/** In-progress search terms: fade in one by one right after the main copy, and after completion are replaced by "found N pages." */
function RunningQueries({ queries }: { queries: string[] }) {
return (
<span className="text-foreground/70">
@@ -152,12 +146,9 @@ function RunningQueries({ queries }: { queries: string[] }) {
}
/**
- * 工具行 marker:失败告警,其余按工具语义给固定图标。
+ * Tool-row marker: a failure alert, otherwise a fixed icon by tool meaning.
*
- * 进行中**不转圈**。转圈只留过程区顶行那一枚:顶行在收起态也在场,且开了联网到首个工具帧
- * 到达之间还有一段时间线为空的空档,动效必须由它承担。两处同时转就是同一件事报两遍,
- * 各转各的更乱。进行中的那一行靠文案区分——`搜索 <关键词>` 对 `搜索到 N 个网页`,
- * 图标反而因此在「进行中 → 完成」之间保持同一枚,不在收尾那一刻跳一下形。
+ * While in progress it **does not spin**. Spinning is left to the one icon on the process-area top row: the top row is present even when collapsed, and there is still a gap between turning web search on and the first tool frame arriving when the timeline is empty, so the motion has to be carried there. Spinning in both places reports the same thing twice, and spinning independently is more confusing. The in-progress row is distinguished by copy — `search <keyword>` versus `found N pages` — so the icon stays the same from "in progress → done" and does not change shape at the moment it finishes.
*/
function ToolMarker({ event }: { event: ToolEvent }) {
if (event.status === 'failed') {
@@ -166,7 +157,7 @@ function ToolMarker({ event }: { event: ToolEvent }) {
if (event.status === 'interrupted') {
return <CircleAlert className="size-4 text-muted-foreground/60" aria-hidden="true" />;
}
- // 进行中的这一行用 primary 着色,让「现在在跑哪一步」仍然一眼可辨
+ // Color this in-progress row with primary, so "which step is running now" is still obvious at a glance
const className =
event.status === 'running' ? 'size-4 text-primary' : 'size-4 text-muted-foreground/70';
if (isSearchTool(event.tool)) return <Search className={className} aria-hidden="true" />;
@@ -176,15 +167,14 @@ function ToolMarker({ event }: { event: ToolEvent }) {
}
/**
- * 生成工具行主文案。
+ * Builds the main copy of a tool row.
*
- * 完成态优先报「成果数量」而不是工具名:用户关心的是搜到/读了多少,而不是调用了哪个函数。
- * 数量拿不到时(旧消息、后端没给计数)退回工具名,不编造数字。
+ * The finished state prefers to report "how many results" rather than the tool name: the user cares how many were found or read, not which function was called. When the count is unavailable (old messages, the backend did not send a count), fall back to the tool name and do not invent a number.
*
- * @param event 工具事件
- * @param citations 该行的来源,用于计数兜底
- * @param t i18n 翻译函数
- * @returns 主文案
+ * @param event Tool event
+ * @param citations Sources for this row, used as a count fallback
+ * @param t i18n translate function
+ * @returns Main copy
*/
function toolLabel(
event: ToolEvent,
diff --git a/webdemo/frontend/src/pages/playground/components/SettingsPanel.tsx b/webdemo/frontend/src/pages/playground/components/SettingsPanel.tsx
index 401d9ab..af3052d 100644
--- a/webdemo/frontend/src/pages/playground/components/SettingsPanel.tsx
+++ b/webdemo/frontend/src/pages/playground/components/SettingsPanel.tsx
@@ -1,8 +1,7 @@
/**
- * 参数设置面板(弹窗)。
+ * Parameter settings panel (dialog).
*
- * 用途:调节对话采样、思考参数风格与 v4.7 图片压缩比例。
- * 滑块需求暂以数字输入承载(避免新增 @map/ui 原语),范围由 min/max/step 约束。
+ * Purpose: adjust chat sampling, the reasoning-parameter style, and the v4.7 image compression ratio. Slider needs are carried by a number input for now (avoid adding an @map/ui primitive), and the range is constrained by min/max/step.
*/
import {
@@ -30,16 +29,16 @@ interface SettingsPanelProps {
modelId: string;
onOpenChange: (open: boolean) => void;
params: PlaygroundParams;
- /** 当前模型是否支持深度思考,不支持时隐藏思考设置。 */
+ /** Whether the current model supports deep reasoning; hide reasoning settings when it does not. */
showReasoning?: boolean;
onUpdate: (patch: Partial<PlaygroundParams>) => void;
- /** 流式输出开关 */
+ /** Streaming-output switch */
onStreamChange: (stream: boolean) => void;
onReset: () => void;
}
/**
- * 参数设置弹窗。
+ * Parameter settings dialog.
*/
export function SettingsPanel({
open,
@@ -176,7 +175,7 @@ export function SettingsPanel({
);
}
-/** 开关字段:标签 + 说明 + 右侧开关(@map/ui 暂无 Switch 原语,用受控按钮模拟) */
+/** Switch field: label + description + switch on the right (@map/ui has no Switch primitive yet; simulate it with a controlled button) */
function ToggleField({
label,
hint,
@@ -217,7 +216,7 @@ function ToggleField({
);
}
-/** 带说明的数字输入字段 */
+/** Number input field with a description */
function NumberField({
id,
label,
diff --git a/webdemo/frontend/src/pages/playground/components/SidebarSection.tsx b/webdemo/frontend/src/pages/playground/components/SidebarSection.tsx
index cbddb6c..622eb2e 100644
--- a/webdemo/frontend/src/pages/playground/components/SidebarSection.tsx
+++ b/webdemo/frontend/src/pages/playground/components/SidebarSection.tsx
@@ -1,32 +1,32 @@
/**
- * 侧栏分组(标题 + 项列表)。
+ * Sidebar group (title + item list).
*
- * 用途:渲染体验中心左侧栏的一个分组。项可为真功能(可点击)或占位(带「敬请期待」标,禁用)。
+ * Purpose: render one group in the experience-center left sidebar. An item can be a real feature (clickable) or a placeholder (with a "coming soon" mark, disabled).
*/
import { Badge } from '@map/ui';
-/** 单个侧栏项 */
+/** A single sidebar item */
export interface SidebarItem {
key: string;
label: string;
icon: React.ReactNode;
- /** 是否为占位项(禁用 + 待开放标) */
+ /** Whether this is a placeholder item (disabled + not-yet-open mark) */
placeholder?: boolean;
}
interface SidebarSectionProps {
title: string;
items: SidebarItem[];
- /** 当前激活项 key */
+ /** Key of the currently active item */
activeKey?: string;
- /** 是否收起(仅显示图标) */
+ /** Whether it is collapsed (icons only) */
collapsed?: boolean;
onSelect?: (key: string) => void;
}
/**
- * 渲染一个侧栏分组。
+ * Renders one sidebar group.
*/
export function SidebarSection({
title,
@@ -71,7 +71,7 @@ export function SidebarSection({
);
}
-/** 侧栏项的状态样式:占位 / 激活 / 普通 */
+/** State styles for a sidebar item: placeholder / active / normal */
function itemStateClass(placeholder: boolean, active: boolean): string {
if (placeholder) return 'cursor-not-allowed text-muted-foreground/50';
if (active) return 'bg-primary/10 font-medium text-primary';
diff --git a/webdemo/frontend/src/pages/playground/components/SourcesChip.tsx b/webdemo/frontend/src/pages/playground/components/SourcesChip.tsx
index 1cb9fbe..1407e63 100644
--- a/webdemo/frontend/src/pages/playground/components/SourcesChip.tsx
+++ b/webdemo/frontend/src/pages/playground/components/SourcesChip.tsx
@@ -1,8 +1,7 @@
/**
- * 回答下方的来源胶囊。
+ * Source chip under an answer.
*
- * 用途:用一枚「一叠站点图标 + N 个网页」的胶囊取代整条横滑卡片,回答与过程之间只留一个
- * 通往来源抽屉的入口。来源的标题、摘要、序号统一由抽屉承载,正文下方不再重复一遍。
+ * Purpose: replace the whole horizontally scrolling card row with one chip of "a stack of site icons + N pages," leaving a single entry to the source drawer between the answer and the process. Source titles, summaries, and indexes are all carried by the drawer and are not repeated under the body.
*/
import { useTranslation } from 'react-i18next';
@@ -13,20 +12,20 @@ import type { Citation } from '../types';
import { StackedFavicons } from './StackedFavicons';
interface SourcesChipProps {
- /** 本轮回答使用的全部来源。 */
+ /** All sources used by this answer. */
citations: Citation[];
- /** 打开来源抽屉。 */
+ /** Open the source drawer. */
onOpen?: () => void;
- /** 来源抽屉当前是否已打开(供胶囊标注 aria-expanded)。 */
+ /** Whether the source drawer is currently open (for the chip's aria-expanded). */
panelOpen?: boolean;
}
/**
- * 渲染来源胶囊。
- * @param citations 本轮回答使用的全部来源
- * @param onOpen 打开来源抽屉
- * @param panelOpen 来源抽屉是否已打开
- * @returns 来源胶囊;无来源或无法打开抽屉时不渲染
+ * Renders the source chip.
+ * @param citations All sources used by this answer
+ * @param onOpen Open the source drawer
+ * @param panelOpen Whether the source drawer is already open
+ * @returns The source chip; render nothing when there are no sources or the drawer cannot be opened
*/
export function SourcesChip({ citations, onOpen, panelOpen }: SourcesChipProps) {
const { t } = useTranslation('playground');
@@ -43,17 +42,12 @@ export function SourcesChip({ citations, onOpen, panelOpen }: SourcesChipProps)
data-testid="sources-chip"
className={cn(
/*
- mt-1 而不是照抄下方指标行的 mt-2.5:上面那行正文是 leading-7,自带 7.5px 半行距,
- 眼睛看到的间距是「半行距 + 外边距」。4 + 7.5 ≈ 10 + 1.5,胶囊才落在正中间;
- 两边写同一个数反而会明显偏下。前提是正文尾元素的下边距已清零(见 MarkdownRenderer)。
+ mt-1 rather than copying the metrics row's mt-2.5 below: the body line above is leading-7 and brings 7.5px of half-leading, and the spacing the eye sees is "half-leading + margin." 4 + 7.5 ≈ 10 + 1.5, which is what lands the chip in the middle; writing the same number on both sides makes it sit noticeably low. This assumes the last body's bottom margin is already cleared (see MarkdownRenderer).
*/
'mt-1 inline-flex min-h-9 items-center gap-2 rounded-full bg-muted py-1.5 pl-2.5 pr-3',
'text-xs text-muted-foreground transition-colors duration-200',
/*
- hover 拿 primary 淡染,不是把灰加深。--muted-foreground 是低饱和中灰 (220 9% 46%),
- 混进浅色底会把饱和度一起拉掉,合成色正好落在 --border 上——用画分隔线的颜色铺满
- 一整块,在这排冷蓝界面里成了唯一偏离蓝轴的一处,所以显脏。primary 在明暗两套主题
- 里同值且亮度居中,换成它两种模式都是同向反馈;8% 取自 @map/ui 既有的同类 hover。
+ Hover uses a light primary wash, not a darker gray. --muted-foreground is a low-saturation mid gray (220 9% 46%). Mixing it into a light background pulls the saturation down with it, and the mixed color lands exactly on --border — filling a whole block with the color used to draw separators, the one place in this cool-blue interface that leaves the blue axis, so it looks dirty. primary has the same value and a centered lightness in both light and dark themes, so switching to it is feedback in the same direction in both modes; 8% is taken from the existing hover of the same kind in @map/ui.
*/
'hover:bg-primary/[0.08] hover:text-foreground',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40',
diff --git a/webdemo/frontend/src/pages/playground/components/StackedFavicons.tsx b/webdemo/frontend/src/pages/playground/components/StackedFavicons.tsx
index 26a95f1..066a461 100644
--- a/webdemo/frontend/src/pages/playground/components/StackedFavicons.tsx
+++ b/webdemo/frontend/src/pages/playground/components/StackedFavicons.tsx
@@ -1,8 +1,7 @@
/**
- * 叠放的来源站点图标。
+ * Stacked source-site icons.
*
- * 用途:过程时间线的搜索行与回答下方的来源胶囊共用同一枚「一叠网页」视觉,
- * 用极小的横向占位表达「这一步碰了这些站点」,具体是哪些页面由抽屉承载。
+ * Purpose: the search row on the process timeline and the source chip under the answer share one "a stack of pages" visual. A very small horizontal footprint says "this step touched these sites," and which pages they are is carried by the drawer.
*/
import { cn } from '@map/ui';
@@ -12,29 +11,25 @@ import { MAX_ROW_FAVICONS, STAGGER_CLASS_NAME, staggerStyle } from '../utils/ans
import { CitationFavicon } from './CitationFavicon';
interface StackedFaviconsProps {
- /** 要展示的来源;只取其 url 画图标。 */
+ /** Sources to show; only their url is used to draw the icon. */
citations: Citation[];
- /** 最多叠放几个,多出来的不展示也不计数。 */
+ /** How many to stack at most; extras are neither shown nor counted. */
max?: number;
- /** 外层容器样式。 */
+ /** Outer container styles. */
className?: string;
}
/**
- * 渲染一叠重叠的站点图标。
+ * Renders a stack of overlapping site icons.
*
- * 图标是纯装饰(`aria-hidden`):同一批来源的可读表达已经由紧挨着的文案(「搜索到 N 个网页」、
- * 胶囊上的「N 个网页」)和抽屉里的完整列表给出,这里再读一遍只会让屏幕阅读器把一行念成
- * 一串无意义的域名。
+ * The icons are pure decoration (`aria-hidden`): a readable expression of the same sources is already given by the adjacent copy ("found N pages," "N pages" on the chip) and the full list in the drawer. Reading them again here would only make a screen reader speak a row as a string of meaningless domains.
*
- * 溢出**不报 +N**:数量就在旁边那句文案里,再补一个 +N 是同一件事说两遍;而搜索行的这一叠
- * 是拿整条消息的来源兜底出来的近似值(后端不发 web_search 的地址),+N 会与该行自己报的
- * 「搜索到 N 个网页」直接对不上——截图里 `搜索到 10 个网页 +26` 就是这么来的。
+ * Overflow **does not report +N**: the count is in the copy beside it, and adding a +N says the same thing twice. The stack on a search row is an approximation filled from the whole message's sources (the backend does not send web_search addresses), so +N would fail to match the "found N pages" that row reports itself — `found 10 pages +26` in the screenshot came from exactly that.
*
- * @param citations 来源列表
- * @param max 最多叠放数量,默认 MAX_ROW_FAVICONS
- * @param className 外层容器样式
- * @returns 叠放图标;没有来源时不渲染
+ * @param citations Source list
+ * @param max Maximum stack count; default MAX_ROW_FAVICONS
+ * @param className Outer container styles
+ * @returns Stacked icons; render nothing when there are no sources
*/
export function StackedFavicons({
citations,
@@ -52,8 +47,7 @@ export function StackedFavicons({
aria-hidden="true"
style={staggerStyle(index)}
/*
- 重叠靠负外边距,层级靠 ring 与 background 撑出的"描边"——两个图标之间必须有一圈
- 与页面同色的环,否则深色站点图标叠在一起会糊成一团分不出个数。
+ Overlap comes from a negative margin, and layering comes from the "stroke" held up by ring and background — there must be a ring the same color as the page between two icons, or dark site icons stacked together blur into one mass and the count cannot be told apart.
*/
className={cn(STAGGER_CLASS_NAME, '-ml-1.5 first:ml-0')}
>
diff --git a/webdemo/frontend/src/pages/playground/components/TaskCards.tsx b/webdemo/frontend/src/pages/playground/components/TaskCards.tsx
index 2c517f9..4f8dc7f 100644
--- a/webdemo/frontend/src/pages/playground/components/TaskCards.tsx
+++ b/webdemo/frontend/src/pages/playground/components/TaskCards.tsx
@@ -1,21 +1,20 @@
/**
- * 「试试以下任务」示例卡片网格。
+ * "Try these tasks" example-card grid.
*
- * 用途:对话开始前展示一组示例提示词,点击把文案填入输入框(半真功能)。
- * 文案为静态预设,呼应火山方舟的任务卡片区。
+ * Purpose: before a conversation starts, show a set of example prompts; clicking fills the copy into the input (a half-real feature). The copy is a static preset, echoing Volcano Ark's task-card area.
*/
import { Card } from '@map/ui';
import { useTranslation } from 'react-i18next';
interface TaskCardsProps {
- /** 点击卡片:把示例文案填入输入框 */
+ /** Click a card: fill the example copy into the input */
onPick: (prompt: string) => void;
}
/**
- * 渲染示例卡片网格。
- * @param onPick 选中回调
+ * Renders the example-card grid.
+ * @param onPick Selection callback
*/
export function TaskCards({ onPick }: TaskCardsProps) {
const { t } = useTranslation('playground');
diff --git a/webdemo/frontend/src/pages/playground/components/WelcomeHero.tsx b/webdemo/frontend/src/pages/playground/components/WelcomeHero.tsx
index ddb1454..8720138 100644
--- a/webdemo/frontend/src/pages/playground/components/WelcomeHero.tsx
+++ b/webdemo/frontend/src/pages/playground/components/WelcomeHero.tsx
@@ -1,14 +1,14 @@
/**
- * 体验中心欢迎语。
+ * Experience-center welcome line.
*
- * 用途:对话开始前展示在输入框上方的居中欢迎标题,呼应火山方舟的欢迎区。
+ * Purpose: a centered welcome title shown above the input before a conversation starts, echoing Volcano Ark's welcome area.
*/
import { ModelbestMark } from '@/components/ModelbestMark';
import { APP_NAME } from '@/config/brand';
import { useTranslation } from 'react-i18next';
-/** 居中欢迎标题 */
+/** Centered welcome title */
export function WelcomeHero() {
const { t } = useTranslation('playground');
return (
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/AudioWavePlayer.tsx b/webdemo/frontend/src/pages/playground/components/experiences/AudioWavePlayer.tsx
index b7ce174..ff8d651 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/AudioWavePlayer.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/AudioWavePlayer.tsx
@@ -1,9 +1,7 @@
/**
- * 语音波形播放器。
+ * Voice waveform player.
*
- * 用途:为合成/回复音频提供紧凑的自定义播放器——播放/暂停、可点击 seek 的波形进度、
- * 时间、倍速、下载,单行排布。波形取自音频真实峰值(解码一次高分辨率,再按容器宽度
- * 重采样),细条居中镜像,随播放进度高亮;解码失败时退化为一条中线,不影响播放。
+ * Purpose: a compact custom player for synthesized / reply audio — play/pause, a clickable seekable waveform, time, playback rate, and download, in one row. The waveform comes from the audio's real peaks (decode once at high resolution, then resample to the container width). Thin bars are mirrored around the center and highlight with playback progress; on decode failure it degrades to a center line and playback is unaffected.
*/
import { useEffect, useMemo, useRef, useState } from 'react';
@@ -12,24 +10,24 @@ import { useTranslation } from 'react-i18next';
import { decodeWaveformPeaks } from '../../utils/audioEncode';
interface AudioWavePlayerProps {
- /** 音频 Object URL */
+ /** Audio Object URL */
src: string;
- /** 下载文件名 */
+ /** Download file name */
downloadName?: string;
- /** 音频就绪后尝试自动播放;播放被浏览器拦截时保留手动播放入口 */
+ /** Try to autoplay once the audio is ready; if the browser blocks playback, keep a manual play entry */
autoPlay?: boolean;
}
-/** 解码分辨率:一次解够,之后按容器宽度重采样,避免缩放时反复解码 */
+/** Decode resolution: decode enough once, then resample to the container width, so resizing does not decode again */
const PEAK_RESOLUTION = 1024;
-/** 单条占位(条宽 2px + 间隙 2px),用于按容器宽度推算条数 */
+/** Placeholder for one bar (bar width 2px + gap 2px), used to estimate the bar count from the container width */
const BAR_PITCH = 4;
/**
- * 波形播放器。
- * @param src 音频 URL
- * @param downloadName 下载文件名
- * @param autoPlay 是否在音频就绪后尝试自动播放
+ * Waveform player.
+ * @param src Audio URL
+ * @param downloadName Download file name
+ * @param autoPlay Whether to try autoplay once the audio is ready
*/
export function AudioWavePlayer({
src,
@@ -52,10 +50,10 @@ export function AudioWavePlayer({
const [autoPlayBlocked, setAutoPlayBlocked] = useState(false);
const progress = duration > 0 ? current / duration : 0;
- // 结果带 src 存放:src 切换后自动视为“未解码”,无需在 effect 里同步重置
+ // Store the result with src: after src changes it is automatically treated as "not decoded," with no synchronous reset in the effect
const peaks = decoded.src === src ? decoded.peaks : null;
- // 解码真实波形(每个 src 一次)
+ // Decode the real waveform (once per src)
useEffect(() => {
let alive = true;
decodeWaveformPeaks(src, PEAK_RESOLUTION).then((p) => {
@@ -66,7 +64,7 @@ export function AudioWavePlayer({
};
}, [src]);
- // 条数跟随容器宽度,窄屏自动变稀,避免固定条数被挤成胖块
+ // Bar count follows the container width and thins out automatically on a narrow screen, so a fixed count is not squeezed into fat blocks
useEffect(() => {
const el = waveRef.current;
if (!el) return undefined;
@@ -160,7 +158,7 @@ export function AudioWavePlayer({
)}
</button>
- {/* 可点击 / 方向键 seek 的波形 */}
+ {/* Waveform that can be seeked by click / arrow keys */}
<div
ref={waveRef}
onClick={onWaveClick}
@@ -216,7 +214,7 @@ export function AudioWavePlayer({
);
}
-/** 高分辨率峰值 → 指定条数(每条取区间均值,条数多于源时按比例取样) */
+/** High-resolution peaks → a given bar count (each bar takes the interval mean; when there are more bars than the source, sample proportionally) */
function resample(peaks: number[], count: number): number[] {
const out = new Array<number>(count).fill(0);
const ratio = peaks.length / count;
@@ -230,7 +228,7 @@ function resample(peaks: number[], count: number): number[] {
return out;
}
-/** 秒 → mm:ss */
+/** Seconds → mm:ss */
function fmt(sec: number): string {
if (!Number.isFinite(sec) || sec < 0) return '00:00';
const m = Math.floor(sec / 60);
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/DocumentUploadStatus.tsx b/webdemo/frontend/src/pages/playground/components/experiences/DocumentUploadStatus.tsx
index ce17fd8..f729b70 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/DocumentUploadStatus.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/DocumentUploadStatus.tsx
@@ -6,11 +6,11 @@ import { formatBytes } from '../../utils/attachments';
interface DocumentUploadStatusProps {
upload: ReturnType<typeof useDocumentUpload>;
- /** 已有文档时保留预览,只把输入校验错误放在内容上方。 */
+ /** When a document already exists, keep the preview and place input-validation errors above the content. */
inline?: boolean;
}
-/** 在上传区域展示文件与真实等待状态,失败可原文件重试;不伪造进度。 */
+/** In the upload area, show the file and the real waiting state. On failure the original file can be retried; do not fake progress. */
export function DocumentUploadStatus({ upload, inline }: DocumentUploadStatusProps) {
const { t } = useTranslation('playground');
if (!upload.pending && !upload.error) return null;
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/DuplexControlBar.tsx b/webdemo/frontend/src/pages/playground/components/experiences/DuplexControlBar.tsx
index 37567df..ac35ea6 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/DuplexControlBar.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/DuplexControlBar.tsx
@@ -1,9 +1,7 @@
/**
- * 双工底部控制栏(全双工)。
+ * Duplex bottom control bar (full duplex).
*
- * 用途:全双工通话的控制区——未通话时为「开始通话」;通话中麦克风持续在线(无按键说话),
- * 中央为实时状态胶囊(连接中/聆听中/模型说话中/已暂停),配强制聆听 / 暂停 / 结束。
- * 三个按钮都是真实动作。图标用 lucide-react。纯展示组件。
+ * Purpose: the control area for a full-duplex call — "start call" when not in a call; during a call the microphone stays live (no push-to-talk). The center is a realtime status chip (connecting / listening / model speaking / paused), with force-listen / pause / end. All three buttons are real actions. Icons use lucide-react. Pure display component.
*/
import { Tooltip, TooltipContent, TooltipTrigger } from '@map/ui';
@@ -33,7 +31,7 @@ interface DuplexControlBarProps {
}
/**
- * 控制栏。
+ * Control bar.
*/
export function DuplexControlBar({
mode,
@@ -157,7 +155,7 @@ export function DuplexControlBar({
);
}
-/** 通用控制按钮 */
+/** Generic control button */
function CtrlBtn({
children,
icon,
@@ -203,7 +201,7 @@ function CtrlBtn({
);
}
-/** 实时状态胶囊(非交互,据 voiceStatus/paused 反映当前会话态) */
+/** Realtime status chip (non-interactive; reflects the current session state from voiceStatus/paused) */
function StatusPill({
status,
paused,
@@ -226,7 +224,7 @@ function StatusPill({
);
}
-/** 状态胶囊内容:图标 + 文案 + 配色 */
+/** Status-chip content: icon + copy + color */
function pillContent(
status: VoiceStatus,
paused: boolean,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/DuplexConversation.tsx b/webdemo/frontend/src/pages/playground/components/experiences/DuplexConversation.tsx
index f1999ff..121954f 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/DuplexConversation.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/DuplexConversation.tsx
@@ -1,8 +1,7 @@
/**
- * 双工对话记录(纯列表)。
+ * Duplex conversation log (a plain list).
*
- * 用途:展示语音对话的文字气泡,每轮回复后加「本轮结束」分隔(借鉴 MiniCPM-o Omni
- * Conversation)。无外层卡片与标题,供「查看记录」弹窗或其他容器包裹复用。纯展示组件。
+ * Purpose: show the text bubbles of a voice conversation, with a "this turn ended" separator after each reply (borrowed from MiniCPM-o Omni Conversation). No outer card or title, so a "view log" dialog or another container can wrap and reuse it. Pure display component.
*/
import type { SessionMetrics } from '../../utils/realtimeSessionMetrics';
@@ -10,7 +9,7 @@ import type { VoiceEvent, VoiceMessage } from '../../hooks/useRealtimeSession';
import { useTranslation } from 'react-i18next';
/**
- * 对话记录列表。
+ * Conversation log list.
*/
export function DuplexConversation({
messages,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/DuplexExperience.tsx b/webdemo/frontend/src/pages/playground/components/experiences/DuplexExperience.tsx
index 3ddc020..7b2e325 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/DuplexExperience.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/DuplexExperience.tsx
@@ -1,10 +1,7 @@
/**
- * 体验中心「实时音视频(双工)」体验页。
+ * Experience-center "realtime audio-video (duplex)" page.
*
- * 用途:对齐 MiniCPM-o Omni 全双工的通话工作台——视频舞台(真摄像头 / 环形声纹)+ 控制栏 +
- * 右侧完整参数(对话模式/模型/音色/系统提示词/TTS开关/音色克隆/采样参数/设备)+ 对话记录。
- * 通话经后端 realtime WS 代理接入 MiniCPM-O:麦克风持续上行、模型语音下行播放、文本转字幕,
- * video 模式下摄像头帧按 ~1fps 上行做视频理解。逻辑收敛在 useRealtimeSession / useCamera 等。
+ * Purpose: a call workspace aligned with MiniCPM-o Omni full duplex — video stage (real camera / ring voiceprint) + control bar + full parameters on the right (conversation mode/model/voice/system prompt/TTS switch/voice clone/sampling parameters/devices) + conversation log. The call reaches MiniCPM-O through the backend realtime WS proxy: the microphone streams up continuously, model speech plays downstream, and text becomes captions. In video mode camera frames go upstream at ~1fps for video understanding. Logic is gathered in useRealtimeSession / useCamera and the like.
*/
import { useEffect, useMemo, useRef, useState } from 'react';
@@ -42,8 +39,8 @@ const STATUS_HINT: Record<VoiceStatus, string> = {
};
/**
- * 实时音视频双工体验页。
- * @param model 模型与密钥编排(来自页面顶层 usePlaygroundModel)
+ * Realtime audio-video duplex page.
+ * @param model Model and key orchestration (from the page-level usePlaygroundModel)
*/
export function DuplexExperience({ model }: { model: PlaygroundModel }) {
const { t } = useTranslation('playground');
@@ -87,7 +84,7 @@ export function DuplexExperience({ model }: { model: PlaygroundModel }) {
);
const connectionMessage =
rt.status === 'requesting' ? describeConnection(rt.queue, translate) : undefined;
- // 控制条上方提示:模型主动告别时优先提示即将结束,其次按会话状态给操作引导
+ // Hint above the control bar: when the model says goodbye on its own, prefer a hint that the call is about to end; otherwise give action guidance from the session state
const hintText = resolveHint(rt.endedByModel, sessionActive, rt.status, forceListen, translate);
useEffect(() => {
if (!sessionActive || paused) return undefined;
@@ -95,13 +92,13 @@ export function DuplexExperience({ model }: { model: PlaygroundModel }) {
return () => window.clearInterval(id);
}, [sessionActive, paused]);
- // 开始通话:视频模式先开摄像头(失败即放弃),再建立 realtime 会话;连接失败回滚。
+ // Start the call: in video mode open the camera first (give up on failure), then establish the realtime session; roll back if the connection fails.
async function startSession() {
setVoiceError(undefined);
let cameraStream: MediaStream | null = null;
if (videoMode) {
cameraStream = await cam.start();
- if (!cameraStream) return; // cam.error 已置,保持未开始
+ if (!cameraStream) return; // cam.error is already set; stay not started
}
const voice = VOICES.find((item) => item.value === effectiveVoice);
let presetRefAudio: string | undefined;
@@ -142,7 +139,7 @@ export function DuplexExperience({ model }: { model: PlaygroundModel }) {
onInputAudio: (samples) => recorder.current.pushLeft(samples),
onOutputAudio: (samples, sampleRate, timestamp) =>
recorder.current.pushRight(samples, sampleRate, timestamp),
- // 模型输出挂断标记后自动结束:同步关摄像头、复位 UI(与手动点「结束」一致)
+ // After the model emits a hang-up marker, end automatically: turn the camera off and reset the UI in sync (the same as clicking "end" manually)
onSessionEnd: () => {
const result = recorder.current.stop();
if (result) setRecordingResult(result);
@@ -253,7 +250,7 @@ export function DuplexExperience({ model }: { model: PlaygroundModel }) {
setMode(source === 'both' ? 'video' : 'audio');
}
- // 选择音色是一次明确的覆盖操作:清空旧的手动参考音频,确保启动会话时使用用户刚选的音色。
+ // Choosing a voice is an explicit override: clear the old manual reference audio so the session starts with the voice the user just selected.
function changeVoice(voice: string) {
patch({
voice,
@@ -295,7 +292,7 @@ export function DuplexExperience({ model }: { model: PlaygroundModel }) {
else void stageRef.current.requestFullscreen?.();
}
- // 暂停/继续:暂停上行麦克风(下行播放不受影响,据实为会话级暂停)
+ // Pause/resume: pause the upstream microphone (downstream playback is unaffected; in practice this is a session-level pause)
function togglePause() {
setPaused((prev) => {
const next = !prev;
@@ -307,7 +304,7 @@ export function DuplexExperience({ model }: { model: PlaygroundModel }) {
return (
<div className="flex h-full w-full flex-col gap-4 overflow-y-auto px-3 py-4 sm:px-4">
<div className="grid min-h-0 flex-1 grid-cols-1 gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]">
- {/* 左:聚焦通话卡(上画面 + 下控制条同卡,填满与右栏等高) */}
+ {/* Left: focused call card (picture on top + control bar below, one card, filling to the same height as the right column) */}
<div className="flex min-w-0 flex-col">
<section
ref={stageRef}
@@ -363,7 +360,7 @@ export function DuplexExperience({ model }: { model: PlaygroundModel }) {
</section>
</div>
- {/* 右:完整参数面板 */}
+ {/* Right: full parameter panel */}
<DuplexSidePanel
model={model}
sources={SOURCES}
@@ -384,7 +381,7 @@ export function DuplexExperience({ model }: { model: PlaygroundModel }) {
/>
</div>
- {/* 完整对话记录弹窗 */}
+ {/* Full conversation-log dialog */}
<Dialog open={recordOpen} onOpenChange={setRecordOpen}>
<DialogContent className="max-w-lg" onClose={() => setRecordOpen(false)}>
<DialogHeader>
@@ -408,12 +405,12 @@ export function DuplexExperience({ model }: { model: PlaygroundModel }) {
}
/**
- * 控制条上方的提示文案。
- * @param endedByModel 模型是否已输出挂断标记(即将自动结束)
- * @param sessionActive 会话是否进行中
- * @param status 实时会话状态
- * @param forceListen 是否正在让模型优先聆听用户
- * @returns 当前该展示的提示文案
+ * Hint copy above the control bar.
+ * @param endedByModel Whether the model has emitted a hang-up marker (about to end automatically)
+ * @param sessionActive Whether the session is in progress
+ * @param status Realtime session status
+ * @param forceListen Whether the model is being made to listen to the user first
+ * @returns The hint copy that should be shown now
*/
function resolveHint(
endedByModel: boolean,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/DuplexSidePanel.tsx b/webdemo/frontend/src/pages/playground/components/experiences/DuplexSidePanel.tsx
index e0e0cfd..a7126a4 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/DuplexSidePanel.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/DuplexSidePanel.tsx
@@ -1,10 +1,7 @@
/**
- * 双工右侧设置面板(Tabs 分组)。
+ * Duplex right settings panel (grouped in Tabs).
*
- * 用途:对齐 MiniCPM-o demo 的完整参数——通话(对话模式/模型/音色/系统提示词/TTS开关)、
- * 音色克隆(参考音频上传)、高级(Length Penalty/Max Tokens/Temperature/播放延迟)、设备
- * (麦克风/扬声器)。系统提示词/音色/模型/TTS开关真实生效;采样参数透传上游(支持则生效);
- * 参考音频做音色克隆;设备切换真实。图标用 lucide-react。纯展示组件。
+ * Purpose: the full parameters aligned with the MiniCPM-o demo — call (conversation mode/model/voice/system prompt/TTS switch), voice clone (reference-audio upload), advanced (Length Penalty/Max Tokens/Temperature/playback delay), devices (microphone/speaker). System prompt/voice/model/TTS switch actually take effect; sampling parameters are passed through upstream (they take effect when supported); reference audio does voice cloning; device switching is real. Icons use lucide-react. Pure display component.
*/
import { Activity, ChevronDown, RefreshCw, RotateCcw, Upload } from 'lucide-react';
@@ -48,7 +45,7 @@ interface DuplexSidePanelProps {
patch: (p: Partial<DuplexSettings>) => void;
onVoiceChange: (voice: string) => void;
selectLanguage: (language: DuplexLanguage) => void;
- /** 切换对话模式(会话中同步开/关摄像头) */
+ /** Switch conversation mode (open/close the camera in sync during a session) */
onAudioSource: (v: string) => void;
mics: DeviceOption[];
speakers: DeviceOption[];
@@ -61,7 +58,7 @@ interface DuplexSidePanelProps {
}
/**
- * 右侧设置面板。
+ * Right settings panel.
*/
export function DuplexSidePanel(props: DuplexSidePanelProps) {
const { t } = useTranslation('playground');
@@ -114,7 +111,7 @@ export function DuplexSidePanel(props: DuplexSidePanelProps) {
</TabsTrigger>
</TabsList>
- {/* 通话 */}
+ {/* Call */}
<TabsContent forceMount value="call" className={`${TAB_CONTENT_CLASS} flex flex-col gap-4`}>
<fieldset className="flex flex-col gap-1.5">
<legend className="text-xs font-medium text-muted-foreground">
@@ -153,7 +150,7 @@ export function DuplexSidePanel(props: DuplexSidePanelProps) {
</div>
</fieldset>
<Field label={t('selectModel')}>
- {/* 候选来自管理端勾选实时能力的模型;通话中(locked)不允许换模型 */}
+ {/* Candidates come from models the admin console marked with the realtime capability; the model cannot be changed during a call (locked) */}
<SimpleSelect
value={model.realtimeModel?.id ?? ''}
onChange={model.selectRealtimeModel}
@@ -226,7 +223,7 @@ export function DuplexSidePanel(props: DuplexSidePanelProps) {
</label>
</TabsContent>
- {/* 高级 */}
+ {/* Advanced */}
<TabsContent
forceMount
value="advanced"
@@ -387,7 +384,7 @@ export function DuplexSidePanel(props: DuplexSidePanelProps) {
</Button>
</TabsContent>
- {/* 设备 */}
+ {/* Devices */}
<TabsContent
forceMount
value="device"
@@ -555,7 +552,7 @@ function PresetButton({
);
}
-/** 让同组数字字段共享标签、输入框与单位三列。 */
+/** Let number fields in the same group share three columns: label, input, and unit. */
function NumberFieldGroup({ children }: { children: React.ReactNode }) {
return (
<div
@@ -659,7 +656,7 @@ function AudioReferenceField({
);
}
-/** 字段容器 */
+/** Field container */
function Field({ label, children }: { label: string; children: React.ReactNode }) {
return (
<label className="flex flex-col gap-1.5">
@@ -669,7 +666,7 @@ function Field({ label, children }: { label: string; children: React.ReactNode }
);
}
-/** 分段按钮 */
+/** Segmented button */
function SegBtn({
active,
disabled,
@@ -696,7 +693,7 @@ function SegBtn({
);
}
-/** 精简 Select 包装。placeholder 供无候选/未选中时占位(缺省时沿用 Radix 空白态) */
+/** Slim Select wrapper. placeholder is the stand-in when there are no candidates or nothing is selected (when omitted, keep Radix's empty state) */
function SimpleSelect({
value,
onChange,
@@ -722,7 +719,7 @@ function SimpleSelect({
);
}
-/** 滑块字段 */
+/** Slider field */
function RangeField({
label,
value,
@@ -763,7 +760,7 @@ function RangeField({
);
}
-/** 状态行 */
+/** Status row */
function Row({ k, v }: { k: string; v: string }) {
return (
<div className="flex items-center justify-between">
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseBlocksOverlay.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseBlocksOverlay.tsx
index 025b252..f1b7f0d 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseBlocksOverlay.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseBlocksOverlay.tsx
@@ -15,9 +15,9 @@ interface ImageParseBlocksOverlayProps {
}
/**
- * 统一样式的识别框,保留区域定位、阅读顺序与键盘交互,不展示置信度。
- * @param props 原始区域、联动状态与选择回调
- * @returns 与原图共用坐标系的识别框覆盖层
+ * Recognition boxes in one style. Keep region location, reading order, and keyboard interaction, and do not show confidence.
+ * @param props Original regions, linkage state, and selection callback
+ * @returns A recognition-box overlay that shares a coordinate system with the original image
*/
export function ImageParseBlocksOverlay({
blocks,
@@ -33,7 +33,7 @@ export function ImageParseBlocksOverlay({
<div className="pointer-events-none absolute inset-0">
{blocks.flatMap((block, order) => {
const id = imageParseBlockId(block, order);
- // 后端 order 从 0 开始;界面从 1 开始,避免用户把第一个块当成错误。
+ // Backend order starts at 0; the UI starts at 1, so users do not treat the first block as an error.
const readingOrder = (block.order ?? order) + 1;
return imageParseBlockRegions(block).map((region, regionIndex) => {
const selected = id === selectedBlockId;
@@ -69,7 +69,7 @@ export function ImageParseBlocksOverlay({
onSelect(id);
}}
className={cn(
- // 边框独立于尺寸,避免极薄文本框被按钮边框最小高度撑大。
+ // The border is independent of size, so a very thin text box is not stretched by the button border's minimum height.
'pointer-events-auto absolute inset-0 h-full w-full min-h-0 cursor-pointer overflow-visible rounded-sm border-0 bg-transparent p-0 hover:border-primary hover:bg-primary/10 hover:text-primary focus-visible:border-primary focus-visible:bg-primary/10 focus-visible:text-primary focus-visible:ring-2 focus-visible:ring-ring',
'border-border/60 text-muted-foreground after:pointer-events-none after:absolute after:-inset-px after:rounded-[inherit] after:border after:border-[color:inherit]',
(selected || highlighted) &&
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseComparison.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseComparison.tsx
index 9d8e960..5b6a2f9 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseComparison.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseComparison.tsx
@@ -13,8 +13,8 @@ interface ImageParseComparisonProps {
}
/**
- * 单块复核的前后对比:当前最优在左、原始在右,窄屏时最优结果优先展示。
- * @param result 该块的重生成结果(原始、最优、差异与轮次信息)
+ * Before/after comparison for reviewing one block: the current best on the left, the original on the right. On a narrow screen the best result is shown first.
+ * @param result Regeneration result for this block (original, best, diff, and round information)
*/
export function ImageParseComparison({ result }: ImageParseComparisonProps) {
const { t } = useTranslation('playground');
@@ -24,7 +24,7 @@ export function ImageParseComparison({ result }: ImageParseComparisonProps) {
);
return (
<div
- // 未提升时直接展示两版正文,不为隐藏的说明保留空白信息栏。
+ // When there is no improvement, show both bodies directly, and do not reserve a blank info bar for a hidden note.
className="border-t border-border/60"
data-regeneration-comparison
>
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseDisplaySettings.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseDisplaySettings.tsx
index 15052f1..c0290ef 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseDisplaySettings.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseDisplaySettings.tsx
@@ -22,9 +22,9 @@ interface ImageParseDisplaySettingsProps {
}
/**
- * 图片和 PDF 共用的显示设置,收拢识别框、阅读顺序、页眉页脚和双栏联动。
- * @param props 识别框与双栏联动受控状态
- * @returns 支持键盘和触屏的设置菜单
+ * Display settings shared by images and PDFs, gathering recognition boxes, reading order, header/footer, and two-column linkage.
+ * @param props Controlled state for recognition boxes and two-column linkage
+ * @returns A settings menu that supports keyboard and touch
*/
export function ImageParseDisplaySettings({
showBlocks = false,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseDocumentWorkspace.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseDocumentWorkspace.tsx
index ab5bf3d..c6d91c2 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseDocumentWorkspace.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseDocumentWorkspace.tsx
@@ -15,7 +15,7 @@ import { ImageParseDropzone } from './ImageParseDropzone';
import { PaneDivider } from './ImageParsePanes';
import { ImageParseTaskPane } from './ImageParseTaskPane';
-/** 已上传文档后的双栏工作区。 */
+/** Two-column workspace after a document has been uploaded. */
interface ImageParseDocumentWorkspaceProps {
parse: ReturnType<typeof useImageParse>;
split: ReturnType<typeof useSplitPane>;
@@ -51,9 +51,9 @@ interface ImageParseDocumentWorkspaceProps {
}
/**
- * 渲染原件与任务结果的双栏布局,不承担上传或识别状态编排。
- * @param props 当前解析状态、分栏与结果交互回调
- * @returns 文档工作区
+ * Renders the two-column layout of the original and the task result. It does not own upload or recognition-state orchestration.
+ * @param props Current parse state, column split, and result interaction callbacks
+ * @returns Document workspace
*/
export function ImageParseDocumentWorkspace({
parse,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseDownloadMenu.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseDownloadMenu.tsx
index e67b891..d77e16b 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseDownloadMenu.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseDownloadMenu.tsx
@@ -31,9 +31,9 @@ const FORMATS = [
] as const;
/**
- * OCR 下载格式菜单;保留原图标入口,按选择导出当前结果。
- * @param props 禁用状态、生成状态与格式选择回调
- * @returns Markdown、JSON 和 Word 命令菜单
+ * OCR download-format menu; keep the original icon entry and export the current result by the selection.
+ * @param props Disabled state, generation state, and format-selection callback
+ * @returns A command menu for Markdown, JSON, and Word
*/
export function ImageParseDownloadMenu({
disabled,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseDropzone.test.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseDropzone.test.tsx
index 165e323..fa56de0 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseDropzone.test.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseDropzone.test.tsx
@@ -1,5 +1,5 @@
/**
- * 图像解析上传区单测:空态引导、拖拽/粘贴入图、已选图后的看图控制与更换/移除。
+ * Image-parse upload-area unit tests: empty-state guidance, drag/paste an image in, and view controls plus replace/remove after an image is selected.
*/
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
@@ -171,7 +171,7 @@ describe('ImageParseDropzone', () => {
expect(onPreview).toHaveBeenCalledWith('data:image/png;base64,AAA');
expect(screen.queryByRole('button', { name: 'imageParseRemove' })).toBeNull();
- expect(screen.queryByRole('button', { name: 'imageParseReplace' })).toBeNull(); // 底栏更换按钮已移除
+ expect(screen.queryByRole('button', { name: 'imageParseReplace' })).toBeNull(); // The bottom-bar replace button has been removed
});
it('exposes the view controls next to the image', () => {
@@ -184,7 +184,7 @@ describe('ImageParseDropzone', () => {
/>,
);
- // 缩放旋转是核对时的主操作,必须常显而不是悬停才出现。
+ // Zoom and rotation are the main actions while checking, so they must stay visible rather than appear only on hover.
for (const name of [
'imageParseZoomOut',
'imageParseZoomIn',
@@ -212,7 +212,7 @@ describe('ImageParseDropzone', () => {
expect(screen.getByText('125%')).toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'imageParseZoomReset' })).toBeNull();
- // 缩到 25% 后仍能按同一档距回到 100%。
+ // After zooming to 25%, the same step size can still return to 100%.
for (let step = 0; step < 5; step += 1) {
fireEvent.click(screen.getByRole('button', { name: 'imageParseZoomOut' }));
}
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseDropzone.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseDropzone.tsx
index 3058eec..35fb901 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseDropzone.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseDropzone.tsx
@@ -1,10 +1,9 @@
/**
- * 文档解析上传区。
+ * Document-parse upload area.
*
- * 用途:空态对标 mineru-web 上传页——标题、虚线拖放面、限制条目横向排列。
- * 图片使用原图工作台;PDF 按需加载分页预览器,避免增加图片入口的加载成本。
+ * Purpose: the empty state is aligned with the mineru-web upload page — title, dashed drop surface, and limit items in a horizontal row. Images use the original-image workspace; PDFs load a paginated previewer on demand, so the image entry does not pay extra load cost.
*
- * 统一处理文件选择、拖放和页面级粘贴。
+ * File selection, drag-and-drop, and page-level paste are handled in one place.
*/
import { lazy, Suspense, useCallback, useEffect, useState } from 'react';
@@ -29,12 +28,12 @@ interface ImageParseDropzoneProps {
onPick: (file: File) => void;
onClear: () => void;
onPreview: (src: string) => void;
- /** 该图的版面块;空数组表示不画框,只跑扫描 */
+ /** Layout blocks for this image; an empty array means draw no boxes and only run the scan */
blocks?: readonly ImageParseLayoutBlock[];
- /** 服务端旋转摆正信息;仅图片工作台直接消费。 */
+ /** Server rotation-adaptation info; consumed directly only by the image workspace. */
rotation?: ImageParseRotationInfo;
pageBlocks?: Readonly<Record<number, readonly ImageParseLayoutBlock[]>>;
- /** 每一页自己的服务端摆正角度,键是页码。 */
+ /** This page's own server rotation-adaptation angle; the key is the page number. */
pageServerAngles?: Readonly<Record<number, number>>;
progress?: ImageParseProgressSnapshot | null;
parsing?: boolean;
@@ -62,7 +61,7 @@ interface ImageParseDropzoneProps {
const PdfDocumentStage = lazy(() => lazyWithRetry(() => import('./PdfDocumentStage')));
/**
- * 单文档上传与图片、PDF 预览。
+ * Single-document upload and image and PDF preview.
*/
export function ImageParseDropzone({
attachment,
@@ -110,7 +109,7 @@ export function ImageParseDropzone({
[disabled, onPick, t, toast],
);
- // 页面级粘贴:不必先点上传区,从剪贴板直接放入更符合阅读工具习惯。
+ // Page-level paste: no need to click the upload area first. Putting it in straight from the clipboard matches a reading tool better.
useEffect(() => {
function onPaste(event: ClipboardEvent) {
if (disabled) return;
@@ -244,7 +243,7 @@ interface EmptyDropzoneProps {
onDrop: (event: React.DragEvent<HTMLButtonElement>) => void;
}
-/** 空态:mineru 式上传页,限制说明拆成三条,避免一句提示堆在拖放面上。 */
+/** Empty state: a mineru-style upload page. The limit notes are split into three lines so one hint is not piled on the drop surface. */
function EmptyDropzone({
disabled,
previewOnly,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseEditorToolbar.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseEditorToolbar.tsx
index b7588a5..e2be5de 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseEditorToolbar.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseEditorToolbar.tsx
@@ -14,7 +14,7 @@ interface ImageParseEditorToolbarProps {
onSave: () => void;
}
-/** 编辑器工具栏;格式、撤销与单元格操作全部调用 Tiptap 命令。 */
+/** Editor toolbar; formatting, undo, and cell actions all call Tiptap commands. */
export function ImageParseEditorToolbar({
editor,
state,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseExampleGrid.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseExampleGrid.tsx
index 1f2cdc2..3f40f29 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseExampleGrid.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseExampleGrid.tsx
@@ -1,7 +1,7 @@
import { useTranslation } from 'react-i18next';
import { Button } from '@map/ui';
-/** 示例卡片的最小渲染契约;标准解析与 KIE 各自扩展字段。 */
+/** Minimum render contract for an example card; standard parse and KIE each extend the fields. */
export interface ImageParseExampleCard<TType extends string = string> {
id: string;
type: TType;
@@ -12,7 +12,7 @@ export interface ImageParseExampleCard<TType extends string = string> {
pageCount?: number;
}
-/** 示例网格组件属性。 */
+/** Example-grid component props. */
export interface ImageParseExampleGridProps<TType extends string = string> {
titleKey?: string;
examples: readonly ImageParseExampleCard<TType>[];
@@ -21,9 +21,9 @@ export interface ImageParseExampleGridProps<TType extends string = string> {
}
/**
- * 渲染示例文档自适应网格,桌面端 4×2,小屏逐级降列。
- * @param props 示例元数据、禁用状态和选择回调
- * @returns 示例文档网格
+ * Renders an adaptive grid of example documents: 4×2 on desktop, dropping columns step by step on small screens.
+ * @param props Example metadata, disabled state, and selection callback
+ * @returns Example-document grid
*/
export function ImageParseExampleGrid<TType extends string>({
examples,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseExperience.test.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseExperience.test.tsx
index 0643770..0928c65 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseExperience.test.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseExperience.test.tsx
@@ -1,6 +1,5 @@
/**
- * 图像解析体验页单测:空态不展示结果栏;选图后固定对照结果、停止、下载。
- * 另覆盖三件新行为:解析中的分阶段进度、原文页改稿后可还原、区域复制入口不再放在顶栏。
+ * Image-parse experience page unit tests: the empty state does not show the result column; after an image is selected, the comparison result, stop, and download stay fixed. Also covers three new behaviors: staged progress while parsing, restore after editing on the original page, and the region-copy entry no longer living in the top bar.
*/
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
@@ -62,7 +61,7 @@ vi.mock('../../utils/copyText', () => ({
copyText: (text: string) => mocks.copyText(text),
}));
-// 新手引导自带 driver.js 与计时器,页面单测里单独验证,这里整体替换掉。
+// The first-run guide brings driver.js and timers. Page unit tests verify it separately, so it is replaced entirely here.
vi.mock('../../hooks/useImageParseExperienceTour', () => ({
useImageParseExperienceTour: () => ({ replay: vi.fn() }),
}));
@@ -166,7 +165,7 @@ beforeAll(() => {
HTMLElement.prototype.scrollTo = vi.fn();
Range.prototype.getClientRects = () => [] as unknown as DOMRectList;
Range.prototype.getBoundingClientRect = () => new DOMRect();
- // jsdom 不做坐标命中测试,键盘输入沿用当前焦点元素。
+ // jsdom does not hit-test coordinates; keyboard input follows the currently focused element.
document.elementFromPoint = () => document.activeElement;
});
@@ -540,7 +539,7 @@ describe('ImageParseExperience', () => {
expect(document.querySelector('[data-pane="markdown"]')).toHaveAttribute('data-state', 'split');
expect(document.querySelector('[data-pane="origin"]')?.className).not.toMatch(/opacity-/);
expect(document.querySelector('[data-pane="markdown"]')?.className).not.toMatch(/opacity-/);
- // 两个标签页都保持挂载,所以只在当前激活的面板里找结果文本
+ // Both tabs stay mounted, so look for the result text only in the currently active panel
const activePanel = document.querySelector<HTMLElement>(
'[role="tabpanel"][data-state="active"]',
);
@@ -749,7 +748,7 @@ describe('ImageParseExperience', () => {
await waitFor(() =>
expect(screen.getByRole('button', { name: 'imageParseEditorUndo' })).toBeEnabled(),
);
- // 点编辑块以外的区域即失焦保存,草稿随之更新。
+ // Clicking outside the edited block blurs and saves, and the draft updates with it.
fireEvent.pointerDown(screen.getByRole('article'));
expect(screen.getByText('imageParseEdited')).toBeInTheDocument();
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseExperience.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseExperience.tsx
index b533002..869f306 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseExperience.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseExperience.tsx
@@ -1,4 +1,4 @@
-/** 图像解析工作台:上传后自动全文识别,字段提取先配置,原件与结果对照。 */
+/** Image-parse workspace: after upload, run full-text recognition automatically. Field extraction is configured first. The original and the result sit side by side. */
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useToast } from '@map/ui';
@@ -43,7 +43,7 @@ type PlaygroundModel = ReturnType<typeof usePlaygroundModel>;
interface ImageParseExperienceProps {
model: PlaygroundModel;
task?: 'standard' | 'kie';
- /** 侧栏主动进入时新建工作台;直接进入或刷新仍可恢复当前文档。 */
+ /** Entering from the sidebar on purpose starts a new workspace; a direct entry or a refresh can still restore the current document. */
startFresh?: boolean;
showMenuButton?: boolean;
onOpenSidebar?: () => void;
@@ -51,11 +51,11 @@ interface ImageParseExperienceProps {
}
/**
- * 图像解析体验页。
- * @param model 模型与密钥编排
- * @param startFresh 主动进入时跳过当前历史的自动恢复
- * @param showMenuButton 移动端显示侧栏汉堡键
- * @param onOpenSidebar 打开体验中心侧栏
+ * Image-parse experience page.
+ * @param model Model and key orchestration
+ * @param startFresh On a purposeful entry, skip automatic restore of the current history
+ * @param showMenuButton On mobile, show the sidebar hamburger
+ * @param onOpenSidebar Open the experience-center sidebar
*/
export function ImageParseExperience({
model,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseFormulaSource.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseFormulaSource.tsx
index 9bf9f56..a0f2368 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseFormulaSource.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseFormulaSource.tsx
@@ -15,7 +15,7 @@ interface ImageParseFormulaSourceProps {
onComposing: (value: boolean) => void;
}
-/** 编辑所选数学节点的 LaTeX;沿用原节点事务,不新增第二份公式或插入 HTML。 */
+/** Edit the LaTeX of the selected math node; reuse the original node transaction, and do not add a second formula or insert HTML. */
export function ImageParseFormulaSource({
latex,
display,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseImageLinkage.test.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseImageLinkage.test.tsx
index 4298270..9ad045b 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseImageLinkage.test.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseImageLinkage.test.tsx
@@ -44,7 +44,7 @@ const ranges = imageParseBlockRanges(result.markdown, result.blocks);
const linkedRanges = [...ranges].map(([id, range]) => ({ id, range }));
const crops = ['data:image/png;base64,AA=='];
-/** 复用原图选择与结果定位链路,覆盖图片和连续 PDF 的真实图片映射。 */
+/** Reuse the original-image selection and result-location path, covering the real image mapping for images and continuous PDFs. */
function ImageLinkageWorkspace({
pdf,
onFocus,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseInspectionControls.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseInspectionControls.tsx
index 4a79893..0b5ef29 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseInspectionControls.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseInspectionControls.tsx
@@ -12,7 +12,7 @@ interface ImageParseInspectionControlsProps {
compact?: boolean;
}
-/** 工作台识别框开关;只根据区块坐标提供原文定位。 */
+/** Workspace recognition-box switch; provide original-text location only from block coordinates. */
export function ImageParseInspectionControls({
parse,
uploading,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseKieFields.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseKieFields.tsx
index 6c97076..441271f 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseKieFields.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseKieFields.tsx
@@ -20,8 +20,7 @@ interface ImageParseKieFieldsProps {
}
/**
- * 关键信息抽取字段区。列表下方添加字段,选择模式支持批量删除;
- * 字段在进入请求前会再次由 API 层和后端校验。
+ * Key information extraction field area. Add fields under the list; selection mode supports batch delete. Fields are validated again by the API layer and the backend before they enter a request.
*/
export function ImageParseKieFields({
fields,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseKiePdfPreview.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseKiePdfPreview.tsx
index 984cd3e..ac9a73b 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseKiePdfPreview.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseKiePdfPreview.tsx
@@ -14,10 +14,9 @@ interface ImageParseKiePdfPreviewProps {
}
/**
- * KIE 的 PDF 结果按当前页展示,避免把多页 JSON 连续铺在同一栏。
- * 抽取进行中复用文档解析的页面等待态,完成后再展示当前页字段。
- * @param parse 当前识别状态
- * @param draft 当前页可编辑草稿
+ * KIE PDF results are shown for the current page, so multi-page JSON is not laid out continuously in the same column. While extraction is in progress, reuse the document-parse page waiting state, and show the current page's fields after it finishes.
+ * @param parse Current recognition state
+ * @param draft Editable draft for the current page
*/
export function ImageParseKiePdfPreview({ parse, draft }: ImageParseKiePdfPreviewProps) {
const { t } = useTranslation('playground');
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseKieResultCommands.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseKieResultCommands.tsx
index cb30ac5..664ac8f 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseKieResultCommands.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseKieResultCommands.tsx
@@ -14,9 +14,9 @@ interface ImageParseKieResultCommandsProps {
}
/**
- * 集中展示字段命中统计、修改字段与 JSON 复制,供结果工具栏及失败状态复用。
- * @param props 当前结果、请求字段与编辑入口
- * @returns 随窄栏换行的统计和图标操作
+ * Gather field-hit stats, field edits, and JSON copy in one place, for reuse by the result toolbar and the failure state.
+ * @param props Current result, requested fields, and edit entry
+ * @returns Stats and icon actions that wrap with a narrow column
*/
export function ImageParseKieResultCommands({
content,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseKieSetupPane.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseKieSetupPane.tsx
index 3393182..e61ac69 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseKieSetupPane.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseKieSetupPane.tsx
@@ -30,10 +30,9 @@ interface ImageParseKieSetupPaneProps {
}
/**
- * 信息抽取的字段配置面板。配置阶段复用结果栏空间,左侧保留原图,
- * 让用户能一边查看图片一边决定需要抽取的信息。
- * @param props 字段状态、开始/返回回调与禁用原因
- * @returns 右侧字段配置工作区
+ * Field-configuration panel for key information extraction. The configuration phase reuses the result-column space and keeps the original image on the left, so the user can look at the image while deciding what to extract.
+ * @param props Field state, start/back callbacks, and the disable reason
+ * @returns Field-configuration workspace on the right
*/
export function ImageParseKieSetupPane({
fields,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseKieSummary.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseKieSummary.tsx
index 94d31a5..c089922 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseKieSummary.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseKieSummary.tsx
@@ -5,14 +5,14 @@ import { imageParseKieRows, imageParseKieValues } from '../../utils/imageParseKi
interface ImageParseKieSummaryProps {
content: string;
- /** 请求时提交的字段顺序;模型漏掉的字段也会以“未找到”展示。 */
+ /** Field order submitted with the request; fields the model missed are still shown as "not found." */
fields?: readonly string[];
}
/**
- * 将模型返回的 JSON 对象按字段展开为结果表;非 JSON 时不渲染摘要,仅保留原文展示。
- * @param content 模型返回的原始文本或 Markdown 草稿
- * @param fields 用户请求的字段列表
+ * Expand the JSON object returned by the model into a result table by field; when it is not JSON, do not render a summary and keep only the original text.
+ * @param content Raw text or Markdown draft returned by the model
+ * @param fields Field list the user requested
*/
export function ImageParseKieSummary({ content, fields = [] }: ImageParseKieSummaryProps) {
const { t } = useTranslation('playground');
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseKieUpload.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseKieUpload.tsx
index fdd2d09..951a62d 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseKieUpload.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseKieUpload.tsx
@@ -20,9 +20,9 @@ interface ImageParseKieUploadProps {
}
/**
- * 信息抽取上传入口,布局与文档解析空态一致,并允许选择真实票据案例。
- * @param props 文件、案例选择回调与任务禁用状态
- * @returns 上传区域和可选择的内置案例
+ * Upload entry for key information extraction. The layout matches the document-parse empty state, and real receipt examples can be selected.
+ * @param props File and example selection callbacks, and the task disabled state
+ * @returns Upload area and selectable built-in examples
*/
export function ImageParseKieUpload({
onPick,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseMarkdownBlock.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseMarkdownBlock.tsx
index 02d2943..47e2cbf 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseMarkdownBlock.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseMarkdownBlock.tsx
@@ -3,7 +3,7 @@ import type { ExtraProps } from 'react-markdown';
import { ImageParseBlockEditContext } from '../../utils/imageParseBlockEditContext';
-/** 可信块标记转为可编辑预览;普通 HTML div 继续沿用原有属性和内容。 */
+/** A trusted block marker becomes an editable preview; an ordinary HTML div keeps its original attributes and content. */
export function ImageParseMarkdownBlock({
node,
children,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseMathNodeView.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseMathNodeView.tsx
index 8dd4ab1..d9ba3e9 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseMathNodeView.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseMathNodeView.tsx
@@ -8,7 +8,7 @@ import { cn } from '@map/ui';
import { useImageParseFormulaNode } from '../../hooks/useImageParseFormulaNode';
import { ImageParseFormulaSource } from './ImageParseFormulaSource';
-/** 公式保持可复制的 KaTeX DOM;输入框直接替换当前节点,不使用图片或独立编辑面板。 */
+/** Formulas stay as copyable KaTeX DOM; the input replaces the current node directly, with no image or separate edit panel. */
export function ImageParseMathNodeView(props: NodeViewProps) {
const { t } = useTranslation('playground');
const formula = useImageParseFormulaNode(props);
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseOptionInfo.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseOptionInfo.tsx
index 03f7599..e838eed 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseOptionInfo.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseOptionInfo.tsx
@@ -8,9 +8,9 @@ interface ImageParseOptionInfoProps {
}
/**
- * 展示解析选项的功能说明;悬停或键盘聚焦时出现,不占用常驻空间。
- * @param props 选项名称与说明文案
- * @returns 支持悬停和键盘聚焦的 info 按钮
+ * Show what a parse option does; it appears on hover or keyboard focus and does not take permanent space.
+ * @param props Option name and description copy
+ * @returns An info button that supports hover and keyboard focus
*/
export function ImageParseOptionInfo({ label, hint }: ImageParseOptionInfoProps) {
const { t } = useTranslation('playground');
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseOrderToggle.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseOrderToggle.tsx
index c019f61..2cb3940 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseOrderToggle.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseOrderToggle.tsx
@@ -5,8 +5,7 @@ import { useAppStore } from '@map/store';
import { WORKSPACE_CONTROL } from '../../utils/imageParseWorkspaceStyles';
/**
- * 版面框上的阅读顺序序号开关;偏好持久化,单图与 PDF 共用。
- * 识别框隐藏时序号也看不到,按钮随之禁用。
+ * Reading-order number switch on layout boxes; the preference is persisted and shared by single images and PDFs. When recognition boxes are hidden the numbers cannot be seen either, and the button is disabled with them.
*/
export function ImageParseOrderToggle({ disabled }: { disabled?: boolean }) {
const { t } = useTranslation('playground');
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePageRail.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePageRail.tsx
index 7a9c3c5..7f6fbb6 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePageRail.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePageRail.tsx
@@ -5,7 +5,7 @@ import { Button, cn } from '@map/ui';
import { DOCUMENT_ACCEPT } from '../../utils/documentUpload';
-/** 原件页导航项;预览由图片或 PDF 阅读器提供。 */
+/** Original-page navigation item; the preview is provided by the image or PDF reader. */
export interface ImageParsePageItem {
pageNumber: number;
preview: ReactNode;
@@ -21,9 +21,9 @@ interface ImageParsePageRailProps {
}
/**
- * 原件页面缩略图列表;桌面纵向排列,窄屏使用独立滚动的横向页带。
- * @param props 页面预览、当前页及切页和追加回调
- * @returns 页面导航与列表末尾的添加入口
+ * Thumbnail list of original pages; stacked vertically on desktop, and a separately scrolling horizontal page strip on a narrow screen.
+ * @param props Page previews, the current page, and page-change and append callbacks
+ * @returns Page navigation and the add entry at the end of the list
*/
export function ImageParsePageRail({
pages,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePanes.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePanes.tsx
index 05ee66a..2140fdc 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePanes.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePanes.tsx
@@ -3,9 +3,9 @@ import { cn } from '@map/ui';
import type { SplitPane } from '../../hooks/useSplitPane';
/**
- * 分栏分隔条。窄屏是上下布局,没有横向分栏可拖,所以整条隐藏。
+ * Column-split handle. A narrow screen is a top-bottom layout and has no horizontal split to drag, so the whole handle is hidden.
*
- * 仅在交互时显示居中短提示,不贯穿顶部工具栏;透明抓取区不增加布局宽度。
+ * Show a short centered hint only while interacting, and do not run it through the top toolbar; the transparent grab area does not add layout width.
*/
export function PaneDivider({ split }: { split: SplitPane }) {
const { t } = useTranslation('playground');
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePdfHighlight.test.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePdfHighlight.test.tsx
index 12af6bc..0204c65 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePdfHighlight.test.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePdfHighlight.test.tsx
@@ -39,7 +39,7 @@ const result = adaptImageParseV2({
const ranges = imageParseBlockRanges(result.markdown, result.blocks);
const linkedRanges = [...ranges].map(([id, range]) => ({ id, range }));
-/** 复用工作台悬停状态链路,覆盖真实服务响应到原图框的双向映射。 */
+/** Reuse the workspace hover-state path, covering the two-way mapping from a real service response to original-image boxes. */
function PdfHoverWorkspace() {
const [hoveredId, setHoveredId] = useState<string>();
const parse = {
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePdfPreview.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePdfPreview.tsx
index cc94ed7..0c8734f 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePdfPreview.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePdfPreview.tsx
@@ -21,7 +21,7 @@ interface ImageParsePdfPreviewProps {
recognizeChart: boolean;
}
-/** PDF 全页连续预览;未返回页保留等待锚点,离屏结果仅按虚拟列表挂载。 */
+/** Continuous full-page PDF preview; pages not yet returned keep a waiting anchor, and off-screen results mount only through the virtual list. */
export function ImageParsePdfPreview({
parse,
draft,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePdfResultPage.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePdfResultPage.tsx
index dc38eef..0e5d68b 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePdfResultPage.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePdfResultPage.tsx
@@ -40,7 +40,7 @@ interface ImageParsePdfResultPageProps {
onEditingChange: (page: number, value: boolean) => void;
}
-/** 单页结果的高亮和编辑严格限制在本页,避免跨页重复 ID 命中。 */
+/** Highlight and edit for a single-page result stay strictly on this page, so a duplicate id across pages is not hit. */
export const ImageParsePdfResultPage = memo(function ImageParsePdfResultPage({
page,
resultKey,
@@ -193,7 +193,7 @@ interface ImageParsePdfPendingPageProps {
onRetry: (page: number) => void;
}
-/** 未完成页只保留页码锚点;只有当前页展示加载状态和整体进度。 */
+/** An unfinished page keeps only a page-number anchor; only the current page shows the loading state and overall progress. */
export function ImageParsePdfPendingPage({
page,
completed,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePreservedSource.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePreservedSource.tsx
index 12e02f0..75a0e91 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePreservedSource.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePreservedSource.tsx
@@ -4,8 +4,8 @@ import { useTranslation } from 'react-i18next';
import { MarkdownRenderer } from '../MarkdownRenderer';
/**
- * 展示无法可靠转换的原始文档块;只读保留,避免保存其它内容时丢失。
- * @param node 仅含原始源码的 schema 节点
+ * Show an original document block that cannot be converted reliably; keep it read-only so it is not lost when other content is saved.
+ * @param node Schema node that contains only the original source
*/
export function ImageParsePreservedSource({ node }: NodeViewProps) {
const { t } = useTranslation('playground');
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePreviewReview.test.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePreviewReview.test.tsx
index 0552d2f..4863384 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePreviewReview.test.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePreviewReview.test.tsx
@@ -387,7 +387,7 @@ describe('结果预览单块复核', () => {
expect(regeneration.regenerateBlock).not.toHaveBeenCalled();
rerender(<ImageParseResultPane {...props} />);
const wrapper = container.querySelector('[data-edit-block]')!;
- // 模拟编辑器挂载与卸载,不在此测试中加载第三方编辑器。
+ // Simulate editor mount and unmount; do not load the third-party editor in this test.
wrapper.setAttribute('data-visual-editing', 'true');
await waitFor(() =>
expect(screen.queryByRole('button', { name: 'imageParseRegenerateBlock' })).toBeNull(),
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePreviewReview.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePreviewReview.tsx
index 1078835..b3df610 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePreviewReview.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParsePreviewReview.tsx
@@ -21,18 +21,18 @@ interface ImageParsePreviewReviewProps {
onCopyRegion?: (id: string) => void;
}
-/** 操作条与选中块底边的间距,保持悬浮在块外。 */
+/** Gap between the action bar and the bottom edge of the selected block, so it floats outside the block. */
const PREVIEW_ACTION_GAP = 6;
-/** 操作条按钮沿用工作台控件尺寸,桌面保持紧凑,粗指针设备保留点击热区。 */
+/** Action-bar buttons reuse the workspace control size: compact on desktop, and a click target kept on coarse-pointer devices. */
const PREVIEW_ACTION_BUTTON_CLASS =
'h-7 min-h-7 gap-1.5 rounded-full px-2.5 text-xs [@media(pointer:coarse)]:h-9 [@media(pointer:coarse)]:min-h-9';
-/** 选中块左上角的类型角标,跟随块边界定位。 */
+/** Type badge at the top left of the selected block, positioned along the block bounds. */
const PREVIEW_ACTION_LABEL_CLASS =
'pointer-events-none absolute z-20 -translate-y-full rounded-t-sm bg-ocr-link px-1.5 py-0 text-[10px] font-medium leading-4 text-primary-foreground';
-/** 选中块右下角展示操作条;悬停不展示,复核能力隐藏时仅保留区域复制。 */
+/** Show the action bar at the bottom right of the selected block; do not show it on hover. When review is hidden, keep only region copy. */
export function ImageParsePreviewReview({
root,
selectedId,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseProgressPanel.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseProgressPanel.tsx
index 16a741b..fd86a3c 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseProgressPanel.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseProgressPanel.tsx
@@ -1,8 +1,7 @@
/**
- * 解析进度面板。
+ * Parse progress panel.
*
- * 用途:解析等待视图。共享案例使用前端固定演示进度;真实服务未提供进度时保持 indeterminate。
- * 服务端将来返回真实进度时,同一组件可直接展示确定性进度。
+ * Purpose: the waiting view while parsing. Shared examples use a fixed demo progress on the frontend; when the real service does not provide progress, stay indeterminate. When the server later returns real progress, the same component can show determinate progress directly.
*/
import { useTranslation } from 'react-i18next';
@@ -15,8 +14,8 @@ interface ImageParseProgressPanelProps {
}
/**
- * 解析中的极简进度视图。
- * @param progress 当前进度快照
+ * Minimal progress view while parsing.
+ * @param progress Current progress snapshot
*/
export function ImageParseProgressPanel({ progress }: ImageParseProgressPanelProps) {
const { t } = useTranslation('playground');
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseReadingOrder.test.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseReadingOrder.test.tsx
index fe5dc3a..66fecfd 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseReadingOrder.test.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseReadingOrder.test.tsx
@@ -33,7 +33,7 @@ function block(
const blocks = [
block(0, 'header'),
block(1, 'text'),
- // 跨栏合并块有两个区域:序号只标一次
+ // A cross-column merged block has two regions: the number is marked only once
block(2, 'table', {
regions: [
{ x: 0.1, y: 0.3, w: 0.3, h: 0.1 },
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseReadyPane.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseReadyPane.tsx
index 5f6733e..dbc484d 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseReadyPane.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseReadyPane.tsx
@@ -16,9 +16,9 @@ interface ImageParseReadyPaneProps {
}
/**
- * 上传完成但尚未调用模型时的操作区;PDF 字段提取提供明确的恢复动作。
- * @param props 文件能力、开始识别和任务恢复入口
- * @returns 当前文件对应的待执行面板
+ * Action area after upload finishes but before the model is called; PDF field extraction provides a clear resume action.
+ * @param props File capabilities, start-recognition, and task-resume entries
+ * @returns The pending panel for the current file
*/
export function ImageParseReadyPane({
unsupported = false,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseRecognitionSettings.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseRecognitionSettings.tsx
index 25e9f50..f67eb2b 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseRecognitionSettings.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseRecognitionSettings.tsx
@@ -26,9 +26,9 @@ interface ImageParseRecognitionSettingsProps {
}
/**
- * 收拢影响下一次全文识别的选项,不与原件显示设置混用。
- * @param props 摆正、印章与图表展示受控状态、请求期间禁用标记
- * @returns 支持键盘和触屏的识别设置菜单
+ * Gather the options that affect the next full-text recognition, and do not mix them with original-display settings.
+ * @param props Controlled state for rotation adaptation, seal, and chart display, and the disabled flag while a request is in flight
+ * @returns A recognition-settings menu that supports keyboard and touch
*/
export function ImageParseRecognitionSettings({
upright,
@@ -95,9 +95,9 @@ interface RecognitionSettingItemProps {
}
/**
- * 渲染带说明 Tooltip 和受控 Switch 的识别设置项。
- * @param props 设置项文案、当前状态与切换回调
- * @returns 菜单中的识别设置行
+ * Renders a recognition-settings item with a descriptive Tooltip and a controlled Switch.
+ * @param props Setting copy, current state, and toggle callback
+ * @returns A recognition-settings row in the menu
*/
function RecognitionSettingItem({
dataTour,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseResultActions.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseResultActions.tsx
index 1166704..b186a81 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseResultActions.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseResultActions.tsx
@@ -10,9 +10,7 @@ interface ImageParseResultActionsProps {
}
/**
- * 结果导出操作:只负责下载,不包含视图切换入口。
- * 一键复制正文的格式无法保证(Markdown 源码粘到哪里都不是文档),
- * 结果文本统一走下载,区域复制放在选中块的就近操作处。
+ * Result export actions: download only, with no view-switch entry. One-click copy of the body cannot guarantee a format (Markdown source pasted anywhere is not a document). Result text goes through download, and region copy lives on the nearby actions of the selected block.
*/
export function ImageParseResultActions({
loading,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseResultError.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseResultError.tsx
index b01da69..f845563 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseResultError.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseResultError.tsx
@@ -9,9 +9,9 @@ interface ImageParseResultErrorProps {
}
/**
- * 识别错误与唯一重试入口;PDF 单页错误仍由相应结果页负责。
- * @param props 可见错误、重试状态及回调
- * @returns 可恢复的内联错误条
+ * Recognition error and the only retry entry; a single-page PDF error is still owned by the matching result page.
+ * @param props Visible error, retry state, and callbacks
+ * @returns A recoverable inline error bar
*/
export function ImageParseResultError({ message, disabled, onRetry }: ImageParseResultErrorProps) {
const { t } = useTranslation('playground');
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseResultPane.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseResultPane.tsx
index 74c6a12..add7699 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseResultPane.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseResultPane.tsx
@@ -1,4 +1,4 @@
-/** 图像解析结果栏:切视图时保持正文挂载,避免重复解析。 */
+/** Image-parse result column: keep the body mounted when switching views, so it is not parsed again. */
import { useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -39,13 +39,13 @@ import {
type ImageParseState = ReturnType<typeof useImageParse>;
-/** 面板切换保持挂载;不要在每次展开时从透明度 0 重播入场动画。 */
+/** Keep mounted across panel switches; do not replay the entrance animation from opacity 0 on every expand. */
const TAB_CONTENT_CLASS = 'mt-0 min-h-0 flex-1 overflow-auto bg-card data-[state=inactive]:hidden';
-/** 三页共用的内容留白。底部多留一截,滚到末尾时最后一行不会贴着栏底。 */
+/** Content padding shared by the three pages. Leave extra at the bottom so the last line does not sit against the column edge when scrolled to the end. */
const PAGE_PADDING = 'px-4 pb-12 pt-4 sm:px-6';
-/** 内容列限宽居中,避免全宽模式下行长影响阅读。 */
+/** The content column is width-limited and centered, so line length does not hurt reading in full-width mode. */
const CONTENT_COLUMN = 'mx-auto w-full max-w-5xl';
interface ImageParseResultPaneProps {
@@ -59,7 +59,7 @@ interface ImageParseResultPaneProps {
previewLinkedRanges?: readonly ImageParseLinkedRange[];
previewCrops?: readonly string[];
previewOnly?: boolean;
- /** 复制当前选中区域;表格由上层按 HTML + TSV 处理 */
+ /** Copy the currently selected region; tables are handled by the parent as HTML + TSV */
onCopyRegion?: (id: string) => void;
selectedBlockId?: string;
hoveredBlockId?: string;
@@ -68,7 +68,7 @@ interface ImageParseResultPaneProps {
selectedRange?: ImageParseTextRange;
linkedRanges?: readonly ImageParseLinkedRange[];
tab?: string;
- /** 临时开关:是否展示待复核页。 */
+ /** Temporary switch: whether to show the pending-review page. */
reviewEnabled?: boolean;
onTabChange?: (tab: string) => void;
onSelectBlock?: (id: string, page?: number) => void;
@@ -76,7 +76,7 @@ interface ImageParseResultPaneProps {
onToggleLinked?: () => void;
showBlocks?: boolean;
onToggleBlocks?: () => void;
- /** 多页示例的跨页表格合并;PDF 多页时用 parse.pdf.tableMerge。 */
+ /** Cross-page table merge for multi-page examples; for a multi-page PDF use parse.pdf.tableMerge. */
exampleTableMerge?: ReturnType<typeof useImageParseExampleMerge>;
regeneration?: ReturnType<typeof useImageParseRegeneration>;
downloading?: boolean;
@@ -89,10 +89,10 @@ interface ImageParseResultPaneProps {
}
/**
- * Markdown 结果栏。
- * @param parse 图像解析编排状态
- * @param draft 可编辑草稿
- * @param onCopyRegion 复制当前选中区域
+ * Markdown result column.
+ * @param parse Image-parse orchestration state
+ * @param draft Editable draft
+ * @param onCopyRegion Copy the currently selected region
*/
export function ImageParseResultPane({
parse,
@@ -162,14 +162,14 @@ export function ImageParseResultPane({
);
const algorithmMode = parse.mode === 'standard' || isImageParsePipelineMode(parse.mode);
const showReview = reviewEnabled && !algorithmMode;
- // 页数说明原文已打开;未完成页保留占位,避免用户误以为结果栏无响应。
+ // The page-count note says the original is already open; unfinished pages keep a placeholder so users do not think the result column is unresponsive.
const continuousPdf = Boolean(parse.pdf?.pages);
- // 印章识别允许空正文;只要返回了真实区块,也应展示结果而不是空态。
+ // Seal recognition allows an empty body; as long as real blocks came back, show the result rather than the empty state.
const hasPreview = Boolean(shownMarkdown || continuousPdf || shownLayout.length > 0);
const hasStableResult = !loading && (parse.finished || Boolean(parse.pdf?.completed));
const [localTab, setLocalTab] = useState('preview');
const requestedTab = tab ?? localTab;
- // 待复核能力临时隐藏;外部恢复旧视图时回落到预览,避免停留在不可见内容。
+ // Pending review is temporarily hidden; when the outside restores an old view, fall back to preview so it does not stay on invisible content.
const activeTab = showReview || requestedTab !== 'review' ? requestedTab : 'preview';
const review = useImageParseReview(parse.resultKey);
const previewRef = useRef<HTMLElement>(null);
@@ -193,7 +193,7 @@ export function ImageParseResultPane({
);
let emptyDescription = 'imageParseEmptyHint';
if (previewOnly) emptyDescription = 'imageParseLocalResultHint';
- // 成功复核即完成待办,不要求提分;失败仍保留待办,分数与对比列表不受影响。
+ // A successful review completes the to-do and does not require a higher score; a failure keeps the to-do, and scores and the comparison list are unaffected.
const reviewCount = computedQuality.suggested.filter((item) => {
const result = regeneration?.results[item.id];
return !result || Boolean(result.error);
@@ -238,7 +238,7 @@ export function ImageParseResultPane({
{parse.mode === 'kie' ? (
<ImageParseKieSummary content={draft.value} fields={parse.fields} />
) : null}
- {/* KIE 成功解析后只展示结果表,避免同一份 JSON 再以正文重复渲染。 */}
+ {/* After KIE parses successfully, show only the result table, so the same JSON is not rendered again as body text. */}
{parse.mode === 'kie' && kieValues ? null : (
<ImageParseVisualEditor
key={`${parse.resultKey}:${loading}`}
@@ -269,7 +269,7 @@ export function ImageParseResultPane({
);
}
- // 切标签时保留正文挂载和纯色背景,避免内容先透明再出现。
+ // When switching tabs, keep the body mounted and the solid background, so the content does not go transparent and then appear.
return (
<section
ref={resultPaneRef}
@@ -352,7 +352,7 @@ export function ImageParseResultPane({
onScroll={onPreviewScroll}
className={`${TAB_CONTENT_CLASS} ${PAGE_PADDING}`}
>
- {/* 正文与顶栏同底色,只靠限宽和留白成版,不再套卡片吃掉边距 */}
+ {/* The body and the top bar share a background color. The page is made by the width limit and whitespace only, and a card is no longer wrapped around it to eat the margin */}
<article
ref={continuousPdf ? undefined : previewRef}
className={cn(
@@ -476,7 +476,7 @@ export function ImageParseResultPane({
);
}
-/** 文档节点上的直接定位入口;链接和表单控件沿用自身交互。 */
+/** Direct location entry on a document node; links and form controls keep their own interaction. */
function linkedBlockId(target: EventTarget | null): string | undefined {
if (!(target instanceof HTMLElement) || target.closest('a, button, input, textarea, select')) {
return undefined;
@@ -484,7 +484,7 @@ function linkedBlockId(target: EventTarget | null): string | undefined {
return target.closest<HTMLElement>('[data-ocr-block-id]')?.dataset.ocrBlockId;
}
-/** 点击的结果页提供页级定位上下文;图片预览保持原有单参数事件。 */
+/** The clicked result page provides page-level location context; the image preview keeps the original single-argument event. */
function linkedPage(target: EventTarget | null): number | undefined {
if (!(target instanceof HTMLElement)) return undefined;
const value = target.closest<HTMLElement>('[data-ocr-result-page]')?.dataset.ocrResultPage;
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseResultPaneReview.test.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseResultPaneReview.test.tsx
index d11604c..15c6201 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseResultPaneReview.test.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseResultPaneReview.test.tsx
@@ -37,7 +37,7 @@ const props = {
setValue: vi.fn(),
reset: vi.fn(),
},
- // 保留待复核实现的单测开关;生产默认隐藏。
+ // Keep the unit-test switch for the pending-review implementation; hidden by default in production.
reviewEnabled: true,
};
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseResultToolbar.test.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseResultToolbar.test.tsx
index dfbc80c..f28ab39 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseResultToolbar.test.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseResultToolbar.test.tsx
@@ -49,7 +49,7 @@ const props = {
recognizeSeal: true,
onRecognizeSealChange: vi.fn(),
hasScoredBlocks: true,
- // 保留待复核实现的单测开关;生产默认隐藏。
+ // Keep the unit-test switch for the pending-review implementation; hidden by default in production.
reviewEnabled: true,
reviewAll: false,
onToggleReviewAll: vi.fn(),
@@ -290,7 +290,7 @@ describe('OCR 结果工具栏', () => {
expect(screen.queryByRole('button', { name: hidden })).toBeNull();
}
- // 批量重生成期间不再额外展示顶部命令行。
+ // During batch regeneration, do not also show a command row at the top.
view.rerender(
<Tabs value="review" onValueChange={() => undefined}>
<ImageParseResultToolbar
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseResultToolbar.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseResultToolbar.tsx
index 7bebe6c..103bca0 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseResultToolbar.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseResultToolbar.tsx
@@ -55,23 +55,23 @@ interface ImageParseResultToolbarProps {
regeneration?: ReturnType<typeof useImageParseRegeneration>;
downloading?: boolean;
onDownload?: (format: ImageParseDownloadFormat) => void;
- /** 当前视图;待复核页展示筛选与重生成,不展示联动与导出。 */
+ /** Current view; the pending-review page shows filters and regeneration, and does not show linkage or export. */
activeTab?: string;
- /** 信息抽取等非 Markdown 结果的自定义页签文案。 */
+ /** Custom tab copy for non-Markdown results such as key information extraction. */
previewLabel?: string;
sourceLabel?: string;
- /** 文档类结果才展示表格合并、页眉页脚和双栏联动。 */
+ /** Table merge, header/footer, and two-column linkage are shown only for document results. */
documentCommands?: boolean;
- /** 只有已有且稳定的识别结果才展示统一设置入口。 */
+ /** Show the unified settings entry only when there is already a stable recognition result. */
settingsVisible?: boolean;
- /** 当前任务的统计和操作,与视图切换共用一条工具栏。 */
+ /** Stats and actions for the current task, sharing one toolbar with the view switch. */
resultCommands?: ReactNode;
- /** 临时开关:是否展示待复核页。 */
+ /** Temporary switch: whether to show the pending-review page. */
reviewEnabled?: boolean;
hasScoredBlocks?: boolean;
reviewAll?: boolean;
onToggleReviewAll?: () => void;
- /** 多页 PDF 或多页示例才有:跨页表格合并 */
+ /** Only a multi-page PDF or a multi-page example has this: cross-page table merge */
tableMerge?:
| ReturnType<typeof usePdfImageParse>['tableMerge']
| ReturnType<typeof useImageParseExampleMerge>
@@ -79,8 +79,7 @@ interface ImageParseResultToolbarProps {
}
/**
- * 结果栏工具区:左侧切换视图,当前视图的操作集中在右侧。
- * 待复核显示筛选与批量重生成;窄栏自动换行,不挤压标签和操作。
+ * Result-column tool area: switch views on the left, and gather the current view's actions on the right. Pending review shows filters and batch regeneration; a narrow column wraps automatically and does not squeeze labels and actions.
*/
export function ImageParseResultToolbar({
loading,
@@ -128,7 +127,7 @@ export function ImageParseResultToolbar({
<TabsTrigger value="source" className={TRIGGER_CLASS}>
{sourceLabel ?? t('imageParseSource')}
</TabsTrigger>
- {/* 编辑说明跟随源码标签,悬停图标展示,不再占用右侧操作区。 */}
+ {/* The edit note follows the source tab and is shown on icon hover, so it no longer takes the action area on the right. */}
{documentCommands && !reviewOnly ? (
<ImageParseOptionInfo
label={t('imageParseInlineEditor')}
@@ -269,7 +268,7 @@ export function ImageParseResultToolbar({
);
}
-/** 跨页表格合并:带文字的按钮,合并中显示进度,完成后可撤销,结果用 toast 告知。 */
+/** Cross-page table merge: a button with text, progress while merging, undo after it finishes, and the result reported with a toast. */
function ImageParseTableMergeButton({
tableMerge,
}: {
@@ -345,7 +344,7 @@ function ImageParseTableMergeButton({
<Tooltip>
<TooltipTrigger asChild>
{disabled ? (
- // 原生禁用按钮不接收指针与焦点,用外层承接提示,按钮仍保持不可执行。
+ // A natively disabled button does not receive pointer or focus. The outer layer carries the hint, and the button stays non-executable.
<span
tabIndex={0}
className="inline-flex rounded-md focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/30"
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseReviewPane.test.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseReviewPane.test.tsx
index 6cffa8f..4e83898 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseReviewPane.test.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseReviewPane.test.tsx
@@ -345,7 +345,7 @@ describe('块复核列表边界', () => {
expect(collapse).toHaveAttribute('aria-expanded', 'true');
fireEvent.click(collapse);
expect(container.querySelector('[data-regeneration-comparison]')).toBeNull();
- // 收起只影响对比,卡头与分数仍留在列表里。
+ // Collapse affects only the comparison; the card header and score stay in the list.
expect(container.querySelector('[data-review-block-id="low"]')).not.toBeNull();
const expand = screen.getByRole('button', { name: 'imageParseComparisonExpand' });
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseReviewPane.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseReviewPane.tsx
index 35160a2..8a4ca4a 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseReviewPane.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseReviewPane.tsx
@@ -28,7 +28,7 @@ interface ImageParseReviewPaneProps {
onLoadMore: () => void;
}
-/** 待复核条目沿用标准卡片;重生成后在同一卡片内展示两版对比,不重复展开原文。 */
+/** Pending-review items reuse the standard card; after regeneration, show the two-version comparison inside the same card and do not expand the original again. */
export function ImageParseReviewPane({
quality,
dirty,
@@ -47,9 +47,9 @@ export function ImageParseReviewPane({
onLoadMore,
}: ImageParseReviewPaneProps) {
const { t } = useTranslation('playground');
- /** 复核后的对比默认展开;只记录被收起的块,切换结果时随组件 key 一起重置。 */
+ /** The comparison after review is expanded by default; only record blocks that were collapsed, and reset them with the component key when the result changes. */
const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(new Set());
- // 已优化至高分的块仍保留对比条目,不因离开待审核集合而隐藏优化结果。
+ // Blocks already optimized to a high score still keep a comparison entry, and the optimized result is not hidden just because they left the pending-review set.
const items = all
? quality.scored
: quality.scored.filter((item) => item.suggested || results[item.id]);
@@ -95,7 +95,7 @@ export function ImageParseReviewPane({
<div className="space-y-4">
{items.slice(0, limit).map((item) => {
const selected = selectedBlockId === item.id;
- // 只有图片/印章这类无可读文字的块清洗后会为空,此时不占一行空白。
+ // Only blocks with no readable text, such as images or seals, are empty after cleaning, and then they do not take a blank line.
const excerpt = qualityExcerpt(item.block);
const result = results[item.id];
const folded = collapsed.has(item.id);
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseRichEditor.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseRichEditor.tsx
index 783654a..41a5e3c 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseRichEditor.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseRichEditor.tsx
@@ -34,7 +34,7 @@ interface ImageParseRichEditorProps {
onCommit: () => void;
}
-/** Tiptap 文档编辑视图:正文、表格和撤销共用成熟编辑器的事务模型。 */
+/** Tiptap document edit view: body, tables, and undo share the mature editor's transaction model. */
export function ImageParseRichEditor({
source,
onSave,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseScanOverlay.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseScanOverlay.tsx
index 17ce8d8..70d3238 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseScanOverlay.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseScanOverlay.tsx
@@ -1,10 +1,9 @@
/**
- * 原图上的识别过程覆盖层。
+ * Recognition-process overlay on the original image.
*
- * 用途:解析中在原图上叠扫描带与版面检出框,让「正在识别」看得见落在哪一块上,
- * 而不是只在右栏转一个圈。覆盖层与结果栏共用 useImageParse 的同一份进度快照。
+ * Purpose: while parsing, stack a scan band and detected layout boxes on the original so "recognition in progress" is visible on a particular block, rather than only a spinner in the right column. The overlay and the result column share the same progress snapshot from useImageParse.
*
- * 共享案例使用固定演示坐标;真实文档在服务端返回坐标前只显示扫描带。
+ * Shared examples use fixed demo coordinates; a real document shows only the scan band until the server returns coordinates.
*/
import { useTranslation } from 'react-i18next';
@@ -16,13 +15,13 @@ import type { ImageParseProgressSnapshot } from '../../utils/imageParseSimulatio
interface ImageParseScanOverlayProps {
blocks: readonly ImageParseLayoutBlock[];
progress: ImageParseProgressSnapshot | null;
- /** 是否正在解析;结束后覆盖层整体淡出 */
+ /** Whether parsing is in progress; when it ends the overlay fades out as a whole */
active: boolean;
- /** 原图地址,用它的 alpha 通道给覆盖层做遮罩 */
+ /** Original-image address, used as a mask for the overlay through its alpha channel */
maskSrc: string;
}
-/** 版面块类型 → 框线配色,走图表色板拿到足够区分度又不脱离 token。 */
+/** Layout-block type → box-stroke color, taken from the chart palette so they are distinct enough without leaving the tokens. */
const KIND_STYLE: Record<ImageParseBlockKind, { idle: string; done: string }> = {
header: { idle: 'border-chart-1/50', done: 'border-chart-1 bg-chart-1/10' },
footer: { idle: 'border-chart-6/50', done: 'border-chart-6 bg-chart-6/10' },
@@ -37,15 +36,15 @@ const KIND_STYLE: Record<ImageParseBlockKind, { idle: string; done: string }> =
seal: { idle: 'border-destructive/50', done: 'border-destructive bg-destructive/10' },
};
-/** 只给这几类块挂类型角标——16 个框全带文字会糊成一片。 */
+/** Hang a type badge only on these block kinds — text on all 16 boxes would blur into a mass. */
const LABELLED_KINDS: readonly ImageParseBlockKind[] = ['header', 'footer', 'table', 'formula'];
/**
- * 识别过程覆盖层。
- * @param blocks 归一化版面坐标,空数组表示这张图不画框
- * @param progress 当前进度快照
- * @param active 是否正在解析
- * @param maskSrc 原图地址,覆盖层只在图的不透明像素上显示
+ * Recognition-process overlay.
+ * @param blocks Normalized layout coordinates; an empty array means this image draws no boxes
+ * @param progress Current progress snapshot
+ * @param active Whether parsing is in progress
+ * @param maskSrc Original-image address; the overlay shows only on the image's opaque pixels
*/
export function ImageParseScanOverlay({
blocks,
@@ -62,9 +61,9 @@ export function ImageParseScanOverlay({
const mask = `url(${JSON.stringify(maskSrc)})`;
return (
- // 覆盖层用原图自己的 alpha 做遮罩,而不是写死圆角或直角:
- // 图自带圆角、透明抠图时,按矩形外框扫会让扫描线伸进透明区、凸出在图外;
- // 按像素遮罩后,图是什么形状扫描就是什么形状。
+ // The overlay masks with the original image's own alpha, rather than hard-coding rounded or square corners:
+ // When the image has its own rounded corners or a transparent cutout, scanning the rectangular outer frame lets the scan line run into the transparent area and stick out past the image;
+ // After a per-pixel mask, the scan has whatever shape the image has.
<div
className="pointer-events-none absolute inset-0 overflow-hidden"
style={{
@@ -77,7 +76,7 @@ export function ImageParseScanOverlay({
}}
aria-hidden="true"
>
- {/* 扫描带:无限来回的大面积动效,prefers-reduced-motion 下整块不渲染 */}
+ {/* Scan band: a large motion that travels back and forth forever. Under prefers-reduced-motion the whole block is not rendered */}
<div className="absolute inset-0 motion-reduce:hidden">
<div className="absolute inset-x-0 h-[14%] animate-[map-image-scan_1.9s_ease-in-out_infinite] bg-gradient-to-b from-transparent via-primary/15 to-transparent">
<div className="absolute inset-x-0 bottom-0 h-px bg-primary/70 shadow-[0_0_8px_hsl(var(--primary)/0.6)]" />
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseSealLinkage.test.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseSealLinkage.test.tsx
index e7e0d37..f0f532d 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseSealLinkage.test.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseSealLinkage.test.tsx
@@ -36,7 +36,7 @@ const result = adaptImageParseV2({
const ranges = imageParseBlockRanges(result.markdown, result.blocks);
const linkedRanges = [...ranges].map(([id, range]) => ({ id, range }));
-/** 以真实适配结果连接原图框与图片/PDF 结果预览。 */
+/** Connect original-image boxes to the image/PDF result preview with the real adapted result. */
function SealLinkageWorkspace({
pdf,
onFocus,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseStage.test.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseStage.test.tsx
index fdffb0f..0b54943 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseStage.test.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseStage.test.tsx
@@ -76,7 +76,7 @@ describe('ImageParseStage bounded origin', () => {
expect(button.textContent).toBe('');
expect(button).toHaveAttribute('title', label);
}
- // 更换文件交给拖拽与顶栏入口,底栏不再保留更换按钮(t 在测试里返回 key)。
+ // Replacing a file is left to drag-and-drop and the top-bar entry. The bottom bar no longer keeps a replace button (t returns the key in tests).
expect(screen.queryByRole('button', { name: 'imageParseReplace' })).toBeNull();
fireEvent.click(screen.getByRole('button', { name: 'imageParseZoomIn' }));
expect(toolbar).toHaveTextContent('125%');
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseStage.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseStage.tsx
index 8afd5d5..455c85d 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseStage.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseStage.tsx
@@ -1,13 +1,9 @@
/**
- * 图像解析原图栏(有图后的工作台)。
+ * Image-parse original-image column (the workspace once there is an image).
*
- * 用途:核对 OCR 结果要能凑近看清小字、印章、手写,所以这一栏是个真的看图器——
- * 默认滚轮纵向阅读、Ctrl/Meta 滚轮锚点缩放、受限平移、旋转、还原与全屏。
- * 视图控制常显:缩放旋转是核对时的主操作,做成悬停出现等于没有。
+ * Purpose: checking an OCR result has to get close enough to read small type, seals, and handwriting, so this column is a real viewer — wheel scrolls vertically by default, Ctrl/Meta wheel zooms anchored at the cursor, pan is constrained, plus rotate, reset, and fullscreen. View controls stay visible: zoom and rotation are the main actions while checking, and making them appear only on hover is the same as not having them.
*
- * 解析中要在图上叠扫描与版面框,所以图框尺寸必须精确——包裹层用图片真实宽高比
- * 铺满视口宽度,长文档顶部先展示,覆盖层 inset-0 与原图使用同一坐标系。
- * 原图按目标尺寸绘制,覆盖层使用同一坐标系;框线和编号保持固定大小。
+ * While parsing, a scan and layout boxes are stacked on the image, so the image frame size has to be exact — the wrapper uses the image's real aspect ratio to fill the viewport width, a long document shows the top first, and the overlay's inset-0 shares a coordinate system with the original. The original is drawn at the target size and the overlay uses the same coordinate system; box strokes and numbers stay a fixed size.
*/
import {
@@ -33,13 +29,13 @@ import { ImageParseStageToolbar } from './ImageParseStageToolbar';
interface ImageParseStageProps {
attachment: Attachment;
- /** 已解析出的可显示地址 */
+ /** Displayable address already resolved */
previewSrc: string;
disabled?: boolean;
onPreview: (src: string) => void;
onClear: () => void;
blocks: readonly ImageParseLayoutBlock[];
- /** 服务端旋转摆正信息;bbox/regions 坐标已基于摆正后的图。 */
+ /** Server rotation-adaptation info; bbox/regions coordinates are already based on the image after rotation adaptation. */
rotation?: ImageParseRotationInfo;
progress: ImageParseProgressSnapshot | null;
parsing: boolean;
@@ -61,13 +57,13 @@ interface ImageParseStageProps {
}
/**
- * 原图看图器。
- * @param attachment 当前图片附件
- * @param previewSrc 图片地址
- * @param onPreview 打开全屏预览
- * @param blocks 版面块,空数组表示不画框
- * @param progress 解析进度快照
- * @param parsing 是否正在解析
+ * Original-image viewer.
+ * @param attachment Current image attachment
+ * @param previewSrc Image address
+ * @param onPreview Open the fullscreen preview
+ * @param blocks Layout blocks; an empty array means draw no boxes
+ * @param progress Parse progress snapshot
+ * @param parsing Whether parsing is in progress
*/
export function ImageParseStage({
attachment,
@@ -94,7 +90,7 @@ export function ImageParseStage({
onScrollProgress,
}: ImageParseStageProps) {
const { t } = useTranslation('playground');
- // 保存原始图尺寸;服务端摆正后包裹层按旋转后的外接框定尺。
+ // Save the original image size; after server rotation adaptation the wrapper is sized to the rotated bounding box.
const [naturalSize, setNaturalSize] = useState<{ width: number; height: number } | null>(null);
const zoom = useImageZoom({ fitWidth: true });
const lastFocus = useRef<{ src: string; request: number } | null>(null);
@@ -123,7 +119,7 @@ export function ImageParseStage({
const ratio = rotatedLayout ? rotatedLayout.width / rotatedLayout.height : null;
const imageWidthPercent =
naturalSize && rotatedLayout ? (naturalSize.width / rotatedLayout.width) * 100 : 100;
- // 两个 ref 回调先解构出来:把 zoom 的属性直接塞进 ref 属性,lint 会把整个 zoom 当成 ref。
+ // Destructure the two ref callbacks first: stuffing zoom's properties straight into the ref prop makes lint treat the whole zoom object as the ref.
const { reset, setViewport, setContent, focusBlock, scrollToProgress } = zoom;
const attachViewport = useCallback(
(node: HTMLElement | null) => {
@@ -134,7 +130,7 @@ export function ImageParseStage({
[setViewport, originScrollRef],
);
- // 换图后回到初始视图,否则新图会带着上一张的倍数与角度。
+ // After changing images, return to the initial view, or the new image carries the previous one's scale and angle.
useEffect(() => {
reset();
}, [previewSrc, reset]);
@@ -142,7 +138,7 @@ export function ImageParseStage({
useLayoutEffect(() => {
if (pendingProgress.current?.src !== previewSrc) pendingProgress.current = undefined;
if (scrollProgress === undefined || !Number.isFinite(scrollProgress)) {
- // 外部请求消费后只结束其自身确认,不清除适合宽度切换时仍待确认的点击定位。
+ // After an external request is consumed, only end its own confirmation, and do not clear a click location that is still pending confirmation across a fit-width switch.
if (pendingProgress.current?.source === 'scroll') pendingProgress.current = undefined;
return;
}
@@ -160,7 +156,7 @@ export function ImageParseStage({
useEffect(() => {
if (!zoom.raster.width || !zoom.raster.height) return;
const actual = zoom.scrollProgress;
- // 确认实际位置并消费请求;程序定位只禁止反向回写,不能吞掉位置确认。
+ // Confirm the actual position and consume the request; programmatic location only forbids writing back the other way, and must not swallow position confirmation.
if (pendingProgress.current !== undefined) {
if (Math.abs(actual - pendingProgress.current.progress) < 0.001) {
pendingProgress.current = undefined;
@@ -193,7 +189,7 @@ export function ImageParseStage({
})
)
lastFocus.current = { src: previewSrc, request: focusRequest };
- // 收起的图片栏测不到尺寸;重新展开后首次测量完成时执行未完成的定位。
+ // A collapsed image column cannot be measured; run unfinished location on the first measurement after it expands again.
}, [blocks, focusBlock, focusRequest, previewSrc, selectedBlockId]);
return (
@@ -249,7 +245,7 @@ export function ImageParseStage({
onPointerUp={zoom.onPointerUp}
onPointerCancel={zoom.onPointerUp}
className={cn(
- // touch-none:触屏上要拿到 pointermove 才能平移,否则会被当成页面滚动吞掉
+ // touch-none: on a touch screen, pointermove has to be received before panning works, or it is swallowed as page scrolling
'flex h-full min-h-0 w-full touch-none items-center justify-center overflow-hidden',
stageCursor(zoom),
)}
@@ -257,11 +253,11 @@ export function ImageParseStage({
<span
ref={setContent}
style={{ aspectRatio: ratio ? String(ratio) : undefined }}
- // min-h-0:服务端 90/270 度摆正后宽高比与原图相反,aspect-ratio 默认的
- // min-height:auto 会被按原图比例排版的测量图撑高,框层随之被纵向拉伸。
+ // min-h-0: after server rotation adaptation of 90/270 degrees the aspect ratio is the opposite of the original, and aspect-ratio's default
+ // min-height:auto is stretched by the measurement image laid out at the original ratio, and the box layer is stretched vertically with it.
className="relative flex min-h-0 w-full shrink-0 items-center justify-center"
>
- {/* 仅用于测量原图尺寸;拿到比例后脱离文档流,容器高度只由摆正后的比例决定。 */}
+ {/* Used only to measure the original image size; once the ratio is known it leaves document flow, and the container height is decided only by the ratio after rotation adaptation. */}
<img
src={previewSrc}
alt=""
@@ -285,7 +281,7 @@ export function ImageParseStage({
height: zoom.raster.height || '100%',
transform: `translate(-50%, -50%) ${zoom.raster.transform}`,
}}
- // 边界校正立即生效,避免 resize 后位移过渡短暂露出图片外的空白。
+ // Boundary correction takes effect immediately, so a translation transition after resize does not briefly show blank space outside the image.
className="absolute left-1/2 top-1/2"
>
<span className="absolute inset-0 flex items-center justify-center overflow-visible">
@@ -325,7 +321,7 @@ export function ImageParseStage({
);
}
-/** 视口光标:文档可以在边界内拖动,按下时切换为抓取状态。 */
+/** Viewport cursor: the document can be dragged inside the bounds, and pressing switches to the grabbing state. */
function stageCursor(zoom: ImageZoom): string {
return zoom.dragging ? 'cursor-grabbing' : 'cursor-grab';
}
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseStageToolbar.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseStageToolbar.tsx
index 5304997..01a006a 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseStageToolbar.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseStageToolbar.tsx
@@ -24,7 +24,7 @@ interface ImageParseStageToolbarProps {
}
/**
- * 原图头部工具组:缩放和方向操作按组排列,与 PDF 原图工具栏保持一致。
+ * Tool group at the head of the original image: zoom and orientation actions are grouped, consistent with the PDF original-image toolbar.
*/
export function ImageParseStageToolbar({
zoom,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseStatusStrip.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseStatusStrip.tsx
index c65ca99..4d92536 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseStatusStrip.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseStatusStrip.tsx
@@ -12,9 +12,9 @@ interface ImageParseStatusStripProps {
}
/**
- * 工作台顶部的上传状态条;识别错误由结果区域承接。
- * @param props 模型凭据、解析状态、上传生命周期与流水线档位
- * @returns 与当前状态匹配的状态条组合
+ * Upload status bar at the top of the workspace; recognition errors are carried by the result area.
+ * @param props Model credentials, parse state, upload lifecycle, and pipeline tier
+ * @returns The status-bar combination that matches the current state
*/
export function ImageParseStatusStrip({
parse,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseTaskBar.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseTaskBar.tsx
index b94101e..de889a8 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseTaskBar.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseTaskBar.tsx
@@ -30,7 +30,7 @@ const TASKS = [
] as const;
/**
- * 工作台仅展示算法服务支持的文档识别与字段抽取。
+ * The workspace shows only document recognition and field extraction supported by the algorithm service.
*/
export function ImageParseTaskBar({
mode,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseTaskPane.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseTaskPane.tsx
index f6ba132..5642c6d 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseTaskPane.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseTaskPane.tsx
@@ -21,9 +21,9 @@ interface ImageParseTaskPaneProps {
}
/**
- * 按任务阶段显示待执行、字段配置或识别结果,同一时刻仅提供一个开始入口。
- * @param props 当前任务、操作状态及结果面板参数
- * @returns 工作台右侧任务内容
+ * By task phase, show pending, field configuration, or the recognition result, and offer only one start entry at a time.
+ * @param props Current task, action state, and result-panel parameters
+ * @returns Task content on the right of the workspace
*/
export function ImageParseTaskPane({
parse,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseToolButton.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseToolButton.tsx
index 029a1a2..fd6db48 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseToolButton.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseToolButton.tsx
@@ -12,13 +12,13 @@ interface ImageParseToolButtonProps {
onClick: () => void;
disabled?: boolean;
pressed?: boolean;
- /** 直接展示操作文字;图标控件保持紧凑,文字控件用于工具栏主操作。 */
+ /** Show the action text directly; icon controls stay compact, and text controls are for the toolbar's primary action. */
showLabel?: boolean;
className?: string;
children: ReactNode;
}
-/** 文档工具按钮:统一尺寸、键盘焦点、无障碍名称、悬停提示和可选可见文字。 */
+/** Document tool button: shared size, keyboard focus, accessible name, hover hint, and optional visible text. */
export function ImageParseToolButton({
label,
hint = label,
@@ -53,7 +53,7 @@ export function ImageParseToolButton({
<Tooltip>
<TooltipTrigger asChild>
{disabled ? (
- // 原生禁用按钮不接收指针与焦点,用外层承接提示,按钮仍保持不可执行。
+ // A natively disabled button does not receive pointer or focus. The outer layer carries the hint, and the button stays non-executable.
<span
tabIndex={0}
className="inline-flex rounded-md focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/30"
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseToolbar.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseToolbar.tsx
index f533302..50cc45a 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseToolbar.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseToolbar.tsx
@@ -1,8 +1,7 @@
/**
- * 图像解析工作台顶栏。
+ * Image-parse workspace top bar.
*
- * 用途:左侧显示文件名,右侧保留识别与结果操作;识别设置仅在已有文档时显示。
- * 空态保留汉堡键与文档入口,避免再叠一层体验中心标题栏。
+ * Purpose: file name on the left, and recognition and result actions kept on the right; recognition settings are shown only when a document already exists. The empty state keeps the hamburger and the docs entry, so another experience-center title bar is not stacked on top.
*/
import { useRef } from 'react';
@@ -35,18 +34,18 @@ interface ImageParseToolbarProps {
onNewDocument: () => void;
showMenuButton?: boolean;
onOpenSidebar?: () => void;
- /** 把本次选择的 PDF/图片接到当前识别后面;字段提取任务不提供追加入口。 */
+ /** Append the PDF/image selected this time after the current recognition; field-extraction tasks do not offer an append entry. */
onAppendPages?: (files: FileList) => void;
- /** 正在合成追加页时禁用入口并展示进度文案。 */
+ /** While appended pages are being composed, disable the entry and show progress copy. */
appending?: boolean;
- /** 字段配置阶段由设置面板提供主操作时隐藏顶栏识别按钮。 */
+ /** During field configuration, hide the top-bar recognition button when the settings panel provides the primary action. */
showParseAction?: boolean;
- /** 共享示例没有可直接重跑的来源;由外层先转成个人上传任务。 */
+ /** A shared example has no source that can be rerun directly; the outer layer first turns it into a personal upload task. */
onReparseExample?: () => void;
}
/**
- * 对照工作台顶栏。有图后显示文件名与识别操作。
+ * Comparison-workspace top bar. Once there is an image, show the file name and recognition actions.
*/
export function ImageParseToolbar({
fileName,
@@ -209,7 +208,7 @@ export function ImageParseToolbar({
);
}
-/** 顶栏文档入口。文档解析页打开本仓库的部署指南。 */
+/** Docs entry in the top bar. The document-parse page opens this repo's deployment guide. */
function DocsLink({ experience }: { experience: Exclude<ExperienceKey, 'language'> }) {
const locale = useAppStore((state) => state.locale);
const docsTitle = getPortalRouteTitle('/docs', locale, 'API 文档');
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseUploadDialog.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseUploadDialog.tsx
index 19ca9d3..723d871 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseUploadDialog.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseUploadDialog.tsx
@@ -12,7 +12,7 @@ interface ImageParseUploadDialogProps {
onPick: (file: File) => void;
}
-/** 新建识别弹窗,复用工作台的上传校验和解析生命周期。 */
+/** New-recognition dialog, reusing the workspace's upload validation and parse lifecycle. */
export function ImageParseUploadDialog({
open,
disabled,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseUploadSurface.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseUploadSurface.tsx
index 075bb64..6ecdd0d 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseUploadSurface.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseUploadSurface.tsx
@@ -20,9 +20,9 @@ interface ImageParseUploadSurfaceProps {
}
/**
- * 虚线框和框外限制说明。点虚线框打开同一个文件选择器,图片和 PDF 都从这里选。
- * @param props 文件选择回调、拖放事件和禁用状态
- * @returns 工作台与上传页共用的上传面
+ * Dashed frame and the limit notes outside it. Clicking the dashed frame opens the same file picker; both images and PDFs are chosen from here.
+ * @param props File-selection callback, drag-and-drop events, and disabled state
+ * @returns Upload surface shared by the workspace and the upload page
*/
export function ImageParseUploadSurface({
disabled,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseVisualEditor.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseVisualEditor.tsx
index ea13275..677a426 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseVisualEditor.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseVisualEditor.tsx
@@ -24,12 +24,12 @@ interface ImageParseVisualEditorProps {
loading: boolean;
onSave: (value: string, editedRange?: ImageParseTextRange) => void;
onEditingChange?: (editing: boolean) => void;
- /** 服务标记为页脚 / 页码的块范围;只在文字仍像页码时弱化展示。 */
+ /** Block ranges the service marked as footer / page number; mute them only while the text still looks like a page number. */
pageNumberRanges?: ReadonlySet<string>;
children: React.ReactNode;
}
-/** 双击语义块才创建编辑器;其它块保留预览,失焦保存并释放唯一实例。 */
+/** Create the editor only on a double-click of a semantic block; other blocks keep the preview, and blur saves and releases the single instance. */
export function ImageParseVisualEditor({
source,
loading,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseWorkspace.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseWorkspace.tsx
index e3316bc..c33d532 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ImageParseWorkspace.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ImageParseWorkspace.tsx
@@ -13,7 +13,7 @@ import { ImageParseExampleGrid } from './ImageParseExampleGrid';
import { ImageParseUploadSurface } from './ImageParseUploadSurface';
import { ImageParseKieUpload } from './ImageParseKieUpload';
-/** 空态保留直接上传和顶栏新建两种入口。 */
+/** The empty state keeps both direct upload and the top-bar new entry. */
export interface ImageParseWorkspaceProps {
onNewDocument: () => void;
onExample?: (type: ImageParseExampleType) => void;
@@ -25,9 +25,9 @@ export interface ImageParseWorkspaceProps {
}
/**
- * 单区上传空态及真实内置样例,不承担上传或解析状态。
- * @param props 样例、新建文档及文件选择回调
- * @returns 紧凑文档工作台
+ * Single-area upload empty state and real built-in samples. It does not own upload or parse state.
+ * @param props Samples, new-document, and file-selection callbacks
+ * @returns Compact document workspace
*/
export function ImageParseWorkspace({
onNewDocument,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/PdfDocumentPage.tsx b/webdemo/frontend/src/pages/playground/components/experiences/PdfDocumentPage.tsx
index 45cbdd9..d04e3cf 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/PdfDocumentPage.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/PdfDocumentPage.tsx
@@ -17,7 +17,7 @@ interface PdfDocumentPageProps {
ready: boolean;
showLoading?: boolean;
rotation: number;
- /** 这一页服务端摆正角度。0 表示预览保持原方向。 */
+ /** This page's server rotation-adaptation angle. 0 means the preview keeps the original orientation. */
serverAngle?: number;
blocks: readonly ImageParseLayoutBlock[];
showBlocks?: boolean;
@@ -30,7 +30,7 @@ interface PdfDocumentPageProps {
setPageCanvas: (pageNumber: number, canvas: HTMLCanvasElement | null) => void;
}
-/** PDF 单页骨架与识别框;仅为视口附近页面挂载画布和交互层,联动标记按当前页隔离。 */
+/** PDF single-page skeleton and recognition boxes; mount the canvas and interaction layer only for pages near the viewport, and isolate linkage marks to the current page. */
export const PdfDocumentPage = memo(function PdfDocumentPage({
pageNumber,
width,
@@ -66,7 +66,7 @@ export const PdfDocumentPage = memo(function PdfDocumentPage({
);
const userAngle = ((rotation % 360) + 360) % 360;
const serverTurns = ((serverAngle % 360) + 360) % 360;
- // 服务端摆正时,框留在摆正坐标系,只旋转底图。框跟着底图一起转时,高亮会落到页底,多页连排就压到下一页页眉上。
+ // During server rotation adaptation, leave the boxes in the rotation-adaptation coordinate system and rotate only the base image. If the boxes rotate with the base image, the highlight lands at the bottom of the page, and in a multi-page run it presses onto the next page's header.
const serverUpright = serverTurns !== 0 && userAngle === 0;
const bounds = serverUpright ? rotatedPageBounds(width, height, serverAngle) : { width, height };
const overlayBlocks = useMemo(
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/PdfDocumentStage.tsx b/webdemo/frontend/src/pages/playground/components/experiences/PdfDocumentStage.tsx
index b94e63e..f3d9d2a 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/PdfDocumentStage.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/PdfDocumentStage.tsx
@@ -23,7 +23,7 @@ interface PdfDocumentStageProps {
parsing?: boolean;
blocks?: readonly ImageParseLayoutBlock[];
pageBlocks?: Readonly<Record<number, readonly ImageParseLayoutBlock[]>>;
- /** 每一页自己的服务端摆正角度,键是页码。 */
+ /** This page's own server rotation-adaptation angle; the key is the page number. */
pageServerAngles?: Readonly<Record<number, number>>;
showBlocks?: boolean;
onToggleBlocks?: () => void;
@@ -40,7 +40,7 @@ interface PdfDocumentStageProps {
const NO_BLOCKS: readonly ImageParseLayoutBlock[] = [];
-/** PDF 原文阅读器:所有页面在同一视口连续滚动,页码只负责定位。 */
+/** PDF original reader: every page scrolls continuously in one viewport, and the page number is only for location. */
export default function PdfDocumentStage({
attachment,
disabled,
@@ -112,7 +112,7 @@ export default function PdfDocumentStage({
{ label: 'imageParseZoomIn', icon: ZoomIn, action: pdf.zoomIn, disabled: pdf.scale >= 3 },
{ label: 'imageParseRotateRight', icon: RotateCw, action: pdf.rotate },
];
- // 首帧提交前使用固定视口占位,不随页面尺寸或连续文档的滚动位置重新居中。
+ // Before the first frame is committed, use a fixed viewport placeholder, and do not re-center with page size or the scroll position of a continuous document.
const initialLoading = pdf.rendering && !pdf.readyPageNumbers.length && !pdf.error;
const focusPreviewBlock = useCallback(
(id: string) => {
@@ -125,7 +125,7 @@ export default function PdfDocumentStage({
if (!viewport || !block) return false;
const bounds = viewport.getBoundingClientRect();
const target = block.getBoundingClientRect();
- // 不用 scrollIntoView,避免滚动链同时移动工作台外层页面。
+ // Do not use scrollIntoView, so the scroll chain does not also move the page outside the workspace.
viewport.scrollTop = Math.max(
0,
Math.min(
@@ -199,7 +199,7 @@ export default function PdfDocumentStage({
if (expected !== undefined && Math.abs(expected - viewport.scrollTop) < 1)
onScrollProgress?.(progress, true);
else {
- // 联动和块定位只调整当前页视口,不能再次用视口中心反向改写所选页。
+ // Linkage and block location only adjust the current page's viewport, and must not write the selected page back again from the viewport center.
updateCurrentPage();
onScrollProgress?.(progress);
}
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/PdfPageThumbnail.tsx b/webdemo/frontend/src/pages/playground/components/experiences/PdfPageThumbnail.tsx
index cf6dfdf..150d910 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/PdfPageThumbnail.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/PdfPageThumbnail.tsx
@@ -4,7 +4,7 @@ import { cn } from '@map/ui';
import { usePdfThumbnail } from '../../hooks/usePdfThumbnail';
-/** PDF 低分辨率预览;仅可见项绘制,不与正文共用 canvas。 */
+/** Low-resolution PDF preview; draw only visible items, and do not share a canvas with the body. */
export function PdfPageThumbnail({
document,
pageNumber,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/PdfPreviewLoading.tsx b/webdemo/frontend/src/pages/playground/components/experiences/PdfPreviewLoading.tsx
index 68c374a..ebae95c 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/PdfPreviewLoading.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/PdfPreviewLoading.tsx
@@ -7,8 +7,8 @@ interface PdfPreviewLoadingProps {
}
/**
- * PDF 预览加载占位:文档骨架与紧凑状态共用于按需加载和页面渲染。
- * @param className 外层布局样式
+ * PDF preview loading placeholder: the document skeleton and the compact state are shared by on-demand loading and page rendering.
+ * @param className Outer layout styles
*/
export function PdfPreviewLoading({ className }: PdfPreviewLoadingProps) {
const { t } = useTranslation('playground');
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/ReferenceAudioField.tsx b/webdemo/frontend/src/pages/playground/components/experiences/ReferenceAudioField.tsx
index fcc110b..aa61594 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/ReferenceAudioField.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/ReferenceAudioField.tsx
@@ -1,12 +1,12 @@
/**
- * 参考音频采集区(语音复刻用)。
+ * Reference-audio capture area (for voice cloning).
*
- * 用途:TTS「上传复刻」音色下的参考音频三态视图——
- * 1) 空态:上传文件 / 开始录音两个入口;
- * 2) 录制中:实时声纹 + 已录秒数 + 剩余提示,用户看得见自己有没有出声;
- * 3) 已就绪:波形播放器可试听,配「重新录制」与「删除」。重录/重传直接覆盖旧音频。
+ * Purpose: the three-state view of reference audio under the TTS "upload clone" voice —
+ * 1) empty: two entries, upload a file / start recording;
+ * 2) recording: a realtime voiceprint + seconds recorded + remaining hint, so the user can see whether they are making sound;
+ * 3) ready: a waveform player for preview, with "record again" and "delete." Recording or uploading again overwrites the old audio directly.
*
- * 本组件只吃 props 渲染,录音编排在 useVoiceRecorder / useTtsSynthesis。
+ * This component only renders from props. Recording orchestration is in useVoiceRecorder / useTtsSynthesis.
*/
import { Upload, Mic, Square, Trash2, RotateCcw } from 'lucide-react';
@@ -16,28 +16,28 @@ import { AudioWavePlayer } from './AudioWavePlayer';
import { TTS_REF_MAX_SECONDS } from '../../utils/ttsVoices';
interface ReferenceAudioFieldProps {
- /** 是否录制中 */
+ /** Whether recording is in progress */
recording: boolean;
- /** 录制中的实时频谱条(0–1) */
+ /** Realtime spectrum bars while recording (0–1) */
bars: number[];
- /** 已录秒数 */
+ /** Seconds already recorded */
seconds: number;
- /** 已就绪的参考音频 data URI,未采集时 undefined */
+ /** Data URI of the ready reference audio; undefined when nothing has been captured */
referenceUrl?: string;
- /** 已就绪音频的展示名 */
+ /** Display name of the ready audio */
referenceName?: string;
- /** 录音权限 / 时长错误 */
+ /** Recording permission / duration error */
error?: string;
onStart: () => void;
onStop: () => void;
onClear: () => void;
- /** 选择本地文件 */
+ /** Choose a local file */
onPickFile: (file: File) => void;
}
/**
- * 参考音频采集区。
- * @param props 三态所需的状态与回调
+ * Reference-audio capture area.
+ * @param props State and callbacks needed by the three states
*/
export function ReferenceAudioField({
recording,
@@ -128,7 +128,7 @@ export function ReferenceAudioField({
);
}
-/** 录音中的实时声纹:频谱条居中镜像,静音时退化为一条细中线(提示"没收到声音") */
+/** Realtime voiceprint while recording: spectrum bars mirrored around the center, degrading to a thin center line when silent (a hint that "no sound was received") */
function LiveWave({ bars }: { bars: number[] }) {
const { t } = useTranslation('playground');
const silent = bars.length === 0 || bars.every((b) => b < 0.02);
@@ -152,7 +152,7 @@ function LiveWave({ bars }: { bars: number[] }) {
);
}
-/** 空态的虚线上传区 */
+/** Dashed upload area in the empty state */
function FilePickLabel({ onPick }: { onPick: (file: File) => void }) {
const { t } = useTranslation('playground');
return (
@@ -169,7 +169,7 @@ function FilePickLabel({ onPick }: { onPick: (file: File) => void }) {
);
}
-/** 已就绪态的「重新上传」按钮(label 包 input 以复用原生文件选择) */
+/** "Upload again" button in the ready state (a label wrapping an input, to reuse the native file picker) */
function FilePickButton({ label, onPick }: { label: string; onPick: (file: File) => void }) {
return (
<label className="flex h-8 flex-1 cursor-pointer items-center justify-center gap-1.5 rounded-md border border-border bg-background px-3 text-xs font-medium text-foreground transition-colors hover:bg-muted">
@@ -185,7 +185,7 @@ function FilePickButton({ label, onPick }: { label: string; onPick: (file: File)
);
}
-/** 秒 → mm:ss */
+/** Seconds → mm:ss */
function fmtSeconds(sec: number): string {
const m = Math.floor(sec / 60);
const s = sec % 60;
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/TtsExperience.tsx b/webdemo/frontend/src/pages/playground/components/experiences/TtsExperience.tsx
index 85b495a..26dddf1 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/TtsExperience.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/TtsExperience.tsx
@@ -1,10 +1,7 @@
/**
- * 体验中心「语音合成(TTS)」体验页。
+ * Experience-center "speech synthesis (TTS)" page.
*
- * 用途:真实语音合成工作台——左侧文本输入与波形播放器结果,右侧合成设置(TtsSettingsPanel)。
- * 走 L2 `/v1/audio/speech`。音色三态:默认音色 / 预置示范音色 / 上传复刻(语音复刻,上传或录制
- * 参考音频克隆音色);声音描述(Control Instruction)以文本前缀控制风格;输出支持 wav / mp3。本页为
- * 容器:装配 useTtsSynthesis 与视图,请求/状态编排收敛在 hook,设置控件收敛在 TtsSettingsPanel。
+ * Purpose: a real speech-synthesis workspace — text input and waveform-player result on the left, synthesis settings on the right (TtsSettingsPanel). It goes through L2 `/v1/audio/speech`. Three voice states: default voice / preset demo voice / upload clone (voice cloning, cloning a voice by uploading or recording reference audio); a voice description (Control Instruction) controls style as a text prefix; output supports wav / mp3. This page is a container: it assembles useTtsSynthesis and the views. Request/state orchestration stays in the hook, and setting controls stay in TtsSettingsPanel.
*/
import { useEffect, useState } from 'react';
@@ -22,8 +19,8 @@ import { resolveTtsMode, VOICE_DEFAULT, VOICE_UPLOAD } from '../../utils/ttsVoic
type PlaygroundModel = ReturnType<typeof usePlaygroundModel>;
/**
- * 语音合成体验页。
- * @param model 模型与密钥编排(来自页面顶层 usePlaygroundModel)
+ * Speech-synthesis experience page.
+ * @param model Model and key orchestration (from the page-level usePlaygroundModel)
*/
export function TtsExperience({ model }: { model: PlaygroundModel }) {
const { toast } = useToast();
@@ -52,7 +49,7 @@ export function TtsExperience({ model }: { model: PlaygroundModel }) {
}
}
- // 上传参考音频:超 50s / 转码失败给出可读提示(不静默吞)
+ // Uploading reference audio: over 50s / transcode failure gives a readable hint (it is not swallowed silently)
async function onUpload(file: File) {
try {
await tts.uploadReference(file);
@@ -68,7 +65,7 @@ export function TtsExperience({ model }: { model: PlaygroundModel }) {
return (
<div className="flex h-full w-full flex-col gap-4 overflow-y-auto px-3 py-4 sm:px-4">
<div className="grid min-h-0 flex-1 grid-cols-1 gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]">
- {/* 左:文本 + 结果 */}
+ {/* Left: text + result */}
<div className="flex min-w-0 flex-col gap-4">
<section className="flex flex-col rounded-2xl bg-card p-4 shadow-card sm:p-5">
<div className="mb-2 flex items-center justify-between">
@@ -120,7 +117,7 @@ export function TtsExperience({ model }: { model: PlaygroundModel }) {
/>
</div>
- {/* 右:合成设置 */}
+ {/* Right: synthesis settings */}
<TtsSettingsPanel
model={model}
tts={tts}
@@ -134,7 +131,7 @@ export function TtsExperience({ model }: { model: PlaygroundModel }) {
);
}
-/** 合成结果卡:加载 / 错误 / 播放器 / 空态四态。下载名跟随结果音频的实际格式 */
+/** Synthesis result card: the four states of loading / error / player / empty. The download name follows the result audio's actual format */
function ResultCard({
audioUrl,
format,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/TtsSettingsPanel.tsx b/webdemo/frontend/src/pages/playground/components/experiences/TtsSettingsPanel.tsx
index d119c90..6f8a92d 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/TtsSettingsPanel.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/TtsSettingsPanel.tsx
@@ -1,10 +1,7 @@
/**
- * 语音合成「合成设置」面板。
+ * Speech-synthesis "synthesis settings" panel.
*
- * 用途:TtsExperience 右栏设置的展示组件——模型(只读锁定)、声音描述(预设下拉 + 自定义展开
- * + 查看示例)、音色(默认/预置/上传复刻)、上传或录制参考音频、高级设置
- * (CFG 引导强度滑块 + 参考音频降噪 / 文本规范化开关)、合成按钮与密钥状态。逻辑全在 useTtsSynthesis,
- * 本组件只吃 props 渲染,不含请求/状态编排。响应式:随外层栅格在窄屏堆叠,控件均全宽自适应。
+ * Purpose: the display component for TtsExperience's right-column settings — model (read-only and locked), voice description (preset dropdown + custom expand + view examples), voice (default/preset/upload clone), upload or record reference audio, advanced settings (CFG guidance-strength slider + reference-audio denoise / text-normalization switches), the synthesize button, and key status. All logic is in useTtsSynthesis. This component only renders from props and does not orchestrate requests or state. Responsive: it stacks with the outer grid on a narrow screen, and controls are all full-width and adaptive.
*/
import { AudioLines, Loader2, Sparkles, SlidersHorizontal, ChevronDown } from 'lucide-react';
@@ -55,18 +52,18 @@ interface TtsSettingsPanelProps {
model: PlaygroundModel;
tts: TtsState;
mode: TtsMode;
- /** 当前用户是否可使用语音复刻;未授权时只展示普通语音生成。 */
+ /** Whether the current user may use voice cloning; when unauthorized, show only ordinary speech generation. */
canUseVoiceClone: boolean;
onModeChange: (mode: TtsMode) => void;
- /** 上传参考音频(含错误 toast) */
+ /** Upload reference audio (including an error toast) */
onUpload: (file: File) => void;
}
/**
- * 合成设置面板。
- * @param model 模型与密钥编排
- * @param tts useTtsSynthesis 返回的状态与动作
- * @param onUpload 参考音频上传处理
+ * Synthesis settings panel.
+ * @param model Model and key orchestration
+ * @param tts State and actions returned by useTtsSynthesis
+ * @param onUpload Reference-audio upload handler
*/
export function TtsSettingsPanel({
model,
@@ -213,7 +210,7 @@ export function TtsSettingsPanel({
{t('cloningHint')}
</p>
)}
- {/* 暂时隐藏生成模式说明,避免与当前简化的设置面板重复。 */}
+ {/* Hide the generation-mode note for now, so it does not repeat the currently simplified settings panel. */}
<Button
className="mt-auto w-full gap-2"
@@ -243,7 +240,7 @@ function getTtsActionLabel(isClone: boolean, cloneLabel: string, generateLabel:
return isClone ? cloneLabel : generateLabel;
}
-/** 高级设置:CFG 引导强度滑块 + 参考音频降噪 / 文本规范化开关(后二者透传上游) */
+/** Advanced settings: CFG guidance-strength slider + reference-audio denoise / text-normalization switches (the latter two are passed through upstream) */
function AdvancedSettings({ tts, isClone }: { tts: TtsState; isClone: boolean }) {
const { t } = useTranslation('playground');
return (
@@ -254,7 +251,7 @@ function AdvancedSettings({ tts, isClone }: { tts: TtsState; isClone: boolean })
<ChevronDown className="ml-auto h-3.5 w-3.5 shrink-0 transition-transform duration-200 group-open:rotate-180" />
</summary>
<div className="mt-3 flex flex-col gap-4">
- {/* CFG 引导强度:滑块直观调参,右侧同步数值 */}
+ {/* CFG guidance strength: the slider adjusts it directly, and the number on the right stays in sync */}
<div className="flex flex-col gap-1.5">
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-muted-foreground">{t('cfgGuidance')}</span>
@@ -273,7 +270,7 @@ function AdvancedSettings({ tts, isClone }: { tts: TtsState; isClone: boolean })
<p className="text-[11px] leading-relaxed text-muted-foreground/70">{t('cfgHint')}</p>
</div>
- {/* 透传开关:官方为 demo 侧预处理,我方作字段透传,生效取决于上游 LIS 能力 */}
+ {/* Pass-through switches: officially these are demo-side preprocessing. We pass the fields through, and whether they take effect depends on upstream LIS capability */}
{isClone && (
<ToggleRow
label={t('referenceDenoise')}
@@ -282,13 +279,13 @@ function AdvancedSettings({ tts, isClone }: { tts: TtsState; isClone: boolean })
onChange={tts.setDenoise}
/>
)}
- {/* 暂时隐藏文本规范化:当前上游能力未稳定提供,保留状态与透传逻辑以便恢复。 */}
+ {/* Hide text normalization for now: the current upstream capability is not provided stably. Keep the state and pass-through logic so it can be restored. */}
</div>
</details>
);
}
-/** 开关行:标题 + 「上游支持时生效」诚实标注 + Switch */
+/** Switch row: title + an honest "takes effect when upstream supports it" mark + Switch */
function ToggleRow({
label,
hint,
@@ -311,7 +308,7 @@ function ToggleRow({
);
}
-/** 「查看示例」弹窗:对齐官方 demo 的角色扮演 + 方言生成指南,给声音描述灵感 */
+/** "View examples" dialog: aligned with the official demo's role-play + dialect generation guide, for voice-description ideas */
function ExamplesDialog() {
const { t } = useTranslation('playground');
const [open, setOpen] = useState(false);
@@ -361,7 +358,7 @@ function ExamplesDialog() {
);
}
-/** 带标题的表单字段容器 */
+/** Form field container with a title */
function Field({ label, children }: { label: string; children: React.ReactNode }) {
return (
<label className="flex flex-col gap-1.5">
@@ -371,10 +368,9 @@ function Field({ label, children }: { label: string; children: React.ReactNode }
);
}
-/** 只读锁定模型下拉:仅一个选项并默认选中,保持下拉外观但不提供切换 */
+/** Read-only locked model dropdown: only one option, selected by default. It keeps the dropdown look but does not offer switching */
/**
- * 语音合成模型下拉:候选来自管理端勾了「语音合成」能力的全部模型。
- * 只有一个候选时下拉照常可用(仅一项),无候选时禁用并显示「暂无可用模型」。
+ * Speech-synthesis model dropdown: candidates are every model the admin console marked with the "speech synthesis" capability. With only one candidate the dropdown still works (just one item); with no candidates it is disabled and shows "no model available."
*/
function ExperienceModelSelect({
models,
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/VideoStage.tsx b/webdemo/frontend/src/pages/playground/components/experiences/VideoStage.tsx
index 9480324..b8c5edc 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/VideoStage.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/VideoStage.tsx
@@ -1,9 +1,7 @@
/**
- * 双工视频舞台。
+ * Duplex video stage.
*
- * 用途:全双工外壳的主视觉区——视频模式用 useEffect 把摄像头流挂到 <video> 预览,纯语音
- * 模式显示环形声纹;舞台底部以浮层显示最新对话字幕(沉浸式,参照豆包/ChatGPT 语音)。左上角
- * LIVE 徽标与会话时长。video 模式下摄像头帧会按 ~1fps 上行给模型做视频理解。纯展示组件。
+ * Purpose: the main visual area of the full-duplex shell — video mode uses useEffect to attach the camera stream to a <video> preview, and voice-only mode shows a ring voiceprint. A floating layer at the bottom of the stage shows the latest conversation captions (immersive, in the manner of Doubao/ChatGPT voice). A LIVE badge and the session duration sit at the top left. In video mode camera frames go upstream at ~1fps for the model to understand the video. Pure display component.
*/
import { useEffect, useRef, type RefObject } from 'react';
@@ -22,19 +20,19 @@ import { VoiceOrb } from './VoiceOrb';
import type { VizFrame, VoiceMessage } from '../../hooks/useRealtimeSession';
interface VideoStageProps {
- /** 是否视频模式(音频源含视频) */
+ /** Whether this is video mode (the audio source includes video) */
videoMode: boolean;
- /** 摄像头视频流(null 表示未开启) */
+ /** Camera video stream (null means not started) */
stream: MediaStream | null;
- /** 频谱帧的可变引用,透传给声纹画布(不进 React 状态,见 VizFrame) */
+ /** Mutable ref for a spectrum frame, passed through to the voiceprint canvas (not React state; see VizFrame) */
viz: RefObject<VizFrame>;
- /** 声纹是否活跃(聆听/播放) */
+ /** Whether the voiceprint is active (listening/playing) */
active: boolean;
- /** 是否在通话中(显示 LIVE) */
+ /** Whether a call is in progress (show LIVE) */
live: boolean;
- /** 会话时长(秒) */
+ /** Session duration (seconds) */
elapsed: number;
- /** 对话消息(底部浮层显示最新几条) */
+ /** Conversation messages (the bottom overlay shows the latest few) */
messages: VoiceMessage[];
rounds: number;
onOpenRecord: () => void;
@@ -51,7 +49,7 @@ interface VideoStageProps {
}
/**
- * 视频舞台。
+ * Video stage.
*/
export function VideoStage({
videoMode,
@@ -78,7 +76,7 @@ export function VideoStage({
const videoRef = useRef<HTMLVideoElement>(null);
const showVideo = videoMode && stream != null;
- // 流或 video 元素(重新挂载)变化时都重挂 srcObject,避免切换音频源后画面空白
+ // Reattach srcObject whenever the stream or the video element (remount) changes, so the picture is not blank after switching audio sources
useEffect(() => {
if (videoRef.current) videoRef.current.srcObject = stream;
}, [stream, showVideo]);
@@ -87,7 +85,7 @@ export function VideoStage({
return (
<div className="relative flex min-h-[18rem] w-full flex-1 items-center justify-center overflow-hidden bg-gradient-to-b from-primary/[0.06] to-card">
- {/* 背景呼吸氛围光 */}
+ {/* Background breathing ambient light */}
<span
aria-hidden
className="pointer-events-none absolute h-64 w-64 rounded-full bg-primary/15 blur-3xl motion-safe:animate-[map-breathe_4.5s_ease-in-out_infinite]"
@@ -158,7 +156,7 @@ export function VideoStage({
</div>
)}
- {/* 实时字幕浮层:最新两条对话 */}
+ {/* Realtime caption overlay: the latest two conversation turns */}
{subtitles && latest.length > 0 && (
<div
className="absolute inset-x-0 bottom-0 flex flex-col justify-end gap-1.5 px-4 pb-4 pt-10"
@@ -220,7 +218,7 @@ function TooltipIcon({
);
}
-/** 秒 → m:ss */
+/** Seconds → m:ss */
function fmtTime(sec: number): string {
const m = Math.floor(sec / 60);
const s = Math.floor(sec % 60);
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/VoiceOrb.tsx b/webdemo/frontend/src/pages/playground/components/experiences/VoiceOrb.tsx
index 8eef18c..6fecc74 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/VoiceOrb.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/VoiceOrb.tsx
@@ -1,9 +1,7 @@
/**
- * 环形声纹可视化(Canvas)。
+ * Ring voiceprint visualization (Canvas).
*
- * 用途:有辨识度的圆形声纹——中心辉光 + 一圈随频谱律动的渐变柱(按角度紫→蓝),待机时
- * 亮带沿圆周旋转流动、说话时各频段随能量放大;中心是随音量脉动的麦克风核心(lucide 图标)。
- * Canvas + rAF 命令式绘制,半径取 min(宽,高) 保证正圆;颜色取自 `--primary` 令牌,暗色自适配。
+ * Purpose: a recognizable circular voiceprint — a center glow plus a ring of gradient bars that move with the spectrum (purple→blue by angle). While idle a bright band flows around the circle; while speaking each band grows with its energy. The center is a microphone core that pulses with volume (a lucide icon). Drawn imperatively with Canvas + rAF. The radius is min(width, height) so it stays a circle; color comes from the `--primary` token and adapts in dark mode.
*/
import { useEffect, useRef, type RefObject } from 'react';
@@ -11,15 +9,15 @@ import { Mic } from 'lucide-react';
import type { VizFrame } from '../../hooks/useRealtimeSession';
interface VoiceOrbProps {
- /** 频谱帧的可变引用(60fps 直写,见 VizFrame);柱高与中心脉动都在画布 rAF 里直接读 */
+ /** Mutable ref for a spectrum frame (written directly at 60fps; see VizFrame); bar height and the center pulse are both read directly in the canvas rAF */
viz: RefObject<VizFrame>;
- /** 是否活跃(聆听/播放) */
+ /** Whether it is active (listening/playing) */
active: boolean;
className?: string;
}
/**
- * 环形声纹。
+ * Ring voiceprint.
*/
export function VoiceOrb({ viz, active, className }: VoiceOrbProps) {
const canvasRef = useRef<HTMLCanvasElement>(null);
@@ -59,19 +57,19 @@ export function VoiceOrb({ viz, active, className }: VoiceOrbProps) {
const act = activeRef.current;
const n = data.length || 40;
- // 中心辉光
+ // Center glow
const glow = ctx.createRadialGradient(cx, cy, size * 0.08, cx, cy, size * 0.5);
glow.addColorStop(0, `hsla(${c.h},${c.s}%,${c.l}%,0.2)`);
glow.addColorStop(1, `hsla(${c.h},${c.s}%,${c.l}%,0)`);
ctx.fillStyle = glow;
ctx.fillRect(0, 0, cw, ch);
- // 频谱柱环
+ // Spectrum bar ring
ctx.lineCap = 'round';
for (let i = 0; i < n; i += 1) {
const angle = (i / n) * Math.PI * 2 - Math.PI / 2;
const energy = data[i] ?? 0;
- // 待机:亮带沿圆周旋转流动;说话:叠加频段能量
+ // Idle: a bright band flows around the circle; speaking: add per-band energy
const idle = act ? 0.05 : 0.16 + 0.13 * Math.sin(phase * 1.6 - i * 0.5);
const len = Math.max(3, (idle + energy) * maxLen);
const cos = Math.cos(angle);
@@ -85,7 +83,7 @@ export function VoiceOrb({ viz, active, className }: VoiceOrbProps) {
ctx.stroke();
}
- // 中心核心随音量脉动:与柱环同帧直接写 style,避免为此每帧触发一次 React 渲染
+ // The center core pulses with volume: write style directly on the same frame as the bar ring, so this does not trigger a React render every frame
if (coreRef.current) {
coreRef.current.style.transform = `scale(${1 + Math.min(viz.current.level, 1) * 0.16})`;
}
@@ -100,7 +98,7 @@ export function VoiceOrb({ viz, active, className }: VoiceOrbProps) {
return (
<div className={`relative aspect-square ${className ?? ''}`}>
<canvas ref={canvasRef} className="absolute inset-0 h-full w-full" aria-hidden />
- {/* 中心核心:呼吸光环 + 渐变圆 + 麦克风,随音量脉动 */}
+ {/* Center core: breathing halo + gradient circle + microphone, pulsing with volume */}
<div className="absolute inset-0 flex items-center justify-center">
<span
aria-hidden
@@ -117,7 +115,7 @@ export function VoiceOrb({ viz, active, className }: VoiceOrbProps) {
);
}
-/** 读取 --primary 设计令牌(HSL 三元组)为数值 */
+/** Read the --primary design token (an HSL triple) as numbers */
function readPrimaryHsl(): { h: number; s: number; l: number } {
const raw = getComputedStyle(document.documentElement).getPropertyValue('--primary').trim();
const m = raw.match(/([\d.]+)\s+([\d.]+)%\s+([\d.]+)%/);
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/VoiceSelector.test.tsx b/webdemo/frontend/src/pages/playground/components/experiences/VoiceSelector.test.tsx
index 92a9524..0464994 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/VoiceSelector.test.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/VoiceSelector.test.tsx
@@ -15,7 +15,7 @@ const SAVED_VOICE = {
};
beforeAll(() => {
- // Radix Select 在真实浏览器依赖 Pointer Capture;jsdom 没有该 API,需要最小兼容垫片。
+ // Radix Select depends on Pointer Capture in a real browser; jsdom does not have that API, so a minimal compatibility shim is needed.
HTMLElement.prototype.hasPointerCapture = () => false;
HTMLElement.prototype.setPointerCapture = () => undefined;
HTMLElement.prototype.releasePointerCapture = () => undefined;
diff --git a/webdemo/frontend/src/pages/playground/components/experiences/VoiceSelector.tsx b/webdemo/frontend/src/pages/playground/components/experiences/VoiceSelector.tsx
index 90e4360..272b4b2 100644
--- a/webdemo/frontend/src/pages/playground/components/experiences/VoiceSelector.tsx
+++ b/webdemo/frontend/src/pages/playground/components/experiences/VoiceSelector.tsx
@@ -1,7 +1,7 @@
/**
- * 可搜索的音色选择器。
+ * Searchable voice selector.
*
- * 用途:按场景在预置音色与当前用户保存的私有音色之间选择;名称和业务 ID 都可快速过滤。
+ * Purpose: choose, by scene, between preset voices and private voices saved by the current user; both the name and the business ID can be filtered quickly.
*/
import { Search } from 'lucide-react';
@@ -12,7 +12,7 @@ import type { MapVoiceResource } from '@/api/map';
export interface VoiceSelectorOption {
value: string;
label: string;
- /** 用于快速搜索的补充文本,例如预置音色的内部标识。 */
+ /** Extra text for quick search, for example a preset voice's internal identifier. */
searchText?: string;
}
@@ -21,7 +21,7 @@ interface VoiceSelectorProps {
onChange: (value: string) => void;
presetOptions: VoiceSelectorOption[];
savedVoices: MapVoiceResource[];
- /** 是否允许当前场景读取和展示用户私有音色。 */
+ /** Whether the current scene may read and show the user's private voices. */
allowSavedVoices?: boolean;
disabled?: boolean;
loading?: boolean;
@@ -33,9 +33,9 @@ interface VoiceSelectorProps {
}
/**
- * 可搜索的音色选择器。
- * @param props 音色目录、当前值和分组展示文案
- * @returns 预置与私有音色的可访问选择控件
+ * Searchable voice selector.
+ * @param props Voice catalog, current value, and group display copy
+ * @returns An accessible select control for preset and private voices
*/
export function VoiceSelector({
value,
@@ -73,7 +73,7 @@ export function VoiceSelector({
const empty = matchingPresets.length === 0 && matchingSaved.length === 0;
function handleChange(nextValue: string) {
- // 选择后立即关闭并清空检索词,下一次打开时始终展示完整目录。
+ // Close immediately after a selection and clear the query, so the next open always shows the full catalog.
setQuery('');
setOpen(false);
onChange(nextValue);
@@ -163,9 +163,9 @@ interface VoiceOptionGroupProps {
}
/**
- * 音色候选分组。
- * @param props 分组标题与候选项
- * @returns 分组化的音色列表
+ * A group of voice candidates.
+ * @param props Group title and candidates
+ * @returns A grouped voice list
*/
function VoiceOptionGroup({ label, children }: VoiceOptionGroupProps) {
return (
@@ -184,9 +184,9 @@ interface VoiceOptionProps {
}
/**
- * 单个音色候选项。
- * @param props 当前选中状态、展示内容和选择动作
- * @returns 可点击的音色行
+ * A single voice candidate.
+ * @param props Current selected state, display content, and selection action
+ * @returns A clickable voice row
*/
function VoiceOption({ active, label, detail, onSelect }: VoiceOptionProps) {
return (
@@ -207,11 +207,11 @@ function VoiceOption({ active, label, detail, onSelect }: VoiceOptionProps) {
}
/**
- * 判断音色名称或业务 ID 是否匹配搜索词。
- * @param label 音色展示名称
- * @param searchText 可选补充检索文本
- * @param query 已归一化的小写搜索词
- * @returns 是否应在当前候选中显示
+ * Decide whether a voice name or business ID matches the search query.
+ * @param label Voice display name
+ * @param searchText Optional extra search text
+ * @param query Normalized lowercase search query
+ * @returns Whether it should be shown among the current candidates
*/
function matchesVoiceSearch(label: string, searchText: string | undefined, query: string): boolean {
if (!query) return true;
@@ -219,11 +219,11 @@ function matchesVoiceSearch(label: string, searchText: string | undefined, query
}
/**
- * 解析当前值对应的展示名称。
- * @param value 当前选中的预置音色或私有音色 ID
- * @param presetOptions 预置音色目录
- * @param savedVoices 当前用户已保存的音色
- * @returns 用于触发按钮回显的音色名称
+ * Resolve the display name for the current value.
+ * @param value Currently selected preset-voice or private-voice ID
+ * @param presetOptions Preset-voice catalog
+ * @param savedVoices Voices already saved by the current user
+ * @returns Voice name shown back on the trigger button
*/
function findVoiceLabel(
value: string,
diff --git a/webdemo/frontend/src/pages/playground/hooks/__tests__/useChat.test.tsx b/webdemo/frontend/src/pages/playground/hooks/__tests__/useChat.test.tsx
index 5ae7e2c..141d70b 100644
--- a/webdemo/frontend/src/pages/playground/hooks/__tests__/useChat.test.tsx
+++ b/webdemo/frontend/src/pages/playground/hooks/__tests__/useChat.test.tsx
@@ -45,7 +45,7 @@ describe('useChat', () => {
}
it('开启联网时占位消息即刻进入搜索态,不等第一个工具事件', () => {
- // 从发请求到首个 tool_status 有几百毫秒空窗,占位就亮搜索态才不会出现"什么都没有"的一帧
+ // There are a few hundred milliseconds of gap from sending the request to the first tool_status; the placeholder must show the search state or there is a frame of "nothing at all"
const result = sendWith(true);
expect(result.current.messages[1]).toMatchObject({
diff --git a/webdemo/frontend/src/pages/playground/hooks/__tests__/useChatCompletion.test.tsx b/webdemo/frontend/src/pages/playground/hooks/__tests__/useChatCompletion.test.tsx
index 93dca9d..3c67a75 100644
--- a/webdemo/frontend/src/pages/playground/hooks/__tests__/useChatCompletion.test.tsx
+++ b/webdemo/frontend/src/pages/playground/hooks/__tests__/useChatCompletion.test.tsx
@@ -59,7 +59,7 @@ describe('useChatCompletion', () => {
result.current.startCompletion(history, 'assistant-1');
});
- // 该 mock 只透传 locale,第二个参数(userLocation)由实现自行携带。
+ // This mock only forwards locale; the second argument (userLocation) is carried by the implementation itself.
expect(collectPlaygroundRuntimeContext).toHaveBeenCalledWith('zh-CN');
expect(streamChat.mock.calls[0]?.[5]).toEqual(runtimeContext);
});
diff --git a/webdemo/frontend/src/pages/playground/hooks/__tests__/useDocumentUpload.test.ts b/webdemo/frontend/src/pages/playground/hooks/__tests__/useDocumentUpload.test.ts
index 6b28d58..ff5361f 100644
--- a/webdemo/frontend/src/pages/playground/hooks/__tests__/useDocumentUpload.test.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/__tests__/useDocumentUpload.test.ts
@@ -1,4 +1,4 @@
-/** 远端上传校验、重试、取消和过期响应隔离,均不访问真实资产服务。 */
+/** Remote-upload validation, retry, cancellation, and stale-response isolation, none of which touch the real asset service. */
import { act, renderHook } from '@testing-library/react';
import { createElement, type PropsWithChildren } from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
diff --git a/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageParse.test.tsx b/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageParse.test.tsx
index 0f9640a..bef4b66 100644
--- a/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageParse.test.tsx
+++ b/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageParse.test.tsx
@@ -1,4 +1,4 @@
-/** 独立 OCR v3 识别生命周期测试。 */
+/** Standalone OCR v3 recognition lifecycle test. */
import { act, renderHook, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { Attachment } from '../../types';
diff --git a/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageParseDraft.test.ts b/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageParseDraft.test.ts
index 129e111..9eef1b6 100644
--- a/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageParseDraft.test.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageParseDraft.test.ts
@@ -1,5 +1,5 @@
/**
- * 校对草稿单测:改稿后进入 dirty、还原回到结果、新结果覆盖旧草稿。
+ * Proofreading-draft unit tests: an edit enters dirty, restore returns to the result, and a new result replaces the old draft.
*/
import { act, renderHook } from '@testing-library/react';
@@ -36,7 +36,7 @@ describe('useImageParseDraft', () => {
});
it('follows a new parse result instead of keeping a stale draft', () => {
- // 重新解析或换图后旧草稿已无意义,留着会让用户以为改动仍对应当前这张图。
+ // After parsing again or changing the image, the old draft is meaningless; leaving it would make the user think the edit still applies to the current image.
const { result, rerender } = renderHook(({ md }) => useImageParseDraft(md), {
initialProps: { md: '第一版' },
});
diff --git a/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageParseExampleMerge.test.ts b/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageParseExampleMerge.test.ts
index dc07de5..8210bc9 100644
--- a/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageParseExampleMerge.test.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageParseExampleMerge.test.ts
@@ -30,7 +30,7 @@ function block(
};
}
-/** 两页示例:第一页表格在页末,第二页表格在页首且重复表头。 */
+/** Two-page example: the first page's table is at the end of the page, and the second page's table is at the start and repeats the header. */
function snapshot(page: number, table: string, atBottom: boolean): ImageParseSnapshot {
const header = `页眉${page}`;
const footer = `${page}`;
diff --git a/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageParseKieTour.test.tsx b/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageParseKieTour.test.tsx
index 0e33f3e..2c92175 100644
--- a/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageParseKieTour.test.tsx
+++ b/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageParseKieTour.test.tsx
@@ -101,7 +101,7 @@ describe('关键信息抽取新手引导', () => {
expect(driverMock.instances[0].isActive()).toBe(true);
expect(driverMock.instances[0].getActiveIndex()).toBe(1);
- // 模拟用户阅读字段说明后点击“下一步”,停留在开始抽取步骤。
+ // Simulate the user reading the field description and clicking "Next", staying on the start-extraction step.
act(() => driverMock.instances[0].moveNext());
rerender({ ready: false, hasDocument: true, resultReady: false });
expect(driverMock.instances[0].isActive()).toBe(false);
diff --git a/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageParseScrollSync.test.tsx b/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageParseScrollSync.test.tsx
index 5b33d68..dac1b50 100644
--- a/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageParseScrollSync.test.tsx
+++ b/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageParseScrollSync.test.tsx
@@ -105,7 +105,7 @@ describe('useImageParseScrollSync', () => {
node.scrollTop = 200;
act(() => result.current.onResultScroll(scrollEvent(node)));
expect(result.current.originProps.scrollProgress).toBe(0.25);
- // 高度变化后的确认不能反向覆盖结果栏的位置。
+ // Confirmation after a height change must not overwrite the result column's position in the other direction.
Object.defineProperty(node, 'scrollHeight', { value: 2000 });
act(() => result.current.originProps.onScrollProgress(0.25));
expect(node.scrollTop).toBe(200);
diff --git a/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageParseTourTargets.test.tsx b/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageParseTourTargets.test.tsx
index 2cb834d..927b680 100644
--- a/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageParseTourTargets.test.tsx
+++ b/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageParseTourTargets.test.tsx
@@ -12,7 +12,7 @@ vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
-/** 使用真实 driver.js 验证选择平台示例后的目标挂载与自动前进,不调用 OCR。 */
+/** Use real driver.js to verify target mounting and automatic advance after choosing a platform example, without calling OCR. */
function TourWorkspace({
existing = false,
settingsReady = true,
@@ -115,7 +115,7 @@ describe('文档解析引导真实目标回归', () => {
expect(screen.getByRole('switch', { name: /imageParseUpright/ })).toBeVisible();
expect(document.body).toHaveClass('map-tour-settings-showcase');
expect(screen.getByRole('button', { name: 'imageParseTourNext' })).toBeVisible();
- // 示例步骤的目标已卸载,回退按钮应禁用,避免落到无目标的居中遮罩。
+ // The example step's target has unmounted; the back button should be disabled, so it does not land on a centered mask with no target.
await waitFor(() => expect(document.querySelector('.driver-popover-prev-btn')).toBeDisabled());
fireEvent.click(document.querySelector('.driver-popover-prev-btn')!);
await expectStep(
@@ -219,7 +219,7 @@ describe('文档解析引导真实目标回归', () => {
const overlay = () => document.querySelector('.driver-overlay path')!.getAttribute('d');
const popover = document.querySelector<HTMLElement>('.driver-popover')!;
await waitFor(() => expect(overlay()).toContain('M102,96 h156'));
- // 等 driver 的 400ms 切步动画与一次性 refresh 结束,避免它掩盖后续布局偏移。
+ // Wait for driver.js's 400ms step-change animation and the one-shot refresh to finish, so they do not hide a later layout shift.
await act(async () => new Promise((resolve) => window.setTimeout(resolve, 500)));
const initialPosition = popover.style.cssText;
diff --git a/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageZoom.test.tsx b/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageZoom.test.tsx
index 03abece..fe285f5 100644
--- a/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageZoom.test.tsx
+++ b/webdemo/frontend/src/pages/playground/hooks/__tests__/useImageZoom.test.tsx
@@ -1,9 +1,9 @@
/**
- * 图片缩放接线单测:滚轮改倍数、合帧、阻止页面滚动、按钮与拖拽。
+ * Unit tests for image-zoom wiring: the wheel changes scale, frames are coalesced, page scroll is prevented, and buttons and dragging work.
*
- * 这里测的是「事件真的到得了 hook」这一层,而不是几何算式(那在 utils/imageZoom 的单测里)。
- * 滚轮监听是 useWheelGesture 以非 passive 方式挂在 setViewport 给到的节点上的,
- * 一旦调用方没把 ref 接上,滚轮缩放会整个静默失效——这组测试就是为了让那种回归立刻可见。
+ * What is tested here is the layer "the event really reaches the hook", not the geometry formulas (those are in the utils/imageZoom unit tests).
+ * The wheel listener is attached by useWheelGesture, non-passive, on the node setViewport provides.
+ * If the caller never connects the ref, wheel zoom fails silently — this set of tests exists so that regression is visible immediately.
*/
import { useCallback } from 'react';
@@ -12,7 +12,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import { useImageZoom } from '../useImageZoom';
import { MAX_SCALE, MIN_SCALE } from '../../utils/imageZoom';
-/** 按 hook 约定接线的最小看图器:视口挂 setViewport,内容挂 setContent。 */
+/** Minimal image viewer wired the way the hook expects: the viewport takes setViewport, and the content takes setContent. */
function Viewer({ document = false }: { document?: boolean }) {
const zoom = useImageZoom({ fitWidth: document });
const { setViewport, setContent } = zoom;
@@ -63,7 +63,7 @@ function Viewer({ document = false }: { document?: boolean }) {
);
}
-/** 滚轮按 requestAnimationFrame 合帧,所以断言前要把这一帧放过去。 */
+/** The wheel coalesces frames on requestAnimationFrame, so that frame has to be flushed before an assertion. */
async function flushFrame() {
await act(async () => {
await new Promise<void>((resolve) => {
@@ -73,8 +73,8 @@ async function flushFrame() {
}
/**
- * 在视口上派发一个原生 wheel(React 的合成 wheel 是 passive 的,测不到真实路径)。
- * @returns 事件是否被 preventDefault
+ * Dispatch a native wheel on the viewport (React's synthetic wheel is passive and cannot exercise the real path).
+ * @returns whether the event was preventDefault'd
*/
function wheel(
node: HTMLElement,
@@ -111,13 +111,13 @@ describe('useImageZoom 滚轮', () => {
render(<Viewer />);
const viewport = screen.getByTestId('viewport');
- // WHEEL_STEP=0.0015:一格 100px 对应 15%
+ // WHEEL_STEP=0.0015: one notch of 100px corresponds to 15%
wheel(viewport, -100, 0, { ctrlKey: true });
await flushFrame();
expect(scale()).toBeCloseTo(1.15, 6);
- // 缩放按比例乘,所以反向滚同样格数不会精确回到 1(1.15 × 0.85 = 0.9775)。
- // 这是刻意的:等比缩放在任何倍数下手感一致,回到贴合走「还原」而不是数格数。
+ // Zoom multiplies by a ratio, so rolling the same number of notches the other way does not land exactly on 1 (1.15 × 0.85 = 0.9775).
+ // This is deliberate: proportional zoom feels the same at any scale, and returning to the fit uses "reset" rather than counting notches.
wheel(viewport, 100, 0, { ctrlKey: true });
await flushFrame();
expect(scale()).toBeCloseTo(0.9775, 6);
@@ -127,8 +127,8 @@ describe('useImageZoom 滚轮', () => {
render(<Viewer />);
const viewport = screen.getByTestId('viewport');
- // 一次滚动能打出上百个事件。合帧后按累计增量 -200 算一次(1.3),
- // 而不是逐个复利(1.15² ≈ 1.3225)——差值就是合帧生效的证据。
+ // One scroll can fire hundreds of events. After coalescing, the accumulated delta of -200 is applied once (1.3),
+ // rather than compounded one by one (1.15² ≈ 1.3225) — the difference is the evidence that coalescing took effect.
wheel(viewport, -100, 0, { ctrlKey: true });
wheel(viewport, -100, 0, { ctrlKey: true });
await flushFrame();
@@ -143,7 +143,7 @@ describe('useImageZoom 滚轮', () => {
it('converts line-mode deltas so Firefox has the same feel', async () => {
render(<Viewer />);
- // 行模式一格 deltaY 只有 ±3,按 LINE_HEIGHT=16 折算成 48px。
+ // In line mode one notch of deltaY is only ±3, converted at LINE_HEIGHT=16 into 48px.
wheel(screen.getByTestId('viewport'), -3, 1, { ctrlKey: true });
await flushFrame();
expect(scale()).toBeCloseTo(1.072, 6);
@@ -259,10 +259,10 @@ describe('useImageZoom 按钮与拖拽', () => {
fireEvent.pointerDown(viewport, { button: 0, clientX: 100, clientY: 100, pointerId: 1 });
fireEvent.pointerMove(viewport, { clientX: 130, clientY: 60, pointerId: 1 });
- // translate 在最外层,拖多少走多少。
+ // translate is outermost, so it moves by however much it is dragged.
expect(screen.getByTestId('transform').textContent).toContain('translate(30px, -40px)');
- // 松手不归位:拖到哪停哪。
+ // Releasing does not snap back: it stops where it was dragged.
fireEvent.pointerUp(viewport, { clientX: 130, clientY: 60, pointerId: 1 });
expect(screen.getByTestId('transform').textContent).toContain('translate(30px, -40px)');
});
diff --git a/webdemo/frontend/src/pages/playground/hooks/__tests__/useMessageVersions.test.tsx b/webdemo/frontend/src/pages/playground/hooks/__tests__/useMessageVersions.test.tsx
index 2081f2e..6d2cee3 100644
--- a/webdemo/frontend/src/pages/playground/hooks/__tests__/useMessageVersions.test.tsx
+++ b/webdemo/frontend/src/pages/playground/hooks/__tests__/useMessageVersions.test.tsx
@@ -1,5 +1,5 @@
/**
- * useMessageVersions hook 单测:regenerate 编排与 feedback/version 委托。
+ * Unit tests for the useMessageVersions hook: regenerate orchestration and feedback/version delegation.
*/
import { act, renderHook } from '@testing-library/react';
diff --git a/webdemo/frontend/src/pages/playground/hooks/imageZoomTypes.ts b/webdemo/frontend/src/pages/playground/hooks/imageZoomTypes.ts
index ab10ec9..36c0881 100644
--- a/webdemo/frontend/src/pages/playground/hooks/imageZoomTypes.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/imageZoomTypes.ts
@@ -2,7 +2,7 @@ import type * as React from 'react';
import type { imageRasterView } from '../utils/imageZoom';
-/** 视图状态与交互接线。 */
+/** View state and interaction wiring. */
export interface ImageZoom {
scale: number;
rotation: number;
diff --git a/webdemo/frontend/src/pages/playground/hooks/useAnswerProcessDisclosure.ts b/webdemo/frontend/src/pages/playground/hooks/useAnswerProcessDisclosure.ts
index 2b7e840..4dc89b7 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useAnswerProcessDisclosure.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useAnswerProcessDisclosure.ts
@@ -1,32 +1,32 @@
/**
- * 回答过程折叠区的展开与滚动跟随状态。
+ * Expand state and scroll-follow state for the answer-process disclosure.
*
- * 用途:把「什么时候自动展开」「滚动要不要跟着输出走」这两件纯交互的事从视图里抽出来。
- * 自动展开有两个来源(流式期间首次出现过程内容、失败态首次出现),两者共用同一个
- * 「用户手动操作过就不再抢占」的闸门。
+ * Purpose: pull the two purely interactive questions "when to expand automatically" and "whether scroll should follow the output" out of the view.
+ * Automatic expand has two sources (process content appearing for the first time while streaming, and the failure state appearing for the first time), and they share one
+ * gate: once the user has operated it manually, neither may take over again.
*/
import { useEffect, useMemo, useRef, useState, type KeyboardEvent, type UIEvent } from 'react';
-/** 判定"仍贴着底部"的容差:差这点距离不算用户主动往回翻。 */
+/** Tolerance for judging "still stuck to the bottom": a gap this small does not count as the user scrolling back on purpose. */
const STICK_THRESHOLD_PX = 32;
interface UseAnswerProcessDisclosureInput {
- /** 是否仍在流式生成。 */
+ /** Whether generation is still streaming. */
streaming: boolean;
- /** 流式期间是否已出现可展示的过程内容(思考文本或工具活动)。 */
+ /** Whether displayable process content (reasoning text or tool activity) has appeared during streaming. */
hasProcess: boolean;
- /** 是否有工具失败或被中断。 */
+ /** Whether a tool failed or was interrupted. */
failed: boolean;
}
-/** 过程滚动区的跟随控制:一个引用稳定的对象,可直接进 effect 依赖。 */
+/** Follow control for the process scroll area: one referentially stable object that can go straight into an effect dependency. */
export interface ProcessFollow {
/**
- * 此刻是否应该把滚动区贴回底部。
+ * Whether the scroll area should be stuck back to the bottom right now.
*
- * 必须在 effect 里调用、不要在渲染期取值:跟随开关与「是否仍贴着底」都存在 ref 里,
- * 渲染期读既拿不到本帧最新值,也会让每个读取点各自快照出一份不一致的状态。
+ * Call this inside an effect, and do not read it during render: both the follow switch and "still stuck to the bottom" live in refs.
+ * A render-time read neither sees this frame's latest value, nor avoids each read site snapshotting its own inconsistent state.
*/
shouldFollow: () => boolean;
onScroll: (event: UIEvent<HTMLDivElement>) => void;
@@ -38,17 +38,17 @@ export interface ProcessFollow {
interface UseAnswerProcessDisclosureResult {
expanded: boolean;
toggle: () => void;
- /** 滚动跟随控制,连同摊给滚动容器的事件处理器。 */
+ /** Scroll-follow control, together with the event handlers spread onto the scroll container. */
follow: ProcessFollow;
}
-/** 会被视为"用户想自己滚"的按键。 */
+/** Keys treated as "the user wants to scroll themselves". */
const SCROLL_KEYS = new Set(['ArrowDown', 'ArrowUp', 'End', 'Home', 'PageDown', 'PageUp', ' ']);
/**
- * 管理过程折叠区的展开状态与滚动跟随。
- * @param input 流式状态、是否已有过程内容、是否失败
- * @returns 展开态、切换函数与滚动区所需的跟随控制
+ * Manage expand state and scroll follow for the process disclosure.
+ * @param input streaming state, whether process content already exists, and whether it failed
+ * @returns the expanded state, the toggle function, and the follow control the scroll area needs
*/
export function useAnswerProcessDisclosure({
streaming,
@@ -59,13 +59,13 @@ export function useAnswerProcessDisclosure({
const stickRef = useRef(true);
const scrollIntentRef = useRef(false);
const followRef = useRef(streaming && hasProcess);
- // 唯一的"别再抢占"闸门:两条自动展开路径都读它,用户手动收起后谁都不许再打开
+ // The only "do not take over again" gate: both automatic-expand paths read it, and after the user collapses it manually neither may open it again
const manuallyToggledRef = useRef(false);
const autoOpenedRef = useRef(streaming && hasProcess);
const previousStreamingRef = useRef(streaming);
const previousFailedRef = useRef(failed);
- // 新一轮流式开始:把上一轮攒下的跟随状态与闸门全部复位
+ // A new streaming turn starts: reset all of the follow state and the gate accumulated in the previous turn
useEffect(() => {
const phaseChanged = previousStreamingRef.current !== streaming;
previousStreamingRef.current = streaming;
@@ -77,12 +77,12 @@ export function useAnswerProcessDisclosure({
manuallyToggledRef.current = false;
}, [streaming]);
- // 流式期间首次出现过程内容时自动展开一次
+ // Expand once automatically when process content appears for the first time during streaming
useEffect(() => {
if (!streaming) {
autoOpenedRef.current = false;
- // 输出结束就交还滚动位置:之后任何高度变化(切换回答版本、图片加载完)都不该
- // 再把过程区拽回底部,否则用户刚翻到的那一段会被抢走。
+ // When output ends, give the scroll position back: any later height change (switching answer versions, an image finishing load) must not
+ // pull the process area back to the bottom, or the passage the user just scrolled to would be taken away.
followRef.current = false;
return;
}
@@ -92,13 +92,13 @@ export function useAnswerProcessDisclosure({
followRef.current = true;
stickRef.current = true;
if (manuallyToggledRef.current) return;
- // 延到下一个宏任务再展开:首段内容与展开动画同帧触发时,grid-template-rows 过渡
- // 会从"内容已经撑满"的状态起步,看上去像是直接跳出来而不是展开
+ // Expand on the next macrotask: when the first content and the expand animation fire in the same frame, the grid-template-rows transition
+ // starts from a state where the content is already full, and it looks like it jumped out instead of expanding
const timer = setTimeout(() => setExpanded(true), 0);
return () => clearTimeout(timer);
}, [hasProcess, streaming]);
- // 失败态首次出现时自动展开,让用户不必多点一次就能看到失败在哪一步
+ // Expand automatically the first time the failure state appears, so the user can see which step failed without an extra click
useEffect(() => {
const justFailed = !previousFailedRef.current && failed;
previousFailedRef.current = failed;
@@ -106,16 +106,16 @@ export function useAnswerProcessDisclosure({
}, [failed]);
/*
- 整个跟随控制收进一个空依赖的 useMemo:ref 本身引用稳定,所以空依赖是成立的,
- 而对象引用稳定才能安全地进滚动区 layout effect 的依赖数组——每渲染新建一个对象,
- 那个 effect 就会每帧重跑一次,把用户往回翻的滚动位置一并抢走。
+ The whole follow control is kept in a useMemo with an empty dependency list: the ref itself is referentially stable, so the empty list is valid,
+ and a stable object reference is what can safely enter the dependency array of the scroll area's layout effect — a new object on every render
+ would rerun that effect every frame and take away the scroll position the user had moved back to.
*/
const follow = useMemo<ProcessFollow>(
() => ({
shouldFollow: () => followRef.current && stickRef.current,
onScroll: (event) => {
- // 只认由 wheel/touch/按键触发的滚动:自动跟随自己写 scrollTop 也会触发 onScroll,
- // 不加这道闸门会被自己的跟随动作误判成"用户往回翻了",跟随立刻失效
+ // Count only scroll caused by wheel, touch, or keys: follow writing scrollTop itself also fires onScroll,
+ // and without this gate its own follow action would be mistaken for "the user scrolled back", and follow would stop immediately
if (!scrollIntentRef.current) return;
const element = event.currentTarget;
const distance = element.scrollHeight - element.scrollTop - element.clientHeight;
diff --git a/webdemo/frontend/src/pages/playground/hooks/useAttachmentPreview.ts b/webdemo/frontend/src/pages/playground/hooks/useAttachmentPreview.ts
index 65d94cc..f7099b8 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useAttachmentPreview.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useAttachmentPreview.ts
@@ -2,7 +2,7 @@ import { useEffect } from 'react';
import type { Attachment } from '../types';
-/** 管理 Blob URL 生命周期,替换或卸载附件时释放大文件内存。 */
+/** Manage Blob URL lifetime, and release large-file memory when an attachment is replaced or unmounted. */
export function useAttachmentPreview(attachment?: Attachment) {
const source = attachment?.dataUrl;
useEffect(() => {
diff --git a/webdemo/frontend/src/pages/playground/hooks/useAutoScroll.test.tsx b/webdemo/frontend/src/pages/playground/hooks/useAutoScroll.test.tsx
index 19caabb..3ded50c 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useAutoScroll.test.tsx
+++ b/webdemo/frontend/src/pages/playground/hooks/useAutoScroll.test.tsx
@@ -8,7 +8,7 @@ interface AutoScrollHarnessProps {
turnKey: string;
}
-/** 挂载自动滚动 hook,供测试真实 ref 与滚动事件。 */
+/** Mount the auto-scroll hook, so tests can use a real ref and scroll events. */
function AutoScrollHarness({ updateKey, turnKey }: AutoScrollHarnessProps) {
const { scrollRef, contentRef, onScroll, onWheel, onTouchMove, onKeyDown, onPointerDown } =
useAutoScroll(updateKey, turnKey);
@@ -33,7 +33,7 @@ interface ScrollMetrics {
clientHeight: number;
}
-/** 为 jsdom 滚动容器提供可控尺寸。 */
+/** Provide a controllable size for a jsdom scroll container. */
function setScrollMetrics(element: HTMLElement, metrics: ScrollMetrics) {
Object.defineProperties(element, {
scrollHeight: {
@@ -47,7 +47,7 @@ function setScrollMetrics(element: HTMLElement, metrics: ScrollMetrics) {
});
}
-/** 触发一次内容尺寸变化。 */
+/** Trigger one content-size change. */
function notifyResize(callback: ResizeObserverCallback | undefined, target: Element) {
callback?.([{ target } as unknown as ResizeObserverEntry], {} as ResizeObserver);
}
@@ -155,7 +155,7 @@ describe('useAutoScroll', () => {
rerender(<AutoScrollHarness updateKey="content-updated" turnKey="turn-1" />);
expect(scroller.scrollTop).toBe(800);
- // 点开一处折叠区:内容长高了,但视口不许动,否则刚点的那一行会被顶出屏幕顶部
+ // Opening one disclosure: the content grows taller, but the viewport must not move, or the row just clicked would be pushed off the top of the screen
fireEvent.pointerDown(scroller);
metrics.scrollHeight = 1_400;
notifyResize(resizeCallback, content);
@@ -174,7 +174,7 @@ describe('useAutoScroll', () => {
rerender(<AutoScrollHarness updateKey="content-updated" turnKey="turn-1" />);
fireEvent.pointerDown(scroller);
- // 免疫只覆盖那一下点击带来的形变,不是永久关掉跟随
+ // The immunity covers only the deformation from that one click, and does not turn follow off permanently
vi.advanceTimersByTime(700);
metrics.scrollHeight = 1_400;
diff --git a/webdemo/frontend/src/pages/playground/hooks/useAutoScroll.ts b/webdemo/frontend/src/pages/playground/hooks/useAutoScroll.ts
index 9a2b179..6f96d73 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useAutoScroll.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useAutoScroll.ts
@@ -1,29 +1,29 @@
/**
- * 消息流自动吸底 hook。
+ * Hook that sticks the message stream to the bottom automatically.
*
- * 用途:流式增量到来时把滚动容器自动滚到底部;但用户主动上滚阅读历史时停止吸底,
- * 直到用户重新滚回底部。避免高频 setState 下打断阅读。
+ * Purpose: when a streaming increment arrives, scroll the container to the bottom; but when the user scrolls up to read history, stop sticking,
+ * until the user scrolls back to the bottom. Avoid interrupting reading under high-frequency setState.
*/
import { useCallback, useEffect, useLayoutEffect, useRef, type KeyboardEvent } from 'react';
-/** 距底部多少像素内视为「贴底」 */
+/** Within how many pixels of the bottom counts as "stuck to the bottom" */
const STICK_THRESHOLD = 48;
-/** 一次滚轮/触摸手势会连发多帧 scroll,这段时间内都算同一次用户滚动 */
+/** One wheel or touch gesture fires several frames of scroll; that whole interval counts as one user scroll */
const USER_SCROLL_INTENT_MS = 180;
/**
- * 用户点击后多久内不因内容高度变化吸底。
+ * How long after a user click a content-height change must not stick to the bottom.
*
- * 要盖住「点开思考过程」这一下的全部形变:折叠面板的 grid 过渡 220ms,里面的过程滚动区
- * 还有一段 max-height 300ms,两者不同时起止。取 600ms 留余量。
+ * It has to cover the whole deformation of "opening the reasoning process": the disclosure's grid transition is 220ms, and the process scroll area inside
+ * has another max-height of 300ms, and the two do not start and end together. 600ms leaves a margin.
*/
const INTERACTION_HOLD_MS = 600;
const SCROLL_KEYS = new Set(['ArrowDown', 'ArrowUp', 'End', 'Home', 'PageDown', 'PageUp', ' ']);
/**
- * @param updateKey 触发吸底的内容更新标识
- * @param turnKey 新一轮对话标识;变化时恢复自动跟随并立即滚到底部
- * @returns 滚动容器 ref、内容 ref 与滚动事件处理器
+ * @param updateKey content-update id that triggers sticking to the bottom
+ * @param turnKey id of a new conversation turn; when it changes, restore automatic follow and scroll to the bottom immediately
+ * @returns scroll-container ref, content ref, and the scroll event handler
*/
export function useAutoScroll(updateKey: unknown, turnKey: unknown) {
const scrollRef = useRef<HTMLDivElement>(null);
@@ -38,7 +38,7 @@ export function useAutoScroll(updateKey: unknown, turnKey: unknown) {
element.scrollTop = element.scrollHeight;
}, []);
- // 只有明确的滚轮、触摸或键盘输入才改变跟随状态,忽略布局变化引发的 scroll。
+ // Only an explicit wheel, touch, or keyboard input changes follow state; ignore scroll caused by a layout change.
const onScroll = useCallback(() => {
if (!userScrollPendingRef.current) return;
const el = scrollRef.current;
@@ -54,19 +54,19 @@ export function useAutoScroll(updateKey: unknown, turnKey: unknown) {
[markUserScrollIntent],
);
- // 用户发起新一轮对话时,无论此前是否上滚,都应立即回到最新消息。
+ // When the user starts a new turn, return to the latest message immediately, whether or not they had scrolled up.
useLayoutEffect(() => {
stickRef.current = true;
scrollToBottom();
}, [scrollToBottom, turnKey]);
- // 流式增量或工具状态更新后,在浏览器绘制前保持吸底。
+ // After a streaming increment or a tool-status update, stay stuck to the bottom before the browser paints.
useLayoutEffect(() => {
if (!stickRef.current) return;
scrollToBottom();
}, [scrollToBottom, updateKey]);
- // Markdown、表格、引用和折叠内容可能在提交后继续改变高度,需监听真实内容尺寸。
+ // Markdown, tables, citations, and disclosure content may keep changing height after commit, so the real content size has to be observed.
useEffect(() => {
const content = contentRef.current;
if (!content || typeof ResizeObserver === 'undefined') return;
@@ -74,10 +74,10 @@ export function useAutoScroll(updateKey: unknown, turnKey: unknown) {
const observer = new ResizeObserver(() => {
if (!stickRef.current) return;
/*
- 用户刚点过:这一次高度变化是他自己按出来的(展开思考过程、切换回答版本、展开长表格),
- 吸底会把刚点的那一行连同它上方的内容一起顶出视口顶部——「点开」的预期是内容向下长
- 出来,而不是页面往上蹿。流式增量不走这条路(由 updateKey 的 layout effect 吸底),
- 所以押住这里不会让跟随输出变迟钝。
+ The user just clicked: this height change is one they pressed themselves (expanding reasoning, switching an answer version, expanding a long table).
+ Sticking to the bottom would push the row just clicked, together with the content above it, off the top of the viewport — the expectation of "opening" is that content grows
+ downward, not that the page jumps upward. Streaming increments do not take this path (updateKey's layout effect sticks to the bottom),
+ so holding here does not make following the output feel sluggish.
*/
if (interactionHoldRef.current) return;
scrollToBottom();
@@ -98,14 +98,14 @@ export function useAutoScroll(updateKey: unknown, turnKey: unknown) {
}
/**
- * 一个到点自动失效的布尔标记。
+ * A boolean flag that clears itself when its time is up.
*
- * 两处用途(识别用户滚动手势、押住点击引发的重排)都要「标一下、过一会儿自己清掉」,
- * 且都必须存 ref 不能存 state:它们在 layout effect 与 ResizeObserver 回调里读,
- * 改成 state 会因重渲染把 observer 整个重建。
+ * Both uses (recognizing a user scroll gesture, and holding back a reflow caused by a click) need "mark it, then clear it after a while",
+ * and both must live in a ref rather than state: they are read inside a layout effect and a ResizeObserver callback,
+ * and turning them into state would rebuild the whole observer on re-render.
*
- * @param durationMs 标记有效时长
- * @returns [标记 ref, 打标记函数]
+ * @param durationMs how long the flag stays valid
+ * @returns [flag ref, function that sets the flag]
*/
function useExpiringFlag(durationMs: number) {
const activeRef = useRef(false);
diff --git a/webdemo/frontend/src/pages/playground/hooks/useCamera.ts b/webdemo/frontend/src/pages/playground/hooks/useCamera.ts
index 38c8ba1..9a1890b 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useCamera.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useCamera.ts
@@ -1,32 +1,32 @@
/**
- * 摄像头预览 Hook。
+ * Camera preview hook.
*
- * 用途:为「实时语音」的全双工通话提供真实的摄像头预览——请求 getUserMedia 视频流并以
- * state 暴露,由组件用 useEffect 挂到自己的 <video>(避免「设 srcObject 时元素尚未挂载」
- * 的时序问题)。video 模式下该流既作本地预览,也由会话按 ~1fps 抽帧上行给模型做视频理解。
- * start() 同时返回流,供开始通话时同步取用;组件卸载或 stop 时释放视频轨。
+ * Purpose: provide a real camera preview for full-duplex calls in "realtime voice" — request a getUserMedia video stream and expose it as
+ * state, and the component attaches it to its own <video> in useEffect (avoiding the timing problem of "setting srcObject before the element is mounted").
+ * In video mode that stream is both the local preview and the frames the session grabs at ~1fps and sends up for the model to understand the video.
+ * start() also returns the stream, so the call can take it synchronously when it starts; the video track is released when the component unmounts or stop is called.
*/
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
interface UseCameraResult {
- /** 当前视频流(供组件挂到 <video>),未开启为 null */
+ /** Current video stream (for the component to attach to <video>); null when it is off */
stream: MediaStream | null;
- /** 摄像头是否已开启 */
+ /** Whether the camera is on */
active: boolean;
- /** 用户可见错误文案 */
+ /** User-visible error copy */
error?: string;
- /** 开启摄像头(需用户手势触发);成功返回流,失败返回 null */
+ /** Turn the camera on (must be triggered by a user gesture); return the stream on success, or null on failure */
start: () => Promise<MediaStream | null>;
- /** 切换前后摄像头;未开启时无操作 */
+ /** Switch between front and back cameras; no-op when the camera is off */
flip: () => Promise<MediaStream | null>;
- /** 关闭摄像头 */
+ /** Turn the camera off */
stop: () => void;
}
/**
- * 摄像头预览。
+ * Camera preview.
*/
export function useCamera(): UseCameraResult {
const { t } = useTranslation('playground');
diff --git a/webdemo/frontend/src/pages/playground/hooks/useChat.ts b/webdemo/frontend/src/pages/playground/hooks/useChat.ts
index 6ba2e6e..6c3c802 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useChat.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useChat.ts
@@ -1,8 +1,8 @@
/**
- * 体验中心核心对话状态机 hook(门面)。
+ * Core conversation state-machine hook for the experience center (facade).
*
- * 用途:托管消息列表与 send/clear;补全网络委托 useChatCompletion,多版本/反馈委托 useMessageVersions。
- * 对外 API 保持不变:页面层只依赖 useChat(args) 及其返回值。
+ * Purpose: own the message list and send/clear; completion networking is delegated to useChatCompletion, and multi-version/feedback to useMessageVersions.
+ * The external API stays the same: the page layer depends only on useChat(args) and its return value.
*/
import { useCallback, useRef, useState } from 'react';
@@ -11,55 +11,55 @@ import { genId, makeDivider, makeMessage } from '../utils/messages';
import { useChatCompletion } from './useChatCompletion';
import { useMessageVersions } from './useMessageVersions';
-/** useChat 入参 */
+/** useChat arguments */
export interface UseChatArgs {
- /** 当前选中模型 id */
+ /** Currently selected model id */
model: string;
- /** 懒取明文密钥(无密钥时返回空,send 会拒绝) */
+ /** Lazily read the plaintext secret (returns empty when there is no secret, and send refuses) */
getSecret: () => string | undefined;
- /** 当前自动选定的 API Key ID,联网模式只把该 ID 交给 BFF */
+ /** Currently auto-selected API Key ID; web-search mode hands only this ID to the BFF */
keyId?: string;
- /** 参数偏好 */
+ /** Parameter preferences */
params: PlaygroundParams;
- /** 可选系统提示 */
+ /** Optional system prompt */
systemPrompt?: string;
- /** 模型目录声明的上下文窗口;0 表示未声明。 */
+ /** Context window declared in the model catalog; 0 means it is not declared. */
contextWindow?: number;
- /** 模型目录声明的最大输出 token。 */
+ /** Maximum output tokens declared in the model catalog. */
modelMaxOutputTokens?: number;
- /** 自动裁剪旧消息后的体验提示。 */
+ /** Experience notice after old messages are trimmed automatically. */
onContextTrim?: (trimmedMessageCount: number) => void;
- /** 当前输入自身超过可用上下文时的体验提示。 */
+ /** Experience notice when the current input itself exceeds the available context. */
onContextLimit?: () => void;
- /** 请求终态后刷新 Playground 免费体验状态。 */
+ /** Refresh Playground free-trial state after a request reaches a terminal state. */
refreshCredential?: () => void;
}
-/** useChat 返回 */
+/** useChat return value */
export interface UseChatReturn {
messages: ChatMessage[];
loading: boolean;
- /** 发送一条用户消息(可带多模态附件)并发起补全 */
+ /** Send one user message (optionally with multimodal attachments) and start a completion */
send: (text: string, attachments?: Attachment[]) => void;
- /** 重新生成某条 assistant 消息(非破坏性):保留既有版本,追加新版本并切到末位 */
+ /** Regenerate one assistant message (non-destructive): keep existing versions, append a new version, and switch to the last one */
regenerate: (assistantId: string) => void;
- /** 切换某条 assistant 消息的反馈态(赞/踩互斥,再次点击同项取消)。写入当前版本并镜像顶层 */
+ /** Toggle feedback on one assistant message (like/dislike are exclusive; clicking the same one again clears it). Write the current version and mirror the top level */
setFeedback: (assistantId: string, kind: MessageFeedback) => void;
- /** 切换某条 assistant 消息的显示版本(‹n/N› 翻页),把该版本字段镜像回顶层 */
+ /** Switch the displayed version of one assistant message (‹n/N› paging), and mirror that version's fields back to the top level */
setActiveVersion: (assistantId: string, index: number) => void;
- /** 停止当前生成(AbortController) */
+ /** Stop the current generation (AbortController) */
stop: () => void;
- /** 清空全部消息 */
+ /** Clear every message */
clear: () => void;
- /** 清除上下文:插入一条分隔线,其上历史不再作为上下文发送(消息仍保留,非新会话) */
+ /** Clear context: insert a divider, and history above it is no longer sent as context (messages stay; this is not a new conversation) */
clearContext: () => void;
- /** 直接替换消息列表(用于切换「最近对话」) */
+ /** Replace the message list directly (used when switching "recent conversations") */
setMessages: (list: ChatMessage[]) => void;
}
/**
- * 对话状态机门面。
- * @param args 模型 / 取密钥 / 参数 / 系统提示
+ * Conversation state-machine facade.
+ * @param args model / secret getter / parameters / system prompt
*/
export function useChat(args: UseChatArgs): UseChatReturn {
const {
@@ -128,8 +128,8 @@ export function useChat(args: UseChatArgs): UseChatReturn {
atts.length ? { attachments: atts } : {},
);
const history = [...messages, userMsg];
- // 开了联网就先把 searching 置起来:从发请求到第一个 tool_status 事件之间有一段空窗,
- // 否则这段时间界面上什么反馈都没有。关闭联网时仍是 false,非联网路径行为不变。
+ // When web search is on, set searching first: there is a gap between sending the request and the first tool_status event,
+ // and otherwise the UI has no feedback during that time. When web search is off it stays false, and the non-search path is unchanged.
const placeholder = makeMessage(assistantId, 'assistant', '', {
streaming: true,
searching: params.webSearch,
diff --git a/webdemo/frontend/src/pages/playground/hooks/useChatCompletion.ts b/webdemo/frontend/src/pages/playground/hooks/useChatCompletion.ts
index 276e8d4..b89d916 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useChatCompletion.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useChatCompletion.ts
@@ -1,8 +1,8 @@
/**
- * 体验中心「一次补全」生命周期 hook。
+ * Experience-center hook for the lifecycle of "one completion".
*
- * 用途:校验 key → AbortController → 构造请求 → 流式/非流式合并增量 → finish/fail/abort 收尾。
- * send 与 regenerate 在 useChat 中构造 history 后调用 startCompletion。
+ * Purpose: check the key → AbortController → build the request → merge streaming or non-streaming increments → finish/fail/abort.
+ * send and regenerate in useChat call startCompletion after they have built history.
*/
import {
@@ -37,7 +37,7 @@ import { buildChatParams, requiresNonStreaming } from '../utils/params';
import { refreshAttachmentLinks } from '../utils/refreshAttachmentLinks';
import { collectPlaygroundRuntimeContext } from '../utils/runtimeContext';
-/** useChatCompletion 入参 */
+/** useChatCompletion arguments */
export interface UseChatCompletionArgs {
setMessages: Dispatch<SetStateAction<ChatMessage[]>>;
model: string;
@@ -49,21 +49,21 @@ export interface UseChatCompletionArgs {
modelMaxOutputTokens?: number;
onContextTrim?: (trimmedMessageCount: number) => void;
onContextLimit?: () => void;
- /** 请求终态后刷新 Playground 免费体验状态。 */
+ /** Refresh Playground free-trial state after a request reaches a terminal state. */
refreshCredential?: () => void;
}
-/** useChatCompletion 返回 */
+/** useChatCompletion return value */
export interface UseChatCompletionReturn {
loading: boolean;
stop: () => void;
- /** 发起一次补全;调用前须已入列 assistant 占位,history 不含该占位 */
+ /** Start one completion; the assistant placeholder must already be enqueued, and history must not include that placeholder */
startCompletion: (history: ChatMessage[], assistantId: string) => void;
}
/**
- * 托管单次补全的网络生命周期与 loading/abort 状态。
- * @param args setMessages、模型、密钥与参数偏好
+ * Own the network lifecycle and loading/abort state of a single completion.
+ * @param args setMessages, model, secret, and parameter preferences
*/
export function useChatCompletion(args: UseChatCompletionArgs): UseChatCompletionReturn {
const { t } = useTranslation('playground');
@@ -97,7 +97,7 @@ export function useChatCompletion(args: UseChatCompletionArgs): UseChatCompletio
const stop = useCallback(() => {
const activeCompletion = activeCompletionRef.current;
if (!activeCompletion) return;
- // 中断前请求可能已被 L2 消耗免费额度;终态同样刷新,避免 UI 停留在旧剩余次数。
+ // The request may already have consumed free quota at L2 before it was aborted; a terminal state refreshes too, so the UI does not stay on the old remaining count.
refreshCredential?.();
activeCompletion.controller.abort();
if (activeStreamRef.current?.controller === activeCompletion.controller) {
@@ -125,7 +125,7 @@ export function useChatCompletion(args: UseChatCompletionArgs): UseChatCompletio
const startCompletion = useCallback(
(history: ChatMessage[], assistantId: string) => {
- // MiniCPM-OCR-Jev 仅验证过完整响应协议;即使用户打开流式开关,也必须走非流式请求。
+ // MiniCPM-OCR-Jev has only been verified against the full-response protocol; even if the user turns streaming on, the request must be non-streaming.
const useStreaming = !forceNonStreaming && (params.stream || params.webSearch);
const hostedWebSearch = !forceNonStreaming && params.webSearch;
const secret = hostedWebSearch ? undefined : getSecret();
@@ -166,14 +166,14 @@ export function useChatCompletion(args: UseChatCompletionArgs): UseChatCompletio
const controller = new AbortController();
setLoading(true);
- // 所有 Playground 调用都生成浏览器关联 ID。直连 L2 用它回查调用日志;
- // 联网搜索由 L3 在最终 L2 调用完成时持久化映射,覆盖 SSE 最后一帧意外丢失。
+ // Every Playground call generates a browser correlation ID. A direct L2 call uses it to look the call log back up;
+ // web search has L3 persist the mapping when the final L2 call finishes, covering an SSE last frame that was lost unexpectedly.
const clientRequestID = createPlaygroundClientRequestID();
setMessages((prev) =>
appendToMessage(prev, assistantId, { clientRequestId: clientRequestID, apiKeyId: keyId }),
);
- // 请求消息在 begin 内按"刷新后的附件链接"重建,这里只准备运行时上下文。
+ // Request messages are rebuilt inside begin from "refreshed attachment links"; here only the runtime context is prepared.
const runtimeContext = collectPlaygroundRuntimeContext(locale, params.userLocation);
const startedAt = performance.now();
@@ -195,7 +195,7 @@ export function useChatCompletion(args: UseChatCompletionArgs): UseChatCompletio
const finish = () => {
if (!isCurrentCompletion()) return;
- // 直连/联网请求都会消耗体验额度;终态后刷新,让 UI 及时回退用户自有 Key。
+ // Both a direct call and a web-search request consume trial quota; refresh after the terminal state so the UI falls back to the user's own key in time.
refreshCredential?.();
setLoading(false);
abortRef.current = null;
diff --git a/webdemo/frontend/src/pages/playground/hooks/useCitationPanel.ts b/webdemo/frontend/src/pages/playground/hooks/useCitationPanel.ts
index 0861a65..e406c41 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useCitationPanel.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useCitationPanel.ts
@@ -1,43 +1,43 @@
/**
- * 引用来源面板的开合与定位编排 hook。
+ * Hook that orchestrates opening, closing, and positioning of the citation-source panel.
*
- * 用途:把「正在展示哪条消息的来源 / 面板是否展开 / 面板内高亮哪一条」这三份状态,连同
- * Esc 关闭、来源消失时自动收起、卸载清理延时器,从页面入口收敛到一处。不含 JSX。
+ * Purpose: pull the three pieces of state "which message's sources are showing / whether the panel is open / which item is highlighted inside the panel", together with
+ * close on Esc, auto-collapse when a source disappears, and clearing the delay timer on unmount, into one place at the page entry. No JSX.
*
- * 为什么 panel 与 open 要分成两份状态:关闭需要走退出动画,面板内容必须等动画跑完才能卸载,
- * 所以 open 先转 false 放动画,panel 延后清空。
+ * Why panel and open are two pieces of state: closing has to play an exit animation, and the panel content must not unmount until the animation finishes,
+ * so open turns false first to run the animation, and panel is cleared later.
*/
import { useCallback, useEffect, useRef, useState } from 'react';
import type { ChatMessage, Citation } from '../types';
-/** 与 PlaygroundLayout 的 PANEL_MOTION(duration-300)对齐:动画跑完再卸载面板内容。 */
+/** Aligned with PlaygroundLayout's PANEL_MOTION (duration-300): unmount the panel content only after the animation finishes. */
const PANEL_EXIT_MS = 300;
-/** 面板当前展示的来源及其归属消息。 */
+/** Sources the panel is currently showing, and the message they belong to. */
interface CitationPanelState {
messageId: string;
citations: Citation[];
}
interface UseCitationPanelResult {
- /** 当前展示的来源;null 表示面板内容已卸载。 */
+ /** Sources currently shown; null means the panel content has unmounted. */
panel: CitationPanelState | null;
- /** 面板是否展开(驱动动画,早于 panel 清空)。 */
+ /** Whether the panel is expanded (drives the animation, and happens before panel is cleared). */
open: boolean;
- /** 面板内高亮定位的来源 URL;未指定时不高亮任何一条。 */
+ /** Source URL highlighted inside the panel; when unset, no item is highlighted. */
activeUrl?: string;
- /** 打开某条消息的来源面板;带 activeUrl 时同时定位并高亮该来源。 */
+ /** Open the source panel for one message; when activeUrl is set, also locate and highlight that source. */
openPanel: (messageId: string, citations: Citation[], activeUrl?: string) => void;
- /** 关闭面板(走退出动画)。 */
+ /** Close the panel (plays the exit animation). */
closePanel: () => void;
}
/**
- * 编排引用来源面板的开合与高亮定位。
- * @param messages 当前对话的全部消息,用于在来源消失时自动收起面板
- * @returns 面板状态与开关方法
+ * Orchestrate opening, closing, and highlight positioning of the citation-source panel.
+ * @param messages every message in the current conversation, used to collapse the panel automatically when a source disappears
+ * @returns panel state and open/close methods
*/
export function useCitationPanel(messages: ChatMessage[]): UseCitationPanelResult {
const [panel, setPanel] = useState<CitationPanelState | null>(null);
@@ -51,7 +51,7 @@ export function useCitationPanel(messages: ChatMessage[]): UseCitationPanelResul
window.clearTimeout(exitTimer.current);
setPanel({ messageId, citations });
setOpen(true);
- // 不带 url 的入口(底部「查看全部」)顺带清掉上一次的高亮,避免停在无关的一条上。
+ // An entry with no url (the "view all" at the bottom) also clears the previous highlight, so it does not stay on an unrelated item.
setActiveUrl(nextActiveUrl);
},
[],
@@ -73,7 +73,7 @@ export function useCitationPanel(messages: ChatMessage[]): UseCitationPanelResul
[],
);
- // Esc 关闭:桌面端是非模态并排,没有遮罩可点,键盘是除面板自带 X 之外唯一的关闭入口。
+ // Close on Esc: on desktop it is a non-modal side-by-side panel with no mask to click, so the keyboard is the only close entry besides the panel's own X.
useEffect(() => {
if (!panel) return;
const handleKeyDown = (event: KeyboardEvent) => {
@@ -83,12 +83,12 @@ export function useCitationPanel(messages: ChatMessage[]): UseCitationPanelResul
return () => window.removeEventListener('keydown', handleKeyDown);
}, [panel, closePanel]);
- // 来源随消息消失(重新生成、切换版本、清空会话)时自动收起,不让面板停在空数据上。
+ // When a source disappears with the message (regenerate, switching versions, clearing the conversation), collapse automatically, so the panel does not sit on empty data.
useEffect(() => {
if (panel && !messages.some((m) => m.id === panel.messageId && m.citations?.length)) {
- // 这里必须走 setState 而非 render 期推导:closePanel 要放完 300ms 退出动画再卸载内容,
- // 纯推导会让面板瞬间消失;且推导态在消息被换回来时会把面板又弹开。
- // 只在归属消息真的消失时触发一次,不是每渲染都跑。
+ // This must go through setState rather than being derived during render: closePanel has to finish the 300ms exit animation before unmounting the content,
+ // and a pure derivation would make the panel vanish instantly; a derived state would also pop the panel open again when the message is swapped back.
+ // Fire once only when the owning message really disappears, not on every render.
// eslint-disable-next-line react-hooks/set-state-in-effect
closePanel();
}
diff --git a/webdemo/frontend/src/pages/playground/hooks/useConversationAutosave.ts b/webdemo/frontend/src/pages/playground/hooks/useConversationAutosave.ts
index bf80427..3a76731 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useConversationAutosave.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useConversationAutosave.ts
@@ -1,8 +1,8 @@
/**
- * Playground 会话自动保存队列。
+ * Playground conversation autosave queue.
*
- * 用途:首次发送时立即创建会话并保存用户消息;回答结束后串行保存最终快照。
- * 同一时刻只允许一个写请求,生成期间产生的新快照只保留最新一份,避免旧请求后完成覆盖新内容。
+ * Purpose: on the first send, create the conversation immediately and save the user message; after the answer ends, save the final snapshot serially.
+ * Only one write request is allowed at a time, and new snapshots produced during generation keep only the latest one, so an older request finishing later cannot overwrite newer content.
*/
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
@@ -30,16 +30,16 @@ interface UseConversationAutosaveArgs {
}
interface UseConversationAutosaveReturn {
- /** 标记服务端已持久化的历史消息,避免加载历史后立即重复保存。 */
+ /** Mark history messages the server has already persisted, so loading history does not save them again immediately. */
markPersisted: (messages: ChatMessage[]) => void;
- /** 开始新对话时废弃当前排队快照,隔离前后两段会话。 */
+ /** When a new conversation starts, discard the snapshot currently queued, isolating the two conversations. */
reset: () => void;
}
/**
- * 串行保存当前 Playground 会话。
- * @param args 当前消息、模型、会话 ID 与 API 写入函数。
- * @returns 历史恢复标记与新会话重置函数。
+ * Save the current Playground conversation serially.
+ * @param args current messages, model, conversation ID, and the API write function.
+ * @returns the history-restore marker and the new-conversation reset function.
*/
export function useConversationAutosave(
args: UseConversationAutosaveArgs,
@@ -63,17 +63,17 @@ export function useConversationAutosave(
),
);
- // mutation 与 URL 回调可能在重渲染后换引用,队列始终使用最新实现。
+ // A mutation and a URL callback may change reference after a re-render; the queue always uses the latest implementation.
useEffect(() => {
queue.updateHandlers({ createConversation, saveConversation, onConversationCreated });
}, [createConversation, onConversationCreated, queue, saveConversation]);
- // URL/历史选择改变活动会话时同步给队列。
+ // When the URL or a history selection changes the active conversation, sync it to the queue.
useLayoutEffect(() => {
queue.setActiveConversationId(activeConversationId);
}, [activeConversationId, queue]);
- // 账号切换立即废弃上一账号队列与草稿。
+ // An account switch discards the previous account's queue and draft immediately.
useLayoutEffect(() => {
if (previousOwnerRef.current === ownerId) return;
queue.reset(previousOwnerRef.current);
@@ -81,7 +81,7 @@ export function useConversationAutosave(
queue.setActiveConversationId(activeConversationId);
}, [activeConversationId, ownerId, queue]);
- // 页面可见消息提交后立即刷新草稿,确保 pagehide 读取到本次提交的最后增量。
+ // After a visible message on the page is committed, refresh the draft immediately, so pagehide reads the last increment of this commit.
useLayoutEffect(() => {
if (!enabled) return;
const draftable = messagesForDraft(messages);
diff --git a/webdemo/frontend/src/pages/playground/hooks/useConversationDetailLoader.ts b/webdemo/frontend/src/pages/playground/hooks/useConversationDetailLoader.ts
index 7956b6b..8f5d208 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useConversationDetailLoader.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useConversationDetailLoader.ts
@@ -1,7 +1,7 @@
/**
- * Playground 历史会话详情加载器。
+ * Playground history-conversation detail loader.
*
- * 用途:给每次详情请求分配序号,连续选择或新建会话时让迟到响应自动失效。
+ * Purpose: assign a sequence number to each detail request, so a late response is invalidated automatically when conversations are selected in succession or a new one is created.
*/
import { useCallback, useEffect, useMemo, useRef } from 'react';
@@ -22,8 +22,8 @@ interface UseConversationDetailLoaderReturn {
}
/**
- * 管理会话详情请求的竞态。
- * @param messages 当前消息,用于在用户已发送新内容时取消初始恢复。
+ * Manage races among conversation-detail requests.
+ * @param messages current messages, used to cancel the initial restore when the user has already sent new content.
*/
export function useConversationDetailLoader(
messages: ChatMessage[],
diff --git a/webdemo/frontend/src/pages/playground/hooks/useConversationPersistence.ts b/webdemo/frontend/src/pages/playground/hooks/useConversationPersistence.ts
index b07e136..d116a8d 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useConversationPersistence.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useConversationPersistence.ts
@@ -1,9 +1,9 @@
/**
- * Playground 历史对话持久化编排 hook。
+ * Hook that orchestrates Playground history-conversation persistence.
*
- * 用途:把「列表查询 + 选中加载 + 自动保存 + 新建 + 删除」收敛为一处,喂给侧栏与页面。
- * 保存时机:首次发送立即保存用户消息,回答完成后串行保存最终快照。
- * 不含 JSX。明文密钥与对话正文分离——本 hook 只处理对话正文的存取,不碰密钥。
+ * Purpose: collapse "list query + load on select + autosave + create + delete" into one place, and feed the sidebar and the page.
+ * Save timing: the first send saves the user message immediately, and after the answer finishes the final snapshot is saved serially.
+ * No JSX. The plaintext secret stays separate from the conversation body — this hook only stores and loads the conversation body, and does not touch secrets.
*/
import { useCallback, useMemo, useState } from 'react';
@@ -20,41 +20,41 @@ import { useConversationAutosave } from './useConversationAutosave';
import { useConversationDetailLoader } from './useConversationDetailLoader';
import { useInitialConversationRestore } from './useInitialConversationRestore';
-/** useConversationPersistence 入参:从 useChat 透传的最小集合 */
+/** useConversationPersistence arguments: the minimum set forwarded from useChat */
interface Args {
messages: ChatMessage[];
- /** 当前选中模型(保存到会话元信息) */
+ /** Currently selected model (saved into conversation metadata) */
model: string;
- /** 当前登录用户 ID,用于隔离同标签页草稿。 */
+ /** Currently logged-in user ID, used to isolate same-tab drafts. */
ownerId?: string;
- /** 用户身份仍在加载时暂停草稿恢复与自动保存。 */
+ /** While user identity is still loading, pause draft restore and autosave. */
ownerLoading: boolean;
- /** 用消息列表替换当前对话(加载历史时用) */
+ /** Replace the current conversation with a message list (used when loading history) */
setMessages: (list: ChatMessage[]) => void;
- /** 清空当前对话(新建时用) */
+ /** Clear the current conversation (used when creating a new one) */
clear: () => void;
/**
- * 恢复会话时把该会话当初使用的模型切回去(切换会话/刷新恢复时调用)。
- * 由上层校验模型是否仍可选,故此处仅在会话确有 model 时透传。
+ * When restoring a conversation, switch back to the model that conversation used (called when switching conversations or restoring on refresh).
+ * The caller checks whether the model is still selectable, so this only forwards it when the conversation actually has a model.
*/
onModelRestore?: (model: string) => void;
}
interface Return {
- /** 侧栏「最近对话」列表项(id+title) */
+ /** A "recent conversations" sidebar item (id+title) */
sessions: { id: string; title: string }[];
activeConversationId?: string;
- /** 是否还有下一页可加载 */
+ /** Whether another page can be loaded */
hasMore: boolean;
- /** 是否正在加载下一页 */
+ /** Whether the next page is loading */
loadingMore: boolean;
- /** 加载下一页(滚到底触发) */
+ /** Load the next page (triggered by scrolling to the bottom) */
loadMore: () => void;
- /** 选中并加载某历史会话 */
+ /** Select and load one history conversation */
selectConversation: (id: string) => void;
- /** 新建对话(清空 + 脱离当前会话) */
+ /** Start a new conversation (clear + leave the current conversation) */
newChat: () => void;
- /** 删除某会话(若删的是当前会话则一并清空) */
+ /** Delete one conversation (if it is the current conversation, clear that too) */
removeConversation: (id: string) => void;
}
@@ -65,7 +65,7 @@ export function useConversationPersistence(args: Args): Return {
const createMut = useCreateConversationMutation();
const saveMut = useSaveConversationMutation();
const deleteMut = useDeleteConversationMutation();
- // 当前会话 id 以 URL 查询参数 `c` 为准——刷新后据此恢复现场(避免回到空白新对话)。
+ // The current conversation id follows the URL query parameter `c` — after a refresh, restore from that (so it does not return to a blank new conversation).
const [searchParams, setSearchParams] = useSearchParams();
const [activeId, setActiveIdState] = useState<string | undefined>(
() => searchParams.get('c') || undefined,
@@ -73,8 +73,8 @@ export function useConversationPersistence(args: Args): Return {
const [autosaveEnabled, setAutosaveEnabled] = useState(false);
/**
- * 设置当前会话 id 并同步写回 URL(replace 不污染浏览器历史)。
- * 传 undefined 时清除参数,回到「新对话」语义。
+ * Set the current conversation id and write it back to the URL (replace does not pollute browser history).
+ * Passing undefined clears the parameter and returns to the "new conversation" meaning.
*/
const setActiveId = useCallback(
(id: string | undefined) => {
@@ -116,7 +116,7 @@ export function useConversationPersistence(args: Args): Return {
onModelRestore,
});
- // 扁平化分页结果为侧栏列表项;对后端未部署/异常返回(page.list 缺失)做容错,避免整页崩溃
+ // Flatten paged results into sidebar items; tolerate a backend that is not deployed or returns an abnormal shape (page.list missing), so the whole page does not crash
const sessions = useMemo(
() =>
(listQuery.data?.pages ?? [])
@@ -133,7 +133,7 @@ export function useConversationPersistence(args: Args): Return {
const selectConversation = useCallback(
(id: string) => {
if (id === activeId) return;
- // 直接拉详情(不走 query 缓存,避免切换时的加载竞态),载回消息
+ // Pull the detail directly (not through the query cache, avoiding a load race while switching), and load the messages back
loadDetail(id).then((result) => {
if (result.status === 'loaded') {
const list = result.detail.messages.map(storedToChatMessage);
@@ -141,7 +141,7 @@ export function useConversationPersistence(args: Args): Return {
setMessages(list);
setActiveId(id);
markPersisted(list);
- // 切换会话时自动切回该会话当初使用的模型(上层校验其是否仍可选)
+ // When switching conversations, switch back to the model that conversation originally used (the caller checks whether it is still selectable)
if (result.detail.conversation.model) {
onModelRestore?.(result.detail.conversation.model);
}
diff --git a/webdemo/frontend/src/pages/playground/hooks/useDevices.ts b/webdemo/frontend/src/pages/playground/hooks/useDevices.ts
index b87a469..69a5570 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useDevices.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useDevices.ts
@@ -1,21 +1,21 @@
/**
- * 音频设备枚举 Hook。
+ * Audio-device enumeration hook.
*
- * 用途:为「实时语音」提供麦克风/扬声器设备列表与刷新(对齐 MiniCPM-o demo 的设备选择)。
- * 挂载即自动枚举一次,并监听设备热插拔自动刷新;仍暴露 refresh 供「刷新设备」按钮与
- * 通话授权后补全 label 调用。设备 label 需在麦克风授权后才完整可见(浏览器隐私限制)。
+ * Purpose: provide the microphone and speaker device list and a refresh for "realtime voice" (aligned with device selection in the MiniCPM-o demo).
+ * Enumerate once on mount, and listen for hot-plug to refresh automatically; refresh is still exposed for the "refresh devices" button and for
+ * filling in labels after the call is authorized. Device labels are fully visible only after microphone permission (a browser privacy limit).
*/
import { useCallback, useEffect, useState } from 'react';
-/** 设备项 */
+/** One device item */
export interface DeviceOption {
id: string;
label: string;
}
/**
- * 枚举音频输入/输出设备。
+ * Enumerate audio input and output devices.
*/
export function useDevices() {
const [mics, setMics] = useState<DeviceOption[]>([]);
@@ -25,8 +25,8 @@ export function useDevices() {
if (!navigator.mediaDevices?.enumerateDevices) return;
try {
const list = await navigator.mediaDevices.enumerateDevices();
- // 过滤浏览器的 default/communications 别名项:它们语义即「系统默认」,与下拉里手写的
- // 「系统默认」(value=default) 重复,且 deviceId 固定,会撞车导致选项重复、标签拼接
+ // Filter the browser's default/communications alias items: they mean "system default", which duplicates the handwritten
+ // "system default" (value=default) in the dropdown, and their deviceId is fixed, so they collide, duplicate options, and concatenate labels
const real = (kind: MediaDeviceKind) =>
list.filter(
(d) =>
@@ -45,12 +45,12 @@ export function useDevices() {
})),
);
} catch {
- // 枚举失败静默降级
+ // Enumeration failure degrades silently
}
}, []);
- // 挂载即自动枚举一次,并监听热插拔自动刷新(enumerate 不申请权限,未授权时 label 退化为占位名)。
- // refresh 是异步的,setState 发生在 await 之后(非渲染同步阶段),不会引发级联渲染,故此处豁免规则。
+ // Enumerate once on mount, and listen for hot-plug to refresh automatically (enumerate does not request permission; without permission, label falls back to a placeholder name).
+ // refresh is async, and setState happens after await (not in the synchronous render phase), so it does not cause a cascading render; the rule is waived here.
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect
void refresh();
diff --git a/webdemo/frontend/src/pages/playground/hooks/useDocumentUpload.ts b/webdemo/frontend/src/pages/playground/hooks/useDocumentUpload.ts
index 7f3d7cf..29c283c 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useDocumentUpload.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useDocumentUpload.ts
@@ -1,4 +1,4 @@
-/** 文档远端上传生命周期:替换即取消旧任务,失败保留文件以便重试。 */
+/** Remote document-upload lifecycle: replacing cancels the old task, and a failure keeps the file so it can be retried. */
import { useEffect, useRef, useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { useTranslation } from 'react-i18next';
@@ -20,18 +20,18 @@ interface UploadState {
error?: string;
}
-/** OCR 文档读取配置:本地大小上限必须显式传入,避免通用附件默认值误伤 PDF。 */
+/** OCR document read config: the local size cap must be passed explicitly, so the generic attachment default does not harm a PDF. */
interface DocumentReadOptions extends ReadAttachmentOptions {
maxBytes: number;
}
/**
- * 编排图像解析的真实上传,组件卸载或新文件到来时隔离过期响应。
- * @param onReady 成功后替换当前附件
- * @param scope 账号及默认项目标识,变化时取消旧上传
- * @param onStart 文件通过校验后清除旧识别结果
- * @param previewOnly 无解析模型时仅本地预览,不向服务端上传
- * @param rules 当前识别档位的格式、数量与大小边界
+ * Orchestrate the real upload for image parsing, and isolate a stale response when the component unmounts or a new file arrives.
+ * @param onReady replace the current attachment after success
+ * @param scope account and default-project id; a change cancels the old upload
+ * @param onStart clear the old recognition result after the file passes checks
+ * @param previewOnly when there is no parsing model, preview locally only and do not upload to the server
+ * @param rules format, count, and size bounds of the current recognition tier
*/
export function useDocumentUpload(
onReady: (attachment: Attachment) => void,
@@ -45,7 +45,7 @@ export function useDocumentUpload(
const active = useRef<AbortController | null>(null);
const previousScope = useRef(scope);
const mutation = useMutation({
- // 上传由用户显式重试,不让缓存保留文档内容。
+ // Upload is retried explicitly by the user; do not let the cache keep the document content.
gcTime: 0,
retry: false,
mutationFn: async ({ resultPromise }: { resultPromise: Promise<ReadAttachmentResult> }) => {
@@ -103,9 +103,9 @@ export function useDocumentUpload(
onStart?.();
setState({ file, pending: true });
try {
- // 先建立上传请求再交给 mutation 追踪,保证连续替换时旧请求已能立即响应 abort。
+ // Create the upload request before handing it to the mutation to track, so when files are replaced in succession the old request can already respond to abort immediately.
const normalized = normalizeDocumentFile(file);
- // 上传失败不进入识别;只有预览模式允许不访问文件服务。
+ // A failed upload does not enter recognition; only preview mode may avoid the file service.
const options = {
maxBytes: rules?.maxBytes ?? DOCUMENT_MAX_BYTES,
accept: rules?.accept ?? DOCUMENT_IMAGE_TYPES,
@@ -123,7 +123,7 @@ export function useDocumentUpload(
setState({
file,
pending: false,
- // SDK/上游消息可能带签名 URL,界面只展示稳定文案。
+ // An SDK or upstream message may carry a signed URL; the UI shows only stable copy.
error: t('documentUploadFailed'),
});
return undefined;
@@ -138,7 +138,7 @@ export function useDocumentUpload(
return { ...state, upload, cancel, retry: () => state.file && void upload(state.file) };
}
-/** OCR 原件上传统一通过文件服务。 */
+/** OCR original uploads all go through the file service. */
function readDocumentAttachment(file: File, options: DocumentReadOptions, signal: AbortSignal) {
return uploadImageParseDocument(file, options, signal);
}
diff --git a/webdemo/frontend/src/pages/playground/hooks/useDuplexSettings.ts b/webdemo/frontend/src/pages/playground/hooks/useDuplexSettings.ts
index e76b7ad..913c339 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useDuplexSettings.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useDuplexSettings.ts
@@ -1,22 +1,22 @@
/**
- * 实时音视频(双工)参数状态 Hook。
+ * Realtime audio and video (duplex) parameter-state hook.
*
- * 用途:集中管理双工通话的全部可调参数(对齐 MiniCPM-o demo)——对话模式、音色、
- * 系统提示词、TTS 开关、Length Penalty、Max Tokens、Temperature、播放延迟、麦克风/扬声器、
- * 参考音频(音色克隆)。以单对象 + patch 收敛,供页面编排与请求组装。
+ * Purpose: manage every adjustable parameter of a duplex call in one place (aligned with the MiniCPM-o demo) — conversation mode, voice,
+ * system prompt, TTS switch, Length Penalty, Max Tokens, Temperature, playback delay, microphone/speaker,
+ * and reference audio (voice clone). Collapsed to one object plus patch, for page orchestration and request assembly.
*/
import { useAppStore, type AppLocale } from '@map/store';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-/** 通用选项 */
+/** Generic option */
export interface DuplexOption {
value: string;
label: string;
}
-/** 双工音色选项,包含声音要求和可选的参考音频素材。 */
+/** Duplex voice option, including the voice requirement and optional reference-audio asset. */
export interface DuplexVoiceOption extends DuplexOption {
instruction: string;
instructionEn: string;
@@ -25,22 +25,22 @@ export interface DuplexVoiceOption extends DuplexOption {
export type DuplexLanguage = 'zh' | 'en';
-/** 双工语言来源:跟随界面语言,或由用户在双工面板中手动指定。 */
+/** Duplex language source: follow the UI language, or be set manually by the user in the duplex panel. */
export type DuplexLanguageMode = 'auto' | 'manual';
-/** 官方 Demo 支持的界面/提示词语言。 */
+/** UI and prompt languages the official demo supports. */
export const LANGUAGES: DuplexOption[] = [
{ value: 'zh', label: 'languageChinese' },
{ value: 'en', label: 'languageEnglish' },
];
-/** 对话模式(字段名 audioSource 为兼容已有持久化配置保留) */
+/** Conversation mode (the field name audioSource is kept for compatibility with existing persisted config) */
export const SOURCES: DuplexOption[] = [
{ value: 'mic', label: 'audioDuplex' },
{ value: 'both', label: 'videoDuplex' },
];
-/** 对话音色 */
+/** Conversation voice */
export const VOICES: DuplexVoiceOption[] = [
{
value: 'female_warm',
@@ -65,14 +65,14 @@ export const VOICES: DuplexVoiceOption[] = [
},
];
-/** 官方 MiniCPM-o-Demo 预设原文。 */
+/** Original text of the official MiniCPM-o-Demo presets. */
export const OFFICIAL_AUDIO_DUPLEX_PROMPT =
'扮演一个具有以上声音特征的助手。请认真、高质量地回复用户的问题。请用高自然度的方式和用户聊天。你处于双工模式,可以一边听、一边说。你是由面壁智能开发的人工智能助手:面壁小钢炮。';
export const OFFICIAL_AUDIO_DUPLEX_ENGLISH_PROMPT =
"Act as an assistant with the voice characteristics described above. Respond to the user's questions thoughtfully and with high quality. Chat with the user in a highly natural manner. You are in duplex mode, so you can listen and speak at the same time. You are ModelBest Xiao Gang Pao, an AI assistant developed by ModelBest Intelligence.";
export const OFFICIAL_OMNI_PROMPT = 'Streaming Omni Conversation.';
-/** 场景预设 → 系统提示词;内容对应 MiniCPM-o-Demo/assets/presets。 */
+/** Scene preset → system prompt; the content corresponds to MiniCPM-o-Demo/assets/presets. */
export const SCENES = [
{
value: 'audio_chinese_call',
@@ -114,7 +114,7 @@ export function promptForAudioSource(
: { scene: 'audio_chinese_call', system: OFFICIAL_AUDIO_DUPLEX_PROMPT, language };
}
-/** 双工全部参数 */
+/** Every duplex parameter */
export interface DuplexSettings {
audioSource: string;
voice: string;
@@ -136,7 +136,7 @@ export interface DuplexSettings {
subtitleTopOpacity: number;
micDeviceId: string;
speakerDeviceId: string;
- /** 参考音频(音色克隆)裸 base64 */
+ /** Reference audio (voice clone) raw base64 */
refAudio?: string;
refAudioName?: string;
ttsRefAudio?: string;
@@ -176,7 +176,7 @@ const DEFAULT: DuplexSettings = {
temperature: 0.7,
ttsEnabled: true,
visionHD: false,
- /** 下行播放预留缓冲(ms):0 等于零缓冲,网络抖一下就是可听见的断裂,默认留一点余量 */
+ /** Reserved downlink playback buffer (ms): 0 means zero buffer, and one network jitter is an audible break, so a little margin is left by default */
playbackDelay: 200,
responseLengthPreset: 'balanced',
subtitleHeightPercent: 20,
@@ -196,11 +196,11 @@ function createDefaultSettings(language: DuplexLanguage): DuplexSettings {
}
/**
- * 将用户选择的音色转换为实际发送给模型的声音要求。
+ * Turn the voice the user selected into the voice requirement actually sent to the model.
*
- * @param system 用户在面板中编辑的系统提示词
- * @param voice 音色标识
- * @returns 保留原提示词并追加声音要求的有效系统提示词
+ * @param system system prompt the user edited in the panel
+ * @param voice voice id
+ * @returns an effective system prompt that keeps the original prompt and appends the voice requirement
*/
export function buildDuplexSystemPrompt(
system: string,
@@ -216,10 +216,10 @@ export function buildDuplexSystemPrompt(
}
/**
- * 从持久化数据恢复双工设置,并迁移旧的官方场景提示词。
+ * Restore duplex settings from persisted data, and migrate old official scene prompts.
*
- * @param saved localStorage 中读取的部分设置
- * @returns 带默认值和迁移结果的完整双工设置
+ * @param saved partial settings read from localStorage
+ * @returns complete duplex settings with defaults and the migration result
*/
export function resolveInitialDuplexSettings(
saved: Partial<DuplexSettings>,
@@ -246,7 +246,7 @@ export function resolveInitialDuplexSettings(
languageMode === 'auto' ||
(KNOWN_SYSTEM_PROMPTS.has(saved.system) &&
(savedScene?.language !== language || saved.scene !== official.scene));
- // 双工只支持官方预置音色;历史持久化的私有音色 ID 必须回退,避免继续发送旧选择。
+ // Duplex supports only official preset voices; a historically persisted private voice ID must fall back, so the old selection is not sent again.
const voice = VOICES.find((item) => item.value === saved.voice)?.value ?? DEFAULT.voice;
return {
@@ -261,13 +261,13 @@ export function resolveInitialDuplexSettings(
}
/**
- * 双工参数状态。
+ * Duplex parameter state.
*/
export function useDuplexSettings() {
const storeLocale = useAppStore((state) => state.locale);
const { i18n } = useTranslation();
- // i18next 语言切换先于持久化 store hydration 完成,优先使用已生效的界面语言,
- // 避免英文界面首次打开时短暂或持续回显中文场景提示词。
+ // An i18next language change finishes before the persisted store hydrates, so prefer the UI language that is already in effect,
+ // and avoid briefly or persistently echoing Chinese scene prompts the first time the English UI opens.
const locale: AppLocale =
i18n.resolvedLanguage === 'en-US' || storeLocale === 'en-US' ? 'en-US' : 'zh-CN';
const previousLocale = useRef(locale);
diff --git a/webdemo/frontend/src/pages/playground/hooks/useElementSize.ts b/webdemo/frontend/src/pages/playground/hooks/useElementSize.ts
index 14ddde9..eaac25c 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useElementSize.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useElementSize.ts
@@ -1,16 +1,16 @@
/**
- * 观测元素的布局尺寸。
+ * Observe an element's layout size.
*
- * 用途:图片视口与内容都要按实际尺寸算缩放贴合与平移边界,而这两个盒子会随
- * 分栏拖拽、窗口缩放、侧栏展开而变——只在挂载时量一次就会算错。
+ * Purpose: both the image viewport and the content need their real size to compute zoom fit and pan bounds, and those two boxes change with
+ * split dragging, window resize, and the sidebar opening — measuring once on mount would compute the wrong value.
*
- * 用 ResizeObserver 而不是监听 window.resize:报的是布局盒,
- * transform 不影响它,所以缩放过程中不会自激成死循环。
+ * Use ResizeObserver rather than listening to window.resize: it reports the layout box,
+ * and transform does not affect it, so zooming does not excite itself into a dead loop.
*/
import { useEffect, useState } from 'react';
-/** 元素布局尺寸;宽为 0 表示还没测量到。 */
+/** Element layout size; width 0 means it has not been measured yet. */
export interface ElementSize {
width: number;
height: number;
@@ -19,8 +19,8 @@ export interface ElementSize {
const EMPTY: ElementSize = { width: 0, height: 0 };
/**
- * 跟随元素尺寸变化。
- * @param node 目标元素,null 时返回零尺寸
+ * Follow changes in an element's size.
+ * @param node target element; return a zero size when null
*/
export function useElementSize(node: HTMLElement | null): ElementSize {
const [size, setSize] = useState<ElementSize>(EMPTY);
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParse.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParse.ts
index 1cec22b..bc7fe19 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParse.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParse.ts
@@ -17,9 +17,9 @@ import { useImageParseTaskNavigation } from './useImageParseTaskNavigation';
import { useImageParseRecognitionAutoRun } from './useImageParseRecognitionAutoRun';
import type { PdfImageParseRestoreOptions } from './usePdfImageParseHistory';
-/** 编排图片/PDF 识别与历史恢复。
- * @param model 当前账号、项目与模型上下文
- * @returns 识别状态、服务端来源及历史恢复入口 */
+/** Orchestrate image/PDF recognition and history restore.
+ * @param model current account, project, and model context
+ * @returns recognition state, server source, and the history-restore entry */
export function useImageParse(
model: ReturnType<typeof usePlaygroundModel>,
{
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseAppend.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseAppend.ts
index a992260..0b86db6 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseAppend.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseAppend.ts
@@ -1,4 +1,4 @@
-/** 追加页面:选择校验、PDF 合成、过期响应隔离与错误提示。 */
+/** Append pages: selection checks, PDF composition, stale-response isolation, and error notices. */
import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useToast } from '@map/ui';
@@ -15,7 +15,7 @@ import { isPdfAttachment } from '../utils/documentUpload';
import type { useImageParse } from './useImageParse';
import { uploadImageParseDocument } from '../utils/imageParseUpload';
-/** 公网 http 页面里 crypto.randomUUID 会抛错,追加页编号需要能在该页面生成。 */
+/** On a public http page crypto.randomUUID throws; appended-page numbers have to be generable on that page. */
function appendId(): string {
try {
return `append-${crypto.randomUUID()}`;
@@ -33,9 +33,9 @@ const KNOWN_ERRORS = new Set([
]);
/**
- * 管理当前文档的追加页面任务。
- * @param parse 当前工作台状态与 appendDocument 入口
- * @returns 追加中状态、文件入口及取消方法
+ * Manage append-page tasks for the current document.
+ * @param parse current workspace state and the appendDocument entry
+ * @returns appending state, the file entry, and the cancel method
*/
export function useImageParseAppend(parse: ReturnType<typeof useImageParse>) {
const { t } = useTranslation('playground');
@@ -47,7 +47,7 @@ export function useImageParseAppend(parse: ReturnType<typeof useImageParse>) {
const generation = useRef(0);
const latest = useRef(parse);
- // 切换识别档位或附件时先同步复位 UI,再在 effect 中中止外部任务。
+ // When the recognition tier or attachment changes, reset the UI synchronously first, then abort the external task in an effect.
if (resetScope !== scope) {
setResetScope(scope);
setAppending(false);
@@ -68,7 +68,7 @@ export function useImageParseAppend(parse: ReturnType<typeof useImageParse>) {
setAppending(false);
}, [abort]);
- // 切换识别档位或附件时必须中止尚未完成的合成,不能写回旧文档。
+ // When the recognition tier or attachment changes, a composition that has not finished must be aborted and must not be written back onto the old document.
useEffect(() => {
abort();
}, [abort, scope]);
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseCrops.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseCrops.ts
index 9078ee2..d82271d 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseCrops.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseCrops.ts
@@ -2,7 +2,7 @@ import { useCallback, useState } from 'react';
import type { ImageParseSdkResult } from '@/api/map/imageParseSdk';
import { imageParseCrops } from '../utils/imageParseCrops';
-/** 原图裁图只在本次解析有效时落地;失败不影响文字结果。 */
+/** An original-image crop lands only while this parse is still valid; failure does not affect the text result. */
export function useImageParseCrops() {
const [crops, setCrops] = useState<readonly string[]>([]);
const clearCrops = useCallback(() => setCrops([]), []);
@@ -24,7 +24,7 @@ export function useImageParseCrops() {
);
if (isCurrent()) setCrops(next);
} catch {
- // 图片解码/裁切失败不影响解析正文与区块选择。
+ // An image decode or crop failure does not affect the parsed body or block selection.
}
},
[],
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseCurrentRestore.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseCurrentRestore.ts
index 5eb5fb4..1ee7093 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseCurrentRestore.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseCurrentRestore.ts
@@ -18,9 +18,9 @@ interface ImageParseCurrentRestoreOptions {
}
/**
- * 刷新恢复当前文档,侧栏主动进入则清空指针并跳过自动恢复;历史记录仍可手动打开。
- * @param options 当前范围、入口意图及历史恢复入口
- * @returns 用户主动选择、上传或清空时取消自动恢复的入口
+ * Restore the current document on refresh; entering on purpose from the sidebar clears the pointer and skips automatic restore. History records can still be opened manually.
+ * @param options current scope, entry intent, and the history-restore entry
+ * @returns the entry that cancels automatic restore when the user selects, uploads, or clears on purpose
*/
export function useImageParseCurrentRestore({
scope,
@@ -64,7 +64,7 @@ export function useImageParseCurrentRestore({
const sequence = ++request.current;
const record = (async () => {
if (!candidates.length) return load(currentId!, true);
- // 旧工作台允许同一附件保存不同任务;只在该附件的记录中寻找匹配结果。
+ // The old workspace allowed the same attachment to save different tasks; look for a matching result only among that attachment's records.
for (const entry of candidates) {
if (cancelled || sequence !== request.current) return null;
const value = await load(entry.id);
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseDownload.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseDownload.ts
index 75b21aa..62b409d 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseDownload.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseDownload.ts
@@ -18,9 +18,9 @@ interface ImageParseDownloadInput extends ImageParseExportInput {
}
/**
- * 当前 OCR 结果下载:保留点击时的快照,禁止并发生成,失败时恢复入口。
- * @param input 草稿、版面信息、文件名与工作台禁用状态
- * @returns 下载状态与格式选择回调
+ * Download of the current OCR result: keep the snapshot from the click, forbid concurrent generation, and restore the entry on failure.
+ * @param input draft, layout info, file name, and workspace disabled state
+ * @returns download state and the format-selection callback
*/
export function useImageParseDownload(input: ImageParseDownloadInput) {
const { t } = useTranslation('playground');
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseDownloadMenu.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseDownloadMenu.ts
index 9b419c0..1d85a15 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseDownloadMenu.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseDownloadMenu.ts
@@ -1,8 +1,8 @@
import { useEffect, useRef, useState } from 'react';
/**
- * 跟踪下载菜单展开状态,使悬停提示在菜单打开时关闭,避免抢占 Escape。
- * @returns 菜单受控状态与展开回调
+ * Track whether the download menu is open, so the hover tooltip closes while the menu is open and does not take over Escape.
+ * @returns controlled menu state and the open callback
*/
export function useImageParseDownloadMenu(downloading: boolean) {
const [open, setOpen] = useState(false);
@@ -21,7 +21,7 @@ export function useImageParseDownloadMenu(downloading: boolean) {
}
function onCloseAutoFocus(event: Event) {
- // Radix 关闭焦点事件可能延迟触发,读取按钮实时状态避免快速下载完成后误阻止原生回焦。
+ // A Radix close-focus event may fire late; read the button's live state so a fast download finishing does not wrongly block native focus return.
if (!triggerRef.current?.disabled) return;
event.preventDefault();
restoreFocus.current = true;
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseDraft.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseDraft.ts
index 70eba53..3ece88f 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseDraft.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseDraft.ts
@@ -1,14 +1,14 @@
/**
- * 识别结果草稿态。
+ * Draft state of a recognition result.
*
- * 用途:OCR 结果必然有错,光能看不能改就只是个演示。这里把结果变成可编辑草稿,
- * 复制与下载都取草稿而不是原始输出,用户改完就能直接带走。
+ * Purpose: an OCR result is bound to have errors, and if it can only be viewed and not edited it is only a demo. Here the result becomes an editable draft,
+ * and both copy and download take the draft rather than the raw output, so the user can take it away as soon as the edit is done.
*
- * 跟随规则:新一轮解析(含流式推进)会覆盖草稿——那是新结果,不是用户的编辑;
- * 用户自己的改动用 dirty 标出来,并保留一键还原。
+ * Follow rule: a new parse (including streaming progress) overwrites the draft — that is a new result, not the user's edit;
+ * the user's own changes are marked dirty, and a one-click restore is kept.
*
- * 实现上不用 useEffect 同步 state:把编辑连同「它基于哪一版结果」一起存下来,
- * 结果一变,基线不匹配,草稿自然失效并回落到新结果——少一次级联渲染。
+ * Implementation does not sync state with useEffect: the edit is stored together with "which version of the result it is based on".
+ * Once the result changes, the baseline no longer matches, the draft expires on its own, and it falls back to the new result — one less cascading render.
*/
import { useCallback, useState } from 'react';
@@ -17,20 +17,20 @@ import { imageParseDraftRanges } from '../utils/imageParseDraftRanges';
const EMPTY_RANGES: ReadonlyMap<string, ImageParseTextRange> = new Map();
-/** 草稿态。 */
+/** Draft state. */
export interface ImageParseDraft {
- /** 当前文本,复制/下载都用它 */
+ /** Current text; both copy and download use it */
value: string;
- /** 是否不同于基础识别,包含主动重生成,供还原操作使用。 */
+ /** Whether it differs from the base recognition, including an active regeneration, for the restore action. */
dirty: boolean;
- /** 是否存在人工修改;旧调用方未提供时按 dirty 兼容。 */
+ /** Whether there is a manual edit; when an old caller does not provide it, treat it as compatible with dirty. */
manuallyEdited?: boolean;
setValue: (next: string, editedRange?: ImageParseTextRange, source?: 'user' | 'model') => void;
- /** 与当前草稿同步的原图定位范围。 */
+ /** Original-image positioning ranges kept in sync with the current draft. */
ranges: ReadonlyMap<string, ImageParseTextRange>;
- /** 丢弃编辑,回到模型原始输出 */
+ /** Discard the edit and return to the model's raw output */
reset: () => void;
- /** 连续文档预览读取同一草稿缓存,不另建逐页编辑状态。 */
+ /** A continuous document preview reads the same draft cache and does not build a separate per-page edit state. */
forResult?: (
markdown: string,
resultKey: string,
@@ -38,7 +38,7 @@ export interface ImageParseDraft {
) => ImageParseDraft;
}
-/** 一次编辑:value 是改后的文本,base 是它当时基于的模型输出。 */
+/** One edit: value is the text after the change, and base is the model output it was based on at the time. */
interface DraftEdit {
resultKey: string;
base: string;
@@ -48,9 +48,9 @@ interface DraftEdit {
}
/**
- * 把解析结果包装成可编辑草稿。
- * @param markdown 模型原始输出(流式期间会持续变化)
- * @param resultKey 文档与解析轮次标识,防止相同输出恢复上一轮的编辑
+ * Wrap a parse result as an editable draft.
+ * @param markdown raw model output (it keeps changing while streaming)
+ * @param resultKey document and parse-round id, so the same output does not restore the previous round's edit
*/
export function useImageParseDraft(
markdown: string,
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseEntryNavigation.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseEntryNavigation.ts
index 6bae1cf..5e348d4 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseEntryNavigation.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseEntryNavigation.ts
@@ -3,15 +3,15 @@ import { experiencePath } from '../utils/experienceRoute';
import { writeCurrentImageParseId } from '../utils/imageParseCurrent';
import type { ImageParseHistoryEntry } from '../utils/imageParseHistoryTypes';
-/** 两个文档入口分别保存当前指针;全文入口沿用原有存储范围。 */
+/** The two document entries each save the current pointer; the full-text entry keeps the original storage scope. */
function taskScope(userId: unknown, projectId: unknown, task: 'standard' | 'kie') {
return JSON.stringify(task === 'kie' ? [userId, projectId, task] : [userId, projectId]);
}
/**
- * 将历史跳转到对应任务入口,只传隔离范围,不把文件或正文写入路由状态。
- * @param options 当前身份、固定任务及侧栏新建意图
- * @returns 当前存储范围、恢复意图与入口跳转命令
+ * Jump history to the matching task entry, passing only the isolation scope, and do not write the file or the body into route state.
+ * @param options current identity, the fixed task, and the sidebar's new-item intent
+ * @returns the current storage scope, restore intent, and the entry-jump command
*/
export function useImageParseEntryNavigation({
userId,
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseExampleMerge.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseExampleMerge.ts
index 479c33e..5cc4f2f 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseExampleMerge.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseExampleMerge.ts
@@ -7,15 +7,15 @@ import { mergeImageParseTables } from '../utils/imageParseTableMerge';
interface ExampleMergeState {
status: 'idle' | 'merging' | 'merged';
- /** 被合并改动过的页(0 起始) */
+ /** Pages changed by a merge (0-based) */
pages: number[];
}
const MERGE_IDLE: ExampleMergeState = { status: 'idle', pages: [] };
/**
- * 多页示例的跨页表格合并:复用 PDF 的前端表格合并逻辑。
- * 结果只返回有变化的页,由调用方写回示例快照并从原图/结果栏重新渲染。
+ * Cross-page table merge for a multi-page example: reuse the PDF frontend table-merge logic.
+ * The result returns only pages that changed; the caller writes them back to the example snapshot and re-renders from the original image and the result column.
*/
export function useImageParseExampleMerge(
snapshots?: readonly ImageParseSnapshot[],
@@ -52,14 +52,14 @@ export function useImageParseExampleMerge(
setState(MERGE_IDLE);
}, [onMerged]);
- // 切换示例时上一组的合并结果不能带到新一组页面。
+ // When switching examples, the previous group's merge result must not be carried onto the new group's pages.
useEffect(() => {
setState(MERGE_IDLE);
}, [snapshots]);
return {
...state,
- /** 与 PDF 合并共用构建开关;关闭时工具栏不渲染合并按钮。 */
+ /** Shares the build flag with PDF merge; when it is off, the toolbar does not render the merge button. */
enabled: IMAGE_PARSE_CROSS_PAGE_MERGE_ENABLED,
available,
merge,
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseExampleReparse.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseExampleReparse.ts
index f31ddbc..159dd41 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseExampleReparse.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseExampleReparse.ts
@@ -12,19 +12,19 @@ interface ImageParseExampleReparseModel {
}
interface ImageParseExampleReparseOptions {
- /** 共享案例成功恢复后的选择代次;同一代次只自动执行一次。 */
+ /** Selection generation after a shared example restores successfully; each generation runs automatically only once. */
selectionRevision?: number;
- /** 案例加载或识别占用工作台时关闭自动执行。 */
+ /** Turn automatic execution off while an example load or recognition occupies the workspace. */
autoRun?: boolean;
}
/**
- * 把共享示例转换为个人上传任务;选择完成后可自动执行,上传成功后由既有自动识别和历史保存链路接管。
- * @param attachment 当前共享示例
- * @param model 模型权限与默认项目
- * @param upload 个人任务上传入口
- * @param autoRunOptions 选择代次与自动执行开关
- * @returns 是否可重跑及重跑回调
+ * Turn a shared example into a personal upload task; it may run automatically after selection, and after a successful upload the existing automatic recognition and history-save path takes over.
+ * @param attachment current shared example
+ * @param model model permission and default project
+ * @param upload upload entry for a personal task
+ * @param autoRunOptions selection generation and the automatic-execution switch
+ * @returns whether it can be run again, and the rerun callback
*/
export function useImageParseExampleReparse(
attachment: Attachment | undefined,
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseExamples.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseExamples.ts
index 7c932bb..fdca505 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseExamples.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseExamples.ts
@@ -14,11 +14,11 @@ import type { ImageParseSnapshot } from '../utils/imageParseHistoryTypes';
import { useImageParseExampleMerge } from './useImageParseExampleMerge';
/**
- * 读取数据库共享案例,并在同一页面会话内复用已校验快照。
- * @param onReady 工作台快照恢复入口
- * @param scope 当前账号和项目范围
- * @param attachmentId 当前附件 ID,用于隔离旧案例的翻页回调
- * @returns 案例加载、取消、忙碌状态及图片组分页
+ * Read shared examples from the database, and reuse a validated snapshot within the same page session.
+ * @param onReady workspace snapshot-restore entry
+ * @param scope current account and project scope
+ * @param attachmentId current attachment ID, used to isolate paging callbacks of an old example
+ * @returns example loading, cancellation, busy state, and image-group paging
*/
export function useImageParseExamples(
onReady: (snapshot: ImageParseSnapshot) => boolean,
@@ -110,7 +110,7 @@ export function useImageParseExamples(
return;
const currentIndex = active.page - 1;
if (!merged.size) {
- // 取消合并:撤销上一次写回的合并结果;合并请求没有变化时不应改写快照。
+ // Cancel merge: undo the merge result written back last time; when the merge request has not changed, the snapshot must not be rewritten.
if (!active.mergedSnapshots) return;
setGroup((previous) => {
if (previous !== active) return previous;
@@ -127,7 +127,7 @@ export function useImageParseExamples(
return result ? { ...snapshot, markdown: result.markdown, layout: result.blocks } : snapshot;
});
setGroup((previous) => (previous === active ? { ...previous, mergedSnapshots } : previous));
- // 只有当前页发生变化时才替换正在展示的结果;其他页在翻页时读取 mergedSnapshots。
+ // Replace the result on display only when the current page changed; other pages read mergedSnapshots when the user turns the page.
const currentSnapshot = mergedSnapshots[currentIndex];
if (merged.has(currentIndex) && currentSnapshot) current.current.onReady(currentSnapshot);
});
@@ -136,7 +136,7 @@ export function useImageParseExamples(
active.current?.abort();
sequence.current++;
setGroup(undefined);
- // mutation 异步启动前也必须能取消,避免同一事件中的新建/上传被旧案例覆盖。
+ // It must also be cancellable before the mutation starts asynchronously, so a create or upload in the same event is not overwritten by an old example.
const controller = new AbortController();
active.current = controller;
const key = cacheKey(type);
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseExecution.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseExecution.ts
index a63bf12..d0bc672 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseExecution.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseExecution.ts
@@ -62,10 +62,10 @@ interface ImageParseExecutionOptions {
}
/**
- * 执行单张图片或 PDF 的识别请求,并隔离取消、超时和过期响应。
- * 所有任务只调用 MAP 同源算法代理,识别前必须取得文件服务 fileId。
- * @param options 当前附件、档位、凭据、状态写入器与裁图编排
- * @returns parse 与 stop 入口;并发请求由 generation 和 AbortSignal 淘汰
+ * Run the recognition request for a single image or a PDF, and isolate cancellation, timeout, and stale responses.
+ * Every task calls only the same-origin MAP algorithm proxy, and a file-service fileId must be obtained before recognition.
+ * @param options current attachment, tier, credentials, state writer, and crop orchestration
+ * @returns parse and stop entries; concurrent requests are retired by generation and AbortSignal
*/
export function useImageParseExecution(options: ImageParseExecutionOptions) {
const queryClient = useContext(QueryClientContext);
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseExperienceTour.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseExperienceTour.ts
index 7650346..add0ebf 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseExperienceTour.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseExperienceTour.ts
@@ -13,9 +13,9 @@ interface UseImageParseExperienceTourOptions {
}
/**
- * 按当前识别任务选择文档解析或关键信息抽取引导。
- * @param options 任务类型、账号状态与两类任务的就绪状态
- * @returns 当前任务的新手引导重播入口
+ * Choose the document-parsing or key information extraction tour from the current recognition task.
+ * @param options task type, account state, and the readiness of the two task kinds
+ * @returns the replay entry for the current task's guided tour
*/
export function useImageParseExperienceTour({
task,
@@ -40,7 +40,7 @@ export function useImageParseExperienceTour({
enabled: task === 'kie' && Boolean(userId && projectId),
ready,
hasDocument,
- // 字段配置和结果核对都属于可继续引导的阶段;错误或运行中由 ready/failed 暂停。
+ // Field configuration and result checking are both phases the tour can continue; an error or a run in progress is paused by ready/failed.
hasResult: hasKieResult,
resultReady: hasDocument && ready,
failed,
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseFieldDraft.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseFieldDraft.ts
index ad8c6c7..759c945 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseFieldDraft.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseFieldDraft.ts
@@ -1,10 +1,10 @@
import { useState } from 'react';
/**
- * 隔离字段配置草稿与已提交字段,同一文件切换任务时保留尚未提交的配置。
- * @param applied 当前结果对应的已提交字段
- * @param documentKey 文件与账号范围标识
- * @returns 配置字段、更新和放弃草稿入口
+ * Isolate the field-configuration draft from the submitted fields, and keep unsubmitted configuration when the same file switches tasks.
+ * @param applied submitted fields that correspond to the current result
+ * @param documentKey file and account-scope id
+ * @returns configuration fields, and the entries that update and discard the draft
*/
export function useImageParseFieldDraft(applied: readonly string[], documentKey: string) {
const [draft, setDraft] = useState<{ key: string; fields: string[] }>();
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseFormulaNode.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseFormulaNode.ts
index dd39fad..c5df05c 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseFormulaNode.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseFormulaNode.ts
@@ -6,7 +6,7 @@ import { ImageParseFormulaEditContext } from '../utils/imageParseFormulaEditCont
import { isSupportedKatex } from '../utils/math-katex';
import { SAFE_KATEX_OPTIONS } from '../utils/math-options';
-/** 管理公式原位输入和节点事务;只有显式双击或键盘操作才从展示切换到输入。 */
+/** Manage in-place formula input and the node transaction; only an explicit double-click or keyboard action switches from display to input. */
export function useImageParseFormulaNode({
editor,
node,
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseGuidedTour.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseGuidedTour.ts
index c60ed85..d6ca7ae 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseGuidedTour.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseGuidedTour.ts
@@ -13,21 +13,21 @@ export interface UseImageParseGuidedTourOptions {
tourId: string;
userId?: string;
enabled: boolean;
- /** 首屏身份、历史与当前文档初始化结束后才自动启动。 */
+ /** Start automatically only after first-screen identity, history, and the current document have finished initializing. */
ready?: boolean;
hasDocument?: boolean;
- /** 当前阶段可展示目标;不同任务可分别表示配置就绪或结果就绪。 */
+ /** Targets the current phase can show; different tasks may mean configuration ready or result ready. */
resultReady?: boolean;
- /** 上传失败、识别失败或用户停止时,取消自动恢复。 */
+ /** Cancel automatic resume when upload fails, recognition fails, or the user stops. */
failed?: boolean;
gateSelectors: readonly string[];
buildSteps: (hasDocument: () => boolean) => DriveStep[];
}
/**
- * 图像解析任务共用的首次引导生命周期,负责任务状态暂停、恢复与已读记录。
- * @param options 引导标识、步骤构造和当前任务状态
- * @returns 手动重播引导的入口
+ * Shared first-visit tour lifecycle for image-parsing tasks, responsible for pausing and resuming on task state, and for the seen record.
+ * @param options tour id, step builder, and current task state
+ * @returns the entry that replays the tour manually
*/
export function useImageParseGuidedTour({
tourId,
@@ -78,7 +78,7 @@ export function useImageParseGuidedTour({
clearTourStepHighlight();
stopLayoutTracking.current();
markSeen();
- // 动画尚未完成时 driver 不一定触发 onDestroyed,用户关闭必须在此清理。
+ // Before the animation finishes, driver may not fire onDestroyed; a user close must clean up here.
tourRef.current = null;
instance.destroy();
},
@@ -93,7 +93,7 @@ export function useImageParseGuidedTour({
tour.drive();
}, [buildSteps, closeAutoOpenedMenu, markSeen, openMenuForStep, t]);
- // 语言变化更新下次启动的步骤,不中途销毁引导。
+ // A language change updates the steps for the next start, and does not destroy the tour halfway.
const startRef = useRef(start);
useLayoutEffect(() => {
documentRef.current = hasDocument;
@@ -112,10 +112,10 @@ export function useImageParseGuidedTour({
tourRef.current = null;
active?.destroy();
}, [closeAutoOpenedMenu]);
- // 程序化清理不走用户关闭钩子,避免切页或账号切换被误记为已读。
+ // Programmatic cleanup does not go through the user-close hook, so changing pages or accounts is not recorded as seen by mistake.
useEffect(() => stop, [enabled, userId, tourId, stop]);
- // 上传/识别时移除遮罩,保留步骤;只在当前任务目标就绪后恢复。
+ // While uploading or recognizing, remove the mask and keep the step; resume only after the current task's target is ready.
useEffect(() => {
if (!enabled || !userId) return;
if (failed) {
@@ -170,7 +170,7 @@ export function useImageParseGuidedTour({
tourRef.current?.isActive()
)
return;
- // 等首屏布局稳定再弹,避免遮罩跟着布局抖动。
+ // Wait for the first-screen layout to settle before popping, so the mask does not jitter with the layout.
timerRef.current = window.setTimeout(() => {
timerRef.current = undefined;
pendingReplay.current = false;
@@ -181,7 +181,7 @@ export function useImageParseGuidedTour({
timerRef.current = undefined;
};
}, [enabled, userId, ready, hasDocument, resultReady, failed, seen]);
- /** 手动重播忽略已读记录,初始化中则等页面就绪。 */
+ /** A manual replay ignores the seen record, and waits for the page to be ready if initialization is still in progress. */
const replay = useCallback(() => {
if (!enabled || !userId) return;
stop();
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseHighlight.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseHighlight.ts
index 27322d3..db222ec 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseHighlight.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseHighlight.ts
@@ -3,8 +3,8 @@ import type { ImageParseLinkedRange } from '../utils/imageParseHighlight';
import type { ImageParseTextRange } from '../utils/imageParseBlocks';
/**
- * 更新映射节点的选中标记与滚动位置,不触发 Markdown、公式和代码重新解析。
- * 隐藏预览时只更新标记,切回预览后再定位,避免滚动到不可见节点。
+ * Update the selected marker and scroll position of mapped nodes, without re-parsing Markdown, formulas, and code.
+ * While the preview is hidden, update only the marker, and position again after switching back to the preview, so it does not scroll to an invisible node.
*/
export function useImageParseHighlight(
ref: RefObject<HTMLElement | null>,
@@ -58,7 +58,7 @@ export function useImageParseHighlight(
}
const element = ref.current;
if (!element) return;
- // 无修改退出编辑也会重新挂载预览节点;仅监听结构变化,标记更新不触发监听循环。
+ // Leaving edit with no change also remounts preview nodes; observe only structural changes, so a marker update does not trigger an observation loop.
const observer = new MutationObserver((records) => {
if (
records.some(
@@ -84,7 +84,7 @@ export function useImageParseHighlight(
]);
}
-/** 计算结果块在当前滚动容器内居中的位置,避免滚动链影响工作台外层页面。 */
+/** Compute the position that centers a result block inside the current scroll container, so the scroll chain does not affect the page outside the workspace. */
function centeredScrollTop(viewport: HTMLElement, target: HTMLElement): number {
const bounds = viewport.getBoundingClientRect();
const viewportHeight = viewport.clientHeight || bounds.height;
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseHistory.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseHistory.ts
index 642c607..c3a726c 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseHistory.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseHistory.ts
@@ -19,7 +19,7 @@ import type {
const EMPTY_HISTORY: ImageParseHistorySummary[] = [];
-/** 历史详情短缓存;写入只失效变更记录,手动刷新才失效全部详情。 */
+/** Short cache of history details; a write invalidates only the changed record, and only a manual refresh invalidates every detail. */
const ENTRY_CACHE = { staleTime: 30_000, gcTime: 120_000 } as const;
export type {
@@ -27,7 +27,7 @@ export type {
UseImageParseHistoryResult,
} from '../utils/imageParseHistoryTypes';
-/** 用查询缓存管理云端历史;自动保存串行执行,切换账号后不提交旧范围的排队写入。 */
+/** Manage cloud history with the query cache; autosave runs serially, and after an account switch a queued write for the old scope is not submitted. */
export function useImageParseHistory({
userId,
projectId,
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseHistoryAutosave.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseHistoryAutosave.ts
index 35bcb77..154ec71 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseHistoryAutosave.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseHistoryAutosave.ts
@@ -21,9 +21,9 @@ interface ImageParseHistoryAutosaveOptions {
}
/**
- * 自动存档仅观察实际结果变化;失败后后续阅读操作可限频重试,恢复记录不重复上传。
- * @param options 当前账号范围、已完成快照和串行保存入口
- * @returns 标记恢复记录身份的入口
+ * Autosave observes only real result changes; after a failure, later reading actions may retry at a limited rate, and a restored record is not uploaded again.
+ * @param options current account scope, finished snapshot, and the serial save entry
+ * @returns the entry that marks the identity of a restored record
*/
export function useImageParseHistoryAutosave({
scopeKey,
@@ -34,7 +34,7 @@ export function useImageParseHistoryAutosave({
}: ImageParseHistoryAutosaveOptions) {
const state = useRef<AutosaveState>({ skipNextSave: false });
useLayoutEffect(() => {
- // 父级清除旧快照前不能把同一结果提交到新账号;仅丢弃旧范围的恢复与重试状态。
+ // Before the parent clears the old snapshot, the same result must not be submitted to the new account; only the old scope's restore and retry state is discarded.
state.current = { seen: state.current.seen, skipNextSave: false };
}, [scopeKey]);
const setActiveEntry = useCallback(
@@ -61,7 +61,7 @@ export function useImageParseHistoryAutosave({
Date.now() >= failed.retryAt &&
sameImageParseHistoryContent(failed.snapshot, snapshot);
if (sameImageParseHistoryContent(previous, snapshot) && !retry) return;
- // 提交时清除失败资格,避免未返回的重试因连续滚动再次排队。
+ // Clear failure eligibility on submit, so a retry that has not returned is not queued again by continuous scrolling.
observed.failed = undefined;
void save(snapshot).then((saved) => {
if (!current() || state.current !== observed) return;
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseHistoryLifecycle.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseHistoryLifecycle.ts
index db54b2b..f22d380 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseHistoryLifecycle.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseHistoryLifecycle.ts
@@ -21,9 +21,9 @@ interface ImageParseHistoryLifecycleOptions {
}
/**
- * 在范围/模式变化时取消旧任务;缓存恢复可同步更新有效范围而不重新识别。
- * @param options 当前任务范围、状态与取消/识别入口
- * @returns 快照有效标识与恢复边界的更新函数
+ * Cancel the old task when the scope or mode changes; a cache restore can update the valid scope synchronously without running recognition again.
+ * @param options current task scope, state, and the cancel/recognition entries
+ * @returns the snapshot-valid flag and the function that updates the restore boundary
*/
export function useImageParseHistoryLifecycle({
scope,
@@ -95,9 +95,9 @@ interface ImageParseHistorySnapshotOptions {
const EMPTY_LAYOUT: readonly ImageParseLayoutBlock[] = [];
/**
- * 上传后立即派生可保存快照;未完成时只保留原件,重新打开后继续识别。
- * @param options 识别结果及当前任务的有效状态
- * @returns 可保存的图片/PDF 快照;共享案例或范围失效时返回 null
+ * Derive a snapshot that can be saved immediately after upload; while it is unfinished, keep only the original, and continue recognition after it is opened again.
+ * @param options recognition result and the valid state of the current task
+ * @returns an image/PDF snapshot that can be saved; null for a shared example or when the scope is no longer valid
*/
export function useImageParseHistorySnapshot({
attachment,
@@ -117,7 +117,7 @@ export function useImageParseHistorySnapshot({
return useMemo(() => {
if (!attachment || !valid || isImageParseSharedExample(attachment.id)) return null;
if (pdfActive && mode === 'seal') return null;
- // 后端要求 kie 快照携带合法字段;字段尚未填好时不要创建或覆盖历史。
+ // The backend requires a kie snapshot to carry legal fields; do not create or overwrite history before the fields are filled in.
if (mode === 'kie' && imageParseKieFieldsError(fields ?? [])) return null;
if (pdfActive) {
if (!pdf) return null;
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseHistoryRestore.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseHistoryRestore.ts
index ea9ae3f..ffae0be 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseHistoryRestore.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseHistoryRestore.ts
@@ -27,7 +27,7 @@ interface ImageParseHistoryRestoreContext {
setImage: (attachment?: Attachment) => void;
cancel: () => void;
loadCrops: ReturnType<typeof useImageParseCrops>['loadCrops'];
- /** 图片还没有识别结果时,恢复后继续自动识别。 */
+ /** When the image does not have a recognition result yet, continue automatic recognition after restore. */
markPending?: () => void;
}
@@ -43,10 +43,10 @@ interface ImageParseHistoryRestoreSetters {
}
/**
- * 恢复缓存只重建本地结果和裁图,同步取消自动执行与旧 OCR 回调。
- * @param context 当前任务范围、取消边界和 PDF 编排
- * @param setters 原始识别结果的状态写入器
- * @returns 接受快照并报告是否有效的恢复函数;后续识别使用工作台默认档位
+ * A cache restore rebuilds only the local result and crops, and synchronously cancels automatic execution and old OCR callbacks.
+ * @param context current task scope, cancel boundary, and PDF orchestration
+ * @param setters state writers for the raw recognition result
+ * @returns a restore function that accepts a snapshot and reports whether it is valid; later recognition uses the workspace default tier
*/
export function useImageParseHistoryRestore(
{
@@ -69,7 +69,7 @@ export function useImageParseHistoryRestore(
setResultRevision,
}: ImageParseHistoryRestoreSetters,
) {
- // 固定共享案例快照在当前会话内不变;普通历史每次仍按不可信输入校验。
+ // A fixed shared-example snapshot does not change within the current session; ordinary history is still validated as untrusted input every time.
const examples = useRef(new WeakMap<ImageParseSnapshot, ImageParseSnapshot>());
return useCallback(
(value: ImageParseSnapshot, options?: { previewOnly?: boolean; finished?: boolean }) => {
@@ -82,8 +82,8 @@ export function useImageParseHistoryRestore(
});
if (!safe) return false;
if (reuse) examples.current.set(value, safe);
- // 既有 LIS 档位恢复后回到默认档位;流水线档位必须保留,否则 KIE 字段与
- // 印章结果会被下一次识别当成文档解析。
+ // An existing LIS tier returns to the default tier after restore; a pipeline tier must be kept, or KIE fields and
+ // seal results would be treated as document parsing by the next recognition.
const cached = {
...safe,
mode: isImageParsePipelineMode(safe.mode) ? safe.mode : IMAGE_PARSE_DEFAULT_MODE,
@@ -97,7 +97,7 @@ export function useImageParseHistoryRestore(
setFields?.(cached.mode === 'kie' ? [...(cached.fields ?? [])] : []);
setMarkdown(cached.markdown);
setLayout(cached.layout);
- // 默认档位仅影响后续解析,不能改写历史 source 中的真实模型和服务端时间。
+ // The default tier affects only later parsing, and must not rewrite the real model and server time in the history source.
setSource?.(cached.source);
setRotation?.(cached.rotation);
const imagePending =
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseHistoryState.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseHistoryState.ts
index 3d36fe2..c96c115 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseHistoryState.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseHistoryState.ts
@@ -56,9 +56,9 @@ interface ImageParseHistoryStateOptions {
}
/**
- * 连接识别状态与历史恢复:范围/档位变化时失效旧快照,并派生页眉页脚过滤后的可见结果。
- * @param options 当前识别状态、历史恢复上下文与全部状态写入器
- * @returns 可保存快照、恢复入口、PDF 错误与当前可见结果
+ * Connect recognition state and history restore: invalidate the old snapshot when the scope or tier changes, and derive the visible result after header and footer filtering.
+ * @param options current recognition state, history-restore context, and every state writer
+ * @returns the snapshot that can be saved, the restore entry, the PDF error, and the currently visible result
*/
export function useImageParseHistoryState(options: ImageParseHistoryStateOptions) {
const {
@@ -148,7 +148,7 @@ export function useImageParseHistoryState(options: ImageParseHistoryStateOptions
currentSource = pdfActive ? pdf.current?.result?.source : source;
currentRotation = pdfActive ? pdf.current?.result?.rotation : rotation;
}
- // 单图结果的页眉页脚过滤;PDF 在 usePdfImageParse 里过滤。历史快照仍存原始结果。
+ // Header and footer filtering for a single-image result; a PDF is filtered in usePdfImageParse. The history snapshot still stores the raw result.
const visible = useMemo(() => {
const stable = stabilizeImageParseResult({ markdown, blocks: layout });
return hideHeaderFooter ? hideImageParseHeaderFooter(stable) : stable;
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseImageState.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseImageState.ts
index 33bed44..564d2a5 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseImageState.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseImageState.ts
@@ -15,10 +15,10 @@ import { useImageParseCrops } from './useImageParseCrops';
import { useImageParseTaskState } from './useImageParseTaskState';
/**
- * 维护单图原始结果和请求身份;替换文件时统一清理旧状态。
- * @param autoParse 是否兼容上传后自动识别
- * @param autoParseOnUpload 是否仅在新文件就绪时自动启动全文识别
- * @returns 原件、结果、任务选项和状态写入入口
+ * Maintain the single-image raw result and request identity; when the file is replaced, clear the old state together.
+ * @param autoParse whether to stay compatible with automatic recognition after upload
+ * @param autoParseOnUpload whether to start full-text recognition automatically only when a new file is ready
+ * @returns the original, the result, task options, and the state-write entry
*/
export function useImageParseImageState(
autoParse: boolean,
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseKieFieldEditor.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseKieFieldEditor.ts
index 17b7b25..1c1c8cd 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseKieFieldEditor.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseKieFieldEditor.ts
@@ -3,10 +3,10 @@ import { useState, type ClipboardEvent } from 'react';
import { imageParseKieFieldsError, splitImageParseKieFields } from '../utils/imageParseKie';
/**
- * 编排单个或批量字段输入,失败保留草稿;主操作包含尚未加入列表的输入。
- * @param fields 已配置的字段
- * @param onChange 字段列表更新入口
- * @returns 输入草稿、即时错误、待提交字段与添加结果
+ * Orchestrate single or batch field input, and keep the draft on failure; the primary action includes input that has not been added to the list yet.
+ * @param fields fields already configured
+ * @param onChange entry that updates the field list
+ * @returns the input draft, the immediate error, fields waiting to be submitted, and the add result
*/
export function useImageParseKieFieldEditor(
fields: readonly string[],
@@ -44,7 +44,7 @@ export function useImageParseKieFieldEditor(
if (splitImageParseKieFields(text).length < 2) return;
event.preventDefault();
const input = event.currentTarget;
- // 合并选区前后的草稿,避免粘贴批量字段时丢掉已经输入的文字。
+ // Merge the draft before and after the selection, so pasting a batch of fields does not drop text that was already typed.
const value = draft.slice(0, input.selectionStart) + text + draft.slice(input.selectionEnd);
add(value);
}
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseKieFieldSelection.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseKieFieldSelection.ts
index 572b582..544c2b5 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseKieFieldSelection.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseKieFieldSelection.ts
@@ -1,11 +1,11 @@
import { useState } from 'react';
/**
- * 管理字段多选与待确认删除快照,确认前不修改字段。
- * @param fields 当前字段
- * @param onChange 字段更新回调
- * @param disabled 是否禁止修改
- * @returns 选择状态、全选和确认删除入口
+ * Manage multi-select of fields and the delete snapshot waiting for confirmation, and do not modify fields before confirmation.
+ * @param fields current fields
+ * @param onChange field-update callback
+ * @param disabled whether modification is forbidden
+ * @returns selection state, and the select-all and confirm-delete entries
*/
export function useImageParseKieFieldSelection(
fields: readonly string[],
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseKieTour.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseKieTour.ts
index 5148b97..266edf1 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseKieTour.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseKieTour.ts
@@ -7,7 +7,7 @@ import {
type UseImageParseGuidedTourOptions,
} from './useImageParseGuidedTour';
-/** 关键信息抽取引导的稳定已读标识;历史版本记录按同族引导兼容。 */
+/** Stable seen id for the key information extraction tour; history version records are compatible as the same family of tour. */
export const IMAGE_PARSE_KIE_TOUR_ID = 'image-parse-kie';
const GATE_SELECTORS = [
'[data-tour="image-parse-kie-examples"]',
@@ -18,14 +18,14 @@ type UseImageParseKieTourOptions = Omit<
UseImageParseGuidedTourOptions,
'tourId' | 'gateSelectors' | 'buildSteps'
> & {
- /** 已有结果时用于裁剪步骤,避免指向已卸载的字段配置面板。 */
+ /** Used to trim steps when a result already exists, so they do not point at a field-configuration panel that has unmounted. */
hasResult?: boolean;
};
/**
- * 关键信息抽取首次访问引导;示例载入后介绍字段配置、开始抽取与结果核对。
- * @param options 是否启用与当前任务状态
- * @returns 手动重播引导的入口
+ * First-visit tour for key information extraction; after the example loads, it introduces field configuration, starting extraction, and checking the result.
+ * @param options whether it is enabled, and the current task state
+ * @returns the entry that replays the tour manually
*/
export function useImageParseKieTour({
hasResult = false,
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParsePageDrop.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParsePageDrop.ts
index f7d9f92..d1be3af 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParsePageDrop.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParsePageDrop.ts
@@ -6,10 +6,10 @@ import type { DocumentFileRules } from '../utils/documentUpload';
import { applyPreparedDocument } from '../utils/imageGroupPdf';
/**
- * 接管工作台空白区域的整页拖放,复用上传前的 PDF/图片预处理。
- * @param onFile 已通过拖放校验的单文件处理入口
- * @param rules 当前识别档位的格式与数量边界
- * @returns 拖拽高亮状态与可直接展开到容器的拖放事件
+ * Take over whole-page drag and drop on the empty workspace area, reusing the PDF/image preprocessing that runs before upload.
+ * @param onFile entry that handles the single file that has already passed the drop checks
+ * @param rules format and count bounds of the current recognition tier
+ * @returns drag-highlight state and drop events that can be spread onto the container directly
*/
export function useImageParsePageDrop(
onFile: (file: File) => void,
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParsePdfPreview.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParsePdfPreview.ts
index 28bb6ff..921aba0 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParsePdfPreview.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParsePdfPreview.ts
@@ -10,7 +10,7 @@ import type { useImageParse } from './useImageParse';
type PdfState = NonNullable<ReturnType<typeof useImageParse>['pdf']>;
-/** 连续结果按页测量并缓存高度;编辑页与当前定位页必须保持挂载。 */
+/** Continuous results measure and cache height per page; the page being edited and the page currently positioned must stay mounted. */
export function useImageParsePdfPreview(
pdf: PdfState,
pageKey: (page: number) => string,
@@ -25,7 +25,7 @@ export function useImageParsePdfPreview(
const reportedPage = useRef(pdf.page);
const previousPage = useRef(0);
const previousFocus = useRef(focusRequest);
- // 保留全部页骨架;未完成页显示等待态,左右滚动才能始终按页码联动。
+ // Keep every page skeleton; an unfinished page shows a waiting state, so left and right scrolling can always stay linked by page number.
const pages = useMemo(
() => Array.from({ length: pdf.pages }, (_, index) => index + 1),
[pdf.pages],
@@ -58,7 +58,7 @@ export function useImageParsePdfPreview(
paddingStart: 0,
measureElement: (element, entry, instance) => {
const height = entry?.borderBoxSize?.[0]?.blockSize ?? element.getBoundingClientRect().height;
- // 标签隐藏时 ResizeObserver 报零高度,不能清掉已测量的页面尺寸。
+ // When the tab is hidden, ResizeObserver reports zero height, and the page size already measured must not be cleared.
return (
height || instance.itemSizeCache.get(pageKey(Number(element.dataset.ocrResultPage))) || 720
);
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParsePipelineCapabilities.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParsePipelineCapabilities.ts
index 76b01ce..3103716 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParsePipelineCapabilities.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParsePipelineCapabilities.ts
@@ -14,8 +14,8 @@ const UNAVAILABLE: ImageParsePipelineCapabilities = {
};
/**
- * 探测后端流水线能力。仅在用户与文档解析模型就绪时请求,测试和无权限用户
- * 不会因为多一次网络请求改变原有工作台行为。
+ * Probe backend pipeline capabilities. Request only when the user and the document-parsing model are ready; tests and users without permission
+ * do not change existing workspace behavior because of one extra network request.
*/
export function useImageParsePipelineCapabilities(enabled: boolean): ImageParsePipelineCapabilities {
const query = useQuery({
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParsePreviewAction.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParsePreviewAction.ts
index cc4fc8a..9003538 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParsePreviewAction.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParsePreviewAction.ts
@@ -8,7 +8,7 @@ interface ActionPosition {
height: number;
}
-/** 跟踪选中块的位置;操作条放在块外,不跟随悬停变化。 */
+/** Track the selected block's position; the action bar sits outside the block and does not follow hover. */
export function useImageParsePreviewAction(
ref: RefObject<HTMLElement | null>,
selectedId: string | undefined,
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseReadingPosition.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseReadingPosition.ts
index bc26525..78239c5 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseReadingPosition.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseReadingPosition.ts
@@ -7,17 +7,17 @@ import {
} from '../utils/imageParseReadingAnchor';
interface ImageParseReadingPositionOptions {
- /** 当前页或当前结果身份;换页、换文件时重新捕获,不做跨文档跳动。 */
+ /** Identity of the current page or the current result; recapture when the page or file changes, and do not jump across documents. */
resultKey: string;
- /** 只改变展示内容、需要保持阅读位置的开关,例如页眉页脚。 */
+ /** A switch that only changes what is shown and needs to keep the reading position, such as header and footer. */
preserveKey: unknown;
- /** 使用结果栏已有的程序化滚动入口,避免联动把原文栏一起改写。 */
+ /** Use the programmatic scroll entry the result column already has, so linking does not rewrite the original column as well. */
scrollTo?: (top: number) => void;
}
/**
- * 在内容开关切换前后保持结果栏阅读位置。
- * 捕获与恢复都在布局阶段完成,避免先绘制跳位后的内容再滚动。
+ * Keep the result column's reading position across a content-switch toggle.
+ * Both capture and restore finish in the layout phase, so content after a jump is not painted before the scroll.
*/
export function useImageParseReadingPosition({
resultKey,
@@ -35,7 +35,7 @@ export function useImageParseReadingPosition({
const capture = useCallback(() => {
if (!viewport) return;
const next = captureImageParseReadingAnchor(viewport);
- // 标签隐藏时视口高度为 0;保留上一次可见时的定位点。
+ // When the tab is hidden the viewport height is 0; keep the anchor from the last time it was visible.
if (next) anchor.current = next;
}, [viewport]);
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseRecognitionAutoRun.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseRecognitionAutoRun.ts
index 25bcd27..92555f0 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseRecognitionAutoRun.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseRecognitionAutoRun.ts
@@ -3,17 +3,17 @@ import { useEffect, useRef } from 'react';
interface ImageParseRecognitionAutoRunOptions {
upright: boolean;
recognizeSeal: boolean;
- /** 当前附件是否已有稳定结果;回到识别中时仍保留上一轮的结果标记。 */
+ /** Whether the current attachment already has a stable result; while it returns to recognizing, the previous round's result mark is still kept. */
hasResult: boolean;
- /** 附件身份变化时重置上一轮结果标记。 */
+ /** Reset the previous round's result mark when the attachment identity changes. */
identity?: string;
- /** 使用最新识别参数重新执行当前任务。 */
+ /** Run the current task again with the latest recognition parameters. */
onReRun: () => void;
}
/**
- * 摆正变化时自动重跑;印章开关只影响展示,不触发请求。
- * @param options 当前识别参数、结果状态、附件身份和重跑入口
+ * Re-run automatically when rotation adaptation changes; the seal switch only affects display and does not trigger a request.
+ * @param options current recognition parameters, result state, attachment identity, and the rerun entry
*/
export function useImageParseRecognitionAutoRun({
upright,
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseRegeneration.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseRegeneration.ts
index 25e32b4..8c6f841 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseRegeneration.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseRegeneration.ts
@@ -16,9 +16,9 @@ import {
interface RegenerationInput {
resultKey: string;
- /** 当前登录用户可见的文档解析模型 ID。 */
+ /** Document-parsing model ID visible to the current logged-in user. */
model: string;
- /** 当前选中 API Key 的明文密钥;仅内存传入,不落盘。 */
+ /** Plaintext secret of the currently selected API Key; passed in memory only and not persisted to disk. */
secret: string;
blocks: readonly ImageParseLayoutBlock[];
draft: ImageParseDraft;
@@ -27,11 +27,11 @@ interface RegenerationInput {
pageIndex: number;
loading: boolean;
source?: ImageParseSource;
- /** 请求终态后刷新 Playground 免费体验状态。 */
+ /** Refresh Playground free-trial state after a request reaches a terminal state. */
refreshTrial?: () => void;
}
-/** 编排主动块优化:限制预算、保护人工修改,并中止跨文档/页码的旧任务。 */
+/** Orchestrate active block optimization: limit the budget, protect manual edits, and abort old tasks that cross documents or page numbers. */
export function useImageParseRegeneration(input: RegenerationInput) {
const { resultKey, blocks } = input;
const { refreshTrial } = input;
@@ -81,7 +81,7 @@ export function useImageParseRegeneration(input: RegenerationInput) {
histories: previous.histories,
pending: new Set(eligibleIds),
}));
- // 批量按顺序调用,避免低分块数量放大服务并发;每块独立失败不会清空已完成结果。
+ // Call the batch in order, so the number of low-score blocks does not amplify service concurrency; one block failing on its own does not clear results already finished.
for (const id of eligibleIds) {
if (!isCurrent()) break;
const original = blocks.find((block, index) => imageParseBlockId(block, index) === id);
@@ -120,7 +120,7 @@ export function useImageParseRegeneration(input: RegenerationInput) {
onApply: (next, range) => {
const draft = latest.current.draft;
draft.setValue(next, range, 'model');
- // React 可合并整批提交,下一块必须同步取得更新后的文本与偏移。
+ // React may batch the whole commit; the next block must synchronously obtain the updated text and offsets.
latest.current = {
...latest.current,
draft: {
@@ -150,7 +150,7 @@ export function useImageParseRegeneration(input: RegenerationInput) {
pending: new Set([...previous.pending].filter((item) => item !== id)),
}));
}
- // 每个块优化都是一次真实 L2 请求;批量结束后刷新免费次数。
+ // Each block optimization is a real L2 request; refresh the free count after the batch ends.
refreshTrial?.();
if (active.current === controller) {
active.current = null;
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseRegionCopy.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseRegionCopy.ts
index e0e6293..fa8370a 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseRegionCopy.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseRegionCopy.ts
@@ -14,9 +14,9 @@ interface ImageParseRegionCopyOptions {
}
/**
- * 复制选中识别块;范围缺失或写入失败时给出稳定错误提示。
- * @param options 当前草稿、块范围与提示入口
- * @returns 接受块 ID 的复制回调
+ * Copy the selected recognition block; when the range is missing or the write fails, show a stable error notice.
+ * @param options current draft, block ranges, and the notice entry
+ * @returns a copy callback that accepts a block ID
*/
export function useImageParseRegionCopy({
markdown,
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseResultPagination.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseResultPagination.ts
index 161ef11..91549ec 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseResultPagination.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseResultPagination.ts
@@ -1,6 +1,6 @@
import { useCallback, useLayoutEffect, useRef, useState } from 'react';
-/** PDF 页码状态与结果身份,用于在现有单页结果栏中接续阅读。 */
+/** PDF page state and result identity, used to continue reading in the existing single-page result column. */
export interface ImageParseResultPaginationOptions {
pdf?: { page: number; pages: number; setPage: (page: number) => void };
resultKeyForPage: (page?: number) => string;
@@ -12,11 +12,11 @@ const GESTURE_IDLE_MS = 160;
const PAGE_TURN_INTERVAL_MS = 320;
/**
- * 当前页预览到达边界后翻页;正文滚动、编辑和缩放继续使用原生交互。
- * @param resultKey 当前结果身份
- * @param options PDF 页码与结果身份
- * @param onEnter 新页挂载后定位到页首或页尾
- * @returns 结果栏根节点 ref,空页和失败页也可接收翻页手势
+ * Turn the page when the current-page preview reaches an edge; body scroll, editing, and zoom keep using native interaction.
+ * @param resultKey current result identity
+ * @param options PDF page number and result identity
+ * @param onEnter after the new page mounts, position at the start or the end of the page
+ * @returns the result-column root ref; an empty page and a failed page can also receive the page-turn gesture
*/
export function useImageParseResultPagination(
resultKey: string,
@@ -60,7 +60,7 @@ export function useImageParseResultPagination(
return;
const viewport = root.querySelector<HTMLElement>('[data-ocr-result-scroll]');
if (viewport && (!(target instanceof Node) || !viewport.contains(target))) return;
- // 嵌套表格/代码滚动区域不应该触发整页切换。
+ // A nested table or code scroll area should not trigger a whole-page switch.
if (target instanceof HTMLElement) {
for (
let node: HTMLElement | null = target;
@@ -96,7 +96,7 @@ export function useImageParseResultPagination(
const next = page + direction;
if (next < 1 || next > pages) return;
event.preventDefault();
- // 一次触控板惯性手势只跨一页,短页也不会连续跳到文档末尾。
+ // One trackpad inertia gesture crosses only one page, so a short page does not keep jumping to the end of the document.
if (gestureLocked.current) return;
entry.current = { key: pageKey(next), previousKey: resultKey, edge: direction > 0 ? 0 : 1 };
gestureLocked.current = true;
@@ -114,7 +114,7 @@ export function useImageParseResultPagination(
if (pending.previousKey !== resultKey) entry.current = undefined;
return;
}
- // 左侧页码定位在下一帧提交,再恢复右侧入口,避免旧页确认覆盖新页底部。
+ // The left page-number position is committed on the next frame, then the right entry is restored, so the old page's confirmation does not cover the bottom of the new page.
let frame = requestAnimationFrame(() => {
frame = requestAnimationFrame(() => {
if (entry.current === pending && onEnter(pending.edge)) entry.current = undefined;
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseResultState.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseResultState.ts
index 6695e2f..f5ffdc0 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseResultState.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseResultState.ts
@@ -11,10 +11,10 @@ import {
} from '../utils/imageParseSealDisplay';
/**
- * 连接结果草稿、原图定位范围和下载数据,确保导出使用当前编辑内容。
- * @param parse 当前识别结果
- * @param examplePageKey 共享案例的逐页身份
- * @returns 草稿、定位范围、质量摘要与下载操作
+ * Connect the result draft, original-image positioning ranges, and download data, so export uses the current edited content.
+ * @param parse current recognition result
+ * @param examplePageKey per-page identity of a shared example
+ * @returns the draft, positioning ranges, quality summary, and download actions
*/
export function useImageParseResultState(
parse: ReturnType<typeof useImageParse>,
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseReview.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseReview.ts
index 8586231..e61b7f7 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseReview.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseReview.ts
@@ -1,13 +1,13 @@
import { useState } from 'react';
/**
- * 顶栏与复核列表共用筛选和分页;换结果立即重置,切标签保留当前进度。
- * @param resultKey 当前解析结果标识
- * @returns 筛选、展示条数及对应操作
+ * The top bar and the review list share filtering and paging; changing the result resets immediately, and switching tabs keeps the current progress.
+ * @param resultKey current parse-result id
+ * @returns the filter, the number of rows shown, and the matching actions
*/
export function useImageParseReview(resultKey: string) {
const [state, setState] = useState({ resultKey, all: false, limit: 40 });
- // 与结果身份一起重置,避免新文档短暂使用旧筛选,或返回旧文档时恢复过期分页。
+ // Reset together with the result identity, so a new document does not briefly use the old filter, and returning to an old document does not restore an expired page.
if (state.resultKey !== resultKey) {
setState({ resultKey, all: false, limit: 40 });
}
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseRichEditor.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseRichEditor.ts
index e80f9e8..36e20ac 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseRichEditor.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseRichEditor.ts
@@ -13,9 +13,9 @@ import type { ImageParseFormulaTarget } from '../utils/imageParseFormulaEditCont
const MATH_TYPES = new Set(['blockMath', 'inlineMath']);
/**
- * Tiptap 编辑生命周期与保存;未改变文档时保留逐字符一致的原始草稿。
- * @param source 当前结果草稿
- * @param extensions OCR schema 和安全配置
+ * Tiptap edit lifecycle and save; when the document is unchanged, keep the original draft identical character by character.
+ * @param source current result draft
+ * @param extensions OCR schema and safe config
*/
export function useImageParseRichEditor(
source: string,
@@ -102,7 +102,7 @@ export function useImageParseRichEditor(
const math = state?.math;
if (redo) editor.commands.redo();
else editor.commands.undo();
- // 历史事务可能恢复普通文本选区;公式属性编辑仍留在原节点,不关闭源码输入框。
+ // A history transaction may restore an ordinary text selection; formula-attribute editing stays on the original node and does not close the source input.
if (math && editor.state.doc.nodeAt(math.pos)?.type.name === math.type) {
editor.commands.setNodeSelection(math.pos);
} else {
@@ -131,7 +131,7 @@ export function useImageParseRichEditor(
flushOpenFormula();
const unchanged = initialDoc.current?.eq(editor.state.doc);
if (!unchanged) {
- // 不拦截模型原有的非法公式,只阻止把本次新增或修改的非法 LaTeX 保存回正文。
+ // Do not intercept an illegal formula the model already had; only stop illegal LaTeX that was added or changed this time from being saved back into the body.
const originals = new Set<string>();
initialDoc.current?.descendants((node) => {
if (MATH_TYPES.has(node.type.name)) originals.add(String(node.attrs.latex ?? ''));
@@ -166,7 +166,7 @@ export function useImageParseRichEditor(
},
composing: () => mathComposing.current || (!editor.isDestroyed && editor.view.composing),
});
- // 会话内容不在编辑期间更新;官方 useEditor 管理卸载,显式切块同步 destroy。
+ // Session content is not updated during editing; the official useEditor manages unmount, and an explicit block switch destroys synchronously.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [editor, register]);
return { editor, state, error, history, formulaContext };
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseScrollSync.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseScrollSync.ts
index 97cefbd..9aafac4 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseScrollSync.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseScrollSync.ts
@@ -16,7 +16,7 @@ type PendingResultScroll = {
source: 'origin' | 'focus';
};
-/** 原图栏接收的进度请求与用户滚动反馈。进度取值为 [0, 1]。 */
+/** Progress requests and user-scroll feedback received by the original-image column. Progress is in [0, 1]. */
export interface ImageParseOriginScrollProps {
scrollProgress?: number;
onScrollProgress: (progress: number, programmatic?: boolean) => void;
@@ -28,12 +28,12 @@ function boundedProgress(value: number): number {
}
/**
- * 双栏滚动接线;禁用联动时不读写另一栏,新结果清除旧请求。
- * @param linked 是否启用联动
- * @param resultKey 当前结果身份;更换文件、页码或结果时应更新
- * @returns 原图 props、结果栏 viewport ref 与 scroll handler
+ * Two-column scroll wiring; when linking is disabled, do not read or write the other column, and a new result clears the old request.
+ * @param linked whether linking is enabled
+ * @param resultKey current result identity; update it when the file, page number, or result changes
+ * @returns original-image props, the result-column viewport ref, and the scroll handler
*
- * 有版面块时按真实渲染锚点插值;无对应节点时不执行不可靠的跨栏跳转。
+ * When there are layout blocks, interpolate by real rendered anchors; when there is no matching node, do not perform an unreliable cross-column jump.
*/
export function useImageParseScrollSync(
linked: boolean,
@@ -76,7 +76,7 @@ export function useImageParseScrollSync(
const expected = pendingOrigin.current;
pendingOrigin.current = undefined;
setRequest(undefined);
- // 原图确认结果栏发出的请求时,不再将同一位置写回结果栏。
+ // When the original image confirms a request sent by the result column, do not write the same position back to the result column.
if (programmatic || (expected !== undefined && Math.abs(progress - expected) < 0.001)) return;
const node = resultNode.current;
if (!node) return;
@@ -114,12 +114,12 @@ export function useImageParseScrollSync(
const node = event.currentTarget;
const expected = pendingResult.current;
pendingResult.current = undefined;
- // 块定位允许浏览器因布局变化落在邻近位置,不能把确认误判为用户滚动并反向改写原图。
+ // Block positioning allows the browser to land nearby because of a layout change, and that confirmation must not be mistaken for a user scroll that rewrites the original image the other way.
if (expected !== undefined) {
if (Math.abs(node.scrollTop - expected.top) < 1 || expected.source === 'focus') return;
}
const range = Math.max(0, node.scrollHeight - node.clientHeight);
- // 换页重建或短结果产生的零偏移不是用户要求原文回到首页。
+ // A zero offset from rebuilding on a page change, or from a short result, is not the user asking the original text to return to the first page.
if (!range) return;
const progress = boundedProgress(node.scrollTop / range);
const anchors = imageParseScrollAnchors(
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseSelection.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseSelection.ts
index 3f896dd..5013f80 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseSelection.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseSelection.ts
@@ -2,7 +2,7 @@ import { useCallback, useState } from 'react';
type Source = 'origin' | 'result';
-/** 按结果身份隔离点击定位与临时悬停,移出悬停区域不清除已选中的块。 */
+/** Isolate click positioning and temporary hover by result identity; leaving the hover area does not clear the block already selected. */
export function useImageParseSelection(key: string, enabled: boolean, linked: boolean) {
const [selection, setSelection] = useState<{
key: string;
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseSetupScroll.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseSetupScroll.ts
index 861a931..21f4c42 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseSetupScroll.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseSetupScroll.ts
@@ -1,10 +1,10 @@
import { useEffect, type RefObject } from 'react';
/**
- * 窄屏纵向工作区打开字段配置时,将配置面板带入可见区域。
- * @param visible 是否已显示字段配置
- * @param containerRef 工作区滚动容器
- * @param paneRef 字段配置所在面板
+ * When a narrow-screen vertical workspace opens field configuration, bring the configuration panel into view.
+ * @param visible whether field configuration is already shown
+ * @param containerRef workspace scroll container
+ * @param paneRef panel that contains the field configuration
*/
export function useImageParseSetupScroll(
visible: boolean,
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseSidebarHistory.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseSidebarHistory.ts
index cfa3949..278b705 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseSidebarHistory.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseSidebarHistory.ts
@@ -20,7 +20,7 @@ interface ImageParseSidebarHistoryOptions {
onChange?: (history: PlaygroundSidebarHistory | undefined) => void;
}
-/** 固定共享案例与个人云端历史分组;打开记录时按需加载,并隔离过期选择响应。 */
+/** Group fixed shared examples and personal cloud history; load on demand when a record is opened, and isolate a stale selection response. */
export function useImageParseSidebarHistory(options: ImageParseSidebarHistoryOptions) {
const { t } = useTranslation('playground');
const { scope, attachmentId, history, onChange } = options;
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseTableMerge.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseTableMerge.ts
index 912a7e1..233b4fe 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseTableMerge.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseTableMerge.ts
@@ -15,7 +15,7 @@ import {
mergeImageParseTablesInPage,
} from '../utils/imageParseTableMerge';
-/** 单图表格合并状态。pages 保留给共用工具栏类型,单图没有页码。 */
+/** Single-image table-merge state. pages is kept for the shared toolbar type; a single image has no page number. */
export interface ImageParseTableMergeState {
status: 'idle' | 'merging' | 'merged';
pages: readonly number[];
@@ -50,9 +50,9 @@ const IDLE_RECORD: ImageParseTableMergeRecord = {
};
/**
- * 合并单图内被识别拆开的相邻表格,并保留原始结果用于撤销。
- * @param options 当前识别结果、状态写入入口与结果身份
- * @returns 工具栏使用的合并状态与操作
+ * Merge adjacent tables that recognition split apart inside a single image, and keep the raw result for undo.
+ * @param options current recognition result, the state-write entry, and the result identity
+ * @returns the merge state and actions the toolbar uses
*/
export function useImageParseTableMerge({
enabled,
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseTaskNavigation.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseTaskNavigation.ts
index 04baae7..83a655d 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseTaskNavigation.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseTaskNavigation.ts
@@ -17,9 +17,9 @@ interface ImageParseTaskNavigationOptions {
}
/**
- * 同一文件内切换任务时保留各自的结果和草稿身份,不跨账号、项目或附件复用。
- * @param options 当前快照、任务与恢复入口
- * @returns 不自动调用模型的任务切换函数
+ * When switching tasks inside the same file, keep each task's result and draft identity, and do not reuse them across accounts, projects, or attachments.
+ * @param options current snapshot, task, and restore entry
+ * @returns a task-switch function that does not call the model automatically
*/
export function useImageParseTaskNavigation({
scope,
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseTaskState.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseTaskState.ts
index 536f8e1..c8e4704 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseTaskState.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseTaskState.ts
@@ -16,9 +16,9 @@ interface ImageParseTaskStateOptions {
}
/**
- * 维护任务、抽取字段、摆正、印章和图表展示选项。
- * @param options 自动识别标记、取消入口与共享案例状态
- * @returns 当前任务状态与受控切换函数
+ * Maintain the task, extraction fields, rotation adaptation, and seal and chart display options.
+ * @param options the automatic-recognition flag, the cancel entry, and shared-example state
+ * @returns the current task state and the controlled switch functions
*/
export function useImageParseTaskState({
pendingAutoRef,
@@ -31,7 +31,7 @@ export function useImageParseTaskState({
const [upright, setUpright] = useState(true);
const [recognizeSeal, setRecognizeSeal] = useState(true);
const [recognizeChart, setRecognizeChart] = useState(true);
- // 信息抽取必须至少有一个合法字段;无字段时不自动发起必然失败的请求。
+ // Key information extraction must have at least one legal field; with no fields, do not automatically start a request that is bound to fail.
useEffect(() => {
if (mode === 'kie' && imageParseKieFieldsError(fields)) {
pendingAutoRef.current = false;
@@ -40,7 +40,7 @@ export function useImageParseTaskState({
const selectMode = useCallback(
(next: ImageParseMode) => {
if (next === mode || sharedExample) return;
- // 点击当下同步中止,避免切换模式后旧回调在 effect 执行前写入。
+ // Abort synchronously at the moment of the click, so an old callback does not write before the effect runs after the mode switches.
cancel();
setMode(next);
},
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseTour.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseTour.ts
index 4609335..1e669f2 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseTour.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseTour.ts
@@ -7,7 +7,7 @@ import {
type UseImageParseGuidedTourOptions,
} from './useImageParseGuidedTour';
-/** 文档解析引导的稳定已读标识;历史版本记录按同族引导兼容。 */
+/** Stable seen id for the document-parsing tour; history version records are compatible as the same family of tour. */
export const IMAGE_PARSE_TOUR_ID = 'image-parse';
const GATE_SELECTORS = ['[data-tour="image-parse-examples"]'] as const;
@@ -17,9 +17,9 @@ type UseImageParseTourOptions = Omit<
>;
/**
- * 文档解析首次访问引导;空态从平台示例开始,关闭后不再常驻重播入口。
- * @param options 是否启用与当前文档状态
- * @returns 手动重播引导的入口
+ * First-visit tour for document parsing; the empty state starts from a platform example, and after it is closed the replay entry does not stay on screen.
+ * @param options whether it is enabled, and the current document state
+ * @returns the entry that replays the tour manually
*/
export function useImageParseTour(options: UseImageParseTourOptions) {
const { t } = useTranslation('playground');
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseTourMenus.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseTourMenus.ts
index 3f55962..10b144b 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseTourMenus.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseTourMenus.ts
@@ -2,7 +2,7 @@ import { useCallback, useRef } from 'react';
import { isImageParseTourSettingsTrigger } from '../utils/imageParseTourSettings';
-/** 引导切换步骤时,只关闭由引导自动打开的设置菜单。 */
+/** When the tour changes steps, close only the settings menu the tour opened automatically. */
export function useImageParseTourMenus() {
const autoOpened = useRef<HTMLElement | null>(null);
const toggle = useCallback((trigger: HTMLElement) => {
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseTourSeen.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseTourSeen.ts
index eed6855..b226745 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseTourSeen.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseTourSeen.ts
@@ -42,11 +42,11 @@ function hasSeenTour(values: string[], tourId: string, userId?: string): boolean
}
/**
- * 读取并写入当前用户绑定的引导已读记录。
- * 历史记录可能带版本号;同一用户看过同族引导的任一版本即视为已读,避免发布后重复弹出。
- * @param tourId 引导标识
- * @param userId 当前用户 ID
- * @returns 是否已读与写入已读的方法
+ * Read and write the tour-seen record bound to the current user.
+ * A history record may carry a version number; if the same user has seen any version of the same family of tour, it counts as seen, so it does not pop again after a release.
+ * @param tourId tour id
+ * @param userId current user ID
+ * @returns whether it has been seen, and the method that writes seen
*/
export function useImageParseTourSeen(tourId: string, userId?: string) {
const seenId = JSON.stringify([tourId, userId]);
@@ -59,7 +59,7 @@ export function useImageParseTourSeen(tourId: string, userId?: string) {
try {
setPlaygroundPrefs({ seenTours: Array.from(new Set([...current, seenId])) });
} catch {
- // Zustand 先更新内存再持久化;浏览器拒绝写入时不妨碍关闭及本次会话的已读判断。
+ // Zustand updates memory first and then persists; when the browser refuses the write, that does not block closing or this session's seen judgment.
}
}, [seenId, setPlaygroundPrefs]);
return { seen, markSeen };
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseVisualEditor.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseVisualEditor.ts
index 2c639e4..0b700de 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseVisualEditor.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseVisualEditor.ts
@@ -2,14 +2,14 @@ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react
import type { ImageParseTextRange } from '../utils/imageParseBlocks';
-/** 当前块提供同步导出和销毁;切块必须先销毁旧实例。 */
+/** The current block provides synchronous export and destroy; switching blocks must destroy the old instance first. */
export interface ImageParseBlockController {
save: () => boolean;
destroy: () => void;
composing: () => boolean;
}
-/** 管理唯一活动块;外部点击或键盘移出时保存,结果更新时丢弃过期会话。 */
+/** Manage the single active block; save when an outside click or the keyboard moves away, and discard an expired session when the result updates. */
export function useImageParseVisualEditor(
source: string,
onSave: (value: string, editedRange?: ImageParseTextRange) => void,
@@ -95,7 +95,7 @@ export function useImageParseVisualEditor(
event.target instanceof Element &&
event.target.closest('[data-edit-block]')
) {
- // 首击保存后暂保留旧块高度,第二击仍命中同一预览块;切换后立即释放。
+ // After the first click saves, keep the old block height for a moment, so the second click still hits the same preview block; release it immediately after the switch.
releaseFootprint();
editorRoot.style.minHeight = `${editorRoot.getBoundingClientRect().height}px`;
footprint.current = { element: editorRoot, timer: setTimeout(releaseFootprint, 400) };
@@ -108,7 +108,7 @@ export function useImageParseVisualEditor(
finish();
}
function compositionend() {
- // ProseMirror 完成输入法事务后再导出,避免丢失最后一个中文字符。
+ // Export only after ProseMirror finishes the IME transaction, so the last CJK character is not lost.
const current = controller.current;
if (pendingBlur.current)
setTimeout(() => {
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseWorkspaceIntake.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseWorkspaceIntake.ts
index d8df4e0..e40a838 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseWorkspaceIntake.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseWorkspaceIntake.ts
@@ -3,11 +3,11 @@ import { useImageParsePageDrop } from './useImageParsePageDrop';
import { useImageParseWorkspacePaste } from './useImageParseWorkspacePaste';
/**
- * 合并工作台页面级拖放与粘贴入口,统一使用当前识别档位的文件边界。
- * @param onFile 已通过校验的单文件回调
- * @param pasteEnabled 是否允许空白工作台接收粘贴
- * @param rules 当前档位的格式、数量与大小限制
- * @returns 页面拖放高亮状态与容器事件
+ * Merge the workspace's page-level drop and paste entries, and use the file bounds of the current recognition tier for both.
+ * @param onFile callback for the single file that has already passed checks
+ * @param pasteEnabled whether an empty workspace may receive a paste
+ * @param rules format, count, and size limits of the current tier
+ * @returns page drop-highlight state and container events
*/
export function useImageParseWorkspaceIntake(
onFile: (file: File) => void,
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseWorkspacePaste.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseWorkspacePaste.ts
index d09cd61..8890977 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseWorkspacePaste.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseWorkspacePaste.ts
@@ -2,7 +2,7 @@ import { useEffect } from 'react';
import type { DocumentFileRules } from '../utils/documentUpload';
import { applyPreparedDocument } from '../utils/imageGroupPdf';
-/** 空工作台仍支持文件粘贴,输入框与编辑器保留自己的剪贴板行为。多张图片会合成一份。 */
+/** An empty workspace still supports pasting a file; inputs and the editor keep their own clipboard behavior. Several images are composed into one document. */
export function useImageParseWorkspacePaste(
enabled: boolean,
onPick: (file: File) => void,
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageParseWorkspaceSelection.ts b/webdemo/frontend/src/pages/playground/hooks/useImageParseWorkspaceSelection.ts
index 83ca1c8..ae9e603 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageParseWorkspaceSelection.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageParseWorkspaceSelection.ts
@@ -8,7 +8,7 @@ import {
import type { useImageParse } from './useImageParse';
import { useImageParseSelection } from './useImageParseSelection';
-/** 工作台区块选择:保留逐页框数据,跨页点击绑定目标结果身份而不是当前页同名块。 */
+/** Workspace block selection: keep per-page box data, and a cross-page click binds the target result identity rather than the same-named block on the current page. */
export function useImageParseWorkspaceSelection(
parse: ReturnType<typeof useImageParse>,
enabled: boolean,
diff --git a/webdemo/frontend/src/pages/playground/hooks/useImageZoom.ts b/webdemo/frontend/src/pages/playground/hooks/useImageZoom.ts
index 017a365..5754537 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useImageZoom.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useImageZoom.ts
@@ -1,5 +1,5 @@
/**
- * 图片视图接线:文档模式贴合顶部、滚轮阅读与 Ctrl/Meta 缩放;交互及 resize 保持边界。
+ * Image-view wiring: document mode fits to the top, wheel reading, and Ctrl/Meta zoom; interaction and resize keep the bounds.
*/
import { useCallback, useEffect, useRef, useState } from 'react';
@@ -12,7 +12,7 @@ import type { ImageZoomView, Point } from '../utils/imageZoom';
export type { ImageZoom };
/**
- * 图片视图控制。setViewport/setContent 分别测量裁剪视口和未缩放的内容。
+ * Image-view controls. setViewport and setContent measure the crop viewport and the unscaled content respectively.
*/
export function useImageZoom({
fitWidth: documentMode = false,
@@ -32,7 +32,7 @@ export function useImageZoom({
? geometry.fitWidthView(storedView, viewportSize, contentSize)
: clamp(storedView, viewportSize, contentSize);
- // 尺寸快照变化时同步调整状态,避免 resize 后下一次放大恢复旧的越界偏移。
+ // When the size snapshot changes, adjust state synchronously, so the next zoom after a resize does not restore an old out-of-bounds offset.
if (measured.viewport !== viewportSize || measured.content !== contentSize) {
setMeasured({ viewport: viewportSize, content: contentSize });
setView((current) =>
@@ -41,7 +41,7 @@ export function useImageZoom({
: clamp(current, viewportSize, contentSize),
);
}
- // 横向增量单独累积;共享滚轮采集器只合并纵向值,不能用最后一帧覆盖横向输入。
+ // Horizontal deltas accumulate on their own; the shared wheel collector merges only the vertical value and must not overwrite horizontal input with the last frame.
useEffect(() => {
if (!viewport) return;
const collect = (event: WheelEvent) => {
diff --git a/webdemo/frontend/src/pages/playground/hooks/useInitialConversationRestore.ts b/webdemo/frontend/src/pages/playground/hooks/useInitialConversationRestore.ts
index b99358c..dff422e 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useInitialConversationRestore.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useInitialConversationRestore.ts
@@ -1,7 +1,7 @@
/**
- * Playground 首次刷新恢复。
+ * Playground first-refresh restore.
*
- * 用途:身份确认后优先恢复同用户草稿,否则按 URL 会话 ID 拉取服务端详情。
+ * Purpose: after identity is confirmed, restore the same user's draft first; otherwise pull the server detail by the URL conversation ID.
*/
import { useEffect, useRef } from 'react';
@@ -25,8 +25,8 @@ interface UseInitialConversationRestoreArgs {
}
/**
- * 恢复刷新前的当前会话。
- * @returns 无返回值。
+ * Restore the current conversation from before the refresh.
+ * @returns no return value.
*/
export function useInitialConversationRestore(args: UseInitialConversationRestoreArgs): void {
const {
@@ -55,11 +55,11 @@ export function useInitialConversationRestore(args: UseInitialConversationRestor
}
async function restore(): Promise<void> {
- // 本地草稿分支也异步执行,避免 effect 内同步触发多次级联 state 更新。
+ // The local-draft branch also runs asynchronously, so the effect does not synchronously trigger several cascading state updates.
await Promise.resolve();
if (run !== runRef.current) return;
if (hasUserActivity) {
- // URL 详情未恢复前用户已发送,必须脱离旧会话,避免用不完整快照覆盖服务端历史。
+ // If the user has already sent before the URL detail is restored, leave the old conversation, so an incomplete snapshot does not overwrite server history.
if (conversationId) setActiveId(undefined);
finish();
return;
diff --git a/webdemo/frontend/src/pages/playground/hooks/useMarkdownPreparation.ts b/webdemo/frontend/src/pages/playground/hooks/useMarkdownPreparation.ts
index 198c471..e90d018 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useMarkdownPreparation.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useMarkdownPreparation.ts
@@ -7,25 +7,25 @@ import type { ImageParseTextRange } from '../utils/imageParseBlocks';
import type { ImageParseLinkedRange } from '../utils/imageParseHighlight';
interface UseMarkdownPreparationOptions {
- /** 原始正文;OCR 范围与编辑块仍以它为权威偏移量。 */
+ /** Original body; OCR ranges and edit blocks still use it as the authoritative offset. */
sourceContent: string;
- /** 实际进入 Markdown/数学规范化的文本;对话场景可能已注入引用角标链接。 */
+ /** Text that actually enters Markdown and math normalization; a chat scene may already have injected citation-marker links. */
renderContent: string;
- /** 对话场景是否推断裸公式。 */
+ /** Whether the chat scene infers bare formulas. */
detectBareMath: boolean;
- /** 是否生成编辑范围。 */
+ /** Whether to generate edit ranges. */
editableBlocks: boolean;
- /** 单块高亮范围。 */
+ /** Highlight range of a single block. */
highlightRange?: ImageParseTextRange;
- /** OCR 联动范围。 */
+ /** OCR linked range. */
linkedRanges?: readonly ImageParseLinkedRange[];
}
/**
- * 缓存 Markdown 预处理;文档范围复用一次规范化映射,不按块重扫文本。
+ * Cache Markdown preprocessing; a document range reuses one normalization map and does not rescan the text per block.
*
- * `sourceContent` 与 `renderContent` 在 OCR 文档中相同;在对话正文中,引用角标可能先被改写成
- * Markdown 链接。范围映射只在文档场景实际使用,此时两个内容保持一致。
+ * `sourceContent` and `renderContent` are the same in an OCR document; in chat body text, citation markers may first be rewritten as
+ * Markdown links. The range map is actually used only in the document scene, where the two contents stay consistent.
*/
export function useMarkdownPreparation({
sourceContent,
diff --git a/webdemo/frontend/src/pages/playground/hooks/useMessageFeedback.ts b/webdemo/frontend/src/pages/playground/hooks/useMessageFeedback.ts
index 1d3be08..69f57aa 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useMessageFeedback.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useMessageFeedback.ts
@@ -1,9 +1,9 @@
/**
- * 体验中心对话反馈编排 hook。
+ * Hook that orchestrates conversation feedback in the experience center.
*
- * 用途:把「点赞直接静默上报 / 点踩弹框选原因后上报 / 本地高亮态切换」收敛为一处,喂给页面。
- * 本地高亮态仍由 useChat.setFeedback 持有(即时反馈);本 hook 负责上报后端与点踩弹框状态。
- * 不含 JSX。上报为 fire-and-forget:失败仅 toast,不回退本地高亮(简单账本式处理)。
+ * Purpose: collapse "a like reports silently / a dislike opens a dialog to pick a reason and then reports / local highlight-state toggle" into one place, and feed the page.
+ * Local highlight state is still held by useChat.setFeedback (immediate feedback); this hook is responsible for reporting to the backend and for dislike-dialog state.
+ * No JSX. Reporting is fire-and-forget: failure only toasts, and does not roll back the local highlight (a simple ledger-style handling).
*/
import { useCallback, useState } from 'react';
@@ -25,25 +25,25 @@ interface FeedbackSnapshot {
}
interface Args {
- /** 当前消息列表(取问答快照) */
+ /** Current message list (used to take the question-answer snapshot) */
messages: ChatMessage[];
- /** 当前模型 id(= public_model) */
+ /** Current model id (= public_model) */
model: string;
- /** 当前会话 id(新对话未保存时为 undefined) */
+ /** Current conversation id (undefined when a new conversation has not been saved) */
conversationId?: string;
- /** 切换本地高亮态(赞/踩互斥、再点取消) */
+ /** Toggle the local highlight state (like/dislike are exclusive; clicking again clears it) */
setLocalFeedback: (assistantId: string, kind: MessageFeedback) => void;
}
interface Return {
- /** 点击赞/踩:赞直接上报,踩打开弹框 */
+ /** Click like or dislike: a like reports directly, and a dislike opens the dialog */
onFeedback: (assistantId: string, kind: MessageFeedback) => void;
- /** 点踩弹框是否打开 */
+ /** Whether the dislike dialog is open */
dialogOpen: boolean;
setDialogOpen: (open: boolean) => void;
- /** 上报中 */
+ /** Reporting in progress */
submitting: boolean;
- /** 提交点踩弹框(带原因/正文) */
+ /** Submit the dislike dialog (with a reason and body) */
submitDown: (payload: { reasons: string[]; comment: string }) => void;
}
@@ -53,7 +53,7 @@ export function useMessageFeedback(args: Args): Return {
const { t } = useTranslation('playground');
const submitMut = useSubmitFeedbackMutation();
const [dialogOpen, setDialogOpen] = useState(false);
- // 待提交点踩的反馈快照:弹框期间会话/版本可能切换,提交必须使用点击当刻的问答与归属。
+ // Feedback snapshot of a dislike waiting to be submitted: the conversation or version may switch while the dialog is open, so submit must use the question, answer, and ownership from the moment of the click.
const [pending, setPending] = useState<FeedbackSnapshot | null>(null);
const makeSnapshot = useCallback(
@@ -115,17 +115,17 @@ export function useMessageFeedback(args: Args): Return {
const onFeedback = useCallback(
(assistantId: string, kind: MessageFeedback) => {
const wasActive = messages.find((m) => m.id === assistantId)?.feedback === kind;
- // 取消高亮(再次点击同项):直接切掉本地态,不上报、不弹框
+ // Clearing the highlight (clicking the same item again): switch the local state off directly, with no report and no dialog
if (wasActive) {
setLocalFeedback(assistantId, kind);
return;
}
if (kind === 'up') {
- // 点赞即时反馈:切高亮 + 静默上报
+ // Immediate feedback for a like: switch the highlight and report silently
setLocalFeedback(assistantId, 'up');
report(makeSnapshot(assistantId), 'up', [], '');
} else {
- // 点踩:先冻结问答快照并打开弹框;提交成功才落高亮,取消则不留痕迹。
+ // A dislike: freeze the question-answer snapshot first and open the dialog; the highlight lands only after a successful submit, and cancel leaves no trace.
setPending(makeSnapshot(assistantId));
setDialogOpen(true);
}
@@ -136,7 +136,7 @@ export function useMessageFeedback(args: Args): Return {
const submitDown = useCallback(
(payload: { reasons: string[]; comment: string }) => {
if (pending) {
- // 若弹框期间已经切换会话,不再改当前页面高亮,但仍按点击当刻快照上报。
+ // If the conversation has already switched while the dialog was open, do not change the highlight on the current page, but still report from the snapshot at the moment of the click.
if (isCurrentPendingTarget(pending)) {
setLocalFeedback(pending.assistantId, 'down');
}
diff --git a/webdemo/frontend/src/pages/playground/hooks/useMessageVersions.ts b/webdemo/frontend/src/pages/playground/hooks/useMessageVersions.ts
index dd1e2c1..b82f7d6 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useMessageVersions.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useMessageVersions.ts
@@ -1,7 +1,7 @@
/**
- * Playground 多版本回答与反馈 hook。
+ * Playground hook for multi-version answers and feedback.
*
- * 用途:regenerate / setFeedback / setActiveVersion;维护 versions 不变式,补全触发委托 startCompletion。
+ * Purpose: regenerate / setFeedback / setActiveVersion; keep the versions invariant, and delegate the completion trigger to startCompletion.
*/
import { useCallback, type Dispatch, type SetStateAction } from 'react';
@@ -14,16 +14,16 @@ import {
prepareRegenerateMessage,
} from '../utils/messageVersions';
-/** useMessageVersions 入参 */
+/** useMessageVersions arguments */
export interface UseMessageVersionsArgs {
messages: ChatMessage[];
setMessages: Dispatch<SetStateAction<ChatMessage[]>>;
loading: boolean;
- /** 来自 useChatCompletion:构造好 history 后发起补全 */
+ /** From useChatCompletion: start a completion after history has been built */
startCompletion: (history: ChatMessage[], assistantId: string) => void;
}
-/** useMessageVersions 返回 */
+/** useMessageVersions return value */
export interface UseMessageVersionsReturn {
regenerate: (assistantId: string) => void;
setFeedback: (assistantId: string, kind: MessageFeedback) => void;
@@ -31,8 +31,8 @@ export interface UseMessageVersionsReturn {
}
/**
- * 托管多版本回答与反馈态;不含网络与 JSX。
- * @param args 消息列表、loading 与 startCompletion 回调
+ * Own multi-version answers and feedback state; no network and no JSX.
+ * @param args message list, loading, and the startCompletion callback
*/
export function useMessageVersions(args: UseMessageVersionsArgs): UseMessageVersionsReturn {
const { messages, setMessages, loading, startCompletion } = args;
diff --git a/webdemo/frontend/src/pages/playground/hooks/usePdfImageParse.test.ts b/webdemo/frontend/src/pages/playground/hooks/usePdfImageParse.test.ts
index a33a700..de46277 100644
--- a/webdemo/frontend/src/pages/playground/hooks/usePdfImageParse.test.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/usePdfImageParse.test.ts
@@ -55,7 +55,7 @@ function block(
};
}
-/** 每页:页眉 + 正文,正文里带页码,便于断言过滤和合并。 */
+/** Each page: header + body, with a page number in the body, so filtering and merging are easy to assert. */
function page(index: number, body = `正文${index}`): ImageParseSdkResult {
const header = '页眉';
return {
@@ -108,7 +108,7 @@ describe('usePdfImageParse 跨页表格合并', () => {
expect(result.current.tableMerge.pages).toEqual([2]);
expect(result.current.results[2]!.result).toBe(mergedPage);
expect(result.current.results[2]!.crops).toEqual(['crop2']);
- // 合并改动过的页换身份,草稿编辑各自保留
+ // Pages changed by a merge get a new identity; draft edits are kept separately
expect(result.current.resultIdentityForPage(2)).toContain(':merged');
expect(result.current.resultIdentityForPage(1)).toBe(untouched);
@@ -116,7 +116,7 @@ describe('usePdfImageParse 跨页表格合并', () => {
expect(result.current.tableMerge.status).toBe('idle');
expect(result.current.results[2]!.result!.markdown).toBe('页眉\n\n正文1');
expect(result.current.resultIdentityForPage(2)).not.toContain(':merged');
- // 用户主动撤销后,效果不能再次自动合并。
+ // After the user undoes on purpose, the effect must not merge automatically again.
await new Promise((resolve) => setTimeout(resolve, 0));
expect(result.current.tableMerge.status).toBe('idle');
});
diff --git a/webdemo/frontend/src/pages/playground/hooks/usePdfImageParse.ts b/webdemo/frontend/src/pages/playground/hooks/usePdfImageParse.ts
index 3805df5..cf4a666 100644
--- a/webdemo/frontend/src/pages/playground/hooks/usePdfImageParse.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/usePdfImageParse.ts
@@ -25,7 +25,7 @@ import { usePdfImageParseHistory } from './usePdfImageParseHistory';
export type { PdfTableMergeState } from './usePdfImageParseTableMerge';
const EMPTY_FIELDS: readonly string[] = [];
-/** 为 PDF 维护页码和 MAP 任务生命周期;替换文件/模式/模型时中止旧任务。 */
+/** Maintain page numbers and the MAP task lifecycle for a PDF; abort the old task when the file, mode, or model is replaced. */
export function usePdfImageParse(
attachment: Attachment | undefined,
mode: ImageParseMode,
@@ -87,7 +87,7 @@ export function usePdfImageParse(
const { source, mode, model, projectId, upright } = scope;
if (!source || !enabled || !model.trim() || !projectId.trim()) return;
stop();
- // 重识别会让合并结果过期:整份重来时直接丢弃,单页重试先还原成逐页结果
+ // Recognizing again expires the merge result: discard it directly when the whole document starts over, and restore per-page results first on a single-page retry
resetTableMerge(onlyPage !== undefined);
setResultScope(scope);
const active = new AbortController();
@@ -188,7 +188,7 @@ export function usePdfImageParse(
loading: valid && loading,
error: valid ? error : undefined,
snapshot,
- // 导航不增加识别代次;重试和合并只更新受影响页的草稿身份。
+ // Navigation does not bump the recognition generation; retry and merge update the draft identity only of the affected pages.
resultIdentity: pageIdentity(page),
resultIdentityForPage: pageIdentity,
tableMerge,
diff --git a/webdemo/frontend/src/pages/playground/hooks/usePdfImageParseCrops.ts b/webdemo/frontend/src/pages/playground/hooks/usePdfImageParseCrops.ts
index 024e626..5121f44 100644
--- a/webdemo/frontend/src/pages/playground/hooks/usePdfImageParseCrops.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/usePdfImageParseCrops.ts
@@ -4,7 +4,7 @@ import { rebuildPdfPageCrops } from '../utils/pdfImageParseCrops';
import { unservedImagePlaceholderOffsets } from '../utils/imageParseCrops';
import type { PdfPageResult } from '../utils/pdfImageParse';
-/** 历史 PDF 只重建可见页的缺失裁图,换页或替换文档即取消旧渲染。 */
+/** A history PDF rebuilds only missing crops of the visible page, and changing the page or replacing the document cancels the old render. */
export function usePdfImageParseCrops(
source: string,
page: number,
@@ -20,7 +20,7 @@ export function usePdfImageParseCrops(
if (!active.signal.aborted) onReady(page, result, crops);
})
.catch(() => {
- // 无法裁切时保留已保存的正文;不重新识别或覆盖页结果。
+ // When it cannot be cropped, keep the saved body; do not run recognition again or overwrite the page result.
});
return () => active.abort();
}, [source, page, current, onReady]);
diff --git a/webdemo/frontend/src/pages/playground/hooks/usePdfImageParseHistory.ts b/webdemo/frontend/src/pages/playground/hooks/usePdfImageParseHistory.ts
index 46dd4eb..d871ff2 100644
--- a/webdemo/frontend/src/pages/playground/hooks/usePdfImageParseHistory.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/usePdfImageParseHistory.ts
@@ -29,9 +29,9 @@ interface PdfImageParseHistoryOptions {
}
/**
- * 管理 PDF 缓存恢复与启动意图;手动模式恢复历史时不自动续跑。
- * @param options 执行上下文、状态写入器和取消入口
- * @returns 历史恢复与显式执行入口
+ * Manage PDF cache restore and the start intent; in manual mode, restoring history does not continue the run automatically.
+ * @param options execution context, state writers, and the cancel entry
+ * @returns history restore and the explicit execution entry
*/
export function usePdfImageParseHistory({
scope,
diff --git a/webdemo/frontend/src/pages/playground/hooks/usePdfImageParsePresentation.ts b/webdemo/frontend/src/pages/playground/hooks/usePdfImageParsePresentation.ts
index b748cd0..a92ac9c 100644
--- a/webdemo/frontend/src/pages/playground/hooks/usePdfImageParsePresentation.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/usePdfImageParsePresentation.ts
@@ -9,7 +9,7 @@ import type { PdfImageParseSnapshot } from '../utils/imageParseHistoryTypes';
import type { PdfPageResult } from '../utils/pdfImageParse';
import { usePdfImageParseCrops } from './usePdfImageParseCrops';
-// 仅缓存纯派生结果;WeakMap 随原始结果释放,不额外持有文档。
+// Cache only a pure derived result; the WeakMap is released with the raw result and does not hold the document extra.
const hiddenCache = new WeakMap<ImageParseSdkResult, ImageParseSdkResult>();
interface PdfImageParsePresentationOptions {
@@ -24,9 +24,9 @@ interface PdfImageParsePresentationOptions {
}
/**
- * 派生 PDF 可见结果与历史快照;裁图始终根据原始结果,避免过滤后身份变化。
- * @param options 页结果及当前可见页状态
- * @returns 过滤后的页结果和可恢复快照
+ * Derive the visible PDF result and the history snapshot; crops always come from the raw result, so identity does not change after filtering.
+ * @param options page results and the current visible-page state
+ * @returns filtered page results and a snapshot that can be restored
*/
export function usePdfImageParsePresentation({
source,
diff --git a/webdemo/frontend/src/pages/playground/hooks/usePdfImageParseTableMerge.ts b/webdemo/frontend/src/pages/playground/hooks/usePdfImageParseTableMerge.ts
index c7edc1c..0eb9a25 100644
--- a/webdemo/frontend/src/pages/playground/hooks/usePdfImageParseTableMerge.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/usePdfImageParseTableMerge.ts
@@ -12,7 +12,7 @@ import { IMAGE_PARSE_CROSS_PAGE_MERGE_ENABLED } from '../utils/imageParseFeature
import { mergeImageParseTables } from '../utils/imageParseTableMerge';
import type { PdfPageResult } from '../utils/pdfImageParse';
-/** 跨页表格合并状态及受影响的页码。 */
+/** Cross-page table-merge state and the page numbers affected. */
export interface PdfTableMergeState {
status: 'idle' | 'merging' | 'merged';
pages: readonly number[];
@@ -29,9 +29,9 @@ interface PdfImageParseTableMergeOptions {
}
/**
- * 在逐页识别完成后拼接跨页表格,支持撤销且不覆盖用户的撤销选择。
- * @param options 当前页结果、写入入口与任务状态
- * @returns 合并操作、取消入口及重新识别时的重置入口
+ * Join cross-page tables after per-page recognition finishes, support undo, and do not overwrite the user's undo choice.
+ * @param options current page results, the write entry, and task state
+ * @returns the merge action, the cancel entry, and the reset entry used when recognition runs again
*/
export function usePdfImageParseTableMerge({
results,
diff --git a/webdemo/frontend/src/pages/playground/hooks/usePdfPageRenderer.ts b/webdemo/frontend/src/pages/playground/hooks/usePdfPageRenderer.ts
index cb27ed1..a20eefb 100644
--- a/webdemo/frontend/src/pages/playground/hooks/usePdfPageRenderer.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/usePdfPageRenderer.ts
@@ -22,9 +22,9 @@ interface PdfPageRendererOptions {
}
/**
- * 渲染连续滚动 PDF 的可见页,并把离屏帧原子提交到对应 canvas。
- * @param options PDF 文档、页面骨架、当前页、可见页、缩放与加载错误
- * @returns 预览状态、canvas ref 注册函数与渲染状态
+ * Render the visible pages of a continuously scrolling PDF, and atomically commit offscreen frames to the matching canvas.
+ * @param options PDF document, page skeletons, current page, visible pages, zoom, and load error
+ * @returns preview state, the canvas ref registration function, and render state
*/
export function usePdfPageRenderer({
document,
@@ -68,7 +68,7 @@ export function usePdfPageRenderer({
},
[revision, rotation, scale, viewportWidth],
);
- // 观察器可能发布同样页码的新数组,不能因此中止仍在绘制的页面。
+ // The observer may publish a new array of the same page numbers, and that must not abort a page that is still being drawn.
const visibleKey = visiblePageNumbers.join(',');
const targets = useMemo(
() =>
diff --git a/webdemo/frontend/src/pages/playground/hooks/usePdfPreview.ts b/webdemo/frontend/src/pages/playground/hooks/usePdfPreview.ts
index b214727..590e537 100644
--- a/webdemo/frontend/src/pages/playground/hooks/usePdfPreview.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/usePdfPreview.ts
@@ -7,15 +7,15 @@ import { usePdfPreviewZoom } from './usePdfPreviewZoom';
import type { PdfPageView } from '../utils/pdfPreviewRender';
import { isImageParseSharedPdfUrl } from '../utils/imageParseExamples';
-/** 滚轮停止后的高清重绘等待时长,先用 CSS 缩放保持交互跟手。 */
+/** How long to wait after the wheel stops before a high-resolution redraw; CSS zoom keeps the interaction following the hand first. */
const PDF_ZOOM_RENDER_DELAY_MS = 150;
/**
- * 编排 PDF.js 连续阅读生命周期;只渲染视口附近页面,避免大 PDF 一次性占满内存。
- * @param source PDF 地址或 data URL
- * @param selectedPage 外部要求定位的页码
- * @param onPageChange 当前页变化回调
- * @returns 页面骨架、当前页、渲染状态与缩放旋转操作
+ * Orchestrate the PDF.js continuous-reading lifecycle; render only pages near the viewport, so a large PDF does not fill memory all at once.
+ * @param source PDF URL or data URL
+ * @param selectedPage page number an external caller asked to position
+ * @param onPageChange callback when the current page changes
+ * @returns page skeletons, the current page, render state, and zoom and rotation actions
*/
export function usePdfPreview(
source: string,
diff --git a/webdemo/frontend/src/pages/playground/hooks/usePdfPreviewFrames.ts b/webdemo/frontend/src/pages/playground/hooks/usePdfPreviewFrames.ts
index 3c7cc11..bd2cb11 100644
--- a/webdemo/frontend/src/pages/playground/hooks/usePdfPreviewFrames.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/usePdfPreviewFrames.ts
@@ -3,7 +3,7 @@ import type { PDFDocumentProxy } from 'pdfjs-dist';
import type { PdfPageFrame } from '../utils/pdfPreviewRender';
-/** 已提交的页面只保存视图身份;离屏 canvas 移除时立即清空像素与缓存。 */
+/** A committed page stores only the view identity; when an offscreen canvas is removed, clear its pixels and cache immediately. */
export interface RenderedPdfPage {
key: string;
canvas: HTMLCanvasElement;
@@ -14,10 +14,10 @@ export interface RenderedPdfPage {
}
/**
- * 管理可见画布和提交帧的生命周期,不让帧提交改变渲染任务依赖。
- * @param document 当前 PDF 文档
- * @param revision 用户重试版本
- * @returns 画布注册、帧缓存、状态发布和重试入口
+ * Manage the lifetime of the visible canvas and committed frames, without letting a frame commit change render-task dependencies.
+ * @param document current PDF document
+ * @param revision user retry version
+ * @returns canvas registration, the frame cache, state publishing, and the retry entry
*/
export function usePdfPreviewFrames(document: PDFDocumentProxy | undefined, revision: number) {
const scope = useMemo(() => ({ document, revision }), [document, revision]);
@@ -41,10 +41,10 @@ export function usePdfPreviewFrames(document: PDFDocumentProxy | undefined, revi
if (!frame?.buffer.width || canvasNodes.current[Number(pageNumber)] !== item.canvas) return;
const context = item.canvas.getContext('2d');
if (!context) return;
- // 像素、方向、缩放和识别框在同一布局提交中生效,不能在异步回调里先换像素。
+ // Pixels, orientation, zoom, and recognition boxes take effect in the same layout commit, and pixels must not be swapped first inside an async callback.
item.canvas.width = frame.buffer.width;
item.canvas.height = frame.buffer.height;
- // 各页高清帧逐页提交,显示尺寸只跟随各自骨架,不能共享当前页的帧倍率。
+ // Each page's high-resolution frame is committed page by page; display size follows only that page's skeleton, and must not share the current page's frame scale.
item.canvas.style.width = '100%';
item.canvas.style.height = '100%';
context.drawImage(frame.buffer, 0, 0);
@@ -110,7 +110,7 @@ export function usePdfPreviewFrames(document: PDFDocumentProxy | undefined, revi
};
}
-/** 清空尚未提交或已离屏的缓冲区,不保留高分辨率像素副本。 */
+/** Clear buffers that have not been committed or are already offscreen, and do not keep a high-resolution pixel copy. */
function releaseBuffer(item: RenderedPdfPage) {
if (item.frame) item.frame.buffer.width = item.frame.buffer.height = 0;
}
diff --git a/webdemo/frontend/src/pages/playground/hooks/usePdfPreviewPages.ts b/webdemo/frontend/src/pages/playground/hooks/usePdfPreviewPages.ts
index 7871d86..e2f65c5 100644
--- a/webdemo/frontend/src/pages/playground/hooks/usePdfPreviewPages.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/usePdfPreviewPages.ts
@@ -16,11 +16,11 @@ interface PdfLoaded {
}
/**
- * 管理 PDF 文档与连续滚动页面骨架。
- * @param source PDF 地址或 data URL
- * @param selectedPage 外部要求定位的页码
- * @param onPageChange 当前页变化回调
- * @returns 文档、页面尺寸、页码、可见页与滚动操作
+ * Manage the PDF document and the continuously scrolling page skeletons.
+ * @param source PDF URL or data URL
+ * @param selectedPage page number an external caller asked to position
+ * @param onPageChange callback when the current page changes
+ * @returns the document, page sizes, page number, visible pages, and scroll actions
*/
export function usePdfPreviewPages(
source: string,
diff --git a/webdemo/frontend/src/pages/playground/hooks/usePdfPreviewPan.ts b/webdemo/frontend/src/pages/playground/hooks/usePdfPreviewPan.ts
index 976c0fe..f32b5ec 100644
--- a/webdemo/frontend/src/pages/playground/hooks/usePdfPreviewPan.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/usePdfPreviewPan.ts
@@ -9,9 +9,9 @@ interface PdfPanOrigin {
}
/**
- * PDF 鼠标拖拽阅读;只更新原生滚动位置,不改变倍率或重绘画布。
- * @param enabled 文档就绪后允许拖拽,触屏仍使用原生滚动。
- * @returns 抓取状态和视口指针事件处理函数。
+ * PDF mouse-drag reading; update only the native scroll position, and do not change the scale or redraw the canvas.
+ * @param enabled dragging is allowed after the document is ready; touch still uses native scroll.
+ * @returns the grab state and the viewport pointer-event handlers.
*/
export function usePdfPreviewPan(enabled: boolean) {
const origin = useRef<PdfPanOrigin | null>(null);
@@ -20,7 +20,7 @@ export function usePdfPreviewPan(enabled: boolean) {
(event: PointerEvent<HTMLDivElement>) => {
if (!enabled || origin.current || event.button !== 0 || event.pointerType === 'touch') return;
const target = event.target;
- // 识别框和操作控件保留点击语义,不能被阅读拖拽捕获。
+ // Recognition boxes and action controls keep click semantics and must not be captured by reading drag.
if (
target instanceof Element &&
target.closest('button, a, input, select, textarea, [role="button"], [contenteditable]')
diff --git a/webdemo/frontend/src/pages/playground/hooks/usePdfPreviewZoom.ts b/webdemo/frontend/src/pages/playground/hooks/usePdfPreviewZoom.ts
index 8d179cc..dedfa5d 100644
--- a/webdemo/frontend/src/pages/playground/hooks/usePdfPreviewZoom.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/usePdfPreviewZoom.ts
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
import { WHEEL_STEP } from '../utils/imageZoom';
-/** 在缩放提交后修正滚动位置,让指针指向的内容保持在原视口位置。 */
+/** After a zoom commit, correct the scroll position so the content under the pointer stays at its original viewport position. */
function applyZoomScrollAnchor(
viewport: HTMLElement,
ratio: number,
@@ -12,10 +12,10 @@ function applyZoomScrollAnchor(
}
/**
- * PDF 缩放控制:普通滚轮保留原生阅读,Ctrl/Meta 滚轮按帧合并缩放。
- * @param viewport PDF 阅读视口。
- * @param enabled 文档加载成功后才接管缩放手势。
- * @returns 当前倍数、按钮缩放与还原操作。
+ * PDF zoom control: an ordinary wheel keeps native reading, and a Ctrl/Meta wheel merges zoom by frame.
+ * @param viewport PDF reading viewport.
+ * @param enabled take over the zoom gesture only after the document has loaded successfully.
+ * @returns the current scale, button zoom, and the reset action.
*/
export function usePdfPreviewZoom(viewport: HTMLElement | null, enabled: boolean) {
const [scale, setScale] = useState(1);
@@ -66,7 +66,7 @@ export function usePdfPreviewZoom(viewport: HTMLElement | null, enabled: boolean
if (event.deltaMode === 1) unit = 16;
else if (event.deltaMode === 2) unit = Math.max(1, viewport.clientHeight);
delta += event.deltaY * unit;
- // PDF 重绘开销较大,连续滚轮每帧只提交一次倍率更新。
+ // PDF redraw is expensive, so a continuous wheel submits only one scale update per frame.
if (frame === undefined) frame = window.requestAnimationFrame(flush);
};
viewport.addEventListener('wheel', onWheel, { passive: false });
diff --git a/webdemo/frontend/src/pages/playground/hooks/usePdfThumbnail.ts b/webdemo/frontend/src/pages/playground/hooks/usePdfThumbnail.ts
index 3543fb4..ef9b834 100644
--- a/webdemo/frontend/src/pages/playground/hooks/usePdfThumbnail.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/usePdfThumbnail.ts
@@ -2,10 +2,10 @@ import { useEffect, useRef, useState } from 'react';
import type { PDFDocumentProxy, RenderTask } from 'pdfjs-dist';
/**
- * 为进入页带可见区域的 PDF 页面绘制低分辨率缩略图,复用阅读器文档。
- * @param pdf 当前 PDF.js 文档
- * @param pageNumber 页码
- * @returns 画布引用与就绪状态
+ * Draw a low-resolution thumbnail for a PDF page once it enters the visible band, reusing the reader document.
+ * @param pdf current PDF.js document
+ * @param pageNumber page number
+ * @returns the canvas ref and the ready state
*/
export function usePdfThumbnail(pdf: PDFDocumentProxy | undefined, pageNumber: number) {
const canvasRef = useRef<HTMLCanvasElement>(null);
@@ -42,7 +42,7 @@ export function usePdfThumbnail(pdf: PDFDocumentProxy | undefined, pageNumber: n
context.drawImage(buffer, 0, 0);
setReadyPage({ document: pdf, pageNumber });
} catch {
- // 缩略图失败保留文件占位,不影响正文阅读或触发额外的文档加载。
+ // A failed thumbnail keeps the file placeholder, and does not affect body reading or trigger an extra document load.
} finally {
buffer.width = buffer.height = 0;
}
diff --git a/webdemo/frontend/src/pages/playground/hooks/usePlaygroundCredential.ts b/webdemo/frontend/src/pages/playground/hooks/usePlaygroundCredential.ts
index fd29c23..14a157e 100644
--- a/webdemo/frontend/src/pages/playground/hooks/usePlaygroundCredential.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/usePlaygroundCredential.ts
@@ -1,8 +1,8 @@
/**
- * Playground 凭据编排 hook。
+ * Playground credential-orchestration hook.
*
- * 用途:把「用户自有 API Key」和「平台免费体验 Key」收敛成一个有效凭据。当前体验
- * 免费额度仍有剩余时优先使用内部体验 Key;用完后回退默认项目下的普通 API Key。
+ * Purpose: collapse "the user's own API Key" and "the platform free-trial key" into one effective credential. While the current experience
+ * still has free quota left, the internal trial key is preferred; after it is used up, fall back to an ordinary API Key under the default project.
*/
import { useCallback, useMemo } from 'react';
@@ -16,7 +16,7 @@ import {
} from '@/api/map';
import type { MapApiKey, MapPlaygroundTrial, PlaygroundTrialExperience } from '@/api/map';
-/** 免费体验凭据选择结果;secret 仅在体验 Key 场景直接来自 L3 返回值。 */
+/** Free-trial credential selection result; secret comes directly from the L3 return value only in the trial-key case. */
interface PlaygroundCredentialSelection {
keyId: string;
projectId?: string;
@@ -30,7 +30,7 @@ const emptyTrialRemaining: Record<PlaygroundTrialExperience, number> = {
'image-parse': 0,
};
-/** 非 language 体验是否有可见模型;与体验路由回退使用同一组模型目录口径。 */
+/** Whether a non-language experience has a visible model; the same model-catalog measure as the experience-route fallback. */
export type PlaygroundCredentialExperienceAvailability = {
tts: boolean;
realtime: boolean;
@@ -38,8 +38,8 @@ export type PlaygroundCredentialExperienceAvailability = {
};
/**
- * 将 URL 体验类型映射为计费凭据类型。模型加载中保持原体验;加载完成后若该体验无
- * 可见模型,则与页面路由同步回退 language,避免语言对话误消耗其它体验额度。
+ * Map a URL experience type to a billing credential type. While models are loading, keep the original experience; after loading, if that experience has no
+ * visible model, fall back to language in sync with the page route, so a language conversation does not consume another experience's quota by mistake.
*/
export function resolvePlaygroundCredentialExperience(
experience: PlaygroundTrialExperience,
@@ -51,12 +51,12 @@ export function resolvePlaygroundCredentialExperience(
}
/**
- * 选择 Playground 当前有效凭据。
- * @param keys 用户自有 active Key 列表
- * @param trial 免费体验状态
- * @param defaultProjectId 默认项目 ID
- * @param experience 当前体验类型;额度按类型独立回退
- * @returns 有效 Key、项目与体验 Key 明文;无可用凭据时 keyId 为空
+ * Select the credential currently effective for Playground.
+ * @param keys the user's own active Key list
+ * @param trial free-trial state
+ * @param defaultProjectId default project ID
+ * @param experience current experience type; quota falls back independently per type
+ * @returns the effective key, project, and trial-key plaintext; keyId is empty when no credential is available
*/
export function resolvePlaygroundCredential(
keys: MapApiKey[],
@@ -73,12 +73,12 @@ export function resolvePlaygroundCredential(
return { keyId, projectId: keys.find((key) => key.id === keyId)?.project_id };
}
-/** usePlaygroundCredential 返回的有效凭据与剩余次数状态。 */
+/** Effective credential and remaining-count state returned by usePlaygroundCredential. */
export function usePlaygroundCredential(experience: PlaygroundTrialExperience = 'language') {
const queryClient = useQueryClient();
const keysQuery = useAllKeysQuery();
const trialQuery = usePlaygroundTrialQuery();
- // 只为默认项目选择普通 Key;与 Header 等共用 /me 缓存,不重复请求。
+ // Select an ordinary key only for the default project; share the /me cache with Header and others, and do not request it again.
const meQuery = useQuery({ queryKey: mapKeys.me(), queryFn: mapAuthApi.me });
const keys = useMemo(
@@ -101,36 +101,36 @@ export function usePlaygroundCredential(experience: PlaygroundTrialExperience =
}, [queryClient]);
return {
- /** 当前默认项目,供上传与识别生命周期隔离。 */
+ /** Current default project, used to isolate upload and recognition lifecycles. */
defaultProjectId: meQuery.data?.default_project_id,
- /** 普通自有 Key 是否仍在加载(免费体验状态也视为凭据加载的一部分)。 */
+ /** Whether an ordinary own key is still loading (free-trial state also counts as part of credential loading). */
keysLoading: keysQuery.isLoading || trialQuery.isLoading,
- /** 是否存在用户自有 active API Key;隐藏体验 Key 不计入。 */
+ /** Whether the user has an own active API Key; the hidden trial key is not counted. */
hasKeys: keys.length > 0,
- /** 当前有效 Key id:有免费体验时为隐藏 Key,否则为普通 Key。 */
+ /** Current effective key id: the hidden key while a free trial remains, otherwise an ordinary key. */
keyId: credential.keyId,
- /** 当前有效 Key 所属项目。 */
+ /** Project the current effective key belongs to. */
keyProjectId: credential.projectId,
- /** 四类体验的剩余免费次数。 */
+ /** Remaining free counts for the four experiences. */
trialRemaining,
- /** 免费体验状态是否仍在加载。 */
+ /** Whether free-trial state is still loading. */
trialLoading: trialQuery.isLoading,
- /** 免费体验状态是否获取失败。 */
+ /** Whether fetching free-trial state failed. */
trialError: trialQuery.isError,
- /** 当前体验仍有额度且隐藏 Key 可用。 */
+ /** The current experience still has quota and the hidden key is available. */
trialAvailable: usingTrial,
- /** 明文密钥就绪态。 */
+ /** Plaintext-secret readiness. */
secretReady: Boolean(secret),
secretLoading: usingTrial ? trialQuery.isFetching : secretQuery.isFetching,
secretError: usingTrial ? trialQuery.isError : secretQuery.isError,
- /** 懒取当前有效明文密钥;仅内存使用,不落盘。 */
+ /** Lazily read the current effective plaintext secret; used in memory only, and not persisted to disk. */
getSecret,
- /** 请求终态后刷新免费体验状态。 */
+ /** Refresh free-trial state after a request reaches a terminal state. */
refreshTrial,
};
}
-/** 默认 Key 选定:默认项目下首个 active key 优先,否则首个 active key。 */
+/** Default key selection: the first active key under the default project is preferred, otherwise the first active key. */
function pickDefaultKeyId(keys: MapApiKey[], defaultProjectId?: string): string {
if (defaultProjectId) {
const inDefault = keys.find((key) => key.project_id === defaultProjectId);
diff --git a/webdemo/frontend/src/pages/playground/hooks/usePlaygroundModel.ts b/webdemo/frontend/src/pages/playground/hooks/usePlaygroundModel.ts
index 6fb235c..92126a8 100644
--- a/webdemo/frontend/src/pages/playground/hooks/usePlaygroundModel.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/usePlaygroundModel.ts
@@ -1,8 +1,8 @@
/**
- * 模型 + API Key 选择与明文密钥编排 hook。
+ * Hook that selects the model and API Key and orchestrates the plaintext secret.
*
- * 用途:把「可调用模型列表」与「Playground 有效凭据」收敛为一个选择器状态机。
- * 明文密钥仅存 TanStack Query 缓存(staleTime/gcTime=0),不落盘。
+ * Purpose: collapse "the list of callable models" and "the effective Playground credential" into one selector state machine.
+ * The plaintext secret lives only in the TanStack Query cache (staleTime/gcTime=0) and is not persisted to disk.
*/
import { useCallback, useMemo, useState } from 'react';
@@ -15,67 +15,67 @@ import {
} from './usePlaygroundCredential';
import { languageModels, modelsByExperience } from '@/utils/modelExperience';
-/** usePlaygroundModel 返回 */
+/** usePlaygroundModel return value */
interface UsePlaygroundModelReturn {
- /** 当前登录用户 ID,供会话草稿按账号隔离。 */
+ /** Currently logged-in user ID, so conversation drafts are isolated by account. */
userId?: string;
- /** 当前默认项目,供上传与识别生命周期隔离。 */
+ /** Current default project, used to isolate upload and recognition lifecycles. */
defaultProjectId?: string;
- /** 当前用户信息是否仍在加载。 */
+ /** Whether the current user info is still loading. */
userLoading: boolean;
- /** 语言对话可选模型(已排除语音合成 / 实时语音) */
+ /** Models available for language chat (speech synthesis and realtime voice are already excluded) */
models: MapModel[];
modelsLoading: boolean;
- /** 当前语言对话选中模型 id */
+ /** Model id currently selected for language chat */
modelId: string;
selectModel: (id: string) => void;
- /** 语音合成可选模型(管理端勾了「语音合成」的全部模型) */
+ /** Models available for speech synthesis (every model the admin console checked as "speech synthesis") */
ttsModels: MapModel[];
- /** 当前选中的语音合成模型,无可用模型时 undefined */
+ /** Speech-synthesis model currently selected; undefined when no model is available */
ttsModel?: MapModel;
selectTtsModel: (id: string) => void;
- /** 实时对话可选模型(管理端勾了「实时对话」的全部模型) */
+ /** Models available for realtime conversation (every model the admin console checked as "realtime conversation") */
realtimeModels: MapModel[];
- /** 当前选中的实时对话模型,无可用模型时 undefined */
+ /** Realtime-conversation model currently selected; undefined when no model is available */
realtimeModel?: MapModel;
selectRealtimeModel: (id: string) => void;
- /** 图像解析可选模型(管理端勾了「图像解析」且支持图像输入) */
+ /** Models available for image parsing (checked as "image parsing" in the admin console and supporting image input) */
imageParseModels: MapModel[];
- /** 当前选中的图像解析模型,无可用模型时 undefined */
+ /** Image-parsing model currently selected; undefined when no model is available */
imageParseModel?: MapModel;
selectImageParseModel: (id: string) => void;
- /** 密钥列表是否加载中(用于区分「加载中」与「确无可用 Key」) */
+ /** Whether the secret list is loading (used to tell "loading" from "there really is no usable key") */
keysLoading: boolean;
- /** 是否存在可用 API Key(无则上层引导去创建) */
+ /** Whether a usable API Key exists (if not, the caller guides the user to create one) */
hasKeys: boolean;
- /** 自动选定的 Key id(默认项目优先,对用户不可见、不可切换) */
+ /** Auto-selected key id (the default project is preferred; invisible to the user and not switchable) */
keyId: string;
- /** 实际模型 Key 所属项目,用于核对文档上传的默认项目边界。 */
+ /** Project the actual model key belongs to, used to check the default-project boundary of a document upload. */
keyProjectId?: string;
- /** 明文密钥就绪态 */
+ /** Plaintext-secret readiness */
secretReady: boolean;
secretLoading: boolean;
secretError: boolean;
- /** 四类体验剩余免费次数 */
+ /** Remaining free counts for the four experiences */
trialRemaining: ReturnType<typeof usePlaygroundCredential>['trialRemaining'];
- /** 免费体验状态加载中 */
+ /** Free-trial state is loading */
trialLoading: boolean;
- /** 免费体验状态获取失败 */
+ /** Fetching free-trial state failed */
trialError: boolean;
- /** 是否正在使用隐藏免费体验 Key */
+ /** Whether the hidden free-trial key is in use */
trialAvailable: boolean;
- /** 懒取明文密钥(供 useChat 在 send 时调用) */
+ /** Lazily read the plaintext secret (for useChat to call at send time) */
getSecret: () => string | undefined;
- /** 请求终态后刷新免费体验状态。 */
+ /** Refresh free-trial state after a request reaches a terminal state. */
refreshTrial: () => void;
}
/**
- * 模型选择与密钥编排。
+ * Model selection and secret orchestration.
*
- * 四类体验各自记忆选中模型(语言 / TTS / 实时 / 图像解析),互不干扰。
- * API Key 不暴露选择器:免费额度未用完时自动使用隐藏体验 Key;用完后回退默认项目下
- * 的 active key。两者都不可用时由上层显示「去创建 API Key」引导。
+ * Each of the four experiences remembers its own selected model (language / TTS / realtime / image parsing), and they do not interfere.
+ * The API Key exposes no selector: while free quota remains, the hidden trial key is used automatically; after it is used up, fall back to the
+ * active key under the default project. When neither is available, the caller shows the "go create an API Key" guide.
*/
export function usePlaygroundModel(
credentialExperience: PlaygroundTrialExperience = 'language',
@@ -84,13 +84,13 @@ export function usePlaygroundModel(
const setPrefs = useAppStore((s) => s.setPlaygroundPrefs);
const modelsQuery = useModelsQuery();
- // 按能力筛选四类体验;支持文本输入的图像解析模型也可用于语言对话。
+ // Filter the four experiences by capability; an image-parsing model that supports text input can also be used for language chat.
const allModels = useMemo(() => modelsQuery.data?.list ?? [], [modelsQuery.data]);
const models = useMemo(() => languageModels(allModels), [allModels]);
const ttsModels = useMemo(() => modelsByExperience(allModels, 'tts'), [allModels]);
const realtimeModels = useMemo(() => modelsByExperience(allModels, 'realtime'), [allModels]);
const imageParseModels = useMemo(() => modelsByExperience(allModels, 'image-parse'), [allModels]);
- // URL 体验在无对应模型时会回退语言页面;凭据类型必须同步回退,避免误扣其它体验额度。
+ // A URL experience falls back to the language page when it has no matching model; the credential type must fall back in sync, so another experience's quota is not charged by mistake.
const effectiveCredentialExperience = resolvePlaygroundCredentialExperience(
credentialExperience,
{
@@ -106,7 +106,7 @@ export function usePlaygroundModel(
const [realtimeModelIdState, setRealtimeModelIdState] = useState<string>('');
const [imageParseModelIdState, setImageParseModelIdState] = useState<string>('');
- // 渲染期条件 seeding:列表就绪且未选时,落定初值(优先持久化偏好),避免 effect+setState。
+ // Conditional seeding during render: when the list is ready and nothing is selected, settle the initial value (persisted preference first), avoiding effect plus setState.
const modelId = resolveSelection(
modelIdState,
prefs.lastModelId,
@@ -130,7 +130,7 @@ export function usePlaygroundModel(
const ttsModel = ttsModels.find((m) => m.id === ttsModelId);
const realtimeModel = realtimeModels.find((m) => m.id === realtimeModelId);
const imageParseModel = imageParseModels.find((m) => m.id === imageParseModelId);
- // 草稿隔离直接使用当前 JWT 的 sub,避免账号切换时 TanStack Query 短暂返回上一账号 /me 缓存。
+ // Draft isolation uses the current JWT sub directly, so an account switch does not briefly get the previous account's /me cache from TanStack Query.
const userId = getTokenSubject();
const selectModel = useCallback(
@@ -181,7 +181,7 @@ export function usePlaygroundModel(
};
}
-/** 模型选择落定:已手动选 → 用之;否则用持久化偏好(若在列表内);再否则列表首项 */
+/** Settle model selection: if one was chosen manually, use it; otherwise the persisted preference if it is in the list; otherwise the first item in the list */
function resolveSelection(manual: string, preferred: string, ids: string[]): string {
if (manual && ids.includes(manual)) return manual;
if (preferred && ids.includes(preferred)) return preferred;
diff --git a/webdemo/frontend/src/pages/playground/hooks/usePlaygroundParams.ts b/webdemo/frontend/src/pages/playground/hooks/usePlaygroundParams.ts
index b15f240..6dc1a39 100644
--- a/webdemo/frontend/src/pages/playground/hooks/usePlaygroundParams.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/usePlaygroundParams.ts
@@ -1,8 +1,8 @@
/**
- * 对话参数偏好 hook(按模型持久化)。
+ * Conversation parameter-preference hook (persisted per model).
*
- * 用途:托管温度/top_p/最大输出/思考深度/思考风格/流式等参数。这些参数**按模型分别记忆**——
- * 用户设置优先于模型 parameter_config;两者都未设置的数值字段保持空值。
+ * Purpose: own parameters such as temperature, top_p, maximum output, reasoning depth, reasoning style, and streaming. These parameters are **remembered per model** —
+ * a user setting takes priority over the model parameter_config; a numeric field set by neither stays empty.
*/
import { useCallback, useMemo } from 'react';
@@ -12,32 +12,32 @@ import { DEFAULT_PARAMS, type PlaygroundParams, type ThinkingDepth } from '../ty
import { requiresNonStreaming } from '../utils/params';
import { resolveModelParameterDefaults } from '../utils/modelParameterDefaults';
-/** usePlaygroundParams 返回 */
+/** usePlaygroundParams return value */
interface UsePlaygroundParamsReturn {
params: PlaygroundParams;
- /** 增量更新参数(写入当前模型那份) */
+ /** Update parameters incrementally (written into the copy for the current model) */
update: (patch: Partial<PlaygroundParams>) => void;
- /** 单独设置思考深度 */
+ /** Set reasoning depth on its own */
setThinkingDepth: (depth: ThinkingDepth) => void;
- /** 切换联网搜索 */
+ /** Toggle web search */
setWebSearch: (webSearch: boolean) => void;
- /** 设置联网启用的工具列表(webSearch=true 时生效) */
+ /** Set the tool list enabled for web search (takes effect when webSearch=true) */
setEnabledTools: (tools: string[]) => void;
- /** 设置用户位置(用于 datetime 工具) */
+ /** Set the user location (used by the datetime tool) */
setUserLocation: (location: string) => void;
- /** 切换流式输出 */
+ /** Toggle streaming output */
setStream: (stream: boolean) => void;
- /** 重置当前模型为默认值 */
+ /** Reset the current model to defaults */
reset: () => void;
}
/**
- * 参数偏好状态机(按模型)。
- * @param modelId 当前选中模型 id;为空时退化为一份临时默认参数(仍可调,但不落到具体模型)
- * @param capabilities deep_thinking 决定能力,show_reasoning 仅决定未设置用户偏好时的默认值。
- * 不支持时覆盖存档与模型参数,强制关闭;支持时保留用户按模型保存的选择。
- * @param parameterConfig 管理端配置的模型级默认请求参数。
- * @param allowWebSearch 当前模型是否显式支持联网搜索;缺省按不支持处理。
+ * Parameter-preference state machine (per model).
+ * @param modelId currently selected model id; when empty, fall back to one temporary set of default parameters (still adjustable, but not stored on a specific model)
+ * @param capabilities deep_thinking decides the capability, and show_reasoning only decides the default when the user has not set a preference.
+ * When unsupported, override the archive and model parameters and force it off; when supported, keep the choice the user saved per model.
+ * @param parameterConfig model-level default request parameters configured in the admin console.
+ * @param allowWebSearch whether the current model explicitly supports web search; treated as unsupported when omitted.
*/
export function usePlaygroundParams(
modelId: string,
@@ -61,7 +61,7 @@ export function usePlaygroundParams(
const thinkingDepth =
stored?.thinkingDepth ?? modelDefaults.values.thinkingDepth ?? defaultThinkingDepth;
- // raw 是当前生效参数,但模型默认值不会写入用户偏好,避免后续管理端调整失效。
+ // raw is the parameters currently in effect, but model defaults are not written into user preferences, so a later admin-console change does not stop taking effect.
const raw = useMemo<PlaygroundParams>(() => {
return {
...DEFAULT_PARAMS,
@@ -73,7 +73,7 @@ export function usePlaygroundParams(
thinkingDepth,
thinkingStyle:
stored?.thinkingStyle ?? modelDefaults.values.thinkingStyle ?? DEFAULT_PARAMS.thinkingStyle,
- // 客户端开关与模型默认一致时仍由 L2 原样注入;不一致时显式覆盖整组思考参数。
+ // When the client switch matches the model default, L2 still injects it as-is; when they differ, explicitly override the whole reasoning-parameter group.
includeThinkingParams:
storedHasThinkingOverride ||
!modelDefaults.hasThinkingDefaults ||
@@ -81,13 +81,13 @@ export function usePlaygroundParams(
thinkingControlFormat:
stored?.thinkingStyle === 'thinking' ? 'thinking' : modelDefaults.thinkingControlFormat,
thinkingDefaults: modelDefaults.values.thinkingDefaults,
- // MiniCPM-OCR-Jev 默认非流式;用户显式打开只保留 UI 偏好,实际请求由补全链路强制非流式。
+ // MiniCPM-OCR-Jev defaults to non-streaming; the user turning it on explicitly keeps only the UI preference, and the actual request is forced non-streaming by the completion path.
stream:
stored?.stream ??
(forceNonStreaming ? false : (modelDefaults.values.stream ?? DEFAULT_PARAMS.stream)),
webSearch: allowWebSearch ? (stored?.webSearch ?? DEFAULT_PARAMS.webSearch) : false,
- // 不回落到默认值:未存过工具选择时保持 undefined,请求体里不出现 enabled_tools,
- // 后端据此启用全部工具(见 types.ts 中 enabledTools 的三态说明)。
+ // Do not fall back to a default: when no tool selection has been stored, keep it undefined, so enabled_tools does not appear in the request body,
+ // and the backend enables every tool from that (see the three-state note on enabledTools in types.ts).
enabledTools: stored?.enabledTools,
userLocation: stored?.userLocation,
};
@@ -100,7 +100,7 @@ export function usePlaygroundParams(
forceNonStreaming,
]);
- // 不支持深度思考时必须显式关闭,避免旧偏好或 L2 默认参数重新开启。
+ // When deep reasoning is unsupported it must be turned off explicitly, so an old preference or an L2 default parameter does not turn it back on.
const params = useMemo<PlaygroundParams>(
() =>
allowReasoning
diff --git a/webdemo/frontend/src/pages/playground/hooks/useRealtimeSession.ts b/webdemo/frontend/src/pages/playground/hooks/useRealtimeSession.ts
index 2c58b64..40ad0d9 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useRealtimeSession.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useRealtimeSession.ts
@@ -1,9 +1,9 @@
/**
- * 实时全双工会话 Hook(MiniCPM-O realtime,替代原半双工 useVoiceChat)。
+ * Realtime full-duplex session hook (MiniCPM-O realtime, replacing the old half-duplex useVoiceChat).
*
- * 薄适配层:把 RealtimeConnection 抛出的状态/波形/字幕增量映射到 React 状态,并维护
- * 助手字幕气泡的累积(每轮一条,收到 listen 事件后收尾)。传输/音频/会话时序见
- * utils/realtimeConnection.ts。返回的 VoiceStatus/VoiceMessage/VOICE_BAR_COUNT 供双工组件复用。
+ * A thin adapter: map state, waveform, and caption increments thrown by RealtimeConnection onto React state, and maintain
+ * accumulation of the assistant caption bubble (one per turn, closed when a listen event arrives). Transport, audio, and session timing are in
+ * utils/realtimeConnection.ts. The returned VoiceStatus, VoiceMessage, and VOICE_BAR_COUNT are reused by duplex components.
*/
import { useEffect, useRef, useState } from 'react';
@@ -26,16 +26,16 @@ export type { VoiceStatus } from '../utils/realtimeConnection';
type PlaygroundModel = ReturnType<typeof usePlaygroundModel>;
-/** 波形条数量 */
+/** Number of waveform bars */
export const VOICE_BAR_COUNT = 40;
/**
- * 模型输出挂断标记后,延迟多久真正挂断。
- * 留一点时间让已缓冲的告别语音播完,避免话没说完就断线。
+ * How long to wait after the model outputs the hang-up marker before actually hanging up.
+ * Leave a little time for the buffered goodbye audio to finish playing, so the line does not drop before the sentence is finished.
*/
const HANGUP_DELAY_MS = 2500;
-/** 一条字幕消息 */
+/** One caption message */
export interface VoiceEvent {
id: number;
at: number;
@@ -50,7 +50,7 @@ export interface VoiceMessage {
text: string;
}
-/** 上游实时服务下发的排队信息。 */
+/** Queue info issued by the upstream realtime service. */
export interface RealtimeQueue {
position?: number;
estimatedWaitSeconds?: number;
@@ -58,29 +58,29 @@ export interface RealtimeQueue {
}
/**
- * 频谱可视化帧。
+ * A spectrum visualization frame.
*
- * 刻意**不进 React 状态**:频谱由 rAF 以 ~60fps 推送,若每帧 setState,整棵双工组件树
- * (舞台/字幕/控制条/参数面板)每秒重渲染 60 次,字幕掉帧且主线程被挤占后下行音频的排队
- * 调度被推迟、播放出现空隙。消费方(VoiceOrb)本就是 canvas 命令式绘制,直接读这个可变
- * 引用即可,不需要 React 参与。
+ * Deliberately **not in React state**: the spectrum is pushed by rAF at ~60fps. If every frame called setState, the whole duplex component tree
+ * (stage, captions, control bar, parameter panel) would re-render 60 times a second, captions would drop frames, and once the main thread is crowded the downlink audio queue
+ * scheduling would be delayed and playback would gap. The consumer (VoiceOrb) already draws the canvas imperatively, so it can read this mutable
+ * reference directly and does not need React involved.
*/
export interface VizFrame {
- /** 平滑后的音量 0–1,驱动中心脉动 */
+ /** Smoothed volume 0–1, driving the center pulse */
level: number;
- /** 频谱条 0–1,驱动环形柱高 */
+ /** Spectrum bars 0–1, driving the ring bar height */
bars: number[];
}
-/** connect 当轮参数(model/secret/barCount 由 Hook 注入) */
+/** Parameters for this connect turn (model, secret, and barCount are injected by the hook) */
export type ConnectOptions = Omit<RealtimeConnectOptions, 'barCount' | 'model' | 'secret'> & {
- /** 会话被模型主动结束时回调,供视图同步关摄像头与复位 UI */
+ /** Callback when the session is ended by the model on purpose, so the view can turn the camera off and reset the UI in sync */
onSessionEnd?: () => void;
};
const IDLE_BARS = (): number[] => new Array(VOICE_BAR_COUNT).fill(0);
-/** 实时全双工会话;返回状态、波形、字幕与会话控制方法。 */
+/** Realtime full-duplex session; returns state, waveform, captions, and session control methods. */
export function useRealtimeSession(model: PlaygroundModel) {
const { t } = useTranslation('playground');
const [status, setStatus] = useState<VoiceStatus>('idle');
@@ -93,10 +93,10 @@ export function useRealtimeSession(model: PlaygroundModel) {
const [error, setError] = useState<string>();
const [queue, setQueue] = useState<RealtimeQueue>();
const [forceListen, setForceListen] = useState(false);
- /** 模型主动请求结束通话(命中挂断标记),供视图提示"通话已由模型结束" */
+ /** The model requested to end the call on purpose (the hang-up marker was hit), so the view can say "the call was ended by the model" */
const [endedByModel, setEndedByModel] = useState(false);
- /** 频谱帧:60fps 直写,绕开 React 渲染(见 VizFrame 注释) */
+ /** Spectrum frame: written directly at 60fps, bypassing React render (see the VizFrame comment) */
const viz = useRef<VizFrame>({ level: 0, bars: IDLE_BARS() });
const conn = useRef<RealtimeConnection | null>(null);
const idSeq = useRef(0);
@@ -104,10 +104,10 @@ export function useRealtimeSession(model: PlaygroundModel) {
const metricsRef = useRef(metrics);
const metricsPaintAt = useRef(0);
const assistantId = useRef<number | null>(null);
- /** 当前轮已累积的字幕(已剔除挂断标记),用于跨 delta 检测被拆断的标记 */
+ /** Caption accumulated for the current turn (hang-up marker already removed), used to detect a marker split across deltas */
const turnText = useRef('');
const hangupTimer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
- /** 会话结束回调(由视图注入,用于同步关摄像头/复位 UI) */
+ /** Session-end callback (injected by the view, used to turn the camera off and reset the UI in sync) */
const onSessionEnd = useRef<(() => void) | undefined>(undefined);
function clearHangupTimer() {
@@ -116,8 +116,8 @@ export function useRealtimeSession(model: PlaygroundModel) {
}
/**
- * 命中挂断标记:延迟挂断,留时间播完告别语音。
- * 幂等——同一轮里标记可能被拆成多个 delta,重复触发只保留第一个定时器。
+ * The hang-up marker was hit: delay the hang-up, leaving time for the goodbye audio to finish.
+ * Idempotent — within one turn the marker may be split across several deltas, and repeated triggers keep only the first timer.
*/
function scheduleHangup() {
if (hangupTimer.current) return;
@@ -130,11 +130,11 @@ export function useRealtimeSession(model: PlaygroundModel) {
}
/**
- * 助手字幕增量:无进行中气泡则新建,否则续写当前气泡。
+ * Assistant caption increment: if there is no bubble in progress, create one; otherwise continue the current bubble.
*
- * 挂断标记在**累积后的整段文本**上检测:标记可能被上游拆进相邻两个 delta
- * (如 "[[HANG" + "UP]]"),逐段匹配会漏检。命中后从展示文本剔除并安排挂断。
- * 累积文本用 ref 跟随,避免在 setState updater 里做副作用(updater 须为纯函数)。
+ * The hang-up marker is detected on the **whole accumulated text**: the marker may be split by the upstream into two adjacent deltas
+ * (such as "[[HANG" + "UP]]"), and matching segment by segment would miss it. After a hit, strip it from the displayed text and schedule the hang-up.
+ * Accumulated text is followed with a ref, so a side effect is not done inside a setState updater (an updater must be a pure function).
*/
function pushUserText(text: string): void {
if (!text.trim()) return;
@@ -213,7 +213,7 @@ export function useRealtimeSession(model: PlaygroundModel) {
setMetrics(next);
}
if (event.type === 'session_created') {
- // realtime 免费次数在握手通过后消耗;立即刷新,额度用尽时提示创建 API Key。
+ // Realtime free count is consumed after the handshake succeeds; refresh immediately, and when the quota is used up prompt to create an API Key.
model.refreshTrial();
const nextId = event.sessionId || `local-${event.at}`;
setSessionId(nextId);
@@ -253,7 +253,7 @@ export function useRealtimeSession(model: PlaygroundModel) {
}
},
onViz: (lvl, next) => {
- // 直写可变引用:60fps 不触发任何重渲染,画布下一帧自然读到新值
+ // Write the mutable reference directly: 60fps triggers no re-render, and the canvas reads the new value on the next frame
viz.current.level = viz.current.level * 0.7 + lvl * 0.3;
viz.current.bars = next;
},
@@ -304,12 +304,12 @@ export function useRealtimeSession(model: PlaygroundModel) {
setStatus('error');
return false;
}
- // onSessionEnd 是 Hook 层回调,不传给传输层
+ // onSessionEnd is a hook-level callback and is not passed to the transport layer
const { onSessionEnd: onEnd, ...connectOpts } = o;
onSessionEnd.current = onEnd;
return ensureConn().connect({
...connectOpts,
- // 挂断约定追加在发送时,不污染用户在面板里编辑的系统提示词
+ // The hang-up convention is appended at send time, so it does not contaminate the system prompt the user edits in the panel
system: withHangupProtocol(o.system),
barCount: VOICE_BAR_COUNT,
model: modelId,
@@ -342,7 +342,7 @@ export function useRealtimeSession(model: PlaygroundModel) {
return conn.current?.toggleHD() ?? false;
}
- // 卸载兜底:断连并清掉待触发的挂断定时器
+ // Unmount fallback: disconnect and clear a hang-up timer that has not fired yet
useEffect(
() => () => {
clearHangupTimer();
diff --git a/webdemo/frontend/src/pages/playground/hooks/useSplitPane.ts b/webdemo/frontend/src/pages/playground/hooks/useSplitPane.ts
index 95135ce..aeeba18 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useSplitPane.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useSplitPane.ts
@@ -1,38 +1,38 @@
/**
- * 左右对照分栏拖拽。
+ * Dragging a left-right comparison split.
*
- * 用途:对照阅读时,原图和结果谁该占更多宽度取决于图本身——竖排表格想给原图多点,
- * 通篇文字想给 Markdown 多点。固定 50/50 是替用户做了决定。
+ * Purpose: while reading side by side, whether the original image or the result should take more width depends on the image itself — a vertical table wants more for the original,
+ * and a page of text wants more for the Markdown. A fixed 50/50 decides that for the user.
*
- * 拖拽用 Pointer Events + setPointerCapture:一次捕获到底,
- * 指针划出分隔条甚至划出窗口都不会丢事件,不必在 window 上挂全局监听再记得摘掉。
+ * Dragging uses Pointer Events plus setPointerCapture: one capture lasts to the end,
+ * so the pointer leaving the divider or even the window does not drop events, and there is no global listener on window to remember to remove.
*
- * 按下时记录指针、比例与容器宽度,移动按位移换算,避免从透明抓取区边缘按下时跳动。
+ * On press, record the pointer, the ratio, and the container width, and convert movement from the displacement, so pressing from the edge of the transparent grab area does not jump.
*/
import { useCallback, useRef, useState } from 'react';
-/** 左栏占比上下限,避免任一侧被拖到不可用。 */
+/** Upper and lower bounds of the left-pane ratio, so neither side can be dragged until it is unusable. */
const MIN_RATIO = 24;
const MAX_RATIO = 76;
-/** 键盘每次调整的步长。 */
+/** Step for each keyboard adjustment. */
const KEY_STEP = 2;
-/** 容器标记属性,分隔条靠它反查自己该按谁的宽度换算。 */
+/** Container marker attribute; the divider uses it to find which width it should convert against. */
const CONTAINER_ATTR = 'data-split-container';
-/** 分栏控制。 */
+/** Split controls. */
export interface SplitPane {
- /** 左栏占比(百分数) */
+ /** Left-pane ratio (percent) */
ratio: number;
- /** 是否正在拖拽。拖拽期间必须关掉分栏宽度过渡,否则栏宽会慢指针一步 */
+ /** Whether a drag is in progress. The split-width transition must be turned off while dragging, or the pane width lags the pointer by one step */
dragging: boolean;
- /** 摊到分栏容器上,让分隔条能找到它 */
+ /** Spread onto the split container so the divider can find it */
containerProps: Record<string, string>;
onPointerDown: (event: React.PointerEvent<HTMLElement>) => void;
onPointerMove: (event: React.PointerEvent<HTMLElement>) => void;
onPointerUp: (event: React.PointerEvent<HTMLElement>) => void;
onKeyDown: (event: React.KeyboardEvent<HTMLElement>) => void;
- /** 双击分隔条回到均分 */
+ /** Double-click the divider to return to an even split */
reset: () => void;
min: number;
max: number;
@@ -43,13 +43,13 @@ function clamp(value: number): number {
}
/**
- * 可拖拽分栏。
- * @param initial 左栏初始占比,默认均分
+ * A draggable split.
+ * @param initial initial left-pane ratio; even split by default
*/
export function useSplitPane(initial = 50): SplitPane {
const [ratio, setRatio] = useState(clamp(initial));
const [dragging, setDragging] = useState(false);
- // 事件间同步保存拖拽快照,避免状态更新延迟或第二根手指改变本次拖拽。
+ // Save the drag snapshot synchronously between events, so a delayed state update or a second finger does not change this drag.
const dragRef = useRef<{
pointerId: number;
clientX: number;
@@ -66,7 +66,7 @@ export function useSplitPane(initial = 50): SplitPane {
const dividerRect = target.getBoundingClientRect();
const width = containerRect?.width ?? 0;
if (!containerRect || width <= 0) return;
- // 负边距让分隔条右边缘贴合原图栏边界,按当前布局接续未结束的调宽过渡。
+ // A negative margin makes the divider's right edge meet the original-image pane boundary, continuing an unfinished width transition for the current layout.
const ratio = clamp(
((dividerRect.left + dividerRect.width - containerRect.left) / width) * 100,
);
diff --git a/webdemo/frontend/src/pages/playground/hooks/useTtsSynthesis.ts b/webdemo/frontend/src/pages/playground/hooks/useTtsSynthesis.ts
index 8fa513b..537c702 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useTtsSynthesis.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useTtsSynthesis.ts
@@ -1,11 +1,11 @@
/**
- * 语音合成(TTS)编排 Hook。
+ * Speech-synthesis (TTS) orchestration hook.
*
- * 用途:把「合成文本」「声音描述(预设/自定义)」「音色选择」「上传/录制参考音频」「引导
- * 强度/高级开关」状态与一次真实合成请求收敛为状态机。合成走 synthesizeSpeech(L2 `/v1/audio/speech`),
- * 成功后拿到可播放/下载的 Object URL,并在重合成/卸载时释放旧 URL。音色三态:默认(无 ref)/ 预置(内置
- * wav → data URI)/ 平台私有音色(voice_xxx 由 MAP 按用户归属解析,仅语音复刻模式可用)。
- * 明文密钥经 usePlaygroundModel 懒取,不落盘。
+ * Purpose: collapse the state of "synthesis text", "voice description (preset or custom)", "voice selection", "uploaded or recorded reference audio", and "guidance
+ * strength / advanced switches" together with one real synthesis request into a state machine. Synthesis goes through synthesizeSpeech (L2 `/v1/audio/speech`),
+ * and on success receives an Object URL that can be played and downloaded; the old URL is released on re-synthesis or unmount. A voice has three states: default (no ref) / preset (built-in
+ * wav → data URI) / a platform private voice (voice_xxx is resolved by MAP from user ownership, and is available only in voice-clone mode).
+ * The plaintext secret is read lazily through usePlaygroundModel and is not persisted to disk.
*/
import { useEffect, useMemo, useRef, useState } from 'react';
@@ -33,7 +33,7 @@ import type { usePlaygroundModel } from './usePlaygroundModel';
type PlaygroundModel = ReturnType<typeof usePlaygroundModel>;
-// 供视图直接从本 Hook 取用音色目录 / 声音描述预设 / 输出格式与合成参数常量(避免视图跨层再引 utils)
+// The view takes the voice catalog, voice-description presets, output format, and synthesis-parameter constants directly from this hook (so the view does not import utils across layers)
export {
TTS_VOICES,
VOICE_DEFAULT,
@@ -58,29 +58,29 @@ export {
} from '../utils/ttsVoices';
/**
- * 语音合成编排。
- * @param model usePlaygroundModel 返回(提供模型、密钥)
- * @param allowSavedVoices 是否为语音复刻模式;仅该模式读取用户私有音色
+ * Speech-synthesis orchestration.
+ * @param model return value of usePlaygroundModel (provides the model and the secret)
+ * @param allowSavedVoices whether this is voice-clone mode; only that mode reads the user's private voices
*/
export function useTtsSynthesis(model: PlaygroundModel, allowSavedVoices: boolean) {
const { t, i18n } = useTranslation('playground');
const [text, setText] = useState(() => t('ttsSample1'));
const defaultSampleRef = useRef(t('ttsSample1'));
const [voice, setVoice] = useState(VOICE_DEFAULT);
- // 声音描述(Control Instruction):预设选择 + 自定义/预设共用的描述文本 + 引导强度(cfg_value)
+ // Voice description (Control Instruction): preset selection + description text shared by custom and preset + guidance strength (cfg_value)
const [controlPreset, setControlPreset] = useState(CONTROL_NONE);
const [control, setControl] = useState('');
const [cfg, setCfg] = useState(TTS_CFG_DEFAULT);
- // 高级开关:参考音频降噪 / 文本规范化(透传上游,生效取决于 LIS 能力)
+ // Advanced switches: reference-audio denoise / text normalization (forwarded upstream; whether they take effect depends on LIS capability)
const [denoise, setDenoise] = useState(false);
const [normalize, setNormalize] = useState(false);
- // 上传复刻的参考音频(16k wav data URI)与原文件名
+ // Reference audio of an uploaded clone (16k wav data URI) and the original file name
const [uploadRef, setUploadRef] = useState<string>();
const [uploadName, setUploadName] = useState<string>();
- // 录音路径错误(权限/时长)——上传路径的错误由视图 try/catch 弹 toast
+ // Recording-path errors (permission or duration) — upload-path errors are toasted by the view in try/catch
const [recordError, setRecordError] = useState<string>();
const [audioUrl, setAudioUrl] = useState<string>();
- // 结果音频的实际格式(随合成落定,与 format 选择解耦——切了格式但未重合成时下载名仍对应现有音频)
+ // Actual format of the result audio (settled with the synthesis, decoupled from the format selection — if the format was switched but not re-synthesized, the download name still matches the existing audio)
const [audioFormat, setAudioFormat] = useState<TtsFormat>('wav');
const urlRef = useRef<string | undefined>(undefined);
const voicesQuery = useVoicesQuery(allowSavedVoices);
@@ -88,8 +88,8 @@ export function useTtsSynthesis(model: PlaygroundModel, allowSavedVoices: boolea
() => voicesQuery.data?.list ?? [],
[voicesQuery.data?.list],
);
- // 查询完成后若历史音色已删除,视图和请求都回退默认值;不在 effect 里同步 setState,
- // 避免查询结果到达时产生额外级联渲染,同时保留用户刚选择的有效私有音色。
+ // After the query finishes, if a history voice was deleted, both the view and the request fall back to the default; do not setState synchronously in an effect,
+ // so the query result arriving does not cause an extra cascading render, while a valid private voice the user just selected is kept.
const effectiveVoice = resolveTtsVoice(
voice,
allowSavedVoices,
@@ -107,12 +107,12 @@ export function useTtsSynthesis(model: PlaygroundModel, allowSavedVoices: boolea
}, [i18n.resolvedLanguage, t]);
const isUpload = effectiveVoice === VOICE_UPLOAD;
- // 自定义项才展开描述输入框;预设项直接用其固定描述,不可编辑
+ // Only the custom item expands the description input; a preset item uses its fixed description directly and cannot be edited
const isCustomControl = controlPreset === CONTROL_CUSTOM;
/**
- * 选择声音描述预设:预设→套用其描述并(若有)填入配套示例文案;
- * 自定义→清空描述交由用户输入;不使用→清空描述。
+ * Select a voice-description preset: a preset applies its description and, if any, fills in the matching example copy;
+ * custom clears the description for the user to type; none clears the description.
*/
function selectControlPreset(value: string) {
setControlPreset(value);
@@ -126,8 +126,8 @@ export function useTtsSynthesis(model: PlaygroundModel, allowSavedVoices: boolea
if (preset?.sampleText) setText(preset.sampleText);
}
- // 预置/临时录音通过 ref_audio 传递;私有音色只传 voice_xxx,
- // 由后端按当前用户归属解析对象存储资源,避免浏览器重复下载大文件。
+ // A preset or a temporary recording is passed through ref_audio; a private voice passes only voice_xxx,
+ // and the backend resolves the object-storage resource from the current user's ownership, so the browser does not download a large file again.
async function resolveRefAudio(): Promise<string | undefined> {
if (effectiveVoice === VOICE_DEFAULT) return undefined;
if (effectiveVoice.startsWith('voice_')) return undefined;
@@ -150,7 +150,7 @@ export function useTtsSynthesis(model: PlaygroundModel, allowSavedVoices: boolea
voice: effectiveVoice.startsWith('voice_') ? effectiveVoice : undefined,
control,
refAudio,
- // cfg 门控:仅在用户从默认调开时下发,保护默认合成路径;denoise/normalize 仅开启时下发(透传上游)
+ // cfg gating: send it only when the user has moved it off the default, protecting the default synthesis path; denoise and normalize are sent only when turned on (forwarded upstream)
cfg: cfg !== TTS_CFG_DEFAULT ? cfg : undefined,
denoise: denoise || undefined,
normalize: normalize || undefined,
@@ -163,12 +163,12 @@ export function useTtsSynthesis(model: PlaygroundModel, allowSavedVoices: boolea
setAudioFormat(result.format);
},
onSettled: () => {
- // 合成终态后刷新免费次数,额度用尽时立即回退用户自有 Key。
+ // After synthesis reaches a terminal state, refresh the free count, and fall back to the user's own key immediately when the quota is used up.
model.refreshTrial();
},
});
- /** 上传/录音参考音频:转 16k wav data URI 存入状态;超 50s 或转码失败回抛可读文案 */
+ /** Upload or record reference audio: convert to a 16k wav data URI and store it in state; over 50s, or a transcode failure, rethrows readable copy */
async function uploadReference(file: Blob, name?: string) {
const { base64, durationSeconds } = await blobToWav16k(file);
if (durationSeconds > TTS_REF_MAX_SECONDS) {
@@ -183,7 +183,7 @@ export function useTtsSynthesis(model: PlaygroundModel, allowSavedVoices: boolea
setUploadName(name ?? (file instanceof File ? file.name : t('recordingClip')));
}
- // 录音路径:录完的整段音频复用 uploadReference(含 50s 校验),错误落 recordError 供视图内联展示
+ // Recording path: the finished clip reuses uploadReference (including the 50s check), and errors land in recordError for inline display in the view
const recorder = useVoiceRecorder(async (blob) => {
try {
await uploadReference(blob, `${t('recordingClip')}.wav`);
@@ -199,10 +199,10 @@ export function useTtsSynthesis(model: PlaygroundModel, allowSavedVoices: boolea
setRecordError(undefined);
}
- // 卸载时释放最后一个 Object URL
+ // On unmount, release the last Object URL
useEffect(() => () => void (urlRef.current && URL.revokeObjectURL(urlRef.current)), []);
- // 可合成:有文本 + 有模型 + 非合成中;选「上传复刻」时须已上传参考音频
+ // Can synthesize: has text + has a model + not synthesizing; when "upload a clone" is selected, reference audio must already be uploaded
const credentialAvailable = model.trialRemaining.tts > 0 || model.hasKeys;
const canSynthesize = useMemo(
() =>
@@ -232,7 +232,7 @@ export function useTtsSynthesis(model: PlaygroundModel, allowSavedVoices: boolea
setText,
voice: effectiveVoice,
setVoice,
- // 声音描述(预设下拉 + 自定义展开)与引导强度
+ // Voice description (preset dropdown + custom expand) and guidance strength
controlPreset,
selectControlPreset,
isCustomControl,
@@ -240,7 +240,7 @@ export function useTtsSynthesis(model: PlaygroundModel, allowSavedVoices: boolea
setControl,
cfg,
setCfg,
- // 高级开关:降噪 / 文本规范化(透传,生效取决于上游)
+ // Advanced switches: denoise / text normalization (passed through; whether they take effect depends on the upstream)
denoise,
setDenoise,
normalize,
@@ -250,13 +250,13 @@ export function useTtsSynthesis(model: PlaygroundModel, allowSavedVoices: boolea
savedVoicesLoading: voicesQuery.isLoading,
savedVoicesError: voicesQuery.isError,
uploadName,
- // 参考音频 data URI,可直接喂 <audio> 试听(重录/重传会自动覆盖,无需先清除)
+ // Reference-audio data URI, which can be fed straight to <audio> for a preview (re-recording or re-uploading overwrites it; no need to clear first)
referenceUrl: uploadRef,
uploadReference,
clearReference,
- // 录音入口(对齐官方 microphone 来源)
+ // Recording entry (aligned with the official microphone source)
recording: recorder.recording,
- // 录制中的实时频谱条与已录秒数,供视图显示声纹,让用户确认在收音
+ // Live spectrum bars and recorded seconds while recording, so the view can show a voiceprint and the user can confirm it is picking up sound
recordBars: recorder.bars,
recordSeconds: recorder.seconds,
startRecording: () => {
diff --git a/webdemo/frontend/src/pages/playground/hooks/useVoiceRecorder.ts b/webdemo/frontend/src/pages/playground/hooks/useVoiceRecorder.ts
index 038706b..f7e1696 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useVoiceRecorder.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useVoiceRecorder.ts
@@ -1,4 +1,4 @@
-/** 麦克风直接采集 PCM/WAV,支持暂停、继续、声纹反馈和有效时长限制。 */
+/** Capture PCM/WAV from the microphone directly, with pause, resume, voiceprint feedback, and an effective-duration limit. */
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -12,10 +12,10 @@ import {
const RECORD_BAR_COUNT = 28;
/**
- * 麦克风录音片段编排。
- * @param onClip 录制结束后的 WAV Blob 回调
- * @param maxSeconds 单段录音上限(秒),达上限自动停止;默认 50(对齐官方参考音频时长上限)
- * @returns 录音状态及 start / pause / resume / stop / cancel 操作
+ * Orchestration of a microphone recording clip.
+ * @param onClip WAV Blob callback after recording ends
+ * @param maxSeconds cap for one recording (seconds); it stops automatically at the cap. Default 50 (aligned with the official reference-audio duration cap)
+ * @returns recording state and the start / pause / resume / stop / cancel actions
*/
export function useVoiceRecorder(onClip: (blob: Blob) => void, maxSeconds = 50) {
const { t } = useTranslation('playground');
@@ -114,7 +114,7 @@ export function useVoiceRecorder(onClip: (blob: Blob) => void, maxSeconds = 50)
setSeconds(0);
secondsRef.current = 0;
- // 频谱失败不应影响录音主链路,因此使用独立 AudioContext 并单独容错。
+ // A spectrum failure must not affect the main recording path, so it uses a separate AudioContext and handles errors on its own.
try {
const vizContext = new AudioContext();
vizContextRef.current = vizContext;
@@ -127,7 +127,7 @@ export function useVoiceRecorder(onClip: (blob: Blob) => void, maxSeconds = 50)
},
);
} catch {
- // 浏览器禁用 AudioContext 时仍保留录音能力,只是不显示声纹。
+ // When the browser disables AudioContext, recording still works; only the voiceprint is not shown.
}
tickRef.current = setInterval(() => {
diff --git a/webdemo/frontend/src/pages/playground/hooks/useWheelGesture.ts b/webdemo/frontend/src/pages/playground/hooks/useWheelGesture.ts
index 6f0e5e1..d0ace61 100644
--- a/webdemo/frontend/src/pages/playground/hooks/useWheelGesture.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/useWheelGesture.ts
@@ -1,27 +1,27 @@
/**
- * 滚轮手势采集。
+ * Wheel-gesture collection.
*
- * 用途:图片缩放要跟着滚轮走,但原生滚轮事件直接接会有两个坑:
- * 1. React 把根上的 wheel 注册为 passive,合成事件里 preventDefault 拦不住页面滚动,
- * 必须自己以非 passive 方式挂原生监听;
- * 2. 一次滚动能打出上百个事件,逐个 setState 会让大图掉帧——所以按
- * requestAnimationFrame 合帧,累计增量每帧只应用一次。
+ * Purpose: image zoom has to follow the wheel, but attaching the native wheel event directly has two pitfalls:
+ * 1. React registers wheel on the root as passive, so preventDefault in a synthetic event cannot stop page scroll,
+ * and a native listener has to be attached non-passive by hand;
+ * 2. one scroll can fire hundreds of events, and setState on each one drops frames on a large image — so they are coalesced on
+ * requestAnimationFrame, and the accumulated delta is applied only once per frame.
*
- * 另外把「正在滚」暴露出去:连续手势期间调用方应关掉 CSS 过渡才跟手。
+ * "Currently scrolling" is also exposed: during a continuous gesture the caller should turn CSS transitions off so it follows the hand.
*/
import { useCallback, useEffect, useRef, useState } from 'react';
-/** 行模式滚轮(Firefox)一格 deltaY 只有 ±3,按行高折算成像素才有同样手感。 */
+/** In line-mode wheel (Firefox) one notch of deltaY is only ±3; convert it by line height into pixels so the feel matches. */
const LINE_HEIGHT = 16;
-/** 滚动停止多久后认为手势结束。 */
+/** How long after scrolling stops the gesture is considered finished. */
const SETTLE_MS = 140;
/**
- * 把元素上的滚轮接成合帧后的增量回调。
- * @param node 目标元素,null 时不监听
- * @param onDelta 每帧回调一次,delta 是累计的像素增量,event 是该帧最后一个事件
- * @returns gesturing 是否正在连续滚动
+ * Turn the wheel on an element into a coalesced delta callback.
+ * @param node target element; do not listen when null
+ * @param onDelta called once per frame; delta is the accumulated pixel increment, and event is the last event of that frame
+ * @returns gesturing, whether a continuous scroll is in progress
*/
export function useWheelGesture(
node: HTMLElement | null,
diff --git a/webdemo/frontend/src/pages/playground/hooks/voiceRecorderSession.ts b/webdemo/frontend/src/pages/playground/hooks/voiceRecorderSession.ts
index 3720923..aaec1f6 100644
--- a/webdemo/frontend/src/pages/playground/hooks/voiceRecorderSession.ts
+++ b/webdemo/frontend/src/pages/playground/hooks/voiceRecorderSession.ts
@@ -1,4 +1,4 @@
-/** PCM 录音会话及其浏览器资源。 */
+/** A PCM recording session and its browser resources. */
export interface PcmRecordingSession {
stream: MediaStream;
context: AudioContext;
@@ -10,8 +10,8 @@ export interface PcmRecordingSession {
}
/**
- * 释放一次 PCM 录音会话占用的浏览器资源。
- * @param session 待释放的录音会话
+ * Release the browser resources held by one PCM recording session.
+ * @param session recording session to release
*/
export function releaseRecordingSession(session: PcmRecordingSession): void {
session.processor.disconnect();
@@ -22,9 +22,9 @@ export function releaseRecordingSession(session: PcmRecordingSession): void {
}
/**
- * 合并录音过程中采集的 PCM 分片。
- * @param chunks PCM 分片
- * @returns 连续的单声道 PCM 样本
+ * Merge PCM chunks captured during recording.
+ * @param chunks PCM chunks
+ * @returns continuous mono PCM samples
*/
export function mergeRecordingChunks(chunks: Float32Array[]): Float32Array {
const length = chunks.reduce((total, chunk) => total + chunk.length, 0);
diff --git a/webdemo/frontend/src/pages/playground/index.tsx b/webdemo/frontend/src/pages/playground/index.tsx
index 758918f..443af5c 100644
--- a/webdemo/frontend/src/pages/playground/index.tsx
+++ b/webdemo/frontend/src/pages/playground/index.tsx
@@ -1,4 +1,4 @@
-/** 体验中心页面:组合模型入口、凭据、对话状态与文档工作台。 */
+/** Playground page: composes the model entry, credentials, chat state, and document workspace. */
import { useCallback, useState } from 'react';
import { useNavigate, useNavigationType, useParams } from 'react-router-dom';
@@ -40,7 +40,7 @@ import { canUsePlaygroundWebSearch } from './utils/webSearchCapability';
import { CitationDrawer } from './components/CitationDrawer';
import { useCitationPanel } from './hooks/useCitationPanel';
-/** URL 体验键到免费额度类型的映射;语言模型使用缺省 language。 */
+/** Map from a URL experience key to a free-quota type; language models use the default language. */
const playgroundCredentialExperiences = {
language: 'language',
tts: 'tts',
@@ -49,7 +49,7 @@ const playgroundCredentialExperiences = {
'field-extract': 'image-parse',
} as const;
-/** 按 URL 组合独立体验页与公共侧栏。 */
+/** Compose the standalone experience page and the shared sidebar from the URL. */
export default function PlaygroundPage() {
const { toast } = useToast();
const { t } = useTranslation('playground');
@@ -58,19 +58,19 @@ export default function PlaygroundPage() {
const { experience: experienceParam } = useParams();
const collapsed = useAppStore((s) => s.playground.sidebarCollapsed);
const setPrefs = useAppStore((s) => s.setPlaygroundPrefs);
- // 移动端(<lg)侧栏转抽屉
+ // On mobile (<lg) the sidebar becomes a drawer.
const isMobile = !useBreakpoint('lg');
const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);
const [imageParseHistory, setImageParseHistory] = useState<PlaygroundSidebarHistory>();
const [imageParseWorkspaceKey, setImageParseWorkspaceKey] = useState(0);
- // 凭据按 URL 对应的体验类型独立回退:该类型免费额度用尽时立即改用用户自有 Key。
+ // Credentials fall back independently for the experience type in the URL: when that type’s free quota is used up, switch immediately to the user’s own key.
const credentialExperience =
playgroundCredentialExperiences[normalizeExperience(experienceParam)];
const model = usePlaygroundModel(credentialExperience);
const selectedModel = model.models.find((item) => item.id === model.modelId);
const attachmentCapabilities = selectedModel?.capabilities;
- // 思考展示、参数默认值与消息渲染遵从当前模型能力。
+ // Reasoning display, parameter defaults, and message rendering follow the current model’s capabilities.
const allowReasoning = allowsReasoning(
model.models.find((m) => m.id === model.modelId)?.capabilities,
);
@@ -91,7 +91,7 @@ export default function PlaygroundPage() {
const [input, setInput] = useState('');
const [settingsOpen, setSettingsOpen] = useState(false);
- // 引用来源面板:开合、内容归属、高亮定位统一由 useCitationPanel 编排
+ // Citation panel: open and close, which content it belongs to, and highlight positioning are all orchestrated by useCitationPanel.
const {
panel: citationPanel,
open: citationPanelOpen,
@@ -99,7 +99,7 @@ export default function PlaygroundPage() {
openPanel: openCitationPanel,
closePanel: closeCitationPanel,
} = useCitationPanel(chat.messages);
- // URL 保持入口;模型加载完成后,无权限的体验回退语言模型。
+ // The URL stays the entry; after models load, an experience the user cannot access falls back to language chat.
const hasTtsModels = model.ttsModels.length > 0;
const hasRealtimeModels = model.realtimeModels.length > 0;
const hasImageParseModels = model.imageParseModels.length > 0;
@@ -112,7 +112,7 @@ export default function PlaygroundPage() {
const isDocument = isDocumentExperience(experience);
const hasMessages = chat.messages.length > 0;
- // 可发送要求:已选模型 + 已选 Key + 明文密钥已就绪(避免密钥解密未完成就发起请求而失败)
+ // Send requires a selected model, a selected key, and a plaintext secret that is ready (so a request is not sent, and fails, before the secret finishes decrypting).
const canSend =
Boolean(model.modelId) && Boolean(model.keyId) && (params.webSearch || model.secretReady);
const sendDisabledReason = getSendDisabledReason(
@@ -130,11 +130,11 @@ export default function PlaygroundPage() {
t,
);
- // 历史恢复模型时由 resolveSelection 兜底;只依赖稳定的选择函数。
+ // Restoring a model from history is covered by resolveSelection; depend only on the stable selection function.
// eslint-disable-next-line react-hooks/exhaustive-deps
const restoreModel = useCallback((m: string) => model.selectModel(m), [model.selectModel]);
- // 历史对话持久化(列表/加载/自动保存/新建/删除)
+ // Chat history persistence (list, load, autosave, create, delete).
const conv = useConversationPersistence({
messages: chat.messages,
model: model.modelId,
@@ -145,7 +145,7 @@ export default function PlaygroundPage() {
onModelRestore: restoreModel,
});
- // 对话反馈编排:点赞静默上报,点踩弹框选原因后上报;本地高亮仍由 chat.setFeedback 持有
+ // Chat feedback: thumbs-up is reported quietly, thumbs-down opens a reason dialog and then reports; local highlight still lives in chat.setFeedback.
const feedback = useMessageFeedback({
messages: chat.messages,
model: model.modelId,
@@ -153,9 +153,9 @@ export default function PlaygroundPage() {
setLocalFeedback: chat.setFeedback,
});
- // 移动端:选会话/新建后自动收起抽屉
+ // Mobile: collapse the drawer after selecting a conversation or starting a new one.
const closeDrawer = useCallback(() => setMobileSidebarOpen(false), []);
- // 切换体验(语言/语音合成/实时音视频/图像解析):写入 URL 以便刷新保持;移动端顺带收起抽屉
+ // Switch experience (language, speech synthesis, realtime audio and video, image parse): write it into the URL so refresh keeps it; on mobile, also collapse the drawer.
const selectExperience = useCallback(
(key: ExperienceKey) => {
if (isDocumentExperience(key) && !hasImageParseModels) return;
@@ -177,19 +177,19 @@ export default function PlaygroundPage() {
const currentModelId = model.modelId;
const selectModel = model.selectModel;
const newChat = useCallback(() => {
- // 已是空白新对话(无消息且未落库)时,仅提示,避免"点了没反应"的困惑
+ // When it is already a blank new chat (no messages and not yet saved), only show a notice, so a click does not feel like it did nothing.
if (chat.messages.length === 0 && !conv.activeConversationId) {
toast({ title: t('currentNewConversation') });
closeDrawer();
return;
}
conv.newChat();
- setInput(''); // 顺带清空输入框,回到干净的新对话现场
+ setInput(''); // Also clear the input, back to a clean new-chat scene.
toast({ title: t('newConversationStarted') });
closeDrawer();
}, [chat.messages.length, closeDrawer, conv, t, toast]);
- // 用户主动切换不同模型时,模型上下文不能继续复用。旧会话保留在最近对话中,
- // 新模型从空白会话开始;历史会话恢复模型则继续使用 restoreModel,不经过这里。
+ // When the user switches to a different model on purpose, the model context cannot be reused. The old conversation stays in recent chats,
+ // and the new model starts from a blank conversation; restoring a model from a history conversation still uses restoreModel and does not pass through here.
const selectLanguageModel = useCallback(
(nextModelId: string) => {
if (
@@ -203,7 +203,7 @@ export default function PlaygroundPage() {
},
[chat.messages.length, conv, currentModelId, selectModel, t, toast],
);
- // 删除二次确认:destructive 弹窗确认后再真正删除,避免误删历史对话
+ // Delete confirmation: a destructive dialog confirms before the history conversation is actually deleted, so it is not removed by mistake.
const deleteSession = useCallback(
async (id: string) => {
const target = conv.sessions.find((s) => s.id === id);
@@ -283,7 +283,7 @@ export default function PlaygroundPage() {
);
}
- // 语言输入槽在欢迎态与对话态复用,避免重复装配 Composer 与密钥状态行。
+ // The language input slot is shared by the welcome state and the chat state, so Composer and the key-status row are not assembled twice.
const composer = (
<>
<ComposerSlot
@@ -303,7 +303,7 @@ export default function PlaygroundPage() {
</>
);
- // 语言模型体验主区:欢迎态(居中输入 + 任务卡)与对话态(消息流 + 底部输入)二选一
+ // Language-model main area: either the welcome state (centered input plus task cards) or the chat state (message stream plus input at the bottom).
function renderLanguage() {
return hasMessages ? (
<div className="flex h-full flex-col">
@@ -334,7 +334,7 @@ export default function PlaygroundPage() {
);
}
- // 主区按体验分发:语言模型渲染真功能对话区,其余体验各自独立页面
+ // The main area is dispatched by experience: language models render the real chat area, and the other experiences each have their own page.
function renderMain() {
if (isLanguage) return renderLanguage();
if (experience === 'tts') return <TtsExperience model={model} />;
@@ -388,7 +388,7 @@ export default function PlaygroundPage() {
onReset={reset}
/>
- {/* 点踩反馈弹窗:收集原因标签 + 可选正文后上报 */}
+ {/* Thumbs-down feedback dialog: collect a reason tag plus optional text, then report. */}
<FeedbackDialog
open={feedback.dialogOpen}
onOpenChange={feedback.setDialogOpen}
diff --git a/webdemo/frontend/src/pages/playground/types.ts b/webdemo/frontend/src/pages/playground/types.ts
index fdbdb4d..dda20c7 100644
--- a/webdemo/frontend/src/pages/playground/types.ts
+++ b/webdemo/frontend/src/pages/playground/types.ts
@@ -1,19 +1,19 @@
/**
- * 体验中心(Playground)本页类型集合。
+ * Types local to the Playground page.
*
- * 用途:集中声明对话消息、参数偏好、思考深度等本页专用类型,供 hooks / components 共享。
- * 与 SSE API 层(src/api/map/chat.ts)的 token usage 类型对齐。
+ * Purpose: chat messages, parameter preferences, reasoning depth, and other types used only on this page, shared by hooks and components.
+ * Aligned with the token usage types in the SSE API layer (src/api/map/chat.ts).
*/
import type { TokenUsage } from '@/api/map/chat';
-/** 对话消息角色 */
+/** Chat message role. */
export type ChatRole = 'system' | 'user' | 'assistant';
-/** i18n 翻译函数签名(与 react-i18next 的 t 函数兼容)。 */
+/** i18n translate function signature (compatible with react-i18next’s t). */
export type Translate = (key: string, options?: Record<string, unknown>) => string;
-/** 联网搜索过程阶段(仅用于当前回答的实时展示)。 */
+/** Web-search progress phase (live display for the current answer only). */
export type SearchProgressStep =
| 'searching'
| 'found'
@@ -22,12 +22,12 @@ export type SearchProgressStep =
| 'failed'
| 'browse_failed';
-/** 工具调用事件终态。 */
+/** Terminal state of a tool-call event. */
export type ToolEventStatus = 'running' | 'success' | 'failed' | 'interrupted';
/**
- * 一次工具调用的用户可见摘要。
- * 不保存原始 arguments、工具全文结果或内部凭据。
+ * A user-visible summary of one tool call.
+ * Raw arguments, the tool’s full result, and internal credentials are not stored.
*/
export interface ToolEvent {
eventId: string;
@@ -35,125 +35,125 @@ export interface ToolEvent {
tool: string;
status: ToolEventStatus;
queryCount?: number;
- /** 该工具实际使用的查询词,进行中的搜索行就地展示它。 */
+ /** The query this tool actually used; an in-progress search row shows it in place. */
queries?: string[];
resultCount?: number;
pageCount?: number;
durationMs?: number;
message?: string;
- /** 该工具涉及的来源地址(已归一化),用于在过程时间线上就地展示站点图标与页面标题。 */
+ /** Source addresses this tool touched (already normalized), shown in place on the progress timeline as a site icon and page title. */
citationUrls?: string[];
/**
- * 该工具首帧到达时已产出的思考字符数,作为思考文本的切分点。
- * 由前端在流式期间推导,后端不下发;历史消息与非流式回答没有该字段。
+ * Reasoning character count already produced when this tool’s first frame arrived, used as the split point in the reasoning text.
+ * Derived on the frontend during streaming; the backend does not send it. History messages and non-streaming answers do not have this field.
*/
reasoningOffset?: number;
}
-/** 附件模态:图像 / 视频 / 音频 / 文件(文档等) */
+/** Attachment modality: image, video, audio, or file (documents and similar). */
export type AttachmentKind = 'image' | 'video' | 'audio' | 'file';
/**
- * 用户随消息上传的附件。体验中心优先使用对象存储 URL,dataUrl 仅作为本地预览/兼容兜底。
- * 各模态发送时映射为不同的 OpenAI content-part(见 utils/attachments.ts)。
+ * An attachment the user uploaded with a message. The Playground prefers an object-storage URL; dataUrl is only a local preview or compatibility fallback.
+ * Each modality is mapped to a different OpenAI content part when sent (see utils/attachments.ts).
*/
export interface Attachment {
- /** 前端生成的唯一 id(用于 key / 移除) */
+ /** Unique id generated on the frontend (used as a key and for removal). */
id: string;
- /** 模态类别 */
+ /** Modality. */
kind: AttachmentKind;
- /** 原始文件名(file 模态透传给上游识别类型,其余用于展示) */
+ /** Original filename (passed through for the file modality so the upstream can recognize the type; other modalities use it for display). */
name: string;
- /** MIME 类型 */
+ /** MIME type. */
mime: string;
- /** 字节大小 */
+ /** Size in bytes. */
size: number;
/**
- * 本地预览地址。上传失败兜底使用 base64 data URL;云端 PDF 历史恢复时临时使用短时链接,
- * 保存前会被 fileId 引用替换,不持久化短时链接。
+ * Local preview URL. A failed upload falls back to a base64 data URL; restoring a cloud PDF from history uses a short-lived link temporarily,
+ * which is replaced by a fileId reference before save. The short-lived link is not persisted.
*/
dataUrl: string;
- /** 后端上传到对象存储后的访问 URL,发送给模型时优先使用 */
+ /** Access URL after the backend uploads to object storage; preferred when sending to the model. */
url?: string;
- /** 平台同源代理 URL,用于前端展示,避免 OBS 防盗链影响浏览器访问 */
+ /** Same-origin platform proxy URL, used for display so OBS hotlink protection does not block the browser. */
proxyUrl?: string;
- /** 平台公开签名代理 URL,供 LIS/模型按 URL 拉取附件 */
+ /** Public signed platform proxy URL, so LIS or the model can fetch the attachment by URL. */
publicUrl?: string;
- /** 对象存储 key,用于问题定位 */
+ /** Object-storage key, used when tracing a problem. */
objectKey?: string;
- /** file-upload 的业务文件 ID;发送前按当前登录用户重新签发模型读取链接 */
+ /** Business file id from file-upload; before send, a model read link is re-signed for the current logged-in user. */
fileId?: string;
}
/**
- * 单条对话消息。
- * assistant 消息在流式生成期间 `streaming=true`,正文增量并入 `content`、思考增量并入 `reasoning`。
+ * One chat message.
+ * While an assistant message is streaming, `streaming=true`; content deltas merge into `content` and reasoning deltas merge into `reasoning`.
*/
export interface ChatMessage {
- /** 消息唯一 id(前端生成) */
+ /** Unique message id (generated on the frontend). */
id: string;
role: ChatRole;
- /** 正文(markdown) */
+ /** Body (markdown). */
content: string;
- /** 用户随消息上传的附件(图像/视频/音频/文件;仅会话内,不持久化到历史) */
+ /** Attachments the user uploaded with the message (image, video, audio, or file; session only, not persisted to history). */
attachments?: Attachment[];
- /** 思考过程(reasoning,部分模型才有) */
+ /** Reasoning trace (only some models have it). */
reasoning?: string;
- /** 是否正在流式生成 */
+ /** Whether it is currently streaming. */
streaming?: boolean;
- /** 是否处于联网搜索阶段(开启联网后、首个正文到达前的客户端推断态) */
+ /** Whether it is in the web-search phase (a client-inferred state after web search is on and before the first body text arrives). */
searching?: boolean;
- /** 联网搜索工具状态文本 */
+ /** Web-search tool status text. */
searchStatus?: string;
- /** 联网搜索当前过程阶段 */
+ /** Current web-search progress phase. */
searchStep?: SearchProgressStep;
- /** 联网搜索已发现的来源数量 */
+ /** Number of sources web search has found. */
searchResultCount?: number;
- /** 当前正在执行或最近完成的联网工具。 */
+ /** The web tool currently running, or the one that finished most recently. */
searchActiveTool?: string;
- /** 网页读取工具本次准备浏览或成功浏览的页面数量。 */
+ /** How many pages the page-read tool is about to browse, or did browse, this time. */
searchBrowseCount?: number;
- /** 联网搜索实际使用的查询词,用于过程区展示。 */
+ /** Query web search actually used, shown in the progress area. */
searchQueries?: string[];
- /** 本轮联网过程中实际调用过的工具名称。 */
+ /** Tool names actually called during this turn’s web search. */
searchTools?: string[];
- /** 本轮工具调用的追加式事件摘要。 */
+ /** Append-only event summary of this turn’s tool calls. */
toolEvents?: ToolEvent[];
- /** 联网搜索引用来源(有则在回答下方展示) */
+ /** Web-search citation sources (shown under the answer when present). */
citations?: Citation[];
- /** 本轮 token 用量(尾块 usage) */
+ /** Token usage for this turn (usage on the tail chunk). */
usage?: TokenUsage;
- /** 本轮性能指标(前端计时:首 token 延迟、总耗时) */
+ /** Performance for this turn (frontend timing: time to first token, and total duration). */
metrics?: MessageMetrics;
- /** 当前选中回答版本对应的平台 L2 请求 ID */
+ /** Platform L2 request id for the currently selected answer version. */
requestId?: string;
- /** 本次 Playground 调用的客户端关联 ID,用于响应头不可读时精确反查平台请求 ID */
+ /** Client correlation id for this Playground call, used to look up the platform request id exactly when the response header cannot be read. */
clientRequestId?: string;
- /** 本次 Playground 调用实际使用的 API Key ID */
+ /** API key id actually used for this Playground call. */
apiKeyId?: string;
- /** 错误信息(生成失败时) */
+ /** Error message (when generation fails). */
error?: string;
- /** 上游错误码,用于区分内容安全拦截与普通请求失败 */
+ /** Upstream error code, used to tell a content-safety block from an ordinary request failure. */
errorCode?: string;
- /** 安审拦截的轮次仅保留展示与审计,不再参与任何后续模型上下文。 */
+ /** A turn blocked by content-safety review is kept only for display and audit, and no longer takes part in any later model context. */
contextExcluded?: boolean;
- /** 回答是否因页面刷新等客户端生命周期中断而不完整 */
+ /** Whether the answer is incomplete because a client lifecycle event, such as a page refresh, interrupted it. */
interrupted?: boolean;
- /** 上下文分隔线标记:渲染为横线;其上的历史不再作为上下文发送给模型(非新会话) */
+ /** Context divider: rendered as a horizontal rule; history above it is not sent to the model as context (this is not a new conversation). */
divider?: boolean;
- /** 反馈高亮(当前选中版本的点赞/点踩;会话保存时持久化,并上报 /feedback) */
+ /** Feedback highlight (thumbs-up or thumbs-down on the selected version; persisted when the conversation is saved, and reported to /feedback). */
feedback?: MessageFeedback;
/**
- * 多版本回答(「重新生成」保留旧版本,ChatGPT 式 ‹n/N›)。仅重新生成过的 assistant 轮次存在。
- * 不变式:顶层 content/reasoning/citations/usage/metrics/feedback 始终镜像 versions[activeVersion],
- * 使所有读顶层字段的逻辑(toRequestMessages/复制/渲染)无需感知多版本。
+ * Multi-version answers ("regenerate" keeps older versions, ChatGPT-style ‹n/N›). Present only on assistant turns that have been regenerated.
+ * Invariant: top-level content, reasoning, citations, usage, metrics, and feedback always mirror versions[activeVersion],
+ * so every reader of the top-level fields (toRequestMessages, copy, and render) does not need to know about multiple versions.
*/
versions?: AnswerVersion[];
- /** 当前选中版本索引(指向 versions;默认末位) */
+ /** Index of the selected version (into versions; defaults to the last one). */
activeVersion?: number;
}
-/** 单个回答版本快照(重新生成产生的一份完整回答)。 */
+/** Snapshot of one answer version (one complete answer produced by regenerate). */
export interface AnswerVersion {
content: string;
reasoning?: string;
@@ -164,110 +164,110 @@ export interface AnswerVersion {
searchBrowseCount?: number;
searchQueries?: string[];
searchTools?: string[];
- /** 该回答版本的工具调用事件摘要。 */
+ /** Tool-call event summary for this answer version. */
toolEvents?: ToolEvent[];
citations?: Citation[];
usage?: TokenUsage;
metrics?: MessageMetrics;
- /** 该回答版本对应的平台 L2 请求 ID */
+ /** Platform L2 request id for this answer version. */
requestId?: string;
- /** 该回答版本对应的客户端关联 ID */
+ /** Client correlation id for this answer version. */
clientRequestId?: string;
- /** 该回答版本实际使用的 API Key ID */
+ /** API key id actually used for this answer version. */
apiKeyId?: string;
error?: string;
- /** 该版本是否为中断后恢复的部分回答 */
+ /** Whether this version is a partial answer restored after an interruption. */
interrupted?: boolean;
- /** 反馈属于具体版本(不同版本可各自点赞/点踩) */
+ /** Feedback belongs to a specific version (each version can be liked or disliked on its own). */
feedback?: MessageFeedback;
}
-/** 助手消息反馈态:赞 / 踩。二者互斥,再次点击同一项即取消。 */
+/** Assistant feedback: up or down. They are mutually exclusive; clicking the same one again clears it. */
export type MessageFeedback = 'up' | 'down';
/**
- * 单轮生成的性能指标(前端计时,非后端字段)。
- * 流式下逐步填充:发起→首增量得 firstTokenMs,发起→完成得 durationMs。
+ * Performance for one generation turn (frontend timing, not a backend field).
+ * Filled in during streaming: request start to the first delta is firstTokenMs, and request start to completion is durationMs.
*/
export interface MessageMetrics {
- /** 首 token 延迟(ms):从发起到第一个正文/思考增量到达 */
+ /** Time to first token (ms): from send until the first body or reasoning delta arrives. */
firstTokenMs?: number;
- /** 总耗时(ms):从发起到本轮结束(含网络与生成) */
+ /** Total duration (ms): from send until this turn ends (including network and generation). */
durationMs?: number;
}
-/** 联网搜索引用来源(由响应的 url_citation annotations 归一化而来) */
+/** Web-search citation source (normalized from url_citation annotations on the response). */
export interface Citation {
/**
- * 后端分配的全局来源编号(1 起),跨轮稳定、与 URL 绑定。
+ * Global source number assigned by the backend (starting at 1), stable across turns and bound to the URL.
*
- * 角标数字必须取它而不是数组下标:后端每轮搜索都会按相关性重排结果,
- * 数组下标只在单轮搜索时碰巧与之相同,多轮时会静默指向无关网页。
- * 老后端不下发时才回退到数组下标(见 citationDisplayIndex)。
+ * The marker number must come from this, not from the array index: each search reorders results by relevance,
+ * and the array index only happens to match on a single search. Across multiple searches it would silently point at an unrelated page.
+ * Fall back to the array index only when an old backend does not send it (see citationDisplayIndex).
*/
ref?: number;
- /** 来源 URL */
+ /** Source URL. */
url: string;
- /** 来源标题(缺省时前端回退展示域名) */
+ /** Source title (the frontend falls back to the domain when it is missing). */
title?: string;
- /** 搜索结果或网页正文中提取的短摘要。 */
+ /** Short snippet extracted from the search result or the page body. */
snippet?: string;
}
-/** 思考深度(UI 档位):关闭 / 开启 */
+/** Reasoning depth (UI level): off or on. */
export type ThinkingDepth = 'off' | 'on';
/**
- * 思考参数风格:不同模型对「开启思考」的字段命名不一。
- * - `reasoning_effort`:OpenAI 风格枚举
- * - `thinking`:部分模型用 `{type:enabled|disabled}`
- * - `both`:两者都发,最大兼容
+ * Reasoning parameter style: models do not agree on the field name for "turn reasoning on".
+ * - `reasoning_effort`: OpenAI-style enum
+ * - `thinking`: some models use `{type:enabled|disabled}`
+ * - `both`: send both, for the widest compatibility
*/
export type ThinkingStyle = 'reasoning_effort' | 'thinking' | 'both';
-/** 思考开关字段格式;与是否附加 reasoning_effort 分开处理。 */
+/** Format of the reasoning switch field; handled separately from whether reasoning_effort is also attached. */
export type ThinkingControlFormat = 'chat_template_kwargs' | 'thinking' | 'both';
-/** 对话参数偏好(非敏感,可持久化到 store) */
+/** Chat parameter preferences (non-sensitive, safe to persist in the store). */
export interface PlaygroundParams {
- /** 采样温度 */
+ /** Sampling temperature. */
temperature?: number;
- /** 核采样 top_p */
+ /** Nucleus sampling top_p. */
topP?: number;
- /** 最大输出 token;未设置时不下发,显式 0 仍是有效值 */
+ /** Maximum output tokens; omitted when unset. An explicit 0 is still a valid value. */
maxTokens?: number;
- /** v4.7 图片压缩比例;仅用户显式选择时发送,否则沿用模型默认值 */
+ /** v4.7 image compression ratio; sent only when the user explicitly chooses it, otherwise the model default is kept. */
imageDownsampleMode?: '4x' | '16x';
- /** 思考深度档位 */
+ /** Reasoning depth level. */
thinkingDepth: ThinkingDepth;
- /** 思考参数风格 */
+ /** Reasoning parameter style. */
thinkingStyle: ThinkingStyle;
- /** 是否由体验中心显式发送思考参数;false 时交给模型 parameter_config 注入 */
+ /** Whether the Playground explicitly sends reasoning parameters; when false, the model’s parameter_config injects them. */
includeThinkingParams: boolean;
- /** 用户切换思考时应使用的模型协议字段 */
+ /** Model protocol field to use when the user toggles reasoning. */
thinkingControlFormat: ThinkingControlFormat;
- /** 当前模型的思考对象默认值,仅用于请求合并,不写入用户偏好 */
+ /** Default reasoning object for the current model, used only when merging the request, not written into user preferences. */
thinkingDefaults?: {
chat_template_kwargs?: Record<string, unknown>;
thinking?: Record<string, unknown>;
};
- /** 是否流式输出(true=SSE 逐字;false=一次性返回完整回复) */
+ /** Whether output is streamed (true = SSE token by token; false = the full reply is returned at once). */
stream: boolean;
- /** 是否开启联网搜索(开启时走 L3 Playground BFF) */
+ /** Whether web search is on (when on, the call goes through the L3 Playground BFF). */
webSearch: boolean;
/**
- * 本次联网请求启用的工具名称列表,三态语义与后端 enabledToolDefinitions 对齐:
- * `undefined`(不下发该字段)= 全部工具可用;空数组 = 全部禁用;具名列表 = 按名过滤。
+ * Tool names enabled for this web-search request. The three-state meaning matches backend enabledToolDefinitions:
+ * `undefined` (field omitted) = every tool is available; an empty array = all disabled; a named list = filter by name.
*
- * 默认必须是 `undefined` 而非 `[]`:用户没做过工具选择时,工具集应由后端当下的注册表决定。
- * 一旦在前端物化成显式列表存进偏好,后续新增的内置工具对老用户就永远不会生效。
+ * The default must be `undefined`, not `[]`: when the user has not chosen tools, the set should follow the backend registry as it is now.
+ * Once the frontend materializes an explicit list into preferences, a built-in tool added later never takes effect for existing users.
*/
enabledTools?: string[];
- /** 用户手动设置的当前位置(如"北京市"),用于 datetime 工具回答地点相关问题。 */
+ /** Location the user set manually (for example "Beijing"), used by the datetime tool for place-related questions. */
userLocation?: string;
}
-/** 参数默认值 */
+/** Parameter defaults. */
export const DEFAULT_PARAMS: PlaygroundParams = {
thinkingDepth: 'off',
thinkingStyle: 'both',
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/answerTimeline.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/answerTimeline.test.ts
index 5ecfa27..e5c3456 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/answerTimeline.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/answerTimeline.test.ts
@@ -1,5 +1,5 @@
/**
- * 过程时间线排序与取数纯函数单测:交错切段、两种退化、押后未播到的工具行、工具行取来源。
+ * Unit tests for process-timeline ordering and lookup pure functions: interleaved splits, two fallbacks, tool rows held back until played, and tool-row source lookup.
*/
import { describe, expect, it } from 'vitest';
@@ -21,7 +21,7 @@ function event(patch: Partial<ToolEvent> & { eventId: string }): ToolEvent {
};
}
-/** 把时间线压成 'reasoning:文本' / 'tool:eventId' 的串,便于整体断言顺序。 */
+/** Compress the timeline into 'reasoning:text' / 'tool:eventId' strings so the overall order can be asserted. */
function outline(items: ProcessTimelineItem[]): string[] {
return items.map((item) =>
item.kind === 'reasoning' ? `reasoning:${item.text}` : `tool:${item.id}`,
@@ -70,7 +70,7 @@ describe('buildProcessTimeline', () => {
reasoning: '很短',
toolEvents: [
event({ eventId: 'a', reasoningOffset: 999 }),
- // 回退的 offset(理论上不该出现)不能让游标倒回去重放前面的思考
+ // A fallback offset (which should not occur in theory) must not move the cursor backward and replay earlier reasoning
event({ eventId: 'b', reasoningOffset: 0 }),
],
});
@@ -121,7 +121,7 @@ describe('buildProcessTimeline', () => {
event({ eventId: 'b', step: 2, reasoningOffset: 11 }),
];
- // 已显示 8 个字:第一行该出了,第二行的切点还没播到
+ // 8 characters are displayed: the first row should appear, and the second row's split point has not been played yet
const playing = buildProcessTimeline({
reasoning: '先搜一下。再看看',
toolEvents,
@@ -129,7 +129,7 @@ describe('buildProcessTimeline', () => {
});
expect(outline(playing.items)).toEqual(['reasoning:先搜一下。', 'tool:a', 'reasoning:再看看']);
- // 播到了,第二行随之出现
+ // It has been played, and the second row appears with it
const played = buildProcessTimeline({
reasoning: '先搜一下。再看看几页。',
toolEvents,
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/attachments.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/attachments.test.ts
index 1a3a96e..ed0a117 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/attachments.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/attachments.test.ts
@@ -1,5 +1,5 @@
/**
- * attachments 工具单测:模态识别 + content-part 映射 + 大小格式化。
+ * Unit tests for the attachments helpers: modality recognition + content-part mapping + size formatting.
*/
import { describe, it, expect, vi } from 'vitest';
@@ -242,7 +242,7 @@ describe('readFileAsAttachment cancellation', () => {
});
});
-/** 构造测试用附件 */
+/** Build a test attachment */
function att(overrides: Partial<Attachment>): Attachment {
return {
id: 'a',
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/chatCompletion.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/chatCompletion.test.ts
index 87a6da8..acbe8f1 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/chatCompletion.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/chatCompletion.test.ts
@@ -1,6 +1,6 @@
/**
- * chatCompletion 纯函数单测:auth 校验与 finish/abort/fail 收尾策略,
- * 以及同属一次补全生命周期的流式 SSE 回调(chatStreamCallbacks)。
+ * Unit tests for chatCompletion pure functions: auth checks and finish/abort/fail finalization,
+ * plus the streaming SSE callbacks that belong to the same completion lifecycle (chatStreamCallbacks).
*/
import type { SetStateAction } from 'react';
@@ -99,7 +99,7 @@ describe('createStreamCallbacks', () => {
vi.useRealTimers();
});
- /** 测试用翻译桩:回显 key,避免断言依赖具体译文。 */
+ /** Test translation stub: echo the key so assertions do not depend on a specific translation. */
const translate = (key: string) => key;
it('保留联网搜索真实查询词供过程区展示', () => {
@@ -156,7 +156,7 @@ describe('createStreamCallbacks', () => {
it('开了联网但模型没调工具时,正文一到就收掉 searching', () => {
vi.useFakeTimers();
- // useChat 的占位消息在开启联网时就是 searching: true,这里复现那一帧
+ // useChat's placeholder message is searching: true when web search is on; reproduce that frame here
let messages = [assistant('assistant-1', { searching: true })];
const setMessages = vi.fn((update: SetStateAction<ChatMessage[]>) => {
messages = typeof update === 'function' ? update(messages) : update;
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/chatStatus.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/chatStatus.test.ts
index 951aca3..e0862b6 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/chatStatus.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/chatStatus.test.ts
@@ -1,12 +1,12 @@
/**
- * chatStatus 纯函数单测。
+ * Unit tests for chatStatus pure functions.
*/
import { describe, it, expect } from 'vitest';
import { toolStatusStep, toolStatusText } from '../chatStatus';
import type { Translate } from '../../types';
-/** 测试用翻译桩:回显 key 与插值,断言走的是 i18n 而非硬编码中文。 */
+/** Test translation stub: echo the key and interpolations, asserting the path is i18n rather than hardcoded Chinese. */
const t: Translate = (key, options) =>
options?.count === undefined ? key : `${key}:${String(options.count)}`;
@@ -42,9 +42,9 @@ describe('toolStatusText', () => {
'found',
);
expect(toolStatusStep({ tool: 'web_extractor', status: 'running' })).toBe('reading');
- // 搜索失败:整个过程条标红
+ // Search failed: the whole process bar turns red
expect(toolStatusStep({ tool: 'web_search', status: 'failed' })).toBe('failed');
- // 读网页失败:只让读取步骤标红,不让"搜索"被误判为失败
+ // Page read failed: only the read step turns red, so "search" is not misjudged as failed
expect(toolStatusStep({ tool: 'web_extractor', status: 'failed' })).toBe('browse_failed');
expect(toolStatusStep({ tool: 'web_search', status: 'failed', urls: ['https://x'] })).toBe(
'browse_failed',
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/citationMarkers.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/citationMarkers.test.ts
index 37db624..03d093e 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/citationMarkers.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/citationMarkers.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest';
import { linkifyCitationMarkers } from '../citationMarkers';
import type { Citation } from '../../types';
-/** 两条来源:下标 +1 即角标编号。 */
+/** Two sources: index + 1 is the citation-marker number. */
const citations: Citation[] = [
{ url: 'https://one.example.com/a', title: '来源一' },
{ url: 'https://two.example.com/b', title: '来源二' },
@@ -83,7 +83,7 @@ describe('linkifyCitationMarkers', () => {
expect(linkifyCitationMarkers('结论[ref_7]。', withRefs)).toBe(
'结论[7](https://two.example.com/b)。',
);
- // 裸角标是兜底路径:模型不听话时同样按编号查,而不是按数组下标。
+ // A bare citation marker is the fallback path: when the model does not follow instructions, look it up by number rather than by array index.
expect(linkifyCitationMarkers('结论[4]。', withRefs)).toBe(
'结论[4](https://one.example.com/a)。',
);
@@ -94,8 +94,8 @@ describe('linkifyCitationMarkers', () => {
{ ref: 4, url: 'https://one.example.com/a', title: '来源一' },
{ ref: 7, url: 'https://two.example.com/b', title: '来源二' },
];
- // [1] 在旧口径下会指向数组第一条;有 ref 之后它是个无效编号,必须原样留着——
- // 回退数组下标恰好会把无效角标指到一条无关来源上,那正是本次改动要消灭的缺陷。
+ // Under the old rule, [1] pointed at the first array item; once a ref exists it is an invalid number and must be left as-is —
+ // falling back to the array index would point that invalid marker at an unrelated source, which is the defect this change removes.
expect(linkifyCitationMarkers('结论[1]。', withRefs)).toBe('结论[1]。');
expect(linkifyCitationMarkers('结论[ref_9]。', withRefs)).toBe('结论[ref_9]。');
});
@@ -109,13 +109,13 @@ describe('linkifyCitationMarkers', () => {
});
it('英文正文里紧跟单词的 [ref_N] 仍是引用', () => {
- // 提示词要求角标紧跟论断,英文下必然写成 blue[ref_1]。下标判据若对带 ref_ 的角标
- // 也一刀切,英文回答的角标会被整批当成 arr[1] 吞掉。
+ // The prompt requires the citation marker to follow the claim, so English necessarily writes blue[ref_1]. If the index heuristic also
+ // cuts markers that contain ref_, every citation marker in an English answer would be swallowed as arr[1].
const withRefs: Citation[] = [{ ref: 1, url: 'https://a.example', title: 'A' }];
expect(linkifyCitationMarkers('The sky is blue[ref_1].', withRefs)).toBe(
'The sky is blue[1](https://a.example).',
);
- // 裸角标没有前缀消歧,紧跟标识符时仍按下标取值处理。
+ // A bare citation marker has no prefix to disambiguate it; when it immediately follows an identifier it is still treated as an index lookup.
expect(linkifyCitationMarkers('arr[1] 取值', withRefs)).toBe('arr[1] 取值');
});
@@ -130,7 +130,7 @@ describe('linkifyCitationMarkers', () => {
});
it('一个方括号里合写的多个编号全部展开', () => {
- // 提示词只要求角标紧跟论断,没规定一处只能引一条来源,模型把多来源合写是常态。
+ // The prompt only requires the marker to follow the claim; it does not limit a claim to one source, so the model often writes several sources together.
const withRefs: Citation[] = [
{ ref: 3, url: 'https://one.example.com/a', title: '来源一' },
{ ref: 5, url: 'https://two.example.com/b', title: '来源二' },
@@ -138,14 +138,14 @@ describe('linkifyCitationMarkers', () => {
expect(linkifyCitationMarkers('打造模型库[ref_3, ref_5]。', withRefs)).toBe(
'打造模型库[3](https://one.example.com/a)[5](https://two.example.com/b)。',
);
- // 裸角标合写同理,中文顿号也是模型常用的分隔符。
+ // Grouped bare markers work the same way; the Chinese enumeration comma is also a separator the model commonly uses.
expect(linkifyCitationMarkers('打造模型库[3、5]。', withRefs)).toBe(
'打造模型库[3](https://one.example.com/a)[5](https://two.example.com/b)。',
);
});
it('合写角标里有编号查不到来源时整体保持原文', () => {
- // 半改写会留下「一个链接 + 一截裸文本」,读者无从判断后半截是没搜到还是渲染坏了。
+ // A partial rewrite leaves "one link + a trailing bare text fragment", and the reader cannot tell whether the trailing part was not found or failed to render.
const withRefs: Citation[] = [{ ref: 3, url: 'https://one.example.com/a', title: '来源一' }];
expect(linkifyCitationMarkers('打造模型库[ref_3, ref_9]。', withRefs)).toBe(
'打造模型库[ref_3, ref_9]。',
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/conversationDraft.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/conversationDraft.test.ts
index 32450db..cb8a5dd 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/conversationDraft.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/conversationDraft.test.ts
@@ -1,5 +1,5 @@
/**
- * conversationDraft 单测:有效期、损坏数据清理与敏感字段剥离。
+ * Unit tests for conversationDraft: expiry, cleanup of corrupt data, and stripping of sensitive fields.
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/conversations.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/conversations.test.ts
index 632a338..89a8252 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/conversations.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/conversations.test.ts
@@ -1,5 +1,5 @@
/**
- * conversations 映射纯函数单测:stored↔ChatMessage 互转 + 签名。
+ * Unit tests for conversations mapping pure functions: stored↔ChatMessage conversion + signatures.
*/
import { describe, it, expect } from 'vitest';
@@ -244,8 +244,8 @@ describe('chatMessagesToSavePayload', () => {
streaming: false,
usage: { prompt_tokens: 1, completion_tokens: 2, total_tokens: 3 },
},
- { id: '3', role: 'assistant', content: '', streaming: true }, // 空占位,跳过
- { id: '4', role: 'assistant', content: 'x', error: '失败' }, // 错误,跳过
+ { id: '3', role: 'assistant', content: '', streaming: true }, // Empty placeholder, skip
+ { id: '4', role: 'assistant', content: 'x', error: '失败' }, // Error, skip
];
const payload = chatMessagesToSavePayload(messages, '标题', 'gpt');
expect(payload.title).toBe('标题');
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/experienceRoute.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/experienceRoute.test.ts
index 3389e9a..08e332d 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/experienceRoute.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/experienceRoute.test.ts
@@ -1,5 +1,5 @@
/**
- * 体验中心 URL 路由单测:合法体验键、加载期不回退、无可见模型时回退。
+ * Unit tests for experience-center URL routing: valid experience keys, no fallback while loading, fallback when no model is visible.
*/
import { describe, expect, it } from 'vitest';
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/fixtures/imageParseConstantsTable.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/fixtures/imageParseConstantsTable.ts
index 75e693d..0b59a8a 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/fixtures/imageParseConstantsTable.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/fixtures/imageParseConstantsTable.ts
@@ -1,4 +1,4 @@
-/** 用户提供的合并单元格与物理常数公式表格,供编辑和预览回归共用。 */
+/** User-provided merged-cell and physical-constants formula table, shared by editor and preview regression tests. */
export const IMAGE_PARSE_CONSTANTS_TABLE = String.raw`<table><tr><td rowspan="2">名称</td><td rowspan="2">符号</td><td rowspan="2">数值</td><td colspan="2">单位</td></tr>
<tr><td>SI</td><td>(厘米克秒)单位系</td></tr>
<tr><td>中子的康普顿波长</td><td>$\lambda ca=h/m_{a}c$</td><td>1.319 590 9</td><td>$10^{-15}$</td><td>$10^{-13}cm$</td></tr>
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/imageGroupPdf.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/imageGroupPdf.test.ts
index 11072f6..4dbb75b 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/imageGroupPdf.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/imageGroupPdf.test.ts
@@ -27,7 +27,7 @@ describe('pdfFromJpegs', () => {
expect(text.startsWith('%PDF-1.4')).toBe(true);
expect(text).toContain('/Count 2');
- // 预览按 2 倍渲染,页面尺寸取像素的一半。
+ // Preview renders at 2x; page size is half the pixel dimensions.
expect(text).toContain('/MediaBox [0 0 500 1000]');
expect(text).toContain('/MediaBox [0 0 400 300]');
expect(text).toContain('/DCTDecode');
@@ -128,7 +128,7 @@ describe('prepareDocumentFiles', () => {
expect(result.file.type).toBe('application/pdf');
expect(result.file.name).toBe('1 等2张.pdf');
expect(context.drawImage).toHaveBeenCalledTimes(2);
- // 长边超过上限时按比例缩小。
+ // When the long edge exceeds the limit, scale down proportionally.
expect(context.drawImage).toHaveBeenCalledWith(bitmap, 0, 0, 2000, 1333);
expect(close).toHaveBeenCalledTimes(2);
});
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/imageParse.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/imageParse.test.ts
index 0390d84..80a4d05 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/imageParse.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/imageParse.test.ts
@@ -1,5 +1,5 @@
/**
- * 图像解析契约单测:系统提示词与 Chat Completions 请求装配。
+ * Contract unit tests for image parsing: system prompt and Chat Completions request assembly.
*/
import { describe, expect, it } from 'vitest';
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/imageParseClipboard.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/imageParseClipboard.test.ts
index e2e369e..fe36e25 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/imageParseClipboard.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/imageParseClipboard.test.ts
@@ -1,6 +1,6 @@
/**
- * 表格复制单测:必须同时写入 HTML 与 TSV ——
- * 飞书、Word 靠 HTML 还原成表格,Excel 靠 TSV 分列;两者缺一都会退化成纯文本。
+ * Unit tests for table copy: HTML and TSV must both be written —
+ * Feishu and Word restore a table from HTML, Excel splits columns from TSV; missing either one degrades to plain text.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/imageParseQuality.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/imageParseQuality.test.ts
index 8736b91..928e1ac 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/imageParseQuality.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/imageParseQuality.test.ts
@@ -47,7 +47,7 @@ describe('原文档框色分级(第一期临时阈值)', () => {
});
it('框色分级与待审核筛选阈值相互独立', () => {
- // 0.8 及以上的块不进入待审核,但框色要到 99% 才转绿。
+ // Blocks at 0.8 or above do not enter review, but the box turns green only at 99%.
expect(imageParseConfidenceLevel(0.8)).toBe('low');
expect(imageParseConfidenceLevel(0.98)).toBe('low');
expect(imageParseConfidenceLevel(0.99)).toBe('high');
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/imageParseSampleFixtures.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/imageParseSampleFixtures.ts
index 5b27092..2c7824f 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/imageParseSampleFixtures.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/imageParseSampleFixtures.ts
@@ -1,18 +1,18 @@
import type { ImageParseLayoutBlock } from '../imageParseSample';
/**
- * 图像解析单元测试固定数据。
+ * Fixed data for image-parsing unit tests.
*
- * 用途:仅给单元测试提供稳定版面块与 Markdown,Playground 运行时不得引用。
+ * Purpose: provide stable layout blocks and Markdown for unit tests only. The Playground runtime must not import this.
*
- * 固定数据不经过模型,也不代表线上识别结果。
+ * The fixed data does not go through a model and does not represent online recognition results.
*
*/
-/** 样例图原始像素尺寸,版面框按此归一化。 */
+/** Original pixel size of the sample image; layout boxes are normalized against it. */
export const IMAGE_PARSE_SAMPLE_SIZE = { width: 2640, height: 3720 } as const;
/**
- * 样例图的 16 个版面块,按阅读顺序排列——检出动画依赖这个顺序自上而下推进。
+ * The sample image's 16 layout blocks, in reading order — the detection animation advances top to bottom in this order.
*/
export const IMAGE_PARSE_SAMPLE_BLOCKS: readonly ImageParseLayoutBlock[] = [
{
@@ -193,11 +193,11 @@ export const IMAGE_PARSE_SAMPLE_BLOCKS: readonly ImageParseLayoutBlock[] = [
];
/**
- * 把块的 Markdown 片段拼成整篇结果。
+ * Join block Markdown fragments into a full result.
*
- * 连续的列表项之间只留一个换行,其余块之间留空行:判据取 Markdown 自身的 `- ` 前缀,
- * 而不是块的 kind——会议纪要四条在版面上是 text 块,在文档里却是同一个列表。
- * @param blocks 按阅读顺序排列的版面块
+ * Consecutive list items are separated by a single newline; other blocks get a blank line. The criterion is the Markdown `- ` prefix itself,
+ * not the block's kind — the four meeting-notes items are text blocks on the layout, but one list in the document.
+ * @param blocks layout blocks in reading order
*/
function joinBlockMarkdown(blocks: readonly ImageParseLayoutBlock[]): string {
const body = blocks
@@ -211,5 +211,5 @@ function joinBlockMarkdown(blocks: readonly ImageParseLayoutBlock[]): string {
return `${body}\n`;
}
-/** 与样例图内容对齐的 Markdown,用来预览结果栏而不是空白空态。 */
+/** Markdown aligned with the sample image, used to preview the result column instead of a blank empty state. */
export const IMAGE_PARSE_SAMPLE_MARKDOWN = joinBlockMarkdown(IMAGE_PARSE_SAMPLE_BLOCKS);
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/imageParseScrollAnchors.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/imageParseScrollAnchors.test.ts
index 254dead..f656122 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/imageParseScrollAnchors.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/imageParseScrollAnchors.test.ts
@@ -125,7 +125,7 @@ describe('imageParseScrollAnchors', () => {
const mapped = imageParseMappedProgress(anchors, progress, 'result');
expect(imageParseMappedProgress(anchors, mapped, 'origin')).toBeCloseTo(progress);
}
- // 离屏 canvas 卸载或标准模式没有版面块时,仍以当前页骨架限定范围。
+ // When an offscreen canvas unmounts, or standard mode has no layout blocks, the current page skeleton still bounds the range.
canvas.remove();
const unrendered = imageParseScrollAnchors(origin, result, [], 0);
expect(imageParseMappedProgress(unrendered, 0, 'result')).toBeCloseTo(start);
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/imageZoom.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/imageZoom.test.ts
index ae0a7d3..1419bad 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/imageZoom.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/imageZoom.test.ts
@@ -1,5 +1,5 @@
/**
- * 图片视图几何单测:光标锚点缩放、平移夹紧、旋转贴合、transform 拼装顺序。
+ * Unit tests for image-view geometry: cursor-anchored zoom, pan clamping, rotation fit, and transform composition order.
*/
import { describe, expect, it } from 'vitest';
@@ -28,7 +28,7 @@ import {
type ImageZoomView,
} from '../imageZoom';
-/** 800×600 视口里放一张 800×600 的图,scale=1 正好铺满。 */
+/** An 800×600 image in an 800×600 viewport; scale=1 fills it exactly. */
const VIEWPORT = { width: 800, height: 600 };
const CONTENT = { width: 800, height: 600 };
@@ -127,10 +127,10 @@ describe('bounded document reading', () => {
describe('scaleTo', () => {
it('keeps the cursor anchor fixed while zooming', () => {
- // 锚点相对视口中心 (100, 50),放大到 2 倍后该点在屏幕上不该移动。
+ // The anchor is (100, 50) relative to the viewport center; after zooming to 2x that point should not move on screen.
const anchor = { x: 100, y: 50 };
const next = scaleTo(INITIAL_VIEW, 2, anchor);
- // 锚点的屏幕位置 = offset + scale * 内容坐标;内容坐标在缩放前后相同。
+ // Screen position of the anchor = offset + scale * content coordinates; content coordinates stay the same across the zoom.
const before = (anchor.x - INITIAL_VIEW.offset.x) / INITIAL_VIEW.scale;
const after = (anchor.x - next.offset.x) / next.scale;
expect(after).toBeCloseTo(before, 6);
@@ -143,7 +143,7 @@ describe('scaleTo', () => {
const anchor = { x: 10, y: 10 };
const back = scaleTo(zoomed, 0.1, anchor);
expect(back.scale).toBe(MIN_SCALE);
- // 缩小时不把平移归零:拖到一边的图应停在原处,只是锚点跟着换算。
+ // Do not zero the pan when zooming out: an image dragged to one side should stay there, with only the anchor recomputed.
expect(back.offset.x).toBeCloseTo(12.5, 6);
expect((anchor.x - back.offset.x) / back.scale).toBeCloseTo(
(anchor.x - zoomed.offset.x) / zoomed.scale,
@@ -180,7 +180,7 @@ describe('buttonScale', () => {
describe('viewBounds / clampView', () => {
it('lets a fitting image be dragged aside, keeping 48px on screen', () => {
- // 贴合状态下也有余量:(视口 + 包围盒) / 2 - 48,所以「按住拖不动」不会再发生。
+ // There is still slack in the fitted state: (viewport + bounding box) / 2 - 48, so holding and being unable to drag no longer happens.
expect(viewBounds(INITIAL_VIEW, VIEWPORT, CONTENT)).toEqual({ x: 752, y: 552 });
const dragged = clampView(panBy(INITIAL_VIEW, 120, -80), VIEWPORT, CONTENT);
expect(dragged.offset).toEqual({ x: 120, y: -80 });
@@ -194,14 +194,14 @@ describe('viewBounds / clampView', () => {
});
it('keeps a dragged-aside image in place when zooming in', () => {
- // 「拖到一边再放大盯着看」是核对常规动作,缩放不该把偏移吃掉。
+ // Drag aside, then zoom in to inspect, is a normal check; zoom must not eat the offset.
const dragged = view({ offset: { x: 300, y: -200 } });
const zoomed = clampView(scaleTo(dragged, 2, null), VIEWPORT, CONTENT);
expect(zoomed.offset).toEqual({ x: 300, y: -200 });
});
it('swaps width and height on a quarter turn', () => {
- // 竖图 600×800 转 90°,包围盒变 800×600,余量与横图贴合时一致。
+ // A portrait 600×800 image rotated 90° has an 800×600 bounding box, with the same slack as a landscape image when fitted.
const bounds = viewBounds(view({ rotation: 90 }), VIEWPORT, { width: 600, height: 800 });
expect(bounds).toEqual({ x: 752, y: 552 });
});
@@ -219,7 +219,7 @@ describe('fitFactor', () => {
});
it('shrinks a landscape image so a quarter turn still fits', () => {
- // 800×600 的图转 90° 后占 600×800,高度超出 600,需要缩到 0.75。
+ // An 800×600 image rotated 90° occupies 600×800; the height exceeds 600 and must scale to 0.75.
expect(fitFactor(90, VIEWPORT, CONTENT)).toBeCloseTo(0.75, 6);
expect(fitFactor(270, VIEWPORT, CONTENT)).toBeCloseTo(0.75, 6);
});
@@ -270,7 +270,7 @@ describe('rotateView / resetZoom / isTransformed', () => {
expect(isTransformed(INITIAL_VIEW)).toBe(false);
expect(isTransformed(view({ rotation: 90 }))).toBe(true);
expect(isTransformed(view({ offset: { x: 1, y: 0 } }))).toBe(true);
- // 缩到贴合以下也算动过,否则「还原」按钮会在缩小状态下变灰。
+ // Scaling below the fit also counts as moved; otherwise the reset button would grey out while zoomed out.
expect(isTransformed(view({ scale: MIN_SCALE }))).toBe(true);
});
});
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/markdownTable.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/markdownTable.test.ts
index 54e2afd..b1cc55b 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/markdownTable.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/markdownTable.test.ts
@@ -1,5 +1,5 @@
/**
- * Markdown 表格抽取单测:只认规范 GFM 表,宁可漏也不误判公式与代码。
+ * Unit tests for Markdown table extraction: only well-formed GFM tables count; prefer a miss over mistaking formulas and code for tables.
*/
import { describe, expect, it } from 'vitest';
@@ -32,7 +32,7 @@ describe('extractMarkdownTables', () => {
});
it('ignores pipe-bearing lines without a delimiter row', () => {
- // LaTeX 的绝对值、代码里的管道都带 `|`,误判成表格会把公式拆碎。
+ // LaTeX absolute values and pipes inside code both contain `|`; treating them as a table would shatter the formula.
expect(extractMarkdownTables('$$ \\| x \\|_2 $$\ncat a | grep b')).toEqual([]);
});
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/math.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/math.test.ts
index 930aab4..063edee 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/math.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/math.test.ts
@@ -1,5 +1,5 @@
/**
- * normalizeMathDelimiters 单测:LaTeX 定界符转换 + 代码区保护。
+ * Unit tests for normalizeMathDelimiters: LaTeX delimiter conversion + code-region protection.
*/
import { describe, it, expect } from 'vitest';
@@ -291,7 +291,7 @@ describe('normalizeMathDelimiters', () => {
'mode = production',
'2026-08-13',
'20:30:15',
- // 模型把工具调用当正文输出的残片:曾被 `=`/`>`/`_` 误判成公式并渲染成衬线数学体。
+ // A fragment of the model emitting a tool call as body text: it used to be misread as a formula by `=` / `>` / `_` and rendered as serif math.
' name="weather_search"> name="location">Beijing',
'name="location"',
"name='location'",
@@ -300,7 +300,7 @@ describe('normalizeMathDelimiters', () => {
expect(normalizeMathDelimiters(content)).toBe(content);
});
- // 这些行里的 `-`/`*`/`=` 曾被当成运算符,KaTeX 又能解析成功,分割线于是渲染成一串衬线减号。
+ // The `-` / `*` / `=` in these lines used to be treated as operators, and KaTeX could parse them, so a thematic break was rendered as a string of serif minus signs.
it.each(['---', '----', '***', '___', '- - -', '* * *', '===', '**', '+', '>'])(
'Markdown 标记行保持原样:%s',
(line) => {
@@ -315,9 +315,9 @@ describe('normalizeMathDelimiters', () => {
});
/*
- 联网搜索的引用角标曾被整类渲染成公式:`_` 命中下标特征,`ref` 只有三个字母、过得了
- 「标识符都很短」这道判据,KaTeX 又能把 ref_1 解析成功,于是 wrapBracketedMath 把方括号
- 当成公式定界符吃掉——正文里角标消失,只剩一串斜体下标。
+ Web-search citation markers used to be rendered as formulas as a class: `_` hits the subscript feature, `ref` is only three letters and passes
+ the "identifiers are all short" check, and KaTeX can parse ref_1, so wrapBracketedMath eats the brackets
+ as formula delimiters — the marker disappears from the body and only a run of italic subscripts remains.
*/
it.each(['[ref_1]', '[ref_12]', '[ref_3, ref_5]', '[ref_3,ref_5]', '[ref_1; ref_2]'])(
'联网搜索引用角标不被当成公式:%s',
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/messageVersions.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/messageVersions.test.ts
index 481966a..990482b 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/messageVersions.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/messageVersions.test.ts
@@ -1,5 +1,5 @@
/**
- * messageVersions 纯函数单测:regenerate 上下文、准备态、反馈切换、版本翻页。
+ * Unit tests for messageVersions pure functions: regenerate context, preparing state, feedback toggle, and version paging.
*/
import { describe, it, expect } from 'vitest';
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/messages.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/messages.test.ts
index 5bbc599..932885a 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/messages.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/messages.test.ts
@@ -1,5 +1,5 @@
/**
- * toRequestMessages 单测:多模态附件消息构造 + 占位过滤。
+ * Unit tests for toRequestMessages: multimodal attachment message construction + placeholder filtering.
*/
import { describe, it, expect } from 'vitest';
@@ -12,7 +12,7 @@ import {
findQAPair,
} from '../messages';
-/** 构造测试用附件 */
+/** Build a test attachment */
function att(kind: Attachment['kind'], overrides: Partial<Attachment> = {}): Attachment {
return {
id: `a-${kind}`,
@@ -191,7 +191,7 @@ describe('mergeCitations', () => {
});
it('有后端编号时以编号为身份,并按编号升序排列', () => {
- // 第二轮搜索先回了编号更大的那条:数组顺序若照到达顺序排,来源面板会读成 2、1。
+ // The second search returned the item with the larger number first: if array order followed arrival order, the source panel would read as 2, then 1.
const merged = mergeCitations(
[{ ref: 1, url: 'https://a.com', title: 'A' }],
[
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/metrics.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/metrics.test.ts
index 8a46575..c7b7b31 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/metrics.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/metrics.test.ts
@@ -1,5 +1,5 @@
/**
- * metrics 派生纯函数单测:速率扣除首 token 延迟、指标项按数据存在与否纳入。
+ * Unit tests for metrics derived pure functions: rate excludes time-to-first-token, and metric items are included only when data exists.
*/
import { describe, it, expect } from 'vitest';
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/params.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/params.test.ts
index 162ee02..eed3d8d 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/params.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/params.test.ts
@@ -1,5 +1,5 @@
/**
- * params 映射纯函数单测:思考字段开关需真实下发,采样参数需透传。
+ * Unit tests for params mapping pure functions: reasoning-field switches must actually be sent, and sampling parameters must be passed through.
*/
import { describe, it, expect } from 'vitest';
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/pcmStream.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/pcmStream.test.ts
index c8b7f92..3aa2a8d 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/pcmStream.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/pcmStream.test.ts
@@ -1,6 +1,6 @@
/**
- * pcmStream 纯函数单测:float32 编解码需无损往返(无 Int16 量化),线性重采样长度/端点正确,
- * 非 4 字节对齐的 base64 尾部安全丢弃。AudioContext 相关类依赖浏览器音频栈,此处不覆盖。
+ * Unit tests for pcmStream pure functions: float32 encode/decode must round-trip losslessly (no Int16 quantization), linear resampling length/endpoints must be correct,
+ * and a base64 tail that is not 4-byte aligned is safely dropped. AudioContext-related classes depend on the browser audio stack and are not covered here.
*/
import { describe, expect, it, vi } from 'vitest';
@@ -45,7 +45,7 @@ describe('float32ToBase64 ↔ base64ToFloat32', () => {
describe('base64ToFloat32 对齐', () => {
it('非 4 字节对齐时丢弃尾部字节', () => {
- // 6 字节:前 4 字节 = float32 1.0(小端 00 00 80 3F),尾部 2 字节丢弃
+ // 6 bytes: the first 4 bytes = float32 1.0 (little-endian 00 00 80 3F); the trailing 2 bytes are dropped
const b64 = btoa(String.fromCharCode(0, 0, 128, 63, 1, 2));
const out = base64ToFloat32(b64);
expect(out.length).toBe(1);
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/realtimeProtocol.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/realtimeProtocol.test.ts
index cfcd673..c68becd 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/realtimeProtocol.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/realtimeProtocol.test.ts
@@ -1,6 +1,6 @@
/**
- * realtimeProtocol 纯函数单测:帧构造需符合 MiniCPM-O API V2 线协议,
- * 下行事件归一化需按 type/kind 正确分流,未知/损坏帧安全降级为 other。
+ * Unit tests for realtimeProtocol pure functions: frame construction must match the MiniCPM-O API V2 wire protocol,
+ * downlink event normalization must branch correctly by type/kind, and unknown or corrupt frames safely degrade to other.
*/
import { describe, it, expect } from 'vitest';
@@ -216,7 +216,7 @@ describe('挂断标记约定', () => {
});
it('模型不输出标记时靠告别语兜底(实测 MiniCPM-o 只说自然语言)', () => {
- // 这几句都是实测出现过的真实回复
+ // These sentences are real replies that were actually observed
expect(stripHangupMarker('好的,我这就帮你挂断通话。').hangup).toBe(true);
expect(stripHangupMarker('好的,我可以帮你挂断。你还有其他需要帮助的事情吗?').hangup).toBe(
true,
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/sendDisabledReason.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/sendDisabledReason.test.ts
index a6d8c48..9a4b0d8 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/sendDisabledReason.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/sendDisabledReason.test.ts
@@ -1,5 +1,5 @@
/**
- * 发送禁用原因单测:模型、密钥与明文密钥各阶段给出明确提示。
+ * Unit tests for the send-disabled reason: model, secret, and plaintext-secret stages each produce a clear message.
*/
import { describe, expect, it } from 'vitest';
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/sse.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/sse.test.ts
index 05bee45..351263b 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/sse.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/sse.test.ts
@@ -11,7 +11,7 @@ import {
flushThinkDelta,
} from '../sse';
-/** 把整段文本按任意分片喂给拆分器,聚合出正文/思考,模拟真实流式切分。 */
+/** Feed the whole text to the splitter in arbitrary chunks and aggregate body and reasoning, simulating a real streaming split. */
function runThinkSplit(chunks: string[]): { content: string; reasoning: string } {
const state = createThinkSplitState();
let content = '';
@@ -25,7 +25,7 @@ function runThinkSplit(chunks: string[]): { content: string; reasoning: string }
return { content: content + tail.content, reasoning: reasoning + tail.reasoning };
}
-/** SSE 行解析与 OpenAI chunk 抽取的纯函数单测 */
+/** Unit tests for SSE line parsing and OpenAI chunk extraction pure functions */
describe('splitSseLines', () => {
it('保留末尾未完成片段', () => {
const { lines, rest } = splitSseLines('data: a\ndata: b\ndata: par');
@@ -235,7 +235,7 @@ describe('normalizeCitations', () => {
{ type: 'url_citation', url_citation: { index: 2, url: 'https://b.com' } },
]),
).toEqual([{ ref: 2, url: 'https://b.com' }]);
- // 0 与非整数不是合法编号,不能落成 ref——下游会把它当「后端已发号」来判定越界。
+ // 0 and non-integers are not valid numbers and must not become a ref — downstream treats that as "the backend already assigned a number" when judging out-of-range.
expect(normalizeCitations([{ ref: 0, url: 'https://c.com' }])).toEqual([
{ url: 'https://c.com' },
]);
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/thinkSplit.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/thinkSplit.test.ts
index 348e582..a9a44b2 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/thinkSplit.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/thinkSplit.test.ts
@@ -7,7 +7,7 @@ import {
normalizeAssistantReply,
} from '../thinkSplit';
-/** 模拟流式分片喂入拆分器 */
+/** Simulate feeding the splitter with streaming chunks */
function runThinkSplit(chunks: string[]): { content: string; reasoning: string } {
const state = createThinkSplitState();
let content = '';
@@ -21,7 +21,7 @@ function runThinkSplit(chunks: string[]): { content: string; reasoning: string }
return { content: content + tail.content, reasoning: reasoning + tail.reasoning };
}
-/** think 标签拆分与展示归一化单测 */
+/** Unit tests for think-tag splitting and display normalization */
describe('splitInlineThinkText', () => {
it('识别 think 标签', () => {
const r = splitInlineThinkText('<think>先想</think>正式回答');
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/toolEvents.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/toolEvents.test.ts
index e996b33..01f101c 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/toolEvents.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/toolEvents.test.ts
@@ -90,9 +90,9 @@ describe('toolEvents', () => {
],
});
- // 前两条只差末尾斜杠、hash 与查询参数顺序,归一化后是同一条
+ // The first two differ only by a trailing slash, hash, and query-parameter order; after normalization they are the same item
expect(events[0]?.citationUrls).toEqual(['https://example.com/a?a=1&b=2']);
- // pageCount 仍取原始条数,主文案要用
+ // pageCount still uses the raw count; the main copy needs it
expect(events[0]?.pageCount).toBe(4);
});
@@ -134,7 +134,7 @@ describe('toolEvents', () => {
{ event_id: 'evt-1', step: 1, tool: 'web_search', status: 'running' },
120,
);
- // success 帧比 running 帧晚几秒,这期间流出的思考属于工具行「之后」,不能改切点
+ // The success frame arrives seconds after the running frame; reasoning that streams in during that gap belongs after the tool row and must not move the split point
const done = upsertToolEvent(
running,
{ event_id: 'evt-1', step: 1, tool: 'web_search', status: 'success', result_count: 4 },
@@ -197,7 +197,7 @@ describe('runningSearchQueries', () => {
it('没有进行中的搜索时返回空数组,顶行据此退回静态文案', () => {
const events: ToolEvent[] = [
- // running 但不带 queries:模型还在生成 tool_call 参数
+ // running without queries: the model is still generating tool_call arguments
{ eventId: 'a', step: 1, tool: 'web_search', status: 'running' },
{ eventId: 'b', step: 2, tool: 'web_extractor', status: 'running' },
];
diff --git a/webdemo/frontend/src/pages/playground/utils/__tests__/webSearchCapability.test.ts b/webdemo/frontend/src/pages/playground/utils/__tests__/webSearchCapability.test.ts
index 1c30f48..902e67e 100644
--- a/webdemo/frontend/src/pages/playground/utils/__tests__/webSearchCapability.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/__tests__/webSearchCapability.test.ts
@@ -6,8 +6,8 @@ describe('canUsePlaygroundWebSearch', () => {
expect(canUsePlaygroundWebSearch({ web_search: true, function_call: true })).toBe(true);
});
- // 这条是重点:只勾 web_search 的模型不会真检索,只会捏造一次工具调用再编出带假引用的回答,
- // 因此入口必须连同 function_call 一起判,与后端两条入口保持一致。
+ // This one matters: a model with only web_search checked will not actually search; it fabricates a tool call and then an answer with fake citations,
+ // so the entry check must also require function_call, matching the two backend entry points.
it('缺少 function_call 时不展示联网入口', () => {
expect(canUsePlaygroundWebSearch({ web_search: true, function_call: false })).toBe(false);
expect(canUsePlaygroundWebSearch({ web_search: true })).toBe(false);
diff --git a/webdemo/frontend/src/pages/playground/utils/answerTimeline.ts b/webdemo/frontend/src/pages/playground/utils/answerTimeline.ts
index 71d2d79..09f1ef9 100644
--- a/webdemo/frontend/src/pages/playground/utils/answerTimeline.ts
+++ b/webdemo/frontend/src/pages/playground/utils/answerTimeline.ts
@@ -1,80 +1,80 @@
/**
- * 回答过程时间线的排序与取数纯函数。
+ * Pure functions that order and read the answer-process timeline.
*
- * 用途:把「一整块流式思考文本」与「按到达顺序排列的工具事件」还原成模型真实的
- * 「思考 → 调工具 → 继续思考」单条时间线,并为工具行解析出就地展示的来源。
+ * Purpose: turn "one streaming reasoning blob" and "tool events in arrival order" back into the model's real
+ * "reason → call a tool → continue reasoning" timeline, and resolve the sources shown inline on a tool row.
*/
import type { Citation, ToolEvent } from '../types';
import { citationURLKey } from './citations';
-/** 归联网过程的工具名。 */
+/** Tool names that count as web-search activity. */
export const WEB_TOOLS = new Set(['web_search', 'web_extractor']);
-/** 工具行与来源胶囊上最多叠放的站点图标数;多出来的不计数,那一叠只是「碰了这些站点」的示意。 */
+/** Maximum site icons stacked on a tool row and a source pill; extras are not counted. The stack only suggests "these sites were touched". */
export const MAX_ROW_FAVICONS = 4;
-/** 工具行上最多内联展示的页面标题数,超出用 +N 表示。 */
+/** Maximum page titles shown inline on a tool row; the rest use +N. */
export const MAX_ROW_TITLES = 3;
-/** stagger 入场动画的单步延时与最大档位,避免来源多时最后一个要等好几秒。 */
+/** Per-step delay and maximum tier of the stagger entrance animation, so the last source does not wait several seconds when there are many. */
export const STAGGER_STEP_MS = 60;
export const STAGGER_MAX_STEPS = 6;
/**
- * 判断工具是否为内置网页读取器(web_extractor)。
- * @param tool 工具名
- * @returns true 表示该工具用于读取网页正文而非搜索结果
+ * Whether the tool is the built-in page reader (web_extractor).
+ * @param tool tool name
+ * @returns true when the tool reads page body text rather than search results
*/
export function isReaderTool(tool: string | undefined): boolean {
return tool === 'web_extractor';
}
/**
- * 判断工具是否为内置联网搜索(web_search)。
- * @param tool 工具名
- * @returns true 表示该工具产出的是搜索结果列表
+ * Whether the tool is the built-in web search (web_search).
+ * @param tool tool name
+ * @returns true when the tool produces a search-result list
*/
export function isSearchTool(tool: string | undefined): boolean {
return tool === 'web_search';
}
-/** 时间线上的一项:一段思考文本,或一次工具调用。 */
+/** One timeline item: a reasoning segment, or one tool call. */
export type ProcessTimelineItem =
| { kind: 'reasoning'; id: string; text: string }
| { kind: 'tool'; id: string; event: ToolEvent };
-/** 时间线排序结果。 */
+/** Timeline ordering result. */
export interface ProcessTimeline {
items: ProcessTimelineItem[];
/**
- * 是否真正做到了交错。false 表示退化成「思考整块置顶 + 工具依次排下」——
- * 仍是一条线,只是分不出工具是在思考的哪一处插进来的。
+ * Whether interleaving actually happened. false means it fell back to "the whole reasoning block on top + tool rows underneath" —
+ * still one line, but it no longer shows where in the reasoning each tool was inserted.
*/
interleaved: boolean;
}
/**
- * 把思考文本按工具事件的切分点切段,与工具行交错成一条时间线。
+ * Split reasoning text at tool-event split points and interleave it with tool rows into one timeline.
*
- * 切分点是 `ToolEvent.reasoningOffset`(流式期间在 SSE 回调里累加得到的字符数)。
- * 传入的 `reasoning` 必须是**未 trim 的原文**:offset 是按原文累加的,先 trim 再按 offset
- * 切会整体错位(模型惯常在调工具前留一个换行,trim 掉之后显示长度反而短于 offset)。
- * 段内首尾空白由逐段 trim 收拾。
+ * The split point is `ToolEvent.reasoningOffset` (the character count accumulated in the SSE callback while streaming).
+ * The `reasoning` passed in must be the **untrimmed original**: offsets are accumulated against that text. Trimming first and then
+ * splitting by offset shifts everything (models often leave a newline before a tool call, so the trimmed display length is shorter than the offset).
+ * Leading and trailing whitespace inside each segment is cleaned up by a per-segment trim.
*
- * 以下两种情况无法交错,退化为思考整块置顶:
- * - `reasoningRewritten`:展示层的 normalizeAssistantReply 改写过思考文本(清空或前置拼接
- * 正文里的残留 think 段),offset 全部错位;
- * - 任一事件缺 `reasoningOffset`:非流式回答一次性给全文,本次改动之前存下的历史消息同理。
+ * Interleaving is impossible in these two cases, which fall back to putting the whole reasoning block on top:
+ * - `reasoningRewritten`: the display layer's normalizeAssistantReply rewrote the reasoning text (cleared it, or prepended a leftover think
+ * segment from the body), so every offset is misaligned;
+ * - any event lacks `reasoningOffset`: a non-streaming answer arrives as one full text, as do history messages stored before this change.
*
- * @param input 思考原文、按到达顺序的工具事件、是否被展示层改写过、是否押后未播到的工具行
- * @returns 时间线各项与是否真正交错
+ * @param input original reasoning, tool events in arrival order, whether the display layer rewrote it, and whether to hold back tool rows not yet played
+ * @returns timeline items and whether they are truly interleaved
*/
export function buildProcessTimeline(input: {
reasoning: string;
toolEvents: ToolEvent[];
reasoningRewritten?: boolean;
- /** 流式期间传 true:切分点还没被播放队列播到的工具行先不出现,见循环内注释。 */
+ /** Pass true while streaming: tool rows whose split point the playback queue has not reached yet stay hidden. See the comment inside the loop. */
holdUnplayed?: boolean;
}): ProcessTimeline {
const { reasoning, toolEvents, reasoningRewritten = false, holdUnplayed = false } = input;
@@ -93,19 +93,19 @@ export function buildProcessTimeline(input: {
}
const items: ProcessTimelineItem[] = [];
- // 单游标推进即可:后端 emit 从不设 event_id,toolEventKey 走 legacy:step:tool 兜底,
- // 所以 toolEvents 的数组顺序就是到达顺序,不需要再按 step 分组。
- // 下界取 cursor 保证单调(同一 step 的多个工具共用一个切点时不会回退)。
+ // A single cursor is enough: the backend emit never sets event_id, so toolEventKey falls back to legacy:step:tool,
+ // and the array order of toolEvents is the arrival order. There is no need to group by step again.
+ // The lower bound is the cursor, which keeps it monotonic (several tools in the same step share one split point and must not move backward).
let cursor = 0;
for (const event of toolEvents) {
const target = event.reasoningOffset ?? 0;
/*
- 流式期间「还没播到的」工具行先押着不出。offset 记的是 SSE 到达那一刻**已 enqueue**
- 的字符数,而这里的 reasoning 是过了 16ms 播放队列的**已显示**文本,两者差着整个积压。
- 不押的话下面的 clamp 会把切点按显示长度往前拽,工具行就抢在它上方那段思考播完之前
- 先冒出来——读起来是「话没说完先跳出一行」。押到播到为止,顺序才与模型真实执行一致。
+ While streaming, tool rows that have not been played yet are held back. The offset records how many characters had **already been enqueued**
+ when the SSE event arrived, while reasoning here is the text **already displayed** after the 16ms playback queue, so the two differ by the whole backlog.
+ Without holding them back, the clamp below pulls the split point forward to the displayed length, and the tool row pops out before the reasoning above it finishes playing —
+ it reads as a row jumping out before the sentence is finished. Hold until playback catches up, and the order matches what the model actually did.
- 工具事件按到达顺序单调,所以第一个没播到的就可以整体 break。
+ Tool events are monotonic in arrival order, so the first one not yet played can break out of the rest.
*/
if (holdUnplayed && target > reasoning.length) break;
const offset = clamp(target, cursor, reasoning.length);
@@ -122,10 +122,10 @@ export function buildProcessTimeline(input: {
}
/**
- * 追加一段思考。
+ * Append a reasoning segment.
*
- * 纯空白不单独成段(否则时间线上会留一个空项),段内首尾空白也一并去掉:切出来的段常以
- * 换行开头,而首行缩进 4 个空格会被 markdown 当成代码块。
+ * Pure whitespace does not become its own segment (that would leave an empty item on the timeline), and leading and trailing whitespace
+ * inside the segment is removed too: a split segment often starts with a newline, and a 4-space indent on the first line would be treated as a code block by markdown.
*/
function pushReasoning(items: ProcessTimelineItem[], text: string, offset: number): void {
const trimmed = text.trim();
@@ -138,25 +138,25 @@ function clamp(value: number, min: number, max: number): number {
}
/**
- * 为来源建立按归一化 URL 检索的索引,供工具行按 citationUrls 取标题。
- * @param citations 整条消息的来源
- * @returns 归一化 URL → 来源
+ * Build an index of sources by normalized URL, so a tool row can look up titles from citationUrls.
+ * @param citations sources of the whole message
+ * @returns normalized URL → source
*/
export function citationIndex(citations: Citation[]): Map<string, Citation> {
return new Map(citations.map((citation) => [citationURLKey(citation.url), citation]));
}
/**
- * 取某个工具行上要展示的来源。
+ * Take the sources to show on one tool row.
*
- * web_extractor 的事件自带 urls,能精确对上它读了哪几页;web_search 的事件后端一个 url
- * 都不发(只有 queries 与 result_count),所以退回整条消息的来源——单次搜索时两者等价,
- * 多次搜索时各行会展示同一批图标,这是已知且可接受的近似。
+ * A web_extractor event carries its own urls, so it can match exactly which pages it read; a web_search event gets no url from the backend
+ * (only queries and result_count), so it falls back to the whole message's sources — they are equivalent for a single search,
+ * and on several searches each row shows the same batch of icons, which is a known and acceptable approximation.
*
- * @param event 工具事件
- * @param index citationIndex 建好的索引
- * @param allCitations 整条消息的来源,供 web_search 兜底
- * @returns 该行的来源;匹配不到标题时至少保留地址,供 favicon 使用
+ * @param event tool event
+ * @param index index built by citationIndex
+ * @param allCitations sources of the whole message, the fallback for web_search
+ * @returns sources for this row; when no title matches, at least keep the address for the favicon
*/
export function toolRowCitations(
event: ToolEvent,
@@ -170,18 +170,18 @@ export function toolRowCitations(
}
/**
- * 按下标给出递增入场延时,超过档位上限后不再增加。
- * @param index 元素下标
- * @returns 可直接用于 style 的 animationDelay
+ * Give an increasing entrance delay by index, and stop increasing once the tier cap is passed.
+ * @param index element index
+ * @returns an animationDelay that can be used directly in style
*/
export function staggerStyle(index: number): { animationDelay: string } {
return { animationDelay: `${Math.min(index, STAGGER_MAX_STEPS) * STAGGER_STEP_MS}ms` };
}
/**
- * stagger 入场动画的 class。
- * fill-mode-both 必须带上:否则延时期间元素以终态显示,等到动画真正开始才跳回起点,
- * 逐个冒出的观感会变成「先全部出现再闪一下」。
+ * Class for the stagger entrance animation.
+ * fill-mode-both must be included: otherwise the element shows its end state during the delay, then jumps back to the start when the animation actually begins,
+ * and the "appearing one by one" look becomes "everything appears first, then flashes".
*/
export const STAGGER_CLASS_NAME =
'motion-safe:animate-in motion-safe:fade-in-0 motion-safe:slide-in-from-bottom-1 motion-safe:fill-mode-both';
diff --git a/webdemo/frontend/src/pages/playground/utils/appendDocumentPages.ts b/webdemo/frontend/src/pages/playground/utils/appendDocumentPages.ts
index 6912ca0..6c0ee5f 100644
--- a/webdemo/frontend/src/pages/playground/utils/appendDocumentPages.ts
+++ b/webdemo/frontend/src/pages/playground/utils/appendDocumentPages.ts
@@ -1,6 +1,6 @@
/**
- * 把新选的图片或一份 PDF 接在当前文档后面,合成一份新 PDF。
- * 已有 PDF 页按识别时的 2 倍画下来再嵌回去,归一化识别框仍能对上预览。
+ * Append newly selected images or one PDF after the current document and compose a new PDF.
+ * Existing PDF pages are drawn at the same 2x used for recognition and embedded again, so normalized recognition boxes still line up with the preview.
*/
import type { PDFDocumentProxy } from 'pdfjs-dist';
@@ -24,7 +24,7 @@ export interface AppendedPdf {
totalPages: number;
}
-/** 将 PDF 单页按 2 倍缩放编码为 JPEG,保持与逐页识别相同的坐标基准。 */
+/** Encode one PDF page as JPEG at 2x scale, keeping the same coordinate basis as per-page recognition. */
async function renderPdfPageJpeg(
pdf: PDFDocumentProxy,
pageNumber: number,
@@ -78,10 +78,10 @@ async function renderPdfPageJpeg(
}
}
-/** 读取 PDF 全部页面;页数上限与工作台原有预览、识别链路一致。 */
+/** Read every page of a PDF; the page limit matches the workspace preview and recognition path. */
async function pdfSourceToPages(source: string, signal: AbortSignal): Promise<JpegPage[]> {
signal.throwIfAborted();
- // 按需加载 PDF.js:日常单图上传不需要提前初始化画布依赖。
+ // Load PDF.js on demand: an ordinary single-image upload should not initialize the canvas dependency up front.
const { loadPdfPreview } = await import('./pdfPreview');
signal.throwIfAborted();
const task = loadPdfPreview(source);
@@ -111,7 +111,7 @@ async function pdfSourceToPages(source: string, signal: AbortSignal): Promise<Jp
}
}
-/** 将单个新文件转成 JPEG 页;PDF 保持原页序,图片只产生一页。 */
+/** Turn one new file into JPEG pages; a PDF keeps its original page order, and an image produces one page. */
async function fileToPages(
file: File,
signal: AbortSignal,
@@ -129,7 +129,7 @@ async function fileToPages(
return [await imageFileToJpegPage(file, maxEdge)];
}
-/** 读取当前附件;已有图片不缩小,避免识别框与新页图尺寸错位。 */
+/** Read the current attachment; an existing image is not downscaled, so recognition boxes stay aligned with the new page image. */
async function currentToPages(
current: Pick<Attachment, 'dataUrl' | 'mime' | 'kind' | 'name'>,
signal: AbortSignal,
@@ -144,11 +144,11 @@ async function currentToPages(
}
/**
- * 当前文档在前,新选文件按选择顺序接在后面。
- * @param current 当前图片或 PDF 附件
- * @param incoming 通过选择校验的新文件
- * @param signal 取消追加与页面渲染的信号
- * @returns 合成后的 PDF 字节与页数信息
+ * The current document comes first; newly selected files are appended in selection order.
+ * @param current current image or PDF attachment
+ * @param incoming new files that passed selection checks
+ * @param signal signal that cancels append and page rendering
+ * @returns composed PDF bytes and page-count info
*/
export async function buildAppendedPdf(
current: Pick<Attachment, 'dataUrl' | 'mime' | 'kind' | 'name'>,
@@ -169,10 +169,10 @@ export async function buildAppendedPdf(
}
/**
- * 把合成后的 PDF 转成 data URL;复制为独立 ArrayBuffer,避免视图类型影响 Blob。
- * @param bytes PDF 文件字节
- * @param mime 输出 MIME,默认 application/pdf
- * @returns 可直接交给附件状态的 data URL
+ * Turn the composed PDF into a data URL; copy it into an independent ArrayBuffer so the view's typed array does not affect the Blob.
+ * @param bytes PDF file bytes
+ * @param mime output MIME, default application/pdf
+ * @returns a data URL that can be handed straight to attachment state
*/
export function bytesToDataUrl(bytes: Uint8Array, mime = 'application/pdf'): Promise<string> {
return new Promise((resolve, reject) => {
diff --git a/webdemo/frontend/src/pages/playground/utils/appendDocumentPlan.ts b/webdemo/frontend/src/pages/playground/utils/appendDocumentPlan.ts
index 1ea17a8..a799293 100644
--- a/webdemo/frontend/src/pages/playground/utils/appendDocumentPlan.ts
+++ b/webdemo/frontend/src/pages/playground/utils/appendDocumentPlan.ts
@@ -1,4 +1,4 @@
-/** 追加页面的选择规则,以及新页接上后要保留的识别结果。不读取文件内容。 */
+/** Selection rules for appending pages, and which recognition results to keep after the new pages are attached. Does not read file contents. */
import type { ImageParseSdkResult } from '@/api/map/imageParseSdk';
import { documentFileError, normalizeDocumentFile } from './documentUpload';
@@ -6,9 +6,9 @@ import type { PdfImageParseSnapshot } from './imageParseHistoryTypes';
import type { PdfPageResult } from './pdfImageParse';
/**
- * 校验一次追加选择:支持多张图片或一份 PDF,不允许混选或多份 PDF。
- * @param incoming 文件选择器或拖放得到的文件列表
- * @returns 稳定的翻译键;选择合法时返回 undefined
+ * Validate one append selection: several images or one PDF are allowed; mixed selections and multiple PDFs are not.
+ * @param incoming file list from the picker or a drop
+ * @returns a stable translation key; undefined when the selection is valid
*/
export function appendSelectionError(
incoming: FileList | readonly File[],
@@ -26,11 +26,11 @@ export function appendSelectionError(
}
/**
- * 保留旧页结果,并把阅读位置停在第一张新页。
- * @param previousPages 追加前的页数
- * @param totalPages 追加后的页数
- * @param kept 旧页识别结果;没有结果的旧页会在续跑时重新识别
- * @returns 可直接交给 PDF 解析状态恢复的快照
+ * Keep the old page results and leave the reading position on the first new page.
+ * @param previousPages page count before the append
+ * @param totalPages page count after the append
+ * @param kept recognition results for the old pages; old pages without a result are recognized again when the run continues
+ * @returns a snapshot that can be handed straight to PDF parse-state restore
*/
export function appendedPdfSnapshot(
previousPages: number,
@@ -50,9 +50,9 @@ export function appendedPdfSnapshot(
}
/**
- * 单图文档追加时,把已经识别完的这一页当成新 PDF 的第 1 页。
- * @param page 当前单图识别结果
- * @returns 可保留的页结果;空结果返回 undefined
+ * When appending to a single-image document, treat this already-recognized page as page 1 of the new PDF.
+ * @param page current single-image recognition result
+ * @returns a page result that can be kept; undefined when the result is empty
*/
export function imagePageResult(page: {
markdown: string;
diff --git a/webdemo/frontend/src/pages/playground/utils/attachmentCapabilities.ts b/webdemo/frontend/src/pages/playground/utils/attachmentCapabilities.ts
index f4178ed..0d015b0 100644
--- a/webdemo/frontend/src/pages/playground/utils/attachmentCapabilities.ts
+++ b/webdemo/frontend/src/pages/playground/utils/attachmentCapabilities.ts
@@ -9,9 +9,9 @@ const CAPABILITY_BY_KIND: Record<AttachmentKind, string> = {
};
/**
- * 返回模型明确支持的附件模态。
- * @param capabilities 当前模型的能力配置
- * @returns 可上传的附件模态
+ * Return the attachment modalities the model explicitly supports.
+ * @param capabilities capability config of the current model
+ * @returns attachment modalities that can be uploaded
*/
export function supportedAttachmentKinds(
capabilities: Record<string, boolean> | undefined,
@@ -23,10 +23,10 @@ export function supportedAttachmentKinds(
}
/**
- * 判断模型是否支持指定附件模态。
- * @param capabilities 当前模型的能力配置
- * @param kind 待校验的附件模态
- * @returns 是否支持
+ * Whether the model supports the given attachment modality.
+ * @param capabilities capability config of the current model
+ * @param kind attachment modality to check
+ * @returns whether it is supported
*/
export function supportsAttachmentKind(
capabilities: Record<string, boolean> | undefined,
@@ -36,9 +36,9 @@ export function supportsAttachmentKind(
}
/**
- * 按模型能力生成文件选择器 accept 值,避免给不支持的模态展示上传选项。
- * @param capabilities 当前模型的能力配置
- * @returns 文件选择器 accept 值
+ * Build the file-picker accept value from model capabilities, so upload options are not shown for unsupported modalities.
+ * @param capabilities capability config of the current model
+ * @returns file-picker accept value
*/
export function attachmentAcceptForCapabilities(
capabilities: Record<string, boolean> | undefined,
@@ -49,9 +49,9 @@ export function attachmentAcceptForCapabilities(
}
/**
- * 生成附件不支持时的中文提示。
- * @param kind 文件识别出的附件模态
- * @returns 用户可读错误信息
+ * Build the Chinese message shown when an attachment is unsupported.
+ * @param kind attachment modality recognized from the file
+ * @returns user-readable error message
*/
export function unsupportedAttachmentMessage(kind: AttachmentKind): string {
const labels: Record<AttachmentKind, string> = {
@@ -64,10 +64,10 @@ export function unsupportedAttachmentMessage(kind: AttachmentKind): string {
}
/**
- * 根据文件 MIME 和模型能力校验附件是否可上传。
- * @param capabilities 当前模型的能力配置
- * @param mime 文件 MIME
- * @returns 通过时返回 undefined,否则返回错误信息
+ * Check whether an attachment can be uploaded from the file MIME and the model capabilities.
+ * @param capabilities capability config of the current model
+ * @param mime file MIME
+ * @returns undefined when it passes, otherwise an error message
*/
export function validateAttachmentCapability(
capabilities: Record<string, boolean> | undefined,
diff --git a/webdemo/frontend/src/pages/playground/utils/attachmentPdf.ts b/webdemo/frontend/src/pages/playground/utils/attachmentPdf.ts
index dc7b541..0d8a8ed 100644
--- a/webdemo/frontend/src/pages/playground/utils/attachmentPdf.ts
+++ b/webdemo/frontend/src/pages/playground/utils/attachmentPdf.ts
@@ -9,14 +9,14 @@ import {
const PDF_MIME = 'application/pdf';
/**
- * 读取 OCR PDF:文件服务可用时先上传原件,再用运行时 Blob URL 预览。
+ * Read an OCR PDF: when the file service is available, upload the original first, then preview it with a runtime Blob URL.
*
- * 大 PDF 不能先转 base64 data URL;否则 FileReader 与 PDF.js 解码都会长时间占用主线程。
- * Blob URL 仅保存在当前附件状态,云端历史仍只持久化稳定 fileId。
- * @param file 用户选择的 PDF
- * @param signal 连续替换文件时的取消信号
- * @param options OCR 的大小上限与本地兜底策略
- * @returns 上传成功返回 fileId + Blob URL;本地兜底也使用 Blob URL,避免 base64 阻塞主线程
+ * A large PDF must not be converted to a base64 data URL first; otherwise both FileReader and PDF.js decoding occupy the main thread for a long time.
+ * The Blob URL lives only in the current attachment state. Cloud history still persists only the stable fileId.
+ * @param file PDF selected by the user
+ * @param signal cancellation signal when files are replaced in succession
+ * @param options OCR size limit and local-fallback policy
+ * @returns fileId + Blob URL on a successful upload; the local fallback also uses a Blob URL so base64 does not block the main thread
*/
export async function readPdfAttachment(
file: File,
diff --git a/webdemo/frontend/src/pages/playground/utils/attachments.ts b/webdemo/frontend/src/pages/playground/utils/attachments.ts
index 4bca12b..c62339e 100644
--- a/webdemo/frontend/src/pages/playground/utils/attachments.ts
+++ b/webdemo/frontend/src/pages/playground/utils/attachments.ts
@@ -1,8 +1,8 @@
/**
- * 多模态附件工具:读文件预览、上传对象存储、类型/大小校验、OpenAI content-part 映射。
+ * Multimodal attachment helpers: read a file for preview, upload to object storage, check type and size, and map OpenAI content parts.
*
- * 用途:Playground 上传图像/视频/文件优先走对象存储 URL,避免 base64 撑大 L2 请求体;
- * 音频因 OpenAI input_audio 契约仍使用裸 base64。
+ * Purpose: Playground uploads of images, video, and files prefer an object-storage URL so base64 does not bloat the L2 request body;
+ * audio still uses raw base64 because of the OpenAI input_audio contract.
*/
import { mapAssetsApi } from '@/api/map/assets';
@@ -10,24 +10,24 @@ import { fileUploadConfig, uploadPlaygroundFile } from '@/api/map/fileUploads';
import type { Attachment, AttachmentKind } from '../types';
import type { ChatContentPart } from '@/api/map/chat';
-/** 各模态的校验配置:允许的 MIME、大小上限、中文标签 */
+/** Validation config for each modality: allowed MIME types, size limit, and Chinese label */
interface KindConfig {
- /** 允许的精确 MIME 列表(file 模态不做白名单,仅按大小与「非媒体」兜底) */
+ /** Exact allowed MIME list (the file modality has no allowlist; it only falls back by size and "not media") */
accept: string[];
- /** 大小上限(字节) */
+ /** Size limit (bytes) */
maxBytes: number;
- /** 中文标签(错误文案用) */
+ /** Chinese label (used in error copy) */
label: string;
}
const MB = 1024 * 1024;
-/** 图片、音频和视频的单个附件大小上限。 */
+/** Per-attachment size limit for images, audio, and video. */
const MAX_BYTES_PER_ATTACHMENT = 8 * MB;
-/** 文档上传大小上限,需与后端 ASSET_UPLOAD_MAX_BYTES 和 portal Nginx 保持一致。 */
+/** Document upload size limit; must stay consistent with backend ASSET_UPLOAD_MAX_BYTES and the portal Nginx limit. */
const MAX_BYTES_PER_DOCUMENT = 200 * MB;
-/** 模态配置表 */
+/** Modality config table */
const KIND_CONFIG: Record<AttachmentKind, KindConfig> = {
image: {
accept: ['image/jpeg', 'image/png', 'image/webp', 'image/gif'],
@@ -53,7 +53,7 @@ const KIND_CONFIG: Record<AttachmentKind, KindConfig> = {
label: '音频',
},
file: {
- // 常见文档/文本类型;实际以「非 image/video/audio」兜底为 file
+ // Common document and text types; anything that is not image/video/audio actually falls back to file
accept: [
'application/pdf',
'text/plain',
@@ -79,9 +79,9 @@ function mimeAllowed(mime: string, allowed: readonly string[]): boolean {
}
/**
- * 获取单个附件模态对应的文件选择器 accept 值。
- * @param kind 附件模态
- * @returns MIME 与扩展名列表
+ * File-picker accept value for a single attachment modality.
+ * @param kind attachment modality
+ * @returns MIME types and extensions
*/
export function getAttachmentAccept(kind: AttachmentKind): string[] {
const cfg = KIND_CONFIG[kind];
@@ -89,12 +89,12 @@ export function getAttachmentAccept(kind: AttachmentKind): string[] {
return [...cfg.accept, '.pdf', '.txt', '.md', '.csv', '.json', '.doc', '.docx'];
}
-/** 单条消息附件总数上限(避免请求体过大) */
+/** Cap on attachments per message (keeps the request body from growing too large) */
export const MAX_ATTACHMENTS = 6;
/**
- * 按 MIME 判定附件模态。image/video/audio 前缀分别归类,其余一律视为 file。
- * @param mime 文件 MIME
+ * Classify an attachment modality by MIME. image/video/audio prefixes each map to their own kind; everything else is file.
+ * @param mime file MIME
*/
export function detectKind(mime: string): AttachmentKind {
if (mime.startsWith('image/')) return 'image';
@@ -103,7 +103,7 @@ export function detectKind(mime: string): AttachmentKind {
return 'file';
}
-/** 构造本地附件对象;预览地址可以兼容 data URL 与运行时 Blob URL。 */
+/** Build a local attachment object; the preview URL may be either a data URL or a runtime Blob URL. */
export function createLocalAttachment(
file: File,
previewUrl: string,
@@ -120,37 +120,37 @@ export function createLocalAttachment(
};
}
-/** 读取结果:成功带 attachment,失败带中文错误信息 */
+/** Read result: success carries an attachment, failure carries a Chinese error message */
export interface ReadAttachmentResult {
ok: boolean;
attachment?: Attachment;
error?: string;
}
-/** 调用方可覆盖读取行为;不传 options 时保持 Playground 附件规则。 */
+/** Callers may override read behavior; omitting options keeps the Playground attachment rules. */
export interface ReadAttachmentOptions {
- /** 单文件大小上限。 */
+ /** Per-file size limit. */
maxBytes?: number;
- /** 调用方专用 MIME 白名单;缺省使用当前模态配置。 */
+ /** Caller-specific MIME allowlist; defaults to the current modality config. */
accept?: readonly string[];
- /** OCR 专用:文件服务不可用时允许退回本地 dataUrl,避免阻断识别。 */
+ /** OCR only: when the file service is unavailable, allow falling back to a local dataUrl so recognition is not blocked. */
allowLocalFallback?: boolean;
- /** OCR 专用:直接使用旧资产上传入口,返回平台签名链接。 */
+ /** OCR only: use the legacy asset upload entry directly and return the platform signed URL. */
preferLegacyUpload?: boolean;
}
let seq = 0;
-/** 生成附件唯一 id(前端 key / 移除用,无需 crypto 强度) */
+/** Generate a unique attachment id (frontend key / removal; does not need cryptographic strength) */
function nextId(): string {
seq += 1;
return `att_${Date.now().toString(36)}_${seq.toString(36)}`;
}
/**
- * 读取单个文件为本地预览 data URL,不发送网络请求。
- * @param file 用户选中的文件
- * @param signal 连续选图时中止旧文件读取
- * @returns 成功含 attachment;失败含中文 error
+ * Read a single file as a local preview data URL, with no network request.
+ * @param file file the user selected
+ * @param signal abort signal for an older file read when images are selected in succession
+ * @returns success includes an attachment; failure includes a Chinese error
*/
export async function readPreviewAttachment(
file: File,
@@ -160,7 +160,7 @@ export async function readPreviewAttachment(
const kind = detectKind(file.type);
const cfg = KIND_CONFIG[kind];
const maxBytes = options?.maxBytes ?? cfg.maxBytes;
- // 媒体类做 MIME 白名单校验;file 兜底类不限具体类型(仅封顶大小)
+ // Media kinds are checked against a MIME allowlist; the file fallback kind does not limit the specific type (only the size cap)
const allowedTypes = options?.accept ?? cfg.accept;
if (kind !== 'file' && !mimeAllowed(file.type, allowedTypes)) {
return Promise.resolve({
@@ -216,7 +216,7 @@ function isUploadError(
);
}
-/** 仅服务或存储故障回退旧入口;业务校验、鉴权和限流错误不能绕过。 */
+/** Fall back to the legacy entry only for a service or storage failure; business validation, auth, and rate-limit errors must not be bypassed. */
function canFallbackToLegacyUpload(error: unknown): boolean {
if (!isUploadError(error)) return false;
if (
@@ -233,11 +233,11 @@ function canFallbackToLegacyUpload(error: unknown): boolean {
}
/**
- * 读取附件并优先写入文件服务;通用附件在文件服务故障时回退旧资产入口。
- * OCR 选择本地兜底时不访问旧入口,避免上传最终不会使用的对象。
- * @param file 用户选中的文件
- * @param signalOrIndex 中止信号;兼容旧调用方传入的序号
- * @param options 大小上限与本地兜底策略
+ * Read the attachment and write it to the file service first; a general attachment falls back to the legacy asset entry when the file service fails.
+ * When OCR chooses the local fallback, do not touch the legacy entry, so an object that will not be used is not uploaded.
+ * @param file file the user selected
+ * @param signalOrIndex abort signal; compatible with old callers that passed an index
+ * @param options size cap and local-fallback policy
*/
export async function readFileAsAttachment(
file: File,
@@ -321,13 +321,13 @@ export async function readFileAsAttachment(
}
}
-/** 从 data URL 取出去前缀的裸 base64(input_audio.data 需要裸串) */
+/** Take the raw base64 out of a data URL, without the prefix (input_audio.data needs the raw string) */
function stripDataUrlPrefix(dataUrl: string): string {
const comma = dataUrl.indexOf(',');
return comma >= 0 ? dataUrl.slice(comma + 1) : dataUrl;
}
-/** 由音频 MIME 推断 OpenAI input_audio 的 format 字段(mp3/wav/...) */
+/** Infer the OpenAI input_audio format field (mp3/wav/...) from the audio MIME */
function audioFormat(mime: string): string {
if (mime === 'audio/mpeg' || mime === 'audio/mp3') return 'mp3';
if (mime === 'audio/wav' || mime === 'audio/x-wav') return 'wav';
@@ -336,10 +336,10 @@ function audioFormat(mime: string): string {
}
/**
- * 把附件映射为 OpenAI 兼容的 content-part。
- * - image → image_url;video → video_url(Qwen-VL 等约定),优先传平台公开签名代理 URL
- * - audio → input_audio(裸 base64 + format);file → file(优先 file_url,兜底 file_data)
- * @param att 附件
+ * Map an attachment to an OpenAI-compatible content part.
+ * - image → image_url; video → video_url (the Qwen-VL convention and similar), preferring the platform's public signed proxy URL
+ * - audio → input_audio (raw base64 + format); file → file (file_url first, file_data as fallback)
+ * @param att attachment
*/
export function attachmentToPart(att: Attachment): ChatContentPart {
const url = att.publicUrl || att.url || att.dataUrl;
@@ -360,12 +360,12 @@ export function attachmentToPart(att: Attachment): ChatContentPart {
}
}
-/** input[type=file] 的 accept 值:汇总所有模态白名单 + 常见文档扩展名 */
+/** accept value for input[type=file]: every modality allowlist plus common document extensions */
export const ATTACHMENT_ACCEPT = (Object.keys(KIND_CONFIG) as AttachmentKind[])
.flatMap((kind) => getAttachmentAccept(kind))
.join(',');
-/** 人类可读的文件大小(用于附件展示) */
+/** Human-readable file size (for attachment display) */
export function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < MB) return `${(bytes / 1024).toFixed(0)} KB`;
diff --git a/webdemo/frontend/src/pages/playground/utils/audioEncode.ts b/webdemo/frontend/src/pages/playground/utils/audioEncode.ts
index 1802754..1124501 100644
--- a/webdemo/frontend/src/pages/playground/utils/audioEncode.ts
+++ b/webdemo/frontend/src/pages/playground/utils/audioEncode.ts
@@ -1,12 +1,12 @@
/**
- * 体验中心音频编解码工具。
+ * Audio encode and decode helpers for the experience center.
*
- * 用途:语音对话与 TTS 的浏览器侧音频处理——把录音 Blob 解码并重采样为 16kHz mono
- * PCM WAV 的裸 base64(对齐 MiniCPM-o / OpenAI input_audio 约定),以及把上游返回的
- * base64 音频组装成可播放的 Object URL。纯前端,无第三方依赖。
+ * Purpose: browser-side audio for voice chat and TTS — decode a recording Blob and resample it to 16kHz mono
+ * PCM WAV raw base64 (matching the MiniCPM-o / OpenAI input_audio convention), and assemble upstream base64
+ * audio into a playable Object URL. Frontend only, no third-party dependency.
*/
-/** 音频格式 → MIME,用于组装可播放的 Blob */
+/** Audio format → MIME, used to assemble a playable Blob */
export function mimeForFormat(format: string): string {
switch (format.toLowerCase()) {
case 'mp3':
@@ -23,7 +23,7 @@ export function mimeForFormat(format: string): string {
}
}
-/** 裸 base64 音频 → 可播放的 Object URL(调用方负责在不用时 revoke) */
+/** Raw base64 audio → playable Object URL (the caller revokes it when finished) */
export function base64ToObjectUrl(base64: string, format: string): string {
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
@@ -32,11 +32,11 @@ export function base64ToObjectUrl(base64: string, format: string): string {
}
/**
- * 录音/文件 Blob → { 16kHz mono PCM WAV 裸 base64, 时长秒 }。
+ * Recording or file Blob → { raw base64 of 16kHz mono PCM WAV, duration in seconds }.
*
- * 用 AudioContext 解码任意录音容器(webm/opus 等),再经 OfflineAudioContext 重采样到
- * 16kHz 单声道,最后编码为 16-bit PCM WAV。解码一次即同时拿到重采样音频与原始时长,
- * 供 TTS 参考音频做时长校验(≤50s)复用,避免二次解码。
+ * AudioContext decodes any recording container (webm/opus and so on), OfflineAudioContext resamples to
+ * 16kHz mono, then the samples are encoded as 16-bit PCM WAV. One decode yields both the resampled audio and the original duration,
+ * which TTS reference-audio duration checks (≤50s) can reuse, avoiding a second decode.
*/
export async function blobToWav16k(
blob: Blob,
@@ -65,13 +65,13 @@ export async function blobToWav16k(
}
/**
- * 录音/文件 Blob -> 可上传的 16kHz mono PCM WAV 文件。
+ * Recording or file Blob -> uploadable 16kHz mono PCM WAV file.
*
- * 用途:把浏览器 MediaRecorder 常见的 webm/opus 容器转换成音色接口要求的 WAV
- * 文件,调用方可继续复用现有 multipart 上传链路。
- * @param blob 待转换的音频 Blob
- * @param name 输出文件名
- * @returns WAV 文件与解码得到的原始时长
+ * Purpose: convert the webm/opus container typical of the browser MediaRecorder into the WAV
+ * file the voice API requires, so the caller can keep using the existing multipart upload path.
+ * @param blob audio Blob to convert
+ * @param name output file name
+ * @returns WAV file and the original duration from decoding
*/
export async function blobToWav16kFile(
blob: Blob,
@@ -90,21 +90,21 @@ export async function blobToWav16kFile(
}
/**
- * 录音 Blob → 16kHz mono PCM WAV 的裸 base64。
+ * Recording Blob → raw base64 of 16kHz mono PCM WAV.
*
- * 供 input_audio 上传(语音对话)。仅需 base64 时用本函数,内部复用 blobToWav16k。
+ * For input_audio upload (voice chat). Use this when only base64 is needed; it reuses blobToWav16k internally.
*/
export async function blobToWav16kBase64(blob: Blob): Promise<string> {
return (await blobToWav16k(blob)).base64;
}
/**
- * 音频 Blob → 16kHz mono 裸 float32 PCM base64。
+ * Audio Blob → raw float32 PCM base64 at 16kHz mono.
*
- * Realtime 参考音频协议不接受 WAV 容器,只接受裸 float32 PCM;与 TTS 的 WAV
- * 参考音频转换保持独立,避免把容器头误传给实时服务。
- * @param blob 待转换的音频文件
- * @returns 16kHz mono 裸 float32 PCM 的 base64
+ * The realtime reference-audio protocol does not accept a WAV container, only raw float32 PCM; keep this separate from the TTS WAV
+ * reference-audio conversion so a container header is not sent to the realtime service by mistake.
+ * @param blob audio file to convert
+ * @returns base64 of 16kHz mono raw float32 PCM
*/
export async function blobToPcm16kBase64(blob: Blob): Promise<string> {
const arrayBuf = await blob.arrayBuffer();
@@ -128,7 +128,7 @@ export async function blobToPcm16kBase64(blob: Blob): Promise<string> {
return arrayBufferToBase64(samples.buffer);
}
-/** Float32 采样 → 16-bit PCM WAV(含 44 字节头)ArrayBuffer */
+/** Float32 samples → 16-bit PCM WAV (44-byte header included) ArrayBuffer */
function encodeWavPcm16(samples: Float32Array, sampleRate: number): ArrayBuffer {
const buffer = new ArrayBuffer(44 + samples.length * 2);
const view = new DataView(buffer);
@@ -139,13 +139,13 @@ function encodeWavPcm16(samples: Float32Array, sampleRate: number): ArrayBuffer
view.setUint32(4, 36 + samples.length * 2, true);
writeStr(8, 'WAVE');
writeStr(12, 'fmt ');
- view.setUint32(16, 16, true); // fmt chunk 大小
+ view.setUint32(16, 16, true); // fmt chunk size
view.setUint16(20, 1, true); // PCM
- view.setUint16(22, 1, true); // 单声道
+ view.setUint16(22, 1, true); // mono
view.setUint32(24, sampleRate, true);
view.setUint32(28, sampleRate * 2, true); // byteRate = rate * blockAlign
view.setUint16(32, 2, true); // blockAlign = channels * bytesPerSample
- view.setUint16(34, 16, true); // 位深
+ view.setUint16(34, 16, true); // bit depth
writeStr(36, 'data');
view.setUint32(40, samples.length * 2, true);
@@ -159,19 +159,19 @@ function encodeWavPcm16(samples: Float32Array, sampleRate: number): ArrayBuffer
}
/**
- * Float32 PCM -> WAV Blob。
+ * Float32 PCM -> WAV Blob.
*
- * 用途:录音采集层直接得到 PCM 时生成标准 WAV,避免依赖浏览器 MediaRecorder 的容器
- * 编码与解码兼容性。
- * @param samples 单声道 Float32 PCM 采样
- * @param sampleRate 采样率
- * @returns 可播放、可上传的 WAV Blob
+ * Purpose: when the capture layer already has PCM, produce a standard WAV and avoid depending on the browser MediaRecorder's container
+ * encoding and decode compatibility.
+ * @param samples mono Float32 PCM samples
+ * @param sampleRate sample rate
+ * @returns a WAV Blob that can be played and uploaded
*/
export function pcmToWavBlob(samples: Float32Array, sampleRate: number): Blob {
return new Blob([encodeWavPcm16(samples, sampleRate)], { type: 'audio/wav' });
}
-/** ArrayBuffer → base64(分块避免超长字符串爆栈) */
+/** ArrayBuffer → base64 (chunked so a very long string does not blow the stack) */
export function arrayBufferToBase64(buffer: ArrayBuffer): string {
const bytes = new Uint8Array(buffer);
const chunk = 0x8000;
@@ -183,13 +183,13 @@ export function arrayBufferToBase64(buffer: ArrayBuffer): string {
}
/**
- * 音频 URL → 波形峰值数组(长度 buckets,值 0–1,按整段最大振幅归一)。
+ * Audio URL → waveform peak array (length buckets, values 0–1, normalized by the peak amplitude of the whole clip).
*
- * 供播放器画“真实”波形:解码后按桶取每段绝对值峰值。固定用较高分辨率解码一次,
- * 组件再按容器宽度重采样,避免窗口缩放时反复解码。解码失败(格式不支持/跨域)
- * 返回 null,调用方回退占位,不影响播放本身。
- * @param src 音频 URL(Object URL 亦可)
- * @param buckets 峰值桶数
+ * For drawing a "real" waveform in the player: after decoding, each bucket takes the peak absolute value of its slice. Decode once at a fairly high resolution,
+ * then the component resamples to the container width, so window resizes do not decode again. On decode failure (unsupported format or cross-origin)
+ * return null; the caller falls back to a placeholder and playback itself is unaffected.
+ * @param src audio URL (an Object URL is fine)
+ * @param buckets number of peak buckets
*/
export async function decodeWaveformPeaks(src: string, buckets: number): Promise<number[] | null> {
try {
@@ -222,9 +222,9 @@ export async function decodeWaveformPeaks(src: string, buckets: number): Promise
}
/**
- * 麦克风频谱可视化:AnalyserNode 逐帧输出整体音量与频谱条(命令式 rAF)。
- * @param onFrame 每帧回调(level 0–1,bars 0–1 数组)
- * @returns 停止函数(取消动画帧)
+ * Microphone spectrum visualization: AnalyserNode emits overall level and spectrum bars each frame (imperative rAF).
+ * @param onFrame per-frame callback (level 0–1, bars a 0–1 array)
+ * @returns stop function (cancels the animation frame)
*/
export function attachSpectrum(
ctx: AudioContext,
diff --git a/webdemo/frontend/src/pages/playground/utils/chatCompletion.ts b/webdemo/frontend/src/pages/playground/utils/chatCompletion.ts
index d62e00c..60e46f1 100644
--- a/webdemo/frontend/src/pages/playground/utils/chatCompletion.ts
+++ b/webdemo/frontend/src/pages/playground/utils/chatCompletion.ts
@@ -1,8 +1,8 @@
/**
- * Playground 一次补全生命周期的纯函数。
+ * Pure functions for one Playground completion lifecycle.
*
- * 用途:auth 校验、流式收尾、abort/fail 时的消息列表变换;供 useChatCompletion 与单测复用。
- * 流式 SSE 回调集合在 chatStreamCallbacks.ts。
+ * Purpose: auth checks, streaming finalization, and message-list transforms on abort/fail; shared by useChatCompletion and unit tests.
+ * The streaming SSE callback set lives in chatStreamCallbacks.ts.
*/
import type { ChatMessage } from '../types';
@@ -10,14 +10,14 @@ import { appendToMessage, applyVersion, snapshotVersion } from './messages';
import { normalizeAssistantReply } from './thinkSplit';
import { finalizeToolEvents } from './toolEvents';
-/** 未选 Key / 密钥未就绪时的统一错误文案 */
+/** Shared error copy when no key is selected or the secret is not ready */
export const COMPLETION_KEY_ERROR = '请先在左下角选择一个 API Key 以建立会话';
/**
- * 校验补全前 auth 条件;返回错误文案或 null(可继续发起请求)。
- * @param webSearch 是否联网模式
- * @param keyId 联网模式使用的 API Key ID
- * @param secret 普通模式使用的明文密钥
+ * Check auth conditions before a completion; return error copy or null (the request may proceed).
+ * @param webSearch whether web-search mode is on
+ * @param keyId API Key ID used in web-search mode
+ * @param secret plaintext secret used in normal mode
*/
export function authErrorForCompletion(
webSearch: boolean,
@@ -30,10 +30,10 @@ export function authErrorForCompletion(
}
/**
- * 正常完成:落定 streaming 字段、写入总耗时,并把当前回答快照进 versions[]。
- * @param list 当前消息列表
- * @param assistantId 目标 assistant 消息 id
- * @param startedAt performance.now() 起点
+ * Normal completion: settle streaming fields, record total elapsed time, and snapshot the current answer into versions[].
+ * @param list current message list
+ * @param assistantId target assistant message id
+ * @param startedAt performance.now() start
*/
export function finalizeCompletedMessages(
list: ChatMessage[],
@@ -60,10 +60,10 @@ export function finalizeCompletedMessages(
}
/**
- * 用户主动停止:首次生成保留 partial 正文但不写入 versions;重新生成回退到末个已完成版本。
- * @param list 当前消息列表
- * @param assistantId 目标 assistant 消息 id
- * @param startedAt performance.now() 起点
+ * User stop: the first generation keeps the partial body but does not write versions; a regeneration rolls back to the last completed version.
+ * @param list current message list
+ * @param assistantId target assistant message id
+ * @param startedAt performance.now() start
*/
export function finalizeAbortedMessages(
list: ChatMessage[],
@@ -96,11 +96,11 @@ export function finalizeAbortedMessages(
}
/**
- * 请求失败:有历史版本则回退;首次生成则在顶层标 error。
- * @param list 当前消息列表
- * @param assistantId 目标 assistant 消息 id
- * @param message 用户可见错误文案
- * @param errorCode 上游错误码
+ * Request failure: roll back when history versions exist; on the first generation, mark error on the top-level message.
+ * @param list current message list
+ * @param assistantId target assistant message id
+ * @param message user-visible error copy
+ * @param errorCode upstream error code
*/
export function finalizeFailedMessages(
list: ChatMessage[],
@@ -111,8 +111,8 @@ export function finalizeFailedMessages(
if (errorCode === 'content_policy_violation') {
return markConversationTurnContextExcluded(list, assistantId).map((item) => {
if (item.id !== assistantId) return item;
- // 输出安审撤回:正文与思考都可能已经上屏,必须一并清空后替换为中性提示,
- // 否则被撤回的内容会残留在气泡、会话历史与下一轮 messages 里。
+ // Output safety recall: body and reasoning may already be on screen, so both must be cleared and replaced with a neutral notice,
+ // otherwise the recalled content would remain in the bubble, conversation history, and the next turn's messages.
return {
...item,
content: failureMessage,
@@ -148,7 +148,7 @@ export function finalizeFailedMessages(
});
}
-/** 将当前 assistant 占位及其对应的最近用户消息标记为不可进入后续模型上下文。 */
+/** Mark the current assistant placeholder and its nearest user message as excluded from later model context. */
export function markConversationTurnContextExcluded(
list: ChatMessage[],
assistantId: string,
diff --git a/webdemo/frontend/src/pages/playground/utils/chatStatus.ts b/webdemo/frontend/src/pages/playground/utils/chatStatus.ts
index 2088ea7..ebc9501 100644
--- a/webdemo/frontend/src/pages/playground/utils/chatStatus.ts
+++ b/webdemo/frontend/src/pages/playground/utils/chatStatus.ts
@@ -1,19 +1,19 @@
/**
- * Playground 联网工具进度文案。
+ * Playground web-search tool progress copy.
*
- * 用途:把 L3 BFF 下发的 tool_status 事件映射为用户可见的短文案。
+ * Purpose: map tool_status events from the L3 BFF to short user-visible copy.
*/
import type { ToolStatusEvent } from '@/api/map/chat';
import type { SearchProgressStep, Translate } from '../types';
/**
- * 将 tool_status 事件转为 UI 状态条文案。
+ * Turn a tool_status event into status-bar copy for the UI.
*
- * 后端自带 message 时原样透传(它比前端枚举更具体);否则按工具与状态走 i18n。
- * @param status SSE tool_status 事件
- * @param t i18n 翻译函数(playground 命名空间)
- * @returns 用户可见的短文案;无可用文案时返回空串
+ * When the backend includes a message, pass it through (it is more specific than the frontend enum); otherwise use i18n by tool and status.
+ * @param status SSE tool_status event
+ * @param t i18n translate function (playground namespace)
+ * @returns short user-visible copy; an empty string when none is available
*/
export function toolStatusText(status: ToolStatusEvent, t: Translate): string {
if (status.message) return status.message;
@@ -38,16 +38,16 @@ export function toolStatusText(status: ToolStatusEvent, t: Translate): string {
}
/**
- * 将后端工具状态映射为前端过程条阶段。
+ * Map a backend tool status to a frontend process-bar phase.
*
- * 失败状态细分:reader 工具(web_extractor)失败只影响"读取网页"步骤,不应让整个搜索条
- * 标红(搜索本身已成功),否则用户会误以为"整个联网都失败"。
- * @param status SSE tool_status 事件
+ * Failure is split: a reader-tool (web_extractor) failure only affects the "read the page" step and must not turn the whole search bar
+ * red (search itself already succeeded), or the user would think the entire web search failed.
+ * @param status SSE tool_status event
*/
export function toolStatusStep(status: ToolStatusEvent): SearchProgressStep {
const isReader = status.tool === 'web_extractor' || Boolean(status.urls?.length);
if (status.status === 'failed') {
- // 读网页失败但搜索成功 → 单独阶段,不让主标题变红
+ // Page read failed but search succeeded → its own phase, so the main title does not turn red
return isReader ? 'browse_failed' : 'failed';
}
if (isReader) {
diff --git a/webdemo/frontend/src/pages/playground/utils/chatStreamCallbacks.ts b/webdemo/frontend/src/pages/playground/utils/chatStreamCallbacks.ts
index 3f85221..4051107 100644
--- a/webdemo/frontend/src/pages/playground/utils/chatStreamCallbacks.ts
+++ b/webdemo/frontend/src/pages/playground/utils/chatStreamCallbacks.ts
@@ -1,10 +1,10 @@
/**
- * Playground 流式 SSE 回调集合。
+ * Playground streaming SSE callback set.
*
- * 用途:把 content/reasoning/citations/usage/tool_status/done 六路增量收敛成对
- * `setMessages` 的补丁,并在这里持有一次补全期间的流式局部状态(播放队列、工具是否在跑、
- * 思考切分游标)。与 chatCompletion.ts 的纯列表变换分开:那半边是无状态的收尾函数,
- * 这半边是有生命周期的工厂,放一起会让 util 文件越过 300 行上限。
+ * Purpose: fold the six incremental streams content/reasoning/citations/usage/tool_status/done into patches on
+ * `setMessages`, and hold the streaming-local state for one completion (playback queue, whether a tool is running,
+ * reasoning split cursor). Kept apart from the pure list transforms in chatCompletion.ts: that side is stateless finalization,
+ * this side is a factory with a lifecycle. Putting them together would push the util file past the 300-line cap.
*/
import type { Dispatch, SetStateAction } from 'react';
@@ -16,12 +16,12 @@ import { toolStatusStep, toolStatusText } from './chatStatus';
import { createStreamTextQueue, type StreamTextKind } from './streamTextQueue';
import { upsertToolEvent } from './toolEvents';
-/** createStreamCallbacks 入参 */
+/** Arguments to createStreamCallbacks */
export interface StreamCallbackContext {
assistantId: string;
- /** 是否为联网搜索流;普通流式回答不能展示搜索过程条。 */
+ /** Whether this is a web-search stream; an ordinary streaming answer must not show the search process bar. */
webSearch: boolean;
- /** i18n 翻译函数(playground 命名空间),用于工具进度文案。 */
+ /** i18n translate function (playground namespace), used for tool progress copy. */
t: Translate;
isActive: () => boolean;
markFirstToken: () => void;
@@ -36,8 +36,8 @@ export type StreamCallbacksController = StreamCallbacks & {
};
/**
- * 构造流式 SSE 回调集合(content/reasoning/citations/usage/tool_status/done)。
- * @param ctx assistantId、首 token 埋点、完成回调与 setMessages
+ * Build the streaming SSE callback set (content/reasoning/citations/usage/tool_status/done).
+ * @param ctx assistantId, first-token metric, completion callback, and setMessages
*/
export function createStreamCallbacks(ctx: StreamCallbackContext): StreamCallbacksController {
const {
@@ -51,31 +51,31 @@ export function createStreamCallbacks(ctx: StreamCallbackContext): StreamCallbac
onModerationAnswer,
setMessages,
} = ctx;
- // 追踪工具是否仍在执行中(running 状态)。running 期间 content delta 不覆盖 searching,
- // 避免 queue 的 text flush 把正展开的面板在 content delta 到达时错误收起。
+ // Track whether a tool is still running (running status). Content deltas must not clear searching while it is running,
+ // or the queue's text flush would wrongly collapse the open panel when a content delta arrives.
let toolRunningRef = false;
/*
- 思考文本的切分游标:工具首帧到达时把它锚进事件,过程时间线据此把整块思考切成
- 「思考 → 工具 → 思考」交错的一条线。
+ Reasoning split cursor: when the first tool frame arrives, anchor it on the event. The process timeline uses it to cut the reasoning blob into
+ one interleaved line of reasoning → tool → reasoning.
- 必须在 onReasoning 回调里累加,不能改成读 prev.reasoning?.length:思考增量要过
- createStreamTextQueue 的 16ms 节流,而 onToolStatus 是立即 setMessages,读 prev 会拿到
- 滞后于真实进度的长度,切点会系统性偏前。这里累加的是"已 enqueue 总量",与 SSE 到达
- 顺序严格一致,不受播放队列影响。
+ It must be accumulated inside the onReasoning callback, not by reading prev.reasoning?.length: reasoning increments pass through
+ createStreamTextQueue's 16ms throttle, while onToolStatus calls setMessages immediately. Reading prev would see a length that lags
+ the real progress, and split points would systematically sit too early. What is accumulated here is the "total already enqueued", strictly in SSE arrival
+ order, unaffected by the playback queue.
- 这个"抢跑"由渲染侧兜住:onToolStatus 不过播放队列,工具事件会比它上方那段思考文字
- "播完"早几百毫秒到;buildProcessTimeline 的 holdUnplayed 因此把切点还没播到的工具行
- 押着不出。不改成让工具事件也排进同一个队列——那会把 searching 等状态反馈整体推迟。
+ The render side absorbs this running ahead: onToolStatus does not go through the playback queue, so a tool event arrives a few hundred milliseconds before the reasoning above it
+ finishes "playing"; buildProcessTimeline's holdUnplayed therefore holds back tool rows whose split point has not been played yet.
+ Do not also enqueue tool events on that same queue — that would delay status feedback such as searching as a whole.
*/
let enqueuedReasoningChars = 0;
const queue = createStreamTextQueue((kind: StreamTextKind, delta: string) => {
if (!isActive()) return;
markFirstToken();
const deltaPatch = kind === 'content' ? { contentDelta: delta } : { reasoningDelta: delta };
- // 仅在工具已执行完(非 running)时才由 text flush 收 searching 状态;
- // 工具执行中(running)时 searching 状态由 onToolStatus 全权管理。
- // 这里不再要求"曾有过工具活动":开了联网但模型压根没调工具时,正文一开始生成就必须
- // 把 searching 收掉,否则进度卡片会一路转圈到流结束。
+ // Only let the text flush clear searching once the tool has finished (not running);
+ // while a tool is running, searching is owned entirely by onToolStatus.
+ // Do not also require "there was tool activity": if web search is on but the model never calls a tool, searching must be cleared as soon as the body starts,
+ // or the progress card keeps spinning until the stream ends.
const progressPatch = webSearch && !toolRunningRef ? { searching: false } : {};
setMessages((prev) => appendToMessage(prev, assistantId, { ...deltaPatch, ...progressPatch }));
});
@@ -101,7 +101,7 @@ export function createStreamCallbacks(ctx: StreamCallbackContext): StreamCallbac
onToolStatus: (status: ToolStatusEvent) => {
if (!isActive()) return;
toolRunningRef = status.status === 'running';
- // 只按工具名判定"在读网页":带 urls 就算读页会把将来任何附带地址的工具误报成浏览。
+ // Treat "reading a page" by tool name only: counting any tool that carries urls as a page read would misreport any future tool that happens to include an address.
const readingPages = isReaderTool(status.tool);
const resultCount =
status.result_count !== undefined ? status.result_count : status.urls?.length;
@@ -141,7 +141,7 @@ export function createStreamCallbacks(ctx: StreamCallbackContext): StreamCallbac
};
}
-/** 取指定 assistant 的当前工具事件,供函数式状态更新复用。 */
+/** Read the current tool events for a given assistant, reused by functional state updates. */
function prevToolEvents(list: ChatMessage[], assistantId: string): ChatMessage['toolEvents'] {
return list.find((message) => message.id === assistantId)?.toolEvents;
}
diff --git a/webdemo/frontend/src/pages/playground/utils/citationMarkers.ts b/webdemo/frontend/src/pages/playground/utils/citationMarkers.ts
index e39d4a9..7fd5c24 100644
--- a/webdemo/frontend/src/pages/playground/utils/citationMarkers.ts
+++ b/webdemo/frontend/src/pages/playground/utils/citationMarkers.ts
@@ -1,57 +1,57 @@
/**
- * 引用角标 → Markdown 链接的预处理。
+ * Preprocess citation markers into Markdown links.
*
- * 用途:模型被提示"在论断后紧跟 `[ref_N]` 角标",实际输出里还会混进裸 `[N]`(中文模型的
- * 普遍先验)。在 Markdown 解析前把两种角标都改写成指向对应来源的链接,正文渲染侧就只需
- * 处理 `a` 一种情况,无需在 p/li/td 的 children 里遍历文本节点。
+ * Purpose: the model is prompted to follow a claim with a `[ref_N]` marker, but real output also mixes in bare `[N]` (a common prior of Chinese models).
+ * Rewrite both kinds of marker into links to the matching source before Markdown parsing, so body rendering only has to
+ * handle an `a`, with no walk of text nodes inside p/li/td children.
*
- * 编号一律按后端下发的 ref 查,而不是按 citations 数组下标:数组是跨轮累积并去重的,
- * 后端每轮又会按相关性重排结果,两者只在单轮搜索时碰巧对齐。
+ * Numbers are always looked up by the ref issued by the backend, not by the citations array index: the array accumulates and dedupes across turns,
+ * and each turn the backend reorders results by relevance. The two line up only by chance on a single-turn search.
*/
import type { Citation } from '../types';
import { safeCitationHref } from './citations';
/**
- * 代码区段:围栏代码块与行内代码。
+ * Code spans: fenced code blocks and inline code.
*
- * 围栏用 ```` ```…``` ```` / `~~~…~~~`,收尾允许命中字符串结尾——流式期间围栏尚未闭合时,
- * 应当把剩余全文都视为代码,避免代码里的 `[1]` 被改写成链接。
+ * Fences use ```` ```…``` ```` / `~~~…~~~`, and the close may hit the end of the string — while streaming, before the fence closes,
+ * the rest of the text must be treated as code so a `[1]` inside code is not rewritten into a link.
*/
const CODE_SEGMENT = /(```[\s\S]*?(?:```|$)|~~~[\s\S]*?(?:~~~|$)|`[^`\n]*`)/g;
/**
- * 引用角标:`[ref_N]`(提示词要求的形态)或裸 `[N]`(模型不听话时的兜底)。
+ * Citation markers: `[ref_N]` (the form the prompt requires) or a bare `[N]` (the fallback when the model does not follow instructions).
*
- * 一个方括号里允许多个编号(`[ref_3, ref_5]`):提示词只要求「论断后紧跟角标」,从没规定
- * 一处只能引一个来源,模型把多来源合写进一个方括号是常态。不认这种形态的代价不只是少个
- * 链接——残留的裸角标会掉进裸数学识别,`ref_3, ref_5` 正好满足下标特征,方括号被当成公式
- * 定界符吃掉,正文里只剩一串斜体(数学侧的兜底见 math-katex 的 isCitationMarker)。
+ * One pair of brackets may hold several numbers (`[ref_3, ref_5]`): the prompt only requires "a marker right after the claim" and never says
+ * a claim may cite only one source, so the model often writes several sources into one pair of brackets. Missing this form costs more than a
+ * link — a leftover bare marker falls into bare-math recognition, `ref_3, ref_5` exactly matches the subscript pattern, the brackets are eaten as formula
+ * delimiters, and the body is left with a run of italics (the math-side fallback is isCitationMarker in math-katex).
*
- * 位数放到 3 与后端 hostedRefMarkerRe 对齐;放宽不会增加误伤,因为编号必须能在
- * ref 表里查到才改写(见 resolveCitation),查不到的一律原样留着。
- * 半截的 `[1` 天然不匹配,流式下无需额外防御。
+ * The width of 3 digits matches the backend hostedRefMarkerRe; widening it does not add false hits, because a number is rewritten only when it can be
+ * found in the ref table (see resolveCitation), and anything not found is left as-is.
+ * A half-written `[1` naturally does not match, so streaming needs no extra defense.
*/
const CITATION_MARKER = /\[(?:ref_)?\d{1,3}(?:\s*[,,、;;]\s*(?:ref_)?\d{1,3})*\]/g;
-/** 从角标内部逐个取编号,顺序与模型书写顺序一致。 */
+/** Take numbers one by one from inside a marker, in the order the model wrote them. */
const MARKER_NUMBER = /(?:ref_)?(\d{1,3})/g;
-/** 紧挨角标左侧时说明这是下标取值(如 `arr[1]`)而非引用,不应改写。 */
+/** A character immediately left of the marker means this is an index lookup (such as `arr[1]`), not a citation, and must not be rewritten. */
const IDENTIFIER_CHAR = /[A-Za-z0-9_$\]]/;
-/** 左侧紧邻的同形角标,用于把 `[1][2]` 这类连续角标当成一串整体判定归属。 */
+/** A same-shaped marker immediately to the left, used to treat a run such as `[1][2]` as one sequence when deciding what it belongs to. */
const TRAILING_MARKER = /\[(?:ref_)?\d{1,3}(?:\s*[,,、;;]\s*(?:ref_)?\d{1,3})*\]$/;
/**
- * 把正文中的引用角标改写为指向来源的 Markdown 链接。
+ * Rewrite citation markers in the body into Markdown links that point at sources.
*
- * 仅在编号能查到来源时改写,因此流式期间来源尚未到达的角标会保持原样,
- * 等来源送达后的下一次渲染再变成链接。
+ * Rewrite only when the number can be resolved to a source, so during streaming a marker whose source has not arrived yet stays as-is,
+ * and becomes a link on the next render after the source arrives.
*
- * @param markdown 模型输出的 Markdown 原文
- * @param citations 本轮回答已收到的来源
- * @returns 角标已替换为 Markdown 链接的文本;无来源时原样返回
+ * @param markdown original Markdown from the model
+ * @param citations sources already received for this answer
+ * @returns text with markers replaced by Markdown links; returned as-is when there are no sources
*/
export function linkifyCitationMarkers(markdown: string, citations: Citation[]): string {
if (!markdown || citations.length === 0) return markdown;
@@ -62,7 +62,7 @@ export function linkifyCitationMarkers(markdown: string, citations: Citation[]):
if (citation.ref && !byRef.has(citation.ref)) byRef.set(citation.ref, citation);
}
- // 按代码区段切分:split 带捕获组时,奇数下标即分隔符本身(代码),保持原样不动。
+ // Split on code segments: when split keeps the capture group, odd indexes are the separator itself (code) and stay untouched.
return markdown
.split(CODE_SEGMENT)
.map((segment, index) =>
@@ -72,11 +72,11 @@ export function linkifyCitationMarkers(markdown: string, citations: Citation[]):
}
/**
- * 按角标编号找对应来源。
+ * Find the source for a marker number.
*
- * 后端一旦下发过 ref,编号就只认 ref 表:查不到说明模型编了个不存在的号,
- * 此时宁可留着裸文本,也不能退回数组下标——那恰好会把无效角标指向一条无关来源。
- * 整批都没有 ref 才说明对接的是老后端,此时数组下标是唯一可用的口径。
+ * Once the backend has issued a ref, numbers are resolved only against the ref table: a miss means the model invented a number that does not exist,
+ * and it is better to leave the bare text than to fall back to the array index — that would point the invalid marker at an unrelated source.
+ * Only when the whole batch has no ref are we talking to an old backend, and then the array index is the only usable measure.
*/
function resolveCitation(
citations: Citation[],
@@ -87,7 +87,7 @@ function resolveCitation(
return citations[index - 1];
}
-/** 改写单个非代码区段中的角标。 */
+/** Rewrite markers in a single non-code segment. */
function linkifySegment(
segment: string,
citations: Citation[],
@@ -95,16 +95,16 @@ function linkifySegment(
): string {
return segment.replace(CITATION_MARKER, (match: string, offset: number) => {
const before = chainLeadingChar(segment, offset);
- // `![1]` 是图片语法
+ // `![1]` is image syntax
if (before === '!') return match;
- // `arr[1]` 是下标取值。这道判据只对裸角标生效:`ref_` 前缀本身已经消歧,而英文正文里
- // 「论断紧跟角标」必然写成 blue[ref_1] 这种形状,按标识符一刀切会把英文回答的角标整批吞掉。
+ // `arr[1]` is an index lookup. This check applies only to bare markers: the `ref_` prefix already disambiguates, and in English body text
+ // "the marker follows the claim" is necessarily written as blue[ref_1]. Cutting on an identifier would swallow every marker in an English answer.
if (!match.startsWith('[ref_') && before !== undefined && IDENTIFIER_CHAR.test(before)) {
return match;
}
const after = segment.slice(offset + match.length);
- // `[1](…)` 已是链接,`[1]: …` 是链接引用定义,都不能再包一层
+ // `[1](…)` is already a link, and `[1]: …` is a link reference definition; neither can be wrapped again
if (after.startsWith('(') || after.startsWith(':')) return match;
return linkifyMarker(match, citations, byRef);
@@ -112,15 +112,15 @@ function linkifySegment(
}
/**
- * 把一个角标改写成相邻的 Markdown 链接,`[ref_3, ref_5]` 这类合写会展开成多个。
+ * Rewrite one marker into adjacent Markdown links. A grouped form such as `[ref_3, ref_5]` expands into several.
*
- * 任一编号查不到来源、或地址不可安全嵌入就整体放弃:半改写会把 `[ref_3, ref_5]` 变成
- * 「一个链接 + 一截裸文本」,读者无从判断后半截是没搜到还是渲染坏了,不如整条留作原文。
+ * If any number cannot be resolved to a source, or the address cannot be embedded safely, give up the whole marker: a partial rewrite would turn `[ref_3, ref_5]` into
+ * "one link + a trailing bare text fragment", and the reader could not tell whether the trailing part was not found or failed to render. Leaving the whole thing as the original is better.
*
- * @param match 匹配到的完整角标文本
- * @param citations 本轮回答已收到的来源
- * @param byRef 按后端下发 ref 建立的来源索引
- * @returns 改写后的链接串;任一编号不可解析时原样返回
+ * @param match the full marker text that matched
+ * @param citations sources already received for this answer
+ * @param byRef source index built from refs issued by the backend
+ * @returns the rewritten link string; the original when any number cannot be resolved
*/
function linkifyMarker(match: string, citations: Citation[], byRef: Map<number, Citation>): string {
const links: string[] = [];
@@ -136,15 +136,15 @@ function linkifyMarker(match: string, citations: Citation[], byRef: Map<number,
}
/**
- * 取角标所在「连续角标串」左侧第一个字符。
+ * Take the first character to the left of the "contiguous marker run" that contains this marker.
*
- * `]` 本身在 IDENTIFIER_CHAR 里(为挡住 `arr[1]`),若直接看前一个字符,`[1][2]` 的第二个角标
- * 会被误判成下标链。先把左侧连续的同形角标逐个剥掉,再用串首前的字符决定整串是引用还是下标:
- * `两处都提到[1][2]` 剥到「到」→ 是引用;`arr[1][2]` 剥到「r」→ 是下标。
+ * `]` itself is in IDENTIFIER_CHAR (to block `arr[1]`). Looking at the previous character directly would misread the second marker of `[1][2]`
+ * as an index chain. Peel off contiguous same-shaped markers on the left first, then use the character before the run to decide whether the whole run is a citation or an index:
+ * a run preceded by a non-identifier character peels back to that character → a citation; `arr[1][2]` peels back to "r" → an index.
*
- * @param segment 当前非代码区段
- * @param offset 本次匹配在区段中的起始位置
- * @returns 串首左侧字符;角标位于区段开头时返回 undefined
+ * @param segment the current non-code segment
+ * @param offset start position of this match inside the segment
+ * @returns the character to the left of the run start; undefined when the marker is at the start of the segment
*/
function chainLeadingChar(segment: string, offset: number): string | undefined {
let start = offset;
@@ -157,8 +157,8 @@ function chainLeadingChar(segment: string, offset: number): string | undefined {
}
/**
- * 生成可安全嵌入 Markdown 链接的目标地址。
- * 含空白或括号的地址必须用尖括号包裹,否则 Markdown 解析会在第一个 `)` 处截断。
+ * Build a target address that can be embedded safely in a Markdown link.
+ * An address that contains whitespace or brackets must be wrapped in angle brackets, or Markdown parsing truncates at the first `)`.
*/
function markdownDestination(url: string): string | undefined {
if (!safeCitationHref(url)) return undefined;
diff --git a/webdemo/frontend/src/pages/playground/utils/citations.ts b/webdemo/frontend/src/pages/playground/utils/citations.ts
index 54ae0d5..ca46132 100644
--- a/webdemo/frontend/src/pages/playground/utils/citations.ts
+++ b/webdemo/frontend/src/pages/playground/utils/citations.ts
@@ -1,14 +1,14 @@
/**
- * 联网引用来源的 URL 处理与跳转工具。
+ * URL handling and navigation helpers for web-search citation sources.
*
- * 用途:域名/favicon 展示回退、跳转地址白名单校验、模型链接与来源数据的匹配键,
- * 以及来源链接统一的新窗口打开行为,供过程区、行内角标与来源列表复用。
+ * Purpose: domain and favicon display fallback, allowlist checks on navigation URLs, match keys between model links and source data,
+ * and the shared new-window behavior for source links, reused by the process area, inline markers, and the source list.
*/
/**
- * 从 URL 取域名作为无标题引用的回退展示。
- * @param url 来源地址
- * @returns 去除 www 前缀的域名;无效地址回退原串
+ * Take the domain from a URL as the fallback label for a citation with no title.
+ * @param url source URL
+ * @returns domain without a www prefix; invalid URLs fall back to the original string
*/
export function citationDomain(url: string): string {
try {
@@ -19,9 +19,9 @@ export function citationDomain(url: string): string {
}
/**
- * 构造来源站点自己的 favicon 地址,避免引入第三方图标代理。
- * @param url 来源地址
- * @returns favicon 地址;无效地址返回 undefined
+ * Build the source site's own favicon URL, avoiding a third-party icon proxy.
+ * @param url source URL
+ * @returns favicon URL; undefined for an invalid URL
*/
export function citationFavicon(url: string): string | undefined {
try {
@@ -32,9 +32,9 @@ export function citationFavicon(url: string): string | undefined {
}
/**
- * 校验来源跳转地址,仅允许 HTTP(S)。
- * @param url 来源地址
- * @returns 可安全打开的地址;非法协议返回 undefined
+ * Check a source navigation URL, allowing only HTTP(S).
+ * @param url source URL
+ * @returns an address that can be opened safely; undefined for an illegal scheme
*/
export function safeCitationHref(url: string): string | undefined {
try {
@@ -46,9 +46,9 @@ export function safeCitationHref(url: string): string | undefined {
}
/**
- * 生成用于匹配模型 Markdown 链接与来源数据的稳定键。
- * @param url 来源地址
- * @returns 忽略 hash、末尾斜杠和查询参数顺序差异的 URL 键
+ * Build a stable key for matching a model Markdown link to source data.
+ * @param url source URL
+ * @returns a URL key that ignores the hash, a trailing slash, and query-parameter order
*/
export function citationURLKey(url: string): string {
try {
@@ -63,29 +63,29 @@ export function citationURLKey(url: string): string {
}
/**
- * 取一条来源对外展示的角标编号。
+ * Take the citation-marker number a source shows externally.
*
- * 正文角标、来源面板序号、独占一行的来源行三处此前各自用数组下标 +1 算编号,
- * 而数组是跨轮累积并按 URL 去重的,与后端每轮重排后的注入顺序并不对应——
- * 多轮搜索时三处算出的数字会一起指错。改为统一消费后端下发的 ref,
- * 编号只剩一个来源(后端 hostedSourceRegistry)。
+ * Body markers, source-panel numbers, and a source line on its own used to each compute the number as array index + 1,
+ * but the array accumulates across turns and is deduped by URL, and does not match the injection order after the backend reorders each turn —
+ * on a multi-turn search the three places would all point at the wrong number. They now all consume the ref issued by the backend,
+ * so the number has only one source (the backend hostedSourceRegistry).
*
- * @param citation 来源
- * @param fallbackIndex 数组下标(0 起),仅在后端未下发 ref 时用于回退
- * @returns 展示用编号(1 起)
+ * @param citation source
+ * @param fallbackIndex array index (0-based), used only when the backend did not issue a ref
+ * @returns the display number (1-based)
*/
export function citationDisplayIndex(citation: { ref?: number }, fallbackIndex: number): number {
return citation.ref && citation.ref > 0 ? citation.ref : fallbackIndex + 1;
}
/**
- * 判断点击是否应交回浏览器原生处理。
+ * Whether the click should be handed back to the browser's native handling.
*
- * 修饰键、鼠标中键以及已被上层拦截的事件都保留原生语义("在新标签页打开"等),
- * 否则编程式 window.open 会把这些操作统一降级为普通跳转。
+ * Modifier keys, the middle mouse button, and events already intercepted by an upper layer keep their native meaning (such as "open in a new tab"),
+ * or a programmatic window.open would downgrade those actions to an ordinary navigation.
*
- * @param event 鼠标点击事件(只取判定所需的最小字段)
- * @returns true 表示不应接管本次点击
+ * @param event mouse click event (only the minimum fields needed for the decision)
+ * @returns true when this click should not be taken over
*/
export function isNativeOpenIntent(event: {
metaKey: boolean;
@@ -100,18 +100,18 @@ export function isNativeOpenIntent(event: {
}
/**
- * 编程式新窗口打开来源。
+ * Open a source in a new window programmatically.
*
- * 兜底处理:
- * - 部分浏览器对隐式 target=_blank 的拦截;
- * - 在被 Tooltip 等中间件包裹时,preventDefault 后用同步 window.open 让点击总有可见反馈。
+ * Fallbacks:
+ * - some browsers block an implicit target=_blank;
+ * - when wrapped by middleware such as a Tooltip, a synchronous window.open after preventDefault makes sure the click always has visible feedback.
*
- * @param href 来源地址
+ * @param href source URL
*/
export function openCitationWindow(href: string): void {
const popup = window.open('about:blank', '_blank', 'noopener,noreferrer');
if (!popup) {
- // 浏览器拦截了弹窗 → 退化为同窗口跳转,至少保证用户能到达目标页
+ // The browser blocked the popup → fall back to same-window navigation, so the user can at least reach the target page
window.location.assign(href);
return;
}
diff --git a/webdemo/frontend/src/pages/playground/utils/contextBudget.ts b/webdemo/frontend/src/pages/playground/utils/contextBudget.ts
index 13af8ed..36e4b54 100644
--- a/webdemo/frontend/src/pages/playground/utils/contextBudget.ts
+++ b/webdemo/frontend/src/pages/playground/utils/contextBudget.ts
@@ -1,8 +1,8 @@
/**
- * 体验中心上下文预算。
+ * Experience-center context budget.
*
- * 用途:依据模型目录声明的上下文窗口,为输出和安全余量预留空间;前端仅做保守估算与
- * 历史裁剪,不参与用量计算或计费。真实 token 用量仍以 LIS 返回的 usage 为准。
+ * Purpose: from the context window declared in the model catalog, reserve room for output and a safety margin; the frontend only makes a conservative estimate and
+ * trims history. It does not take part in usage calculation or billing. Real token usage still comes from the usage returned by LIS.
*/
import type { ChatRequestMessage } from '@/api/map/chat';
@@ -20,40 +20,40 @@ const ATTACHMENT_TOKEN_ESTIMATES: Record<AttachmentKind, number> = {
};
/**
- * 上下文窗口管理能力已实现,当前按产品策略暂不对用户启用。
- * 启用后会展示占用提示,并在发送前按完整问答轮次裁剪历史。
+ * Context-window management is implemented, and is currently left off for users by product policy.
+ * Once enabled it shows an occupancy hint and trims history by complete question-answer turns before send.
*/
export const CONTEXT_WINDOW_MANAGEMENT_ENABLED = false;
export interface ContextWindowOptions {
- /** 模型目录中的 context_window,0 表示未声明限制。 */
+ /** context_window from the model catalog; 0 means no declared limit. */
contextWindow: number;
- /** 模型目录中的 max_output_tokens。 */
+ /** max_output_tokens from the model catalog. */
modelMaxOutputTokens: number;
- /** 用户在参数面板设置的 max_tokens;大于 0 时优先使用。 */
+ /** max_tokens set in the parameter panel; used first when greater than 0. */
requestedMaxOutputTokens?: number;
- /** 可选系统提示,始终保留在请求开头。 */
+ /** Optional system prompt, always kept at the start of the request. */
systemPrompt?: string;
}
export interface ContextWindowPlan {
requestMessages: ChatRequestMessage[];
- /** 文本与附件的保守估算值,不是模型 tokenizer 的真值。 */
+ /** Conservative estimate for text and attachments, not the model's real tokenizer count. */
estimatedInputTokens: number;
- /** 未声明窗口时为 null,代表不做前端裁剪。 */
+ /** null when no window is declared, meaning the frontend does not trim. */
inputBudgetTokens: number | null;
reservedOutputTokens: number;
safetyMarginTokens: number;
trimmedMessageCount: number;
- /** 系统提示和最近一轮本身已超过输入预算,不能安全发送。 */
+ /** The system prompt and the latest turn alone already exceed the input budget, so the request cannot be sent safely. */
isOverBudget: boolean;
}
/**
- * 将消息构造成满足上下文窗口的请求计划。
+ * Build a request plan that fits the context window.
*
- * 裁剪只发生在最后一条手动清除上下文的分隔线之后;优先保留系统提示、当前提问和
- * 最近完整问答轮次。若当前提问本身超出预算,返回 isOverBudget 供调用方阻止请求。
+ * Trimming happens only after the last manual clear-context divider; the system prompt, the current question, and
+ * the most recent complete question-answer turns are kept first. If the current question itself exceeds the budget, return isOverBudget so the caller can block the request.
*/
export function buildContextWindowPlan(
list: ChatMessage[],
@@ -134,7 +134,7 @@ export function buildContextWindowPlan(
};
}
-/** 估算文本 token;中文及其他非 ASCII 字符按更保守的单字一 token 估算。 */
+/** Estimate text tokens; Chinese and other non-ASCII characters use a more conservative one-token-per-character estimate. */
export function estimateTextTokens(text: string): number {
if (!text) return 0;
let asciiCharacters = 0;
diff --git a/webdemo/frontend/src/pages/playground/utils/conversationAutosaveQueue.ts b/webdemo/frontend/src/pages/playground/utils/conversationAutosaveQueue.ts
index 40d39dc..6344cc5 100644
--- a/webdemo/frontend/src/pages/playground/utils/conversationAutosaveQueue.ts
+++ b/webdemo/frontend/src/pages/playground/utils/conversationAutosaveQueue.ts
@@ -1,8 +1,8 @@
/**
- * Playground 会话自动保存串行队列。
+ * Serial queue for Playground conversation autosave.
*
- * 用途:隔离 React 生命周期与异步写入状态,保证同一会话只串行保存最新快照,
- * 并在网络失败时指数退避重试,避免旧写入覆盖新内容。
+ * Purpose: isolate React lifecycle from async write state, so one conversation saves only the latest snapshot serially,
+ * and retries with exponential backoff on network failure, so an older write cannot overwrite newer content.
*/
import type { MapSaveConversationInput } from '@/api/map';
@@ -36,8 +36,8 @@ export interface ConversationAutosaveInput {
}
/**
- * 串行保存队列。
- * React hook 只负责把最新消息转换成 input,本类负责创建会话、写入、重试与代际隔离。
+ * Serial save queue.
+ * The React hook only turns the latest messages into input; this class creates the conversation, writes, retries, and isolates generations.
*/
export class ConversationAutosaveQueue {
private activeConversationId?: string;
@@ -59,17 +59,17 @@ export class ConversationAutosaveQueue {
this.activeConversationId = activeConversationId;
}
- /** 更新 React 侧最新 API 回调,避免队列捕获过期 mutation。 */
+ /** Update the latest API callbacks on the React side so the queue does not capture a stale mutation. */
updateHandlers(handlers: ConversationAutosaveHandlers): void {
this.handlers = handlers;
}
- /** 同步当前活动会话 ID。 */
+ /** Sync the active conversation ID. */
setActiveConversationId(id?: string): void {
this.activeConversationId = id;
}
- /** 入列最新快照;相同内容不重复写入。 */
+ /** Enqueue the latest snapshot; identical content is not written again. */
enqueue(input: ConversationAutosaveInput): void {
if (input.signature === this.savedSignature) return;
if (this.latest?.generation === this.generation && this.latest.signature === input.signature) {
@@ -86,7 +86,7 @@ export class ConversationAutosaveQueue {
void this.drain();
}
- /** 写入仅供刷新恢复的最新草稿;允许比服务端快照多出尚未完成的流式内容。 */
+ /** Write the latest draft for refresh recovery only; it may contain unfinished streaming content beyond the server snapshot. */
updateDraft(input: ConversationAutosaveInput, interrupted: boolean): void {
const snapshot: DraftSnapshot = {
...input,
@@ -108,7 +108,7 @@ export class ConversationAutosaveQueue {
}, DRAFT_WRITE_INTERVAL_MS - elapsed);
}
- /** 页面刷新/隐藏前同步写入内存中的最后一份草稿。 */
+ /** Synchronously write the last in-memory draft before the page refreshes or hides. */
flushDraft(): void {
if (!this.latestDraft?.ownerId) return;
if (this.draftTimer !== undefined) {
@@ -124,7 +124,7 @@ export class ConversationAutosaveQueue {
this.lastDraftWriteAt = Date.now();
}
- /** 标记服务端已经持久化的消息签名,并清理对应用户草稿。 */
+ /** Mark the signature of messages the server has already persisted, and clear the matching user draft. */
markPersisted(signature: string, ownerId?: string): void {
this.savedSignature = signature;
this.queued = undefined;
@@ -137,7 +137,7 @@ export class ConversationAutosaveQueue {
}
}
- /** 开始新会话或切换账号时废弃当前代际,旧请求完成后不能影响新会话。 */
+ /** Starting a new conversation or switching accounts discards the current generation; a finished old request must not affect the new conversation. */
reset(ownerId?: string): void {
this.generation += 1;
this.activeConversationId = undefined;
@@ -150,7 +150,7 @@ export class ConversationAutosaveQueue {
if (ownerId) clearConversationDraft(ownerId);
}
- /** 组件卸载时停止后续重试。 */
+ /** Stop further retries when the component unmounts. */
dispose(): void {
this.flushDraft();
this.disposed = true;
@@ -158,12 +158,12 @@ export class ConversationAutosaveQueue {
this.clearDraftTimer();
}
- /** React StrictMode 会先模拟卸载再重新挂载;重新启用同一队列实例。 */
+ /** React StrictMode simulates unmount and then remounts; re-enable the same queue instance. */
activate(): void {
this.disposed = false;
}
- /** 串行排空队列;写入期间的新快照只保留最新一份。 */
+ /** Drain the queue serially; while a write is in flight, keep only the latest new snapshot. */
private async drain(): Promise<void> {
if (this.draining || this.disposed) return;
this.draining = true;
@@ -196,7 +196,7 @@ export class ConversationAutosaveQueue {
}
}
- /** 已有会话直接复用;首次保存则创建并立即把 ID 通知 React/URL。 */
+ /** Reuse an existing conversation; on the first save, create one and notify React/URL of the ID immediately. */
private async resolveConversationId(snapshot: QueueSnapshot): Promise<string> {
if (this.activeConversationId) return this.activeConversationId;
const conversation = await this.handlers.createConversation({
@@ -218,7 +218,7 @@ export class ConversationAutosaveQueue {
return conversation.id;
}
- /** 最终快照失败后按 1s、2s、4s... 最长 30s 自动重试。 */
+ /** After a final snapshot fails, retry automatically at 1s, 2s, 4s, ... up to 30s. */
private scheduleRetry(snapshot: QueueSnapshot): void {
if (this.disposed) return;
this.queued = { ...snapshot, retryCount: snapshot.retryCount + 1 };
@@ -229,14 +229,14 @@ export class ConversationAutosaveQueue {
}, delay);
}
- /** 清理尚未触发的重试定时器。 */
+ /** Clear a retry timer that has not fired yet. */
private clearRetryTimer(): void {
if (this.retryTimer === undefined) return;
window.clearTimeout(this.retryTimer);
this.retryTimer = undefined;
}
- /** 清理尚未触发的草稿合并写定时器。 */
+ /** Clear a draft coalesced-write timer that has not fired yet. */
private clearDraftTimer(): void {
if (this.draftTimer === undefined) return;
window.clearTimeout(this.draftTimer);
diff --git a/webdemo/frontend/src/pages/playground/utils/conversationDraft.ts b/webdemo/frontend/src/pages/playground/utils/conversationDraft.ts
index 8b9caa3..b05018c 100644
--- a/webdemo/frontend/src/pages/playground/utils/conversationDraft.ts
+++ b/webdemo/frontend/src/pages/playground/utils/conversationDraft.ts
@@ -1,8 +1,8 @@
/**
- * Playground 当前会话的同标签页临时草稿。
+ * Same-tab temporary draft of the current Playground conversation.
*
- * 用途:在服务端自动保存尚未完成时为刷新提供兜底。仅保存对话保存请求体,
- * 不包含 API Key、Authorization 或附件 Base64;关闭标签页后由 sessionStorage 自动清理。
+ * Purpose: a refresh fallback while server autosave has not finished. Only the conversation save request body is stored,
+ * with no API Key, Authorization, or attachment Base64; sessionStorage clears it when the tab closes.
*/
import type { MapSaveConversationInput } from '@/api/map';
@@ -23,7 +23,7 @@ export interface ConversationDraft {
payload: MapSaveConversationInput;
}
-/** 读取仍在有效期内的当前会话草稿;损坏或过期数据会被清理。 */
+/** Read the current conversation draft if it is still within its lifetime; corrupt or expired data is cleared. */
export function readConversationDraft(
ownerId: string,
storage: Storage = window.sessionStorage,
@@ -62,7 +62,7 @@ export function readConversationDraft(
}
}
-/** 覆盖保存最新待持久化快照;浏览器容量不足时静默降级为仅服务端自动保存。 */
+/** Overwrite with the latest snapshot waiting to be persisted; if the browser is out of space, silently fall back to server autosave only. */
export function writeConversationDraft(
ownerId: string,
draft: Omit<ConversationDraft, 'version' | 'updatedAt'>,
@@ -78,11 +78,11 @@ export function writeConversationDraft(
} satisfies ConversationDraft),
);
} catch {
- // sessionStorage 是刷新兜底,不得因容量或隐私模式限制阻断正常对话。
+ // sessionStorage is a refresh fallback and must not block a normal conversation because of quota or private-mode limits.
}
}
-/** 清理当前标签页的会话草稿。 */
+/** Clear the conversation draft for the current tab. */
export function clearConversationDraft(
ownerId: string,
storage: Storage = window.sessionStorage,
@@ -90,21 +90,21 @@ export function clearConversationDraft(
removeDraft(draftKey(ownerId), storage);
}
-/** 安全删除草稿;部分隐私模式下 Storage 的读取和删除都可能抛错。 */
+/** Delete the draft safely; in some private modes both reading and deleting Storage can throw. */
function removeDraft(key: string, storage: Storage): void {
try {
storage.removeItem(key);
} catch {
- // 清理失败不影响服务端已完成的持久化结果。
+ // A failed clear does not affect a persist that the server has already finished.
}
}
-/** 按用户隔离同标签页草稿,避免同一浏览器切换账号时恢复前一账号内容。 */
+/** Isolate same-tab drafts by user, so switching accounts in the same browser does not restore the previous account. */
function draftKey(ownerId: string): string {
return `${DRAFT_KEY_PREFIX}:${ownerId}`;
}
-/** 校验草稿请求体的最小结构,避免损坏的 sessionStorage 数据进入消息恢复流程。 */
+/** Check the minimum shape of a draft request body, so corrupt sessionStorage data does not enter message restore. */
function isSavePayload(value: unknown): value is MapSaveConversationInput {
if (!isRecord(value) || !Array.isArray(value.messages)) return false;
if (value.title !== undefined && typeof value.title !== 'string') return false;
@@ -112,7 +112,7 @@ function isSavePayload(value: unknown): value is MapSaveConversationInput {
return value.messages.every(isSaveMessage);
}
-/** 校验单条保存消息及恢复流程会遍历的数组字段。 */
+/** Check one saved message and the array fields the restore flow walks. */
function isSaveMessage(value: unknown): boolean {
if (!isRecord(value) || !MESSAGE_ROLES.has(String(value.role))) return false;
if (typeof value.content !== 'string') return false;
@@ -125,7 +125,7 @@ function isSaveMessage(value: unknown): boolean {
return true;
}
-/** 草稿附件只允许远端元数据,明确拒绝本地 dataUrl/Base64。 */
+/** A draft attachment may contain only remote metadata; a local dataUrl/Base64 is explicitly rejected. */
function isAttachment(value: unknown): boolean {
if (!isRecord(value)) return false;
return (
@@ -138,12 +138,12 @@ function isAttachment(value: unknown): boolean {
);
}
-/** 判断值是否为对象数组;具体可选字段继续由消息转换函数防御性读取。 */
+/** Whether the value is an array of objects; optional fields continue to be read defensively by the message conversion functions. */
function isObjectArray(value: unknown): boolean {
return Array.isArray(value) && value.every(isRecord);
}
-/** unknown 对象收窄。 */
+/** Narrow an unknown object. */
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
diff --git a/webdemo/frontend/src/pages/playground/utils/conversations.ts b/webdemo/frontend/src/pages/playground/utils/conversations.ts
index fdc1f79..3b1ec6f 100644
--- a/webdemo/frontend/src/pages/playground/utils/conversations.ts
+++ b/webdemo/frontend/src/pages/playground/utils/conversations.ts
@@ -1,8 +1,8 @@
/**
- * 历史对话存储形态 ↔ 前端 ChatMessage 的互转纯函数。
+ * Pure functions converting stored conversation history ↔ frontend ChatMessage.
*
- * 用途:后端 MapStoredMessage(snake_case + 扁平 token 字段)与前端 ChatMessage
- * (含 streaming/usage 等 UI 态)之间映射。无副作用,便于单测。
+ * Purpose: map backend MapStoredMessage (snake_case + flat token fields) and frontend ChatMessage
+ * (UI state such as streaming/usage). No side effects, so it is easy to unit test.
*/
import type { MapSaveConversationInput, MapStoredMessage, MapStoredVersion } from '@/api/map';
@@ -10,7 +10,7 @@ import type { AnswerVersion, ChatMessage } from '../types';
import { CONTEXT_DIVIDER_MARKER, snapshotVersion } from './messages';
import { normalizeAssistantReply } from './thinkSplit';
-/** 后端版本存储形态 → 前端 AnswerVersion */
+/** Backend stored version → frontend AnswerVersion */
function storedToVersion(v: MapStoredVersion): AnswerVersion {
const normalized = normalizeAssistantReply(v.content, v.reasoning);
const out: AnswerVersion = { content: normalized.content };
@@ -21,7 +21,7 @@ function storedToVersion(v: MapStoredVersion): AnswerVersion {
if (v.client_request_id) out.clientRequestId = v.client_request_id;
if (v.api_key_id) out.apiKeyId = v.api_key_id;
if (v.interrupted) out.interrupted = true;
- // 联网过程字段:刷新后重绘折叠区使用,与 AnswerProcessTimeline 期望的输入对齐
+ // Web-search process fields: used to redraw the disclosure after refresh, aligned with the input AnswerProcessTimeline expects
if (v.search_status !== undefined) out.searchStatus = v.search_status;
if (v.search_step) out.searchStep = v.search_step as AnswerVersion['searchStep'];
if (v.search_result_count !== undefined) out.searchResultCount = v.search_result_count;
@@ -46,7 +46,7 @@ function storedToVersion(v: MapStoredVersion): AnswerVersion {
return out;
}
-/** 前端 AnswerVersion → 后端版本存储形态 */
+/** Frontend AnswerVersion → backend stored version */
function versionToStored(v: AnswerVersion): MapStoredVersion {
const normalized = normalizeAssistantReply(v.content, v.reasoning);
return {
@@ -55,7 +55,7 @@ function versionToStored(v: AnswerVersion): MapStoredVersion {
...(v.citations && v.citations.length ? { citations: v.citations } : {}),
...(v.feedback ? { feedback: v.feedback } : {}),
...(v.interrupted ? { interrupted: true } : {}),
- // 联网过程字段透传,刷新后折叠区才能重绘工具步骤
+ // Pass web-search process fields through, so the disclosure can redraw tool steps after refresh
...(v.searchStatus !== undefined ? { search_status: v.searchStatus } : {}),
...(v.searchStep ? { search_step: v.searchStep } : {}),
...(v.searchResultCount !== undefined ? { search_result_count: v.searchResultCount } : {}),
@@ -83,9 +83,9 @@ function versionToStored(v: AnswerVersion): MapStoredVersion {
};
}
-/** 后端存储消息 → 前端 ChatMessage(回填后一律非流式态) */
+/** Backend stored message → frontend ChatMessage (always non-streaming after backfill) */
export function storedToChatMessage(m: MapStoredMessage): ChatMessage {
- // 上下文分隔线:以 system + 标记往返,加载时还原为 divider(content 清空,避免标记泄漏到 UI)
+ // Context divider: round-trips as system + a marker, and is restored as a divider on load (content cleared so the marker does not leak into the UI)
if (m.role === 'system' && m.content === CONTEXT_DIVIDER_MARKER) {
return { id: m.id, role: 'system', content: '', streaming: false, divider: true };
}
@@ -108,7 +108,7 @@ export function storedToChatMessage(m: MapStoredMessage): ChatMessage {
total_tokens: m.total_tokens,
};
}
- // 回填前端计时指标(首 token 延迟 / 总耗时),使刷新后仍能展示完整指标行
+ // Backfill frontend timing metrics (time to first token / total elapsed) so the full metrics row still shows after refresh
if (typeof m.first_token_ms === 'number' || typeof m.duration_ms === 'number') {
msg.metrics = {
...(typeof m.first_token_ms === 'number' ? { firstTokenMs: m.first_token_ms } : {}),
@@ -116,7 +116,7 @@ export function storedToChatMessage(m: MapStoredMessage): ChatMessage {
};
}
if (m.citations && m.citations.length) msg.citations = m.citations;
- // 联网过程字段(单版本消息顶层),刷新后折叠区重绘需要
+ // Web-search process fields (top level of a single-version message), needed to redraw the disclosure after refresh
if (m.search_status !== undefined) msg.searchStatus = m.search_status;
if (m.search_step) msg.searchStep = m.search_step as ChatMessage['searchStep'];
if (m.search_result_count !== undefined) msg.searchResultCount = m.search_result_count;
@@ -140,9 +140,9 @@ export function storedToChatMessage(m: MapStoredMessage): ChatMessage {
...(att.objectKey ? { objectKey: att.objectKey } : {}),
}));
}
- // 回填反馈高亮(当前选中版本的点赞/点踩),使刷新后高亮保留
+ // Backfill feedback highlight (like/dislike on the selected version) so the highlight survives refresh
if (m.feedback === 'up' || m.feedback === 'down') msg.feedback = m.feedback;
- // 多版本回答:重建 versions + activeVersion(顶层字段已是选中版本的镜像,无需再覆盖)
+ // Multi-version answers: rebuild versions + activeVersion (top-level fields are already a mirror of the selected version and do not need another overwrite)
if (m.alt_versions && m.alt_versions.length > 0) {
msg.versions = m.alt_versions.map(storedToVersion);
msg.activeVersion =
@@ -157,8 +157,8 @@ export function storedToChatMessage(m: MapStoredMessage): ChatMessage {
}
/**
- * 待保存请求体 → 前端消息列表。
- * 用于刷新时恢复 sessionStorage 中尚未完成服务端写入的同标签页草稿。
+ * Pending save request body → frontend message list.
+ * Used on refresh to restore a same-tab draft in sessionStorage that has not finished writing to the server.
*/
export function savePayloadToChatMessages(payload: MapSaveConversationInput): ChatMessage[] {
return payload.messages.map((message, index) =>
@@ -171,8 +171,8 @@ export function savePayloadToChatMessages(payload: MapSaveConversationInput): Ch
}
/**
- * 把 UI 消息收敛为自动保存快照。
- * 首次生成的空 assistant 占位不保存;重新生成时恢复当前历史版本,避免流式期间删除旧回答。
+ * Collapse UI messages into an autosave snapshot.
+ * An empty assistant placeholder from the first generation is not saved; during regenerate, restore the current history version so the old answer is not deleted while streaming.
*/
export function messagesForAutosave(messages: ChatMessage[]): ChatMessage[] {
return messages.flatMap((message) => {
@@ -192,8 +192,8 @@ export function messagesForAutosave(messages: ChatMessage[]): ChatMessage[] {
}
/**
- * 把 UI 消息收敛为刷新草稿。
- * 首次生成保留空占位或部分正文/思考并标记中断;重新生成保留旧版本及当前部分回答。
+ * Collapse UI messages into a refresh draft.
+ * The first generation keeps an empty placeholder or a partial body/reasoning and marks it interrupted; regenerate keeps the old version and the current partial answer.
*/
export function messagesForDraft(messages: ChatMessage[]): ChatMessage[] {
return messages.flatMap((message) => {
@@ -226,14 +226,14 @@ export function messagesForDraft(messages: ChatMessage[]): ChatMessage[] {
});
}
-/** 重新生成尚未返回有效增量时继续使用旧完成版本,不制造空的中断版本。 */
+/** Before regenerate has returned a useful increment, keep using the old completed version, and do not invent an empty interrupted version. */
function hasStreamingDraftContent(message: ChatMessage): boolean {
return Boolean(
message.content || message.reasoning || message.citations?.length || message.toolEvents?.length,
);
}
-/** 将重新生成中的 assistant 临时恢复为当前历史版本,仅供自动保存计算快照。 */
+/** Temporarily restore an assistant that is being regenerated to the current history version, only so autosave can compute a snapshot. */
function restoreVersionForAutosave(
message: ChatMessage,
version: AnswerVersion,
@@ -265,8 +265,8 @@ function restoreVersionForAutosave(
}
/**
- * 前端消息列表 → 保存请求体(剥离 streaming/error 等 UI 态,展开 usage)。
- * 保留有效消息及显式中断占位,跳过普通空占位与错误消息。
+ * Frontend message list → save request body (strip UI state such as streaming/error, and expand usage).
+ * Keep valid messages and explicit interrupted placeholders, and skip ordinary empty placeholders and error messages.
*/
export function chatMessagesToSavePayload(
messages: ChatMessage[],
@@ -276,7 +276,7 @@ export function chatMessagesToSavePayload(
const out: MapSaveConversationInput['messages'] = [];
for (const m of messages) {
if (m.error) continue;
- // 上下文分隔线:以 system + 标记持久化(content 可能已被清空,需特判保留)
+ // Context divider: persist as system + a marker (content may already have been cleared, so it has to be kept by a special case)
if (m.divider) {
out.push({ role: 'system', content: CONTEXT_DIVIDER_MARKER });
continue;
@@ -313,7 +313,7 @@ export function chatMessagesToSavePayload(
? { reasoning: normalized?.reasoning ?? m.reasoning }
: {}),
...(m.citations && m.citations.length ? { citations: m.citations } : {}),
- // 联网过程字段(单版本消息顶层):刷新后折叠区重绘需要
+ // Web-search process fields (top level of a single-version message): needed to redraw the disclosure after refresh
...(m.searchStatus !== undefined ? { search_status: m.searchStatus } : {}),
...(m.searchStep ? { search_step: m.searchStep } : {}),
...(m.searchResultCount !== undefined ? { search_result_count: m.searchResultCount } : {}),
@@ -329,7 +329,7 @@ export function chatMessagesToSavePayload(
total_tokens: m.usage.total_tokens,
}
: {}),
- // 持久化前端计时指标,避免刷新后计时项丢失(输出速率由二者派生,无需单独存)
+ // Persist frontend timing metrics, so timing items are not lost after refresh (output rate is derived from the two and does not need to be stored on its own)
...(m.metrics?.firstTokenMs !== undefined
? { first_token_ms: Math.round(m.metrics.firstTokenMs) }
: {}),
@@ -340,14 +340,14 @@ export function chatMessagesToSavePayload(
...(m.clientRequestId ? { client_request_id: m.clientRequestId } : {}),
...(m.apiKeyId ? { api_key_id: m.apiKeyId } : {}),
...(m.contextExcluded ? { context_excluded: true } : {}),
- // 中断回答借助现有 alt_versions JSONB 保存状态,避免新增数据库列。
+ // An interrupted answer saves its state through the existing alt_versions JSONB, so no new database column is added.
...(m.interrupted || (m.versions && m.versions.length > 1)
? {
alt_versions: (m.versions ?? [snapshotVersion(m)]).map(versionToStored),
active_version: m.activeVersion ?? (m.versions?.length ?? 1) - 1,
}
: {}),
- // 反馈高亮:当前选中版本的点赞/点踩(单版本与多版本均存顶层,刷新后保留高亮)
+ // Feedback highlight: like/dislike on the currently selected version (stored at the top level for both single-version and multi-version, so the highlight survives refresh)
...(m.feedback ? { feedback: m.feedback } : {}),
});
}
@@ -355,8 +355,8 @@ export function chatMessagesToSavePayload(
}
/**
- * 计算消息列表签名,判断相较上次保存有无变化以避免重复写库:角色 + 正文/思考长度 + 版本数/选中索引
- * + 逐个工具事件的 eventId~status~来源数(同 eventId 原地转 success 时条数不变,但正是它带来 citationUrls)。
+ * Compute a message-list signature, to decide whether anything changed since the last save and avoid writing the database again: role + body/reasoning length + version count/selected index
+ * + each tool event's eventId~status~source count (an in-place change of the same eventId to success does not change the count, but that is exactly what brings citationUrls).
*/
export function messagesSignature(messages: ChatMessage[]): string {
return messages
diff --git a/webdemo/frontend/src/pages/playground/utils/copyText.ts b/webdemo/frontend/src/pages/playground/utils/copyText.ts
index 27732df..85b1de9 100644
--- a/webdemo/frontend/src/pages/playground/utils/copyText.ts
+++ b/webdemo/frontend/src/pages/playground/utils/copyText.ts
@@ -1,4 +1,4 @@
-/** 复制文本到剪贴板 */
+/** Copy text to the clipboard */
export async function copyText(text: string): Promise<boolean> {
try {
await navigator.clipboard.writeText(text);
diff --git a/webdemo/frontend/src/pages/playground/utils/documentMime.ts b/webdemo/frontend/src/pages/playground/utils/documentMime.ts
index d72d5ad..f2b240b 100644
--- a/webdemo/frontend/src/pages/playground/utils/documentMime.ts
+++ b/webdemo/frontend/src/pages/playground/utils/documentMime.ts
@@ -1,4 +1,4 @@
-/** 浏览器未标注 MIME 时按扩展名归一化;内容合法性仍由上传与后端校验。 */
+/** When the browser did not label a MIME type, normalize by extension; content validity is still checked by upload and the backend. */
const EXTENSION_MIME: ReadonlyArray<readonly [RegExp, string]> = [
[/\.pdf$/i, 'application/pdf'],
[/\.webp$/i, 'image/webp'],
@@ -16,7 +16,7 @@ const EXTENSION_MIME: ReadonlyArray<readonly [RegExp, string]> = [
[/\.tiff?$/i, 'image/tiff'],
];
-/** 已标注的类型保持不变;空类型和 octet-stream 按文件名补全。 */
+/** A labeled type stays as-is; an empty type and octet-stream are filled in from the file name. */
export function resolveDocumentMime(file: File): string {
if (file.type && file.type !== 'application/octet-stream') return file.type;
return EXTENSION_MIME.find(([pattern]) => pattern.test(file.name))?.[1] ?? '';
diff --git a/webdemo/frontend/src/pages/playground/utils/documentUpload.ts b/webdemo/frontend/src/pages/playground/utils/documentUpload.ts
index 66d4e9e..cb77863 100644
--- a/webdemo/frontend/src/pages/playground/utils/documentUpload.ts
+++ b/webdemo/frontend/src/pages/playground/utils/documentUpload.ts
@@ -1,20 +1,20 @@
-/** 图像解析演示的本地文件读取规则与类型归一化。 */
+/** Local file-read rules and type normalization for the image-parsing demo. */
import type { ImageParseMode } from '@/api/map/imageParseSdk';
import type { Attachment } from '../types';
import { resolveDocumentMime, withResolvedDocumentMime } from './documentMime';
-/** OCR 原件上传上限;PDF 使用 Blob URL 本地预览,不转为 base64。 */
+/** OCR original upload limit; PDFs use a Blob URL for local preview and are not converted to base64. */
export const DOCUMENT_MAX_BYTES = 64 * 1024 * 1024;
-/** PDF 逐页识别的最大页数;本地预览、云端历史与服务端校验共用。 */
+/** Maximum pages for per-page PDF recognition; shared by local preview, cloud history, and server checks. */
export const MAX_PDF_PAGES = 500;
-/** OCR 工作台接受浏览器可解码的图片类型;SVG 不作为位图输入。 */
+/** The OCR workspace accepts image types the browser can decode; SVG is not a bitmap input. */
export const DOCUMENT_IMAGE_TYPES: readonly string[] = [
'image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/bmp', 'image/webp',
];
-/** 文件选择器与拖放共用的格式边界。 */
+/** Format bounds shared by the file picker and drag-and-drop. */
export const DOCUMENT_ACCEPT = `application/pdf,.pdf,${DOCUMENT_IMAGE_TYPES.join(',')}`;
-/** 算法流水线可解码的单图格式;TIFF 在上游固定返回 400。 */
+/** Single-image formats the algorithm pipeline can decode; TIFF always returns 400 upstream. */
export const PIPELINE_IMAGE_TYPES: readonly string[] = [
'image/png',
'image/jpeg',
@@ -24,17 +24,17 @@ export const PIPELINE_IMAGE_TYPES: readonly string[] = [
'image/webp',
];
-/** 上传入口共用的文件边界;算法流水线与历史兼容档位分别传入。 */
+/** File bounds shared by upload entries; the algorithm pipeline and the historical compatibility tier pass their own. */
export interface DocumentFileRules {
maxBytes?: number;
accept?: readonly string[];
- /** 只接收图片;独立印章使用。 */
+ /** Accept images only; used by standalone seal. */
imagesOnly?: boolean;
- /** 一次只能选择一个文件;整图任务使用。 */
+ /** Only one file may be selected at a time; used by whole-image tasks. */
singleImage?: boolean;
}
-/** 工作台上传面的展示与校验规则;历史兼容档位不额外限制。 */
+/** Display and validation rules for the workspace upload surface; the historical compatibility tier adds no extra limit. */
export interface ImageParseUploadRules extends DocumentFileRules {
accept: readonly string[];
imagesOnly: boolean;
@@ -51,7 +51,7 @@ function mimeAllowed(mime: string, allowed: readonly string[]): boolean {
});
}
-/** 判断 MIME 是否可作为 OCR 位图输入。 */
+/** Whether a MIME type can be an OCR bitmap input. */
export function isDocumentImageMime(mime: string): boolean {
const normalized = mime.trim().toLowerCase();
return (
@@ -61,13 +61,13 @@ export function isDocumentImageMime(mime: string): boolean {
);
}
-/** 校验 OCR 可直接提交的图片 data URI 前缀;内容合法性由服务端校验。 */
+/** Check the data-URI prefix of an image OCR can submit directly; content validity is checked by the server. */
export function isDocumentImageDataURL(value: string): boolean {
const match = /^data:(image\/[^;,]+);base64,/i.exec(value);
return Boolean(match && isDocumentImageMime(match[1]));
}
-/** 算法流水线支持的单图 data URI;TIFF 等格式在上游会被拒绝。 */
+/** Single-image data URI the algorithm pipeline supports; formats such as TIFF are rejected upstream. */
export function isPipelineImageDataURL(value: string): boolean {
const match = /^data:(image\/[^;,]+);base64,/i.exec(value);
return Boolean(
@@ -75,23 +75,23 @@ export function isPipelineImageDataURL(value: string): boolean {
);
}
-/** 算法流水线可接受的图片 MIME;OBS 文件引用不依赖本地 data URI。 */
+/** Image MIME types the algorithm pipeline accepts; an OBS file reference does not depend on a local data URI. */
export function isPipelineImageMime(mime: string): boolean {
const normalized = mime.trim().toLowerCase();
return PIPELINE_IMAGE_TYPES.includes(normalized);
}
-/** 判断文档是否为 PDF,不把其它 file 类型当作可预览的文档。 */
+/** Whether the document is a PDF, and do not treat other file types as a previewable document. */
export function isPdfAttachment(attachment: Attachment): boolean {
return attachment.kind === 'file' && attachment.mime === 'application/pdf';
}
-/** OCR 接受图片及 PDF;预览能力与模型输入能力分别处理。 */
+/** OCR accepts images and PDFs; preview capability and model input capability are handled separately. */
export function isParseDocument(attachment?: Attachment): attachment is Attachment {
return Boolean(attachment && (attachment.kind === 'image' || isPdfAttachment(attachment)));
}
-/** 返回翻译键,所有上传入口按当前任务规则执行同一校验。 */
+/** Return a translation key; every upload entry runs the same check against the current task rules. */
export function documentFileError(
file: File,
rules: DocumentFileRules = {},
@@ -105,7 +105,7 @@ export function documentFileError(
return undefined;
}
-/** 文件选择器 accept 属性;PDF 同时带上扩展名,兼容未标 MIME 的浏览器。 */
+/** File-picker accept attribute; PDFs also include the extension, for browsers that did not label a MIME type. */
export function documentAccept(rules?: DocumentFileRules): string {
if (!rules?.accept) return DOCUMENT_ACCEPT;
return rules.accept
@@ -114,7 +114,7 @@ export function documentAccept(rules?: DocumentFileRules): string {
}
/**
- * 按识别档位生成上传规则。标准和 KIE 接受图片及原始 PDF,独立印章仅接受图片。
+ * Build upload rules from the recognition tier. Standard and KIE accept images and the original PDF; standalone seal accepts images only.
*/
export function imageParseUploadRules(mode: ImageParseMode): ImageParseUploadRules | undefined {
const imagesOnly = mode === 'seal';
@@ -128,7 +128,7 @@ export function imageParseUploadRules(mode: ImageParseMode): ImageParseUploadRul
};
}
-/** 浏览器未标注 MIME 时按扩展名归一化;内容有效性仍由上传与后端校验。 */
+/** When the browser did not label a MIME type, normalize by extension; content validity is still checked by upload and the backend. */
export function normalizeDocumentFile(file: File): File {
return withResolvedDocumentMime(file);
}
diff --git a/webdemo/frontend/src/pages/playground/utils/experienceRoute.ts b/webdemo/frontend/src/pages/playground/utils/experienceRoute.ts
index 5b23ed8..eef90f8 100644
--- a/webdemo/frontend/src/pages/playground/utils/experienceRoute.ts
+++ b/webdemo/frontend/src/pages/playground/utils/experienceRoute.ts
@@ -1,16 +1,16 @@
/**
- * 体验中心 URL 与可见模型之间的路由收敛。
+ * Route resolution between experience-center URLs and visible models.
*
- * 用途:把 `/playground/:experience` 收敛为合法体验键。语音合成 / 实时语音在对应
- * 可见模型为空时回退语言模型,避免直达 URL 停在空白页。
+ * Purpose: collapse `/playground/:experience` to a legal experience key. Speech synthesis and realtime voice fall back
+ * to the language model when their visible model list is empty, so a direct URL does not sit on a blank page.
*/
-/** 体验中心可切换的体验类型 */
+/** Experience types the experience center can switch among */
export type ExperienceKey = 'language' | 'tts' | 'duplex' | 'image-parse' | 'field-extract';
/**
- * URL 体验段到内部体验键的映射。
- * `document-parse` 是对外规范路径,`image-parse` 仅保留为历史书签兼容入口。
+ * Map a URL experience segment to an internal experience key.
+ * `document-parse` is the public canonical path; `image-parse` remains only as a compatibility entry for old bookmarks.
*/
const EXPERIENCE_PARAMS: Record<string, ExperienceKey> = {
tts: 'tts',
@@ -20,7 +20,7 @@ const EXPERIENCE_PARAMS: Record<string, ExperienceKey> = {
'field-extract': 'field-extract',
};
-/** 非语言体验是否对当前用户可见(由对应模型列表是否为空决定) */
+/** Whether a non-language experience is visible to the current user (decided by whether the matching model list is empty) */
export type ExperienceAvailability = {
tts: boolean;
duplex: boolean;
@@ -28,19 +28,19 @@ export type ExperienceAvailability = {
};
/**
- * 把 URL 参数收敛为合法体验键(非法/缺省回退语言模型)。
- * @param param 路由参数
+ * Collapse URL parameters to a legal experience key (illegal or missing falls back to the language model).
+ * @param param route parameter
*/
export function normalizeExperience(param?: string): ExperienceKey {
return (param ? EXPERIENCE_PARAMS[param] : undefined) ?? 'language';
}
/**
- * 按当前用户可见模型收敛体验键。
- * 语音合成 / 实时语音 / 文档解析无可见模型时回退语言模型。
- * @param experience URL 收敛出的体验键
- * @param loading 模型列表是否仍在加载(加载期间不回退,避免闪跳)
- * @param available 各非语言体验是否有可见模型
+ * Collapse the experience key by the models visible to the current user.
+ * Speech synthesis, realtime voice, and document parsing fall back to the language model when no model is visible.
+ * @param experience experience key resolved from the URL
+ * @param loading whether the model list is still loading (do not fall back while loading, to avoid a flicker)
+ * @param available whether each non-language experience has a visible model
*/
export function resolveExperience(
experience: ExperienceKey,
@@ -52,14 +52,14 @@ export function resolveExperience(
return 'language';
}
-/** 判断是否使用文档工作台,字段提取与全文识别共享模型权限及外壳。 */
+/** Whether to use the document workspace; field extraction and full-text recognition share model permission and the shell. */
export function isDocumentExperience(experience: ExperienceKey): boolean {
return experience === 'image-parse' || experience === 'field-extract';
}
/**
- * 体验入口路径:语言模型落在 `/playground`,其余带体验段。
- * @param key 体验键
+ * Experience entry path: the language model lives at `/playground`; the others carry an experience segment.
+ * @param key experience key
*/
export function experiencePath(key: ExperienceKey): string {
if (key === 'language') return '/playground';
@@ -68,8 +68,8 @@ export function experiencePath(key: ExperienceKey): string {
}
/**
- * 返回体验对应的文档路径。
- * @param experience 当前体验键
+ * Return the document path for an experience.
+ * @param experience current experience key
*/
export function experienceDocsPath(experience: ExperienceKey): string {
if (experience === 'tts') return '/docs/models/speech';
@@ -79,7 +79,7 @@ export function experienceDocsPath(experience: ExperienceKey): string {
return '/docs/models/text';
}
-/** 非语言体验顶栏所需的文案键(图标由页面按键装配,避免 util 引入 React)。 */
+/** Copy keys the non-language experience top bar needs (the icon is assembled by the page from the key, so the util does not import React). */
export interface ExperienceChromeCopy {
titleKey: 'ttsExperienceTitle' | 'duplexExperienceTitle' | 'imageParseExperienceTitle';
subtitleKey:
@@ -89,8 +89,8 @@ export interface ExperienceChromeCopy {
}
/**
- * 非语言体验顶栏文案键。语言对话走独立顶栏,不经过这里。
- * @param experience 当前体验键
+ * Top-bar copy keys for a non-language experience. Language chat uses its own top bar and does not come through here.
+ * @param experience current experience key
*/
export function experienceChromeCopy(experience: ExperienceKey): ExperienceChromeCopy {
if (experience === 'tts') {
diff --git a/webdemo/frontend/src/pages/playground/utils/imageGroupPdf.ts b/webdemo/frontend/src/pages/playground/utils/imageGroupPdf.ts
index 057e528..646a16b 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageGroupPdf.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageGroupPdf.ts
@@ -1,6 +1,6 @@
/**
- * 多张图片合成一份 PDF,复用现有的分页预览和逐页识别。
- * 单张图片和单份 PDF 保持原文件。
+ * Compose several images into one PDF, reusing the existing paged preview and per-page recognition.
+ * A single image and a single PDF stay as the original file.
*/
import {
documentFileError,
@@ -11,7 +11,7 @@ import {
} from './documentUpload';
import { withResolvedDocumentMime } from './documentMime';
-/** 合成页的长边上限,避免手机原图把主线程和后续识别撑得过大。 */
+/** Long-edge cap for a composed page, so a phone original does not overwhelm the main thread and later recognition. */
export const IMAGE_GROUP_MAX_EDGE = 2000;
export type PreparedDocument = { ok: true; file: File } | { ok: false; error: string };
@@ -22,7 +22,7 @@ interface JpegPage {
height: number;
}
-/** 预览按 2 倍渲染,页面尺寸用像素的一半,识别图才能回到原图像素。 */
+/** Preview renders at 2x and page size uses half the pixels, so the recognition image can return to the original image pixels. */
export function pdfFromJpegs(pages: readonly JpegPage[]): Uint8Array {
if (!pages.length) throw new Error('documentEmptyFile');
const encoder = new TextEncoder();
@@ -96,7 +96,7 @@ function groupFileName(files: readonly File[]): string {
return `${stem} 等${files.length}张.pdf`;
}
-/** 把一张图收成 JPEG 页。已有页面传 Infinity,避免缩小后对不齐原来的识别框。 */
+/** Turn one image into a JPEG page. An existing page passes Infinity, so shrinking it does not misalign the original recognition boxes. */
export async function imageFileToJpegPage(
file: File,
maxEdge = IMAGE_GROUP_MAX_EDGE,
@@ -135,8 +135,8 @@ async function imagesToPdfFile(files: readonly File[]): Promise<File> {
}
/**
- * 一份 PDF 保持原样。多张图片合成一份 PDF。多份 PDF,或 PDF 和图片混在一起,返回错误键。
- * 单文件结果是同步的,避免现有选择流程多等一轮。
+ * One PDF stays as-is. Several images are composed into one PDF. Several PDFs, or a PDF mixed with images, return an error key.
+ * A single-file result is synchronous, so the existing selection flow does not wait an extra round.
*/
export function prepareDocumentFiles(
incoming: FileList | readonly File[],
@@ -173,7 +173,7 @@ export function prepareDocumentFiles(
);
}
-/** 同步结果立刻回调;只有多张图片会等合成完成。 */
+/** A synchronous result calls back immediately; only several images wait for composition to finish. */
export function applyPreparedDocument(
incoming: FileList | readonly File[] | null | undefined,
onFile: (file: File) => void,
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParse.ts b/webdemo/frontend/src/pages/playground/utils/imageParse.ts
index 84f05e7..ab4c653 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParse.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParse.ts
@@ -1,15 +1,15 @@
/**
- * 图像解析体验的系统提示词与 Chat Completions 请求装配。
+ * System prompt and Chat Completions request assembly for the image-parsing experience.
*
- * 用途:历史兼容的「图像 → Markdown」请求适配。当前 OCR Playground 走算法流水线。
- * 不在界面暴露评估场景:试卷/表格/多栏/手写的约束写进同一份提示词,由模型按画面自行适配。
+ * Purpose: the historical "image → Markdown" request adapter. The current OCR Playground uses the algorithm pipeline.
+ * Evaluation scenes are not exposed in the UI: exam, table, multi-column, and handwriting constraints live in the same prompt, and the model adapts from the image.
*/
import type { ChatCompletionParams } from '@/api/map/chat';
import type { Attachment } from '../types';
import { attachmentToPart } from './attachments';
-/** 用户侧短指令。部分视觉模型要求 content 里至少有一段 text,不能只发 image_url。 */
+/** Short user-side instruction. Some vision models require at least one text part in content and cannot receive only image_url. */
const USER_INSTRUCTION = '请将图像转为 Markdown。';
const SYSTEM_PROMPT = [
@@ -24,21 +24,21 @@ const SYSTEM_PROMPT = [
].join('\n');
/**
- * 图像解析系统提示词。产品层固定一份,避免用户先选场景再转换。
+ * Image-parsing system prompt. The product layer keeps a single fixed prompt, so the user does not pick a scene first and then convert.
*/
export function imageParseSystemPrompt(): string {
return SYSTEM_PROMPT;
}
-/** 组装图像解析补全请求的入参 */
+/** Arguments for assembling an image-parsing completion request */
export interface BuildImageParseRequestArgs {
model: string;
attachment: Attachment;
}
/**
- * 组装一次「图像 → Markdown」补全请求:系统提示 + 短指令 + 单张 image_url,不含聊天历史。
- * @param args 模型与图像附件
+ * Assemble one "image → Markdown" completion request: system prompt + short instruction + a single image_url, with no chat history.
+ * @param args model and image attachment
*/
export function buildImageParseRequest(args: BuildImageParseRequestArgs): ChatCompletionParams {
if (args.attachment.kind !== 'image') {
@@ -51,7 +51,7 @@ export function buildImageParseRequest(args: BuildImageParseRequestArgs): ChatCo
return {
model: args.model,
stream: true,
- // 图像转 Markdown 只要正文,显式关掉思考,避免 reasoning 污染结果。
+ // Image-to-Markdown wants only the body, so reasoning is explicitly turned off to keep it from contaminating the result.
chat_template_kwargs: { enable_thinking: false },
messages: [
{ role: 'system', content: imageParseSystemPrompt() },
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseBlockEditContext.ts b/webdemo/frontend/src/pages/playground/utils/imageParseBlockEditContext.ts
index 1f32afc..10f385b 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseBlockEditContext.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseBlockEditContext.ts
@@ -2,7 +2,7 @@ import { createContext, type ReactNode } from 'react';
import type { ImageParseTextRange } from './imageParseBlocks';
-/** 预览块的编辑入口;组件类型保持稳定,切块时不重建其它预览 DOM。 */
+/** Edit entry for a preview block; the component type stays stable so switching blocks does not rebuild the other preview DOM. */
export const ImageParseBlockEditContext = createContext<{
renderBlock: (range: ImageParseTextRange, children: ReactNode) => ReactNode;
} | null>(null);
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseBlockMarkdown.ts b/webdemo/frontend/src/pages/playground/utils/imageParseBlockMarkdown.ts
index 9db1268..7bfb904 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseBlockMarkdown.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseBlockMarkdown.ts
@@ -13,8 +13,8 @@ function labelOf(block: ImageParseLayoutBlock): string {
}
/**
- * 判断块是否为页眉、页脚或页码。
- * 没标 label 的旧块按 kind 判断,页码的 kind 是 footer。
+ * Whether a block is a header, footer, or page number.
+ * Old blocks with no label are judged by kind; a page number's kind is footer.
*/
export function isImageParseHeaderFooterBlock(block: ImageParseLayoutBlock): boolean {
const label = labelOf(block);
@@ -27,8 +27,8 @@ function recognized(block: ImageParseLayoutBlock): boolean {
}
/**
- * 同一公式已经有显示公式块时,不再把另一块裸 LaTeX 写进预览。
- * 显示公式块本身都保留,两块原图公式不会被合成一块。
+ * When the same formula already has a display-formula block, do not write another block's bare LaTeX into the preview.
+ * Display-formula blocks themselves are all kept; two original-image formulas are not merged into one block.
*/
function bareFormulaDuplicate(
block: ImageParseLayoutBlock,
@@ -40,12 +40,12 @@ function bareFormulaDuplicate(
return Boolean(comparable) && displays.has(comparable);
}
-/** 将一个识别块转成预览片段;空文本、失败块和重复公式返回 null。 */
+/** Turn one recognition block into a preview fragment; empty text, failed blocks, and duplicate formulas return null. */
function piece(block: ImageParseLayoutBlock, displays: ReadonlySet<string>): string | null {
const label = labelOf(block);
const text = block.text ?? '';
if (PLACEHOLDER_LABELS.has(label)) return IMAGE_PLACEHOLDER;
- // 印章文字不是正文内容;没有识别出文字时保留原图占位符,避免结果区出现空白。
+ // Seal text is not body content; when no text was recognized, keep the original-image placeholder so the result area is not blank.
if (label === 'seal') return text.trim() ? text : IMAGE_PLACEHOLDER;
if (TEXT_OR_PLACEHOLDER_LABELS.has(label)) return text.trim() ? text : IMAGE_PLACEHOLDER;
if (!recognized(block) || !text.trim() || bareFormulaDuplicate(block, displays)) return null;
@@ -58,11 +58,11 @@ function piece(block: ImageParseLayoutBlock, displays: ReadonlySet<string>): str
}
/**
- * 按识别块的 order 生成预览正文,并记下每块在正文里的起止位置。
- * 不读取服务端聚合 Markdown;没写进正文的块保留下来,范围留空。
- * @param blocks 已完成校验的识别块
- * @param options omitHeaderFooter 为 true 时跳过页眉、页脚与页码
- * @returns 重新组合的正文与块映射
+ * Build preview body text from recognition blocks' order, and record each block's start and end in the body.
+ * Do not read the server's aggregated Markdown; a block that was not written into the body is kept, with an empty range.
+ * @param blocks recognition blocks that have finished validation
+ * @param options when omitHeaderFooter is true, skip header, footer, and page number
+ * @returns the recomposed body and the block map
*/
export function composeImageParseBlockMarkdown(
blocks: readonly ImageParseLayoutBlock[],
@@ -100,7 +100,7 @@ export function composeImageParseBlockMarkdown(
return { markdown, blocks: next };
}
-/** 跨页合并后的重写入口:表格已写回块里,正文只按块再生成一次。 */
+/** Rewrite entry after a cross-page merge: the table has been written back into the block, and the body is generated from blocks once more. */
export function composeImageParsePreview(
_markdown: string,
blocks: readonly ImageParseLayoutBlock[],
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseBlocks.ts b/webdemo/frontend/src/pages/playground/utils/imageParseBlocks.ts
index 6844fc1..d27d203 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseBlocks.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseBlocks.ts
@@ -1,17 +1,17 @@
import type { ImageParseLayoutBlock } from './imageParseSample';
-/** Markdown 中一个块对应的原始字符范围。 */
+/** Original character range in Markdown that corresponds to one block. */
export interface ImageParseTextRange {
start: number;
end: number;
}
-/** 优先使用服务标识;本地样例与无标识响应使用坐标及阅读顺序保证唯一。 */
+/** Prefer the service id; local samples and responses with no id use coordinates plus reading order to stay unique. */
export function imageParseBlockId(block: ImageParseLayoutBlock, order: number): string {
return block.id ?? `${order}:${block.x}:${block.y}:${block.w}:${block.h}`;
}
-/** 合并块优先返回全部 regions;旧结果回落到主 bbox。 */
+/** A merged block prefers to return every region; an old result falls back to the primary bbox. */
export function imageParseBlockRegions(block: ImageParseLayoutBlock) {
return block.regions?.length
? block.regions
@@ -19,8 +19,8 @@ export function imageParseBlockRegions(block: ImageParseLayoutBlock) {
}
/**
- * 按阅读顺序定位片段,重复文字不一律指向第一次出现的位置。
- * 原始范围由草稿的替换记录继续维护;不重新猜测修改后文字的位置。
+ * Locate a fragment in reading order; repeated text does not always point at the first occurrence.
+ * The original range continues to be maintained by the draft's replacement record; do not guess the position of edited text again.
*/
export function imageParseBlockRanges(
markdown: string,
@@ -40,7 +40,7 @@ export function imageParseBlockRanges(
return ranges;
}
-/** 把 0–1 分数显示为整数百分比并向下取整;仅格式化显示,不修改用于复核判断的原始值。 */
+/** Show a 0–1 score as an integer percentage, rounded down; display formatting only, and do not modify the raw value used for review decisions. */
export function imageParseConfidence(value: number | null): string | null {
if (value === null || !Number.isFinite(value) || value < 0 || value > 1) return null;
const percent = Math.floor((value + Number.EPSILON) * 100);
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseClipboard.ts b/webdemo/frontend/src/pages/playground/utils/imageParseClipboard.ts
index 01df710..9ec5f8e 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseClipboard.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseClipboard.ts
@@ -6,15 +6,15 @@ import { splitJoinedDisplayFormulas } from './math-markdown';
import { extractMarkdownTables, markdownTablesToHtml, markdownTablesToTsv } from './markdownTable';
/**
- * 复制文档表格到剪贴板,同时写入 HTML 与纯文本两种格式。
+ * Copy a document table to the clipboard, writing both HTML and plain text.
*
- * - `text/html`:飞书、Word 依赖它还原成真正的表格(纯文本粘过去只会退化成一行行文字)。
- * - `text/plain`:Excel 与各类表格软件依赖 TSV 分列。
+ * - `text/html`: Feishu and Word depend on it to restore a real table (plain text pastes as lines of text).
+ * - `text/plain`: Excel and other spreadsheet apps depend on TSV to split columns.
*
- * 浏览器不支持多格式写入或写入被拒时退回纯 TSV,至少保证表格软件仍可用。
+ * When the browser cannot write multiple formats, or the write is rejected, fall back to plain TSV so spreadsheet apps still work.
*
- * @param markdown 当前结果或草稿的 Markdown 正文
- * @returns 是否写入成功;正文里没有表格时返回 false
+ * @param markdown Markdown body of the current result or draft
+ * @returns whether the write succeeded; false when the body has no table
*/
export async function copyImageParseTable(markdown: string): Promise<boolean> {
if (!extractMarkdownTables(markdown).length) return false;
@@ -34,7 +34,7 @@ export async function copyImageParseTable(markdown: string): Promise<boolean> {
}
/**
- * 给一段落在行间公式内部的正文补回 `$$`。已经带定界符时只做拆段。
+ * Put `$$` back around body text that falls inside a display formula. If delimiters are already present, only split the segments.
*/
function restoreDisplayFormulaMarkdown(slice: string): string {
const trimmed = slice.trim();
@@ -43,8 +43,8 @@ function restoreDisplayFormulaMarkdown(slice: string): string {
}
/**
- * 复制范围两侧跳过空白后是否正好是一对 `$$`。
- * 多段粘在一起时,解析器会在第一处 `$$` 结束,整段范围不再落在同一个公式节点里。
+ * Whether skipping whitespace on both sides of the copy range lands exactly on a pair of `$$`.
+ * When several segments are stuck together, the parser ends at the first `$$`, and the whole range no longer falls inside the same formula node.
*/
function surroundedByDisplayFence(source: string, start: number, end: number): boolean {
let before = start;
@@ -62,8 +62,8 @@ function surroundedByDisplayFence(source: string, start: number, end: number): b
}
/**
- * 区块复制范围经常落在 `$$...$$` 内部,只含 LaTeX。
- * 先补回所在行间公式的定界符,粘在一起的多段再拆开。
+ * A block copy range often falls inside `$$...$$` and contains only LaTeX.
+ * Put the delimiters of that display formula back first, then split segments that are stuck together.
*/
export function imageParseCopyRegionMarkdown(source: string, range: ImageParseTextRange): string {
const slice = source.slice(range.start, range.end);
@@ -88,10 +88,10 @@ export function imageParseCopyRegionMarkdown(source: string, range: ImageParseTe
}
/**
- * 复制当前 OCR 区域:表格保留可粘贴的表格结构,普通内容去除 Markdown 标记。
+ * Copy the current OCR region: a table keeps a pasteable table structure, and ordinary content has Markdown markers removed.
*
- * @param markdown 当前选中区域的 Markdown
- * @returns 是否写入成功;区域为空时返回 false
+ * @param markdown Markdown of the currently selected region
+ * @returns whether the write succeeded; false when the region is empty
*/
export async function copyImageParseRegion(markdown: string): Promise<boolean> {
if (!markdown.trim()) return false;
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseCrops.ts b/webdemo/frontend/src/pages/playground/utils/imageParseCrops.ts
index df9778b..7314a4a 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseCrops.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseCrops.ts
@@ -4,7 +4,7 @@ const IMAGE_KINDS = new Set(['image', 'chart', 'seal']);
const PLACEHOLDER = /!\[image\]\(\)/g;
const IMAGE_MARKUP = /!\[image\]\((?:<([^>\r\n]*)>|([^)]*))\)/g;
-/** 正文里需要用原图裁切补上的插图位置。http(s) 和 data URL 保持原样。 */
+/** Illustration positions in the body that need a crop from the original image. http(s) and data URLs are left as-is. */
export function unservedImagePlaceholderOffsets(markdown: string): number[] {
const offsets: number[] = [];
for (const match of markdown.matchAll(IMAGE_MARKUP)) {
@@ -15,7 +15,7 @@ export function unservedImagePlaceholderOffsets(markdown: string): number[] {
return offsets;
}
-/** 图表与有文字印章在正文里显示文字;关闭展示时才替换为原图占位符。 */
+/** Charts and seals that have text show that text in the body; they are replaced with an original-image placeholder only when display is turned off. */
export function isImageParseDisplayTextBlock(block: ImageParseLayoutBlock): boolean {
return (block.kind === 'chart' || block.kind === 'seal') && Boolean(block.text.trim());
}
@@ -34,7 +34,7 @@ function isEmptySeal(block: ImageParseLayoutBlock): boolean {
return block.kind === 'seal' && !block.text.trim();
}
-/** 展示印章图片时使用的完整裁图集合;页脚图没有正文占位符,不纳入集合。 */
+/** Full crop set used when showing seal images; footer images have no body placeholder and are not included. */
export function imageParseAllCropBlocks(
blocks: readonly ImageParseLayoutBlock[],
): ImageParseLayoutBlock[] {
@@ -42,10 +42,10 @@ export function imageParseAllCropBlocks(
}
/**
- * 正文里的 ![image]() 按阅读顺序对应这些块。
- * 有文字的印章和图表对应正文,不参与图片占位符配对。
- * header_image、footer_image 和 image 一样要出图。服务端若漏了页脚图占位符,数量对不上时先去掉它再配,避免把别的图贴错。
- * 还是对不上就不猜,避免把图贴到错误的块上。
+ * `![image]()` in the body corresponds to these blocks in reading order.
+ * Seals and charts that have text correspond to the body and do not take part in image-placeholder pairing.
+ * header_image, footer_image, and image all need a picture. If the server omitted a footer-image placeholder, drop it before pairing when the counts disagree, so another image is not pasted in the wrong place.
+ * If they still disagree, do not guess, so an image is not pasted onto the wrong block.
*/
export function imageParseCropBlocks(
blocks: readonly ImageParseLayoutBlock[],
@@ -58,10 +58,10 @@ export function imageParseCropBlocks(
}
/**
- * 服务正文已有占位符与图片块配对。
- * 有文字的印章和图表对应正文;服务端通常不会为空印章写占位符,
- * 因此数量对不上时先排除空印章,
- * 再由兼容层补写印章占位符,避免把已有图片占位符错配给印章。
+ * Pair placeholders already in the service body with image blocks.
+ * Seals and charts that have text correspond to the body; the server usually does not write a placeholder for an empty seal,
+ * so when the counts disagree, exclude empty seals first,
+ * then let the compatibility layer write seal placeholders, so an existing image placeholder is not mismatched to a seal.
*/
export function imageParseMarkdownCropBlocks(
blocks: readonly ImageParseLayoutBlock[],
@@ -77,7 +77,7 @@ export function imageParseMarkdownCropBlocks(
return withoutOmitted.length === placeholderCount ? withoutOmitted : [];
}
-/** 占位符数量与可显示图块数量不一致时不猜测配对,避免把别的图贴到错误块上。 */
+/** When the placeholder count and the number of displayable image blocks disagree, do not guess the pairing, so another image is not pasted onto the wrong block. */
export async function imageParseCrops(
markdown: string,
blocks: readonly ImageParseLayoutBlock[],
@@ -101,7 +101,7 @@ export async function imageParseCrops(
const image = new Image();
if (remote) image.crossOrigin = 'anonymous';
image.src = original;
- // jsdom 与部分旧浏览器没有 decode;裁图是增强能力,失败时保留文字与坐标。
+ // jsdom and some old browsers have no decode; cropping is an enhancement, and on failure the text and coordinates are kept.
if (typeof image.decode !== 'function') return [];
try {
await image.decode();
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseCurrent.ts b/webdemo/frontend/src/pages/playground/utils/imageParseCurrent.ts
index 59ff7a6..fcc5f91 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseCurrent.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseCurrent.ts
@@ -6,9 +6,9 @@ function storageKey(scope: string): string {
}
/**
- * 读取当前文档指针。
- * @param scope 用户与项目组成的隔离范围
- * @returns 文档 ID;null 表示用户主动清空,undefined 表示尚未建立指针
+ * Read the current document pointer.
+ * @param scope isolation scope made of the user and the project
+ * @returns document ID; null means the user cleared it on purpose, undefined means no pointer has been established yet
*/
export function readCurrentImageParseId(scope: string): string | null | undefined {
if (typeof window === 'undefined') return undefined;
@@ -22,15 +22,15 @@ export function readCurrentImageParseId(scope: string): string | null | undefine
}
/**
- * 更新当前文档指针;只保存 ID,不把文件内容写入 localStorage。
- * @param scope 用户与项目组成的隔离范围
- * @param attachmentId 当前附件 ID,传 null 表示主动清空
+ * Update the current document pointer; save only the ID, and do not write file content into localStorage.
+ * @param scope isolation scope made of the user and the project
+ * @param attachmentId current attachment ID; null means a clear on purpose
*/
export function writeCurrentImageParseId(scope: string, attachmentId: string | null): void {
if (typeof window === 'undefined') return;
try {
window.localStorage.setItem(storageKey(scope), attachmentId ?? EMPTY_VALUE);
} catch {
- // 本地存储被禁用或空间不足时不阻断文档解析。
+ // Do not block document parsing when local storage is disabled or out of space.
}
}
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseDocumentBlocks.ts b/webdemo/frontend/src/pages/playground/utils/imageParseDocumentBlocks.ts
index 8fed663..dc25001 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseDocumentBlocks.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseDocumentBlocks.ts
@@ -2,15 +2,15 @@ import type { ImageParseTextRange } from './imageParseBlocks';
import { imageParseSourceBlocks, isImageParseSourceBlockEditable } from './imageParseEditorSource';
import { normalizeMathDelimiters } from './math';
-/** 源文档块与规范化预览的对应关系;只允许明确匹配的块进入编辑。 */
+/** Correspondence between a source document block and the normalized preview; only a clearly matched block may be edited. */
export interface ImageParseDocumentBlock extends ImageParseTextRange {
normalized: ImageParseTextRange;
}
/**
- * 按 Markdown AST 的顶层语义块定位;不拆开表格、列表或引用,也不猜测有歧义的范围。
- * @param source 原草稿
- * @param normalized 预览使用的完整规范化文本
+ * Locate by top-level semantic blocks of the Markdown AST; do not split tables, lists, or quotes, and do not guess ambiguous ranges.
+ * @param source original draft
+ * @param normalized full normalized text used by the preview
*/
export function imageParseDocumentBlocks(
source: string,
@@ -44,7 +44,7 @@ interface PreviewNode {
position?: { start: { offset?: number }; end: { offset?: number } };
}
-/** 消毒后的预览节点添加可信块范围,整份文档仍共用一次 Markdown 渲染。 */
+/** Add trusted block ranges to sanitized preview nodes; the whole document still shares one Markdown render. */
export function imageParseDocumentBlockMarkers(blocks: readonly ImageParseDocumentBlock[]) {
return (tree: PreviewNode) => {
const children: PreviewNode[] = [];
@@ -53,7 +53,7 @@ export function imageParseDocumentBlockMarkers(blocks: readonly ImageParseDocume
for (const node of tree.children ?? []) {
const start = node.position?.start.offset;
const end = node.position?.end.offset;
- // 二分定位,避免长文档的节点与块范围产生平方级遍历。
+ // Binary search, so nodes and block ranges in a long document do not walk in quadratic time.
let low = 0;
let high = blocks.length;
while (low < high) {
@@ -95,7 +95,7 @@ export function imageParseDocumentBlockMarkers(blocks: readonly ImageParseDocume
};
}
-/** 编辑片段导入时携带整份文档的链接定义,导出仍只更新该片段。 */
+/** When an edit fragment is imported it carries the whole document's link definitions; export still updates only that fragment. */
export function imageParseReferenceDefinitions(source: string): string {
return imageParseSourceBlocks(source)
.filter((node) => node.type === 'definition')
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseDraftRanges.ts b/webdemo/frontend/src/pages/playground/utils/imageParseDraftRanges.ts
index 18e9beb..f83b339 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseDraftRanges.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseDraftRanges.ts
@@ -1,6 +1,6 @@
import type { ImageParseTextRange } from './imageParseBlocks';
-/** 找出一次替换的准确范围;源码编辑采用公共前后缀,不重新猜测重复文字的位置。 */
+/** Find the exact range of one replacement; source editing uses the common prefix and suffix and does not guess the position of repeated text again. */
function replacementRange(
before: string,
after: string,
@@ -32,8 +32,8 @@ function replacementRange(
}
/**
- * 按一次替换更新原图区块范围,保留编辑块及其后所有区块的联动。
- * 跨多个识别块的有歧义替换仅丢弃受影响范围,不关闭整份文档定位。
+ * Update original-image block ranges from one replacement, keeping the edited block and every block after it linked.
+ * An ambiguous replacement that spans several recognition blocks drops only the affected ranges and does not turn off positioning for the whole document.
*/
export function imageParseDraftRanges(
before: string,
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseEditorExtensions.ts b/webdemo/frontend/src/pages/playground/utils/imageParseEditorExtensions.ts
index 678e5c5..07c1e9d 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseEditorExtensions.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseEditorExtensions.ts
@@ -17,7 +17,7 @@ import { SAFE_KATEX_OPTIONS } from './math-options';
import { inlineMathMarkdown } from './math-native';
import { imageParseEditorMathToken } from './imageParseEditorMath';
-/** 未支持语法的原文保留节点;不会把原文当成编辑器 HTML 插入。 */
+/** A preserved node for source text whose syntax is unsupported; the source is not inserted as editor HTML. */
export const PreservedImageParseSource = Node.create({
name: 'preservedSource',
group: 'block',
@@ -56,7 +56,7 @@ function tableHtml(node: JSONContent, extensions: Extensions) {
const align = (cell as HTMLElement).style.textAlign;
if (['left', 'center', 'right'].includes(align)) cell.setAttribute('align', align);
});
- // 表格不能压成 pipe Markdown;公式用现有预览管线支持的安全 code 节点表示。
+ // A table must not be flattened to pipe Markdown; formulas use a safe code node supported by the existing preview pipeline.
fragment
.querySelectorAll('[data-type="inline-math"], [data-type="block-math"]')
.forEach((math) => {
@@ -70,8 +70,8 @@ function tableHtml(node: JSONContent, extensions: Extensions) {
}
/**
- * OCR 富文本编辑扩展;表格固定导出 HTML,交给 Tiptap schema 处理合并和嵌套内容。
- * @param preserved 可选的 React 节点视图,测试和无视图调用沿用基础保留节点
+ * Rich-text edit extensions for OCR; tables always export HTML, and the Tiptap schema handles merged and nested content.
+ * @param preserved optional React node view; tests and calls with no view keep the basic preserved node
*/
export function imageParseEditorExtensions(
preserved = PreservedImageParseSource,
@@ -102,7 +102,7 @@ export function imageParseEditorExtensions(
parseHTML() {
return [
...(this.parent?.() ?? []),
- // DOM 规则需先于通用 code 标记匹配,否则再次导入会丢失公式节点。
+ // DOM rules must match before the generic code mark, or importing again drops the formula node.
{
tag: 'code.math-inline',
priority: 100,
@@ -116,7 +116,7 @@ export function imageParseEditorExtensions(
markdownTokenizer: {
name: 'blockMath',
level: 'block',
- // marked 用去掉首字符的文本寻找段落中断点,不能匹配多美元围栏的后缀。
+ // marked finds paragraph breaks in text with the first character removed, and cannot match the suffix of a multi-dollar fence.
start: (source) => {
const index = source.search(/\n\$\$(?!\$)/);
return index < 0 ? -1 : index + 1;
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseEditorMath.ts b/webdemo/frontend/src/pages/playground/utils/imageParseEditorMath.ts
index 160edc5..010428c 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseEditorMath.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseEditorMath.ts
@@ -1,8 +1,8 @@
/**
- * 为编辑器读取完整数学围栏;显示模式只由外层标记决定,正文美元符不参与 Markdown 转义。
- * @param source 从数学标记开始的 Markdown
- * @param display 是否读取双美元符的块级公式
- * @returns 现有 Mathematics 扩展接受的 token;未闭合或空公式不转换
+ * Read a complete math fence for the editor; display mode is decided only by the outer marker, and dollar signs in the body do not take part in Markdown escaping.
+ * @param source Markdown starting at the math marker
+ * @param display whether to read a block formula delimited by double dollar signs
+ * @returns a token the existing Mathematics extension accepts; an unclosed or empty formula is not converted
*/
export function imageParseEditorMathToken(source: string, display: boolean) {
const marker = source.match(/^\$+/)?.[0];
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseEditorSource.ts b/webdemo/frontend/src/pages/playground/utils/imageParseEditorSource.ts
index c9b1c17..a113dd6 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseEditorSource.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseEditorSource.ts
@@ -95,7 +95,7 @@ const HTML_ATTRIBUTES = new Set([
function supportedHtml(value: string) {
const fragment = new DOMParser().parseFromString(value, 'text/html');
if (fragment.head.childNodes.length) return false;
- // 注释与特殊 HTML 不能经过 schema 导入时静默消失。
+ // Comments and special HTML must not silently disappear when imported through the schema.
const walker = fragment.createTreeWalker(fragment, NodeFilter.SHOW_COMMENT);
if (walker.nextNode()) return false;
return [...fragment.body.querySelectorAll('*')].every((element) => {
@@ -105,7 +105,7 @@ function supportedHtml(value: string) {
if (name === 'class' && element.tagName === 'CODE') {
return /^(language-[\w-]+|math-inline|math-display)$/.test(attribute);
}
- // Tiptap 导出的列宽与 GFM 对齐是可重建属性,其它样式保留原文。
+ // Column widths and GFM alignment exported by Tiptap are rebuildable attributes; other styles keep the original text.
return (
name === 'style' &&
/^(TABLE|COL|TD|TH)$/.test(element.tagName) &&
@@ -122,7 +122,7 @@ function supported(node: SourceNode): boolean {
return node.children?.every(supported) ?? true;
}
-/** OCR 源文本中的一或双层转义 br;仅进入文字内容,代码和公式由 AST 边界保护。 */
+/** A single- or double-escaped br in OCR source text; it only enters text content. Code and formulas are protected by AST boundaries. */
const ESCAPED_LINE_BREAK = /(?:&amp;|&)(?:lt|#60|#x3c);br\s*\/?\s*(?:&amp;|&)(?:gt|#62|#x3e);/gi;
interface SourceRange {
@@ -150,7 +150,7 @@ function collectTextLineBreaks(
node.children?.forEach((child) => collectTextLineBreaks(child, blockStart, block, ranges));
}
-/** 可编辑 HTML 先识别单元格公式再恢复换行,避免公式中的 br 被误转为 DOM 节点。 */
+/** Editable HTML recognizes cell formulas before restoring line breaks, so a br inside a formula is not turned into a DOM node by mistake. */
function normalizeSupportedLineBreaks(block: string, node: SourceNode) {
if (node.type === 'html') {
if (!/[$\\]/.test(block) && !new RegExp(ESCAPED_LINE_BREAK.source, 'i').test(block))
@@ -170,15 +170,15 @@ function normalizeSupportedLineBreaks(block: string, node: SourceNode) {
);
}
-/** 判断完整语义块是否能进入可视化编辑,图片占位符与未知结构继续保持预览。 */
+/** Whether a complete semantic block can enter visual editing; image placeholders and unknown structure stay in preview. */
export function isImageParseSourceBlockEditable(node: SourceNode): boolean {
return node.type !== 'definition' && supported(node);
}
/**
- * 使用 Markdown AST 识别编辑器不支持的完整块,将其作为保留节点导入。
- * 保留块仍由原预览器安全展示,导出时直接恢复原文,不做有损转换。
- * @param source 原始 OCR 草稿
+ * Use the Markdown AST to recognize complete blocks the editor does not support, and import them as preserved nodes.
+ * Preserved blocks are still shown safely by the original previewer, and export restores the original text directly, with no lossy conversion.
+ * @param source original OCR draft
*/
export function prepareImageParseEditorSource(source: string): string {
const tree = SOURCE_PARSER.parse(source) as SourceNode;
@@ -192,7 +192,7 @@ export function prepareImageParseEditorSource(source: string): string {
result += normalizeMathDelimiters(source.slice(cursor, start), { detectBareMath: false });
if (supported(node)) {
const prepared = normalizeSupportedLineBreaks(block, node);
- // HTML 单元格公式已生成 code 节点;不能再规范化其内部 LaTeX 或代码内容。
+ // HTML cell formulas have already produced a code node; do not normalize the LaTeX or code inside them again.
result +=
node.type === 'html'
? prepared
@@ -206,7 +206,7 @@ export function prepareImageParseEditorSource(source: string): string {
return result + normalizeMathDelimiters(source.slice(cursor), { detectBareMath: false });
}
-/** 从 AST 提取可复制的文字,保留代码、公式与图片说明。 */
+/** Extract copyable text from the AST, keeping code, formulas, and image alt text. */
export function imageParseNodeText(
node: SourceNode,
options?: { mathDelimiters?: boolean },
@@ -234,7 +234,7 @@ export function imageParseNodeText(
);
}
-/** 把 HTML 里的公式代码还原成带定界符的文本,供复制后贴回 Markdown。 */
+/** Turn formula code in HTML back into text with delimiters, so it can be pasted back into Markdown after copying. */
function wrapImageParseHtmlMath(root: ParentNode) {
root.querySelectorAll('code.math-inline, code.math-display').forEach((code) => {
const latex = code.textContent ?? '';
@@ -246,7 +246,7 @@ function wrapImageParseHtmlMath(root: ParentNode) {
});
}
-/** 获取统一解析器的顶层块,供表格导出沿用同一套 GFM 语法规则。 */
+/** Get the top-level blocks of the shared parser, so table export follows the same GFM syntax rules. */
export function imageParseSourceBlocks(source: string): SourceNode[] {
return (SOURCE_PARSER.parse(source) as SourceNode).children ?? [];
}
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseEditorStyles.ts b/webdemo/frontend/src/pages/playground/utils/imageParseEditorStyles.ts
index 2fd6309..94f17cf 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseEditorStyles.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseEditorStyles.ts
@@ -1,6 +1,6 @@
/**
- * OCR 编辑器样式:正文和表格沿用主题色,宽表仅在自身容器内滚动。
- * 首尾节点使用更具体的选择器清除预览排版的外边距,单块编辑不重复增加段间留白。
+ * OCR editor styles: body and tables follow the theme color, and a wide table scrolls only inside its own container.
+ * The first and last nodes use a more specific selector to clear preview-layout margins, so editing a single block does not add extra space between paragraphs.
*/
export const IMAGE_PARSE_RICH_EDITOR_CLASS = `
px-4 py-3 text-sm leading-[1.85] text-foreground
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseEligibility.ts b/webdemo/frontend/src/pages/playground/utils/imageParseEligibility.ts
index 4390cbc..78a62d8 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseEligibility.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseEligibility.ts
@@ -7,12 +7,12 @@ import {
} from './documentUpload';
import { isImageParseSharedExample } from './imageParseExamples';
-/** 文档解析权限所需的最小模型上下文,避免 utils 依赖完整 Playground hook。 */
+/** Minimum model context required for document-parsing permission, so utils do not depend on the full Playground hook. */
export interface ImageParseEligibilityModel {
imageParseModel?: { id: string };
}
-/** 文档解析的 L2 凭据状态;流水线档位不依赖 API Key,因此由调用方决定是否使用。 */
+/** L2 credential state for document parsing; pipeline tiers do not depend on an API Key, so the caller decides whether to use it. */
export interface ImageParseCredentialModel {
keysLoading: boolean;
keyId?: string;
@@ -22,9 +22,9 @@ export interface ImageParseCredentialModel {
}
/**
- * 返回 L2 文档识别所需的凭据阻塞原因。
- * @param model 当前账号的密钥读取与试用状态
- * @returns 稳定的翻译键;凭据已就绪时返回 undefined
+ * Return the credential block reason for L2 document recognition.
+ * @param model secret-read and trial state of the current account
+ * @returns a stable translation key; undefined when credentials are ready
*/
export function imageParseCredentialBlocked(
model: ImageParseCredentialModel,
@@ -35,14 +35,14 @@ export function imageParseCredentialBlocked(
return 'sendKeyReading';
}
-/** 文档解析校验;用户文档需要模型权限,共享案例读取数据库预采集结果。 */
+/** Document-parsing check; a user document needs model permission, and a shared example reads precollected results from the database. */
export function imageParseBlockedReason(
attachment: Attachment | undefined,
model: ImageParseEligibilityModel | undefined,
mode: ImageParseMode = 'scored',
): string | undefined {
if (!attachment) return 'imageParseNeedImage';
- // 查看预采集结果不依赖模型权限;共享案例不允许通过此入口重新识别。
+ // Viewing precollected results does not depend on model permission; a shared example cannot be recognized again through this entry.
if (isImageParseSharedExample(attachment.id)) return undefined;
if (!model?.imageParseModel?.id) return 'imageParseNoModel';
if (mode === 'seal' && isPdfAttachment(attachment)) {
@@ -51,7 +51,7 @@ export function imageParseBlockedReason(
if (isPdfAttachment(attachment)) return undefined;
if (attachment.kind !== 'image') return 'imageParseNeedImage';
{
- // 工作台算法档位只提交 OBS 文件引用;旧历史可先补传本地预览,再发起识别。
+ // The workspace algorithm tier submits only an OBS file reference; old history may re-upload the local preview first, then start recognition.
if (!attachment.fileId && !isDocumentImageDataURL(attachment.dataUrl)) {
return 'imageParseFileReferenceRequired';
}
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseExampleSnapshot.ts b/webdemo/frontend/src/pages/playground/utils/imageParseExampleSnapshot.ts
index 1f84add..bc1f6de 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseExampleSnapshot.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseExampleSnapshot.ts
@@ -2,7 +2,7 @@ import { readPreviewAttachment } from './attachments';
import { IMAGE_PARSE_SHARED_EXAMPLES, type ImageParseExampleType } from './imageParseExamples';
import type { ImageParseSnapshot } from './imageParseHistoryTypes';
-/** 图片组只在当前工作台保留,不扩展个人历史的持久化契约。 */
+/** An image group is kept only in the current workspace and does not extend the persistence contract of personal history. */
export interface ImageParseExampleSnapshot extends ImageParseSnapshot {
imagePages?: readonly ImageParseSnapshot[];
}
@@ -51,10 +51,10 @@ async function previewFromUrl(
}
/**
- * 只读取案例静态原件;案例暂不预识别,也不请求服务端案例结果。
- * @param type 共享案例类型
- * @param signal 切换案例、账号或项目时的取消信号
- * @returns 包含原件和空结果的预览快照
+ * Read only the example's static original; examples are not pre-recognized and do not request a server example result.
+ * @param type shared example type
+ * @param signal cancellation signal when switching example, account, or project
+ * @returns a preview snapshot containing the original and an empty result
*/
export async function loadImageParseExampleSnapshot(
type: ImageParseExampleType,
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseExamples.ts b/webdemo/frontend/src/pages/playground/utils/imageParseExamples.ts
index ee7f30b..91a5c6f 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseExamples.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseExamples.ts
@@ -21,8 +21,8 @@ interface ImageParseExampleDefinition {
}
/**
- * 当前案例只用于展示用户提供的原件,正文和版面结果暂不预识别。
- * 保留固定类型标识,后续补充预采集结果时无需改动工作台入口。
+ * The current example is only for showing the original the user provided; body text and layout results are not pre-recognized for now.
+ * Keep the fixed type id, so filling in precollected results later does not require changing the workspace entry.
*/
const definitions: readonly ImageParseExampleDefinition[] = [
{
@@ -142,7 +142,7 @@ export type ImageParseExampleType =
| 'financial-table'
| 'newspaper'
| 'leave-calendar'
- // 历史测试与旧链接仍可识别为共享案例,但不再展示为入口。
+ // Historical tests and old links can still be recognized as shared examples, but are no longer shown as an entry.
| 'property'
| 'geometry'
| 'linear-algebra'
@@ -164,7 +164,7 @@ const retiredSharedExampleIds = new Set([
'example:industry-report',
]);
-/** 原件走静态资源;正文、坐标与摆正信息暂不读取。 */
+/** The original comes from a static asset; body text, coordinates, and rotation-adaptation info are not read for now. */
export const IMAGE_PARSE_SHARED_EXAMPLES = definitions.map((example) => ({
...example,
captureVersion: 'preview-20261027',
@@ -173,13 +173,13 @@ export const IMAGE_PARSE_SHARED_EXAMPLES = definitions.map((example) => ({
thumbnail: asset(example.thumbnailName) || asset(example.assetName),
}));
-/** 首屏展示全部新案例;图片和 PDF 共用同一网格。 */
+/** The first screen shows every new example; images and PDFs share the same grid. */
export const IMAGE_PARSE_WORKSPACE_EXAMPLES = IMAGE_PARSE_SHARED_EXAMPLES;
/**
- * 判断地址是否为版本固定的共享 PDF 原件。
- * @param source PDF 预览地址
- * @returns 是否可复用共享原件与页面帧
+ * Whether an address is a version-pinned shared PDF original.
+ * @param source PDF preview URL
+ * @returns whether the shared original and page frames can be reused
*/
export function isImageParseSharedPdfUrl(source: string): boolean {
return IMAGE_PARSE_SHARED_EXAMPLES.some(
@@ -187,7 +187,7 @@ export function isImageParseSharedPdfUrl(source: string): boolean {
);
}
-/** 按固定案例 ID 判断共享原件,避免案例被保存为个人云端历史。 */
+/** Decide a shared original by the fixed example ID, so an example is not saved as personal cloud history. */
export function isImageParseSharedExample(id: string): boolean {
return (
retiredSharedExampleIds.has(id) ||
@@ -196,9 +196,9 @@ export function isImageParseSharedExample(id: string): boolean {
}
/**
- * 按内置案例文件名兼容未保存来源的旧记录。
- * @param name 保存的原始文件名
- * @returns 是否归入案例分组
+ * Compatibility for old records that did not save a source, by the built-in example file name.
+ * @param name saved original file name
+ * @returns whether it belongs in the example group
*/
export function isImageParseExampleFilename(name: string): boolean {
return IMAGE_PARSE_SHARED_EXAMPLES.some((example) => example.filename === name);
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseExport.ts b/webdemo/frontend/src/pages/playground/utils/imageParseExport.ts
index a39b599..eb4b76c 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseExport.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseExport.ts
@@ -3,10 +3,10 @@ import { imageParseBlockId } from './imageParseBlocks';
import type { ImageParseLayoutBlock } from './imageParseSample';
import type { ImageParseRotationInfo } from './imageParseSample';
-/** OCR 当前结果支持的下载格式。 */
+/** Download formats supported for the current OCR result. */
export type ImageParseDownloadFormat = 'markdown' | 'json' | 'word';
-/** 下载快照不接收来源 token、API Key 或原始请求,避免凭据进入导出文件。 */
+/** A download snapshot does not accept a source token, API Key, or the raw request, so credentials do not enter the exported file. */
export interface ImageParseExportInput {
markdown: string;
blocks: readonly ImageParseLayoutBlock[];
@@ -22,11 +22,11 @@ const EXTENSIONS: Record<ImageParseDownloadFormat, string> = {
};
/**
- * 根据原始文档命名当前结果;PDF 明确标记当前页,避免误以为导出全部页。
- * @param name 原始文件名
- * @param format 下载格式
- * @param page 可选 PDF 页码,从 1 开始
- * @returns 带正确扩展名的下载文件名
+ * Name the current result from the original document; a PDF is explicitly marked with the current page so it is not mistaken for an export of every page.
+ * @param name original file name
+ * @param format download format
+ * @param page optional PDF page number, starting at 1
+ * @returns download file name with the correct extension
*/
export function imageParseExportFileName(
name: string | undefined,
@@ -38,10 +38,10 @@ export function imageParseExportFileName(
}
/**
- * 创建下载内容;Word 按需加载,JSON 只重建允许导出的版面字段。
- * @param format 用户选择的格式
- * @param input 当前可编辑正文与识别块快照
- * @returns 文件 Blob,不修改草稿或服务返回值
+ * Create download content; Word is loaded on demand, and JSON rebuilds only the layout fields that are allowed to be exported.
+ * @param format format the user selected
+ * @param input current editable body and recognition-block snapshot
+ * @returns a file Blob, without modifying the draft or the service return value
*/
export async function createImageParseExport(
format: ImageParseDownloadFormat,
@@ -68,7 +68,7 @@ export async function createImageParseExport(
h: block.h,
regions: block.regions,
ttsInvalid: block.ttsInvalid,
- // text 与 confidence 是原始识别证据;只有可定位的 Markdown 随人工编辑更新。
+ // text and confidence are the original recognition evidence; only positionable Markdown is updated with a manual edit.
text: block.text,
markdown: range ? input.markdown.slice(range.start, range.end) : block.markdown,
confidence: block.confidence,
@@ -90,9 +90,9 @@ export async function createImageParseExport(
}
/**
- * 启动本地下载并延迟释放对象 URL,给浏览器留出消费文件的时间。
- * @param blob 文件内容
- * @param fileName 下载文件名
+ * Start a local download and release the object URL after a delay, leaving the browser time to consume the file.
+ * @param blob file content
+ * @param fileName download file name
*/
export function saveImageParseExport(blob: Blob, fileName: string): void {
const url = URL.createObjectURL(blob);
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseFeatureFlags.ts b/webdemo/frontend/src/pages/playground/utils/imageParseFeatureFlags.ts
index d90c69d..0e3040b 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseFeatureFlags.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseFeatureFlags.ts
@@ -1,8 +1,8 @@
/**
- * 文档解析功能开关。当前隐藏待复核入口,保留历史结果兼容。
+ * Document-parsing feature flags. The review entry is currently hidden, and historical-result compatibility is kept.
*/
export const IMAGE_PARSE_REVIEW_ENABLED = false;
-/** Playground 表格合并默认开启;跨页与单图相邻表格共用构建开关。 */
+/** Playground table merge is on by default; cross-page tables and adjacent tables in a single image share the build flag. */
export const IMAGE_PARSE_CROSS_PAGE_MERGE_ENABLED =
import.meta.env.VITE_IMAGE_PARSE_CROSS_PAGE_MERGE !== 'false';
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseFileReference.ts b/webdemo/frontend/src/pages/playground/utils/imageParseFileReference.ts
index 459f2e8..47b6e66 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseFileReference.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseFileReference.ts
@@ -3,12 +3,12 @@ import { uploadPlaygroundFile } from '@/api/map/fileUploads';
import type { Attachment } from '../types';
import { isDocumentImageDataURL, isPdfAttachment } from './documentUpload';
-/** OCR 工作台唯一的原件引用是文件服务 fileId。 */
+/** The only original reference in the OCR workspace is the file-service fileId. */
export interface ImageParseFileReference {
fileId: string;
}
-/** 把 OCR 本地预览还原为可上传文件;仅用于补齐缺失的 OBS 文件引用。 */
+/** Turn an OCR local preview back into an uploadable file; used only to fill in a missing OBS file reference. */
function imageDataURLToFile(attachment: Attachment): File {
const comma = attachment.dataUrl.indexOf(',');
if (comma < 0) throw new Error('imageParseFileReferenceRequired');
@@ -24,10 +24,10 @@ function imageDataURLToFile(attachment: Attachment): File {
}
/**
- * 把运行时附件还原为可上传文件;图片使用本地 data URL,PDF 允许短时预览链接。
- * @param attachment 当前展示的原件
- * @param signal 取消信号
- * @returns 可交给文件服务的 File
+ * Turn a runtime attachment back into an uploadable file; images use a local data URL, and PDFs may use a short-lived preview link.
+ * @param attachment original currently on display
+ * @param signal cancellation signal
+ * @returns a File that can be handed to the file service
*/
export async function imageParseAttachmentFile(
attachment: Attachment,
@@ -59,10 +59,10 @@ interface EnsureImageParseFileReferenceOptions {
}
/**
- * 返回可用于 OCR 的 OBS 文件引用。
- * 新上传通常已有 fileId;旧历史或文件服务临时失败时,从本地预览补传一次。
- * @param options 当前附件、项目与取消信号
- * @returns 文件服务 fileId;无法补传时抛出稳定错误键
+ * Return an OBS file reference that can be used for OCR.
+ * A new upload usually already has a fileId; old history, or a temporary file-service failure, re-uploads once from the local preview.
+ * @param options current attachment, project, and cancellation signal
+ * @returns file-service fileId; throws a stable error key when it cannot be re-uploaded
*/
export async function ensureImageParseFileReference({
attachment,
@@ -91,7 +91,7 @@ export async function ensureImageParseFileReference({
} catch (error) {
signal.throwIfAborted();
if (error instanceof DOMException && error.name === 'AbortError') throw error;
- // 上传错误可能包含上游签链或内部地址,只向界面暴露稳定文案。
+ // An upload error may contain an upstream signed URL or an internal address; the UI is shown only stable copy.
throw Object.assign(new Error('imageParseFileReferenceUploadFailed'), { cause: error });
}
}
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseFormulaEditContext.ts b/webdemo/frontend/src/pages/playground/utils/imageParseFormulaEditContext.ts
index b3dafb8..7827ebd 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseFormulaEditContext.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseFormulaEditContext.ts
@@ -1,18 +1,18 @@
import { createContext } from 'react';
-/** 双击命中的公式及其在当前块内的同文出现序号,避免选择相邻的相同公式。 */
+/** The formula hit by a double-click and its occurrence index among identical text in the current block, so an adjacent identical formula is not selected. */
export interface ImageParseFormulaTarget {
latex: string;
occurrence: number;
}
-/** 公式节点共享会话入口与输入法状态,不将编辑状态写入文档。 */
+/** Formula nodes share the session entry and IME state; edit state is not written into the document. */
export const ImageParseFormulaEditContext = createContext<{
initial: ImageParseFormulaTarget | null;
onComposing: (value: boolean) => void;
} | null>(null);
-/** 从 KaTeX 的源码注解定位双击对象;正文双击不自动打开任何公式。 */
+/** Locate the double-click target from KaTeX's source annotation; a double-click on the body does not open any formula automatically. */
export function imageParseFormulaTarget(
target: EventTarget,
block: HTMLElement,
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseFormulaMarkdown.ts b/webdemo/frontend/src/pages/playground/utils/imageParseFormulaMarkdown.ts
index c697114..11c62ff 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseFormulaMarkdown.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseFormulaMarkdown.ts
@@ -1,7 +1,7 @@
import { imageParseNodeText, imageParseSourceBlocks } from './imageParseEditorSource';
import type { ImageParseLayoutBlock } from './imageParseSample';
-/** 比较公式时只忽略数学定界符、排版空白与 Markdown 转义。 */
+/** When comparing formulas, ignore only math delimiters, layout whitespace, and Markdown escaping. */
export function comparableImageParseFormula(value: string): string {
return value
.replace(/^\s*\$\$([\s\S]*?)\$\$\s*$/, '$1')
@@ -11,11 +11,11 @@ export function comparableImageParseFormula(value: string): string {
}
/**
- * 合并紧邻显示公式的同内容裸 LaTeX,保留规范的数学块与其它正文。
- * 多个原图公式块需要各自表示时不合并;重建映射必须使用返回的完整正文。
- * @param source 服务正文或旧缓存正文
- * @param blocks 原图识别块,用于区分重复表示与真正不同的原图区域
- * @returns 去除重复表示后的 Markdown
+ * Merge bare LaTeX of the same content that sits next to a display formula, keeping well-formed math blocks and the other body text.
+ * Do not merge when several original-image formula blocks each need their own representation; rebuilding the map must use the full body that is returned.
+ * @param source service body or old cached body
+ * @param blocks original-image recognition blocks, used to tell a repeated representation from a genuinely different original-image region
+ * @returns Markdown with the duplicate representation removed
*/
export function deduplicateImageParseFormulaMarkdown(
source: string,
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseHeaderFooter.test.ts b/webdemo/frontend/src/pages/playground/utils/imageParseHeaderFooter.test.ts
index 78e8fa2..8d5e9ed 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseHeaderFooter.test.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseHeaderFooter.test.ts
@@ -6,7 +6,7 @@ import {
} from './imageParseHeaderFooter';
import type { ImageParseLayoutBlock } from './imageParseSample';
-/** 按片段顺序拼正文,并给每块写上显式偏移,模拟 reconcileImageParseMarkdown 的产出。 */
+/** Join the body in fragment order and write an explicit offset on each block, simulating the output of reconcileImageParseMarkdown. */
function result(parts: Array<[ImageParseLayoutBlock['kind'], string]>) {
let markdown = '';
const blocks = parts.map(([kind, text], order) => {
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseHeaderFooter.ts b/webdemo/frontend/src/pages/playground/utils/imageParseHeaderFooter.ts
index a090131..1b4a269 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseHeaderFooter.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseHeaderFooter.ts
@@ -10,8 +10,8 @@ import type { ImageParseLayoutBlock } from './imageParseSample';
const stableCache = new WeakMap<ImageParseSdkResult, ImageParseSdkResult>();
/**
- * 给缺少服务端 id 的块补上基于原始顺序的稳定 id。
- * 过滤页眉页脚会改变数组下标,提前固定 id 才能让选中态和滚动锚点跨开关保持。
+ * Fill in a stable id based on original order for blocks that lack a server id.
+ * Filtering headers and footers changes array indexes; fixing the id first lets selection and scroll anchors survive the toggle.
*/
export function stabilizeImageParseResult(result: ImageParseSdkResult): ImageParseSdkResult {
if (result.blocks.every((block) => block.id)) return result;
@@ -27,14 +27,14 @@ export function stabilizeImageParseResult(result: ImageParseSdkResult): ImagePar
return stable;
}
-/** 页眉、页脚与页码(页码在 blockKind 里归入 footer)。 */
+/** Header, footer, and page number (page numbers are grouped into footer in blockKind). */
export function isImageParseHeaderFooter(block: ImageParseLayoutBlock): boolean {
return isImageParseHeaderFooterBlock(block);
}
/**
- * 关掉页眉 / 页脚 / 页码时,跳过这几类再按块生成一遍。
- * 其余块的起止位置随新正文后移;没有可去的块时原样返回同一对象。
+ * When header / footer / page number are turned off, skip those kinds and generate again block by block.
+ * Start and end positions of the remaining blocks shift with the new body; when nothing can be removed, return the same object unchanged.
*/
export function hideImageParseHeaderFooter(result: ImageParseSdkResult): ImageParseSdkResult {
const stable = stabilizeImageParseResult(result);
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseHighlight.ts b/webdemo/frontend/src/pages/playground/utils/imageParseHighlight.ts
index 323c593..ad067c5 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseHighlight.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseHighlight.ts
@@ -2,7 +2,7 @@ import type { ImageParseTextRange } from './imageParseBlocks';
import { comparableImageParseFormula } from './imageParseFormulaMarkdown';
import { groupImageParseHighlightNodes } from './imageParseHighlightGroups';
-/** 消毒后的预览语法树节点;定位与分组只添加可信属性。 */
+/** Sanitized preview syntax-tree node; positioning and grouping only add trusted attributes. */
export interface ImageParsePreviewNode {
type: string;
tagName?: string;
@@ -12,7 +12,7 @@ export interface ImageParsePreviewNode {
position?: { start: { offset?: number }; end: { offset?: number } };
}
-/** 渲染后的语义节点与原图识别块的对应关系。 */
+/** Correspondence between a rendered semantic node and an original-image recognition block. */
export interface ImageParseLinkedRange {
id: string;
range: ImageParseTextRange;
@@ -33,8 +33,8 @@ const BLOCK_TAGS = new Set([
]);
/**
- * 在 Markdown 语法树上标记对应的语义块,不注入 HTML,也不拆散表格或公式。
- * 高亮保留整块的 Markdown 结构,源偏移必须与传入渲染器的文本一致。
+ * Mark the matching semantic block on the Markdown syntax tree, without injecting HTML and without breaking tables or formulas apart.
+ * Highlighting keeps the whole block's Markdown structure, and source offsets must match the text passed to the renderer.
*/
export function imageParseHighlight(
range?: ImageParseTextRange,
@@ -51,7 +51,7 @@ export function imageParseHighlight(
maxEnds.push(Math.max(maxEnds[index - 1] ?? -Infinity, item.range.end));
});
const matches = (start: number, end: number) => {
- // 前缀最大终点支持重叠范围;普通按阅读顺序排列的块只访问相邻命中项。
+ // The prefix maximum end supports overlapping ranges; blocks in ordinary reading order only visit adjacent hits.
let low = 0;
let high = indexed.length;
while (low < high) {
@@ -92,8 +92,8 @@ export function imageParseHighlight(
}
collect(tree);
- // 兼容已经打开的旧草稿:只合并紧邻的重复表示,将旧范围转移到显示公式。
- // 不跨正文寻找相同公式,也不把两个不同原图区域合并为一个点击目标。
+ // Compatible with old drafts already open: only merge an adjacent duplicate representation, and move the old range onto the display formula.
+ // Do not search across the body for the same formula, and do not merge two different original-image regions into one click target.
if (deduplicateFormulas) {
const children: ImageParsePreviewNode[] = [];
let previousMath: ImageParsePreviewNode | undefined;
@@ -146,18 +146,18 @@ export function imageParseHighlight(
const highlighted =
aliasedHighlights.has(node) || Boolean(range && start < range.end && end > range.start);
const matching = matchingIds.get(node) ?? [];
- // 同一个语义节点对应多个原图块时不猜测,避免点错位置。
+ // When one semantic node corresponds to several original-image blocks, do not guess, so the click does not land in the wrong place.
const linkedId = matching.length === 1 ? matching[0] : undefined;
if (highlighted || matching.length) {
const existingClass = node.properties?.className;
const classes = Array.isArray(existingClass) ? existingClass : [];
- // 表格由专用外壳控制描边与圆角,不能被普通文本选中样式覆盖。
+ // Tables are stroked and rounded by a dedicated shell and must not be covered by the ordinary text selection style.
const highlightClasses =
highlighted && node.tagName !== 'table'
? ['ring-1', 'ring-inset', 'ring-primary/60', 'rounded-sm']
: [];
if (node.tagName === 'pre') {
- // KaTeX 会替换 display-math 的 pre 节点,用外壳保留定位标记。
+ // KaTeX replaces the pre node of display-math; a shell keeps the positioning marker.
const original = { ...node };
node.tagName = 'div';
node.children = [original];
@@ -189,7 +189,7 @@ export function imageParseHighlight(
}
: {}),
};
- // 已命中一个语义块,避免列表项与内部段落重复创建点击目标。
+ // One semantic block has already been hit, so a list item and its inner paragraph do not each create a click target.
return;
}
}
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseHighlightGroups.ts b/webdemo/frontend/src/pages/playground/utils/imageParseHighlightGroups.ts
index 0ccb852..b891703 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseHighlightGroups.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseHighlightGroups.ts
@@ -8,8 +8,8 @@ interface LinkedNode {
const CONTAINERS = new Set(['div', 'ul', 'ol']);
/**
- * 连续语义节点属于同一 OCR 块时统一外层定位与编辑范围,正文结构保持不变。
- * 列表必须整体同属一块才分组,避免在 ul/ol 内插入非法容器或合并其他区块。
+ * When consecutive semantic nodes belong to the same OCR block, share the outer positioning and edit range, and leave the body structure unchanged.
+ * A list is grouped only when the whole list belongs to one block, so an illegal container is not inserted inside ul/ol and other blocks are not merged.
*/
export function groupImageParseHighlightNodes(
tree: ImageParsePreviewNode,
@@ -80,7 +80,7 @@ export function groupImageParseHighlightNodes(
pending.push(node);
} else {
flush();
- // 不进入列表重新分组,列表项仍由原来的 li 保持结构和独立定位。
+ // Do not regroup inside a list; list items still keep their structure and independent positioning on the original li.
if (node.tagName === 'div') group(node);
children.push(node);
}
@@ -97,7 +97,7 @@ function isWhitespace(node: ImageParsePreviewNode): boolean {
function groupEditNodes(nodes: ImageParsePreviewNode[]): ImageParsePreviewNode[] {
const elements = nodes.filter((node) => !isWhitespace(node));
- // 仅合并全部具有可信源范围的编辑外壳;保留不支持编辑的内容边界。
+ // Merge only edit shells that all have a trusted source range; keep the boundary of content that cannot be edited.
if (
!elements.every(
(node) =>
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseHistory.ts b/webdemo/frontend/src/pages/playground/utils/imageParseHistory.ts
index f9c509e..cdeac5e 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseHistory.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseHistory.ts
@@ -15,7 +15,7 @@ export type {
ImageParseHistoryStorage,
} from './imageParseHistoryTypes';
-/** 每个用户/项目最多保存 20 个任务;实际可用空间仍由浏览器决定。 */
+/** Each user/project saves at most 20 tasks; usable space is still decided by the browser. */
export const IMAGE_PARSE_HISTORY_LIMIT = 20;
const DATABASE = 'map-ocr-history';
const STORE = 'tasks';
@@ -27,7 +27,7 @@ function unavailableStorage(): Error {
return failure;
}
-/** 返回最新的有限任务列表,不修改调用方数组。 */
+/** Return the latest bounded task list without modifying the caller's array. */
export function newestImageParseHistory(
entries: readonly ImageParseHistoryEntry[],
): ImageParseHistoryEntry[] {
@@ -131,7 +131,7 @@ async function transaction<T>(
});
}
-/** IndexedDB 本地任务存储;写入与淘汰在同一事务内完成,不访问网络。 */
+/** IndexedDB local task store; writes and eviction finish in the same transaction and do not touch the network. */
export const imageParseHistoryStorage: ImageParseHistoryStorage = {
list: (scope) =>
transaction(scope, 'readonly', (store, key, done) => {
@@ -147,7 +147,7 @@ export const imageParseHistoryStorage: ImageParseHistoryStorage = {
const request = store.get([key, id]);
request.onsuccess = () => {
const existing = readEntries([request.result], key)[0];
- // 恢复必须写回原任务;已删除或身份不匹配时不重新创建记录。
+ // Restore must write back to the original task; do not create a new record when it was deleted or the identity does not match.
if (entryId && (!existing || existing.snapshot.attachment.id !== snapshot.attachment.id)) {
abort(new Error('imageParseHistoryEntryUnavailable'));
return;
@@ -161,7 +161,7 @@ export const imageParseHistoryStorage: ImageParseHistoryStorage = {
const all = store.index('scopeKey').getAll(key);
all.onsuccess = () => {
const rows = all.result as Array<{ id: string; createdAt: number }>;
- // 原创建时间决定排序;更新结果和阅读位置不将旧任务移到顶部。
+ // Original creation time decides sort order; updating the result and reading position does not move an old task to the top.
rows.sort((a, b) => b.createdAt - a.createdAt || b.id.localeCompare(a.id));
for (const row of rows.slice(IMAGE_PARSE_HISTORY_LIMIT)) store.delete([key, row.id]);
done(entry);
@@ -198,10 +198,10 @@ function storageAccessFailure(failure: unknown): boolean {
}
/**
- * 创建单个用户/项目的页面历史会话;持久化不可用时保留临时记录,不清空数据库。
- * @param scope 当前用户与项目
- * @param storage 持久化实现
- * @returns 范围绑定的历史操作及是否仅在当前页面保存
+ * Create a page-history session for a single user/project; when persistence is unavailable, keep a temporary record and do not clear the database.
+ * @param scope current user and project
+ * @param storage persistence implementation
+ * @returns scope-bound history operations and whether they are saved only for the current page
*/
export function createImageParseHistorySession(
scope: ImageParseHistoryScope,
@@ -222,7 +222,7 @@ export function createImageParseHistorySession(
if (!temporary) {
try {
const persisted = await storage.list(scope);
- // 降级后不再用晚到的数据库读取覆盖页面内的新结果或删除操作。
+ // After falling back, a late database read must not overwrite a new in-page result or a delete.
if (!temporary) items = persisted;
} catch {
temporary = true;
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseHistoryAttachment.ts b/webdemo/frontend/src/pages/playground/utils/imageParseHistoryAttachment.ts
index dd4569c..6a0c3f8 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseHistoryAttachment.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseHistoryAttachment.ts
@@ -7,12 +7,12 @@ const LOCAL_IMAGE = /^data:image\/(?!svg(?:\+xml)?;)[a-z0-9.+-]+;base64,[a-z\d+/
const LOCAL_PDF = /^data:application\/pdf;base64,[a-z\d+/=\s]+$/i;
const FILE_UPLOAD_ID = /^[a-zA-Z0-9_-]{3,80}$/;
-/** 快照清洗模式:本地缓存、云端保存与运行时恢复各有不同原件边界。 */
+/** Snapshot cleaning mode: local cache, cloud save, and runtime restore each have a different original-file boundary. */
export interface SanitizeImageParseSnapshotOptions {
storage?: 'local' | 'cloud';
- /** 仅运行时恢复允许 fileId 位图/PDF 签链及固定共享 PDF;保存入口不得开启。 */
+ /** Only runtime restore may use a fileId bitmap/PDF signed URL and the fixed shared PDF; save entries must not enable it. */
allowHydratedFileURL?: boolean;
- /** 仅共享图片案例运行时恢复允许空结果,不用于历史保存。 */
+ /** Only runtime restore of a shared image example may have an empty result; it is not used when saving history. */
allowSharedImagePreview?: boolean;
}
@@ -31,7 +31,7 @@ function isFileURL(value: string): boolean {
}
}
-/** 按存储和运行时边界清洗历史附件,签链仅用于预览,永不进入持久化存档。 */
+/** Clean history attachments against storage and runtime boundaries. Signed URLs are for preview only and never enter the persisted archive. */
export function sanitizeImageParseHistoryAttachment(
value: unknown,
options: SanitizeImageParseSnapshotOptions,
@@ -92,7 +92,7 @@ export function sanitizeImageParseHistoryAttachment(
};
}
if (!dataUrl) return null;
- // 不使用 spread:附件可能携带对象存储标识或运行时注入的凭据。
+ // Do not use spread: an attachment may carry an object-storage id or a credential injected at runtime.
return {
id: input.id,
kind,
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseHistoryCache.ts b/webdemo/frontend/src/pages/playground/utils/imageParseHistoryCache.ts
index eafdf38..614a193 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseHistoryCache.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseHistoryCache.ts
@@ -1,6 +1,6 @@
import type { QueryClient, QueryKey } from '@tanstack/react-query';
-/** 保存或删除后仅失效该记录及其附件别名,其他详情保留短缓存。 */
+/** After a save or delete, invalidate only that record and its attachment aliases; other details keep a short cache. */
export async function invalidateImageParseHistoryRecord(
client: QueryClient,
queryKey: QueryKey,
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseHistoryContent.ts b/webdemo/frontend/src/pages/playground/utils/imageParseHistoryContent.ts
index 11b4c8f..dc077ed 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseHistoryContent.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseHistoryContent.ts
@@ -1,10 +1,10 @@
import type { ImageParseSnapshot } from './imageParseHistoryTypes';
/**
- * 比较需要云端存档的内容;PDF 页结果是权威内容,当前页及本地裁图不触发整篇上传。
- * @param previous 上一次已观察的完整快照
- * @param next 当前完整快照
- * @returns 附件、模式及实际识别内容是否未变
+ * Compare content that needs a cloud archive; PDF page results are the authoritative content, and the current page and local crops do not trigger a full-document upload.
+ * @param previous last full snapshot that was observed
+ * @param next current full snapshot
+ * @returns whether the attachment, mode, and actual recognition content are unchanged
*/
export function sameImageParseHistoryContent(
previous: ImageParseSnapshot | null | undefined,
@@ -29,7 +29,7 @@ export function sameImageParseHistoryContent(
const after = next.pdf.results;
if (before === after) return true;
const pages = Object.keys(before);
- // 使用不可变结果的引用,避免滚动时序列化数百页正文或比较仅在客户端使用的裁图。
+ // Use the reference of the immutable result, so scrolling does not serialize hundreds of pages of body text or compare crops used only on the client.
return (
pages.length === Object.keys(after).length &&
pages.every((page) => {
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseHistoryMigration.ts b/webdemo/frontend/src/pages/playground/utils/imageParseHistoryMigration.ts
index 159fc73..aeaa0c5 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseHistoryMigration.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseHistoryMigration.ts
@@ -19,24 +19,24 @@ async function migrate(scope: ImageParseHistoryScope): Promise<MigrationResult>
try {
entries = await imageParseHistoryStorage.list(scope);
} catch {
- // 浏览器存储不可用不影响云端历史,也不再降级为临时持久化。
+ // Browser storage being unavailable does not affect cloud history, and it no longer falls back to temporary persistence.
return result;
}
for (const entry of [...entries].reverse()) {
try {
await saveImageParseHistory(scope, entry.snapshot, undefined, true);
result.changed = true;
- // 只有服务端确认持久化后才移除这一个账号/项目的旧缓存。
+ // Remove the old cache for this one account/project only after the server confirms it was persisted.
await imageParseHistoryStorage.remove(scope, entry.id);
} catch {
- // 单条超限或已删除不能阻断其它有效记录;失败的副本留在原浏览器。
+ // One record over the limit or already deleted must not block other valid records; the failed copy stays in the original browser.
result.pending = true;
}
}
return result;
}
-/** 先确认云端可读,再迁移当前账号的旧记录;失败时保留旧缓存并显示可重试提示。 */
+/** Confirm the cloud copy is readable first, then migrate old records for the current account; on failure keep the old cache and show a retryable notice. */
export async function loadImageParseHistoryPage(
scope: ImageParseHistoryScope,
offset: number,
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseHistoryQueue.ts b/webdemo/frontend/src/pages/playground/utils/imageParseHistoryQueue.ts
index 47d2377..cd4531e 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseHistoryQueue.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseHistoryQueue.ts
@@ -1,11 +1,11 @@
-/** OCR 历史自动保存队列的运行时状态。 */
+/** Runtime state of the OCR history autosave queue. */
export interface ImageParseHistoryQueue {
tail: Promise<void>;
active?: { id: string; attachmentId: string };
deleted: Set<string>;
}
-/** 创建隔离账号范围的保存队列;切换账号后直接丢弃旧队列。 */
+/** Create a save queue isolated by account scope; after an account switch, discard the old queue directly. */
export function createImageParseHistoryQueue(): ImageParseHistoryQueue {
return { tail: Promise.resolve(), deleted: new Set<string>() };
}
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseHistorySnapshot.ts b/webdemo/frontend/src/pages/playground/utils/imageParseHistorySnapshot.ts
index d9c8e6a..77bd4f6 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseHistorySnapshot.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseHistorySnapshot.ts
@@ -102,12 +102,12 @@ function result(
)
) {
const reconciled = reconcileImageParseMarkdown(deduplicated, safe);
- // 恢复旧映射只接受正文不变的结果,不向已编辑的缓存补写识别原文。
+ // Restoring an old mapping accepts only a result whose body is unchanged, and does not write recognition source text back into an already edited cache.
if (reconciled.markdown === deduplicated) {
parsed = validateImageParseSdkResult(reconciled, { allowEmptyMarkdown });
}
}
- // OCR 范围签名允许随历史缓存;只保留白名单字段,不按本地时间丢弃过期原件。
+ // An OCR range signature may travel with the history cache; keep only allowlisted fields, and do not drop an expired original by local time.
const safeSource = sanitizeImageParseSource(source);
const safeRotation = sanitizeImageParseRotation(rotation);
return {
@@ -134,7 +134,7 @@ function pdfSnapshot(value: unknown): PdfImageParseSnapshot | null {
!record(value.results)
)
return null;
- // 刚上传、页数还未知时先记下原件,打开后再继续解析。
+ // Just after upload, while the page count is still unknown, record the original first and continue parsing after it is opened.
if (value.pages === 0) return { page: 1, pages: 0, results: {} };
const results: Record<number, PdfPageResult> = {};
for (const [index, page] of Object.entries(value.results)) {
@@ -165,10 +165,10 @@ function pdfSnapshot(value: unknown): PdfImageParseSnapshot | null {
}
/**
- * 校验快照并按字段白名单重建;远程原件仅允许恢复阶段的 fileId 签链及固定共享 PDF。
- * @param value hook 快照、IndexedDB 或云端接口读出的不可信数据
- * @param options local 保留原件 dataUrl;cloud 优先只保存稳定 fileId
- * @returns 可保存快照,损坏/示例数据返回 null
+ * Validate the snapshot and rebuild it from a field allowlist; a remote original may only be a fileId signed URL from the restore phase, or the fixed shared PDF.
+ * @param value untrusted data read from a hook snapshot, IndexedDB, or the cloud API
+ * @param options local keeps the original dataUrl; cloud prefers to save only the stable fileId
+ * @returns a snapshot that can be saved; null for corrupt or example data
*/
export function sanitizeImageParseSnapshot(
value: unknown,
@@ -225,8 +225,8 @@ export function sanitizeImageParseSnapshot(
};
}
const parsed = result(value.markdown, value.layout, value.source, value.rotation, mode === 'seal');
- // 图片刚上传、识别还没结束时只保留原件,打开后继续识别。
- // 共享案例只在预览场景允许空结果;预览其他图片时不得把空正文当成识别结果。
+ // Just after an image is uploaded, before recognition has finished, keep only the original and continue recognition after it is opened.
+ // A shared example may have an empty result only in the preview scene; when previewing another image, an empty body must not be treated as a recognition result.
if (
!parsed &&
options.allowSharedImagePreview !== true &&
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseHistoryTypes.ts b/webdemo/frontend/src/pages/playground/utils/imageParseHistoryTypes.ts
index 4d13b7c..52dae47 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseHistoryTypes.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseHistoryTypes.ts
@@ -5,57 +5,57 @@ import type { ImageParseLayoutBlock } from './imageParseSample';
import type { ImageParseRotationInfo } from './imageParseSample';
import type { PdfPageResult } from './pdfImageParse';
-/** PDF 缓存只保存已结束任务的页结果及阅读位置,不包含解析器或网络请求。 */
+/** A PDF cache stores only page results of finished tasks and the reading position, with no parser or network request. */
export interface PdfImageParseSnapshot {
page: number;
pages: number;
results: Record<number, PdfPageResult>;
}
-/** 完成任务的可恢复快照;本地缓存含 dataUrl,云端新记录可只保存稳定 fileId。 */
+/** Restorable snapshot of a finished task; the local cache includes a dataUrl, and a new cloud record may save only the stable fileId. */
export interface ImageParseSnapshot {
attachment: Attachment;
mode: ImageParseMode;
- /** 关键信息抽取字段;仅 kie 模式保存,恢复后用于重新识别。 */
+ /** Key information extraction fields; saved only in kie mode, and used to run recognition again after restore. */
fields?: readonly string[];
markdown: string;
layout: readonly ImageParseLayoutBlock[];
- /** 保留服务端原始识别范围;有效期只限制重生成,不影响历史查看。 */
+ /** Keep the original recognition range from the server; expiry only limits regeneration and does not affect viewing history. */
source?: ImageParseSource;
- /** 服务端旋转摆正信息;用于恢复原图与识别框的对齐。 */
+ /** Server rotation-adaptation info; used to restore alignment between the original image and recognition boxes. */
rotation?: ImageParseRotationInfo;
- /** 本页识别的 request_id;多页示例据此请求跨页表格合并。 */
+ /** request_id of this page's recognition; a multi-page example uses it to request a cross-page table merge. */
requestId?: string;
pdf?: PdfImageParseSnapshot;
}
-/** OCR 完整任务快照,用于云端恢复和兼容旧浏览器记录。 */
+/** Full OCR task snapshot, used for cloud restore and compatibility with old browser records. */
export interface ImageParseHistoryEntry {
id: string;
createdAt: number;
snapshot: ImageParseSnapshot;
}
-/** 云端列表只读取摘要,原始文件和正文在打开记录时按需获取。 */
+/** The cloud list reads only a summary; the original file and body are fetched on demand when a record is opened. */
export interface ImageParseHistorySummary {
id: string;
createdAt: number;
attachmentId: string;
name: string;
- /** 记录所属识别模式;摘要仅用于展示与调试,不参与权限判断。 */
+ /** Recognition mode the record belongs to; the summary is only for display and debugging and does not take part in permission checks. */
mode?: ImageParseMode;
}
-/** 用户与项目必须同时存在,避免匿名或跨项目缓存复用。 */
+/** User and project must both be present, so an anonymous or cross-project cache is not reused. */
export interface ImageParseHistoryScope {
userId: string;
projectId: string;
}
-/** 侧栏历史入口任务;standard 兼容全部非 KIE 历史模式。 */
+/** Sidebar history entry task; standard is compatible with every non-KIE history mode. */
export type ImageParseHistoryTask = 'standard' | 'kie';
-/** 本地持久化边界;失败由调用 hook 消化,不能阻断 OCR。 */
+/** Local persistence boundary; failure is absorbed by the calling hook and must not block OCR. */
export interface ImageParseHistoryStorage {
list: (scope: ImageParseHistoryScope) => Promise<ImageParseHistoryEntry[]>;
save: (
@@ -66,16 +66,16 @@ export interface ImageParseHistoryStorage {
remove: (scope: ImageParseHistoryScope, id: string) => Promise<void>;
}
-/** 身份就绪后读写云端个人历史,snapshot 为已完成且非演示的结果。 */
+/** Once identity is ready, read and write cloud personal history. snapshot is a finished, non-demo result. */
export interface UseImageParseHistoryOptions {
userId?: string | null;
projectId?: string | null;
- /** 当前入口任务;standard 显示非 KIE 历史,kie 只显示关键信息抽取。 */
+ /** Current entry task; standard shows non-KIE history, and kie shows only key information extraction. */
task?: ImageParseHistoryTask;
snapshot?: ImageParseSnapshot | null;
}
-/** 轻量列表与按需恢复入口,任何存档失败都不阻断识别。 */
+/** Lightweight list and on-demand restore entry. Any archive failure must not block recognition. */
export interface UseImageParseHistoryResult {
items: ImageParseHistorySummary[];
loading: boolean;
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseHtmlMath.ts b/webdemo/frontend/src/pages/playground/utils/imageParseHtmlMath.ts
index 8449f86..48c3e68 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseHtmlMath.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseHtmlMath.ts
@@ -20,12 +20,12 @@ interface MathPart {
}
const PARSER = unified().use(remarkParse).use(remarkMath);
-// HTML 的缩进是排版空白;代码语义只由外层 code/pre 标签决定。
+// HTML indentation is layout whitespace; code semantics are decided only by the outer code/pre tags.
PARSER.data('micromarkExtensions', [{ disable: { null: ['codeIndented'] } }]);
const PROTECTED_TAGS = new Set(['code', 'pre', 'script', 'style', 'textarea', 'title']);
const PROTECTED_SELECTOR = [...PROTECTED_TAGS].join(',');
-/** 用现有 Markdown 数学解析器提取显式公式,非公式文本不经过 Markdown 转换。 */
+/** Extract explicit formulas with the existing Markdown math parser; non-formula text does not go through Markdown conversion. */
function mathParts(value: string): MathPart[] {
if (!/[$\\]/.test(value)) return [{ value }];
const protectedRanges: { start: number; end: number }[] = [];
@@ -48,7 +48,7 @@ function mathParts(value: string): MathPart[] {
const opening = raw.match(/^\${2,}/)?.[0].length ?? 0;
const lastLine = raw.slice(raw.lastIndexOf('\n') + 1).trim();
const closing = lastLine.match(/^\${2,}$/)?.[0].length ?? 0;
- // remark 允许 EOF 结束数学围栏;OCR 未闭合或带元数据的内容必须原样保留。
+ // remark allows EOF to end a math fence; OCR content that is unclosed or carries metadata must be kept as-is.
if (!raw.includes('\n') || closing < opening || node.meta) return;
}
formulas.push({
@@ -62,7 +62,7 @@ function mathParts(value: string): MathPart[] {
node.children?.forEach(visit);
}
visit(PARSER.parse(value) as MathNode);
- // 原生公式直接生成节点,不能经美元符中转,否则正文的 \$ 或 verb 会截断公式。
+ // A native formula produces a node directly and must not be routed through dollar signs, or a \$ or verb in the body would cut the formula off.
formulas.push(...nativeMathRanges(value, protectedRanges));
const parts: MathPart[] = [];
let cursor = 0;
@@ -78,8 +78,8 @@ function mathParts(value: string): MathPart[] {
}
/**
- * HTML 解析后将单元格的显式公式转为 KaTeX 输入节点,不改变源码及表格位置。
- * @returns 供 OCR 文档预览使用的语法树转换器;代码和单元格外文本不处理
+ * After HTML parsing, turn explicit formulas in cells into KaTeX input nodes, without changing the source or the table position.
+ * @returns a syntax-tree transform for OCR document preview; code and text outside cells are not processed
*/
export function imageParseHtmlMath() {
return (tree: MathNode, file: { value?: unknown }) => {
@@ -90,7 +90,7 @@ export function imageParseHtmlMath() {
let cell = inCell;
if (node.tagName === 'td' || node.tagName === 'th') {
const start = node.position?.start.offset;
- // GFM 单元格已经经过 remark-math 和反斜杠解码,禁止再次推断它的文本。
+ // A GFM cell has already passed through remark-math and backslash decoding; do not infer its text again.
cell = start !== undefined && /^<(?:td|th)(?:\s|>)/i.test(source.slice(start, start + 4));
}
node.children = node.children.flatMap((child): MathNode[] => {
@@ -115,9 +115,9 @@ export function imageParseHtmlMath() {
}
/**
- * 富文本导入前将 HTML 单元格的公式转为已有数学扩展支持的 code 节点。
- * @param root 已由 DOMParser 解析且通过编辑器支持性检查的 HTML
- * @returns 是否转换了公式;属性、代码和转义 HTML 保持原有语义
+ * Before rich-text import, turn formulas in HTML cells into code nodes the existing math extension supports.
+ * @param root HTML already parsed by DOMParser and checked as supported by the editor
+ * @returns whether a formula was converted; attributes, code, and escaped HTML keep their original meaning
*/
export function replaceImageParseHtmlMath(root: ParentNode): boolean {
const document = root.ownerDocument ?? (root as Document);
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseKie.ts b/webdemo/frontend/src/pages/playground/utils/imageParseKie.ts
index be939e1..a7675ad 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseKie.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseKie.ts
@@ -1,8 +1,8 @@
-/** 关键信息抽取字段约束与结果展示解析,与后端校验保持一致。 */
+/** Key information extraction field constraints and result-display parsing, kept consistent with backend validation. */
export const MAX_IMAGE_PARSE_KIE_FIELDS = 20;
-/** 将批量输入按常见分隔符拆分,保留字段内部空格和原始顺序。 */
+/** Split batch input on common separators, keeping spaces inside a field and the original order. */
export function splitImageParseKieFields(value: string): string[] {
return value
.split(/[,,、;;\r\n\t]+/)
@@ -10,7 +10,7 @@ export function splitImageParseKieFields(value: string): string[] {
.filter(Boolean);
}
-/** 字段在去空白后必须非空、唯一,且不能包含会破坏提示词的引号或换行。 */
+/** After whitespace is removed, a field must be non-empty and unique, and must not contain quotes or newlines that would break the prompt. */
export function imageParseKieFieldsError(fields: readonly string[]): string | undefined {
if (fields.length === 0) return 'imageParseKieFieldsRequired';
if (fields.length > MAX_IMAGE_PARSE_KIE_FIELDS) return 'imageParseKieFieldsTooMany';
@@ -25,12 +25,12 @@ export function imageParseKieFieldsError(fields: readonly string[]): string | un
return undefined;
}
-/** 提交前统一去掉首尾空白;后端会再次校验,不能只依赖前端。 */
+/** Strip leading and trailing whitespace before submit; the backend validates again, so the frontend must not be the only check. */
export function normalizeImageParseKieFields(fields: readonly string[]): string[] {
return fields.map((field) => field.trim()).filter(Boolean);
}
-/** 解析模型返回的 JSON 对象;不是对象或不是 JSON 时返回 null,保留原文展示。 */
+/** Parse the JSON object returned by the model; return null when it is not an object or not JSON, and keep the original text for display. */
export function imageParseKieValues(content: string): Record<string, string> | null {
const trimmed = content.trim();
const unfenced = trimmed
@@ -55,7 +55,7 @@ export function imageParseKieValues(content: string): Record<string, string> | n
}
}
-/** 按请求顺序生成结果行,统一正文与工具栏对漏字段、空值和占位值的判断。 */
+/** Build result rows in request order, so the body and the toolbar judge missing fields, empty values, and placeholder values the same way. */
export function imageParseKieRows(
values: Record<string, string> | null,
fields: readonly string[],
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseKieExamples.ts b/webdemo/frontend/src/pages/playground/utils/imageParseKieExamples.ts
index 48d6bdb..81ba054 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseKieExamples.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseKieExamples.ts
@@ -1,10 +1,10 @@
import restaurantReceiptImage from '../assets/ocr-examples/kie-restaurant-receipt.png';
import taxiReceiptImage from '../assets/ocr-examples/kie-taxi-receipt.png';
-/** 关键信息抽取内置案例类型。 */
+/** Built-in example type for key information extraction. */
export type ImageParseKieExampleType = 'taxi-receipt' | 'restaurant-receipt';
-/** 关键信息抽取内置案例;字段使用翻译键,选择后按当前语言生成请求字段。 */
+/** Built-in examples for key information extraction; fields use translation keys and, once selected, generate request fields in the current language. */
export interface ImageParseKieExample {
id: string;
type: ImageParseKieExampleType;
@@ -16,7 +16,7 @@ export interface ImageParseKieExample {
fields: readonly string[];
}
-/** 两张真实票据原件,与文档解析案例一样可作为工作台入口。 */
+/** Two real receipt originals, which can be workspace entries the same way document-parsing examples can. */
export const IMAGE_PARSE_KIE_EXAMPLES: readonly ImageParseKieExample[] = [
{
id: 'example:kie-taxi-receipt',
@@ -51,10 +51,10 @@ export const IMAGE_PARSE_KIE_EXAMPLES: readonly ImageParseKieExample[] = [
];
/**
- * 把内置案例静态资源还原为可上传文件。
- * @param example 当前案例
- * @param signal 取消信号
- * @returns 图片 PNG 文件
+ * Turn a built-in example's static asset back into an uploadable file.
+ * @param example current example
+ * @param signal cancellation signal
+ * @returns image PNG file
*/
export async function imageParseKieExampleFile(
example: ImageParseKieExample,
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseKieTourSteps.ts b/webdemo/frontend/src/pages/playground/utils/imageParseKieTourSteps.ts
index 7b93bbb..070484d 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseKieTourSteps.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseKieTourSteps.ts
@@ -9,22 +9,22 @@ interface ImageParseKieTourStepsOptions {
}
/**
- * 构造关键信息抽取引导:先选择示例,再配置字段并开始抽取,最后核对结果。
- * @param options 翻译与当前任务状态
- * @returns 示例、字段、开始抽取和结果步骤
+ * Build the key information extraction tour: choose an example, then configure fields and start extraction, and finally check the result.
+ * @param options translations and current task state
+ * @returns example, fields, start-extraction, and result steps
*/
export function imageParseKieTourSteps({
t,
hasDocument = () => false,
hasResult = () => false,
}: ImageParseKieTourStepsOptions): DriveStep[] {
- // 字段配置和结果都会随任务阶段挂载;缺失目标先跳过,等待生命周期恢复。
+ // Field configuration and the result both mount with the task phase; a missing target is skipped first, and the lifecycle restores it later.
const workspaceStep = { skipMissingElement: true, waitForElement: 0 };
const steps: DriveStep[] = [];
if (!hasDocument()) {
steps.push({
...workspaceStep,
- // 示例载入后选择区会卸载;该步骤已完成,回退时由 driver.js 跳过而不是停在无目标遮罩。
+ // After the example loads, the picker unmounts; that step is already done, and going back lets driver.js skip it instead of stopping on a mask with no target.
element: '[data-tour="image-parse-kie-examples"]',
popover: {
title: t('imageParseKieTourExampleTitle'),
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseLineBreaks.ts b/webdemo/frontend/src/pages/playground/utils/imageParseLineBreaks.ts
index e88a097..7eb06da 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseLineBreaks.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseLineBreaks.ts
@@ -5,16 +5,16 @@ interface DocumentNode {
children?: DocumentNode[];
}
-/** OCR 文本中的显式 br 形态;双层转义在 Markdown 解码一次后仍会残留实体。 */
+/** Explicit br forms in OCR text; a double-escaped form still leaves an entity after one Markdown decode. */
const TEXT_LINE_BREAK = /(?:<|&(?:lt|#60|#x3c);)br\s*\/?\s*(?:>|&(?:gt|#62|#x3e);)/gi;
const TEXT_LINE_BREAK_ONCE = new RegExp(TEXT_LINE_BREAK.source, 'i');
-/** 将文字内容中的显式 br 转成目标字符;不修改其它转义 HTML。 */
+/** Turn an explicit br in text content into the target character; do not modify other escaped HTML. */
export function imageParseTextLineBreaks(value: string, replacement: string) {
return value.replace(TEXT_LINE_BREAK, replacement);
}
-/** 将 DOM 正文中的显式 br 替换为换行元素,返回是否发生转换;代码保持原样。 */
+/** Replace an explicit br in DOM body text with a line-break element and return whether a conversion happened; code stays as-is. */
export function replaceImageParseTextLineBreaks(root: ParentNode): boolean {
const document = root.ownerDocument ?? (root as Document);
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
@@ -41,8 +41,8 @@ export function replaceImageParseTextLineBreaks(root: ParentNode): boolean {
}
/**
- * 将 OCR 预览中被转义的 br 文本恢复为换行节点,不改写源文档或解析其他 HTML。
- * @returns HTML 解析后的语法树转换器;代码块与行内代码保持原样
+ * Restore escaped br text in the OCR preview to line-break nodes, without rewriting the source document or parsing other HTML.
+ * @returns a syntax-tree transform after HTML parsing; code blocks and inline code stay as-is
*/
export function imageParseLineBreaks() {
return (tree: DocumentNode) => {
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseMarkdownCompatibility.ts b/webdemo/frontend/src/pages/playground/utils/imageParseMarkdownCompatibility.ts
index f59b253..fbfbf65 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseMarkdownCompatibility.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseMarkdownCompatibility.ts
@@ -39,12 +39,12 @@ interface Insertion {
const IMAGE_KINDS = new Set(['image', 'chart', 'seal']);
-/** 版面把图标和文字收成页脚图时,服务端正文里没有对应片段。补一张图,框才能跳过去。 */
+/** When layout gathers an icon and text into a footer image, the server body has no matching fragment. Add one image so the box can jump there. */
function isOmittedFooterImage(block: ImageParseLayoutBlock): boolean {
return (block.label ?? '').toLowerCase() === 'footer_image' && IMAGE_KINDS.has(block.kind);
}
-/** 空印章没有可写回正文的文字,用原图占位符保留它在阅读顺序中的位置。 */
+/** An empty seal has no text to write back into the body; an original-image placeholder keeps its place in reading order. */
function isOmittedSealImage(block: ImageParseLayoutBlock): boolean {
return block.kind === 'seal' && !block.text.trim();
}
@@ -53,7 +53,7 @@ function omittedImageMarkdown(block: ImageParseLayoutBlock): string {
return isOmittedFooterImage(block) || isOmittedSealImage(block) ? '![image]()' : block.text;
}
-/** 只忽略排版空白;文字与标点仍必须一致,不对识别结果做模糊纠错。 */
+/** Ignore only layout whitespace; text and punctuation must still match. Do not fuzzy-correct recognition results. */
function comparableText(source: string): string {
return imageParseSourceBlocks(source)
.map((node) => imageParseNodeText(node))
@@ -62,13 +62,13 @@ function comparableText(source: string): string {
}
/**
- * 只对纯数字或纯拉丁单词检查词边界。中文正文没有空格,按字符拼在一起的
- * 相邻列表项不能被当作一个单词;`01A` 这类编号也要允许在拼接文本中命中。
+ * Check word boundaries only for pure numbers or pure Latin words. Chinese body text has no spaces, so adjacent list items
+ * concatenated character by character must not be treated as one word; an id such as `01A` must also be allowed to hit inside concatenated text.
*/
const WORD_CHAR = /[\p{Script=Latin}\p{N}]/u;
const BOUNDED_NEEDLE = /^(?:\p{N}+|\p{Script=Latin}+)$/u;
-/** 数字和单词只在完整边界上命中,避免页码 20 落进年份 2018。 */
+/** Numbers and words hit only on a complete boundary, so page number 20 does not fall inside the year 2018. */
function findBounded(text: string, needle: string, from: number): number {
if (!BOUNDED_NEEDLE.test(needle)) return text.indexOf(needle, from);
let index = text.indexOf(needle, from);
@@ -88,8 +88,8 @@ function findBounded(text: string, needle: string, from: number): number {
}
/**
- * 图片只认正文里的 `![image]()`。
- * 占位符的说明文字是 image,不能拿它去对普通段落里的同一个词。
+ * Images are recognized only as `![image]()` in the body.
+ * The placeholder's alt text is image, and must not be matched against the same word in an ordinary paragraph.
*/
function findImagePlaceholder(source: string, nodes: SourceBlock[]): Match | undefined {
const placeholder = '![image]()';
@@ -111,7 +111,7 @@ function findImagePlaceholder(source: string, nodes: SourceBlock[]): Match | und
return undefined;
}
-/** 消耗每次匹配的位置,使不同识别块中的重复文字不会共用同一次出现。 */
+/** Consume each match position, so repeated text in different recognition blocks does not share one occurrence. */
function findMatch(source: string, text: string, nodes: SourceBlock[]): Match | undefined {
const comparable = comparableText(text);
if (!comparable) return undefined;
@@ -120,7 +120,7 @@ function findMatch(source: string, text: string, nodes: SourceBlock[]): Match |
if (exact >= node.start && exact < node.end && exact + text.length > node.end) {
const last = nodes.find((item) => item.end >= exact + text.length);
if (!last) continue;
- // 一个服务块可能覆盖多个段落,直接保留完整原文范围而不是重复拼接。
+ // One service block may cover several paragraphs; keep the full original range instead of concatenating it again.
for (const covered of nodes) {
if (covered.start > last.start) break;
covered.rawCursor = Math.min(covered.end, exact + text.length);
@@ -129,12 +129,12 @@ function findMatch(source: string, text: string, nodes: SourceBlock[]): Match |
return { start: exact, end: exact + text.length, nodeStart: node.start, nodeEnd: last.end };
}
const index = findBounded(node.text, comparable, node.textCursor);
- // 跳过节点中间的短数字会把页码 20 认成参考文献里的卷期,并让前面的段落被再插入一次。
+ // Skipping a short number in the middle of a node would take page number 20 for a volume/issue in the references, and insert the earlier paragraph a second time.
if (index < 0 || (index !== node.textCursor && node.text !== comparable)) continue;
node.textCursor = index + comparable.length;
const rawMatch = exact >= node.start && exact + text.length <= node.end;
node.rawCursor = rawMatch ? exact + text.length : node.end;
- // 已越过的语义块不再参与匹配,保证与服务阅读顺序一致。
+ // A semantic block already passed is no longer matched, so the order stays consistent with the service reading order.
for (const earlier of nodes) {
if (earlier.start >= node.start) break;
earlier.textCursor = earlier.text.length;
@@ -151,7 +151,7 @@ function findMatch(source: string, text: string, nodes: SourceBlock[]): Match |
return undefined;
}
-/** 将结构化公式块绑定到正文中的完整 display-math 节点,避免按普通段落补写裸 LaTeX。 */
+/** Bind a structured formula block to a complete display-math node in the body, so bare LaTeX is not written in as an ordinary paragraph. */
function findFormulaMatch(text: string, nodes: SourceBlock[]): Match | undefined {
const comparable = comparableImageParseFormula(text);
if (!comparable) return undefined;
@@ -176,13 +176,13 @@ function findFormulaMatch(text: string, nodes: SourceBlock[]): Match | undefined
}
/**
- * 保留服务 Markdown,将成功识别但聚合正文遗漏的块补入完整语义块之间。
- * 匹配忽略 Markdown 排版与空白差异;图片占位符、失败块和原有表格保持原样。
- * @param source 服务聚合正文
- * @param blocks 已按服务阅读顺序排列、完成校验的识别块
- * @returns 兼容后的正文及精确定位范围,供预览、编辑、复制和下载共用
+ * Keep the service Markdown, and insert blocks that were recognized successfully but omitted from the aggregated body between complete semantic blocks.
+ * Matching ignores Markdown layout and whitespace differences; image placeholders, failed blocks, and existing tables stay as-is.
+ * @param source aggregated service body
+ * @param blocks recognition blocks already in service reading order and validated
+ * @returns the compatible body and exact positioning ranges, shared by preview, edit, copy, and download
*/
-/** 浏览器打不开的相对插图路径改回空占位符,预览再按原图裁出来。 */
+/** A relative illustration path the browser cannot open is turned back into an empty placeholder, and the preview crops it from the original image. */
function browserImagePlaceholders(source: string): string {
return source.replace(
/!\[image\]\((?:<([^>\r\n]+)>|([^)\s]+))\)/g,
@@ -217,10 +217,10 @@ export function reconcileImageParseMarkdown(
});
const placeholderCount = [...source.matchAll(/!\[image\]\(\)/g)].length;
const cropBlocks = imageParseMarkdownCropBlocks(blocks, placeholderCount);
- // 图片与正文可能采用不同的阅读顺序,分别消耗匹配游标,避免相互跳过已有内容。
+ // Images and body text may use different reading orders; consume their match cursors separately so they do not skip existing content past each other.
const imageNodes = nodes.map((node) => ({ ...node }));
- // 服务明确标为标题的编号属于正文,不能被 Markdown 当作有序列表标记剥掉。
- // 仅为匹配补充标题语义,不改写服务原文或最终 Markdown。
+ // A number the service explicitly marked as a heading belongs to the body and must not be stripped by Markdown as an ordered-list marker.
+ // Heading semantics are added only for matching, and do not rewrite the service original or the final Markdown.
const texts = blocks.map((block) =>
block.kind === 'heading' && /^\s*\d+[.)]\s/.test(block.text)
? `# ${block.text.trimStart()}`
@@ -229,10 +229,10 @@ export function reconcileImageParseMarkdown(
const matches = blocks.map((block, index) => {
if (block.kind === 'formula')
return findFormulaMatch(block.text, nodes) ?? findMatch(source, block.text, nodes);
- // 有文字的印章和图表绑定正文,不占用图片占位符或其它插图的映射位置。
+ // Seals and charts that have text bind to the body, and do not take an image-placeholder or other illustration mapping slot.
if (!IMAGE_KINDS.has(block.kind) || isImageParseDisplayTextBlock(block))
return findMatch(source, texts[index], nodes);
- // 数量一致时才将图片占位符作为锚点,与裁图规则一样避免猜测图片对应关系。
+ // Use image placeholders as anchors only when the counts match, the same way crop rules avoid guessing which image is which.
return cropBlocks.includes(block) ? findImagePlaceholder(source, imageNodes) : undefined;
});
const replacements = imageParseMarkdownReplacementRanges(source, texts, matches);
@@ -254,7 +254,7 @@ export function reconcileImageParseMarkdown(
.reverse()
.find((match) => match !== undefined);
const next = matches.slice(index + 1).find((match) => match !== undefined);
- // 同一段落/列表内无法安全插入时,放在完整块之后,避免破坏表格或标题语法。
+ // When it cannot be inserted safely inside the same paragraph or list, place it after the complete block, so table or heading syntax is not broken.
const offset = next ? Math.max(next.nodeStart, previous?.nodeEnd ?? 0) : source.length;
const group = insertions.find((insertion) => insertion.offset === offset);
if (group) group.blocks.push(index);
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseMarkdownRanges.ts b/webdemo/frontend/src/pages/playground/utils/imageParseMarkdownRanges.ts
index be5c847..861b133 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseMarkdownRanges.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseMarkdownRanges.ts
@@ -53,12 +53,12 @@ function possibleRanges(nodes: SourceNode[], target: string): ImageParseTextRang
}
/**
- * 检测服务块候选范围的实际交集,避免把已属于另一块的正文再次补入。
- * @param source 原始 Markdown
- * @param texts 识别块文字
- * @param matches 消耗阅读位置后的匹配结果
- * @param replacements 已确认的完整替换范围,避免用整个列表的定位锚点误判相邻条目
- * @returns 存在范围冲突的块序号,禁止补齐或覆盖这些块
+ * Detect the real overlap of candidate ranges of service blocks, so body text that already belongs to another block is not inserted again.
+ * @param source original Markdown
+ * @param texts recognition-block text
+ * @param matches match results after reading positions have been consumed
+ * @param replacements confirmed complete replacement ranges, so a positioning anchor of the whole list is not used to misjudge a neighboring item
+ * @returns indexes of blocks whose ranges conflict; those blocks must not be filled in or overwritten
*/
export function imageParseMarkdownOverlaps(
source: string,
@@ -97,7 +97,7 @@ function listRange(node: SourceNode, match: MatchedText): ImageParseTextRange |
for (const item of node.children ?? []) {
const range = nodeRange(item);
if (!range || item.type !== 'listItem') return undefined;
- // 只在完整条目的语义边界处替换;不能把同列表的其它条目包含进来。
+ // Replace only at the semantic boundary of a complete item; do not include other items of the same list.
if (cursor === match.textStart) start = range.start;
cursor += imageParseNodeText(item).replace(/\s+/g, '').length;
if (start !== undefined && cursor === match.textEnd) return { start, end: range.end };
@@ -107,11 +107,11 @@ function listRange(node: SourceNode, match: MatchedText): ImageParseTextRange |
}
/**
- * 将文字匹配提升为完整 Markdown 语义范围,包含标题、列表和加粗等原有标记。
- * @param source 原始整页 Markdown
- * @param texts 按阅读顺序返回的识别文字
- * @param matches 已消耗重复文字位置的匹配结果
- * @returns 唯一且完整的替换范围;段落内的局部文字仍作定位锚点,但不允许重算覆盖
+ * Promote a text match to a complete Markdown semantic range, including existing markers such as headings, lists, and bold.
+ * @param source original whole-page Markdown
+ * @param texts recognition text returned in reading order
+ * @param matches match results that have already consumed repeated-text positions
+ * @returns unique and complete replacement ranges; partial text inside a paragraph remains a positioning anchor, but must not be recomputed over
*/
export function imageParseMarkdownReplacementRanges(
source: string,
@@ -155,7 +155,7 @@ export function imageParseMarkdownReplacementRanges(
const anchors = matchedRanges.map((range, index) => (ambiguous[index] ? undefined : range));
return matchedRanges.map((range, index) => {
if (!range || !ambiguous[index]) return range;
- // 漏检一个重复编号不应禁用其它章节;只接受前后完整块之间唯一且已匹配的候选。
+ // Missing one repeated number must not disable other sections; accept only a unique already-matched candidate between complete blocks before and after.
const previous = anchors
.slice(0, index)
.reverse()
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParsePageNumber.ts b/webdemo/frontend/src/pages/playground/utils/imageParsePageNumber.ts
index c9bfe54..64d3a92 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParsePageNumber.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParsePageNumber.ts
@@ -2,7 +2,7 @@ import type { ImageParseTextRange } from './imageParseBlocks';
import { imageParseBlockId } from './imageParseBlocks';
import type { ImageParseLayoutBlock } from './imageParseSample';
-/** 页码块的文字特征;只用于已标记为 footer 的语义块,避免把普通数字正文当成页码。 */
+/** Text pattern of a page-number block; used only on semantic blocks already marked as footer, so ordinary numeric body text is not treated as a page number. */
const PAGE_NUMBER_PATTERNS = [
/^(?:第\s*)?\d{1,4}\s*(?:页)?$/,
/^\d{1,4}\s*\/\s*\d{1,4}$/,
@@ -10,7 +10,7 @@ const PAGE_NUMBER_PATTERNS = [
/^(?:page|p\.?)\s*\d{1,4}(?:\s*(?:of|\/)\s*\d{1,4})?$/i,
];
-/** 去掉常见 Markdown 强调标记,判断一段独立文字是否只是页码。 */
+/** Strip common Markdown emphasis markers and decide whether a standalone piece of text is only a page number. */
export function isImageParsePageNumber(text: string): boolean {
const plain = text
.trim()
@@ -22,12 +22,12 @@ export function isImageParsePageNumber(text: string): boolean {
return PAGE_NUMBER_PATTERNS.some((pattern) => pattern.test(plain));
}
-/** 编辑器按范围判断显示样式;range key 与 pageNumberRanges 共用。 */
+/** The editor decides display style by range; the range key is shared with pageNumberRanges. */
export function imageParseRangeKey(range: ImageParseTextRange): string {
return `${range.start}:${range.end}`;
}
-/** 只有服务明确标记为页脚 / 页码的块才进入候选,具体文字由编辑器再次确认。 */
+/** Only a block the service explicitly marked as footer / page number becomes a candidate; the editor confirms the actual text again. */
export function imageParsePageNumberRanges(
blocks: readonly ImageParseLayoutBlock[],
ranges: ReadonlyMap<string, ImageParseTextRange>,
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParsePdfScrollAnchors.ts b/webdemo/frontend/src/pages/playground/utils/imageParsePdfScrollAnchors.ts
index b245e40..11f3f54 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParsePdfScrollAnchors.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParsePdfScrollAnchors.ts
@@ -4,7 +4,7 @@ import type { ImageParseLayoutBlock } from './imageParseSample';
const bounded = (value: number) => Math.max(0, Math.min(1, value));
-/** 连续 PDF 按页面骨架映射全篇,当前页再用真实区块细化;离屏页仍可定位。 */
+/** A continuous PDF maps the whole document by page skeletons, then the current page is refined with real blocks; offscreen pages can still be positioned. */
export function imageParsePdfScrollAnchors(
origin: HTMLElement,
result: HTMLElement,
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseQuality.ts b/webdemo/frontend/src/pages/playground/utils/imageParseQuality.ts
index aa6fd3e..c3127bf 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseQuality.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseQuality.ts
@@ -1,23 +1,23 @@
import type { ImageParseLayoutBlock } from './imageParseSample';
import { imageParseBlockId, imageParseConfidence } from './imageParseBlocks';
-/** 界面分流阈值,仅用于提示复核,不代表校准后的正确概率。 */
+/** UI split threshold, used only to suggest review, and not a calibrated probability of correctness. */
export const IMAGE_PARSE_REVIEW_THRESHOLD = 0.8;
/**
- * 原文档框色分级阈值(第一期临时标准,由平台统一配置,暂不开放用户调整):
- * 低于 99% 使用淡灰色框,99% 及以上使用深绿色并加粗框线。
+ * Color tiers for boxes on the original document (a temporary first-phase standard, configured by the platform, not yet open for users to adjust):
+ * below 99% uses a light gray box; 99% and above uses dark green and a thicker stroke.
*/
export const IMAGE_PARSE_CONFIDENCE_ERROR_MAX = 0.2;
export const IMAGE_PARSE_CONFIDENCE_HIGH_MIN = 0.99;
-/** 置信度色块分级;缺失或非法分数为中性色,不参与红黄绿判断。 */
+/** Confidence color tiers; a missing or illegal score is a neutral color and does not take part in the red/yellow/green decision. */
export type ImageParseConfidenceLevel = 'error' | 'low' | 'high' | 'neutral';
/**
- * 按平台统一阈值给有效分数分级。
- * @param confidence 服务返回的 0–1 分数,或 null/非法值
- * @returns 色块分级:低于 20% 为 error、20%–99% 为 low、99% 及以上为 high,其余为 neutral;界面将非 high 统一渲染为淡灰色
+ * Tier a valid score by the platform's unified threshold.
+ * @param confidence 0–1 score returned by the service, or null/an illegal value
+ * @returns color tier: below 20% is error, 20%–99% is low, 99% and above is high, otherwise neutral; the UI renders anything that is not high as light gray
*/
export function imageParseConfidenceLevel(confidence: number | null): ImageParseConfidenceLevel {
if (confidence === null || !Number.isFinite(confidence) || confidence < 0 || confidence > 1)
@@ -27,18 +27,18 @@ export function imageParseConfidenceLevel(confidence: number | null): ImageParse
return 'high';
}
-/** 原图框线与分数列共用状态分级,失败优先标红,跳过保持中性。 */
+/** Original-image box strokes and the score column share status tiers; failure is marked red first, and skip stays neutral. */
export function imageParseBlockConfidenceLevel(
block: ImageParseLayoutBlock,
): ImageParseConfidenceLevel {
- // 跨页表格合并后的 score 来自合并前半表,不能当作当前完整表格质量。
+ // After a cross-page table merge, score comes from the first half of the table before the merge and cannot be treated as the quality of the current full table.
if (block.ttsInvalid) return 'neutral';
if (block.status === 'skipped_no_vlm') return 'neutral';
if (block.status && block.status !== 'ok') return 'error';
return imageParseConfidenceLevel(block.confidence);
}
-/** 跳过、失败、纯图与无分数的块没有可重算的文字;旧演示允许省略状态。 */
+/** Skipped, failed, image-only, and unscored blocks have no text that can be recomputed; the old demo may omit status. */
export function imageParseBlockCanRegenerate(block: ImageParseLayoutBlock): boolean {
return (
!block.ttsInvalid &&
@@ -49,7 +49,7 @@ export function imageParseBlockCanRegenerate(block: ImageParseLayoutBlock): bool
);
}
-/** 保留阅读顺序的有分数区块。 */
+/** Scored blocks kept in reading order. */
export interface ImageParseQualityItem {
id: string;
order: number;
@@ -58,7 +58,7 @@ export interface ImageParseQualityItem {
suggested: boolean;
}
-/** 汇总服务实际提供的有效分数;缺失与非法值不补造,0 仍是有效分数。 */
+/** Summarize valid scores the service actually provided; missing and illegal values are not invented, and 0 is still a valid score. */
export function imageParseQuality(blocks: readonly ImageParseLayoutBlock[]) {
const scored: ImageParseQualityItem[] = [];
blocks.forEach((block, order) => {
@@ -85,11 +85,11 @@ export function imageParseQuality(blocks: readonly ImageParseLayoutBlock[]) {
}
/**
- * 给复核列表生成可读摘要。服务可能把 HTML 片段放在 text 或 markdown 中,
- * 列表只展示文本内容,避免把表格标签直接暴露给用户。
+ * Build a readable summary for the review list. The service may put an HTML fragment in text or markdown,
+ * and the list shows only text content, so table tags are not exposed to the user directly.
*
- * 图片节点(如 `![image]()`)没有可读文本、也没有有效地址,属于无意义内容,直接丢弃;
- * 链接只保留文字,避免把 URL 当正文。清洗后为空时返回空串,由调用方决定不渲染。
+ * An image node (such as `![image]()`) has no readable text and no valid URL, so it is meaningless content and is dropped;
+ * a link keeps only its text, so a URL is not treated as body text. When cleaning leaves it empty, return an empty string and let the caller decide not to render.
*/
export function qualityExcerpt(block: ImageParseQualityItem['block']): string {
const source = block.text || block.markdown;
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseReadingAnchor.ts b/webdemo/frontend/src/pages/playground/utils/imageParseReadingAnchor.ts
index 8383751..effb472 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseReadingAnchor.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseReadingAnchor.ts
@@ -1,11 +1,11 @@
interface ImageParseReadingCandidate {
ids: readonly string[];
page?: number;
- /** 块顶部相对结果滚动视口顶部的偏移。 */
+ /** Offset of the block top relative to the top of the result scroll viewport. */
offset: number;
}
-/** 结果栏在内容重排前捕获的阅读定位点。 */
+/** Reading anchor captured in the result column before content is reflowed. */
export interface ImageParseReadingAnchor {
candidates: readonly ImageParseReadingCandidate[];
page?: number;
@@ -32,8 +32,8 @@ function pageOf(node: HTMLElement): number | undefined {
}
/**
- * 记录当前结果视口里最靠上的可定位块。
- * 页眉页脚切换只改变块内容,块的稳定 id 不会变化,因此可用它把视线锚回同一段正文。
+ * Record the topmost positionable block in the current result viewport.
+ * Toggling header and footer only changes block content; a block's stable id does not change, so it can anchor the view back to the same body text.
*/
export function captureImageParseReadingAnchor(
viewport: HTMLElement,
@@ -75,7 +75,7 @@ export function captureImageParseReadingAnchor(
const range = Math.max(0, viewport.scrollHeight - viewport.clientHeight);
return {
- // 顶部块被隐藏时继续尝试下一段可见正文,避免锚到一个已删除的页眉。
+ // When the top block is hidden, keep trying the next visible body text, so the anchor does not land on a header that was removed.
candidates: candidates.slice(0, 12),
page: Number.isFinite(page) ? page : undefined,
pageOffset,
@@ -96,8 +96,8 @@ function findCandidateNode(
}
/**
- * 计算重排后的滚动位置:优先还原同一正文块,找不到时退到页首和整体进度。
- * @returns 需要写入结果视口的 scrollTop;视口不可用或没有可还原目标时返回 undefined
+ * Compute the scroll position after reflow: restore the same body block first, and fall back to the top of the page and overall progress when it cannot be found.
+ * @returns scrollTop to write into the result viewport; undefined when the viewport is unavailable or there is no target to restore
*/
export function resolveImageParseReadingTop(
viewport: HTMLElement,
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseRegeneration.ts b/webdemo/frontend/src/pages/playground/utils/imageParseRegeneration.ts
index 9cbb627..956a1dd 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseRegeneration.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseRegeneration.ts
@@ -8,10 +8,10 @@ import {
type ImageParseTextRange,
} from './imageParseBlocks';
-/** 每次主动优化的单块请求预算,不展示中间候选。 */
+/** Per-block request budget for one active optimization; intermediate candidates are not shown. */
export const IMAGE_PARSE_MAX_RETRIES = 5;
-/** 只展示稳定错误键,不将 SDK 或上游返回的消息直接暴露到页面。 */
+/** Show only stable error keys, and do not expose SDK or upstream messages on the page directly. */
export function imageParseRegenerationErrorKey(failure: unknown): string {
const known = [
'imageParseRegenerateEdited',
@@ -33,7 +33,7 @@ export function imageParseRegenerationErrorKey(failure: unknown): string {
return known.includes(message) ? message : 'imageParseRegenerateFailed';
}
-/** 两版对比与可恢复的操作状态;original 始终是首次基础识别。 */
+/** Comparison of the two versions and recoverable operation state; original is always the first base recognition. */
export interface ImageParseRegeneration {
original: ImageParseLayoutBlock;
best: ImageParseLayoutBlock;
@@ -51,7 +51,7 @@ interface RegenerationDraft {
ranges: ReadonlyMap<string, ImageParseTextRange>;
}
-/** 全部可重算低分目标;未映射或人工改稿不纳入队列,展示分页不影响目标集合。 */
+/** Every low-score target that can be recomputed; unmapped blocks and manual edits are not queued, and display paging does not affect the target set. */
export function imageParseRegenerationIds(
blocks: readonly ImageParseLayoutBlock[],
draft: RegenerationDraft,
@@ -80,7 +80,7 @@ interface RegenerateMappedBlockInput {
onApply: (next: string, range: ImageParseTextRange) => void;
}
-/** 每轮及写入前检查实时映射,目标块有人工修改时不继续请求或覆盖。 */
+/** Check the live mapping each round and before writing; if the target block has a manual edit, do not keep requesting or overwrite it. */
export async function regenerateMappedImageParseBlock({
id,
original,
@@ -118,7 +118,7 @@ export async function regenerateMappedImageParseBlock({
return result;
}
-/** v4 按服务端轮次结束;旧 SDK 最多五次单轮,仅采纳评分严格更高的候选。 */
+/** v4 ends on the server round; the old SDK does at most five single rounds, and only a candidate with a strictly higher score is accepted. */
export async function optimizeImageParseBlock(
original: ImageParseLayoutBlock,
generate: (attempt: number, best: ImageParseLayoutBlock) => Promise<ImageParseRegenerateResult>,
@@ -136,7 +136,7 @@ export async function optimizeImageParseBlock(
} catch (failure) {
signal.throwIfAborted();
if (!rounds) throw failure;
- // 后续网络故障不能丢弃此前已评分的候选,但界面仍需说明优化未完整执行。
+ // A later network failure must not discard candidates already scored, but the UI still has to say the optimization did not run to completion.
return {
original,
best,
@@ -193,7 +193,7 @@ export async function optimizeImageParseBlock(
};
}
-/** 以公共前后文隔离差异区域,线性复杂度避免长表格造成二次方开销。 */
+/** Isolate the differing region by the common prefix and suffix; linear complexity avoids quadratic cost on a long table. */
export function imageParseTextDifference(before: string, after: string) {
const left = Array.from(before);
const right = Array.from(after);
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseRegenerationRequest.ts b/webdemo/frontend/src/pages/playground/utils/imageParseRegenerationRequest.ts
index 0906f45..e298218 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseRegenerationRequest.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseRegenerationRequest.ts
@@ -4,16 +4,16 @@ import type { ImageParseLayoutBlock } from './imageParseSample';
interface BlockGenerationInput {
source?: ImageParseSource;
- /** 当前登录用户可见的文档解析模型 ID。 */
+ /** Document-parsing model ID visible to the current logged-in user. */
model: string;
- /** 当前选中 API Key 的明文密钥;仅内存传递,不落盘。 */
+ /** Plaintext secret of the currently selected API Key; passed in memory only and not persisted to disk. */
secret: string;
documentDataUrl: string;
mime: string;
pageIndex: number;
}
-/** 真实 v4 只使用服务端签发的整页引用;没有来源证明时必须显式不可用。 */
+/** Real v4 uses only a whole-page reference issued by the server; without proof of origin it must be explicitly unavailable. */
export function imageParseBlockGenerator(
input: BlockGenerationInput,
original: ImageParseLayoutBlock,
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseRequest.ts b/webdemo/frontend/src/pages/playground/utils/imageParseRequest.ts
index 26c5a66..b1838c9 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseRequest.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseRequest.ts
@@ -15,17 +15,17 @@ interface ImageParseRun {
signal: AbortSignal;
isCurrent: () => boolean;
mode?: ImageParseMode;
- /** 当前登录用户可见的文档解析模型 ID;空值表示无权限。 */
+ /** Document-parsing model ID visible to the current logged-in user; an empty value means no permission. */
model: string;
- /** 当前选中 API Key 的明文密钥;仅内存传递,不落盘。 */
+ /** Plaintext secret of the currently selected API Key; passed in memory only and not persisted to disk. */
secret: string;
- /** Playground 单图优先使用 OBS 文件引用;文件服务异常时回退内联图片。 */
+ /** A Playground single image prefers an OBS file reference; when the file service fails, fall back to an inline image. */
fileId?: string;
- /** 文件服务不可用时,使用平台旧资产入口返回的签名链接。 */
+ /** When the file service is unavailable, use the signed URL returned by the platform's legacy asset entry. */
fileUrl?: string;
}
-/** 通过 L2 API Key 链路解析页图;不以 L3 代理配置判定 L2 可用性,也不回退传统模型。 */
+/** Parse the page image through the L2 API Key path; do not judge L2 availability from the L3 proxy config, and do not fall back to a traditional model. */
export async function runImageParse(args: ImageParseRun): Promise<ImageParseSdkResult | undefined> {
const signal = AbortSignal.any([args.signal, AbortSignal.timeout(300_000)]);
const assertCurrent = () => {
@@ -34,8 +34,8 @@ export async function runImageParse(args: ImageParseRun): Promise<ImageParseSdkR
};
assertCurrent();
if (!args.model?.trim()) throw new Error('imageParseNoModel');
- // 显式传入的空串表示本次必须使用内联图片,不能回退到 attachment,
- // 否则引用失效后的内联重试会再次带上已清理的 fileId/URL。
+ // An explicitly passed empty string means this attempt must use an inline image and must not fall back to the attachment,
+ // or an inline retry after the reference failed would attach the fileId/URL that was already cleared.
const fileId =
args.fileId !== undefined ? args.fileId.trim() : (args.attachment.fileId?.trim() ?? '');
const fileUrl =
@@ -78,14 +78,14 @@ function fileToDataUrl(file: File): Promise<string> {
});
}
-/** 将解析错误键转换为界面文案键;高精度档位超时使用更具体的提示。 */
+/** Turn a parse error key into a UI copy key; a high-precision tier timeout uses a more specific notice. */
export function imageParseCopyKey(key: string, mode: ImageParseMode): string {
return key === 'imageParseTimeout' && mode === 'high-precision'
? 'imageParseHighPrecisionTimeout'
: key;
}
-/** 将 v3 OCR 代理错误转换为稳定文案键,不展示未经净化的上游消息。 */
+/** Turn a v3 OCR proxy error into a stable copy key, and do not show an unsanitized upstream message. */
export function imageParseErrorKey(error: unknown): string {
if (error instanceof DOMException && error.name === 'TimeoutError') return 'imageParseTimeout';
if (error instanceof Error && /^imageParse[A-Z]/.test(error.message)) return error.message;
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseRotation.ts b/webdemo/frontend/src/pages/playground/utils/imageParseRotation.ts
index d44a740..479417c 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseRotation.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseRotation.ts
@@ -6,10 +6,10 @@ import type {
} from './imageParseSample';
/**
- * 按顺时针 90 度步长旋转一个归一化矩形。
- * @param region 原坐标系中的矩形
- * @param angle 已归一化的顺时针角度
- * @returns 旋转后坐标系中的矩形
+ * Rotate a normalized rectangle in clockwise 90-degree steps.
+ * @param region rectangle in the original coordinate system
+ * @param angle normalized clockwise angle
+ * @returns rectangle in the rotated coordinate system
*/
function rotateRegion(
region: ImageParseLayoutRegion,
@@ -28,10 +28,10 @@ function rotateRegion(
}
/**
- * 将原图归一化坐标投影到顺时针旋转后的页面,不修改识别数据。
- * @param blocks 原图方向的识别块,已包含 PDF 自带旋转的影响
- * @param rotation 工具栏额外旋转角度,以 90 度为步长
- * @returns 预览坐标和稳定标识,分数及内容保持不变
+ * Project normalized coordinates of the original image onto the page after a clockwise rotation, without modifying recognition data.
+ * @param blocks recognition blocks in the original-image orientation, already including the PDF's own rotation
+ * @param rotation extra toolbar rotation angle, in 90-degree steps
+ * @returns preview coordinates and a stable id; score and content stay unchanged
*/
export function rotateImageParseBlocks(
blocks: readonly ImageParseLayoutBlock[],
@@ -41,12 +41,12 @@ export function rotateImageParseBlocks(
if (angle === 0) return blocks;
const direction = angle as 90 | 180 | 270;
return blocks.map((block, order) => {
- // 无服务标识的块必须沿用原始坐标生成的 ID,否则旋转会断开结果定位。
+ // A block with no service id must keep the id generated from the original coordinates, or rotation would disconnect result positioning.
const original = { ...block, id: imageParseBlockId(block, order) };
return {
...original,
...rotateRegion(block, direction),
- // PDF 原方向恢复必须连同 regions 投影,否则合并块仍会画在服务端摆正坐标。
+ // Restoring the PDF's original orientation must project regions as well, or a merged block would still be drawn in server rotation-adaptation coordinates.
...(block.regions?.length
? { regions: block.regions.map((region) => rotateRegion(region, direction)) }
: {}),
@@ -55,10 +55,10 @@ export function rotateImageParseBlocks(
}
/**
- * 将服务端摆正后的 PDF 坐标投回原始页面方向。
- * @param blocks 服务端摆正坐标系中的识别块
- * @param rotation 服务端旋转元数据
- * @returns 原始 PDF 预览方向中的识别块;未摆正时复用原数组
+ * Project PDF coordinates after server rotation adaptation back to the original page orientation.
+ * @param blocks recognition blocks in the server rotation-adaptation coordinate system
+ * @param rotation server rotation metadata
+ * @returns recognition blocks in the original PDF preview orientation; reuse the original array when rotation adaptation was not applied
*/
export function restoreImageParseBlocksToOriginal(
blocks: readonly ImageParseLayoutBlock[],
@@ -69,8 +69,8 @@ export function restoreImageParseBlocksToOriginal(
}
/**
- * 这一页预览要转回摆正方向的角度。
- * 单图用 totalAngle 直接转原图;PDF 的框已经按 orientationAngle 投回原页,页面必须转同一个角度,框才会跟着落在文字上。
+ * Angle this page's preview must rotate back toward the rotation-adaptation orientation.
+ * A single image uses totalAngle to rotate the original directly; PDF boxes have already been projected back to the original page by orientationAngle, so the page must rotate by the same angle for the boxes to land on the text.
*/
export function imageParseServerDisplayAngle(rotation: ImageParseRotationInfo | undefined): number {
if (!rotation?.enabled || !rotation.applied || !Number.isFinite(rotation.orientationAngle))
@@ -79,7 +79,7 @@ export function imageParseServerDisplayAngle(rotation: ImageParseRotationInfo |
return turns === 0 ? 0 : rotation.orientationAngle;
}
-/** 原页面绕中心旋转后的外接矩形。0° 和 180° 的占位尺寸不变。 */
+/** Bounding box of the original page after rotation about its center. The placeholder size is unchanged at 0° and 180°. */
export function rotatedPageBounds(
width: number,
height: number,
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseSample.ts b/webdemo/frontend/src/pages/playground/utils/imageParseSample.ts
index 27d1b7f..cb2e3f0 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseSample.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseSample.ts
@@ -1,12 +1,12 @@
-/** 图像解析版面块类型与旧样例 ID;运行时识别结果只能来自服务端。 */
+/** Image-parsing layout block types and old sample IDs; runtime recognition results can come only from the server. */
/**
- * 旧内置样例附件 ID。仅用于拒绝历史缓存把本地演示结果保存成个人记录,
- * 不再提供任何本地演示附件或识别结果。
+ * Attachment IDs of old built-in samples. Used only to refuse history cache that would save a local demo result as a personal record,
+ * and no longer provides any local demo attachment or recognition result.
*/
export const IMAGE_PARSE_SAMPLE_ATTACHMENT_ID = 'image-parse-sample';
-/** 版面块语义类型,决定框线颜色与类型角标。 */
+/** Semantic type of a layout block; it decides box color and the type badge. */
export type ImageParseBlockKind =
| 'header'
| 'footer'
@@ -20,13 +20,13 @@ export type ImageParseBlockKind =
| 'chart'
| 'seal';
-/** 服务端旋转摆正信息;坐标始终基于摆正后的图片。 */
+/** Server rotation-adaptation info; coordinates are always based on the image after rotation adaptation. */
export interface ImageParseRotationInfo {
enabled: boolean;
applied: boolean;
- /** 服务端实际逆时针旋转角度;浏览器显示使用反向角度。 */
+ /** Actual counterclockwise rotation angle from the server; the browser displays the opposite angle. */
totalAngle: number;
- /** 摆正没跑出预测(未启用 / gated)时为 null。 */
+ /** null when rotation adaptation produced no prediction (disabled / gated). */
predictedAngle: number | null;
predictedScore: number | null;
confirmed: boolean | null;
@@ -35,7 +35,7 @@ export interface ImageParseRotationInfo {
skippedReason: string | null;
}
-/** 版面块内的一个归一化区域;合并块会包含多个区域。 */
+/** One normalized region inside a layout block; a merged block can contain several regions. */
export interface ImageParseLayoutRegion {
x: number;
y: number;
@@ -43,39 +43,39 @@ export interface ImageParseLayoutRegion {
h: number;
}
-/** 一个版面块:归一化坐标(0–1)+ 语义类型 + 识别内容。 */
+/** One layout block: normalized coordinates (0–1) + semantic type + recognition content. */
export interface ImageParseLayoutBlock {
- /** 服务返回的稳定标识,可选;没有标识时以坐标和阅读顺序组合标识。 */
+ /** Stable id returned by the service, optional; when there is no id, combine coordinates and reading order. */
id?: string;
- /** 服务阅读序号从 0 开始;旧结果缺省时取数组位置。 */
+ /** The service reading index starts at 0; an old result with none uses the array position. */
order?: number;
label?: string;
status?: string;
- /** 在整篇 Markdown 中的 UTF-16 起止偏移,用于消除重复文字的歧义。 */
+ /** UTF-16 start and end offsets in the whole Markdown, used to remove ambiguity from repeated text. */
markdownStart?: number;
markdownEnd?: number;
kind: ImageParseBlockKind;
- /** 左上角 x,占图宽比例 */
+ /** Top-left x, as a fraction of image width */
x: number;
- /** 左上角 y,占图高比例 */
+ /** Top-left y, as a fraction of image height */
y: number;
- /** 宽度占比 */
+ /** Width fraction */
w: number;
- /** 高度占比 */
+ /** Height fraction */
h: number;
- /** 服务端返回的全部区域;缺省时使用主 bbox 渲染。 */
+ /** Every region returned by the server; when absent, render the primary bbox. */
regions?: readonly ImageParseLayoutRegion[];
/**
- * 该块在图上识别到的原始文字:保留图上的换行,表格按行分行、按列用制表符分隔。
- * 与 markdown 的区别是这里没有结构——标题不带 `#`,列表不带 `-`,复选框是字符本身。
+ * Original text recognized on the image for this block: keep the line breaks on the image; a table breaks rows into lines and separates columns with tabs.
+ * The difference from markdown is that there is no structure here — headings have no `#`, lists have no `-`, and a checkbox is the character itself.
*/
text: string;
- /** 该块结构化后的 Markdown 片段,按阅读顺序拼起来即「原文」页内容。 */
+ /** Structured Markdown fragment for this block; joined in reading order it is the content of the "original text" page. */
markdown: string;
- /** 服务返回的 0–1 置信度,缺失时为 null;前端不估算。 */
+ /** 0–1 confidence returned by the service, or null when missing; the frontend does not estimate. */
confidence: number | null;
- /** 跨页表格合并标记;true 时 score 只代表合并前半表。 */
+ /** Cross-page table-merge flag; when true, score represents only the first half of the table before the merge. */
ttsInvalid?: boolean;
- /** 跨页表格合并:本块是上一页表格的续表,内容已并入上一页,本页清空。 */
+ /** Cross-page table merge: this block continues the previous page's table, its content was merged into the previous page, and this page is cleared. */
mergedIntoPreviousPage?: boolean;
}
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseScrollAnchors.ts b/webdemo/frontend/src/pages/playground/utils/imageParseScrollAnchors.ts
index ca914a5..892d787 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseScrollAnchors.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseScrollAnchors.ts
@@ -13,7 +13,7 @@ function internal(anchor: Anchor): boolean {
return anchor.origin > 0 && anchor.origin < 1 && anchor.result > 0 && anchor.result < 1;
}
-/** 使用可见原文和预览的同一块构建滚动锚点;无真实映射时不推断定位。 */
+/** Build scroll anchors from the same block in the visible original and the preview; do not infer a position when there is no real mapping. */
export function imageParseScrollAnchors(
origin: HTMLElement | null,
result: HTMLElement,
@@ -29,7 +29,7 @@ export function imageParseScrollAnchors(
return imageParsePdfScrollAnchors(origin, result, blocks);
const currentPage = Number(origin.dataset.pdfCurrentPage);
const activeCanvas = isPdf ? origin.querySelector<HTMLElement>('canvas[role="img"]') : null;
- // 页面骨架始终存在;离屏画布卸载时也不能退回整份 PDF 的滚动范围。
+ // The page skeleton is always present; when an offscreen canvas unmounts, do not fall back to the scroll range of the whole PDF.
const raster = isPdf
? (origin.querySelector<HTMLElement>(`[data-pdf-page="${currentPage}"]`) ??
activeCanvas?.closest<HTMLElement>('[data-pdf-page]') ??
@@ -99,8 +99,8 @@ export function imageParseScrollAnchors(
];
})
.sort((a, b) => a.origin - b.origin);
- // 图片端点对应整张图片;PDF 结果只对应当前页,首尾不能跨到其他页面。
- // 旋转、合并段落可能产生重复或逆序锚点;只插值严格单调的真实对应关系。
+ // Image endpoints correspond to the whole image; a PDF result corresponds only to the current page, and the ends must not cross onto other pages.
+ // Rotation and merged paragraphs can produce duplicate or out-of-order anchors; interpolate only strictly monotonic real correspondences.
const ordered: Anchor[] = [];
for (const anchor of anchors) {
if (
@@ -116,7 +116,7 @@ export function imageParseScrollAnchors(
return anchors.length || isPdf ? [endpoints[0], ...ordered, endpoints[1]] : [];
}
-/** 在相邻块锚点间插值并限制在当前结果范围;反向映射复用同一组锚点。 */
+/** Interpolate between anchors of adjacent blocks and clamp to the current result range; the reverse mapping reuses the same anchors. */
export function imageParseMappedProgress(
anchors: readonly Anchor[],
progress: number,
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseSealDisplay.ts b/webdemo/frontend/src/pages/playground/utils/imageParseSealDisplay.ts
index 25bb3a0..f367f43 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseSealDisplay.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseSealDisplay.ts
@@ -37,12 +37,12 @@ function blockRange(
}
/**
- * 将原始 OCR 结果转换为图片/文字展示结果;关闭印章或图表文字时只替换对应正文。
- * @param result 原始识别结果或用户编辑后的结果
- * @param showSealText 是否展示印章识别文字
- * @param showChartText 是否展示图表识别文字
- * @param ranges 用户编辑后仍有效的块范围
- * @returns 仅用于预览的派生结果,不修改原始识别结果
+ * Turn a raw OCR result into an image/text display result; when seal or chart text is off, replace only the matching body text.
+ * @param result raw recognition result, or the result after the user edited it
+ * @param showSealText whether to show seal recognition text
+ * @param showChartText whether to show chart recognition text
+ * @param ranges block ranges that are still valid after the user edited
+ * @returns a derived result for preview only; the raw recognition result is not modified
*/
export function imageParseSealDisplayResult(
result: Pick<ImageParseSdkResult, 'markdown' | 'blocks'> &
@@ -107,12 +107,12 @@ export function imageParseSealDisplayResult(
}
/**
- * 按当前印章/图表展示模式筛选已生成的裁图;裁图数组按全部图片块顺序缓存。
- * @param blocks 当前预览使用的版面块
- * @param crops 按全部图片块生成的裁图
- * @param showSealText 是否展示印章识别文字
- * @param showChartText 是否展示图表识别文字
- * @returns 与当前 Markdown 占位符一一对应的裁图
+ * Filter already generated crops by the current seal/chart display mode; the crop array is cached in the order of every image block.
+ * @param blocks layout blocks used by the current preview
+ * @param crops crops generated for every image block
+ * @param showSealText whether to show seal recognition text
+ * @param showChartText whether to show chart recognition text
+ * @returns crops in one-to-one correspondence with the current Markdown placeholders
*/
export function imageParseSealDisplayCrops(
blocks: readonly ImageParseLayoutBlock[],
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseSimulation.ts b/webdemo/frontend/src/pages/playground/utils/imageParseSimulation.ts
index 8f1945c..1418cca 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseSimulation.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseSimulation.ts
@@ -1,17 +1,17 @@
-/** 进度组件的状态契约;当前 OCR 仅返回最终结果,不在前端模拟进度。 */
+/** State contract for the progress component; current OCR returns only the final result and does not simulate progress on the frontend. */
-/** 解析阶段。顺序即执行顺序,界面按这个顺序推进扫描与版面框。 */
+/** Parse phases. The order is the execution order; the UI advances the scan and layout boxes in this order. */
export type ImageParseStage = 'layout' | 'structure' | 'render';
-/** 服务端进度快照;尚无进度事件时使用 null,不合成百分比。 */
+/** Server progress snapshot; null when there is no progress event yet, and no percentage is synthesized. */
export interface ImageParseProgressSnapshot {
stage: ImageParseStage;
- /** 总进度 0–100 */
+ /** Overall progress 0–100 */
percent: number;
- /** 已检出的版面块数量,驱动原图上的框逐个出现 */
+ /** Number of layout blocks already detected, which drives boxes appearing one by one on the original image */
detectedBlocks: number;
- /** 已完成结构还原的版面块数量,驱动框的高亮向下推进 */
+ /** Number of layout blocks whose structure has been restored, which drives the highlight moving down the boxes */
scannedBlocks: number;
- /** 当前已流出的 Markdown 片段 */
+ /** Markdown fragment that has streamed out so far */
markdown: string;
}
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseTableMerge.ts b/webdemo/frontend/src/pages/playground/utils/imageParseTableMerge.ts
index 6921af9..fdcb6f7 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseTableMerge.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseTableMerge.ts
@@ -8,7 +8,7 @@ import {
type ImageParseTextRange,
} from './imageParseBlocks';
-/** 只忽略页面装饰块;页脚之后的表格仍视为页末内容。 */
+/** Ignore only page-decoration blocks; a table after the footer is still treated as end-of-page content. */
const PAGE_DECORATION_KINDS = new Set<ImageParseLayoutBlock['kind']>(['header', 'footer']);
interface TableCandidate {
@@ -26,7 +26,7 @@ interface PageTable {
last?: TableCandidate;
}
-/** 单元格合并后表格的列数;rowspan 占位必须计入后续行的宽度。 */
+/** Column count of a table after cells are merged; a rowspan placeholder must count toward the width of later rows. */
function tableWidth(table: HTMLTableElement): number {
const occupied: boolean[][] = [];
let width = 0;
@@ -78,7 +78,7 @@ function sameHeaderRow(left: HTMLTableRowElement, right: HTMLTableRowElement): b
);
}
-/** 表头可能占两行;只有 th 或跨行/跨列单元格才参与续页重复表头剔除。 */
+/** A header may take two rows; only th or cells that span rows or columns take part in dropping a repeated header on a continuation page. */
function looksLikeHeaderRow(row: HTMLTableRowElement): boolean {
return Array.from(row.cells).some(
(cell) =>
@@ -142,9 +142,9 @@ function tableCandidate(
return tableCandidateAt(result, blockIndex);
}
-/** 页末表格接上下一页页首表格;需要列数一致并具备明确的跨页位置关系。 */
+/** An end-of-page table joins the table at the start of the next page; column counts must match and the cross-page position relationship must be clear. */
function canMergeTable(previous: TableCandidate, next: TableCandidate): boolean {
- // 续页可能只剩一行数据,不能要求下一页表格至少两行。
+ // A continuation page may have only one data row left, so the next page's table must not be required to have at least two rows.
if (previous.width !== next.width || previous.table.rows.length < 2 || next.table.rows.length < 1)
return false;
const bottom = previous.block.y + previous.block.h;
@@ -152,13 +152,13 @@ function canMergeTable(previous: TableCandidate, next: TableCandidate): boolean
if (bottom < 0.62 || top > 0.38) return false;
const repeatedHeader = repeatedHeaderRows(previous.table, next.table);
if (repeatedHeader > 0) return repeatedHeader < next.table.rows.length;
- // 下一页没有重复表头时,要求表格确实贴近页边界,且首行不是新的表头。
+ // When the next page has no repeated header, require the table to actually sit against the page edge, and the first row must not be a new header.
if (bottom < 0.75 || top > 0.3) return false;
const firstRow = next.table.rows[0]!;
return !Array.from(firstRow.cells).some((cell) => cell.tagName.toLowerCase() === 'th');
}
-/** 同一页内的续表必须垂直贴近且水平范围基本重合,避免拼接两张独立表。 */
+/** A continuation table on the same page must be vertically close and mostly overlap horizontally, so two independent tables are not joined. */
function canMergeTableInPage(previous: TableCandidate, next: TableCandidate): boolean {
if (previous.width !== next.width || !previous.table.rows.length || !next.table.rows.length)
return false;
@@ -222,7 +222,7 @@ function replaceTable(
};
}
-/** 移除续表占位,并把后续块范围前移;不留下连续空行。 */
+/** Remove the continuation-table placeholder and shift later block ranges forward; do not leave consecutive blank lines. */
function removeTable(result: ImageParseSdkResult, candidate: TableCandidate): ImageParseSdkResult {
let start = candidate.range.start;
let end = candidate.range.end;
@@ -254,7 +254,7 @@ function removeTable(result: ImageParseSdkResult, candidate: TableCandidate): Im
return { ...result, markdown, blocks };
}
-/** 合并后的单图表格要覆盖所有原始区域,保证原图框与正文定位仍可用。 */
+/** A merged single-image table must cover every original region, so original-image boxes and body positioning still work. */
function expandTableBlock(
result: ImageParseSdkResult,
blockIndex: number,
@@ -275,7 +275,7 @@ function expandTableBlock(
};
}
-/** 单图续表直接从版面中移除,不保留空块占位。 */
+/** A single-image continuation table is removed from the layout directly, with no empty-block placeholder kept. */
function removeTableBlock(
result: ImageParseSdkResult,
candidate: TableCandidate,
@@ -321,14 +321,14 @@ function imageTableChains(result: ImageParseSdkResult): TableCandidate[][] {
return chains;
}
-/** 判断单图是否存在可保守合并的相邻表格,用于决定工具栏入口是否渲染。 */
+/** Whether a single image has adjacent tables that can be merged conservatively, used to decide whether the toolbar entry renders. */
export function hasMergableImageParseTables(result: ImageParseSdkResult): boolean {
return imageTableChains(result).length > 0;
}
/**
- * 合并同一张图片内被识别拆开的相邻表格。只处理阅读顺序连续、垂直贴近、
- * 水平范围基本重合且列数一致的表格;中间有正文或疑似新表头时保持原样。
+ * Merge adjacent tables that recognition split apart inside the same image. Only tables that are consecutive in reading order, vertically close,
+ * mostly overlapping horizontally, and equal in column count are handled; when there is body text in between, or a suspected new header, leave them as-is.
*/
export function mergeImageParseTablesInPage(
result: ImageParseSdkResult,
@@ -357,10 +357,10 @@ export function mergeImageParseTablesInPage(
}
/**
- * 自动拼接 PDF 跨页表格。只处理「上一页最后一个内容块是表格、下一页第一个内容块也是表格」
- * 的保守场景;列结构不一致、存在页间正文或表格不在页边界时保持原样。
- * @param pages 按 PDF 页码(1 起始)排列的识别结果
- * @returns 发生变化页的 0 起始页码 → 新结果
+ * Automatically join cross-page PDF tables. Only the conservative case "the last content block of the previous page is a table, and the first content block of the next page is also a table"
+ * is handled; when the column structure differs, there is body text between pages, or the table is not on the page edge, leave them as-is.
+ * @param pages recognition results ordered by PDF page number (starting at 1)
+ * @returns 0-based page number of each changed page → new result
*/
export function mergeImageParseTables(
pages: readonly { page: number; result?: ImageParseSdkResult }[],
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseTaskView.ts b/webdemo/frontend/src/pages/playground/utils/imageParseTaskView.ts
index 9e0bd7d..20dd091 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseTaskView.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseTaskView.ts
@@ -2,7 +2,7 @@ import { isImageParsePipelineImageMode } from '@/api/map/imageParseSdk';
import type { useImageParse } from '../hooks/useImageParse';
import { isPdfAttachment } from './documentUpload';
-/** 当前任务对用户呈现的互斥阶段。 */
+/** Mutually exclusive phase the current task shows the user. */
export type ImageParseTaskPhase =
| 'empty'
| 'unsupported'
@@ -13,11 +13,11 @@ export type ImageParseTaskPhase =
| 'result';
/**
- * 派生任务对应的操作阶段,避免文档正文被误判为已有字段结果。
- * @param parse 当前识别状态
- * @param setupOpen 是否主动打开字段配置
- * @param uploading 是否仍在上传原件
- * @returns 任务、格式限制和开始操作状态
+ * Derive the operation phase for the task, so document body text is not mistaken for an existing field result.
+ * @param parse current recognition state
+ * @param setupOpen whether field configuration was opened on purpose
+ * @param uploading whether the original is still uploading
+ * @returns task, format limits, and start-operation state
*/
export function imageParseTaskView(
parse: ReturnType<typeof useImageParse>,
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseTourLayout.ts b/webdemo/frontend/src/pages/playground/utils/imageParseTourLayout.ts
index 0ae4927..f0a5177 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseTourLayout.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseTourLayout.ts
@@ -1,9 +1,9 @@
import type { Driver } from 'driver.js';
/**
- * 引导期间跟踪目标几何变化,让加载、换行及容器滚动后的遮罩和提示框保持对齐。
- * @param instance 当前引导实例
- * @returns 切步、关闭或卸载时取消检测的入口
+ * Track target geometry during the tour, so the mask and popover stay aligned after loading, wrapping, and container scroll.
+ * @param instance current tour instance
+ * @returns entry that cancels detection on step change, close, or unmount
*/
export function trackImageParseTourLayout(
instance: Pick<Driver, 'isActive' | 'getActiveElement' | 'refresh'>,
@@ -22,7 +22,7 @@ export function trackImageParseTourLayout(
instance.getActiveElement() !== element
)
return;
- // ResizeObserver 不感知同尺寸的位置变化;逐帧只读取当前目标,变化时才重绘。
+ // ResizeObserver does not notice a position change at the same size; each frame reads only the current target, and redraws only when it changes.
const rect = element.getBoundingClientRect();
if (
rect.x !== previous.x ||
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseTourSettings.ts b/webdemo/frontend/src/pages/playground/utils/imageParseTourSettings.ts
index 7f856a1..c7b2a67 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseTourSettings.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseTourSettings.ts
@@ -1,30 +1,30 @@
import type { Driver } from 'driver.js';
-/** 引导中需要展开设置菜单的两个触发器。 */
+/** The two triggers whose settings menu must be expanded during the tour. */
export const IMAGE_PARSE_TOUR_SETTINGS_TRIGGER_SELECTOR =
'[data-tour="image-parse-recognition-settings"], [data-tour="image-parse-confidence-toggle"]';
-/** 设置步骤临时隐藏遮罩,避免菜单被引导层压暗。 */
+/** The settings step temporarily hides the mask, so the menu is not dimmed by the tour layer. */
export const IMAGE_PARSE_TOUR_SETTINGS_CLASS = 'map-tour-settings-showcase';
-/** 设置菜单展开时,让引导说明与菜单保持安全距离。 */
+/** While the settings menu is open, keep a safe distance between the tour copy and the menu. */
const SETTINGS_POPOVER_OFFSET = 200;
-/** 普通步骤沿用 driver.js 默认间距。 */
+/** Ordinary steps keep driver.js default spacing. */
const DEFAULT_POPOVER_OFFSET = 10;
/**
- * 判断当前引导目标是否是需要展开菜单的设置入口。
- * @param element driver.js 当前高亮元素
- * @returns 是否为识别设置或显示设置触发器
+ * Whether the current tour target is a settings entry that needs its menu expanded.
+ * @param element element currently highlighted by driver.js
+ * @returns whether it is the recognition-settings or display-settings trigger
*/
export function isImageParseTourSettingsTrigger(element: Element | undefined): boolean {
return Boolean(element?.matches(IMAGE_PARSE_TOUR_SETTINGS_TRIGGER_SELECTOR));
}
/**
- * 设置步骤切换引导说明与高亮范围,其余步骤恢复默认遮罩和间距。
- * @param element driver.js 当前高亮元素
- * @param instance 当前引导实例
+ * The settings step switches tour copy and highlight range; other steps restore the default mask and spacing.
+ * @param element element currently highlighted by driver.js
+ * @param instance current tour instance
*/
export function syncTourStepHighlight(
element: Element | undefined,
@@ -38,7 +38,7 @@ export function syncTourStepHighlight(
});
}
-/** 关闭或离开引导时清理设置步骤专用样式。 */
+/** Clear styles that belong only to the settings step when the tour closes or is left. */
export function clearTourStepHighlight(): void {
document.body.classList.remove(IMAGE_PARSE_TOUR_SETTINGS_CLASS);
}
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseTourSteps.ts b/webdemo/frontend/src/pages/playground/utils/imageParseTourSteps.ts
index af7731a..f054db5 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseTourSteps.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseTourSteps.ts
@@ -1,8 +1,8 @@
import type { DriveStep } from 'driver.js';
/**
- * 示例步骤同时给出「下一步」。点下一步时载入当前列表的第一个示例,
- * 后续步骤等文档挂载后再由引导生命周期前进。
+ * The example step also offers "Next". Clicking Next loads the first example in the current list,
+ * and later steps advance through the tour lifecycle only after the document has mounted.
*/
export function exampleGatePopover(
selector: string,
@@ -10,7 +10,7 @@ export function exampleGatePopover(
): NonNullable<DriveStep['popover']> {
return {
showButtons: ['next', 'close'],
- // 后面的目标还没挂载时,driver.js 会把这一步当成最后一步,按钮变成「开始使用」。
+ // When a later target has not mounted yet, driver.js treats this step as the last one and the button becomes "Get started".
nextBtnText: nextLabel,
onNextClick: (_element, _step, { driver: instance }) => {
const example = document.querySelector<HTMLButtonElement>(
@@ -31,21 +31,21 @@ interface ImageParseTourStepsOptions {
}
/**
- * 构造文档解析引导:空态先让用户选择平台示例,再介绍识别设置与结果区能力。
- * @param options 翻译与当前文档状态
- * @returns 选择示例、识别设置、识别框、块编辑和导出步骤
+ * Build the document-parsing tour: the empty state first lets the user pick a platform example, then introduces recognition settings and result-area capabilities.
+ * @param options translations and current document state
+ * @returns the choose-example, recognition-settings, recognition-box, block-edit, and export steps
*/
export function imageParseTourSteps({
t,
hasDocument = () => false,
}: ImageParseTourStepsOptions): DriveStep[] {
- // 识别等待由引导生命周期处理;缺失的可选目标直接跳过,避免隐藏提示框后留下遮罩。
+ // Recognition waiting is handled by the tour lifecycle; a missing optional target is skipped directly, so a mask is not left behind after the popover is hidden.
const workspaceStep = { skipMissingElement: true, waitForElement: 0 };
const steps: DriveStep[] = [];
if (!hasDocument()) {
steps.push({
...workspaceStep,
- // 示例载入后选择区会卸载;该步骤已完成,回退时由 driver.js 跳过而不是停在无目标遮罩。
+ // After the example loads, the picker unmounts; that step is already done, and going back lets driver.js skip it instead of stopping on a mask with no target.
element: '[data-tour="image-parse-examples"]',
popover: {
title: t('imageParseTourExampleTitle'),
@@ -86,7 +86,7 @@ export function imageParseTourSteps({
},
{
...workspaceStep,
- // 解析完成前下载按钮尚不存在,先指向稳定的结果栏,避免引导空等。
+ // Before parsing finishes the download button does not exist yet, so point at the stable result bar first and do not leave the tour waiting on nothing.
element: '[data-pane="markdown"]',
popover: {
title: t('imageParseTourExportTitle'),
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseUpload.ts b/webdemo/frontend/src/pages/playground/utils/imageParseUpload.ts
index 071b607..3dfb707 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseUpload.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseUpload.ts
@@ -7,11 +7,11 @@ import {
} from './attachments';
/**
- * OCR 原件只上传文件服务,PDF 使用 Blob URL 预览,不经过旧资产或本地兜底。
- * @param file 已完成格式和大小校验的文件
- * @param options 文档格式及大小边界
- * @param signal 上传生命周期
- * @returns 稳定 fileId 与本地预览;失败不返回可识别附件
+ * OCR originals are uploaded only to the file service. PDFs preview with a Blob URL and do not go through the legacy asset path or a local fallback.
+ * @param file file that has already passed format and size checks
+ * @param options document format and size bounds
+ * @param signal upload lifecycle
+ * @returns stable fileId and local preview; on failure, do not return an attachment that can be recognized
*/
export async function uploadImageParseDocument(
file: File,
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseWord.ts b/webdemo/frontend/src/pages/playground/utils/imageParseWord.ts
index 26b7b6a..4df28ad 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseWord.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseWord.ts
@@ -106,7 +106,7 @@ function wordBlocks(
case 'code':
return [new Paragraph({ children: textRuns(node.value, { font: 'Courier New' }) })];
case 'math':
- // 保留 LaTeX 原文,避免把不支持的公式转换成错误的数学表达式。
+ // Keep the original LaTeX, so an unsupported formula is not converted into a wrong math expression.
return [new Paragraph({ children: textRuns(node.value) })];
case 'html':
return imageParseHtmlToWord(node.value, context.numbering);
@@ -168,9 +168,9 @@ function wordBlocks(
}
/**
- * 将当前 Markdown 草稿导出为真实 DOCX,保留标题、正文格式、列表和可编辑表格。
- * @param markdown 点击下载时的当前正文;公式保留 LaTeX,远程图片不自动请求
- * @returns 可直接交给浏览器下载的 Word 文件
+ * Export the current Markdown draft as a real DOCX, keeping headings, body formatting, lists, and editable tables.
+ * @param markdown current body at the moment of download; formulas keep LaTeX, and remote images are not requested automatically
+ * @returns a Word file that can be handed straight to the browser to download
*/
export async function createImageParseWordBlob(markdown: string): Promise<Blob> {
const tree = PARSER.parse(normalizeMathDelimiters(markdown, { detectBareMath: false })) as Root;
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseWordHtml.ts b/webdemo/frontend/src/pages/playground/utils/imageParseWordHtml.ts
index 4071678..b5f8aad 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseWordHtml.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseWordHtml.ts
@@ -14,29 +14,29 @@ import {
import { imageParseTextLineBreaks } from './imageParseLineBreaks';
-/** HTML 与 GFM 表格共用的 Word 单元格信息。 */
+/** Word cell info shared by HTML and GFM tables. */
export interface ImageParseWordCell {
children: Array<Paragraph | Table>;
columnSpan?: number;
rowSpan?: number;
}
-/** HTML 列表与 Markdown 列表共用的编号定义。 */
+/** Numbering definition shared by HTML lists and Markdown lists. */
export type ImageParseWordNumbering = Array<{ reference: string; levels: ILevelsOptions[] }>;
-/** A4 页面扣除两侧各 1 英寸留白后的正文宽度,单位为 twip。 */
+/** Body width of an A4 page after 1 inch of margin on each side, in twips. */
export const IMAGE_PARSE_WORD_WIDTH = 9026;
-/** 保留安全链接为 Word 超链接,危险协议只保留可见文字。 */
+/** Keep a safe link as a Word hyperlink; a dangerous scheme keeps only the visible text. */
export function imageParseWordLink(url: string, children: TextRun[]) {
if (!/^(https?:\/\/|mailto:)/i.test(url)) return children;
return [new ExternalHyperlink({ link: url, children })];
}
/**
- * 创建有明确列宽的可编辑表格;合并行列交由 docx 生成合法 OOXML。
- * @param rows 按阅读顺序排列的单元格
- * @returns 自适应正文宽度的 Word 表格
+ * Create an editable table with explicit column widths; merged rows and columns are left to docx to emit legal OOXML.
+ * @param rows cells in reading order
+ * @returns a Word table that fits the body width
*/
export function imageParseWordTable(rows: ImageParseWordCell[][]): Table {
const columns = Math.max(
@@ -196,9 +196,9 @@ function htmlBlocks(
}
/**
- * 解析 OCR 的 HTML 片段;DOM 仅在脱离页面的文档中读取,不执行脚本或加载远程媒体。
- * @param html 原始 HTML 块
- * @returns 可编辑表格与正文段落
+ * Parse an OCR HTML fragment; the DOM is read only in a document detached from the page, and does not run scripts or load remote media.
+ * @param html original HTML block
+ * @returns editable tables and body paragraphs
*/
export function imageParseHtmlToWord(
html: string,
@@ -208,7 +208,7 @@ export function imageParseHtmlToWord(
return htmlFlow([...document.body.childNodes], numbering, 0);
}
-/** 转换 Markdown 内嵌 HTML,保留显式换行且不执行脚本。 */
+/** Convert HTML embedded in Markdown, keeping explicit line breaks and not running scripts. */
export function imageParseHtmlWordRuns(html: string, style: IRunOptions) {
const document = new DOMParser().parseFromString(html, 'text/html');
return [...document.body.childNodes].flatMap((node) => htmlRuns(node, style));
diff --git a/webdemo/frontend/src/pages/playground/utils/imageParseWorkspaceStyles.ts b/webdemo/frontend/src/pages/playground/utils/imageParseWorkspaceStyles.ts
index 06c945d..601cf74 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageParseWorkspaceStyles.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageParseWorkspaceStyles.ts
@@ -1,35 +1,35 @@
import { cn } from '@map/ui';
-/** 左右工作栏共用头部尺寸,避免控件留白不同导致分隔线错位。 */
+/** Shared header size for the left and right workspace columns, so different control padding does not misalign the divider. */
export const WORKSPACE_TOOLBAR =
'flex min-h-11 shrink-0 flex-wrap items-center gap-y-1 border-b border-border/60 bg-card px-3 [@media(pointer:coarse)]:min-h-14';
-/** 文档工作台的紧凑控件:桌面 32px,粗指针设备保留 44px 点击目标。 */
+/** Compact controls for the document workspace: 32px on desktop, and a 44px hit target kept on coarse-pointer devices. */
export const WORKSPACE_CONTROL =
'h-8 min-h-8 rounded-md px-2.5 text-xs font-medium [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:min-h-11 [@media(pointer:coarse)]:min-w-11';
-/** 图标操作与文字操作共用高度、圆角和焦点规则。 */
+/** Icon actions and text actions share height, radius, and focus rules. */
export const WORKSPACE_ICON_CONTROL =
'h-8 w-8 min-h-8 shrink-0 rounded-md p-0 [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:w-11';
-/** 分段控件外壳使用薄描边,仅选中项填充,避免整组按钮视觉过重。 */
+/** The segmented-control shell uses a thin stroke and fills only the selected item, so the whole group of buttons is not visually heavy. */
export const WORKSPACE_SEGMENT =
'inline-flex shrink-0 items-center gap-0.5 rounded-lg border border-border/70 bg-muted/40 p-px';
-/** 分段项比外壳紧凑一档,触屏尺寸仍与其他操作一致。 */
+/** A segment is one step more compact than the shell; the touch size still matches the other actions. */
export const WORKSPACE_SEGMENT_ITEM =
'h-7 min-h-7 rounded-md px-2.5 text-xs font-medium [@media(pointer:coarse)]:h-11 [@media(pointer:coarse)]:min-h-11';
type PaneId = 'origin' | 'markdown';
/**
- * 文档对照分栏:桌面按 --map-split 调整原图宽度,窄屏上下排列。
- * @param pane 原图栏或识别结果栏
- * @param dragging 是否正在拖分隔条,为真时关掉宽度过渡
+ * Document comparison split: on desktop, original-image width follows --map-split; on a narrow screen the panes stack.
+ * @param pane original-image pane or recognition-result pane
+ * @param dragging whether the divider is being dragged; when true, turn off the width transition
*/
export function paneClass(pane: PaneId, dragging: boolean, setup = false): string {
return cn(
- // 将栏内的 sticky 顶栏限定在本栏,避免遮挡分隔条的抓取区。
+ // Confine the sticky top bar to its own pane, so it does not cover the divider's grab area.
'isolate min-h-0 min-w-0 overflow-hidden bg-background',
'transition-[flex] duration-200 ease-out motion-reduce:transition-none',
dragging && 'transition-none',
diff --git a/webdemo/frontend/src/pages/playground/utils/imageZoom.ts b/webdemo/frontend/src/pages/playground/utils/imageZoom.ts
index 9d2a022..7859552 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageZoom.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageZoom.ts
@@ -1,9 +1,9 @@
/**
- * 图片视图(缩放 / 平移 / 旋转)的纯几何换算。
+ * Pure geometry for the image view (zoom / pan / rotation).
*
- * 文档阅读使用严格边界与顶部对齐;clampView 保留全屏预览的旧几何契约。
- * transform 约定为 translate → scale → rotate:translate 写在最外层,
- * 平移量落在屏幕坐标系里,任意倍数、任意角度下都是「拖一像素走一像素」。
+ * Document reading uses a strict boundary and top alignment; clampView keeps the old geometry contract of fullscreen preview.
+ * The transform is translate → scale → rotate: translate is written outermost,
+ * so pan is in screen coordinates and is "drag one pixel, move one pixel" at any scale and any angle.
*/
import type { ImageZoomView, Point, Size } from './imageZoomTypes';
@@ -11,19 +11,19 @@ import type { ImageZoomView, Point, Size } from './imageZoomTypes';
export type { ImageZoomView, Point, Size } from './imageZoomTypes';
/**
- * 缩放区间与步进。
- * FIT_SCALE=1 是布局基准;MIN_SCALE 允许缩小查看全貌,上限 6 倍用于核对小字。
+ * Zoom range and step.
+ * FIT_SCALE=1 is the layout baseline; MIN_SCALE allows zooming out to see the whole image, and the 6x cap is for checking small text.
*/
export const FIT_SCALE = 1;
export const MIN_SCALE = 0.25;
export const MAX_SCALE = 6;
-/** 按钮每次缩放的步长。25% 一档,缩到下限后仍能逐档回到 100%。 */
+/** Step for each button zoom. 25% per step, so after zooming to the floor it can still return to 100% step by step. */
export const BUTTON_STEP = 0.25;
-/** 滚轮像素 → 缩放比例的系数。 */
+/** Coefficient from wheel pixels to zoom ratio. */
export const WHEEL_STEP = 0.0015;
-/** 双击放大到的倍数。 */
+/** Scale a double-click zooms to. */
export const DOUBLE_CLICK_SCALE = 2.5;
-/** 无论怎么拖,图至少要留这么多像素在视口里,否则就真找不回来了。 */
+/** No matter how it is dragged, the image must leave at least this many pixels inside the viewport, or it really cannot be found again. */
const KEEP_VISIBLE = 48;
export const INITIAL_VIEW: ImageZoomView = {
@@ -32,7 +32,7 @@ export const INITIAL_VIEW: ImageZoomView = {
rotation: 0,
};
-/** 是否为 90° / 270°,此时内容的宽高在屏幕上互换。 */
+/** Whether the angle is 90° / 270°, when content width and height are swapped on screen. */
export function isQuarterTurn(rotation: number): boolean {
return rotation % 180 !== 0;
}
@@ -41,7 +41,7 @@ export function clampScale(value: number): number {
return Math.min(MAX_SCALE, Math.max(MIN_SCALE, value));
}
-/** 按钮缩放对齐到 25% 网格,避免缩到 25% 后再放大时跳过 100%。 */
+/** Button zoom snaps to a 25% grid, so zooming back in after 25% does not skip 100%. */
export function buttonScale(current: number, direction: 1 | -1): number {
const steps = current / BUTTON_STEP;
const nearest = Math.round(steps);
@@ -59,17 +59,17 @@ function clampAbs(value: number, max: number): number {
}
/**
- * 旋转贴合系数;避免包围盒超出视口,未测量到尺寸时返回 1。
- * @param rotation 当前角度
- * @param viewport 视口尺寸
- * @param content 内容未变换时的布局尺寸
+ * Rotation fit factor; keeps the bounding box from exceeding the viewport, and returns 1 when size has not been measured.
+ * @param rotation current angle
+ * @param viewport viewport size
+ * @param content layout size of the content before transform
*/
export function fitFactor(rotation: number, viewport: Size, content: Size): number {
if (!isQuarterTurn(rotation) || !viewport.width || !content.width || !content.height) return 1;
return Math.min(1, viewport.width / content.height, viewport.height / content.width);
}
-/** 变换后内容在屏幕上的包围盒。旋转 90° 时宽高互换。 */
+/** Bounding box of the transformed content on screen. Width and height swap at 90°. */
function contentBox(view: ImageZoomView, viewport: Size, content: Size): Size {
const effective = view.scale * fitFactor(view.rotation, viewport, content);
const quarter = isQuarterTurn(view.rotation);
@@ -79,7 +79,7 @@ function contentBox(view: ImageZoomView, viewport: Size, content: Size): Size {
};
}
-/** 阅读模式禁止拖出图片边界;短图固定顶部对齐,横向不足视口时居中。 */
+/** Reading mode forbids dragging past the image edge; a short image stays top-aligned, and is centered when it is narrower than the viewport. */
export function clampDocumentView(
view: ImageZoomView,
viewport: Size,
@@ -96,14 +96,14 @@ export function clampDocumentView(
return { ...view, offset: { x, y } };
}
-/** 文档纵向位置在可滚动范围内的比例,用于双栏联动。 */
+/** Fraction of the document's vertical position within the scrollable range, used to link the two columns. */
export function documentScrollProgress(view: ImageZoomView, viewport: Size, content: Size): number {
if (!viewport.height || !content.height) return 0;
const max = Math.max(0, (contentBox(view, viewport, content).height - viewport.height) / 2);
return max ? Math.max(0, Math.min(1, (max - view.offset.y) / (max * 2))) : 0;
}
-/** 把结果栏的滚动比例映射到图片的竖向平移。 */
+/** Map the result column's scroll fraction to the image's vertical pan. */
export function viewAtDocumentProgress(
view: ImageZoomView,
viewport: Size,
@@ -121,17 +121,17 @@ export function viewAtDocumentProgress(
content,
);
}
-/** 任何时候都要留在视口里的内容像素;内容或视口本身很小时退让到一半。 */
+/** Content pixels that must stay inside the viewport at all times; when the content or the viewport itself is very small, yield to half. */
function keepVisible(contentSpan: number, viewportSpan: number): number {
return Math.min(KEEP_VISIBLE, contentSpan / 2, viewportSpan / 2);
}
/**
- * 全屏预览旧平移上限:至少保留 KEEP_VISIBLE 像素;未测量时不设限。
- * @param view 当前视图
- * @param viewport 视口尺寸
- * @param content 内容未变换时的布局尺寸
- * @returns 两轴平移量的绝对值上限
+ * Old pan limit for fullscreen preview: keep at least KEEP_VISIBLE pixels; when unmeasured, set no limit.
+ * @param view current view
+ * @param viewport viewport size
+ * @param content layout size of the content before transform
+ * @returns absolute upper bound of pan on both axes
*/
export function viewBounds(view: ImageZoomView, viewport: Size, content: Size): Point {
if (!viewport.width || !content.width) return { x: Infinity, y: Infinity };
@@ -142,7 +142,7 @@ export function viewBounds(view: ImageZoomView, viewport: Size, content: Size):
};
}
-/** 把平移量夹回上限内,图就不会被拖出视口再也找不回来。 */
+/** Clamp pan back inside the limit, so the image cannot be dragged out of the viewport and lost. */
export function clampView(view: ImageZoomView, viewport: Size, content: Size): ImageZoomView {
const bounds = viewBounds(view, viewport, content);
const x = clampAbs(view.offset.x, bounds.x);
@@ -152,17 +152,17 @@ export function clampView(view: ImageZoomView, viewport: Size, content: Size): I
}
/**
- * 换算缩放后的视图。
- * anchor 给定时保持该点在屏幕上不动——滚轮锚在光标上,放大后要看的字不会被挤出视口;
- * 按钮缩放传 null,锚在视口中心。
- * @param view 当前视图
- * @param next 目标倍数,会夹进 [MIN_SCALE, MAX_SCALE]
- * @param anchor 锚点相对视口中心的偏移,null 表示锚在中心
+ * Compute the view after a zoom.
+ * When anchor is given, that point stays still on screen — the wheel anchors on the cursor, so the text you zoomed in to read is not pushed out of the viewport;
+ * button zoom passes null and anchors on the viewport center.
+ * @param view current view
+ * @param next target scale, clamped to [MIN_SCALE, MAX_SCALE]
+ * @param anchor anchor offset relative to the viewport center; null means the anchor is the center
*/
export function scaleTo(view: ImageZoomView, next: number, anchor: Point | null): ImageZoomView {
const scale = clampScale(next);
if (scale === view.scale) return view;
- // 锚在中心时平移量不用动:中心点本来就不随缩放移动。
+ // When the anchor is the center, pan does not need to move: the center point does not move with zoom anyway.
if (!anchor) return { ...view, scale };
const ratio = 1 - scale / view.scale;
return {
@@ -176,9 +176,9 @@ export function scaleTo(view: ImageZoomView, next: number, anchor: Point | null)
}
/**
- * 锚点换算:把屏幕坐标换成「相对视口中心的偏移」,即 scaleTo 要的 anchor。
- * @param point 屏幕坐标(WheelEvent / MouseEvent 都满足)
- * @param rect 视口矩形,拿不到时返回 null 表示锚在中心
+ * Anchor conversion: turn screen coordinates into "offset relative to the viewport center", the anchor scaleTo wants.
+ * @param point screen coordinates (WheelEvent and MouseEvent both qualify)
+ * @param rect viewport rectangle; when unavailable, return null to mean the anchor is the center
*/
export function anchorFromCenter(
point: { clientX: number; clientY: number },
@@ -191,17 +191,17 @@ export function anchorFromCenter(
};
}
-/** 平移。dx/dy 是屏幕位移,直接相加即 1:1 跟手。 */
+/** Pan. dx/dy are screen deltas and are added directly, so it follows the hand 1:1. */
export function panBy(view: ImageZoomView, dx: number, dy: number): ImageZoomView {
return { ...view, offset: { x: view.offset.x + dx, y: view.offset.y + dy } };
}
/**
- * 将原图归一化坐标中的识别块居中;旋转后按屏幕坐标换算平移量。
- * @param block 识别块坐标
- * @param view 当前缩放与旋转
- * @param viewport 视口尺寸
- * @param content 图片的布局尺寸
+ * Center the recognition block in normalized original-image coordinates; after rotation, convert pan in screen coordinates.
+ * @param block recognition-block coordinates
+ * @param view current zoom and rotation
+ * @param viewport viewport size
+ * @param content layout size of the image
*/
export function focusBlockView(
block: { x: number; y: number; w: number; h: number },
@@ -230,10 +230,10 @@ export function focusBlockView(
}
/**
- * 按最终布局尺寸绘制原图;变换只处理平移和旋转,框线与编号保持固定尺寸。
- * @param view 当前视图
- * @param viewport 视口尺寸
- * @param content 图片未缩放的布局尺寸
+ * Draw the original image at the final layout size; the transform handles only pan and rotation, and box strokes and numbers keep a fixed size.
+ * @param view current view
+ * @param viewport viewport size
+ * @param content unscaled layout size of the image
*/
export function imageRasterView(view: ImageZoomView, viewport: Size, content: Size) {
const factor = view.scale * fitFactor(view.rotation, viewport, content);
@@ -245,10 +245,10 @@ export function imageRasterView(view: ImageZoomView, viewport: Size, content: Si
}
/**
- * 将图片旋转后的宽度贴合视口;长图从顶部开始,后续可拖动核对。
- * @param view 当前视图
- * @param viewport 视口尺寸
- * @param content 图片未缩放的布局尺寸
+ * Fit the image's width to the viewport after rotation; a long image starts at the top, and can be dragged later to check it.
+ * @param view current view
+ * @param viewport viewport size
+ * @param content unscaled layout size of the image
*/
export function fitWidthView(view: ImageZoomView, viewport: Size, content: Size): ImageZoomView {
if (!viewport.width || !content.width || !content.height) return view;
@@ -268,20 +268,20 @@ export function fitWidthView(view: ImageZoomView, viewport: Size, content: Size)
}
/**
- * @param view 当前视图
- * @param direction 1 顺时针,-1 逆时针
+ * @param view current view
+ * @param direction 1 clockwise, -1 counterclockwise
*/
export function rotateView(view: ImageZoomView, direction: 1 | -1 = 1): ImageZoomView {
- // 先加 360 再取模,避免逆时针在 0° 时算出 -90。
+ // Add 360 before the modulo, so counterclockwise does not compute -90 at 0°.
return { ...view, rotation: (view.rotation + 360 + 90 * direction) % 360 };
}
-/** 只还原缩放与平移,保留角度——双击用,纠正过方向的图不该被一并转回去。 */
+/** Restore only zoom and pan, and keep the angle — used by double-click, so an image whose orientation was corrected is not rotated back as well. */
export function resetZoom(view: ImageZoomView): ImageZoomView {
return { ...view, scale: FIT_SCALE, offset: { x: 0, y: 0 } };
}
-/** 是否偏离初始视图,用于决定是否显示「还原」。 */
+/** Whether the view has left the initial view, used to decide whether to show "Reset". */
export function isTransformed(view: ImageZoomView): boolean {
return (
view.scale !== FIT_SCALE || view.rotation !== 0 || view.offset.x !== 0 || view.offset.y !== 0
@@ -289,17 +289,17 @@ export function isTransformed(view: ImageZoomView): boolean {
}
/**
- * 生成 CSS transform。顺序见文件头说明,改动顺序会同时破坏平移方向与锚点换算。
- * @param view 当前视图
- * @param viewport 视口尺寸
- * @param content 内容未变换时的布局尺寸
+ * Build the CSS transform. The order is explained at the top of the file; changing the order breaks both pan direction and anchor conversion.
+ * @param view current view
+ * @param viewport viewport size
+ * @param content layout size of the content before transform
*/
export function viewTransform(view: ImageZoomView, viewport: Size, content: Size): string {
const scale = view.scale * fitFactor(view.rotation, viewport, content);
return `translate(${round(view.offset.x)}px, ${round(view.offset.y)}px) scale(${round(scale, 4)}) rotate(${view.rotation}deg)`;
}
-/** 收掉浮点噪声,避免 style 字符串每帧都长得不一样。 */
+/** Drop floating-point noise, so the style string does not look different every frame. */
function round(value: number, digits = 2): number {
const factor = 10 ** digits;
return Math.round(value * factor) / factor;
diff --git a/webdemo/frontend/src/pages/playground/utils/imageZoomTypes.ts b/webdemo/frontend/src/pages/playground/utils/imageZoomTypes.ts
index 3f12ac8..c7dc824 100644
--- a/webdemo/frontend/src/pages/playground/utils/imageZoomTypes.ts
+++ b/webdemo/frontend/src/pages/playground/utils/imageZoomTypes.ts
@@ -1,20 +1,20 @@
-/** 屏幕坐标系中的点或平移量,单位为 CSS 像素。 */
+/** A point or pan amount in screen coordinates, in CSS pixels. */
export interface Point {
x: number;
y: number;
}
-/** 元素的布局尺寸;宽为 0 表示还没测量到。 */
+/** Layout size of an element; width 0 means it has not been measured yet. */
export interface Size {
width: number;
height: number;
}
-/** 视图状态。scale=FIT_SCALE 恒定表示「整图贴合视口」,与角度无关。 */
+/** View state. scale=FIT_SCALE always means "the whole image fits the viewport", independent of angle. */
export interface ImageZoomView {
scale: number;
- /** 屏幕坐标系下的平移量(CSS 像素) */
+ /** Pan in screen coordinates (CSS pixels) */
offset: Point;
- /** 旋转角度,90° 步进,取值 0/90/180/270 */
+ /** Rotation angle, in 90° steps, one of 0/90/180/270 */
rotation: number;
}
diff --git a/webdemo/frontend/src/pages/playground/utils/markdownTable.ts b/webdemo/frontend/src/pages/playground/utils/markdownTable.ts
index 817fc0f..30e4cae 100644
--- a/webdemo/frontend/src/pages/playground/utils/markdownTable.ts
+++ b/webdemo/frontend/src/pages/playground/utils/markdownTable.ts
@@ -1,7 +1,7 @@
import { imageParseNodeText, imageParseSourceBlocks } from './imageParseEditorSource';
import { replaceImageParseTextLineBreaks } from './imageParseLineBreaks';
-/** 一张表的二维文字网格;合并单元格只在左上位置保留文字。 */
+/** Two-dimensional text grid of one table; a merged cell keeps its text only at the top-left position. */
export type MarkdownTable = string[][];
function htmlTables(value: string): MarkdownTable[] {
@@ -35,8 +35,8 @@ function htmlTables(value: string): MarkdownTable[] {
}
/**
- * 使用成熟 Markdown AST 抽取 GFM 与 HTML 表格,排除代码块内的示例。
- * @param markdown 原始或编辑后的文档,HTML 合并表格无需降级
+ * Extract GFM and HTML tables with a mature Markdown AST, excluding examples inside code blocks.
+ * @param markdown original or edited document; an HTML table with merged cells does not need to be downgraded
*/
export function extractMarkdownTables(markdown: string): MarkdownTable[] {
return imageParseSourceBlocks(markdown).flatMap((block) => {
@@ -56,7 +56,7 @@ function tsvCell(value: string) {
return /[\t\n\r"]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value;
}
-/** 将文档表格导出为 TSV;换行和引号遵循表格软件的字段转义规则。 */
+/** Export a document table as TSV; newlines and quotes follow spreadsheet field-escaping rules. */
export function markdownTablesToTsv(markdown: string): string {
return extractMarkdownTables(markdown)
.map((table) => table.map((row) => row.map(tsvCell).join('\t')).join('\n'))
@@ -73,10 +73,10 @@ function htmlCell(value: string) {
}
/**
- * 将文档表格导出为 HTML 表格:飞书、Word 只有拿到 `text/html` 才会还原出单元格,
- * 纯文本粘过去只会退化成一行行文字。
- * 表头信息在抽取阶段已经丢失(GFM 表与 HTML 表都只剩二维网格),因此统一输出 `td`。
- * 多张表之间插入空段落,避免 Word 把相邻表格合并成一张。
+ * Export a document table as an HTML table: Feishu and Word restore cells only when they receive `text/html`,
+ * and plain text pastes as lines of text.
+ * Header information is already lost at extraction time (both GFM tables and HTML tables are left as a two-dimensional grid), so everything is emitted as `td`.
+ * An empty paragraph is inserted between tables, so Word does not merge adjacent tables into one.
*/
export function markdownTablesToHtml(markdown: string): string {
return extractMarkdownTables(markdown)
diff --git a/webdemo/frontend/src/pages/playground/utils/math-katex.ts b/webdemo/frontend/src/pages/playground/utils/math-katex.ts
index 5a14876..601293b 100644
--- a/webdemo/frontend/src/pages/playground/utils/math-katex.ts
+++ b/webdemo/frontend/src/pages/playground/utils/math-katex.ts
@@ -1,7 +1,7 @@
/**
- * 裸数学表达式识别与 KaTeX 语法校验。
+ * Bare math-expression recognition and KaTeX syntax checks.
*
- * 用途:识别未加定界符的模型数学输出,并由 KaTeX 判断命令与环境是否受支持。
+ * Purpose: recognize model math output that has no delimiters, and let KaTeX decide whether a command or environment is supported.
*/
import katex from 'katex';
@@ -59,14 +59,14 @@ const PROSE_IDENTIFIERS = new Set([
'with',
]);
-/** 把普通文本中的裸数学块补成块级公式,已有美元符公式不会进入此函数。 */
+/** Turn a bare math block in ordinary text into a block formula; formulas that already use dollar signs do not enter this function. */
export function wrapBareMath(text: string): string {
const withBracketedMath = wrapBracketedMath(text, isBareMath);
const blocks = withBracketedMath.split(/(\n[ \t]*\n+)/);
return blocks
.map((block, index) => {
if (index % 2 === 1 || !block.trim()) return block;
- // 全英文/数字表格也可能通过 KaTeX 校验,必须先保护表格行,避免整表误转成公式。
+ // An all-English or all-numeric table can also pass KaTeX checks, so table rows must be protected first, or the whole table would be turned into a formula by mistake.
if (!block.split('\n').some(isMarkdownTableRow) && isBareMath(block.trim())) {
return preserveOuterWhitespace(block, wrapDisplayMath);
}
@@ -88,16 +88,16 @@ export function wrapBareMath(text: string): string {
}
/**
- * 把模型误用反引号包裹的明确数学表达式转换为行内公式。
+ * Turn an explicit math expression the model wrapped in backticks by mistake into an inline formula.
*
- * 仅接受 KaTeX 可完整解析,且包含显式命令、Unicode 数学运算符或至少两类数学结构的内容;
- * 单个变量、路径、命令和普通代码继续保留 Markdown 代码语义。
+ * Accept only content KaTeX can parse completely, and that contains an explicit command, a Unicode math operator, or at least two kinds of math structure;
+ * a single variable, a path, a command, and ordinary code keep Markdown code semantics.
*/
export function normalizeInlineCodeMath(codeSpan: string): string {
return normalizeMarkdownInlineCodeMath(codeSpan, isBareMath);
}
-/** 将完整且受 KaTeX 支持的任意裸环境转换为块级公式。 */
+/** Turn any complete bare environment that KaTeX supports into a block formula. */
function wrapSupportedEnvironments(text: string): string {
let cursor = 0;
let output = '';
@@ -119,7 +119,7 @@ function wrapSupportedEnvironments(text: string): string {
return output;
}
-/** 查找下一个配对完整的 LaTeX 环境,支持环境嵌套。 */
+/** Find the next fully paired LaTeX environment, supporting nested environments. */
function findNextEnvironment(
text: string,
from: number,
@@ -146,36 +146,36 @@ function findNextEnvironment(
}
/**
- * 判断一段文本是否为模型吐出的工具调用/属性标记,而不是公式。
+ * Whether a piece of text is a tool-call or attribute marker the model emitted, rather than a formula.
*
- * 小模型会把工具调用当正文输出(2026-09-21 实测 MiniCPM5-2B:
- * `name="weather_search"> name="location">Beijing`)。这类残片里的 `=`、`>`、`_`
- * 会被当成关系符和下标,KaTeX 又恰好能解析成功,于是整段被渲染成衬线公式。
- * isBareMath 里的 HTML 标签护栏拦不住它——残片里根本没有 `<`。
+ * Small models emit tool calls as body text (measured 2026-09-21 on MiniCPM5-2B:
+ * `name="weather_search"> name="location">Beijing`). The `=`, `>`, and `_` in such a fragment
+ * are taken as relations and subscripts, and KaTeX happens to parse it, so the whole fragment is rendered as a serif formula.
+ * The HTML-tag guard in isBareMath does not stop it — the fragment has no `<` at all.
*/
function isToolCallMarkup(value: string): boolean {
- // 公式基本不含 ASCII 双引号;英寸/角分等写法请显式用 $...$ 包裹。
+ // A formula basically contains no ASCII double quotes; write inches or arcminutes explicitly inside $...$.
if (value.includes('"')) return true;
- // key="value" / key='value' 形态的属性赋值。
+ // Attribute assignment of the form key="value" / key='value'.
if (/[A-Za-z_][\w-]*\s*=\s*["'][^"']*["']/.test(value)) return true;
- // snake_case 标识符:真实下标几乎都是单字符(x_1、F_{net}),两侧各两个以上字母的更像代码。
+ // A snake_case identifier: a real subscript is almost always a single character (x_1, F_{net}); two or more letters on each side looks more like code.
if (/[A-Za-z]{2,}_[A-Za-z]{2,}/.test(value)) return true;
return false;
}
/**
- * 判断一行是否只由 Markdown 标记符号组成,不含任何被运算的内容。
+ * Whether a line is made only of Markdown marker characters and contains nothing being operated on.
*
- * `---`、`***` 是分割线,`---`、`===` 紧跟段落时是 setext 标题下划线,落单的 `-`、`+`、`>`
- * 是空列表项或空引用。这些行里的 `-`、`*`、`=` 会被当成运算符和关系符,KaTeX 又恰好能解析成功,
- * 于是分割线被渲染成一串衬线减号,setext 标题也被拆成「段落 + 公式」两块。
- * 真实公式至少含一个被运算的字母、数字或命令,整类排除不会误伤。
+ * `---` and `***` are thematic breaks; `---` and `===` right after a paragraph are a setext heading underline; a lone `-`, `+`, or `>`
+ * is an empty list item or an empty quote. The `-`, `*`, and `=` in these lines are taken as operators and relations, and KaTeX happens to parse them,
+ * so a thematic break is rendered as a string of serif minus signs, and a setext heading is split into "paragraph + formula".
+ * A real formula contains at least one letter, digit, or command being operated on, so excluding the whole class does not cause false misses.
*/
function isMarkdownPunctuationLine(value: string): boolean {
return /^[-*_=+>][-*_=+>\t ]*$/.test(value);
}
-/** 判断一段独占内容是否具备明确数学特征且能被 KaTeX 完整解析。 */
+/** Whether a standalone piece of content has clear math features and can be parsed completely by KaTeX. */
export function isBareMath(value: string): boolean {
if (!value || value.length > KATEX_MAX_INPUT_LENGTH || value.includes('$')) return false;
if (isMarkdownPunctuationLine(value)) return false;
@@ -213,7 +213,7 @@ export function isBareMath(value: string): boolean {
const hasMathStructure = hasRelation || hasScript || hasOperator || hasFunctionShape;
if (!hasEnvironment && !startsWithCommand && !hasMathStructure && !hasCommand) return false;
- // 以 LaTeX 命令或环境开头是明确的公式意图,不套用工具调用启发式;其余内容一律先排除标记残片。
+ // Starting with a LaTeX command or environment is a clear formula intent and does not use the tool-call heuristic; everything else excludes marker fragments first.
if (!startsWithCommand && !hasEnvironment && isToolCallMarkup(textMasked)) return false;
if (containsProseIdentifier) return false;
if (
@@ -230,9 +230,9 @@ export function isBareMath(value: string): boolean {
}
/**
- * 用 KaTeX 公共 API 校验完整语法,预览与公式编辑共用安全配置和有界缓存。
- * @param value 不带数学定界符的 LaTeX
- * @returns 是否可以安全解析为公式
+ * Validate complete syntax with the KaTeX public API; preview and formula editing share the safe config and a bounded cache.
+ * @param value LaTeX without math delimiters
+ * @returns whether it can be parsed safely as a formula
*/
export function isSupportedKatex(value: string): boolean {
const cached = KATEX_VALIDITY_CACHE.get(value);
@@ -256,7 +256,7 @@ export function isSupportedKatex(value: string): boolean {
return valid;
}
-/** 屏蔽 `\text{...}` 等文本命令参数,使公式内中文不会被当作外部说明文字。 */
+/** Mask text-command arguments such as `\text{...}`, so Chinese inside a formula is not treated as external explanatory text. */
function maskTextCommandArguments(value: string): string {
const chars = value.split('');
TEXT_COMMAND_PATTERN.lastIndex = 0;
@@ -273,7 +273,7 @@ function maskTextCommandArguments(value: string): string {
return chars.join('');
}
-/** 找到指定左花括号对应的右花括号。 */
+/** Find the right brace that matches the given left brace. */
function findClosingBrace(value: string, open: number): number {
let depth = 0;
for (let index = open; index < value.length; index += 1) {
@@ -285,7 +285,7 @@ function findClosingBrace(value: string, open: number): number {
return -1;
}
-/** 流式输出分组尚未闭合时保持纯文本,避免短暂显示 KaTeX 错误。 */
+/** While a streaming-output group is still unclosed, keep plain text, so a KaTeX error is not shown briefly. */
function hasBalancedBraces(value: string): boolean {
let depth = 0;
for (let index = 0; index < value.length; index += 1) {
@@ -297,46 +297,46 @@ function hasBalancedBraces(value: string): boolean {
return depth === 0;
}
-/** 保留原字符串两侧空白,仅替换中间有效内容。 */
+/** Keep whitespace on both sides of the original string, and replace only the effective content in the middle. */
function preserveOuterWhitespace(value: string, transform: (content: string) => string): string {
const leading = value.match(/^\s*/)?.[0] ?? '';
const trailing = value.match(/\s*$/)?.[0] ?? '';
return `${leading}${transform(value.slice(leading.length, value.length - trailing.length))}${trailing}`;
}
-/** 生成 remark-math 可识别的块级公式。 */
+/** Build a block formula that remark-math can recognize. */
function wrapDisplayMath(value: string): string {
return `$$\n${value.trim()}\n$$`;
}
-/** 排除 Markdown 表格行,同时允许 `|x|` 这类绝对值公式。 */
+/** Exclude Markdown table rows, while still allowing absolute-value formulas such as `|x|`. */
function isMarkdownTableRow(value: string): boolean {
return /^\s*\|.*\|\s*$/.test(value) && (value.match(/\|/g)?.length ?? 0) >= 3;
}
-/** 排除日期等外形类似算式的常见非数学字面量。 */
+/** Exclude common non-math literals, such as dates, that look like expressions. */
function isCommonNonMathLiteral(value: string): boolean {
return /^\d{4}-\d{1,2}-\d{1,2}$/.test(value) || /^\d{1,2}:\d{2}(?::\d{2})?$/.test(value);
}
/**
- * 排除联网搜索的引用角标,它长得像下标但不是公式。
+ * Exclude web-search citation markers. They look like subscripts but are not formulas.
*
- * 提示词要求模型在论断后紧跟 `[ref_N]`,多来源时模型还会合写成 `[ref_3, ref_5]`。这类角标
- * 会把裸数学识别的每一道判据都恰好走通:`_` 命中 hasScript,`ref` 只有三个字母、过得了
- * allIdentifiersShortOrMath,KaTeX 又能把 `ref_1` 当下标解析成功。于是 wrapBracketedMath
- * 把方括号当成公式定界符吃掉,正文里只剩一个斜体下标——角标没了,来源也没了。
+ * The prompt requires the model to follow a claim with `[ref_N]`, and for several sources the model also groups them as `[ref_3, ref_5]`. These markers
+ * happen to pass every bare-math check: `_` hits hasScript, `ref` is only three letters and passes
+ * allIdentifiersShortOrMath, and KaTeX can parse `ref_1` as a subscript. wrapBracketedMath then
+ * eats the brackets as formula delimiters, and the body is left with one italic subscript — the marker is gone, and so is the source.
*
- * 角标能否改写成链接取决于来源是否已到达(见 citationMarkers),流式途中、编号查不到来源、
- * 或思考文本里没有来源可查时,它都会以裸文本形态走到这里。改写与否是另一回事,但它在任何
- * 情况下都不是公式,所以这道护栏留在数学侧兜底,不依赖上游是否改写成功。
+ * Whether a marker can be rewritten into a link depends on whether the source has arrived (see citationMarkers). Mid-stream, when the number cannot find a source,
+ * or when reasoning text has no source to look up, it arrives here as bare text. Whether it was rewritten is a separate question, but it is never
+ * a formula, so this guard stays on the math side as a fallback and does not depend on the upstream rewrite succeeding.
*/
function isCitationMarker(value: string): boolean {
- // 允许可选的外层方括号:wrapBracketedMath 传进来的是括号内的 body,而独占一行时整行仍带括号。
+ // Allow an optional outer pair of brackets: wrapBracketedMath is given the body inside the brackets, while a line on its own still carries the brackets.
return /^\[?\s*ref_\d{1,3}(?:\s*[,,、;;]\s*ref_\d{1,3})*\s*\]?$/.test(value);
}
-/** 判断当前位置字符是否被奇数个反斜杠转义。 */
+/** Whether the character at the current position is escaped by an odd number of backslashes. */
function isEscaped(value: string, index: number): boolean {
let slashes = 0;
for (let cursor = index - 1; cursor >= 0 && value[cursor] === '\\'; cursor -= 1) slashes += 1;
diff --git a/webdemo/frontend/src/pages/playground/utils/math-markdown.ts b/webdemo/frontend/src/pages/playground/utils/math-markdown.ts
index 6db79b6..f2e9e73 100644
--- a/webdemo/frontend/src/pages/playground/utils/math-markdown.ts
+++ b/webdemo/frontend/src/pages/playground/utils/math-markdown.ts
@@ -1,7 +1,7 @@
/**
- * Markdown 数学规范化的保护性切片。
+ * Protective slices for Markdown math normalization.
*
- * 用途:识别已有美元符公式、围栏代码、缩进代码和行内代码,供数学规范化器跳过这些区域。
+ * Purpose: recognize existing dollar-sign formulas, fenced code, indented code, and inline code, so the math normalizer skips those regions.
*/
export interface ProtectedTextSegment {
@@ -11,8 +11,8 @@ export interface ProtectedTextSegment {
}
/**
- * KaTeX 不接受 `\bigg{[}` 这种把定界符再包一层花括号的写法,
- * 等价形式是 `\bigg[`。只改尺寸命令后面的定界符,代码区保持原样。
+ * KaTeX does not accept a form such as `\bigg{[}` that wraps the delimiter in another pair of braces;
+ * the equivalent form is `\bigg[`. Only change the delimiter after a sizing command, and leave code regions as-is.
*/
export function unwrapSizedDelimiters(text: string): string {
return splitMarkdownCode(text)
@@ -20,7 +20,7 @@ export function unwrapSizedDelimiters(text: string): string {
.join('');
}
-/** 去掉 `\big`、`\left` 等命令后多余的定界符花括号。 */
+/** Remove extra delimiter braces after commands such as `\big` and `\left`. */
function unwrapSizedDelimiterRun(text: string): string {
return text.replace(
/\\(Biggl|Biggr|biggl|biggr|Bigl|Bigr|bigl|bigr|Bigg|bigg|Big|big|left|right|middle)\{\s*(\\[{}|]|\\(?:lVert|rVert|lvert|rvert|langle|rangle|lfloor|rfloor|lceil|rceil|vert|Vert|uparrow|downarrow|updownarrow|Uparrow|Downarrow|Updownarrow|backslash)|[()[\]|./])\s*\}/g,
@@ -29,8 +29,8 @@ function unwrapSizedDelimiterRun(text: string): string {
}
/**
- * 把粘在同一处的多段 `$$...$$` 拆成各自独立的显示公式。
- * 单个公式保持原样;代码区不参与拆分。
+ * Split several `$$...$$` segments stuck together into independent display formulas.
+ * A single formula stays as-is; code regions do not take part in the split.
*/
export function splitJoinedDisplayFormulas(text: string): string {
return splitMarkdownCode(text)
@@ -40,7 +40,7 @@ export function splitJoinedDisplayFormulas(text: string): string {
.join('');
}
-/** 在一段不含代码的正文里拆开仅由空白相连的显示公式。 */
+/** Inside a stretch of body text that contains no code, split display formulas that are joined only by whitespace. */
function splitJoinedDisplayFormulaRun(text: string): string {
let output = '';
let cursor = 0;
@@ -84,7 +84,7 @@ function splitJoinedDisplayFormulaRun(text: string): string {
return output;
}
-/** 让拆开后的第一段公式从行首开始,避免 ` $$` 仍被当成普通段落。 */
+/** Make the first formula after a split start at the beginning of the line, so ` $$` is not still treated as an ordinary paragraph. */
function displayFormulaPrefix(prefix: string): string {
if (prefix.endsWith('\n')) return prefix;
const stripped = prefix.replace(/\s*$/, '');
@@ -92,7 +92,7 @@ function displayFormulaPrefix(prefix: string): string {
return prefix;
}
-/** 查找下一个未转义的双美元符。 */
+/** Find the next unescaped double dollar sign. */
function indexOfUnescapedMarker(text: string, marker: string, from: number): number {
for (let index = from; index <= text.length - marker.length; index += 1) {
if (text.startsWith(marker, index) && !isEscaped(text, index)) return index;
@@ -100,7 +100,7 @@ function indexOfUnescapedMarker(text: string, marker: string, from: number): num
return -1;
}
-/** 把已有 `$...$` / `$$...$$` 切成保护片段,防止重复补定界符。 */
+/** Slice existing `$...$` / `$$...$$` into protected fragments, so delimiters are not added twice. */
export function splitDollarMath(text: string): ProtectedTextSegment[] {
const segments: ProtectedTextSegment[] = [];
let plainStart = 0;
@@ -110,7 +110,7 @@ export function splitDollarMath(text: string): ProtectedTextSegment[] {
cursor += 1;
continue;
}
- // 单美元符必须自成一段,不能借用 `$$` 围栏里的某个字符充作闭合符。
+ // A single dollar sign must be its own segment, and must not borrow a character inside a `$$` fence as its closer.
const marker = countRun(text, cursor, '$') === 1 ? '$' : '$$';
const close = findDollarClose(text, cursor + marker.length, marker);
if (close < 0) {
@@ -129,7 +129,7 @@ export function splitDollarMath(text: string): ProtectedTextSegment[] {
return segments;
}
-/** 将 Markdown 围栏代码块、缩进代码块与行内代码切成保护片段。 */
+/** Slice Markdown fenced code blocks, indented code blocks, and inline code into protected fragments. */
export function splitMarkdownCode(text: string): ProtectedTextSegment[] {
const segments: ProtectedTextSegment[] = [];
let plainStart = 0;
@@ -180,10 +180,10 @@ export function splitMarkdownCode(text: string): ProtectedTextSegment[] {
}
/**
- * 把模型误用反引号包裹的明确数学表达式转换为行内公式。
+ * Turn an explicit math expression the model wrapped in backticks by mistake into an inline formula.
*
- * 调用方负责完整数学语法校验;本层额外要求命令、Unicode 数学符号或至少两类数学结构,
- * 使普通路径、命令、单变量与代码仍保留 Markdown 代码语义。
+ * The caller is responsible for a full math-syntax check; this layer additionally requires a command, a Unicode math symbol, or at least two kinds of math structure,
+ * so an ordinary path, command, single variable, and code still keep Markdown code semantics.
*/
export function normalizeInlineCodeMath(
codeSpan: string,
@@ -197,10 +197,10 @@ export function normalizeInlineCodeMath(
}
/**
- * 把普通文本中 `[ LaTeX ]` 形式的模型输出转换为行内公式。
+ * Turn model output of the form `[ LaTeX ]` in ordinary text into an inline formula.
*
- * 方括号可出现在列表或说明文字内部,不能依赖整行裸公式判断;仅当括号内容通过调用方
- * 的数学校验时转换,并排除 Markdown 链接、图片、任务列表和普通引用编号。
+ * Brackets can appear inside a list or explanatory text, so this cannot rely on a whole-line bare-formula check; convert only when the bracket contents pass the caller's
+ * math check, and exclude Markdown links, images, task lists, and ordinary citation numbers.
*/
export function wrapBracketedMath(text: string, isMath: (value: string) => boolean): string {
let cursor = 0;
@@ -222,8 +222,8 @@ export function wrapBracketedMath(text: string, isMath: (value: string) => boole
}
/**
- * 检测 Markdown 星号强调,避免把 `**标题**` / `*标签*` 的星号当成数学乘法。
- * 仅匹配符合 Markdown 边界的强调写法,不影响 `a*b*c` 等紧邻变量的乘法表达式。
+ * Detect Markdown asterisk emphasis, so the asterisks of `**title**` / `*label*` are not treated as math multiplication.
+ * Match only emphasis that fits Markdown boundaries, and do not affect multiplication such as `a*b*c` between adjacent variables.
*/
export function hasMarkdownAsteriskEmphasis(value: string): boolean {
return (
@@ -232,7 +232,7 @@ export function hasMarkdownAsteriskEmphasis(value: string): boolean {
);
}
-/** 对行内代码采用比独占行更严格的数学结构判定,降低代码误转公式的风险。 */
+/** Use a stricter math-structure check for inline code than for a line on its own, so code is less likely to be turned into a formula by mistake. */
function isLikelyInlineCodeMath(value: string, isMath: (value: string) => boolean): boolean {
if (!isMath(value)) return false;
if (/\\[A-Za-z@]+/.test(value)) return true;
@@ -247,7 +247,7 @@ function isLikelyInlineCodeMath(value: string, isMath: (value: string) => boolea
return structures.filter(Boolean).length >= 2;
}
-/** 查找美元符数学片段的闭合定界符;行内公式不跨行。 */
+/** Find the closing delimiter of a dollar-sign math fragment; an inline formula does not cross lines. */
function findDollarClose(text: string, from: number, marker: '$' | '$$'): number {
for (let cursor = from; cursor < text.length; cursor += 1) {
if (marker === '$' && text[cursor] === '\n') return -1;
@@ -258,7 +258,7 @@ function findDollarClose(text: string, from: number, marker: '$' | '$$'): number
return -1;
}
-/** 查找未被反斜杠转义的指定字符。 */
+/** Find the given character when it is not escaped by a backslash. */
function findNextUnescaped(text: string, character: string, from: number): number {
for (let index = from; index < text.length; index += 1) {
if (text[index] === character && !isEscaped(text, index)) return index;
@@ -266,7 +266,7 @@ function findNextUnescaped(text: string, character: string, from: number): numbe
return -1;
}
-/** 查找支持嵌套的右方括号,兼容公式内的 `\left[...\right]` 与根式可选参数。 */
+/** Find a right bracket that supports nesting, compatible with `\left[...\right]` inside a formula and optional radical arguments. */
function findClosingSquareBracket(text: string, open: number): number {
let depth = 0;
for (let index = open; index < text.length; index += 1) {
@@ -278,12 +278,12 @@ function findClosingSquareBracket(text: string, open: number): number {
return -1;
}
-/** 判断当前行是否为 Markdown 四空格或 Tab 缩进代码行。 */
+/** Whether the current line is a Markdown indented code line of four spaces or a tab. */
function isIndentedCodeLine(text: string, lineStart: number): boolean {
return text.startsWith(' ', lineStart) || text[lineStart] === '\t';
}
-/** 保护连续的 Markdown 缩进代码块;块内空行一并保留。 */
+/** Protect a contiguous Markdown indented code block; blank lines inside the block are kept too. */
function findIndentedCodeEnd(text: string, from: number): number {
let lineStart = from;
while (lineStart < text.length) {
@@ -296,7 +296,7 @@ function findIndentedCodeEnd(text: string, from: number): number {
return text.length;
}
-/** 读取 Markdown 围栏起始行。 */
+/** Read the opening line of a Markdown fence. */
function readFenceStart(
text: string,
lineStart: number,
@@ -317,7 +317,7 @@ function readFenceStart(
};
}
-/** 查找 Markdown 围栏闭合行;未闭合时保护到文本结尾。 */
+/** Find the Markdown fence closing line; when it is unclosed, protect through the end of the text. */
function findFenceEnd(
text: string,
from: number,
@@ -344,14 +344,14 @@ function findFenceEnd(
return text.length;
}
-/** 计算相同字符的连续长度。 */
+/** Count the run length of the same character. */
function countRun(text: string, from: number, character: string): number {
let cursor = from;
while (text[cursor] === character) cursor += 1;
return cursor - from;
}
-/** 判断当前位置字符是否被奇数个反斜杠转义。 */
+/** Whether the character at the current position is escaped by an odd number of backslashes. */
function isEscaped(value: string, index: number): boolean {
let slashes = 0;
for (let cursor = index - 1; cursor >= 0 && value[cursor] === '\\'; cursor -= 1) slashes += 1;
diff --git a/webdemo/frontend/src/pages/playground/utils/math-native.ts b/webdemo/frontend/src/pages/playground/utils/math-native.ts
index e618071..3082dd4 100644
--- a/webdemo/frontend/src/pages/playground/utils/math-native.ts
+++ b/webdemo/frontend/src/pages/playground/utils/math-native.ts
@@ -5,14 +5,14 @@ interface NativeMathOptions {
}
/**
- * 选择比正文美元符更长的行内围栏,避免 remark 与编辑器截断 LaTeX 正文。
- * @param latex 不包含外层定界符的公式
- * @returns 安全的 Markdown 行内公式;不含美元符时保持标准单美元符
+ * Choose an inline fence longer than dollar signs in the body, so remark and the editor do not truncate LaTeX body text.
+ * @param latex formula without the outer delimiters
+ * @returns a safe Markdown inline formula; when it contains no dollar sign, keep the standard single dollar sign
*/
export function inlineMathMarkdown(latex: string): string {
const runs = latex.match(/\$+/g) ?? [];
const length = runs.reduce((maximum, run) => Math.max(maximum, run.length + 1), 1);
- // 双美元符由编辑器块级 tokenizer 所有;含美元符的行内公式使用至少三个。
+ // Double dollar signs belong to the editor's block tokenizer; an inline formula that contains a dollar sign uses at least three.
const marker = '$'.repeat(length === 1 ? 1 : Math.max(3, length));
return marker + latex + marker;
}
@@ -24,7 +24,7 @@ interface NativeMathRange {
display: boolean;
}
-/** 跳过 verb 的逐字正文,避免其中的定界符提前结束外层公式。 */
+/** Skip the verbatim body of verb, so a delimiter inside it does not end the outer formula early. */
function verbEnd(text: string, start: number): number | undefined {
const command = text.slice(start, start + 7).match(/^\\verb\*?([^A-Za-z\s])/);
if (!command) return undefined;
@@ -33,7 +33,7 @@ function verbEnd(text: string, start: number): number | undefined {
return close < 0 ? text.length : close + 1;
}
-/** 查找外层闭合标记;成对反斜杠和 verb 正文不参与定界符匹配。 */
+/** Find the outer closing marker; paired backslashes and verb body text do not take part in delimiter matching. */
function nativeMathEnd(text: string, from: number, closing: string): number {
let cursor = from;
while (cursor < text.length) {
@@ -53,10 +53,10 @@ function nativeMathEnd(text: string, from: number, closing: string): number {
}
/**
- * 单次扫描原生公式边界,不重写 LaTeX 正文或已有数学/代码范围。
- * @param text 尚未转换原生定界符的文字
- * @param protectedRanges 按源码顺序的保护范围
- * @returns 完整原生公式的源码范围与原始正文;不包含未闭合公式
+ * Scan native-formula boundaries once, without rewriting LaTeX body text or existing math/code ranges.
+ * @param text text whose native delimiters have not been converted yet
+ * @param protectedRanges protected ranges in source order
+ * @returns source ranges and original body of complete native formulas; unclosed formulas are not included
*/
export function nativeMathRanges(
text: string,
@@ -82,7 +82,7 @@ export function nativeMathRanges(
continue;
}
const close = nativeMathEnd(text, cursor + 2, opening === '(' ? ')' : ']');
- // 未闭合时停止扫描,避免大量起始标记反复搜索同一段剩余文本。
+ // When one is unclosed, stop scanning, so a large number of opening markers do not search the same remainder over and over.
if (close < 0) break;
if (close === cursor + 2) {
cursor = close + 2;
@@ -100,10 +100,10 @@ export function nativeMathRanges(
}
/**
- * 将原生公式外层标记转换为 Markdown 定界符,保留公式正文。
- * @param text 原始 Markdown 文本
- * @param options 保护范围与行内边界回调
- * @returns 供 remark-math 使用的文本
+ * Convert the outer markers of a native formula to Markdown delimiters, keeping the formula body.
+ * @param text original Markdown text
+ * @param options protected ranges and the inline-boundary callback
+ * @returns text for remark-math
*/
export function replaceNativeMathDelimiters(
text: string,
diff --git a/webdemo/frontend/src/pages/playground/utils/math-options.ts b/webdemo/frontend/src/pages/playground/utils/math-options.ts
index a78f92b..c49d8d3 100644
--- a/webdemo/frontend/src/pages/playground/utils/math-options.ts
+++ b/webdemo/frontend/src/pages/playground/utils/math-options.ts
@@ -1,12 +1,12 @@
/**
- * KaTeX 统一安全与资源限制。
+ * Unified KaTeX safety and resource limits.
*
- * 用途:裸公式校验和最终 DOM 渲染共用同一套限制,避免模型内容触发外部资源或异常尺寸。
+ * Purpose: bare-formula checks and the final DOM render share the same limits, so model content cannot trigger external resources or an abnormal size.
*/
import type { KatexOptions } from 'katex';
-/** 不信任模型输入,并限制宏展开次数与可生成的最大尺寸。 */
+/** Do not trust model input, and limit macro expansion count and the maximum size that can be generated. */
export const SAFE_KATEX_OPTIONS = {
maxExpand: 1_000,
maxSize: 50,
diff --git a/webdemo/frontend/src/pages/playground/utils/math.ts b/webdemo/frontend/src/pages/playground/utils/math.ts
index 6c07576..c5a21ea 100644
--- a/webdemo/frontend/src/pages/playground/utils/math.ts
+++ b/webdemo/frontend/src/pages/playground/utils/math.ts
@@ -1,9 +1,9 @@
/**
- * 数学公式定界符规范化。
+ * Math-formula delimiter normalization.
*
- * 用途:兼容模型输出的 `$...$`、`$$...$$`、`\(...\)`、`\[...\]`、裸 LaTeX
- * 以及无命令的独占行数学表达式。KaTeX 负责判断具体命令和环境是否受支持,MAP 不维护语法白名单。
- * Markdown 代码区和已有公式保持原样,避免把代码、金额、表格或普通说明文字误判为公式。
+ * Purpose: accept model output of `$...$`, `$$...$$`, `\(...\)`, `\[...\]`, bare LaTeX,
+ * and math expressions that occupy a line with no command. KaTeX decides whether a specific command or environment is supported; MAP does not keep a syntax allowlist.
+ * Markdown code regions and existing formulas stay as-is, so code, amounts, tables, or ordinary explanatory text are not mistaken for formulas.
*/
import { unified } from 'unified';
@@ -21,7 +21,7 @@ import {
import { inlineMathMarkdown, nativeMathRanges, replaceNativeMathDelimiters } from './math-native';
interface NormalizeMathDelimitersOptions {
- /** 是否识别并补齐模型未显式标记的数学表达式。 */
+ /** Whether to recognize and complete math expressions the model did not mark explicitly. */
detectBareMath?: boolean;
}
@@ -47,10 +47,10 @@ interface DisplayFenceRepair {
deletionEnd: number;
}
-/** 行尾 `$ $$`:OCR 偶发把块级公式开头的 `$$` 与一个多余的 `$` 混写在同一行。 */
+/** A trailing `$ $$`: OCR occasionally writes the opening `$$` of a block formula and an extra `$` on the same line. */
const STRAY_DISPLAY_FENCE = /(^|\n)([^\n$]*)\$[ \t]*\$\$(?=[ \t]*(?:\r?\n|$))/g;
-/** 原生公式应在正文内美元符切片之前识别,同时跳过已有美元符公式。 */
+/** Native formulas should be recognized before dollar-sign slices inside the body, and existing dollar-sign formulas are skipped. */
function dollarRanges(text: string) {
let cursor = 0;
return splitDollarMath(text).flatMap((segment) => {
@@ -60,7 +60,7 @@ function dollarRanges(text: string) {
});
}
-/** 原始 HTML 交由 DOM 公式转换,避免提前规范化属性、代码及单元格内美元符正文。 */
+/** Raw HTML is left to the DOM formula transform, so attributes, code, and dollar-sign body text inside cells are not normalized early. */
function splitDocumentHtml(content: string): ProtectedTextSegment[] {
if (!content.includes('<')) return splitMarkdownCode(content);
const tree = DOCUMENT_PARSER.parse(content);
@@ -91,11 +91,11 @@ function splitDocumentHtml(content: string): ProtectedTextSegment[] {
}
/**
- * 找出可安全修复的 `prefix$ $$` 残片。
+ * Find a `prefix$ $$` fragment that can be repaired safely.
*
- * 只有整行前缀本身能通过裸公式校验时才修复,避免把金额、代码或说明文字并进公式。
- * `$ $$` 后面的 `$$` 必须已被识别为成对公式;修复时删除多余的 `$` 与原 `$$` 开头,
- * 并在行首补回 `$$`。
+ * Repair only when the whole-line prefix itself passes the bare-formula check, so amounts, code, or explanatory text are not pulled into the formula.
+ * The `$$` after `$ $$` must already have been recognized as a paired formula; the repair deletes the extra `$` and the original `$$` opening,
+ * and puts `$$` back at the start of the line.
*/
function displayFenceRepairs(
text: string,
@@ -108,7 +108,7 @@ function displayFenceRepairs(
const lineStart = match.index + match[1].length;
const prefix = match[2];
if (!isBareMath(prefix.trim())) continue;
- // 多行公式正文里也可能出现 `$`,不能把公式内部误当成 OCR 残片。
+ // A `$` can also appear inside a multi-line formula body, and must not be mistaken for an OCR fragment inside the formula.
if (protectedRanges.some((range) => range.start < lineStart && range.end > lineStart)) {
continue;
}
@@ -121,9 +121,9 @@ function displayFenceRepairs(
}
/**
- * 应用文本编辑,并保留原始偏移到规范化文本的单调映射。
+ * Apply a text edit, and keep a monotonic map from original offsets to the normalized text.
*
- * 删除区间内部的偏移统一落到替换内容末尾;块级高亮只需要稳定落在同一语义块内。
+ * Offsets inside a deleted range all land at the end of the replacement; block highlighting only needs to land stably inside the same semantic block.
*/
function applyTextEdits(text: string, edits: readonly MathTextEdit[]) {
const sorted = [...edits].sort((left, right) => left.start - right.start || left.end - right.end);
@@ -184,7 +184,7 @@ function applyTextEdits(text: string, edits: readonly MathTextEdit[]) {
return { content: output, mapOffset };
}
-/** 文档预览只修复公式定界符,不推断裸 LaTeX;裸公式识别由对话场景单独控制。 */
+/** Document preview only repairs formula delimiters and does not infer bare LaTeX; bare-formula recognition is controlled separately by the chat scene. */
function documentMathEdits(
text: string,
protectedRanges: readonly { start: number; end: number }[],
@@ -213,9 +213,9 @@ function documentMathEdits(
}
/**
- * 文档公式规范化同时记录分段偏移映射,避免每个 OCR 块重复扫描整段前缀。
- * @param content 原始 Markdown;代码与已有美元符公式保持原样
- * @returns 规范化文本与原始边界到预览边界的二分映射
+ * Document formula normalization also records a segmented offset map, so each OCR block does not rescan the whole prefix.
+ * @param content original Markdown; code and existing dollar-sign formulas stay as-is
+ * @returns normalized text and a binary map from original boundaries to preview boundaries
*/
export function normalizeDocumentMathDelimiters(content: string) {
const mappings: {
@@ -271,10 +271,10 @@ export function normalizeDocumentMathDelimiters(content: string) {
}
/**
- * 文档预览的完整公式规范化。
+ * Full formula normalization for document preview.
*
- * 先拆开 `\] \[` 收成的粘连 `$$ $$`,再修定界符。没有这些改写时沿用一次扫描的偏移;
- * 拆开后按前缀长度对齐,和原先文档渲染走 `normalizeMathDelimiters` 的结果一致。
+ * First split a stuck-together `$$ $$` that `\] \[` collapsed into, then repair delimiters. When there is no such rewrite, keep the offsets from one scan;
+ * after the split, align by prefix length, consistent with the previous document render going through `normalizeMathDelimiters`.
*/
export function prepareDocumentMath(content: string) {
const prepared = splitJoinedDisplayFormulas(unwrapSizedDelimiters(content));
@@ -290,11 +290,11 @@ export function prepareDocumentMath(content: string) {
}
/**
- * 规范化模型输出中的数学公式,跳过 Markdown 代码区。
+ * Normalize math formulas in model output, skipping Markdown code regions.
*
- * @param content 原始 Markdown 文本
- * @param options 数学识别选项
- * @returns 可交给 remark-math 与 KaTeX 渲染的 Markdown
+ * @param content original Markdown text
+ * @param options math recognition options
+ * @returns Markdown that can be handed to remark-math and KaTeX
*/
export function normalizeMathDelimiters(
content: string,
diff --git a/webdemo/frontend/src/pages/playground/utils/messageVersions.ts b/webdemo/frontend/src/pages/playground/utils/messageVersions.ts
index 8fd3e51..d7df752 100644
--- a/webdemo/frontend/src/pages/playground/utils/messageVersions.ts
+++ b/webdemo/frontend/src/pages/playground/utils/messageVersions.ts
@@ -1,23 +1,23 @@
/**
- * Playground 多版本回答与反馈态纯函数。
+ * Pure functions for Playground multi-version answers and feedback state.
*
- * 用途:维护「顶层字段镜像 versions[activeVersion]」不变式;regenerate 准备态、反馈切换、版本翻页。
+ * Purpose: keep the invariant "top-level fields mirror versions[activeVersion]"; regenerate preparing state, feedback toggle, and version paging.
*/
import type { ChatMessage, MessageFeedback } from '../types';
import { applyVersion, snapshotVersion } from './messages';
-/** regenerate 所需的上下文:assistant 之前的可发送历史 + 目标消息 */
+/** Context regenerate needs: sendable history before the assistant, plus the target message */
export interface RegenerateContext {
base: ChatMessage[];
target: ChatMessage;
}
/**
- * 解析重新生成上下文:目标 assistant 之前的消息须含至少一条可发送 user 轮次。
- * @param messages 当前消息列表
- * @param assistantId 目标 assistant id
- * @returns 上下文或 null(找不到 / 不可发送时)
+ * Resolve regenerate context: messages before the target assistant must include at least one sendable user turn.
+ * @param messages current message list
+ * @param assistantId target assistant id
+ * @returns the context, or null (not found / not sendable)
*/
export function findRegenerateContext(
messages: ChatMessage[],
@@ -31,8 +31,8 @@ export function findRegenerateContext(
}
/**
- * 构造重新生成前的 assistant 消息:保留 versions,清空 live 字段,标 streaming。
- * @param target 当前 assistant 消息
+ * Build the assistant message before regenerate: keep versions, clear live fields, and mark streaming.
+ * @param target current assistant message
*/
export function prepareRegenerateMessage(target: ChatMessage): ChatMessage {
const existingVersions = (
@@ -66,10 +66,10 @@ export function prepareRegenerateMessage(target: ChatMessage): ChatMessage {
}
/**
- * 在列表中替换目标 assistant 为重新生成准备态。
- * @param list 当前消息列表
- * @param assistantId 目标 id
- * @param prepared prepareRegenerateMessage 的结果
+ * Replace the target assistant in the list with the regenerate preparing state.
+ * @param list current message list
+ * @param assistantId target id
+ * @param prepared result of prepareRegenerateMessage
*/
export function applyRegeneratePrep(
list: ChatMessage[],
@@ -80,9 +80,9 @@ export function applyRegeneratePrep(
}
/**
- * 切换单条消息的反馈态(赞/踩互斥,再次点击同项取消),并同步进当前选中版本。
- * @param message 目标 assistant 消息
- * @param kind 赞或踩
+ * Toggle feedback on a single message (like/dislike are exclusive; clicking the same one again clears it), and sync it into the currently selected version.
+ * @param message target assistant message
+ * @param kind like or dislike
*/
export function toggleFeedbackOnMessage(message: ChatMessage, kind: MessageFeedback): ChatMessage {
const next = message.feedback === kind ? undefined : kind;
@@ -94,10 +94,10 @@ export function toggleFeedbackOnMessage(message: ChatMessage, kind: MessageFeedb
}
/**
- * 在列表中切换指定 assistant 的反馈态。
- * @param list 当前消息列表
- * @param assistantId 目标 id
- * @param kind 赞或踩
+ * Toggle feedback for a given assistant in the list.
+ * @param list current message list
+ * @param assistantId target id
+ * @param kind like or dislike
*/
export function applyFeedbackToggle(
list: ChatMessage[],
@@ -108,10 +108,10 @@ export function applyFeedbackToggle(
}
/**
- * 在列表中把指定 assistant 切换到某个显示版本(‹n/N› 翻页)。
- * @param list 当前消息列表
- * @param assistantId 目标 id
- * @param index 版本索引
+ * Switch a given assistant in the list to a display version (‹n/N› paging).
+ * @param list current message list
+ * @param assistantId target id
+ * @param index version index
*/
export function applyActiveVersionSwitch(
list: ChatMessage[],
diff --git a/webdemo/frontend/src/pages/playground/utils/messages.ts b/webdemo/frontend/src/pages/playground/utils/messages.ts
index c8a9e52..48ae889 100644
--- a/webdemo/frontend/src/pages/playground/utils/messages.ts
+++ b/webdemo/frontend/src/pages/playground/utils/messages.ts
@@ -1,7 +1,7 @@
/**
- * 对话消息构造与增量合并纯函数。
+ * Pure functions that build conversation messages and merge increments.
*
- * 用途:把 useChat 的消息状态变换收敛为无副作用纯函数,便于复用与单测。
+ * Purpose: collapse useChat message-state transforms into side-effect-free pure functions, so they can be reused and unit tested.
*/
import type { AnswerVersion, ChatMessage, ChatRole, Citation } from '../types';
@@ -12,28 +12,28 @@ import { buildContextWindowPlan, type ContextWindowOptions } from './contextBudg
import { normalizeAssistantReply } from './thinkSplit';
/**
- * 上下文分隔线的存储标记。
- * 分隔线在前端以 `divider:true` 标识;持久化时无独立字段,借用 role='system' + 本标记往返,
- * 加载时据此还原 divider 标记(见 conversations.ts)。
+ * Storage marker for a context divider.
+ * On the frontend a divider is identified by `divider:true`; persistence has no separate field, so it round-trips as role='system' plus this marker,
+ * and on load the divider flag is restored from that (see conversations.ts).
*/
export const CONTEXT_DIVIDER_MARKER = '[[map:context-cleared]]';
-/** 生成一个轻量唯一 id(无需 crypto,足够前端去重/key 使用) */
+/** Generate a lightweight unique id (no crypto needed; enough for frontend dedupe and keys) */
export function genId(seed: number): string {
return `m_${seed.toString(36)}_${(seed % 1000).toString(36)}`;
}
-/** 构造一条上下文分隔线消息(role=system 以便默认不参与请求,content 用标记以便持久化往返) */
+/** Build a context-divider message (role=system so it stays out of the request by default; content uses a marker so it can round-trip through persistence) */
export function makeDivider(id: string): ChatMessage {
return { id, role: 'system', content: CONTEXT_DIVIDER_MARKER, divider: true };
}
/**
- * 构造一条消息。
- * @param id 唯一 id
- * @param role 角色
- * @param content 正文
- * @param extra 额外字段(streaming/reasoning 等)
+ * Build one message.
+ * @param id unique id
+ * @param role role
+ * @param content body
+ * @param extra extra fields (streaming, reasoning, and so on)
*/
export function makeMessage(
id: string,
@@ -45,11 +45,11 @@ export function makeMessage(
}
/**
- * 把流式增量并入消息列表中指定 id 的消息(函数式更新,不可变)。
+ * Merge a streaming increment into the message with the given id (functional update, immutable).
*
- * @param list 当前消息列表
- * @param id 目标 assistant 消息 id
- * @param patch 要合并/追加的内容(content/reasoning 为追加,其余字段为覆盖)
+ * @param list current message list
+ * @param id target assistant message id
+ * @param patch content to merge or append (content and reasoning are appended; other fields overwrite)
*/
export function appendToMessage(
list: ChatMessage[],
@@ -68,7 +68,7 @@ export function appendToMessage(
const next: ChatMessage = { ...m };
if (patch.contentDelta) next.content = m.content + patch.contentDelta;
if (patch.reasoningDelta) next.reasoning = (m.reasoning ?? '') + patch.reasoningDelta;
- // 引用来源按 url 去重合并(流式下可能多帧携带同一来源)
+ // Citation sources are merged and deduped by url (streaming may carry the same source on several frames)
if (patch.citationsDelta && patch.citationsDelta.length) {
next.citations = mergeCitations(m.citations, patch.citationsDelta);
}
@@ -92,7 +92,7 @@ export function appendToMessage(
if (patch.requestId !== undefined) next.requestId = patch.requestId;
if (patch.clientRequestId !== undefined) next.clientRequestId = patch.clientRequestId;
if (patch.apiKeyId !== undefined) next.apiKeyId = patch.apiKeyId;
- // metrics 为增量合并:保留已有字段,仅覆盖本次提供的(首 token 与总耗时分两次到达)
+ // metrics are merged incrementally: keep existing fields, and overwrite only what this update provides (time to first token and total elapsed arrive separately)
if (patch.metrics !== undefined) next.metrics = { ...m.metrics, ...patch.metrics };
if (patch.error !== undefined) next.error = patch.error;
return next;
@@ -100,15 +100,15 @@ export function appendToMessage(
}
/**
- * 合并引用来源并去重;保持首次顺序,同时保留后续工具返回的更完整元数据。
+ * Merge citation sources and dedupe them; keep first-seen order, and keep the fuller metadata a later tool returns.
*
- * 身份优先取后端编号 ref:它跨轮跨工具与 URL 一一绑定,比任何前端归一化都准。
- * 没有 ref(老后端)时退回 citationURLKey——此前这里用的是裸 url,与别处(角标匹配、
- * 来源面板高亮)用的归一化键不是一套口径,差一个末尾斜杠就会多出一条重复来源。
+ * Identity prefers the backend number ref: it is bound one-to-one with the URL across turns and tools, and is more accurate than any frontend normalization.
+ * When there is no ref (an old backend), fall back to citationURLKey — this used to be the raw url, a different measure from elsewhere (marker matching,
+ * source-panel highlight). One trailing slash would then produce an extra duplicate source.
*
- * @param prev 已累积的来源
- * @param incoming 本次事件带来的来源
- * @returns 合并后的来源列表;全部带 ref 时按 ref 升序,保证列表序号连续
+ * @param prev sources already accumulated
+ * @param incoming sources brought by this event
+ * @returns the merged source list; when every item has a ref, sorted by ref ascending so list numbers stay contiguous
*/
export function mergeCitations(prev: Citation[] | undefined, incoming: Citation[]): Citation[] {
const merged = [...(prev ?? [])];
@@ -121,7 +121,7 @@ export function mergeCitations(prev: Citation[] | undefined, incoming: Citation[
const existing = merged[existingIndex];
merged[existingIndex] = {
...existing,
- // ref 回填:同一来源可能先由不带编号的通道到达,后续事件补上编号。
+ // ref backfill: the same source may arrive first on a channel with no number, and a later event fills the number in.
...(!existing.ref && c.ref ? { ref: c.ref } : {}),
...(!existing.title && c.title ? { title: c.title } : {}),
...(preferLongerText(existing.snippet, c.snippet) ? { snippet: c.snippet } : {}),
@@ -131,29 +131,29 @@ export function mergeCitations(prev: Citation[] | undefined, incoming: Citation[
indexByIdentity.set(citationIdentity(c), merged.length);
merged.push(c);
}
- // 全部带编号时按编号排序:来源面板展示的就是 ref,数组顺序与编号不一致会让列表读成 1,2,5,3。
- // 只差一条没编号就不排,避免把「无编号」的那条挤到一个它并不属于的位置。
+ // When every item has a number, sort by number: the source panel displays ref, and an array order that disagrees with the numbers would read as 1, 2, 5, 3.
+ // If even one item has no number, do not sort, so the "no number" item is not pushed into a position it does not belong to.
if (merged.length > 0 && merged.every((c) => Boolean(c.ref))) {
merged.sort((a, b) => (a.ref ?? 0) - (b.ref ?? 0));
}
return merged;
}
-/** 来源的去重身份:有后端编号用编号,否则用归一化 URL 键。 */
+/** Dedup identity of a source: use the backend number when present, otherwise the normalized URL key. */
function citationIdentity(citation: Citation): string {
return citation.ref ? `ref:${citation.ref}` : `url:${citationURLKey(citation.url)}`;
}
-/** 后续网页读取正文比搜索摘要更完整时,用更长文本补全预览。 */
+/** When a later page-read body is fuller than the search snippet, fill the preview with the longer text. */
function preferLongerText(current?: string, incoming?: string): incoming is string {
return Boolean(incoming && incoming.length > (current?.length ?? 0));
}
/**
- * 把本页消息历史转为后端请求所需的最小结构(仅 role + content,剔除空的流式占位)。
+ * Turn this page's message history into the minimum structure the backend request needs (role + content only, dropping empty streaming placeholders).
*
- * @param list 本页消息列表
- * @param systemPrompt 可选系统提示,置于最前
+ * @param list this page's message list
+ * @param systemPrompt optional system prompt, placed first
*/
export function toRequestMessages(
list: ChatMessage[],
@@ -167,7 +167,7 @@ export function toRequestMessages(
if (systemPrompt && systemPrompt.trim()) {
out.push({ role: 'system', content: systemPrompt.trim() });
}
- // 上下文截断:只取最后一条分隔线之后的消息(分隔线以上的历史不再作为上下文发送)
+ // Context truncation: take only messages after the last divider (history above the divider is no longer sent as context)
let lastDivider = -1;
for (let i = 0; i < list.length; i++) {
if (list[i]?.divider) lastDivider = i;
@@ -177,12 +177,12 @@ export function toRequestMessages(
if (m.contextExcluded) continue;
if (m.role === 'system') continue;
if (m.interrupted) continue;
- // 跳过尚无正文/附件的流式占位(最后一条 assistant 在 send 时才追加)
+ // Skip streaming placeholders that have no body or attachment yet (the last assistant is appended only at send time)
if (!m.content && !m.reasoning && !(m.attachments && m.attachments.length)) continue;
const normalized =
m.role === 'assistant' ? normalizeAssistantReply(m.content, m.reasoning) : undefined;
if (m.role === 'assistant' && !normalized?.content.trim()) continue;
- // 带附件的用户消息走多模态 content 数组(文本在前,附件按序在后);否则保持纯字符串
+ // A user message with attachments uses a multimodal content array (text first, then attachments in order); otherwise keep a plain string
if (m.role === 'user' && m.attachments && m.attachments.length) {
const parts: ChatRequestMessage['content'] = [];
if (m.content) parts.push({ type: 'text', text: m.content });
@@ -198,7 +198,7 @@ export function toRequestMessages(
return out;
}
-/** 取会话标题:首条用户消息前 20 字,缺省回退「新对话」 */
+/** Conversation title: the first 20 characters of the first user message, falling back to "New conversation" when absent */
export function deriveTitle(list: ChatMessage[]): string {
const firstUser = list.find((m) => m.role === 'user' && m.content.trim());
if (!firstUser) return '新对话';
@@ -207,12 +207,12 @@ export function deriveTitle(list: ChatMessage[]): string {
}
/**
- * 取某条 assistant 消息对应的「问答对」:向前找最近的用户提问,答为该条正文。
- * 用于反馈上报的内容快照。找不到(异常)时返回空串。
+ * Take the "question-answer pair" for one assistant message: look backward for the nearest user question, and the answer is that message's body.
+ * Used as the content snapshot for feedback reporting. Return empty strings when it cannot be found (an abnormal case).
*
- * @param list 消息列表
- * @param assistantId 目标 assistant 消息 id
- * @returns { question, answer } 文本快照
+ * @param list message list
+ * @param assistantId target assistant message id
+ * @returns { question, answer } text snapshot
*/
export function findQAPair(
list: ChatMessage[],
@@ -229,7 +229,7 @@ export function findQAPair(
const answer = list[ai].content;
let question = '';
for (let i = ai - 1; i >= 0; i--) {
- if (list[i].divider) break; // 越过分隔线不再上溯(上下文已清除)
+ if (list[i].divider) break; // Do not walk back past a divider (the context has been cleared)
if (list[i].role === 'user') {
question = list[i].content;
break;
@@ -244,7 +244,7 @@ export function findQAPair(
};
}
-/** 从消息顶层「live 字段」抽出一份版本快照(一轮回答完成时调用)。 */
+/** Pull a version snapshot out of the message's top-level "live fields" (called when one answer finishes). */
export function snapshotVersion(m: ChatMessage): AnswerVersion {
const normalized =
m.role === 'assistant' ? normalizeAssistantReply(m.content, m.reasoning) : undefined;
@@ -253,7 +253,7 @@ export function snapshotVersion(m: ChatMessage): AnswerVersion {
...((normalized?.reasoning ?? m.reasoning)
? { reasoning: normalized?.reasoning ?? m.reasoning }
: {}),
- // 联网过程字段:刷新后折叠区才能重绘工具步骤
+ // Web-search process fields: the disclosure needs them to redraw tool steps after refresh
...(m.searchStatus !== undefined ? { searchStatus: m.searchStatus } : {}),
...(m.searchStep ? { searchStep: m.searchStep } : {}),
...(m.searchResultCount !== undefined ? { searchResultCount: m.searchResultCount } : {}),
@@ -275,8 +275,8 @@ export function snapshotVersion(m: ChatMessage): AnswerVersion {
}
/**
- * 把指定版本的字段镜像回消息顶层(切换 ‹n/N› 或加载时调用),保持
- * 「顶层 == versions[activeVersion]」不变式。清掉未在该版本出现的可选字段避免残留。
+ * Mirror the given version's fields back onto the top level of the message (called when switching ‹n/N› or on load), keeping
+ * the invariant "top level == versions[activeVersion]". Clear optional fields that do not appear on that version so they do not linger.
*/
export function applyVersion(m: ChatMessage, index: number): ChatMessage {
const v = m.versions?.[index];
@@ -306,7 +306,7 @@ export function applyVersion(m: ChatMessage, index: number): ChatMessage {
};
}
-/** 合并字符串列表并去重,保持首次出现顺序。 */
+/** Merge string lists and dedupe them, keeping first-seen order. */
function mergeUniqueStrings(previous: string[] | undefined, incoming: string[]): string[] {
return [...new Set([...(previous ?? []), ...incoming])];
}
diff --git a/webdemo/frontend/src/pages/playground/utils/metrics.ts b/webdemo/frontend/src/pages/playground/utils/metrics.ts
index 19f2d81..a3fe96e 100644
--- a/webdemo/frontend/src/pages/playground/utils/metrics.ts
+++ b/webdemo/frontend/src/pages/playground/utils/metrics.ts
@@ -1,38 +1,38 @@
/**
- * 单轮生成性能指标的派生与格式化纯函数。
+ * Pure functions that derive and format performance metrics for one generation.
*
- * 用途:把 useChat 埋点得到的原始计时(firstTokenMs/durationMs)与尾块 usage,
- * 换算为消息底部指标行所需的展示值(秒、tokens/s),无副作用便于单测与复用。
+ * Purpose: turn raw timings from useChat instrumentation (firstTokenMs/durationMs) and the tail usage
+ * into the display values the message-footer metrics row needs (seconds, tokens/s). No side effects, so they are easy to unit test and reuse.
*/
import type { MessageMetrics } from '../types';
import type { TokenUsage } from '@/api/map/chat';
-/** 单个指标项的展示结构 */
+/** Display structure of one metric item */
export interface MetricItem {
- /** 指标名(如「首 token」) */
+ /** Metric name (such as "time to first token") */
label: string;
- /** 主数值文本(如「0.32」「51」) */
+ /** Primary value text (such as "0.32" or "51") */
value: string;
- /** 数值单位(如「s」「tokens/s」;无单位时为空串) */
+ /** Value unit (such as "s" or "tokens/s"; an empty string when there is no unit) */
unit: string;
- /** 悬浮说明;无则不展示 info 图标 */
+ /** Hover explanation; when absent, do not show the info icon */
hint?: string;
}
-/** 毫秒转秒并保留两位小数(如 320 → "0.32") */
+/** Convert milliseconds to seconds with two decimal places (for example 320 → "0.32") */
export function formatSeconds(ms: number): string {
return (ms / 1000).toFixed(2);
}
/**
- * 输出速率(tokens/s):完成 token 数 ÷ 纯生成耗时。
- * 纯生成耗时 = 总耗时 − 首 token 延迟(扣除排队/首包网络往返,更贴近吐字速度)。
- * 缺少任一输入、或有效耗时 ≤ 0 时返回 null(不展示)。
+ * Output rate (tokens/s): completion token count ÷ pure generation time.
+ * Pure generation time = total elapsed − time to first token (queueing and the first-packet round trip are excluded, so it is closer to the token rate).
+ * Return null (do not display) when any input is missing, or the effective elapsed time is ≤ 0.
*
- * @param completionTokens 本轮完成(输出)token 数
- * @param firstTokenMs 首 token 延迟(ms)
- * @param durationMs 总耗时(ms)
+ * @param completionTokens completion (output) token count for this turn
+ * @param firstTokenMs time to first token (ms)
+ * @param durationMs total elapsed time (ms)
*/
export function outputRate(
completionTokens: number | undefined,
@@ -46,11 +46,11 @@ export function outputRate(
}
/**
- * 组装消息底部要展示的指标项列表(按参考看板口径:首 token / 总耗时 / 输出速率 / 共调用)。
- * 仅纳入有数据的项;全无则返回空数组,交由调用方决定是否渲染。
+ * Assemble the metric items to show in the message footer (dashboard convention: time to first token / total elapsed / output rate / total calls).
+ * Include only items that have data; if none do, return an empty array and let the caller decide whether to render.
*
- * @param metrics 前端计时指标(可能只有部分字段)
- * @param usage 尾块 token 用量
+ * @param metrics frontend timing metrics (only some fields may be present)
+ * @param usage tail-chunk token usage
*/
export function buildMetricItems(
metrics: MessageMetrics | undefined,
diff --git a/webdemo/frontend/src/pages/playground/utils/modelParameterDefaults.ts b/webdemo/frontend/src/pages/playground/utils/modelParameterDefaults.ts
index 96f9e4d..07a3de5 100644
--- a/webdemo/frontend/src/pages/playground/utils/modelParameterDefaults.ts
+++ b/webdemo/frontend/src/pages/playground/utils/modelParameterDefaults.ts
@@ -7,9 +7,9 @@ interface ResolvedModelParameterDefaults {
}
/**
- * 解析模型默认参数,用于数值回显与思考请求协议选择。
- * @param parameterConfig 管理端模型级默认请求参数
- * @returns 面板可表达的默认值、思考字段存在性与开关协议
+ * Parse model default parameters, used for numeric echo and choosing the reasoning request protocol.
+ * @param parameterConfig model-level default request parameters from the admin console
+ * @returns defaults the panel can express, whether reasoning fields exist, and the switch protocol
*/
export function resolveModelParameterDefaults(
parameterConfig?: Record<string, unknown>,
@@ -30,7 +30,7 @@ export function resolveModelParameterDefaults(
values: {
temperature: readNumber(parameterConfig.temperature, 0, 2),
topP: readNumber(parameterConfig.top_p, 0, 1),
- // 面板只对应 max_tokens;max_completion_tokens 留给 L2 按原字段名注入。
+ // The panel corresponds only to max_tokens; max_completion_tokens is left for L2 to inject under the original field name.
maxTokens: readNumber(parameterConfig.max_tokens, 0, 32768),
thinkingDepth: resolveThinkingDepth(
enableThinking,
@@ -51,25 +51,25 @@ export function resolveModelParameterDefaults(
};
}
-/** 仅接受面板可表达范围内的有限数字,避免异常配置污染受控输入。 */
+/** Accept only a finite number inside the range the panel can express, so a bad config does not pollute a controlled input. */
function readNumber(value: unknown, min: number, max: number): number | undefined {
if (typeof value !== 'number' || !Number.isFinite(value)) return undefined;
if (value < min || value > max) return undefined;
return value;
}
-/** 仅接受显式布尔值,其他类型继续使用体验中心默认行为。 */
+/** Accept only an explicit boolean; other types keep the experience-center default behavior. */
function readBoolean(value: unknown): boolean | undefined {
return typeof value === 'boolean' ? value : undefined;
}
-/** 读取 chat_template_kwargs.enable_thinking。 */
+/** Read chat_template_kwargs.enable_thinking. */
function readEnableThinking(value: unknown): boolean | undefined {
if (!isRecord(value)) return undefined;
return readBoolean(value.enable_thinking);
}
-/** 读取 thinking.type 的 enabled/disabled 状态。 */
+/** Read the enabled/disabled state of thinking.type. */
function readThinkingEnabled(value: unknown): boolean | undefined {
if (!isRecord(value)) return undefined;
if (value.type === 'enabled') return true;
@@ -77,13 +77,13 @@ function readThinkingEnabled(value: unknown): boolean | undefined {
return undefined;
}
-/** 把模型思考配置映射为开关值,仅用于判断是否需要覆盖 L2 默认参数。 */
+/** Map the model's reasoning config to a switch value, used only to decide whether L2 default parameters need to be overridden. */
function resolveThinkingDepth(
enableThinking: boolean | undefined,
thinkingEnabled: boolean | undefined,
hasReasoningEffort: boolean,
): ThinkingDepth | undefined {
- // 矛盾的双协议默认值不能判为匹配,必须让客户端显式统一两种开关。
+ // Contradictory defaults from the two protocols cannot be treated as a match; the client must explicitly unify both switches.
if (
enableThinking !== undefined &&
thinkingEnabled !== undefined &&
@@ -97,7 +97,7 @@ function resolveThinkingDepth(
return undefined;
}
-/** 根据模型配置中存在的思考字段选择对应的面板参数风格。 */
+/** Choose the matching panel parameter style from the reasoning fields present in the model config. */
function resolveThinkingStyle(
hasThinkingSwitch: boolean,
hasReasoningEffort: boolean,
@@ -108,7 +108,7 @@ function resolveThinkingStyle(
return undefined;
}
-/** 保留模型默认配置实际使用的思考开关协议。 */
+/** Keep the reasoning-switch protocol the model default config actually uses. */
function resolveThinkingControlFormat(
hasChatTemplateKwargs: boolean,
hasThinking: boolean,
@@ -118,12 +118,12 @@ function resolveThinkingControlFormat(
return 'chat_template_kwargs';
}
-/** 判断未知值是否为可读取字段的普通对象。 */
+/** Whether an unknown value is an ordinary object whose fields can be read. */
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
-/** 兼容当前编译目标的自有字段判断。 */
+/** Own-property check compatible with the current compile target. */
function hasOwn(record: Record<string, unknown>, key: string): boolean {
return Object.prototype.hasOwnProperty.call(record, key);
}
diff --git a/webdemo/frontend/src/pages/playground/utils/modelSwitch.ts b/webdemo/frontend/src/pages/playground/utils/modelSwitch.ts
index e854125..f1038ff 100644
--- a/webdemo/frontend/src/pages/playground/utils/modelSwitch.ts
+++ b/webdemo/frontend/src/pages/playground/utils/modelSwitch.ts
@@ -1,6 +1,6 @@
/**
- * 判断用户主动切换语言模型时是否必须开启新会话。
- * 同一模型、空白会话和恢复历史会话的模型回填均不需要清空当前上下文。
+ * Whether the user switching language models on purpose must start a new conversation.
+ * The same model, a blank conversation, and filling the model back in when restoring a history conversation do not need to clear the current context.
*/
export function shouldStartNewConversationOnModelChange(
currentModelId: string,
diff --git a/webdemo/frontend/src/pages/playground/utils/params.ts b/webdemo/frontend/src/pages/playground/utils/params.ts
index 7b0430d..74b1897 100644
--- a/webdemo/frontend/src/pages/playground/utils/params.ts
+++ b/webdemo/frontend/src/pages/playground/utils/params.ts
@@ -1,17 +1,17 @@
/**
- * 对话参数 → 请求字段映射纯函数。
+ * Pure functions that map conversation parameters → request fields.
*
- * 用途:把本页参数偏好(温度/思考深度等)组装为后端 `/v1/chat/completions` 请求参数。
- * 思考字段不同模型命名不一,按 `thinkingStyle` 决定发 reasoning_effort / thinking / 两者。
+ * Purpose: assemble this page's parameter preferences (temperature, reasoning depth, and so on) into backend `/v1/chat/completions` request parameters.
+ * Reasoning fields are named differently per model; `thinkingStyle` decides whether to send reasoning_effort, thinking, or both.
*/
import type { PlaygroundParams, ThinkingControlFormat, ThinkingDepth } from '../types';
import type { ChatCompletionParams, ChatRequestMessage } from '@/api/map/chat';
/**
- * 判断当前公开模型是否属于已支持图片压缩设置的 MiniCPM-V-4.7 系列。
- * @param model 公开模型 ID
- * @returns 仅精确系列名或连字符后缀返回 true,避免误匹配 v4.70 等模型
+ * Whether the current public model belongs to the MiniCPM-V-4.7 series that already supports image-compression settings.
+ * @param model public model ID
+ * @returns true only for the exact series name or a hyphen suffix, so models such as v4.70 are not matched by mistake
*/
export function supportsImageDownsampleMode(model: string): boolean {
const normalized = model.trim().toLowerCase();
@@ -19,24 +19,24 @@ export function supportsImageDownsampleMode(model: string): boolean {
}
/**
- * 判断当前公开模型是否必须使用非流式请求。
- * @param model 公开模型 ID
- * @returns 仅 MiniCPM-OCR-Jev 返回 true,避免影响其他 OCR 模型
+ * Whether the current public model must use a non-streaming request.
+ * @param model public model ID
+ * @returns true only for MiniCPM-OCR-Jev, so other OCR models are not affected
*/
export function requiresNonStreaming(model: string): boolean {
return model.trim().toLowerCase() === 'minicpm-ocr-jev';
}
/**
- * 由思考深度档位构造思考相关请求字段。
+ * Build reasoning-related request fields from the reasoning-depth tier.
*
- * 按模型协议发送 `chat_template_kwargs.enable_thinking` 或 `thinking.type`。
- * OpenAI 风格的 `reasoning_effort` 没有关闭值,仅在开启时按配置风格附加。
+ * Send `chat_template_kwargs.enable_thinking` or `thinking.type` according to the model protocol.
+ * OpenAI-style `reasoning_effort` has no off value, and is attached by config style only when reasoning is on.
*
- * @param depth 思考深度档位(on/off)
- * @param style 思考参数风格
- * @param controlFormat 思考开关应使用的协议字段
- * @returns 思考相关的请求字段片段
+ * @param depth reasoning-depth tier (on/off)
+ * @param style reasoning parameter style
+ * @param controlFormat protocol field the reasoning switch should use
+ * @returns the reasoning-related fragment of request fields
*/
export function buildThinkingParams(
depth: ThinkingDepth,
@@ -53,7 +53,7 @@ export function buildThinkingParams(
out.thinking = { type: enabled ? 'enabled' : 'disabled' };
}
- // OpenAI 风格附加项:reasoning_effort 枚举无「关闭」值,仅开启时下发 medium
+ // OpenAI-style extra: the reasoning_effort enum has no "off" value, so medium is sent only when reasoning is on
if (style === 'reasoning_effort' || style === 'both') {
if (enabled) out.reasoning_effort = 'medium';
}
@@ -61,11 +61,11 @@ export function buildThinkingParams(
}
/**
- * 组装完整的对话请求参数。
+ * Assemble the full conversation request parameters.
*
- * @param model 选中的模型 id
- * @param messages 历史消息(已转为 role+content)
- * @param params 参数偏好
+ * @param model selected model id
+ * @param messages history messages (already converted to role+content)
+ * @param params parameter preferences
*/
export function buildChatParams(
model: string,
@@ -92,7 +92,7 @@ export function buildChatParams(
params.thinkingStyle,
params.thinkingControlFormat,
);
- // L2 按整字段覆盖思考对象,修改开关时需保留模型配置的同层参数。
+ // L2 overrides the reasoning object as a whole field; when the switch changes, same-level parameters from the model config must be kept.
if (thinking.chat_template_kwargs) {
thinking.chat_template_kwargs = {
...params.thinkingDefaults?.chat_template_kwargs,
@@ -108,12 +108,12 @@ export function buildChatParams(
};
}
-/** 数值参数只有在明确设置且为有限数字时才进入请求,0 不视为空值。 */
+/** A numeric parameter enters the request only when it is explicitly set and finite; 0 is not treated as empty. */
function isFiniteNumber(value: number | undefined): value is number {
return typeof value === 'number' && Number.isFinite(value);
}
-/** 仅当当前请求实际包含图片输入时,才允许发送图片处理参数。 */
+/** Image-processing parameters may be sent only when the current request actually contains image input. */
function hasImageInput(messages: ChatRequestMessage[]): boolean {
return messages.some(
(message) =>
diff --git a/webdemo/frontend/src/pages/playground/utils/pcmStream.ts b/webdemo/frontend/src/pages/playground/utils/pcmStream.ts
index 1595f04..ecc1c2d 100644
--- a/webdemo/frontend/src/pages/playground/utils/pcmStream.ts
+++ b/webdemo/frontend/src/pages/playground/utils/pcmStream.ts
@@ -1,10 +1,10 @@
/**
- * 实时双工的浏览器音频 DSP 与采集/播放。
+ * Browser audio DSP plus capture and playback for realtime duplex.
*
- * 上行:AudioContext(16kHz) + AudioWorklet 每积满 1s 输出一块 Float32(浏览器自动重采样到
- * 16k)→ 裸 float32 PCM 的 base64。下行:上游 24kHz 裸 float32 PCM 的 base64 →
- * Float32Array → 线性重采样到本地 AudioContext 采样率 → AudioBufferSourceNode 无缝排队播放。
- * 视频帧:从 <video> 抓 JPEG。纯前端,无第三方依赖;协议帧构造见 realtimeProtocol.ts。
+ * Uplink: AudioContext(16kHz) + AudioWorklet emits one Float32 block each time 1s is filled (the browser resamples to
+ * 16k automatically) → base64 of raw float32 PCM. Downlink: base64 of upstream 24kHz raw float32 PCM →
+ * Float32Array → linear resample to the local AudioContext sample rate → AudioBufferSourceNode queued seamlessly.
+ * Video frames: grab JPEG from <video>. Frontend only, no third-party dependency; protocol frame construction is in realtimeProtocol.ts.
*/
import { arrayBufferToBase64 } from './audioEncode';
@@ -13,9 +13,9 @@ const UPSTREAM_RATE = 16000;
const DOWNSTREAM_RATE = 24000;
/**
- * capture-processor AudioWorklet 源码(内联为字符串,经 Blob URL 注册,
- * 避免 Vite `/console/` base 下 worklet 静态资源路径解析问题)。
- * 每积满 chunkSize 个采样(默认 16000 = 1s@16k)向主线程 postMessage 一块 Float32。
+ * capture-processor AudioWorklet source (inlined as a string and registered via a Blob URL,
+ * avoiding worklet static-asset path resolution under the Vite `/console/` base).
+ * Each time chunkSize samples are filled (default 16000 = 1s@16k), postMessage one Float32 block to the main thread.
*/
const CAPTURE_WORKLET_SRC = `
class CaptureProcessor extends AudioWorkletProcessor {
@@ -43,7 +43,7 @@ class CaptureProcessor extends AudioWorkletProcessor {
registerProcessor('capture-processor', CaptureProcessor);
`;
-/** 线性插值重采样(fromRate → toRate)。纯函数。 */
+/** Linear-interpolation resample (fromRate → toRate). Pure function. */
export function resamplePcm(
samples: Float32Array<ArrayBuffer>,
fromRate: number,
@@ -63,7 +63,7 @@ export function resamplePcm(
return out;
}
-/** base64(裸 float32 PCM)→ Float32Array。纯函数;非 4 字节对齐的尾部安全丢弃。 */
+/** base64 (raw float32 PCM) → Float32Array. Pure function; a tail that is not 4-byte aligned is safely dropped. */
export function base64ToFloat32(base64: string): Float32Array<ArrayBuffer> {
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
@@ -73,18 +73,18 @@ export function base64ToFloat32(base64: string): Float32Array<ArrayBuffer> {
return new Float32Array(bytes.buffer, 0, usable / 4);
}
-/** Float32 采样 → 裸 float32 PCM 的 base64(复用分块 base64,避免超长字符串爆栈)。 */
+/** Float32 samples → base64 of raw float32 PCM (reuses chunked base64 so a very long string does not blow the stack). */
export function float32ToBase64(samples: Float32Array): string {
- // 拷贝出独占且精确的 ArrayBuffer 再编码:worklet 切片视图可能带 byteOffset,
- // 且编码需普通 ArrayBuffer(非 SharedArrayBuffer);每秒 1 块的拷贝成本可忽略。
+ // Copy into an exclusive, exact ArrayBuffer before encoding: a worklet slice view may carry a byteOffset,
+ // and encoding needs an ordinary ArrayBuffer (not a SharedArrayBuffer); the cost of one copy per second is negligible.
const copy = new Float32Array(samples.length);
copy.set(samples);
return arrayBufferToBase64(copy.buffer);
}
/**
- * 从 <video> 抓一帧 JPEG,返回去掉 data URL 前缀的裸 base64。
- * 视频尚未就绪(宽或高为 0)时返回 null。
+ * Grab one JPEG frame from <video>, and return raw base64 with the data-URL prefix removed.
+ * Return null when the video is not ready yet (width or height is 0).
*/
export function captureJpegFrame(
video: HTMLVideoElement,
@@ -105,8 +105,8 @@ export function captureJpegFrame(
}
/**
- * 下行音频播放器:把上游 24kHz 裸 float32 PCM 分块按到达顺序无缝排入播放队列。
- * playbackDelayMs 用于每轮开始时预留少量缓冲,缓解首块抖动。
+ * Downlink audio player: queue upstream 24kHz raw float32 PCM chunks seamlessly in arrival order.
+ * playbackDelayMs reserves a little buffer at the start of each turn, to absorb jitter on the first chunk.
*/
export class RealtimePlayer {
private ctx: AudioContext | null = null;
@@ -122,13 +122,13 @@ export class RealtimePlayer {
this.nextTime = this.ctx.currentTime;
}
- /** 新一轮开始:把排队起点推进到当前时刻(含 playbackDelay 缓冲)。 */
+ /** Start of a new turn: advance the queue start to the current time (including the playbackDelay buffer). */
beginTurn(): void {
if (this.ctx)
this.nextTime = Math.max(this.nextTime, this.ctx.currentTime + this.delayMs / 1000);
}
- /** 排入一段 base64 音频;重采样到本地采样率后按序调度。 */
+ /** Enqueue one base64 audio segment; resample to the local sample rate, then schedule in order. */
enqueue(base64: string): void {
if (!this.ctx) return;
const rawSamples = base64ToFloat32(base64);
@@ -141,8 +141,8 @@ export class RealtimePlayer {
const src = this.ctx.createBufferSource();
src.buffer = buffer;
src.connect(this.ctx.destination);
- // nextTime 落后于当前时刻说明队列已放空(上游供给或主线程调度跟不上播放):
- // 重新起排时补回缓冲,否则紧贴当前时刻排队,下一次抖动会立刻再断一次。
+ // nextTime behind the current time means the queue has drained (upstream supply or main-thread scheduling cannot keep up with playback):
+ // when starting the queue again, put the buffer back, or queueing flush against the current time will break again at the next jitter.
const startAt =
this.nextTime > this.ctx.currentTime
? this.nextTime
@@ -153,23 +153,23 @@ export class RealtimePlayer {
src.onended = () => this.sources.delete(src);
}
- /** 本轮结束:让已排队音频自然播完(无操作)。 */
+ /** End of this turn: let audio already queued finish naturally (no operation). */
endTurn(): void {}
- /** 打断:立即停止并清空所有已调度音频。 */
+ /** Interrupt: stop immediately and clear every scheduled audio clip. */
stopAll(): void {
this.sources.forEach((s) => {
try {
s.stop();
} catch {
- /* 已停止 */
+ /* stopped */
}
});
this.sources.clear();
if (this.ctx) this.nextTime = this.ctx.currentTime;
}
- /** 关闭播放器并释放 AudioContext。 */
+ /** Close the player and release the AudioContext. */
stop(): void {
this.stopAll();
this.ctx?.close().catch(() => undefined);
@@ -179,8 +179,8 @@ export class RealtimePlayer {
}
/**
- * 上行麦克风采集:AudioContext(16kHz) + AudioWorklet 每 1s 输出一块 Float32(16k)。
- * 不接 destination,避免麦克风回放造成啸叫;暴露 context 供频谱可视化复用同一上下文。
+ * Uplink microphone capture: AudioContext(16kHz) + AudioWorklet emits one Float32(16k) block every 1s.
+ * Do not connect destination, so microphone playback does not cause howling; expose context so spectrum visualization can reuse the same context.
*/
export class MicCapture {
private ctx: AudioContext | null = null;
diff --git a/webdemo/frontend/src/pages/playground/utils/pdfImageParse.ts b/webdemo/frontend/src/pages/playground/utils/pdfImageParse.ts
index 19aa312..bda5f69 100644
--- a/webdemo/frontend/src/pages/playground/utils/pdfImageParse.ts
+++ b/webdemo/frontend/src/pages/playground/utils/pdfImageParse.ts
@@ -1,4 +1,4 @@
-/** 原始 PDF 只提交一个 MAP 任务;本地渲染仅用于预览和按需裁图。 */
+/** A raw PDF submits only one MAP task; local rendering is only for preview and on-demand crops. */
import type { QueryClient } from '@tanstack/react-query';
import { runImageParseJob, type ImageParseJob } from '@/api/map/imageParseJobs';
@@ -20,28 +20,28 @@ export interface PdfPageResult {
error?: string;
}
-/** PDF 执行上下文;查询复用门户 QueryClient,KIE 字段原样交给任务客户端校验。 */
+/** PDF execution context; queries reuse the portal QueryClient, and KIE fields are handed to the task client for validation as-is. */
export interface PdfImageParseJobOptions {
queryClient?: QueryClient;
fields?: readonly string[];
}
/**
- * 用原 PDF fileId 创建整份任务,增量结果按零起始 metadata.page_index 归档。
- * @param source 本地 PDF 预览地址,仅在原件缺少 fileId 时用于补传
- * @param mode 识别任务,历史档位映射为 standard;seal 不支持 PDF
- * @param model 当前可用的 OCR 模型
- * @param projectId 原件补传所需项目
- * @param signal 任务生命周期;取消由任务客户端 DELETE
- * @param onOpen 整份文档页数,不用单页重试的任务页数覆盖原件页数
- * @param onPage 一起始页面结果;裁图由既有 hooks 按需生成
- * @param onlyPage 可选的一起始原件重试页
- * @param _getPriorityPage 兼容旧调用签名;页调度由 MAP 持有
- * @param skipPages 本地已完成页,仅跳过展示,不改变后端原件任务
- * @param upright 摆正开关
- * @param _recognizeSeal 兼容旧调用方;后端始终开启印章识别
- * @param attachment 原 PDF 附件,优先复用已上传的 fileId
- * @param options 查询客户端及可选 KIE 字段
+ * Create one task for the whole document from the original PDF fileId; incremental results are filed by zero-based metadata.page_index.
+ * @param source local PDF preview URL, used to re-upload only when the original lacks a fileId
+ * @param mode recognition task; a historical tier maps to standard; seal does not support PDF
+ * @param model OCR model currently available
+ * @param projectId project required to re-upload the original
+ * @param signal task lifecycle; cancellation is a DELETE by the task client
+ * @param onOpen page count of the whole document; do not overwrite the original page count with the task page count from a single-page retry
+ * @param onPage a one-based page result; crops are generated on demand by the existing hooks
+ * @param onlyPage optional one-based original page to retry
+ * @param _getPriorityPage compatible with the old call signature; page scheduling is owned by MAP
+ * @param skipPages pages already finished locally; skip display only, and do not change the backend original task
+ * @param upright rotation-adaptation switch
+ * @param _recognizeSeal compatible with old callers; the backend always turns seal recognition on
+ * @param attachment original PDF attachment; prefer an already uploaded fileId
+ * @param options query client and optional KIE fields
*/
export async function parsePdfPages(
source: string,
diff --git a/webdemo/frontend/src/pages/playground/utils/pdfImageParseCrops.ts b/webdemo/frontend/src/pages/playground/utils/pdfImageParseCrops.ts
index 8fbea1a..7789b73 100644
--- a/webdemo/frontend/src/pages/playground/utils/pdfImageParseCrops.ts
+++ b/webdemo/frontend/src/pages/playground/utils/pdfImageParseCrops.ts
@@ -2,7 +2,7 @@ import type { ImageParseSdkResult } from '@/api/map/imageParseSdk';
import { imageParseCrops } from './imageParseCrops';
import { renderPdfPageImage } from './pdfPageImage';
-/** 从存档 PDF 重建当前页裁剪预览,仅执行本地渲染,不调用 OCR 或签链。 */
+/** Rebuild the current page's crop preview from an archived PDF; only local rendering runs, with no OCR call and no signed URL. */
export async function rebuildPdfPageCrops(
source: string,
page: number,
diff --git a/webdemo/frontend/src/pages/playground/utils/pdfImageParseScope.ts b/webdemo/frontend/src/pages/playground/utils/pdfImageParseScope.ts
index 4236400..4582fa5 100644
--- a/webdemo/frontend/src/pages/playground/utils/pdfImageParseScope.ts
+++ b/webdemo/frontend/src/pages/playground/utils/pdfImageParseScope.ts
@@ -1,7 +1,7 @@
import type { ImageParseMode } from '@/api/map/imageParseSdk';
import { isImageParseSharedExample } from './imageParseExamples';
-/** PDF 识别结果所属的文件和执行参数。 */
+/** File and execution parameters a PDF recognition result belongs to. */
export interface PdfParseScope {
id?: string;
source: string;
@@ -12,10 +12,10 @@ export interface PdfParseScope {
}
/**
- * 判断 PDF 结果能否用于当前上下文;共享案例不绑定用户的执行参数。
- * @param previous 结果范围
- * @param next 当前范围
- * @returns 结果是否仍有效
+ * Whether a PDF result can be used in the current context; a shared example is not bound to the user's execution parameters.
+ * @param previous result scope
+ * @param next current scope
+ * @returns whether the result is still valid
*/
export function samePdfScope(previous: PdfParseScope | undefined, next: PdfParseScope): boolean {
return (
diff --git a/webdemo/frontend/src/pages/playground/utils/pdfImageParseStatus.ts b/webdemo/frontend/src/pages/playground/utils/pdfImageParseStatus.ts
index 6c6ece0..9e3fe72 100644
--- a/webdemo/frontend/src/pages/playground/utils/pdfImageParseStatus.ts
+++ b/webdemo/frontend/src/pages/playground/utils/pdfImageParseStatus.ts
@@ -1,6 +1,6 @@
import type { PdfPageResult } from './pdfImageParse';
-/** 将 PDF.js 与 OCR 调用异常映射为稳定的界面文案键。 */
+/** Map PDF.js and OCR call failures to a stable UI copy key. */
export function pdfParseErrorKey(failure: unknown): string {
if (!(failure instanceof Error)) return 'imageParseRequestFailed';
if (failure.name === 'PasswordException') return 'documentPdfPassword';
@@ -11,13 +11,13 @@ export function pdfParseErrorKey(failure: unknown): string {
return 'imageParseRequestFailed';
}
-/** 统计已有结果或错误页,等待占位不参与完成度。 */
+/** Count pages that already have a result or an error; a waiting placeholder does not count toward completion. */
export function countCompletedPdfPages(results: Readonly<Record<number, PdfPageResult>>) {
return Object.values(results).filter((page) => Boolean(page.result) || Boolean(page.error))
.length;
}
-/** 恢复时仅跳过已有成功结果的页;失败页仍可重新展示。 */
+/** On restore, skip only pages that already have a successful result; failed pages can still be shown again. */
export function completedPdfPageIndexes(
results: Readonly<Record<number, PdfPageResult>>,
): Set<number> {
diff --git a/webdemo/frontend/src/pages/playground/utils/pdfPageImage.ts b/webdemo/frontend/src/pages/playground/utils/pdfPageImage.ts
index e891920..e9d673f 100644
--- a/webdemo/frontend/src/pages/playground/utils/pdfPageImage.ts
+++ b/webdemo/frontend/src/pages/playground/utils/pdfPageImage.ts
@@ -1,6 +1,6 @@
import type { PDFDocumentProxy } from 'pdfjs-dist';
-/** 按 OCR 固定倍率生成本地页图,取消及完成后释放画布与页面资源。 */
+/** Produce a local page image at the fixed OCR scale, and release the canvas and page resources on cancel and on completion. */
export async function renderPdfPageImage(
pdf: PDFDocumentProxy,
pageNumber: number,
@@ -33,7 +33,7 @@ export async function renderPdfPageImage(
}
}
-/** 异步编码 PNG;避免每页 toDataURL 在主线程同步压缩造成滚动卡顿。 */
+/** Encode PNG asynchronously; avoid toDataURL compressing each page synchronously on the main thread and stuttering scroll. */
function canvasToDataUrl(canvas: HTMLCanvasElement, signal: AbortSignal): Promise<string> {
return new Promise((resolve, reject) => {
const abort = () => reject(new DOMException('Render cancelled', 'AbortError'));
diff --git a/webdemo/frontend/src/pages/playground/utils/pdfPreview.ts b/webdemo/frontend/src/pages/playground/utils/pdfPreview.ts
index 134ebf0..599eda2 100644
--- a/webdemo/frontend/src/pages/playground/utils/pdfPreview.ts
+++ b/webdemo/frontend/src/pages/playground/utils/pdfPreview.ts
@@ -1,14 +1,14 @@
-/** PDF.js 读取本地文件:原文预览与逐页转图共用加载配置。 */
+/** PDF.js reads a local file: the original-text preview and per-page image conversion share the load config. */
import { getDocument, GlobalWorkerOptions, type PDFDocumentLoadingTask } from 'pdfjs-dist';
import workerUrl from 'pdfjs-dist/build/pdf.worker.min.mjs?url';
import { trimEmptyPdfRevision } from './pdfPreviewSource';
import { isImageParseSharedPdfUrl } from './imageParseExamples';
import { clearPdfPreviewFrames } from './pdfPreviewFrameCache';
-// 已发布的 worker 曾以 octet-stream 缓存一年;改用新 URL 避免继续命中旧响应头。
+// A published worker was cached as octet-stream for a year; use a new URL so the old response headers are not hit again.
GlobalWorkerOptions.workerSrc = `${workerUrl}${workerUrl.includes('?') ? '&' : '?'}mime=js`;
-/** 历史切换常用的 PDF 文档短缓存时长与容量,避免频繁重复解析同一原件。 */
+/** Short-cache duration and capacity for PDF documents that history switching uses often, so the same original is not parsed again and again. */
const PDF_PREVIEW_CACHE_TTL_MS = 30_000;
const PDF_PREVIEW_CACHE_MAX = 2;
const SHARED_PDF_CACHE_TTL_MS = 300_000;
@@ -22,7 +22,7 @@ interface PdfPreviewCacheEntry {
const pdfPreviewCache = new Map<string, PdfPreviewCacheEntry>();
-/** 真正销毁底层 PDF.js 任务;吞掉重复销毁等非关键清理错误。 */
+/** Actually destroy the underlying PDF.js task; swallow non-critical cleanup errors such as destroying twice. */
function destroyPdfPreviewEntry(source: string, entry: PdfPreviewCacheEntry) {
if (entry.releaseTimer !== undefined) window.clearTimeout(entry.releaseTimer);
entry.releaseTimer = undefined;
@@ -31,7 +31,7 @@ function destroyPdfPreviewEntry(source: string, entry: PdfPreviewCacheEntry) {
void entry.task.destroy().catch(() => undefined);
}
-/** 释放一个引用;最后一个引用离开后再延迟销毁,给历史切换留出复用窗口。 */
+/** Release one reference; after the last reference leaves, delay destruction, leaving a reuse window for history switching. */
function releasePdfPreviewEntry(source: string, entry: PdfPreviewCacheEntry) {
entry.refs = Math.max(0, entry.refs - 1);
if (entry.refs > 0 || entry.releaseTimer !== undefined) return;
@@ -44,7 +44,7 @@ function releasePdfPreviewEntry(source: string, entry: PdfPreviewCacheEntry) {
);
}
-/** 容量满时优先淘汰没有引用的文档,避免常驻过多大 PDF。 */
+/** When capacity is full, evict unreferenced documents first, so too many large PDFs do not stay resident. */
function evictIdlePdfPreviewEntry(shared: boolean) {
for (const [source, entry] of pdfPreviewCache) {
if (entry.refs === 0 && isImageParseSharedPdfUrl(source) === shared) {
@@ -54,7 +54,7 @@ function evictIdlePdfPreviewEntry(shared: boolean) {
}
}
-/** 读取或创建 PDF.js 任务;失败任务不留在缓存中。 */
+/** Read or create a PDF.js task; a failed task is not left in the cache. */
function acquirePdfPreviewTask(source: string) {
const cached = pdfPreviewCache.get(source);
if (cached) {
@@ -89,7 +89,7 @@ function acquirePdfPreviewTask(source: string) {
});
const entry: PdfPreviewCacheEntry = { task, refs: 1 };
pdfPreviewCache.set(source, entry);
- // 解析失败时不能让后续历史切换继续拿到同一个失败 Promise。
+ // A parse failure must not let a later history switch keep receiving the same failed Promise.
void task.promise.catch(() => {
if (pdfPreviewCache.get(source) === entry) pdfPreviewCache.delete(source);
if (entry.refs === 0) destroyPdfPreviewEntry(source, entry);
@@ -98,10 +98,10 @@ function acquirePdfPreviewTask(source: string) {
}
/**
- * 创建可销毁的 PDF 读取任务,附属资源固定为同源静态文件。
+ * Create a destroyable PDF read task, with auxiliary resources fixed to same-origin static files.
*
- * 同一地址在短时间内复用底层文档,用于加速左侧历史记录来回切换;调用方的
- * destroy 只释放引用,最后一个引用释放后延迟清理 PDF.js 资源。
+ * The same address reuses the underlying document for a short time, to speed switching back and forth in the left history list; the caller's
+ * destroy only releases a reference, and PDF.js resources are cleaned up after a delay once the last reference is released.
*/
export function loadPdfPreview(source: string) {
const entry = acquirePdfPreviewTask(source);
diff --git a/webdemo/frontend/src/pages/playground/utils/pdfPreviewFrameCache.ts b/webdemo/frontend/src/pages/playground/utils/pdfPreviewFrameCache.ts
index 437d4ff..8280af5 100644
--- a/webdemo/frontend/src/pages/playground/utils/pdfPreviewFrameCache.ts
+++ b/webdemo/frontend/src/pages/playground/utils/pdfPreviewFrameCache.ts
@@ -21,11 +21,11 @@ function discard(entry: CachedFrame) {
}
/**
- * 将命中的页面帧复制到本次离屏画布;调用方仍通过原子提交更新可见 canvas。
- * @param document 当前 PDF.js 文档
- * @param key 页面、缩放、旋转、分辨率与重试版本
- * @param buffer 本次提交专用缓冲区
- * @returns 命中的页面帧,未命中返回 undefined
+ * Copy a hit page frame onto this offscreen canvas; the caller still updates the visible canvas through an atomic commit.
+ * @param document current PDF.js document
+ * @param key page, zoom, rotation, resolution, and retry version
+ * @param buffer buffer dedicated to this commit
+ * @returns the hit page frame, or undefined on a miss
*/
export function readPdfPreviewFrame(
document: PDFDocumentProxy,
@@ -47,10 +47,10 @@ export function readPdfPreviewFrame(
}
/**
- * 保留固定案例的已完成像素副本;按 LRU 淘汰,最多八帧且像素内存不超过 48 MB。
- * @param document 当前 PDF.js 文档
- * @param key 页面视图身份
- * @param frame PDF.js 成功绘制的帧
+ * Keep finished pixel copies of a fixed example; evict by LRU, at most eight frames and no more than 48 MB of pixel memory.
+ * @param document current PDF.js document
+ * @param key page-view identity
+ * @param frame frame PDF.js drew successfully
*/
export function rememberPdfPreviewFrame(
document: PDFDocumentProxy,
@@ -77,7 +77,7 @@ export function rememberPdfPreviewFrame(
pixels += count;
}
-/** PDF.js 文档销毁时同步释放其全部缓存像素与引用。 */
+/** When a PDF.js document is destroyed, release all of its cached pixels and references at the same time. */
export function clearPdfPreviewFrames(document: PDFDocumentProxy) {
for (const entry of frames) {
if (entry.document === document) discard(entry);
diff --git a/webdemo/frontend/src/pages/playground/utils/pdfPreviewRender.ts b/webdemo/frontend/src/pages/playground/utils/pdfPreviewRender.ts
index 5ddc51e..fc47ac4 100644
--- a/webdemo/frontend/src/pages/playground/utils/pdfPreviewRender.ts
+++ b/webdemo/frontend/src/pages/playground/utils/pdfPreviewRender.ts
@@ -1,13 +1,13 @@
import type { PDFDocumentProxy, RenderTask } from 'pdfjs-dist';
import { readPdfPreviewFrame, rememberPdfPreviewFrame } from './pdfPreviewFrameCache';
-/** 将 PDF.js 错误映射为稳定文案,不向页面暴露解析器内部堆栈。 */
+/** Map a PDF.js error to stable copy, and do not expose the parser's internal stack on the page. */
export function pdfError(error: unknown): string {
if (error instanceof Error && error.name === 'PasswordException') return 'documentPdfPassword';
return 'documentPdfFailed';
}
-/** PDF 页面基础尺寸;rotation 只保存文件自带方向。 */
+/** Base size of a PDF page; rotation stores only the orientation that comes with the file. */
export interface PdfPageGeometry {
pageNumber: number;
width: number;
@@ -15,13 +15,13 @@ export interface PdfPageGeometry {
rotation: number;
}
-/** 未叠加用户缩放的页面占位尺寸,实际显示尺寸由 CSS 变量计算。 */
+/** Page placeholder size before user zoom is applied; the actual display size is computed from a CSS variable. */
export interface PdfPageView extends Pick<PdfPageGeometry, 'pageNumber' | 'rotation'> {
baseWidth: number;
baseHeight: number;
}
-/** 大 PDF 页面尺寸后台测量每批数量,避免一次性占用 PDF.js worker 与主线程。 */
+/** Batch size for measuring large-PDF page sizes in the background, so the PDF.js worker and the main thread are not occupied all at once. */
const PDF_GEOMETRY_BATCH_SIZE = 8;
interface PdfProgressiveGeometryOptions {
@@ -32,7 +32,7 @@ interface PdfProgressiveGeometryOptions {
onError?: (error: unknown) => void;
}
-/** 读取单页原始几何信息;失败由调用方决定是否保留估算值。 */
+/** Read one page's raw geometry; on failure the caller decides whether to keep the estimate. */
async function measurePdfPageGeometry(
document: PDFDocumentProxy,
pageNumber: number,
@@ -42,7 +42,7 @@ async function measurePdfPageGeometry(
return { pageNumber, width: view.width, height: view.height, rotation: pdfPage.rotate };
}
-/** 按锚点页向外扩展测量顺序,优先修正用户即将滚到的相邻页。 */
+/** Expand the measurement order outward from the anchor page, so neighboring pages the user is about to scroll to are corrected first. */
function createPdfGeometryOrder(anchorPage: number, pageCount: number): number[] {
const order: number[] = [];
for (let distance = 1; distance < pageCount; distance += 1) {
@@ -54,7 +54,7 @@ function createPdfGeometryOrder(anchorPage: number, pageCount: number): number[]
return order;
}
-/** 只在页面几何确实变化时返回新数组,尺寸相同的页面不会触发重渲染。 */
+/** Return a new array only when page geometry actually changed; pages of the same size do not trigger a re-render. */
function mergePdfPageGeometries(
current: PdfPageGeometry[],
updates: readonly PdfPageGeometry[],
@@ -77,7 +77,7 @@ function mergePdfPageGeometries(
return changed ? next : current;
}
-/** 生成可见页几何签名,让离屏页面尺寸修正不触发当前页重绘。 */
+/** Build a geometry signature of the visible pages, so an offscreen page-size correction does not redraw the current page. */
export function createVisiblePdfGeometryKey(
geometryByPage: ReadonlyMap<number, PdfPageGeometry>,
pageNumbers: readonly number[],
@@ -93,10 +93,10 @@ export function createVisiblePdfGeometryKey(
}
/**
- * 先用锚点页发布完整 PDF 骨架,再分批修正其余页面几何。
+ * Publish a full PDF skeleton from the anchor page first, then correct the geometry of the remaining pages in batches.
*
- * 这样历史记录切换时当前页可以立即渲染,大文档不需要等待所有 `getPage`
- * 调用完成后才出现页面结构。
+ * Then, when switching history records, the current page can render immediately, and a large document does not have to wait for every `getPage`
+ * call to finish before the page structure appears.
*/
export function measurePdfPageGeometries({
document,
@@ -158,28 +158,28 @@ export function measurePdfPageGeometries({
};
}
-/** PDF.js 后台绘制完成但尚未提交到 DOM canvas 的一帧。 */
+/** One frame PDF.js finished drawing in the background but has not yet committed to the DOM canvas. */
export interface PdfPageFrame {
buffer: HTMLCanvasElement;
width: number;
height: number;
}
-/** 单页渲染参数;width 是 PDF 视口的可用内容宽度。 */
+/** Render parameters for one page; width is the usable content width of the PDF viewport. */
export interface PdfPageRenderOptions {
geometry: PdfPageGeometry;
availableWidth: number;
scale: number;
rotation: number;
- /** 固定案例启用有界像素缓存;显式重试更换版本,普通历史不保留帧。 */
+ /** A fixed example enables a bounded pixel cache; an explicit retry changes the version, and ordinary history does not keep frames. */
cacheKey?: string;
}
/**
- * 创建一页 PDF 的后台渲染任务。
+ * Create a background render task for one PDF page.
*
- * 任务先在离屏 canvas 完成 PDF.js 绘制,再返回显示尺寸;调用方可把返回帧
- * 原子提交到 DOM canvas,避免缩放或旋转期间出现空白页。
+ * The task finishes PDF.js drawing on an offscreen canvas first, then returns the display size; the caller can atomically commit the returned frame
+ * to the DOM canvas, so a blank page does not appear during zoom or rotation.
*/
export function createPdfPageRenderTask(
document: PDFDocumentProxy,
@@ -239,9 +239,9 @@ export function createPdfPageRenderTask(
}
/**
- * 从当前页与左右相邻页中找出视口中心最近的页面。
+ * Find the page whose center is closest to the viewport center, among the current page and its left and right neighbors.
*
- * 只比较相邻页可以让滚动页码更新保持 O(1),同时避免页面间隙导致前后页来回震荡。
+ * Comparing only neighbors keeps scroll page-number updates O(1), and avoids the previous and next pages oscillating because of the gap between pages.
*/
export function getNearestPdfPage(
current: number,
diff --git a/webdemo/frontend/src/pages/playground/utils/pdfPreviewSource.ts b/webdemo/frontend/src/pages/playground/utils/pdfPreviewSource.ts
index a76d0ca..4e436d7 100644
--- a/webdemo/frontend/src/pages/playground/utils/pdfPreviewSource.ts
+++ b/webdemo/frontend/src/pages/playground/utils/pdfPreviewSource.ts
@@ -1,6 +1,6 @@
-/** 修复已知的空增量更新交叉引用尾部;正常 PDF 保留原始字节。 */
+/** Repair a known empty incremental-update cross-reference trailer; a normal PDF keeps its original bytes. */
export function trimEmptyPdfRevision(data: Uint8Array): Uint8Array {
- // 只检查文件末尾:扫描正文可能误认图像流中的 xref/%%EOF 为结构标记。
+ // Check only the end of the file: scanning the body could mistake xref/%%EOF inside an image stream for a structure marker.
const tailStart = Math.max(0, data.length - 2048);
const tail = new TextDecoder('latin1').decode(data.subarray(tailStart));
const lastPointer = /startxref\s+(\d+)\s+%%EOF\s*$/.exec(tail);
diff --git a/webdemo/frontend/src/pages/playground/utils/realtimeConnection.ts b/webdemo/frontend/src/pages/playground/utils/realtimeConnection.ts
index b90b35c..7a3373d 100644
--- a/webdemo/frontend/src/pages/playground/utils/realtimeConnection.ts
+++ b/webdemo/frontend/src/pages/playground/utils/realtimeConnection.ts
@@ -1,10 +1,10 @@
/**
- * 实时全双工会话连接(框架无关)。
+ * Realtime full-duplex session connection (framework-agnostic).
*
- * 拥有 WS 传输、麦克风采集(16k)、下行播放(24k)、视频抽帧与会话时序;经回调把状态/波形/
- * 字幕增量/错误抛给上层(useRealtimeSession 负责映射到 React 状态)。协议帧见 realtimeProtocol.ts。
- * MAP API Key 经子协议 `map-api-key.<secret>` 携带,不入 URL/query/日志,并兼作 CSRF 防御;
- * 明文密钥仅由调用方内存传入,本模块不持久化、不打印。
+ * Owns WS transport, microphone capture (16k), downlink playback (24k), video frame grabs, and session timing; callbacks throw state, waveform,
+ * caption increments, and errors up to the caller (useRealtimeSession maps them onto React state). Protocol frames are in realtimeProtocol.ts.
+ * The MAP API Key is carried on the subprotocol `map-api-key.<secret>`, never in the URL, query, or logs, and also serves as CSRF defense;
+ * the plaintext secret is passed in only from the caller's memory. This module does not persist it and does not print it.
*/
import { CHAT_API_BASE } from '@/api/map/chat';
@@ -18,7 +18,7 @@ import {
type RealtimeConfig,
} from './realtimeProtocol';
-/** 会话状态:空闲/连接中/聆听/处理/播放/权限被拒/出错 */
+/** Session state: idle / connecting / listening / processing / playing / permission denied / error */
export type VoiceStatus =
| 'idle'
| 'requesting'
@@ -28,7 +28,7 @@ export type VoiceStatus =
| 'denied'
| 'error';
-/** connect 当轮参数 */
+/** Parameters for this connect turn */
export type RealtimeLifecycleEvent =
| {
type:
@@ -78,7 +78,7 @@ export interface RealtimeConnectOptions {
secret: string;
}
-/** 连接向上层抛出的回调集合 */
+/** Callback set the connection throws up to the caller */
export interface RealtimeCallbacks {
onStatus: (status: VoiceStatus) => void;
onViz: (level: number, bars: number[]) => void;
@@ -94,7 +94,7 @@ const KEY_PROTO_PREFIX = 'map-api-key.';
const VIDEO_MAX_SLICE_NUMS = 1;
const CLOSE_GRACE_PERIOD_MS = 3000;
-/** 构造 L2 `/v1/realtime` 的 WS URL(Key 走子协议,绝不入 URL/query)。 */
+/** Build the WS URL for L2 `/v1/realtime` (the key goes on the subprotocol and never into the URL or query). */
function buildWsUrl(mode: string, model: string): string {
const base = CHAT_API_BASE.replace(/\/$/, '');
const query =
@@ -129,7 +129,7 @@ export class RealtimeConnection {
constructor(private readonly cb: RealtimeCallbacks) {}
- /** 建立会话:麦克风 → 采集/可视化/播放器 → (video)离屏抽帧 → WS 握手。失败返回 false。 */
+ /** Open a session: microphone → capture / visualization / player → (video) offscreen frame grab → WS handshake. Return false on failure. */
async connect(o: RealtimeConnectOptions): Promise<boolean> {
this.closed = false;
this.closing = false;
@@ -205,7 +205,7 @@ export class RealtimeConnection {
return true;
}
- /** 主动挂断(发送 session.close 后清理)。 */
+ /** Hang up on purpose (send session.close, then clean up). */
disconnect(): void {
if (this.closed || this.closing) return;
const sock = this.ws;
@@ -221,7 +221,7 @@ export class RealtimeConnection {
this.cleanup('idle');
return;
}
- // 停止媒体采集和播放,但保留 WS 读取能力,让服务端终态帧能被消费。
+ // Stop media capture and playback, but keep the WS readable so the server's terminal frame can be consumed.
this.cleanupMediaResources();
this.cb.onViz(0, new Array(this.opts?.barCount ?? 0).fill(0));
this.closeTimer = window.setTimeout(() => this.cleanup('idle'), CLOSE_GRACE_PERIOD_MS);
@@ -252,13 +252,13 @@ export class RealtimeConnection {
return this.hdEnabled;
}
- /** 暂停/恢复上行(暂停时不再发送麦克风数据)。 */
+ /** Pause or resume the uplink (while paused, microphone data is no longer sent). */
setPaused(next: boolean): void {
this.paused = next;
this.emit({ type: 'pause', at: Date.now(), paused: next });
}
- /** 单工模式提交当前录音轮次:发送一个带 force_listen 的音频块后暂停上行。 */
+ /** In simplex mode, submit the current recording turn: send one audio chunk with force_listen, then pause the uplink. */
commitTurn(): void {
this.forceOnce = true;
this.paused = false;
@@ -321,8 +321,8 @@ export class RealtimeConnection {
this.emit({ type: 'listening', at: Date.now(), sessionId: evt.sessionId });
break;
case 'audio':
- // 优先聆听开启后,上游可能仍有已生成但尚未到达的残余音频帧;
- // 这些帧不能重新写入播放器,否则用户会感觉「打断」没有生效。
+ // After priority listening is turned on, the upstream may still have leftover audio frames that were generated but have not arrived yet;
+ // those frames must not be written into the player again, or the user would feel the interrupt did not take effect.
if (this.forceListenActive) return;
if (!this.speaking) {
this.speaking = true;
@@ -390,7 +390,7 @@ export class RealtimeConnection {
this.cb.onLifecycle(event);
}
- /** 释放媒体采集、播放和视频预览资源,但保留 WebSocket 供收尾读取。 */
+ /** Release media capture, playback, and video preview resources, but keep the WebSocket for the closing read. */
private cleanupMediaResources(): void {
this.stopViz?.();
this.mic?.stop();
@@ -408,7 +408,7 @@ export class RealtimeConnection {
this.speaking = false;
}
- /** 释放媒体和 WebSocket 资源。 */
+ /** Release media and WebSocket resources. */
private cleanupResources(): void {
this.clearCloseTimer();
this.cleanupMediaResources();
@@ -417,7 +417,7 @@ export class RealtimeConnection {
this.ws = null;
}
- /** 清理主动关闭的有界等待定时器。 */
+ /** Clear the bounded wait timer for a close started on purpose. */
private clearCloseTimer(): void {
if (this.closeTimer !== null) {
window.clearTimeout(this.closeTimer);
diff --git a/webdemo/frontend/src/pages/playground/utils/realtimeProtocol.ts b/webdemo/frontend/src/pages/playground/utils/realtimeProtocol.ts
index 2994d37..678ead0 100644
--- a/webdemo/frontend/src/pages/playground/utils/realtimeProtocol.ts
+++ b/webdemo/frontend/src/pages/playground/utils/realtimeProtocol.ts
@@ -1,12 +1,12 @@
/**
- * MiniCPM-O 实时双工线协议(帧构造 + 下行事件归一化)。
+ * MiniCPM-O realtime duplex wire protocol (frame construction + downlink event normalization).
*
- * 与 L2 `/v1/realtime` 原样透传的 JSON text frame 一一对应,取自官方 realtime-session.js
- * 的 API V2 协议:session.init / input.append / response.output.delta(kind=...)。
- * 纯函数、无 DOM 依赖,便于单测;WS 连接与鉴权在 useRealtimeSession 中处理。
+ * One-to-one with the JSON text frames L2 `/v1/realtime` forwards as-is, taken from the API V2 protocol in the official realtime-session.js:
+ * session.init / input.append / response.output.delta(kind=...).
+ * Pure functions, no DOM dependency, so they are easy to unit test; the WS connection and auth are handled in useRealtimeSession.
*/
-/** 采样/生成配置(透传到 session.init.payload.config;profile v1 主用 length_penalty) */
+/** Sampling and generation config (forwarded to session.init.payload.config; profile v1 mainly uses length_penalty) */
export interface RealtimeConfig {
length_penalty: number;
max_tokens: number;
@@ -16,16 +16,16 @@ export interface RealtimeConfig {
vision_hd?: boolean;
}
-/** session.init 额外参数 */
+/** Extra session.init parameters */
export interface SessionInitOptions {
- /** 参考音频(裸 base64),既作对话侧 ref 也作 TTS 侧 ref(对齐 demo 双字段) */
+ /** Reference audio (raw base64), used both as the conversation-side ref and the TTS-side ref (matching the demo's two fields) */
refAudioBase64?: string;
- /** 图像切片数;video 模式默认 1,越大细节越多但更慢 */
+ /** Image slice count; video mode defaults to 1. More slices mean more detail and more latency */
maxSliceNums?: number;
ttsRefAudioBase64?: string;
}
-/** 归一化后的下行事件 */
+/** Normalized downlink event */
export type ServerEvent =
| { kind: 'queue'; position?: number; estimatedWaitSeconds?: number; queueLength?: number }
| { kind: 'queue_done' }
@@ -37,7 +37,7 @@ export type ServerEvent =
| { kind: 'error'; message: string }
| { kind: 'other' };
-/** 下行原始帧的宽松形状(仅取用到的字段) */
+/** Loose shape of a raw downlink frame (only the fields that are used) */
interface RawServerFrame {
type?: string;
kind?: string;
@@ -54,7 +54,7 @@ interface RawServerFrame {
error?: { code?: string; message?: string } | string;
}
-/** 构造 session.init 帧:system_prompt + config(length_penalty) + 可选 voice / 切片数。 */
+/** Build a session.init frame: system_prompt + config(length_penalty) + optional voice / slice count. */
export function buildSessionInit(
system: string,
config: RealtimeConfig,
@@ -82,7 +82,7 @@ export function buildSessionInit(
return JSON.stringify({ type: 'session.init', payload });
}
-/** 构造 input.append 帧:一段音频(+ 可选强制聆听 / 视频帧)。 */
+/** Build an input.append frame: one audio segment (+ optional force-listen / video frame). */
export function buildInputAppend(
audioBase64: string,
opts: { forceListen?: boolean; videoFrames?: string[] } = {},
@@ -93,38 +93,38 @@ export function buildInputAppend(
return JSON.stringify({ type: 'input.append', input });
}
-/** 构造 session.close 帧(主动挂断)。 */
+/** Build a session.close frame (hang up on purpose). */
export function buildSessionClose(reason: string): string {
return JSON.stringify({ type: 'session.close', reason });
}
/**
- * 模型请求挂断的哨兵串。
+ * Sentinel string for the model requesting a hang-up.
*
- * 线协议里没有"模型想结束通话"这类下行事件(只有客户端发 session.close,或上游通知
- * session.closed),模型说"那我们就先告别啦"只是自然语言、机器读不出意图。这里与模型约定:
- * 确认要结束时在回复末尾输出该标记,前端据此自动挂断,并从展示字幕中剔除标记本身。
+ * The wire protocol has no downlink event for "the model wants to end the call" (only the client sends session.close, or the upstream notifies
+ * session.closed). The model saying "then let's say goodbye for now" is only natural language, and a machine cannot read the intent. The convention with the model is:
+ * when it confirms it should end, it outputs this marker at the end of the reply. The frontend hangs up from that, and strips the marker itself from the displayed caption.
*/
export const HANGUP_MARKER = '[[HANGUP]]';
/**
- * 追加挂断约定到系统提示词。
+ * Append the hang-up convention to the system prompt.
*
- * 约定写在发送时而非用户可见的提示词输入框里:既不干扰用户自己写的场景提示词,
- * 也避免用户误删这段约定导致自动挂断失效。
- * @param system 用户配置的系统提示词
- * @returns 追加了挂断约定的提示词
+ * The convention is written at send time, not in the prompt box the user sees: it does not interfere with the scene prompt the user wrote,
+ * and it also avoids the user deleting this convention by mistake and disabling automatic hang-up.
+ * @param system system prompt configured by the user
+ * @returns the prompt with the hang-up convention appended
*/
export function withHangupProtocol(system: string): string {
return `${system.trim()}\n\n【结束通话约定】当用户明确表示要挂断、结束通话或告别时,先用一句话简短告别,然后在回复的最末尾输出标记 ${HANGUP_MARKER}。除此之外任何情况都不要输出这个标记;不要向用户解释或提及这个标记的存在。`;
}
/**
- * 模型"已答应挂断"的告别语判定词。
+ * Phrases that decide the model "has agreed to hang up".
*
- * 实测 MiniCPM-o **不会**稳定输出 HANGUP_MARKER(它只会用自然语言说"好的,我这就帮你挂断"),
- * 故标记之外必须有这层兜底:命中这些表述即视为模型已答应结束通话。
- * 均为"已在执行/已在告别"的说法,避免"你可以随时挂断"这类**提及**误触发。
+ * Measured behavior: MiniCPM-o does **not** stably output HANGUP_MARKER (it only says in natural language "okay, I'll hang up for you now"),
+ * so there must be this fallback besides the marker: hitting these phrases counts as the model having agreed to end the call.
+ * They are all "already doing it / already saying goodbye" phrasings, so a **mention** such as "you can hang up anytime" does not trigger it.
*/
const HANGUP_PHRASES = [
'帮你挂断',
@@ -143,11 +143,11 @@ const HANGUP_PHRASES = [
];
/**
- * 判断模型回复是否表示"要挂断了"。
+ * Whether the model reply means "about to hang up".
*
- * 双通道:显式标记(模型听话时最准)或告别语兜底(模型不输出标记时仍能工作)。
- * @param text 模型本轮已累积的回复文本
- * @returns 是否应结束通话
+ * Two channels: the explicit marker (most accurate when the model follows instructions) or the goodbye-phrase fallback (still works when the model does not output the marker).
+ * @param text reply text accumulated for this model turn
+ * @returns whether the call should end
*/
export function isHangupIntent(text: string): boolean {
if (text.includes(HANGUP_MARKER)) return true;
@@ -155,16 +155,16 @@ export function isHangupIntent(text: string): boolean {
}
/**
- * 从字幕文本中剥离挂断标记。
- * @param text 模型回复的字幕文本(可能含标记)
- * @returns clean 去掉标记后的展示文本 / hangup 是否应结束通话
+ * Strip the hang-up marker from caption text.
+ * @param text caption text of the model reply (may contain the marker)
+ * @returns clean display text with the marker removed / hangup whether the call should end
*/
export function stripHangupMarker(text: string): { clean: string; hangup: boolean } {
const clean = text.includes(HANGUP_MARKER) ? text.split(HANGUP_MARKER).join('') : text;
return { clean, hangup: isHangupIntent(text) };
}
-/** 解析并归一化一条下行 JSON text frame;解析失败或未知类型 → { kind:'other' }。 */
+/** Parse and normalize one downlink JSON text frame; a parse failure or an unknown type → { kind:'other' }. */
export function parseServerEvent(data: string): ServerEvent {
let msg: RawServerFrame;
try {
@@ -230,14 +230,14 @@ function textEvent(text: unknown, endOfTurn: boolean): ServerEvent {
return typeof text === 'string' && text ? { kind: 'text', text, endOfTurn } : { kind: 'other' };
}
-/** base64 音频字段 → audio 事件;非字符串或空 → other。 */
+/** A base64 audio field → an audio event; a non-string or empty → other. */
function audioEvent(audio: unknown): ServerEvent {
return typeof audio === 'string' && audio.length > 0
? { kind: 'audio', audio }
: { kind: 'other' };
}
-/** 从 error 帧提取可读消息(兼容 error 为对象或字符串)。 */
+/** Extract a readable message from an error frame (compatible with error as an object or a string). */
function errorMessage(msg: RawServerFrame): string {
if (typeof msg.error === 'object' && msg.error?.message) return msg.error.message;
if (typeof msg.error === 'string') return msg.error;
diff --git a/webdemo/frontend/src/pages/playground/utils/refreshAttachmentLinks.ts b/webdemo/frontend/src/pages/playground/utils/refreshAttachmentLinks.ts
index e5651ff..ffc5ec3 100644
--- a/webdemo/frontend/src/pages/playground/utils/refreshAttachmentLinks.ts
+++ b/webdemo/frontend/src/pages/playground/utils/refreshAttachmentLinks.ts
@@ -2,7 +2,7 @@ import { linkPlaygroundFile } from '@/api/map/fileUploads';
import type { ChatMessage } from '../types';
-/** 每次模型请求更新 file-upload 文件的短期链接,历史消息与重新生成共享此流程。 */
+/** Each model request refreshes the short-lived link of a file-upload file; history messages and regenerate share this flow. */
export async function refreshAttachmentLinks(messages: ChatMessage[]): Promise<ChatMessage[]> {
const signed = new Map<string, Promise<string>>();
let lastDivider = -1;
diff --git a/webdemo/frontend/src/pages/playground/utils/runtimeContext.ts b/webdemo/frontend/src/pages/playground/utils/runtimeContext.ts
index 8bbd5a4..c8343d4 100644
--- a/webdemo/frontend/src/pages/playground/utils/runtimeContext.ts
+++ b/webdemo/frontend/src/pages/playground/utils/runtimeContext.ts
@@ -3,11 +3,11 @@ import type { AppLocale } from '@map/store';
import type { PlaygroundRuntimeContext } from '@/api/map/chat';
/**
- * 采集 Playground 请求所需的浏览器上下文提示。
- * @param locale Portal 当前应用语言
- * @param userLocation 用户手动设置的当前位置(用于 datetime 工具回答地点相关问题)
- * @param now 当前浏览器时间,仅用于读取 UTC offset
- * @returns 不包含浏览器当前时刻的时区与语言提示
+ * Collect the browser-context hints a Playground request needs.
+ * @param locale current Portal application language
+ * @param userLocation current location the user set manually (used by the datetime tool to answer location questions)
+ * @param now current browser time, used only to read the UTC offset
+ * @returns timezone and language hints that do not include the browser's current instant
*/
export function collectPlaygroundRuntimeContext(
locale: AppLocale,
diff --git a/webdemo/frontend/src/pages/playground/utils/sendDisabledReason.ts b/webdemo/frontend/src/pages/playground/utils/sendDisabledReason.ts
index 5ec16a3..d623663 100644
--- a/webdemo/frontend/src/pages/playground/utils/sendDisabledReason.ts
+++ b/webdemo/frontend/src/pages/playground/utils/sendDisabledReason.ts
@@ -1,11 +1,11 @@
/**
- * Playground 发送按钮不可用时的可读原因。
+ * Readable reason when the Playground send button is unavailable.
*
- * 用途:把「模型未就绪 / Key 加载 / 无 Key / 解密失败」收敛成一句提示,
- * 避免用户点击发送后看起来没有响应。
+ * Purpose: collapse "model not ready / key loading / no key / decrypt failed" into one notice,
+ * so a click on send does not look like nothing happened.
*/
-/** 判断发送禁用原因所需的最小会话状态 */
+/** Minimum session state needed to decide the send-disabled reason */
export interface SendDisabledState {
modelId: string;
keysLoading: boolean;
@@ -14,15 +14,15 @@ export interface SendDisabledState {
secretReady: boolean;
secretLoading: boolean;
secretError: boolean;
- /** 是否还有任一类免费体验额度;优先使用隐藏体验 Key。 */
+ /** Whether any free-trial quota remains; the hidden trial key is preferred. */
trialAvailable: boolean;
webSearch: boolean;
}
/**
- * 发送不可用时给出明确原因;全部就绪则返回 undefined。
- * @param state 模型与密钥就绪态
- * @param t playground 文案函数
+ * Give a clear reason when send is unavailable; return undefined when everything is ready.
+ * @param state model and secret readiness
+ * @param t playground copy function
*/
export function getSendDisabledReason(
state: SendDisabledState,
diff --git a/webdemo/frontend/src/pages/playground/utils/sse.ts b/webdemo/frontend/src/pages/playground/utils/sse.ts
index 3758ba5..f51f8b6 100644
--- a/webdemo/frontend/src/pages/playground/utils/sse.ts
+++ b/webdemo/frontend/src/pages/playground/utils/sse.ts
@@ -1,60 +1,60 @@
/**
- * SSE(Server-Sent Events)行解析纯函数。
+ * Pure functions that parse SSE (Server-Sent Events) lines.
*
- * 用途:把流式 fetch 累积的文本 buffer 切成完整 SSE 行,并从 OpenAI 兼容 chunk 中
- * 抽取正文增量、思考增量与尾块 usage。无副作用、不依赖 fetch,便于单测。
+ * Purpose: cut the text buffer accumulated by a streaming fetch into complete SSE lines, and from an OpenAI-compatible chunk
+ * extract the body increment, the reasoning increment, and the tail usage. No side effects, no fetch dependency, so they are easy to unit test.
*/
import type { Citation, TokenUsage } from '@/api/map/chat';
-/** 单行 SSE 解析结果 */
+/** Parse result of one SSE line */
export interface SseEvent {
/**
- * chunk = 携带 data JSON 的数据帧;done = `[DONE]` 终止帧;
- * tool_status = 工具进度;citations = 引用来源;request_id = 最终模型调用 ID;
- * moderation = 审核安全回答;error = 带内错误帧。
+ * chunk = a data frame carrying data JSON; done = the `[DONE]` terminal frame;
+ * tool_status = tool progress; citations = citation sources; request_id = the final model-call ID;
+ * moderation = a moderation safety answer; error = an in-band error frame.
*/
type: 'chunk' | 'done' | 'tool_status' | 'citations' | 'request_id' | 'moderation' | 'error';
- /** type=chunk 时的已解析 JSON(解析失败为 undefined) */
+ /** Parsed JSON when type=chunk (undefined when parsing failed) */
data?: unknown;
}
-/** 完整 SSE frame(以空行分隔) */
+/** A complete SSE frame (separated by a blank line) */
export interface SseFrame {
event?: string;
data: string;
}
-/** 从单个 OpenAI chunk 抽出的增量 */
+/** Increment extracted from one OpenAI chunk */
export interface ChunkDeltas {
- /** 正文增量 */
+ /** Body increment */
content: string;
- /** 思考增量 */
+ /** Reasoning increment */
reasoning: string;
- /** 本帧携带的联网引用来源(url_citation annotations,可能为空) */
+ /** Web-search citation sources carried by this frame (url_citation annotations, may be empty) */
citations?: Citation[];
- /** 尾块 usage(仅最后一帧带) */
+ /** Tail usage (present only on the last frame) */
usage?: TokenUsage;
}
/**
- * 把累积 buffer 按换行切成完整行 + 残留未完成片段。
+ * Cut the accumulated buffer into complete lines plus a leftover unfinished fragment, split on newlines.
*
- * @param buffer fetch 累积的解码文本
- * @returns lines 已完整的行(不含换行符);rest 末尾未遇到换行的残片,留待下次拼接
+ * @param buffer decoded text accumulated by fetch
+ * @returns lines that are already complete (without the newline); rest is the trailing fragment that has not seen a newline yet, kept to join next time
*/
export function splitSseLines(buffer: string): { lines: string[]; rest: string } {
const parts = buffer.split('\n');
- // 最后一段可能是不完整行,保留到下次
+ // The last segment may be an incomplete line; keep it until next time
const rest = parts.pop() ?? '';
const lines = parts.map((l) => (l.endsWith('\r') ? l.slice(0, -1) : l));
return { lines, rest };
}
/**
- * 把累积 buffer 按 SSE frame 切分(空行表示一个完整事件)。
- * @param buffer fetch 累积的解码文本
- * @returns frames 完整 frame;rest 末尾未完成片段
+ * Split the accumulated buffer into SSE frames (a blank line means one complete event).
+ * @param buffer decoded text accumulated by fetch
+ * @returns complete frames; rest is the unfinished fragment at the end
*/
export function splitSseFrames(buffer: string): { frames: string[]; rest: string } {
const normalized = buffer.replace(/\r\n/g, '\n');
@@ -63,7 +63,7 @@ export function splitSseFrames(buffer: string): { frames: string[]; rest: string
return { frames: parts, rest };
}
-/** 把 SSE frame 的 event 字段映射为内部事件类型;未声明或未知 event 一律按默认 OpenAI chunk 处理。 */
+/** Map an SSE frame's event field to an internal event type; an undeclared or unknown event is always treated as a default OpenAI chunk. */
function frameEventType(event: string): Exclude<SseEvent['type'], 'done'> {
if (event === 'tool_status') return 'tool_status';
if (event === 'citations') return 'citations';
@@ -74,8 +74,8 @@ function frameEventType(event: string): Exclude<SseEvent['type'], 'done'> {
}
/**
- * 解析完整 SSE frame,支持 event 字段和多行 data。
- * @param frame 不含结尾空行的完整 frame 文本
+ * Parse a complete SSE frame, supporting an event field and multi-line data.
+ * @param frame complete frame text without the trailing blank line
*/
export function parseSseFrame(frame: string): SseEvent | null {
let event = '';
@@ -98,12 +98,12 @@ export function parseSseFrame(frame: string): SseEvent | null {
}
/**
- * 解析单行 SSE。
+ * Parse one SSE line.
*
- * 仅处理 `data:` 前缀的数据行;注释行(`:` 开头,常用于心跳)、空行、其它字段行返回 null。
+ * Only data lines with a `data:` prefix are handled; comment lines (starting with `:`, often used as heartbeats), blank lines, and other field lines return null.
*
- * @param line 单行文本(无换行符)
- * @returns 结构化事件,或 null(应忽略的行)
+ * @param line one line of text (no newline)
+ * @returns a structured event, or null (a line that should be ignored)
*/
export function parseSseLine(line: string): SseEvent | null {
const trimmed = line.trimStart();
@@ -114,24 +114,24 @@ export function parseSseLine(line: string): SseEvent | null {
try {
return { type: 'chunk', data: JSON.parse(data) };
} catch {
- // 不完整/非法 JSON:忽略此帧,避免打断整条流
+ // Incomplete or illegal JSON: ignore this frame so the whole stream is not interrupted
return { type: 'chunk', data: undefined };
}
}
-/** 从未知值安全取正整数字段;缺省或非正数返回 0(视为「没有编号」)。 */
+/** Safely read a positive integer field from an unknown value; a missing or non-positive value returns 0 (treated as "no number"). */
function pickPositiveInt(obj: Record<string, unknown>, key: string): number {
const v = obj[key];
return typeof v === 'number' && Number.isInteger(v) && v > 0 ? v : 0;
}
-/** 从未知值安全取字符串字段 */
+/** Safely read a string field from an unknown value */
function pickString(obj: Record<string, unknown>, key: string): string {
const v = obj[key];
return typeof v === 'string' ? v : '';
}
-/** 仅允许可直接在浏览器新窗口打开的 HTTP(S) 来源。 */
+/** Allow only HTTP(S) sources that can be opened directly in a new browser window. */
function safeCitationURL(value: string): string {
try {
const parsed = new URL(value);
@@ -142,14 +142,14 @@ function safeCitationURL(value: string): string {
}
/**
- * 把 OpenAI 兼容的 annotations 数组归一化为引用来源列表。
+ * Normalize an OpenAI-compatible annotations array into a citation-source list.
*
- * 兼容两种形态:`{type:'url_citation', url_citation:{url,title}}`(OpenAI 官方),
- * 以及部分实现直接 `{url,title}` 的扁平形态。非数组或无有效 url 时返回空数组。
- * 来源编号(ref / index)若有则一并带出,它是角标数字的唯一来源。
+ * Compatible with two shapes: `{type:'url_citation', url_citation:{url,title}}` (official OpenAI),
+ * and the flat `{url,title}` some implementations use directly. Return an empty array when it is not an array or has no valid url.
+ * If a source number (ref / index) is present, carry it along; it is the only source of the citation-marker number.
*
- * @param value delta/message 上的 annotations 原始值
- * @returns 归一化后的引用来源(仅保留含 url 的项)
+ * @param value raw annotations value on delta/message
+ * @returns normalized citation sources (only items that contain a url are kept)
*/
export function normalizeCitations(value: unknown): Citation[] {
if (!Array.isArray(value)) return [];
@@ -157,7 +157,7 @@ export function normalizeCitations(value: unknown): Citation[] {
for (const item of value) {
if (!item || typeof item !== 'object') continue;
const obj = item as Record<string, unknown>;
- // 官方形态:url_citation 子对象;否则退回扁平字段
+ // Official shape: the url_citation child object; otherwise fall back to the flat fields
const src =
obj.url_citation && typeof obj.url_citation === 'object'
? (obj.url_citation as Record<string, unknown>)
@@ -167,9 +167,9 @@ export function normalizeCitations(value: unknown): Citation[] {
const title = pickString(src, 'title');
const snippet =
pickString(src, 'snippet') || pickString(src, 'excerpt') || pickString(src, 'text');
- // 两个出口对同一个编号的字段名不同:体验中心的 citation 事件叫 ref,
- // 公开 API 的 url_citation 叫 index(对齐 OpenAI 的 annotation 形状)。
- // 编号可能挂在 url_citation 子对象上,也可能挂在扁平项上,两处都要看。
+ // The two exits name the same number differently: the experience center's citation event calls it ref,
+ // and the public API's url_citation calls it index (aligned with OpenAI's annotation shape).
+ // The number may hang on the url_citation child object or on the flat item; both places have to be checked.
const ref =
pickPositiveInt(src, 'ref') ||
pickPositiveInt(src, 'index') ||
@@ -186,13 +186,13 @@ export function normalizeCitations(value: unknown): Citation[] {
}
/**
- * 从 OpenAI 兼容 chunk 抽取正文/思考增量与 usage。
+ * Extract the body and reasoning increments and usage from an OpenAI-compatible chunk.
*
- * 思考字段不同模型命名不一,按 `reasoning_content → reasoning → thinking` 顺序兜底取首个非空。
- * usage 仅在尾块出现(后端已强制注入 stream_options.include_usage)。
+ * Reasoning fields are named differently per model; take the first non-empty value in the order `reasoning_content → reasoning → thinking`.
+ * usage appears only on the tail chunk (the backend already forces stream_options.include_usage).
*
- * @param chunk 已 JSON.parse 的 chunk
- * @returns 本帧的正文/思考增量与可选 usage
+ * @param chunk chunk that has already been JSON.parse'd
+ * @returns this frame's body and reasoning increments and optional usage
*/
export function extractDeltas(chunk: unknown): ChunkDeltas {
const empty: ChunkDeltas = { content: '', reasoning: '' };
@@ -214,7 +214,7 @@ export function extractDeltas(chunk: unknown): ChunkDeltas {
pickString(d, 'reasoning_content') ||
pickString(d, 'reasoning') ||
pickString(d, 'thinking');
- // 联网引用可能挂在 delta.annotations(官方)或 delta.citations(部分实现)
+ // A web-search citation may hang on delta.annotations (official) or delta.citations (some implementations)
citations = normalizeCitations(d.annotations ?? d.citations);
}
}
diff --git a/webdemo/frontend/src/pages/playground/utils/thinkSplit.ts b/webdemo/frontend/src/pages/playground/utils/thinkSplit.ts
index 0754195..22064e4 100644
--- a/webdemo/frontend/src/pages/playground/utils/thinkSplit.ts
+++ b/webdemo/frontend/src/pages/playground/utils/thinkSplit.ts
@@ -1,11 +1,11 @@
/**
- * 内联 think 标签流式拆分与一次性归一化。
+ * Streaming split of inline think tags, and one-shot normalization.
*
- * 用途:把模型输出里内联思考段落(think / redacted_thinking / thinking 等标签)
- * 从正文中拆出,路由到 reasoning 通道;供 SSE 流式增量与消息展示层兜底复用。
+ * Purpose: pull inline reasoning paragraphs in model output (tags such as think / redacted_thinking / thinking)
+ * out of the body and route them to the reasoning channel; reused by SSE streaming increments and as a fallback in the message display layer.
*/
-/** 支持的 think 开闭标签对(按常见度排序;流式匹配时取 buffer 内最早出现的开标签) */
+/** Supported think open/close tag pairs (ordered by how common they are; streaming match takes the earliest open tag in the buffer) */
const THINK_TAG_PAIRS: ReadonlyArray<{ open: string; close: string }> = [
{ open: '<think>', close: '</think>' },
{ open: '<redacted_thinking>', close: '</redacted_thinking>' },
@@ -13,10 +13,10 @@ const THINK_TAG_PAIRS: ReadonlyArray<{ open: string; close: string }> = [
];
/**
- * 上游 Agent 偶尔会把内部执行轨迹混入 assistant 文本。
+ * An upstream agent occasionally mixes an internal execution trace into assistant text.
*
- * 这些内容不是面向用户的回答,也不能进入历史上下文;结构化工具状态已经由
- * tool_status/citations 单独承载,因此这里只过滤明确可识别的执行日志。
+ * This content is not an answer for the user, and must not enter history context; structured tool state is already carried
+ * separately by tool_status/citations, so only an execution log that can be recognized clearly is filtered here.
*/
const INTERNAL_EXECUTION_LINE_PATTERNS: ReadonlyArray<RegExp> = [
/^\s*(?:已|正在|刚刚)?查看\s*\d+\s*张(?:图像|图片|截图)/i,
@@ -27,27 +27,27 @@ const INTERNAL_EXECUTION_LINE_PATTERNS: ReadonlyArray<RegExp> = [
/^\s*(?:tool call|function call|read file|view image|open file|searching|searched)\b/i,
];
-/** 只有检测到执行轨迹后才移除的内部开发过程说明,避免误伤正常回答。 */
+/** Internal development-process notes that are removed only after an execution trace is detected, so a normal answer is not damaged by mistake. */
const INTERNAL_PROCESS_LINE_PATTERNS: ReadonlyArray<RegExp> = [
/^\s*(?:我会|接下来我会|现在我会).*(?:工具调用|工具状态|执行日志|过程轨道|重新收成|检查当前实现|补.*测试|运行.*测试|修改.*代码)/i,
];
-/** 内联 think 流式拆分状态 */
+/** Streaming split state for inline think */
export interface ThinkSplitState {
- /** 当前是否处于 think 块内 */
+ /** Whether the parser is currently inside a think block */
inThink: boolean;
- /** 块内时应匹配的闭标签;块外为 null */
+ /** Close tag to match while inside a block; null while outside */
closeTag: string | null;
- /** 末尾可能是半个标签的残片,留待下一分片拼接后再判定 */
+ /** A trailing fragment that may be half a tag, kept to decide again after the next chunk is joined */
pending: string;
}
-/** 新建一条流的 think 拆分状态 */
+/** Create think-split state for a new stream */
export function createThinkSplitState(): ThinkSplitState {
return { inThink: false, closeTag: null, pending: '' };
}
-/** 返回 s 末尾与 tag 前缀相等的最长长度(1..tag.length-1),用于跨分片保留半个标签 */
+/** Longest length (1..tag.length-1) where the end of s equals a prefix of tag, used to keep half a tag across chunks */
function trailingTagPrefixLen(s: string, tag: string): number {
const max = Math.min(s.length, tag.length - 1);
for (let k = max; k >= 1; k -= 1) {
@@ -56,7 +56,7 @@ function trailingTagPrefixLen(s: string, tag: string): number {
return 0;
}
-/** 在 buffer[i..] 中找最早出现的开标签;无则返回 null */
+/** Find the earliest open tag in buffer[i..]; return null when there is none */
function findEarliestOpenTag(
buffer: string,
from: number,
@@ -70,7 +70,7 @@ function findEarliestOpenTag(
return best;
}
-/** 块外:保留 buffer 末尾可能是任意开/闭标签前缀的最长残片 */
+/** Outside a block: keep the longest trailing fragment of buffer that may be a prefix of any open or close tag */
function trailingAnyTagPrefixLen(buffer: string, from: number): number {
let keep = 0;
for (const pair of THINK_TAG_PAIRS) {
@@ -81,9 +81,9 @@ function trailingAnyTagPrefixLen(buffer: string, from: number): number {
}
/**
- * 把一段正文增量按 think 标签拆成「正文」与「思考」两路增量(有状态、可跨 SSE 分片)。
- * @param state 该条流的拆分状态(会被就地更新)
- * @param delta 本帧 delta.content 增量
+ * Split one body increment on think tags into a "body" increment and a "reasoning" increment (stateful, and may cross SSE chunks).
+ * @param state split state of this stream (updated in place)
+ * @param delta this frame's delta.content increment
*/
export function splitThinkDelta(
state: ThinkSplitState,
@@ -132,7 +132,7 @@ export function splitThinkDelta(
return { content, reasoning };
}
-/** 流结束时清空 pending,避免半标签或未闭合 think 吞字 */
+/** On stream end, clear pending so a half tag or an unclosed think does not swallow characters */
export function flushThinkDelta(state: ThinkSplitState): { content: string; reasoning: string } {
const pending = state.pending;
state.pending = '';
@@ -141,8 +141,8 @@ export function flushThinkDelta(state: ThinkSplitState): { content: string; reas
}
/**
- * 对完整字符串一次性拆分 think/正文(无状态,供非流式响应与展示层兜底)。
- * @param text 待拆分全文
+ * Split think and body on a complete string in one pass (stateless, a fallback for non-streaming responses and the display layer).
+ * @param text full text to split
*/
export function splitInlineThinkText(text: string): { content: string; reasoning: string } {
const state = createThinkSplitState();
@@ -165,10 +165,10 @@ function hasInternalExecutionTrace(text: string): boolean {
}
/**
- * 清理正文中可识别的内部执行日志。
+ * Clean recognizable internal execution logs out of the body.
*
- * 返回 detected 供 reasoning 使用:思考字段一旦混入执行轨迹,整段不再展示,
- * 防止只删掉几行后仍泄露文件名、查询词或内部工作说明。
+ * detected is returned for reasoning: once the reasoning field is mixed with an execution trace, the whole segment is no longer shown,
+ * so deleting only a few lines does not still leak a file name, a query, or an internal work note.
*/
function stripInternalExecutionTrace(text: string): { text: string; detected: boolean } {
const detected = hasInternalExecutionTrace(text);
@@ -188,9 +188,9 @@ function stripInternalExecutionTrace(text: string): { text: string; detected: bo
}
/**
- * 归一化 assistant 展示用正文/思考:剥离 content 与 reasoning 中残留的内联 think 标签。
- * @param content 顶层正文
- * @param reasoning 已有思考字段(可为空)
+ * Normalize body and reasoning for assistant display: strip leftover inline think tags from content and reasoning.
+ * @param content top-level body
+ * @param reasoning existing reasoning field (may be empty)
*/
export function normalizeAssistantReply(
content: string,
@@ -200,7 +200,7 @@ export function normalizeAssistantReply(
let fromReasoningField = '';
if (reasoning) {
const splitReasoning = splitInlineThinkText(reasoning);
- // 无内联标签时 split 会把全文落到 content 路,此处应整段视为思考文本
+ // When there is no inline tag, split puts the whole text on the content path; here the whole segment should be treated as reasoning text
fromReasoningField = splitReasoning.reasoning || splitReasoning.content;
}
@@ -210,7 +210,7 @@ export function normalizeAssistantReply(
return {
content: cleanedContent.text,
- // 思考区不展示任何混入内部执行轨迹的原始内容;搜索过程由结构化状态区承载。
+ // The reasoning area does not show any raw content mixed with an internal execution trace; the search process is carried by the structured status area.
reasoning: cleanedReasoning.detected ? '' : rawReasoning,
};
}
diff --git a/webdemo/frontend/src/pages/playground/utils/toolEvents.ts b/webdemo/frontend/src/pages/playground/utils/toolEvents.ts
index d778346..f4dc132 100644
--- a/webdemo/frontend/src/pages/playground/utils/toolEvents.ts
+++ b/webdemo/frontend/src/pages/playground/utils/toolEvents.ts
@@ -3,29 +3,29 @@ import type { ToolStatusEvent } from '@/api/map/chat';
import type { ToolEvent, ToolEventStatus } from '../types';
import { citationURLKey, safeCitationHref } from './citations';
-/** 单条回答最多保留的工具事件数量,避免异常工具循环放大消息体。 */
+/** Maximum number of tool events kept for one answer, so an abnormal tool loop does not inflate the message body. */
export const MAX_TOOL_EVENTS = 32;
-/** 单条工具事件最多保留的来源地址数,与过程行上叠放图标的展示上限对齐。 */
+/** Maximum number of source URLs kept on one tool event, aligned with the display cap of stacked icons on the process row. */
export const MAX_EVENT_CITATION_URLS = 8;
-/** 单条工具事件最多保留的查询词数量,进行中的搜索行只是就地预告,不是完整清单。 */
+/** Maximum number of queries kept on one tool event; an in-progress search row is only an in-place preview, not the full list. */
export const MAX_EVENT_QUERIES = 4;
-/** 顶行最多列出的查询词数:收起态只有这一行,列全会把「正在搜索」本身挤出视野。 */
+/** Maximum number of queries listed on the top row: the collapsed state has only this row, and listing all of them would push "searching" itself out of view. */
const MAX_TITLE_QUERIES = 2;
-/** 顶行单个查询词的字符上限,模型偶尔会把整句话塞进 query。 */
+/** Character cap for one query on the top row; the model occasionally stuffs a whole sentence into query. */
const MAX_TITLE_QUERY_CHARS = 14;
/**
- * 把后端下发的 urls 收敛成可落库的来源地址。
+ * Collapse urls from the backend into source addresses that can be stored.
*
- * 只保留能安全打开的 http(s) 地址,并统一成 citationURLKey 归一化形式——渲染时要拿它去
- * join message.citations 取标题,两边键不一致就永远匹配不上。
+ * Keep only http(s) addresses that can be opened safely, and normalize them to the citationURLKey form — rendering joins
+ * message.citations on that key to get the title, and a mismatched key never matches.
*
- * @param urls 工具事件原始地址
- * @returns 去重且截断后的地址;一个都不剩时返回 undefined(不返回空数组,见 upsertToolEvent 的合并语义)
+ * @param urls raw addresses on the tool event
+ * @returns deduped and truncated addresses; undefined when none remain (do not return an empty array; see the merge semantics of upsertToolEvent)
*/
function normalizeEventUrls(urls?: string[]): string[] | undefined {
if (!urls?.length) return undefined;
@@ -39,10 +39,10 @@ function normalizeEventUrls(urls?: string[]): string[] | undefined {
}
/**
- * 收敛查询词:去空白、去重、截断。
+ * Collapse queries: trim, dedupe, and truncate.
*
- * @param queries 工具事件原始查询词
- * @returns 截断后的查询词;一个都不剩时返回 undefined(空数组会「合法覆盖」掉首帧的值)
+ * @param queries raw queries on the tool event
+ * @returns truncated queries; undefined when none remain (an empty array would "legally overwrite" the first frame's value)
*/
function normalizeEventQueries(queries?: string[]): string[] | undefined {
if (!queries?.length) return undefined;
@@ -56,7 +56,7 @@ function normalizeEventQueries(queries?: string[]): string[] | undefined {
return seen.size > 0 ? [...seen] : undefined;
}
-/** 将后端状态归一化为前端可渲染的工具事件状态。 */
+/** Normalize a backend status into a tool-event status the frontend can render. */
function normalizeToolEventStatus(status?: string): ToolEventStatus {
if (status === 'success' || status === 'failed' || status === 'interrupted') {
return status;
@@ -64,16 +64,16 @@ function normalizeToolEventStatus(status?: string): ToolEventStatus {
return 'running';
}
-/** 为没有 event_id 的旧 SSE 事件生成稳定兼容键。 */
+/** Build a stable compatibility key for an old SSE event that has no event_id. */
export function toolEventKey(event: Pick<ToolStatusEvent, 'event_id' | 'step' | 'tool'>): string {
if (event.event_id) return event.event_id;
return `legacy:${event.step ?? 0}:${event.tool ?? 'unknown'}`;
}
/**
- * 将单个后端工具状态事件转换为前端摘要事件。
- * @param event 后端工具状态事件
- * @param reasoningOffset 该工具首帧到达时已产出的思考字符数,用作过程时间线的切分点
+ * Turn one backend tool-status event into a frontend summary event.
+ * @param event backend tool-status event
+ * @param reasoningOffset reasoning character count already produced when this tool's first frame arrived, used as the process-timeline split point
*/
export function toToolEvent(event: ToolStatusEvent, reasoningOffset?: number): ToolEvent {
const queryCount = event.queries?.length;
@@ -97,11 +97,11 @@ export function toToolEvent(event: ToolStatusEvent, reasoningOffset?: number): T
}
/**
- * 将工具状态追加或合并到事件列表。
- * @param events 当前事件列表
- * @param incoming 后端工具状态事件
- * @param reasoningOffset 思考切分点,仅在该事件首次出现时采用
- * @returns 不超过上限且保持时间顺序的事件列表
+ * Append or merge a tool status into the event list.
+ * @param events current event list
+ * @param incoming backend tool-status event
+ * @param reasoningOffset reasoning split point, used only the first time this event appears
+ * @returns an event list that stays within the cap and keeps time order
*/
export function upsertToolEvent(
events: ToolEvent[],
@@ -124,11 +124,11 @@ export function upsertToolEvent(
pageCount: nextEvent.pageCount ?? current.pageCount,
durationMs: nextEvent.durationMs ?? current.durationMs,
message: nextEvent.message ?? current.message,
- // 地址取"有就覆盖、没有就留着":web_extractor 的 running 与 success 两帧都带 urls,
- // 而 normalizeEventUrls 在一个都不剩时给 undefined,不会拿空值抹掉首帧的结果。
+ // Addresses use "overwrite when present, keep when absent": both the running and success frames of web_extractor carry urls,
+ // and normalizeEventUrls returns undefined when none remain, so it does not wipe the first frame's result with an empty value.
citationUrls: nextEvent.citationUrls ?? current.citationUrls,
- // 切分点必须锚在工具"开始"的那一刻,所以 current 优先:success 帧比 running 帧晚几秒,
- // 用它重算会把这期间流出的思考错划到工具行之前。
+ // The split point must be anchored at the moment the tool "starts", so current wins: the success frame arrives seconds after the running frame,
+ // and recomputing from it would place the reasoning that streamed in during that gap before the tool row.
reasoningOffset: current.reasoningOffset ?? nextEvent.reasoningOffset,
};
const result = [...events];
@@ -137,17 +137,17 @@ export function upsertToolEvent(
}
/**
- * 取出当前进行中的搜索查询词,供过程区顶行做动态摘要。
+ * Take the search queries currently in progress, for a live summary on the top row of the process area.
*
- * 顶行是收起态唯一在场的进度通道,而一轮搜索几秒起步。期间它若一直是静态的「正在搜索」,
- * 用户无从判断是真在跑还是卡住了——展开态的工具行早就把查询词逐个显示了(见 ProcessToolRow
- * 的 RunningQueries),收起时这条信息却整个消失,只剩一个转圈图标。
+ * The top row is the only progress channel present in the collapsed state, and one search takes several seconds to start. If it stayed a static "Searching" the whole time,
+ * the user could not tell whether it was really running or stuck — the expanded tool row has long shown queries one by one (see RunningQueries
+ * in ProcessToolRow), but while collapsed that information disappears entirely and only a spinner remains.
*
- * 不按工具名过滤:带 queries 的只有搜索类工具(web_extractor 的 running 帧带的是 urls),
- * 用字段在不在判断既够用,也不必让本模块反向依赖 answerTimeline 的 WEB_TOOLS。
+ * Do not filter by tool name: only search tools carry queries (web_extractor's running frame carries urls),
+ * so checking whether the field is present is enough, and this module does not have to depend back on answerTimeline's WEB_TOOLS.
*
- * @param events 当前工具事件列表
- * @returns 去首尾空白、按长度截断后的查询词;没有进行中的搜索时返回空数组
+ * @param events current tool-event list
+ * @returns queries with surrounding whitespace removed and truncated by length; an empty array when no search is in progress
*/
export function runningSearchQueries(events: ToolEvent[]): string[] {
const queries: string[] = [];
@@ -167,7 +167,7 @@ export function runningSearchQueries(events: ToolEvent[]): string[] {
return queries;
}
-/** 将生命周期结束时仍运行的事件统一落为指定终态。 */
+/** Settle events that are still running when the lifecycle ends to the given terminal state. */
export function finalizeToolEvents(
events: ToolEvent[],
status: Extract<ToolEventStatus, 'failed' | 'interrupted'>,
diff --git a/webdemo/frontend/src/pages/playground/utils/ttsVoices.ts b/webdemo/frontend/src/pages/playground/utils/ttsVoices.ts
index d69fef1..06c051b 100644
--- a/webdemo/frontend/src/pages/playground/utils/ttsVoices.ts
+++ b/webdemo/frontend/src/pages/playground/utils/ttsVoices.ts
@@ -1,58 +1,58 @@
/**
- * 体验中心「语音合成」音色目录、参考音频加载与合成参数常量。
+ * Voice catalog, reference-audio loading, and synthesis-parameter constants for experience-center "speech synthesis".
*
- * 用途:VoxCPM 是零样本克隆模型,无命名音色库——音色只能来自参考音频(ref_audio),且上游对未知
- * voice 直接 4xx,故请求恒发 voice=default。「预置示范音色」与「上传复刻」底层同为一条 ref_audio
- * 路,仅音频来源不同:默认音色(不带 ref_audio)/ 预置音色(内置 wav → data URI)/ 上传复刻
- * (用户上传 → data URI)。本模块提供音色目录、「预置 wav → data URI」的加载与合成参数常量。纯前端。
+ * Purpose: VoxCPM is a zero-shot clone model and has no named voice library — a voice can come only from reference audio (ref_audio), and the upstream
+ * returns 4xx directly for an unknown voice, so the request always sends voice=default. "Preset demo voices" and "upload a clone" are the same ref_audio
+ * path underneath, and differ only in where the audio comes from: the default voice (no ref_audio) / a preset voice (built-in wav → data URI) / an uploaded clone
+ * (user upload → data URI). This module provides the voice catalog, loading of "preset wav → data URI", and synthesis-parameter constants. Frontend only.
*/
import type { MapVoiceResource } from '@/api/map';
import { arrayBufferToBase64, blobToPcm16kBase64 } from './audioEncode';
-/** 上传复刻哨兵值:选中后展示上传控件,ref_audio 来自用户上传 */
+/** Sentinel for an uploaded clone: once selected, show the upload control, and ref_audio comes from the user upload */
export const VOICE_UPLOAD = '__upload__';
-/** 默认音色值:不带 ref_audio,走上游默认发音 */
+/** Default voice value: no ref_audio, and the upstream default pronunciation is used */
export const VOICE_DEFAULT = 'default';
-/** 参考音频解码后大小上限(5 MiB,对齐 LIS 契约 §4.5,超限上游返回 413) */
+/** Size cap for decoded reference audio (5 MiB, aligned with LIS contract §4.5; over the limit the upstream returns 413) */
export const REF_AUDIO_MAX_BYTES = 5 * 1024 * 1024;
-/** 示例文案 */
+/** Example copy */
export const TTS_SAMPLES = [
'欢迎来到面壁智能 API 平台,这里可以体验语音合成的自然表现力。',
'今天天气晴朗,微风拂面,正适合出门散步、感受大自然的美好。',
'尊敬的用户您好,您的订单已发货,预计三天内送达,请注意查收。',
];
-/** 合成文本上限 */
+/** Synthesis text cap */
export const TTS_MAX_LEN = 2000;
-/** 引导强度(cfg_value)范围:越高越贴合提示/参考音色,越低越自由(对齐官方 1.0–3.0) */
+/** Guidance strength (cfg_value) range: higher sticks closer to the prompt and reference voice, lower is freer (aligned with the official 1.0–3.0) */
export const TTS_CFG_MIN = 1;
export const TTS_CFG_MAX = 3;
export const TTS_CFG_STEP = 0.1;
export const TTS_CFG_DEFAULT = 2;
-/** 参考音频时长上限(秒),对齐官方 VoxCPM2 demo 的 50s */
+/** Reference-audio duration cap (seconds), aligned with the official VoxCPM2 demo's 50s */
export const TTS_REF_MAX_SECONDS = 50;
-/** 一个可选音色 */
+/** One selectable voice */
export interface TtsVoice {
value: string;
label: string;
- /** 预置音色的参考音频地址(相对 public,经 BASE_URL 前缀);默认/上传项为空 */
+ /** Reference-audio URL of a preset voice (relative to public, prefixed by BASE_URL); empty for the default and upload items */
refPath?: string;
}
/**
- * 判断私有音色是否已完成归属校验。
+ * Whether a private voice has finished its ownership check.
*
- * @param voice 当前选择值
- * @param savedVoices 当前登录用户可见的音色
- * @param listLoaded 音色列表是否已成功加载
- * @returns 预置音色始终可用;私有音色只有在列表成功加载且命中时才可提交
+ * @param voice current selection
+ * @param savedVoices voices visible to the currently logged-in user
+ * @param listLoaded whether the voice list loaded successfully
+ * @returns a preset voice is always usable; a private voice can be submitted only when the list loaded successfully and it is in the list
*/
export function isSavedVoiceReady(
voice: string,
@@ -63,7 +63,7 @@ export function isSavedVoiceReady(
return listLoaded && savedVoices.some((savedVoice) => savedVoice.id === voice);
}
-/** 权限收回或私有音色失效时,将当前选择收敛到可安全提交的音色。 */
+/** When permission is revoked or a private voice is no longer valid, collapse the current selection to a voice that can be submitted safely. */
export function resolveTtsVoice(
voice: string,
canUseCustomVoice: boolean,
@@ -84,9 +84,9 @@ export function resolveTtsVoice(
}
/**
- * 音色目录:默认音色 + 预置示范音色 + 上传复刻。
- * value 仅作前端选择器标识,**不进请求体**(请求恒发 voice=default);音色差异全靠 refPath 指向的参考音频。
- * 预置素材放在 portal `public/voices/`,运营补充素材时在此追加即可。
+ * Voice catalog: default voice + preset demo voices + uploaded clone.
+ * value is only a frontend picker id and **does not enter the request body** (the request always sends voice=default); voice differences come entirely from the reference audio refPath points at.
+ * Preset assets live in portal `public/voices/`; when operations adds an asset, append it here.
*/
export const TTS_VOICES: TtsVoice[] = [
{ value: VOICE_DEFAULT, label: 'voiceDefault' },
@@ -96,11 +96,11 @@ export const TTS_VOICES: TtsVoice[] = [
];
/**
- * 返回当前模式可展示的预置音色。
+ * Return the preset voices the current mode can show.
*
- * @param mode 普通生成或上传复刻模式
- * @param canUseCustomVoice 当前用户是否可使用自定义音色入口
- * @returns 普通生成始终包含默认和预置音色;上传复刻仅对获授权用户展示
+ * @param mode ordinary generation, or upload-a-clone mode
+ * @param canUseCustomVoice whether the current user may use the custom-voice entry
+ * @returns ordinary generation always includes the default and preset voices; upload-a-clone is shown only to an authorized user
*/
export function ttsVoicesForMode(
mode: 'generate' | 'clone',
@@ -110,7 +110,7 @@ export function ttsVoicesForMode(
return canUseCustomVoice ? TTS_VOICES.filter((voice) => voice.value === VOICE_UPLOAD) : [];
}
-/** 权限在页面停留期间被收回时立即回退普通生成,避免继续显示自定义音色控件。 */
+/** When permission is revoked while the page stays open, fall back to ordinary generation immediately, so the custom-voice control is not kept on screen. */
export function resolveTtsMode(
mode: 'generate' | 'clone',
canUseCustomVoice: boolean,
@@ -118,18 +118,18 @@ export function resolveTtsMode(
return mode === 'clone' && !canUseCustomVoice ? 'generate' : mode;
}
-/** 预置音色参考音频的 data URI 缓存(避免重复合成时反复 fetch 同一素材) */
+/** data-URI cache of preset-voice reference audio (so repeated synthesis does not fetch the same asset again) */
const refCache = new Map<string, string>();
const realtimeRefCache = new Map<string, string>();
/**
- * 加载预置音色的参考音频并转为 `data:audio/wav;base64,...`。
+ * Load a preset voice's reference audio and convert it to `data:audio/wav;base64,...`.
*
- * 选 data URI 而非直传 URL:契约只接受内联 Base64 WAV,不接受任何 URL(上游不会去拉取外部地址)。
- * 素材超过 5 MiB 会被上游 413 拒绝,故此处先行拦截给出可读文案。
- * @param refPath public 相对路径(如 `voices/demo-a.wav`)
- * @returns 可作 ref_audio 传入的 data URI
- * @throws Error 素材加载失败或超过大小上限(含可读文案)
+ * A data URI is chosen over passing a URL through: the contract accepts only an inline Base64 WAV, and no URL (the upstream will not fetch an external address).
+ * An asset over 5 MiB is rejected by the upstream with 413, so it is blocked here first with readable copy.
+ * @param refPath path relative to public (such as `voices/demo-a.wav`)
+ * @returns a data URI that can be passed as ref_audio
+ * @throws Error when the asset fails to load or exceeds the size cap (with readable copy)
*/
export async function fetchRefAudioDataUri(refPath: string): Promise<string> {
const cached = refCache.get(refPath);
@@ -147,10 +147,10 @@ export async function fetchRefAudioDataUri(refPath: string): Promise<string> {
}
/**
- * 加载并转换实时双工参考音频为 16kHz mono 裸 float32 PCM base64。
+ * Load and convert realtime duplex reference audio to 16kHz mono raw float32 PCM base64.
*
- * @param refPath public 相对路径
- * @returns 符合 Realtime voice 协议的参考音频 base64
+ * @param refPath path relative to public
+ * @returns reference-audio base64 that matches the Realtime voice protocol
*/
export async function fetchRealtimeRefAudioBase64(refPath: string): Promise<string> {
const cached = realtimeRefCache.get(refPath);
@@ -163,28 +163,28 @@ export async function fetchRealtimeRefAudioBase64(refPath: string): Promise<stri
return base64;
}
-// ---------- 声音描述(Control Instruction) ----------
+// ---------- Voice description (Control Instruction) ----------
-/** 声音描述哨兵值:不使用(自然发音,不注入 control 前缀)。
- * 注意用非空串——Radix Select 的 SelectItem value 不允许空字符串(空串专用于清空选择显示占位)。 */
+/** Voice-description sentinel: none (natural pronunciation, no control prefix injected).
+ * Must be a non-empty string — Radix Select's SelectItem value does not allow an empty string (the empty string is reserved for clearing the selection and showing the placeholder). */
export const CONTROL_NONE = 'none';
-/** 声音描述哨兵值:自定义(展开输入框,用户自由填写) */
+/** Voice-description sentinel: custom (expand the input, and the user types freely) */
export const CONTROL_CUSTOM = '__custom__';
-/** 一个声音描述预设 */
+/** One voice-description preset */
export interface ControlPreset {
value: string;
label: string;
- /** 声音描述文本(以 `(control)` 前缀注入 input);哨兵项为空串 */
+ /** Voice-description text (injected into input with a `(control)` prefix); empty for sentinel items */
control: string;
- /** 配套示例目标文案(选中预设时一并填入合成文本,便于快速试听) */
+ /** Matching example target copy (filled into the synthesis text when a preset is selected, so it can be previewed quickly) */
sampleText?: string;
}
/**
- * 声音描述预设目录:不使用 / 若干风格预设 / 自定义。
- * 预设文本对齐官方 VoxCPM2 demo 的声音描述示例(含方言);运营可在此追加。
+ * Voice-description preset catalog: none / several style presets / custom.
+ * Preset text is aligned with the official VoxCPM2 demo's voice-description examples (including dialects); operations can append more here.
*/
export const TTS_CONTROL_PRESETS: ControlPreset[] = [
{ value: CONTROL_NONE, label: 'voiceControlNone', control: '' },
@@ -221,16 +221,16 @@ export const TTS_CONTROL_PRESETS: ControlPreset[] = [
{ value: CONTROL_CUSTOM, label: 'voiceControlCustom', control: '' },
];
-/** 一条声音描述用法示例(用于「查看示例」弹窗,对齐官方示例与方言指南) */
+/** One voice-description usage example (for the "view examples" dialog, aligned with the official examples and dialect guide) */
export interface ControlExample {
title: string;
control: string;
targetText: string;
- /** 方言项:错误示范(普通话原文),与 targetText 对比说明「方言要写方言词句」 */
+ /** Dialect item: a wrong example (Mandarin original), contrasted with targetText to show "a dialect must be written in dialect wording" */
wrongText?: string;
}
-/** 声音描述示例(对齐官方 demo:角色扮演 + 方言生成指南) */
+/** Voice-description examples (aligned with the official demo: role-play + dialect generation guide) */
export const TTS_CONTROL_EXAMPLES: ControlExample[] = [
{
title: 'voiceExampleEmpress',
diff --git a/webdemo/frontend/src/pages/playground/utils/webSearchCapability.ts b/webdemo/frontend/src/pages/playground/utils/webSearchCapability.ts
index aafbc8a..9a000a0 100644
--- a/webdemo/frontend/src/pages/playground/utils/webSearchCapability.ts
+++ b/webdemo/frontend/src/pages/playground/utils/webSearchCapability.ts
@@ -1,14 +1,14 @@
import type { MapModel } from '@/api/map';
/**
- * 判断当前模型是否允许 Playground 联网搜索。
+ * Whether the current model is allowed to use Playground web search.
*
- * 必须两个能力位同时具备,与后端入口(playground_web_search_http.go / l2_web_search_http.go)
- * 保持一致:托管搜索循环靠模型发 tool_calls 驱动,只勾 web_search 却不支持函数调用的模型
- * 不会真去检索,而是照着工具说明捏造一次调用再编出结果。少判一位的后果不是报错,
- * 而是用户拿到一个带假引用的、看起来很正经的回答。
- * @param capabilities 当前模型能力配置
- * @returns 当前模型是否可以展示并使用联网搜索
+ * Both capability bits must be present, consistent with the backend entries (playground_web_search_http.go / l2_web_search_http.go):
+ * the hosted search loop is driven by the model emitting tool_calls. A model with only web_search checked, and no function calling,
+ * will not actually search; it fabricates one call from the tool description and then makes up a result. Missing one bit does not surface as an error,
+ * and the user instead gets a serious-looking answer with fake citations.
+ * @param capabilities capability config of the current model
+ * @returns whether the current model may show and use web search
*/
export function canUsePlaygroundWebSearch(
capabilities: MapModel['capabilities'] | undefined,
diff --git a/webdemo/frontend/src/providers/QueryProvider.tsx b/webdemo/frontend/src/providers/QueryProvider.tsx
index ab373a6..8e74777 100644
--- a/webdemo/frontend/src/providers/QueryProvider.tsx
+++ b/webdemo/frontend/src/providers/QueryProvider.tsx
@@ -2,18 +2,18 @@ import { useState, type PropsWithChildren } from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
/**
- * 创建全局 QueryClient 的默认配置。
+ * Default configuration for the global QueryClient.
*
- * 用途:统一服务端状态(server state)的缓存与重试策略,避免各处 useState+useEffect
- * 手撸请求(硬规则 #4)。配置原则——
- * - staleTime 0:进入/切回页面(组件挂载)即视为过期并后台重拉,保证拿到最新数据;
- * 仍先展示缓存不闪烁。需要更长缓存的读(如当前用户、验证码配置)在各自 useQuery 里单独设 staleTime 覆盖。
- * - gcTime 5min:卸载后缓存保留 5 分钟,切回时先用缓存占位再后台刷新。
- * - retry 1:失败只自动重试 1 次;与 axios-retry(请求层 2 次)分层,避免叠加放大。
- * - refetchOnWindowFocus false:切回标签页不自动重拉,避免长表单/长列表抖动。
+ * Purpose: one cache and retry policy for server state, instead of hand-rolled useState and useEffect
+ * requests everywhere (hard rule #4). Principles:
+ * - staleTime 0: entering or returning to a page (component mount) treats data as stale and refetches in the background, so the latest data is fetched;
+ * cached data is still shown first, without a flash. Reads that need a longer cache (such as the current user or captcha config) override staleTime in their own useQuery.
+ * - gcTime 5min: after unmount the cache is kept for 5 minutes; coming back shows the cache first, then refreshes in the background.
+ * - retry 1: a failure retries automatically once; layered with axios-retry (2 retries in the request layer) so they do not stack and amplify.
+ * - refetchOnWindowFocus false: switching back to the tab does not refetch, so long forms and long lists do not jump.
*
- * 注意:BizError(业务错误码)已在请求层 reject,这里的 retry 仅对网络/超时类错误生效更合理;
- * 如需对 BizError 不重试,可在 retry 传函数按 error 类型判定。
+ * Note: BizError (business error codes) is already rejected in the request layer, so retry here fits network and timeout errors better;
+ * to skip retries for BizError, pass a function to retry and decide by error type.
*/
export function createQueryClient(): QueryClient {
return new QueryClient({
@@ -32,13 +32,13 @@ export function createQueryClient(): QueryClient {
}
/**
- * 全局 Query Provider。
+ * Global Query Provider.
*
- * 用途:在 host 壳层包裹整棵应用树,向 host 自身页面与所有 remote 提供同一个
- * QueryClient(配合联邦 singleton 的 react,远程组件可直接用 useQuery)。
+ * Purpose: wrap the whole app tree in the host shell and give the host pages and every remote the same
+ * QueryClient (with the federated React singleton, a remote component can call useQuery directly).
*
- * 用 useState 惰性初始化 client,保证每个浏览器会话只创建一个实例,
- * 不随 React 重渲染重建(重建会清空所有缓存)。
+ * The client is created lazily with useState so each browser session has one instance,
+ * and React re-renders do not rebuild it (rebuilding would drop every cache).
*/
export function QueryProvider({ children }: PropsWithChildren) {
const [client] = useState(createQueryClient);
diff --git a/webdemo/frontend/src/router/breadcrumb.ts b/webdemo/frontend/src/router/breadcrumb.ts
index 3d289db..0cc2f5f 100644
--- a/webdemo/frontend/src/router/breadcrumb.ts
+++ b/webdemo/frontend/src/router/breadcrumb.ts
@@ -2,11 +2,11 @@ import type { AppRoute } from '@map/types';
export interface BreadcrumbItem {
title: string;
- /** 用于链接;最后一项也可点击跳转当前完整路径 */
+ /** Used for the link; the last item can also be clicked to jump to the current full path. */
path: string;
}
-/** 在父路由的 children 中匹配当前 pathname(精确优先,其次最长前缀) */
+/** Match the current pathname among a parent route’s children (exact match first, then the longest prefix). */
function findMatchingChild(parent: AppRoute, pathname: string): AppRoute | undefined {
const children = parent.children;
if (!children?.length) {
@@ -32,7 +32,7 @@ function findMatchingChild(parent: AppRoute, pathname: string): AppRoute | undef
}
/**
- * 根据 pathname 与静态路由树生成面包屑(含侧边栏 children 子路由标题)。
+ * Build breadcrumbs from the pathname and the static route tree (including child-route titles in the sidebar).
*/
export function getBreadcrumbItems(pathname: string, routes: AppRoute[]): BreadcrumbItem[] {
const items: BreadcrumbItem[] = [{ title: '首页', path: '/' }];
diff --git a/webdemo/frontend/src/router/guard.tsx b/webdemo/frontend/src/router/guard.tsx
index 244b71a..d0c1057 100644
--- a/webdemo/frontend/src/router/guard.tsx
+++ b/webdemo/frontend/src/router/guard.tsx
@@ -4,10 +4,10 @@ import { getToken } from '@/api/map';
import { whiteList } from './constants';
/**
- * 登录守卫:照搬老 portal 的判定——以 `localStorage['map_token']` 是否存在判断登录态。
+ * Login guard: mirrors the old portal — logged in when `localStorage['map_token']` exists.
*
- * 用途:未登录访问受保护路由时跳转 `/login`。MAP 鉴权由后端 `platform_role` 实时判定,
- * 前端无内置角色/权限体系,故守卫只判断 token 是否存在,不做权限码校验。
+ * Purpose: an unauthenticated visit to a protected route redirects to `/login`. MAP auth is decided live by the backend `platform_role`;
+ * the frontend has no built-in role or permission system, so the guard only checks that a token exists and does not check permission codes.
*/
export function AuthGuard({ children }: PropsWithChildren) {
const location = useLocation();
diff --git a/webdemo/frontend/src/router/phone-binding-guard.tsx b/webdemo/frontend/src/router/phone-binding-guard.tsx
index 0cf35f1..baa848d 100644
--- a/webdemo/frontend/src/router/phone-binding-guard.tsx
+++ b/webdemo/frontend/src/router/phone-binding-guard.tsx
@@ -5,11 +5,11 @@ import { mapAuthApi, mapKeys } from '@/api/map';
import { PageLoading } from '@/components/PageLoading';
/**
- * Portal 强制绑定手机号守卫。
+ * Portal guard that requires a bound mobile number.
*
- * 用途:邮箱认证且没有手机号的会话只能进入绑定页;后端中间件同时做接口级兜底。
- * @param children 已通过手机号绑定检查后渲染的页面
- * @returns 绑定检查中的加载态、绑定页跳转或业务页面
+ * Purpose: an email-authenticated session with no mobile number can only enter the binding page; backend middleware also enforces this on the API.
+ * @param children Pages rendered after the mobile-number check passes.
+ * @returns A loading state while checking, a redirect to the binding page, or the business page.
*/
export function PhoneBindingGuard({ children }: PropsWithChildren) {
const location = useLocation();
diff --git a/webdemo/frontend/src/router/prefetch.ts b/webdemo/frontend/src/router/prefetch.ts
index 880f1a6..2d09e6e 100644
--- a/webdemo/frontend/src/router/prefetch.ts
+++ b/webdemo/frontend/src/router/prefetch.ts
@@ -1,36 +1,36 @@
import { routePrefetchers } from './routes';
-// 记录已触发预加载的前缀,避免重复发起请求
+// Remember prefixes that already triggered a preload, so the request is not sent again.
const prefetched = new Set<string>();
/**
- * 根据路径前缀找到对应的页面预加载工厂 key。
- * @param path 目标路径(如 /keys、/models)
- * @returns 匹配到的前缀 key,未匹配返回 undefined
+ * Find the page preload factory key for a path prefix.
+ * @param path Target path (for example /keys or /models).
+ * @returns The matched prefix key, or undefined when nothing matches.
*/
function matchPrefix(path: string): string | undefined {
return Object.keys(routePrefetchers).find((key) => path === key || path.startsWith(`${key}/`));
}
/**
- * 预加载指定路径对应的页面 chunk(若有)。
- * 幂等:同一页面只会触发一次;import() 自带模块缓存,后续真正渲染时瞬时命中。
- * @param path 目标路由路径,通常为侧边栏菜单的 to
+ * Preload the page chunk for a path, when one exists.
+ * Idempotent: each page triggers once; import() caches the module, so the later real render hits instantly.
+ * @param path Target route path, usually the sidebar menu’s to.
*/
export function prefetchRoute(path: string): void {
const key = matchPrefix(path);
if (!key || prefetched.has(key)) return;
prefetched.add(key);
- // 预加载失败不影响主流程(真正点击时会再次尝试并走重试逻辑),静默吞掉
+ // A preload failure does not affect the main flow (a real click tries again and goes through retry), so swallow it.
routePrefetchers[key]().catch(() => {
prefetched.delete(key);
});
}
/**
- * 在浏览器空闲时依次预加载全部业务页面,消除首次切换的等待感。
- * 逐个排队而非并发,避免与首屏关键资源争抢带宽。
- * @returns 清理函数,用于在卸载时取消尚未执行的空闲任务
+ * Preload every business page one by one while the browser is idle, so the first switch does not wait.
+ * Queue them instead of fetching concurrently, so they do not compete with critical first-screen resources for bandwidth.
+ * @returns A cleanup function that cancels idle tasks not yet run on unmount.
*/
export function prefetchAllRoutesOnIdle(): () => void {
const keys = Object.keys(routePrefetchers);
diff --git a/webdemo/frontend/src/router/routeCopy.ts b/webdemo/frontend/src/router/routeCopy.ts
index d620614..8ad6a0b 100644
--- a/webdemo/frontend/src/router/routeCopy.ts
+++ b/webdemo/frontend/src/router/routeCopy.ts
@@ -27,10 +27,10 @@ const ROUTE_COPY: Record<PortalLocale, Record<string, string>> = {
};
/**
- * 根据当前语言返回门户路由显示名称。
- * @param path 路由路径。
- * @param locale 当前界面语言。
- * @param fallback 路由元数据中的默认名称。
+ * Return the portal route display name for the current language.
+ * @param path Route path.
+ * @param locale Current UI language.
+ * @param fallback Default name from route metadata.
*/
export function getPortalRouteTitle(path: string, locale: PortalLocale, fallback: string): string {
return ROUTE_COPY[locale][path] ?? fallback;
diff --git a/webdemo/frontend/src/utils/__tests__/money.test.ts b/webdemo/frontend/src/utils/__tests__/money.test.ts
index 99f145b..e40e6ba 100644
--- a/webdemo/frontend/src/utils/__tests__/money.test.ts
+++ b/webdemo/frontend/src/utils/__tests__/money.test.ts
@@ -1,9 +1,9 @@
/**
- * 积分换算与展示格式化(money.ts)单测:
- * - formatPoints:账本金额按 1:1 展示为固定两位积分 + 千分位;
- * - formatPointsPerMillion:定价按 1:1 展示为固定两位小数积分/1M;
- * - formatPointsQuota:可空额度 NullDecimal → 积分或「不限」。
- * 约束:1 元 = 1 积分,展示层不做换算。
+ * Points conversion and display formatting tests (money.ts):
+ * - formatPoints: ledger amounts are shown 1:1 as points with two fixed decimals plus thousands separators;
+ * - formatPointsPerMillion: pricing is shown 1:1 as points per 1M with two fixed decimals;
+ * - formatPointsQuota: a nullable NullDecimal quota becomes points or "unlimited".
+ * Constraint: 1 yuan = 1 point, and the display layer does not convert.
*/
import { describe, it, expect } from 'vitest';
diff --git a/webdemo/frontend/src/utils/lazyWithRetry.ts b/webdemo/frontend/src/utils/lazyWithRetry.ts
index e8922c6..6b7b2e0 100644
--- a/webdemo/frontend/src/utils/lazyWithRetry.ts
+++ b/webdemo/frontend/src/utils/lazyWithRetry.ts
@@ -1,8 +1,8 @@
/**
- * 动态模块加载失败时按递增延时重试,并保留默认导出的完整类型。
- * @param factory 动态导入函数
- * @param retries 首次失败后的最大重试次数
- * @returns 加载成功的模块;重试耗尽后交由调用方错误边界处理
+ * Retry a failed dynamic module load with increasing delay, and keep the full type of the default export.
+ * @param factory Dynamic import function.
+ * @param retries Maximum retries after the first failure.
+ * @returns The loaded module; when retries are exhausted, the caller’s error boundary handles it.
*/
export function lazyWithRetry<T>(
factory: () => Promise<{ default: T }>,
diff --git a/webdemo/frontend/src/utils/locale.ts b/webdemo/frontend/src/utils/locale.ts
index 72eb2e7..9a58d1a 100644
--- a/webdemo/frontend/src/utils/locale.ts
+++ b/webdemo/frontend/src/utils/locale.ts
@@ -1,16 +1,16 @@
-/** 门户支持的界面语言。 */
+/** UI languages the portal supports. */
export type PortalLocale = 'zh-CN' | 'en-US';
-/** 全局语言状态写入函数。 */
+/** Writer for the global language state. */
export type LocaleSetter = (locale: PortalLocale) => void;
/**
- * 保存新语言并主动刷新当前页面。
+ * Save the new language and reload the current page.
*
- * 用途:让依赖初始化文案、图表和第三方组件的页面在同一语言下重新挂载,避免局部中英混排。
- * @param locale 目标语言。
- * @param setLocale 全局语言状态写入函数。
- * @param reload 页面刷新函数,便于单元测试替换。
+ * Purpose: remount pages that depend on copy, charts, and third-party components initialized for one language, so Chinese and English are not mixed in one view.
+ * @param locale Target language.
+ * @param setLocale Writer for the global language state.
+ * @param reload Page reload function, replaceable in unit tests.
*/
export function switchLocaleAndReload(
locale: PortalLocale,
diff --git a/webdemo/frontend/src/utils/modelExperience.ts b/webdemo/frontend/src/utils/modelExperience.ts
index b57aa0c..9ee5e1e 100644
--- a/webdemo/frontend/src/utils/modelExperience.ts
+++ b/webdemo/frontend/src/utils/modelExperience.ts
@@ -1,28 +1,28 @@
/**
- * 体验中心的模型分类工具。
+ * Model classification helpers for the Playground.
*
- * 用途:后端返回同一份「全量可调用模型」,前端按管理端配置的能力位筛选四类体验:
- * - tts:勾了「语音合成」,走 /v1/audio/speech
- * - realtime:勾了「实时对话」,走 /v1/realtime
- * - image-parse:勾了「图像解析」且支持图像输入,走 Chat Completions 做图像 → Markdown
- * - language:普通对话模型,以及同时支持文本输入的图像解析模型
- * 支持文本输入的图像解析模型可同时出现在语言对话与图像解析列表中。
+ * Purpose: the backend returns one list of "all callable models", and the frontend filters four experiences from capability flags configured in admin:
+ * - tts: "speech synthesis" is checked, and it uses /v1/audio/speech
+ * - realtime: "realtime conversation" is checked, and it uses /v1/realtime
+ * - image-parse: "image parse" is checked and image input is supported; Chat Completions turns an image into Markdown
+ * - language: ordinary chat models, plus image-parse models that also accept text input
+ * An image-parse model that accepts text can appear in both the language chat list and the image-parse list.
*
- * 判定**只认 capabilities**(管理端显式勾选、migration 0032 已归一存量数据),不再按模型名
- * 关键词猜测——改个模型名就分错、新接入模型必须改代码,都是关键词方案的老毛病。
- * 模型没进对体验,就去管理台把能力位勾上。
+ * The decision trusts capabilities only (explicitly checked in admin; migration 0032 already normalized existing data), and no longer guesses from model-name
+ * keywords — a renamed model landing in the wrong place, and every new model requiring a code change, were the old problems with keywords.
+ * If a model is in the wrong experience, check the capability flag in the admin console.
*/
import type { MapModel } from '@/api/map';
-/** 模型在体验中心的类别 */
+/** A model’s experience category in the Playground. */
export type ModelExperience = 'language' | 'tts' | 'realtime' | 'image-parse';
/**
- * 体验中心分流所依据的能力 key(管理端「能力支持」里勾选,与后端门禁同名)。
- * - speech_synthesis:语音合成(历史数据里叫 audio_speech,见 migration 0032)
- * - realtime_dialog:实时对话
- * - document_parse:图像 → Markdown 解析;必须同时具备 input_image,避免纯文本模型误入
+ * Capability keys the Playground uses to route models (checked under admin "capability support", same names as the backend gate).
+ * - speech_synthesis: speech synthesis (called audio_speech in historical data; see migration 0032)
+ * - realtime_dialog: realtime conversation
+ * - document_parse: image → Markdown parsing; input_image is also required so a text-only model is not admitted
*/
export const EXPERIENCE_CAPABILITY_KEYS = {
speechSynthesis: 'speech_synthesis',
@@ -31,12 +31,12 @@ export const EXPERIENCE_CAPABILITY_KEYS = {
} as const;
/**
- * 判断模型是否启用指定协议。
+ * Whether a model has a given protocol enabled.
*
- * `protocols` 为空数组时明确表示未定义协议;字段缺失时兼容旧后端,按历史默认协议处理。
- * @param model 单个可调用模型
- * @param protocol 目标协议
- * @returns 是否支持该协议
+ * An empty `protocols` array means no protocol is defined; when the field is missing, stay compatible with older backends and use the historical default protocol.
+ * @param model One callable model.
+ * @param protocol Target protocol.
+ * @returns Whether that protocol is supported.
*/
export function modelSupportsProtocol(
model: MapModel,
@@ -48,16 +48,16 @@ export function modelSupportsProtocol(
}
/**
- * speech_synthesis 归一前的历史 key。migration 0032 会把它改写掉,
- * 但迁移与前端发版存在时间差,兼容期一并认,避免语音合成体验短时空列表。
+ * Historical key from before speech_synthesis was normalized. Migration 0032 rewrites it,
+ * but migration and the frontend release can be apart in time, so the compatibility window accepts both and the speech-synthesis experience does not briefly show an empty list.
*/
const LEGACY_SPEECH_KEY = 'audio_speech';
/**
- * 判定单个模型的主要体验类别,供接入示例选择协议。
- * 同时具备时:实时优先于语音合成;图像解析模型仍可按文本能力进入语言对话列表。
- * @param model 单个可调用模型
- * @returns 该模型所属体验类别
+ * Decide one model’s primary experience category, so integration examples can pick a protocol.
+ * When several apply: realtime wins over speech synthesis; an image-parse model can still enter the language chat list by its text capability.
+ * @param model One callable model.
+ * @returns The experience category that model belongs to.
*/
export function classifyModel(model: MapModel): ModelExperience {
const caps = model.capabilities;
@@ -68,10 +68,10 @@ export function classifyModel(model: MapModel): ModelExperience {
}
/**
- * 取某一体验类别下的全部可选模型(保持后端返回顺序)。
- * @param models 全量可调用模型
- * @param experience 目标体验类别
- * @returns 该类别下的模型列表,可能为空
+ * All selectable models in one experience category (keeps the backend order).
+ * @param models All callable models.
+ * @param experience Target experience category.
+ * @returns Models in that category; may be empty.
*/
export function modelsByExperience(models: MapModel[], experience: ModelExperience): MapModel[] {
return models.filter((m) => {
@@ -89,19 +89,19 @@ export function modelsByExperience(models: MapModel[], experience: ModelExperien
}
/**
- * 语言对话可选模型(排除语音合成、实时对话及未声明文本输入的图像解析模型)。
- * @param models 全量可调用模型
- * @returns 仅语言对话模型
+ * Models selectable for language chat (excludes speech synthesis, realtime conversation, and image-parse models that do not declare text input).
+ * @param models All callable models.
+ * @returns Language-chat models only.
*/
export function languageModels(models: MapModel[]): MapModel[] {
return modelsByExperience(models, 'language');
}
/**
- * 判定模型是否正处于免费调用期(后端按定价时间窗实时计算)。
- * 免费模型对所有用户免费调用,体验中心据此展示「免费」标签。
- * @param model 单个可调用模型
- * @returns 是否限时免费
+ * Whether a model is currently in its free-call window (the backend computes this live from the pricing window).
+ * A free model is free for every user, and the Playground shows a "Free" tag from this.
+ * @param model One callable model.
+ * @returns Whether it is free for a limited time.
*/
export function isFreeModel(model: MapModel): boolean {
return Boolean(model.is_free);
diff --git a/webdemo/frontend/src/utils/money.ts b/webdemo/frontend/src/utils/money.ts
index 4f679ae..076d92e 100644
--- a/webdemo/frontend/src/utils/money.ts
+++ b/webdemo/frontend/src/utils/money.ts
@@ -1,15 +1,15 @@
/**
- * 金额 / 额度展示格式化工具。
+ * Amount and quota display formatting.
*
- * 后端金额为高精度 numeric 字符串(如 "12.34000000"),直接展示尾部零冗余。
- * 这里统一裁掉无意义的尾零,并对空/非法值给出占位。
+ * Backend amounts are high-precision numeric strings (for example "12.34000000"); showing them raw leaves trailing zeros.
+ * Strip meaningless trailing zeros here, and use a placeholder for empty or invalid values.
*/
import type { AppLocale } from '@map/store';
/**
- * 格式化金额为两位小数,用于余额、花费等展示场景。
- * @param value 高精度金额字符串;空/非法时返回 "0.00"
- * @returns 两位小数的金额文本
+ * Format an amount to two decimal places, for balances, spend, and similar display.
+ * @param value High-precision amount string; empty or invalid returns "0.00".
+ * @returns Amount text with two decimal places.
*/
export function formatMoney(value?: string | null): string {
if (value == null || value === '') return '0.00';
@@ -19,9 +19,9 @@ export function formatMoney(value?: string | null): string {
}
/**
- * 格式化固定 4 位小数金额,适用于模型定价等需要精度显式展示的价格场景。
- * @param value 高精度金额字符串;空/非法时返回 "0.0000"
- * @returns 固定 4 位小数的金额文本
+ * Format an amount to a fixed 4 decimal places, for prices such as model pricing that should show precision explicitly.
+ * @param value High-precision amount string; empty or invalid returns "0.0000".
+ * @returns Amount text with a fixed 4 decimal places.
*/
export function formatMoneyFixed4(value?: string | null): string {
if (value == null || value === '') return '0.0000';
@@ -31,9 +31,9 @@ export function formatMoneyFixed4(value?: string | null): string {
}
/**
- * 格式化可空额度(后端 NullDecimal:{ Decimal, Valid })。
- * @param quota NullDecimal 结构;未设置时表示「不限」
- * @returns 额度文本或「不限」
+ * Format a nullable quota (backend NullDecimal: { Decimal, Valid }).
+ * @param quota NullDecimal value; unset means "unlimited".
+ * @returns Quota text, or "unlimited".
*/
export function formatQuota(quota?: { Decimal: string; Valid: boolean } | null): string {
if (!quota || !quota.Valid) return '不限';
@@ -41,7 +41,7 @@ export function formatQuota(quota?: { Decimal: string; Valid: boolean } | null):
}
/**
- * 账本金额与积分保持 1:1;对外只展示积分,不再进行兑换换算。
+ * Ledger amounts and points stay 1:1; only points are shown, with no exchange conversion.
*/
function parsePoints(value?: string | null): number | null {
if (value == null || value === '') return null;
@@ -51,10 +51,10 @@ function parsePoints(value?: string | null): number | null {
}
/**
- * 格式化余额 / 花费为固定两位小数积分并添加千分位。
- * 模型调用的单次消耗可能小于 1 积分,仍按统一精度展示。
- * @param value 高精度元金额字符串;空/非法时返回 "0"
- * @returns 带千分位的积分文本(不含单位)
+ * Format a balance or spend as points with two fixed decimal places and thousands separators.
+ * A single model call can cost less than 1 point and is still shown at the same precision.
+ * @param value High-precision yuan amount string; empty or invalid returns "0".
+ * @returns Points text with thousands separators (no unit).
*/
export function formatPoints(value?: string | null, locale: AppLocale = 'zh-CN'): string {
const pts = parsePoints(value);
@@ -63,10 +63,10 @@ export function formatPoints(value?: string | null, locale: AppLocale = 'zh-CN')
}
/**
- * 格式化模型定价为「积分 / 1M tokens」,统一固定两位小数。
- * 零值、空值或非法值代表未配置可计费价格,统一展示为「-」。
- * @param value 高精度元单价字符串(每 1M tokens)
- * @returns 积分单价文本(不含单位)或「-」
+ * Format model pricing as "points / 1M tokens", always with two decimal places.
+ * Zero, empty, or invalid means no billable price is configured, and is shown as "-".
+ * @param value High-precision yuan unit price string (per 1M tokens).
+ * @returns Points unit-price text (no unit), or "-".
*/
export function formatPointsPerMillion(
value?: string | null,
@@ -78,9 +78,9 @@ export function formatPointsPerMillion(
}
/**
- * 格式化可空额度为积分(后端 NullDecimal);未设置表示「不限」。
- * @param quota NullDecimal 结构
- * @returns 积分文本或「不限」
+ * Format a nullable quota as points (backend NullDecimal); unset means "unlimited".
+ * @param quota NullDecimal value.
+ * @returns Points text, or "unlimited".
*/
export function formatPointsQuota(quota?: { Decimal: string; Valid: boolean } | null): string {
if (!quota || !quota.Valid) return '不限';
diff --git a/webdemo/frontend/src/utils/preloadErrorRecovery.ts b/webdemo/frontend/src/utils/preloadErrorRecovery.ts
index b14a9a1..9f86069 100644
--- a/webdemo/frontend/src/utils/preloadErrorRecovery.ts
+++ b/webdemo/frontend/src/utils/preloadErrorRecovery.ts
@@ -26,8 +26,8 @@ export function installPreloadErrorRecovery(
// Storage can be unavailable in privacy-restricted browser contexts.
}
- // 未刷新时保留原始 import 错误;拦截后 Vite 会以 undefined 完成 Promise,
- // React.lazy 随后读取 default 才会产生误导性的 TypeError。
+ // Until a reload, keep the original import error; after interception Vite fulfills the Promise with undefined,
+ // and React.lazy only then reads default and throws a misleading TypeError.
if (shouldReload) {
event.preventDefault();
reload();
diff --git a/webdemo/frontend/src/utils/validators.ts b/webdemo/frontend/src/utils/validators.ts
index a19dd77..76cfad3 100644
--- a/webdemo/frontend/src/utils/validators.ts
+++ b/webdemo/frontend/src/utils/validators.ts
@@ -1,23 +1,23 @@
/**
- * 认证相关的格式校验工具。
+ * Format checks for authentication.
*
- * 用途:登录、绑定/换绑邮箱等表单提交前做前置格式校验,避免无效请求打到后端。
- * 仅做格式层面的轻校验,真正的归属校验仍以后端验证码/查重为准。
+ * Purpose: a format check before submit on login, bind-email, and change-email forms, so invalid requests never reach the backend.
+ * This is only a light format check; real ownership is still decided by the backend verification code or uniqueness check.
*/
/**
- * 邮箱格式校验(简化 RFC:本地名@域名.顶级域)。
- * @param email 待校验邮箱
- * @returns 是否为合法邮箱格式
+ * Email format check (simplified RFC: [email protected]).
+ * @param email Email to check.
+ * @returns Whether it is a valid email format.
*/
export function isValidEmail(email: string): boolean {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
}
/**
- * 中国大陆手机号格式校验(11 位,1 开头,第二位 3-9)。
- * @param phone 待校验手机号
- * @returns 是否为合法手机号格式
+ * Mainland China mobile number format check (11 digits, starts with 1, second digit 3-9).
+ * @param phone Phone number to check.
+ * @returns Whether it is a valid mobile number format.
*/
export function isValidPhone(phone: string): boolean {
return /^(?:\+86)?1[3-9]\d{9}$/.test(phone.trim());
diff --git a/webdemo/frontend/vite-env.d.ts b/webdemo/frontend/vite-env.d.ts
index 74fb341..cec388e 100644
--- a/webdemo/frontend/vite-env.d.ts
+++ b/webdemo/frontend/vite-env.d.ts
@@ -7,7 +7,7 @@ interface ImportMetaEnv {
readonly VITE_API_DEBUG?: string;
readonly VITE_USER_CLIENT_ID: string;
readonly VITE_CHAT_BASE_URL?: string;
- /** 文档解析接口基址。设为 `/` 时走当前站点,由开发服务器转发到本机工人。 */
+ /** Document parsing API base. When set to `/`, requests stay on the current site and the dev server forwards them to the local worker. */
readonly VITE_OCR_API_BASE?: string;
readonly VITE_AUTH_PROFILE?: 'legacy' | 'gcp';
readonly VITE_COOKIE_CONSENT_ENABLED?: 'true' | 'false';
diff --git a/webdemo/frontend/vite.config.ts b/webdemo/frontend/vite.config.ts
index 9c132d4..01f7c72 100644
--- a/webdemo/frontend/vite.config.ts
+++ b/webdemo/frontend/vite.config.ts
@@ -3,13 +3,13 @@ import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react';
import { viteStaticCopy } from 'vite-plugin-static-copy';
-/** 前端源码根目录,供 `@/` 路径别名解析 */
+/** Frontend source root, used to resolve the `@/` path alias. */
const srcDir = fileURLToPath(new URL('./src', import.meta.url));
/**
- * 解析站点静态标题(<title> 与 og:title),在构建期定死写入 index.html。
- * 链接预览爬虫不执行 JS、只读原始 HTML,故标题无法靠运行时 i18n 切换,必须在构建期按环境注入。
- * 优先级:显式 VITE_APP_TITLE > 构建期默认标题。
+ * Resolve the static site title (<title> and og:title) and write it into index.html at build time.
+ * Link-preview crawlers do not run JS and only read the raw HTML, so the title cannot switch with runtime i18n and must be injected per environment at build time.
+ * Priority: an explicit VITE_APP_TITLE, then the build-time default title.
*/
function resolveAppTitle(): string {
const explicit = process.env.VITE_APP_TITLE?.trim();
@@ -18,8 +18,8 @@ function resolveAppTitle(): string {
}
/**
- * html-app-title:把 index.html 里的 %VITE_APP_TITLE% 占位替换为构建期解析出的标题。
- * order:'pre' 确保先于 Vite 内置的 %ENV% 替换执行,替换结果唯一确定。
+ * html-app-title: replace the %VITE_APP_TITLE% placeholder in index.html with the title resolved at build time.
+ * order: 'pre' runs before Vite’s built-in %ENV% replacement, so the result is determined in one place.
*/
function htmlAppTitlePlugin() {
const title = resolveAppTitle();
@@ -34,7 +34,7 @@ function htmlAppTitlePlugin() {
};
}
-// 免登录演示:独立部署在根路径,打开后直接进入 Playground。
+// Login-free demo: deployed on its own at the root path, and opens straight into the Playground.
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, fileURLToPath(new URL('.', import.meta.url)), '');
for (const [key, value] of Object.entries(env)) {
@@ -45,7 +45,7 @@ export default defineConfig(({ mode }) => {
plugins: [
react(),
htmlAppTitlePlugin(),
- // PDF 的 CJK 字体映射与解码资源同源部署,预览不依赖第三方 CDN。
+ // PDF CJK font maps and decode assets are served from the same origin, so preview does not depend on a third-party CDN.
viteStaticCopy({
targets: ['cmaps', 'standard_fonts', 'wasm'].map((directory) => ({
src: fileURLToPath(new URL(`./node_modules/pdfjs-dist/${directory}`, import.meta.url)),
@@ -64,6 +64,14 @@ export default defineConfig(({ mode }) => {
target: process.env.VITE_OCR_TARGET ?? 'http://127.0.0.1:8966',
changeOrigin: true,
},
+ '/api/image-parse': {
+ target: process.env.VITE_OCR_TARGET ?? 'http://127.0.0.1:8966',
+ changeOrigin: true,
+ },
+ '/api/kie': {
+ target: process.env.VITE_OCR_TARGET ?? 'http://127.0.0.1:8966',
+ changeOrigin: true,
+ },
'/v1': {
target: process.env.VITE_OCR_TARGET ?? 'http://127.0.0.1:8966',
changeOrigin: true,
@@ -78,6 +86,14 @@ export default defineConfig(({ mode }) => {
target: process.env.VITE_OCR_TARGET ?? 'http://127.0.0.1:8966',
changeOrigin: true,
},
+ '/api/image-parse': {
+ target: process.env.VITE_OCR_TARGET ?? 'http://127.0.0.1:8966',
+ changeOrigin: true,
+ },
+ '/api/kie': {
+ target: process.env.VITE_OCR_TARGET ?? 'http://127.0.0.1:8966',
+ changeOrigin: true,
+ },
'/v1': {
target: process.env.VITE_OCR_TARGET ?? 'http://127.0.0.1:8966',
changeOrigin: true,
@@ -91,15 +107,15 @@ export default defineConfig(({ mode }) => {
cssCodeSplit: true,
rollupOptions: {
output: {
- // 手动拆分第三方依赖:稳定的运行时(react 全家桶)与重型可视化库(recharts)
- // 各自独立成 chunk,既提升长期缓存命中率,又能与业务 chunk 并行下载。
+ // Split third-party dependencies by hand: the stable runtime (the React family) and the heavy chart library (recharts)
+ // each become their own chunk, which improves long-term cache hits and can download in parallel with app chunks.
manualChunks(id) {
if (!id.includes('node_modules')) return undefined;
- // recharts 及其依赖的 d3-* / victory-* 体积大且仅图表页用,单独成块
+ // recharts and its d3-* / victory-* dependencies are large and only the chart pages use them, so they get their own chunk.
if (/[\\/]node_modules[\\/](recharts|d3-|victory-|internmap|decimal\.js)/.test(id)) {
return 'chart-vendor';
}
- // React 运行时三件套放同一 chunk,避免跨块初始化顺序问题
+ // The three React runtime packages share one chunk, so initialization order does not break across chunks.
if (
/[\\/]node_modules[\\/](react|react-dom|react-router|react-router-dom|scheduler)[\\/]/.test(
id,
@@ -107,7 +123,7 @@ export default defineConfig(({ mode }) => {
) {
return 'react-vendor';
}
- // 服务端状态库独立,便于单独缓存
+ // The server-state library stands alone, so it can be cached separately.
if (/[\\/]node_modules[\\/]@tanstack[\\/]/.test(id)) {
return 'query-vendor';
}