Jelajahi Sumber

feat(ui,ledger): 界面可视化验证与修复 + 数据面台账补齐

用 Edge 无头模式真实渲染四个页面并截图(docs/images/),据此修掉一批只在真实
浏览器里才暴露的问题,同时补齐"数据面台账没记录 data_read"的实现缺口。

数据面台账(Python)
- data_read / customs_process 接受 BFF 传入的 call_id、session_id,按同一 call_id
  写入数据面台账(调用级 + 行级 value_index);此前只有 calculator 会记录
- stat 对象的 bytes 改为统计整次运行目录的真实占用(原为 0,界面显示 0 B)
- 新增 2 项接口测试覆盖上述记账行为

前端
- 新增 hash 路由:#/chat、#/process、#/files、#/system 可直连/刷新/截图;
  BFF 对未知无扩展名路径回退 index.html,对缺失的 /assets/* 改为 404
- 历史消息现在也显示溯源 chip(此前只有流式过程中显示)
- 处理页打开时自动加载最近一次成功结果,右侧不再空白
- 工具卡片:无行数时显示摘要(如"2 个对象"),失败时显示原因
- 年度/月度/排名列不再加千分位(2025 不再显示成 2,025)
- 文件页"规模"列区分原始数据(N 行)与统计结果(23 表 · N 行)
- 系统页分别展示数据面台账与会话台账的调用数/索引值数

文档
- README 与使用手册加入四张界面截图与界面导览
- 架构文档补充两本台账的写入口径;实现说明补充前端路由与首屏性能

测试
- Python 85、BFF 54、前端 23、端到端 28 项,合计 190 项全部通过
California 4 hari lalu
induk
melakukan
2326996475

+ 14 - 4
README.md

@@ -22,6 +22,16 @@
 
 ---
 
+## 界面
+
+| 对话问数(数字带溯源 chip + 核验结论) | 数据处理(23 张结果表 + 预览/图表) |
+|---|---|
+| ![对话](docs/images/01-chat.png) | ![数据处理](docs/images/02-process.png) |
+
+| 文件(原始数据 / 统计结果) | 系统(Harness、工具、台账) |
+|---|---|
+| ![文件](docs/images/03-files.png) | ![系统](docs/images/04-system.png) |
+
 ## 2. 整体架构
 
 ```text
@@ -71,8 +81,8 @@ CustomesDataAgent/
 │  ├─ toolsvc/calc.py          #   calculator(带输入溯源)
 │  ├─ toolsvc/readers.py       #   data_read(SQL 过滤/排序/聚合)
 │  ├─ toolsvc/api.py           #   HTTP 接口
-│  └─ tests/                   #   83 项单元与接口测试
-├─ web/                        # React 前端(22 项单测:格式化 + 组件渲染)
+│  └─ tests/                   #   85 项单元与接口测试
+├─ web/                        # React 前端(23 项单测:格式化 + 组件渲染)
 ├─ scripts/                    # start/stop/e2e/run_tests/样本数据生成
 ├─ deploy/                     # Dockerfile + docker-compose(单镜像一键部署)
 ├─ samples/                    # 可复现的测试数据集 + 预言机(expected.json)
@@ -98,9 +108,9 @@ CustomesDataAgent/
 
 | 测试组 | 数量 | 命令 |
 |---|---|---|
-| Python 引擎与接口(pytest) | 83 | `cd tools-service && python -m pytest tests/` |
+| Python 引擎与接口(pytest) | 85 | `cd tools-service && python -m pytest tests/` |
 | BFF 单元与接口(node:test) | 54 | `cd bff && npm run build && node --test "dist/test/*.test.js"` |
-| 前端单元 + 渲染(vitest) | 22 | `cd web && npx vitest run` |
+| 前端单元 + 渲染(vitest) | 23 | `cd web && npx vitest run` |
 | 端到端联调(真实服务 + 真实模型) | 28 项检查 | `node scripts/e2e.mjs` |
 
 一条命令全跑:

+ 4 - 0
bff/dist/src/harness/tools/index.js

@@ -96,6 +96,8 @@ export function createCustomsTools(options) {
                 operation,
                 params: args.options ?? {},
                 output_filename: args.output_filename ? String(args.output_filename) : undefined,
+                call_id: context.callId,
+                session_id: context.sessionId,
             });
             const sheets = result.sheets.map((sheet) => ({ table: sheet.name, rows: sheet.rows, columns: sheet.columns.slice(0, 20) }));
             return {
@@ -172,6 +174,8 @@ export function createCustomsTools(options) {
                 limit,
                 offset: Number(args.offset ?? 0) || 0,
                 aggregate: args.aggregate ?? undefined,
+                call_id: context.callId,
+                session_id: context.sessionId,
             });
             const rows = result.rows.map((row) => ({
                 values: row.values,

File diff ditekan karena terlalu besar
+ 0 - 0
bff/dist/src/harness/tools/index.js.map


File diff ditekan karena terlalu besar
+ 0 - 0
bff/dist/src/tools/client.js.map


+ 5 - 1
bff/src/harness/tools/index.ts

@@ -1,4 +1,4 @@
-/**
+/**
  * 四个海关工具的定义(DSH `ctx.tools.register(defineTool({...}))` 形态)。
  *
  * 设计约束:
@@ -108,6 +108,8 @@ export function createCustomsTools(options: ToolFactoryOptions): ToolDefinition[
         operation,
         params: (args.options as Record<string, unknown>) ?? {},
         output_filename: args.output_filename ? String(args.output_filename) : undefined,
+        call_id: context.callId,
+        session_id: context.sessionId,
       });
       const sheets = result.sheets.map((sheet) => ({ table: sheet.name, rows: sheet.rows, columns: sheet.columns.slice(0, 20) }));
       return {
@@ -185,6 +187,8 @@ export function createCustomsTools(options: ToolFactoryOptions): ToolDefinition[
         limit,
         offset: Number(args.offset ?? 0) || 0,
         aggregate: (args.aggregate as Record<string, unknown>) ?? undefined,
+        call_id: context.callId,
+        session_id: context.sessionId,
       });
 
       const rows: ToolRow[] = result.rows.map((row) => ({

+ 6 - 1
bff/src/tools/client.ts

@@ -1,4 +1,4 @@
-/** Python 工具服务的 HTTP 客户端(BFF 与工具层之间唯一的通信通道)。 */
+/** Python 工具服务的 HTTP 客户端(BFF 与工具层之间唯一的通信通道)。 */
 import { settings } from '../config.js';
 import { HttpError, logger } from '../util/common.js';
 
@@ -67,6 +67,9 @@ export interface DataReadPayload {
   limit?: number;
   offset?: number;
   aggregate?: Record<string, unknown>;
+  /** 由工具层传入,让 Python 台账用同一个 call_id 记录 */
+  call_id?: string;
+  session_id?: string;
 }
 
 export class ToolsClient {
@@ -218,6 +221,8 @@ export class ToolsClient {
     operation?: string;
     params?: Record<string, unknown>;
     output_filename?: string;
+    call_id?: string;
+    session_id?: string;
   }): Promise<{
     run_id: string;
     object_id: string;

+ 8 - 0
docs/01-架构设计.md

@@ -150,6 +150,14 @@ BFF、前端、其他工具**只**依赖 `contract.py` 里的类型;替换实
 
 两者都由同一批工具返回值写入,口径一致;会话台账只保留本次会话的字段值,避免跨会话误命中。
 
+具体写入口径:
+
+* 数据面台账:BFF 把 `call_id` / `session_id` 一起传给工具服务,`data_read`(行级 + 调用级)、
+  `customs_process`(对象+血缘摘要)、`calculator`(结果+输入)都会记录,哈希链按 `prev_hash` 串起来,
+  同时追加 `data/ledger.jsonl`,可用 `/ledger/export` 离线导出复核;
+* 会话台账:BFF 在每次工具返回后写,除了每行的字段值,还包括工具返回里的**标量**
+  (`total_matching_rows`、`stats.included`、`sheet_count` 等),所以模型引用"共 20 行"这类数字也算有来源。
+
 ---
 
 ## 5. 与 DeepSeek Harness 的关系

+ 7 - 1
docs/02-实现说明.md

@@ -1,4 +1,4 @@
-# 实现说明(全部实现细节)
+# 实现说明(全部实现细节)
 
 > 本文是实现级文档:模块职责、数据结构、接口契约、指标口径、配置项、性能与坑。
 > 想看"为什么这么设计"看 [01-架构设计.md](01-架构设计.md);想让业务同事上手看 [03-使用手册.md](03-使用手册.md)。
@@ -152,6 +152,11 @@ verifications(id, session_id, message_id, verdict, payload, created_at)
 
 ## 3. HTTP 接口
 
+### 3.0 前端路由(hash)
+
+`#/chat`、`#/process`、`#/files`、`#/system` 四个页面用 URL hash 切换,
+可直接分享/刷新/被自动化截图;BFF 对未知的无扩展名路径回退 `index.html`,对缺失的 `/assets/*` 返回 404。
+
 ### 3.1 BFF(对外,端口 8787)
 
 | 方法 | 路径 | 说明 |
@@ -426,6 +431,7 @@ systemPrompt: |
 | 完整处理(23 张表) | 1,064 行原始数据 → 11,747 行结果 | ≈ 12 s |
 | 完整处理 | 10,571 行原始数据 | ≈ 40 s |
 | `data_read` 单次查询 | 任一结果表 | < 50 ms |
+| 前端首屏 | 262 KB JS(gzip 82 KB) | < 1 s(本地) |
 | BFF 启动 | — | < 1 s |
 
 优化点(做过的事):

+ 11 - 1
docs/03-使用手册.md

@@ -1,4 +1,4 @@
-# 使用手册(零基础版)
+# 使用手册(零基础版)
 
 > 这份手册假设你**完全没有接触过这个项目**,也没写过代码。照着做就行。
 > 全程大约 20 分钟,其中大部分时间在等安装。
@@ -133,6 +133,8 @@
 
 ### 3.4 认识界面
 
+![对话问数](images/01-chat.png)
+
 左边是侧边栏,从上到下:
 
 - **工作区**:一个工作区 = 一个独立的文件柜(不同项目 / 不同批次的数据分开放);
@@ -141,6 +143,14 @@
 
 ---
 
+### 3.5 四个页面长这样
+
+| 页面 | 截图 |
+|---|---|
+| 数据处理:左边选文件与参数,右边是 23 张结果表,下面是预览(可切"图表") | ![数据处理](images/02-process.png) |
+| 文件:拖拽上传,列出原始数据与统计结果(含行数、大小、表清单) | ![文件](images/03-files.png) |
+| 系统:Harness、Agent Preset、工具、模型提供方、两本台账的状态 | ![系统](images/04-system.png) |
+
 ## 4. 第一次处理数据
 
 ### 4.1 准备一份数据

+ 13 - 8
docs/05-测试报告.md

@@ -21,11 +21,11 @@
 
 | 测试组 | 用例数 | 结果 | 覆盖 |
 |---|---|---|---|
-| Python 引擎与接口(pytest) | **83** | 全部通过 | 数值/权重、规则解析、入库与周四归月、23 张报表口径、对象库、血缘、`data_read`、`calculator`、台账、HTTP 接口 |
+| Python 引擎与接口(pytest) | **85** | 全部通过 | 数值/权重、规则解析、入库与周四归月、23 张报表口径、对象库、血缘、`data_read`、`calculator`、台账、HTTP 接口 |
 | BFF 单元与接口(node:test) | **54** | 全部通过 | YAML 解析、Preset、数字抽取、核验裁决、工具注册与 `finalizeContent`、Agent Loop、HTTP 接口、SSE 对话、multipart |
-| 前端单元 + 渲染(vitest) | **22** | 全部通过 | 数值/百分比/时间格式化、表名分类、图表数据构造、列推断,以及用 SSR 渲染 App / 消息 / 核验面板 / Markdown 组件 |
+| 前端单元 + 渲染(vitest) | **23** | 全部通过 | 数值/百分比/时间格式化、表名分类、图表数据构造、列推断,以及用 SSR 渲染 App / 消息 / 核验面板 / Markdown 组件 |
 | 端到端联调(真实服务 + 真实模型) | **28 项检查** | 全部通过(连续 3 次) | 上传→处理→23 表→预览→血缘→下载→指数口径→自定义聚合→台账→**真实模型对话 + 核验**→前端托管 |
-| **合计** | **187** | **全部通过** | |
+| **合计** | **190** | **全部通过** | |
 
 一键复现:
 
@@ -44,7 +44,7 @@ node scripts/e2e.mjs                                     # 端到端
 
 ---
 
-## 3. Python 测试(83 项)
+## 3. Python 测试(85 项)
 
 ### 3.1 `test_numbers.py`(10)
 
@@ -103,12 +103,13 @@ sum/mean/median/min/max/count/growth/ratio/index/share 正确性;
 过滤+排序、`contains`、聚合模式、未知列报错、limit 上限、预览、行级血缘、
 谓词反推(`build_predicate`)、删除对象连带删文件、台账字段反查、哈希链一致。
 
-### 3.7 `test_api.py`(12)
+### 3.7 `test_api.py`(14)
 
 `/health`、`/meta`、工作区生命周期、上传+预览、`data_read` 工具、非法列 400、
 `calculator` 工具、**同步 `customs_process`(返回 23 张表 + 血缘 + 文件清单)**、
 异步 run(`custom_aggregate`)进度到 1.0、非法 operation 400、
-坏数据返回可读失败原因(422 + `缺少必需字段`)、`/objects/:id/file` 下载与路径穿越防护、台账接口。
+坏数据返回可读失败原因(422 + `缺少必需字段`)、`/objects/:id/file` 下载与路径穿越防护、台账接口,
+以及**数据面台账记账**(`data_read` / `customs_process` 带 `call_id` 时写入调用级与行级记录)。
 
 ---
 
@@ -155,7 +156,7 @@ Agent Loop 完整一轮(工具调用→结果回灌→最终答案,且第二
 
 ---
 
-## 5. 前端测试(22 项)
+## 5. 前端测试(23 项)
 
 `formatNumber`(千分位/小数/空值)、`formatPercent`、`formatBytes`、
 `relativeTime`(刚刚/分钟/小时/天/日期)、`classifySheet`(MLCC 四层级、存储器、补充表、raw)、
@@ -167,7 +168,11 @@ Agent Loop 完整一轮(工具调用→结果回灌→最终答案,且第二
 溯源 chip 的 title、Markdown(粗体/列表/表格)。目的是在**不需要浏览器**的情况下捕获
 组件层的 import 错误与渲染异常。
 
-另有 `tsc --noEmit` 类型检查与 `vite build` 生产构建(产物 262 KB,gzip 82 KB)。
+另有 `tsc --noEmit` 类型检查与 `vite build` 生产构建(产物 263 KB,gzip 82 KB)。
+
+**可视化验证**:用 Edge 无头模式真实渲染四个页面并截图(`docs/images/`),
+确认了工具卡片、溯源 chip、核验面板、23 张结果表清单、预览表格(表格/图表切换)与台账数字都能正常显示;
+期间修正了「年度显示成 2,025」「stat 对象大小显示 0 B」「处理页刷新后右侧空白」三个显示问题。
 
 ---
 

TEMPAT SAMPAH
docs/images/01-chat.png


TEMPAT SAMPAH
docs/images/02-process.png


TEMPAT SAMPAH
docs/images/03-files.png


TEMPAT SAMPAH
docs/images/04-system.png


+ 54 - 1
tools-service/tests/test_api.py

@@ -1,4 +1,4 @@
-"""HTTP 接口测试(FastAPI TestClient):上传 → 处理 → 查询 → 台账。"""
+"""HTTP 接口测试(FastAPI TestClient):上传 → 处理 → 查询 → 台账。"""
 
 from __future__ import annotations
 
@@ -198,3 +198,56 @@ def test_ledger_endpoints(client):
     detail = client.get(f"/ledger/call/{calls[0]['call_id']}")
     assert detail.status_code == 200
     assert client.get("/ledger/export").json()["items"]
+
+def test_data_read_records_data_plane_ledger(client, raw_object):
+    """BFF 传入 call_id 时,data_read 必须把调用与行值写进数据面台账。"""
+
+    call_id = "call_test_data_read_1"
+    response = client.post(
+        "/tools/data_read",
+        json={
+            "object_id": raw_object["id"],
+            "table": "raw",
+            "limit": 2,
+            "call_id": call_id,
+            "session_id": "api-ledger",
+        },
+    )
+    assert response.status_code == 200, response.text
+    payload = response.json()
+    assert payload["rows"], "查询应返回行"
+    amount = payload["rows"][0]["values"].get("MONORSUM")
+
+    detail = client.get(f"/ledger/call/{call_id}")
+    assert detail.status_code == 200, detail.text
+    entry = detail.json()
+    assert entry["tool"] == "data_read"
+    assert entry["object_ids"] == [raw_object["id"]]
+
+    hit = client.get("/ledger/value", params={"value": str(amount), "session_id": "api-ledger"})
+    assert hit.status_code == 200
+    assert any(item["call_id"] == call_id for item in hit.json()["items"]), "返回值应可反查"
+
+
+def test_customs_process_records_data_plane_ledger(client, workspace, raw_object):
+    """customs_process 也按 call_id 记账(对象 + 血缘摘要),便于审计。"""
+
+    call_id = "call_test_process_1"
+    response = client.post(
+        "/tools/customs_process",
+        json={
+            "workspace_id": workspace["id"],
+            "input_object_id": raw_object["id"],
+            "params": {"start_year": 2025, "end_year": 2025},
+            "call_id": call_id,
+            "session_id": "api-ledger",
+        },
+    )
+    assert response.status_code == 200, response.text
+    output_object = response.json()["object_id"]
+
+    entry = client.get(f"/ledger/call/{call_id}").json()
+    assert entry["tool"] == "customs_process"
+    assert raw_object["id"] in entry["object_ids"]
+    assert output_object in entry["object_ids"]
+    assert entry["result"]["sheet_count"] == 23

+ 59 - 0
tools-service/toolsvc/api.py

@@ -237,6 +237,9 @@ class DataReadRequest(BaseModel):
     limit: int | None = None
     offset: int = 0
     aggregate: dict | None = None
+    #: 由 BFF 传入:把本次调用登记进数据面台账,call_id 与溯源令牌一致
+    call_id: str = ""
+    session_id: str = ""
 
 
 @app.post("/tools/data_read")
@@ -256,6 +259,40 @@ def tool_data_read(payload: DataReadRequest) -> dict:
         raise HTTPException(status_code=404, detail=str(error)) from error
     except ReadError as error:
         raise HTTPException(status_code=400, detail=str(error)) from error
+
+    if payload.call_id:
+        # 数据面台账:调用级记录 + 行级索引,供离线审计和"这个数从哪来"
+        ledger.record(
+            payload.call_id,
+            "data_read",
+            {
+                "object_id": payload.object_id,
+                "table": payload.table,
+                "filters": payload.filters,
+                "limit": payload.limit,
+                "offset": payload.offset,
+                "aggregate": payload.aggregate,
+            },
+            {
+                "columns": result["columns"],
+                "total": result.get("total"),
+                "returned": len(result["rows"]),
+            },
+            object_ids=[payload.object_id],
+            session_id=payload.session_id,
+            rows=[
+                {
+                    "values": row["values"],
+                    "_trace": {
+                        "object_id": row["_trace"].get("object_id", payload.object_id),
+                        "table": row["_trace"].get("table", payload.table),
+                        "row_index": row["_trace"].get("row_index", -1),
+                        "row_hash": row["_trace"].get("row_hash", ""),
+                    },
+                }
+                for row in result["rows"]
+            ],
+        )
     return result
 
 
@@ -281,6 +318,8 @@ class ProcessRequest(BaseModel):
     operation: str = "full_pipeline"
     params: dict = Field(default_factory=dict)
     output_filename: str | None = None
+    call_id: str = ""
+    session_id: str = ""
 
 
 @app.post("/tools/customs_process")
@@ -297,6 +336,26 @@ def tool_customs_process(payload: ProcessRequest) -> dict:
             content={"detail": run.get("error") or "处理失败", "run": run},
         )
     item = store.get_object(run["object_id"])
+    if payload.call_id:
+        ledger.record(
+            payload.call_id,
+            "customs_process",
+            {
+                "workspace_id": payload.workspace_id,
+                "input_object_id": payload.input_object_id,
+                "operation": payload.operation,
+                "params": payload.params,
+            },
+            {
+                "run_id": run["id"],
+                "object_id": item["id"],
+                "sheet_count": len(item["tables"]),
+                "rows": item["rows"],
+                "lineage": item["meta"].get("lineage", {}),
+            },
+            object_ids=[payload.input_object_id, item["id"]],
+            session_id=payload.session_id,
+        )
     return {
         "run_id": run["id"],
         "object_id": item["id"],

+ 9 - 1
tools-service/toolsvc/objects.py

@@ -269,6 +269,14 @@ class ObjectStore:
                 if key in {"total", "included", "excluded", "alerts", "min_month", "max_month", "seconds", "engine", "cutoff"}
             },
         }
+        # 磁盘占用:把整次运行目录(xlsx + 逐表 CSV + 两个 sqlite + 明细)都算进去
+        total_bytes = 0
+        for path in run_dir.rglob("*"):
+            if path.is_file():
+                try:
+                    total_bytes += path.stat().st_size
+                except OSError:
+                    continue
         with database.transaction() as connection:
             connection.execute(
                 "INSERT INTO objects(id,workspace_id,name,kind,media_type,path,sha256,bytes,rows,columns_json,"
@@ -281,7 +289,7 @@ class ObjectStore:
                     "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                     str(run_dir),
                     lineage.get("output_hash", ""),
-                    0,
+                    total_bytes,
                     sum(int(sheet.get("rows") or 0) for sheet in result.get("sheets", [])),
                     json.dumps([sheet["sheet"] for sheet in result.get("sheets", [])], ensure_ascii=False),
                     producer,

File diff ditekan karena terlalu besar
+ 0 - 0
web/dist/assets/index-DcCQIZqN.js


File diff ditekan karena terlalu besar
+ 0 - 0
web/dist/assets/index-DzJI8unv.js


+ 1 - 1
web/dist/index.html

@@ -5,7 +5,7 @@
     <meta name="viewport" content="width=device-width, initial-scale=1.0" />
     <title>海关问数 Agent · 电子元器件进出口数据分析</title>
     <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64'%3E%3Crect width='64' height='64' rx='12' fill='%231f4fd1'/%3E%3Ctext x='32' y='43' font-size='30' text-anchor='middle' fill='white' font-family='sans-serif'%3E关%3C/text%3E%3C/svg%3E" />
-    <script type="module" crossorigin src="/assets/index-DzJI8unv.js"></script>
+    <script type="module" crossorigin src="/assets/index-DcCQIZqN.js"></script>
     <link rel="stylesheet" crossorigin href="/assets/index-B1dZrLEW.css">
   </head>
   <body>

+ 27 - 5
web/src/App.tsx

@@ -6,7 +6,7 @@ import { ChatPage } from './pages/ChatPage';
 import { FilesPage } from './pages/FilesPage';
 import { ProcessPage } from './pages/ProcessPage';
 import { SystemPage } from './pages/SystemPage';
-import { relativeTime } from './lib/format';
+
 
 type Tab = 'chat' | 'process' | 'files' | 'system';
 
@@ -17,8 +17,17 @@ const TABS: Array<{ id: Tab; label: string; hint: string }> = [
   { id: 'system', label: '系统', hint: '运行状态' },
 ];
 
+const TAB_IDS = TABS.map((item) => item.id);
+
+/** 用 URL hash 做路由(#/chat、#/process…),页面可直接分享、刷新、截图。 */
+function tabFromHash(): Tab {
+  if (typeof window === 'undefined') return 'chat';
+  const candidate = window.location.hash.replace(/^#\/?/, '').split('?')[0] as Tab;
+  return TAB_IDS.includes(candidate) ? candidate : 'chat';
+}
+
 export default function App() {
-  const [tab, setTab] = useState<Tab>('chat');
+  const [tab, setTab] = useState<Tab>(() => tabFromHash());
   const [workspaces, setWorkspaces] = useState<Workspace[]>([]);
   const [workspaceId, setWorkspaceId] = useState<string>('');
   const [health, setHealth] = useState<HealthPayload | null>(null);
@@ -26,6 +35,20 @@ export default function App() {
   const [loading, setLoading] = useState(true);
   const [version, setVersion] = useState(0);
 
+  // hash ↔ tab 双向同步(支持浏览器前进/后退)
+  useEffect(() => {
+    const onHashChange = () => setTab(tabFromHash());
+    window.addEventListener('hashchange', onHashChange);
+    return () => window.removeEventListener('hashchange', onHashChange);
+  }, []);
+
+  const navigate = (next: Tab) => {
+    setTab(next);
+    if (typeof window !== 'undefined' && window.location.hash !== `#/${next}`) {
+      window.location.hash = `#/${next}`;
+    }
+  };
+
   const showToast = useCallback((tone: 'success' | 'error' | 'info', text: string) => {
     setToast({ tone, text });
     window.setTimeout(() => setToast(null), 4200);
@@ -127,7 +150,7 @@ export default function App() {
 
         <nav className="nav">
           {TABS.map((item) => (
-            <button key={item.id} type="button" className={`nav-item ${tab === item.id ? 'active' : ''}`} onClick={() => setTab(item.id)}>
+            <button key={item.id} type="button" className={`nav-item ${tab === item.id ? 'active' : ''}`} onClick={() => navigate(item.id)}>
               <span className="nav-label">{item.label}</span>
               <span className="nav-hint">{item.hint}</span>
             </button>
@@ -139,8 +162,7 @@ export default function App() {
           <div>
             <strong>{toolsDown ? '工具服务离线' : '服务运行中'}</strong>
             <small>
-              {health ? `${health.harness} · ${health.version}` : '正在连接…'}
-              {workspace ? ` · ${relativeTime(new Date().toISOString())}` : ''}
+              {health ? `${health.harness} · v${health.version}` : '正在连接…'}
             </small>
           </div>
         </div>

+ 10 - 3
web/src/components/ChatMessageView.tsx

@@ -1,4 +1,4 @@
-import { useState, type ReactElement } from 'react';
+import { useState, type ReactElement } from 'react';
 import type { ChatMessage, ClaimChip, ToolResultRecord, Verification } from '../api/types';
 import { Badge, DataTable } from './Common';
 import { MiniChart } from './MiniChart';
@@ -34,6 +34,7 @@ export function ChatMessageView({ message }: { message: ChatMessage }) {
         <div className="bubble">
           <Markdownish text={message.content} />
         </div>
+        {message.verification && message.verification.chips.length > 0 && <TraceChips chips={message.verification.chips} />}
         {message.verification && <VerificationPanel verification={message.verification} />}
       </div>
     </div>
@@ -54,8 +55,14 @@ function ToolCard({ call, result }: { call: { id: string; name: string; argument
       <button type="button" className="tool-head" onClick={() => setOpen((value) => !value)}>
         <span className="tool-dot" />
         <span className="tool-name">{TOOL_LABELS[call.name] ?? call.name}</span>
-        <span className="tool-meta">
-          {result ? (result.ok ? `${result.rows ?? 0} 行 · ${result.duration_ms ?? 0}ms` : '失败') : '执行中…'}
+        <span className="tool-meta" title={result?.summary ?? ''}>
+          {result
+            ? result.ok
+              ? (result.rows ?? 0) > 0
+                ? `${result.rows} 行 · ${result.duration_ms ?? 0}ms`
+                : `${result.summary || '完成'} · ${result.duration_ms ?? 0}ms`
+              : `失败:${result.summary || '未知原因'}`
+            : '执行中…'}
         </span>
         <span className="tool-chevron">{open ? '−' : '+'}</span>
       </button>

+ 9 - 2
web/src/components/Common.tsx

@@ -1,5 +1,5 @@
 import type { CSSProperties, ReactNode } from 'react';
-import { formatNumber, isNumericColumn } from '../lib/format';
+import { formatNumber, isNumericColumn, isPlainIntegerColumn } from '../lib/format';
 
 export interface DataTableProps {
   columns: string[];
@@ -31,9 +31,16 @@ export function DataTable({ columns, rows, maxRows = 30, compact = false, highli
               {columns.map((column) => {
                 const value = row[column];
                 const numeric = isNumericColumn(column);
+                const plain = isPlainIntegerColumn(column);
                 return (
                   <td key={column} className={numeric ? 'num' : ''} title={value === undefined ? '' : String(value)}>
-                    {value === undefined || value === null || value === '' ? '—' : numeric ? formatNumber(value) : String(value)}
+                    {value === undefined || value === null || value === ''
+                      ? '—'
+                      : plain
+                        ? String(value)
+                        : numeric
+                          ? formatNumber(value)
+                          : String(value)}
                   </td>
                 );
               })}

+ 7 - 0
web/src/lib/format.ts

@@ -1,5 +1,12 @@
 /** 纯展示层工具函数(可单测,不依赖 DOM)。 */
 
+/** 这些列是"年份/月份/名次",不加千分位(否则 2025 会显示成 2,025)。 */
+const PLAIN_INTEGER_COLUMNS = new Set(['年度', '月度', 'ISO年', 'ISO周', '归属年', '归属月', '排名', '行号', '记录序号']);
+
+export function isPlainIntegerColumn(column: string): boolean {
+  return PLAIN_INTEGER_COLUMNS.has(column);
+}
+
 export function formatNumber(value: unknown, maxDigits = 4): string {
   if (value === null || value === undefined || value === '') return '—';
   const number = typeof value === 'number' ? value : Number(String(value).replace(/,/g, ''));

+ 8 - 2
web/src/pages/ChatPage.tsx

@@ -286,8 +286,14 @@ export function ChatPage({ workspace, onToast }: ChatPageProps) {
                         <div className="tool-head static">
                           <span className="tool-dot" />
                           <span className="tool-name">{toolLabel(tool.tool)}</span>
-                          <span className="tool-meta">
-                            {tool.result ? (tool.result.ok ? `${tool.result.rows ?? 0} 行` : '失败') : '执行中…'}
+                          <span className="tool-meta" title={tool.result?.summary ?? ''}>
+                            {tool.result
+                              ? tool.result.ok
+                                ? (tool.result.rows ?? 0) > 0
+                                  ? `${tool.result.rows} 行`
+                                  : tool.result.summary || '完成'
+                                : `失败:${tool.result.summary || '未知原因'}`
+                              : '执行中…'}
                           </span>
                         </div>
                       </div>

+ 5 - 3
web/src/pages/FilesPage.tsx

@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useRef, useState } from 'react';
+import { useCallback, useEffect, useRef, useState } from 'react';
 import { api } from '../api/client';
 import type { DataObject, Workspace } from '../api/types';
 import { Badge, DataTable, Modal, Spinner } from '../components/Common';
@@ -142,7 +142,7 @@ export function FilesPage({ workspace, onToast, onChanged }: FilesPageProps) {
             <tr>
               <th>名称</th>
               <th>类型</th>
-              <th>行数</th>
+              <th>规模</th>
               <th>大小</th>
               <th>表</th>
               <th>上传时间</th>
@@ -166,7 +166,9 @@ export function FilesPage({ workspace, onToast, onChanged }: FilesPageProps) {
                 <td>
                   <Badge tone={file.kind === 'raw' ? 'info' : 'success'}>{file.kind === 'raw' ? '原始数据' : '统计结果'}</Badge>
                 </td>
-                <td className="num">{file.rows.toLocaleString('en-US')}</td>
+                <td className="num">
+                  {file.kind === 'raw' ? `${file.rows.toLocaleString('en-US')} 行` : `${file.tables.length} 表 · ${file.rows.toLocaleString('en-US')} 行`}
+                </td>
                 <td className="num">{formatBytes(file.bytes)}</td>
                 <td>
                   <div className="table-chips">

+ 15 - 0
web/src/pages/ProcessPage.tsx

@@ -62,7 +62,22 @@ export function ProcessPage({ workspace, onToast, onChanged }: ProcessPageProps)
     setSelected('');
     setResult(null);
     setRun(null);
+    setPreviewData(null);
     void loadFiles();
+    // 打开页面时把最近一次成功的处理结果自动加载出来,避免右侧空白
+    api
+      .listRuns()
+      .then(async (data) => {
+        setHistory(data.items.filter((item) => item.input_object));
+        const latest = data.items.find((item) => item.status === 'succeeded' && item.object_id);
+        if (latest?.object_id) {
+          const object = await api.getObject(latest.object_id);
+          setResult(object);
+          setPreviewTable(object.tables[0]?.name ?? '');
+          setRun(latest);
+        }
+      })
+      .catch(() => setHistory([]));
     // eslint-disable-next-line react-hooks/exhaustive-deps
   }, [workspace?.id]);
 

+ 9 - 5
web/src/pages/SystemPage.tsx

@@ -1,4 +1,4 @@
-import { useEffect, useState } from 'react';
+import { useEffect, useState } from 'react';
 import { api } from '../api/client';
 import type { HealthPayload } from '../api/types';
 import { Badge, Spinner } from '../components/Common';
@@ -91,10 +91,14 @@ export function SystemPage() {
             <dd>
               {String((health.tools.meta as any)?.processor?.name ?? '—')} v{String((health.tools.meta as any)?.processor?.version ?? '—')}
             </dd>
-            <dt>台账调用数</dt>
-            <dd>{String(ledger?.tools?.calls ?? '—')}</dd>
-            <dt>索引值数量</dt>
-            <dd>{String(ledger?.tools?.indexed_values ?? '—')}</dd>
+            <dt>数据面台账</dt>
+            <dd>
+              {String(ledger?.tools?.calls ?? '—')} 次调用 · {String(ledger?.tools?.indexed_values ?? '—')} 个字段值
+            </dd>
+            <dt>会话台账</dt>
+            <dd>
+              {String(ledger?.session?.calls ?? '—')} 次调用 · {String(ledger?.session?.indexed_values ?? '—')} 个字段值
+            </dd>
             <dt>哈希链校验</dt>
             <dd>{ledger?.tools?.chain_ok ? '完整' : '异常(请导出台账核查)'}</dd>
           </dl>

+ 12 - 1
web/test/format.test.ts

@@ -1,4 +1,4 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it } from 'vitest';
 import {
   buildChartSeries,
   classifySheet,
@@ -6,6 +6,7 @@ import {
   formatNumber,
   formatPercent,
   isNumericColumn,
+  isPlainIntegerColumn,
   pickLabelColumn,
   pickValueColumn,
   relativeTime,
@@ -109,3 +110,13 @@ describe('truncate', () => {
     expect(truncate('短', 3)).toBe('短');
   });
 });
+
+describe('isPlainIntegerColumn', () => {
+  it('年份/月份/名次不加千分位', () => {
+    expect(isPlainIntegerColumn('年度')).toBe(true);
+    expect(isPlainIntegerColumn('月度')).toBe(true);
+    expect(isPlainIntegerColumn('排名')).toBe(true);
+    expect(isPlainIntegerColumn('实际金额(美元)')).toBe(false);
+    expect(isPlainIntegerColumn('金额指数')).toBe(false);
+  });
+});

Beberapa file tidak ditampilkan karena terlalu banyak file yang berubah dalam diff ini