Quellcode durchsuchen

feat: 补齐架构文档要求的交互与接口(溯源抽屉、跳转高亮、进度 SSE、按行取数)

按架构文档逐条自查后补齐 5 处缺口,并用 CDP 驱动真实浏览器点击验证。

溯源 chip 可点击(文档 4.3/5 的明确要求)
- 新增 TraceDrawer:点开数字 → 对象 / 表 / 行号 / 行哈希 / 字段 + 这一行全部原文(命中字段高亮)
  + 下钻谓词(source_rows)+ 原始数据对象
- calculator 产生的数字改为展示"计算 ID / 参数 / 结果哈希"
- 抽屉底部"在结果表中查看这一行" → #/files?object=&table=&row= 深链 → FilesPage 用 preview 的
  offset 定位并蓝色高亮该行(scrollIntoView)
- 核验面板里"已溯源"的数字同样可点开

按行取数 / 预览定位(后端)
- 新增 GET /objects/{id}/row(原文 + 行哈希 + 行级血缘)与 /api/objects/:oid/row
- preview 支持 offset,并返回 row_indexes / row_hashes,供前端定位高亮
- 新增 GET /objects/{id}/sheet_meta;BFF 补齐契约里的嵌套路径 /api/workspaces/:wid/objects/:oid

处理进度 SSE(文档 4.2)
- 新增 GET /api/process/:runId/stream(progress 事件流 + done)
- 前端优先用 SSE,流断自动退回 700ms 轮询

其他
- 文件页新增 SHA256 指纹列
- 数据处理页显式展示血缘五项(输入文件/输入指纹/参数哈希/输出哈希/引擎)
- 自定义聚合补齐"过滤条件"编辑器(文档要求的"配置过滤条件")
- 新增 GET /api/sessions/:id/ledger/:callId(单次调用详情)

真实浏览器验证(新脚本 scripts/ui_probe.mjs)
- 用 Chrome DevTools Protocol 打开页面、点 chip、断言抽屉出现、点跳转、断言弹窗与高亮行
- 顺带抓出并修掉"抽屉里年度显示成 2,026"的问题
- 6 张截图存入 docs/images/,README 与使用手册加入对应图廊与操作步骤

测试
- BFF 58(+4:按行取数/嵌套路径、预览 offset、进度 SSE、台账调用详情)、前端 27(+4:抽屉、深链解析)、
  Python 85(+3:row/sheet_meta/preview offset)、端到端 33(+5:SSE 进度、按行取数、越界 404)、
  UI 探针 7 组汇总全绿
California vor 4 Tagen
Ursprung
Commit
f5ed8dd507
50 geänderte Dateien mit 1680 neuen und 108 gelöschten Zeilen
  1. 15 8
      README.md
  2. 77 3
      bff/dist/src/routes/data.js
  3. 0 0
      bff/dist/src/routes/data.js.map
  4. 10 0
      bff/dist/src/routes/sessions.js
  5. 0 0
      bff/dist/src/routes/sessions.js.map
  6. 26 0
      bff/dist/src/store/ledger.js
  7. 0 0
      bff/dist/src/store/ledger.js.map
  8. 7 2
      bff/dist/src/tools/client.js
  9. 0 0
      bff/dist/src/tools/client.js.map
  10. 75 0
      bff/dist/test/api.test.js
  11. 0 0
      bff/dist/test/api.test.js.map
  12. 29 5
      bff/dist/test/fakes.js
  13. 0 0
      bff/dist/test/fakes.js.map
  14. 87 2
      bff/src/routes/data.ts
  15. 10 1
      bff/src/routes/sessions.ts
  16. 30 0
      bff/src/store/ledger.ts
  17. 33 3
      bff/src/tools/client.ts
  18. 83 0
      bff/test/api.test.ts
  19. 30 6
      bff/test/fakes.ts
  20. 17 1
      docs/01-架构设计.md
  21. 12 1
      docs/02-实现说明.md
  22. 21 0
      docs/03-使用手册.md
  23. 20 7
      docs/05-测试报告.md
  24. BIN
      docs/images/01-chat.png
  25. BIN
      docs/images/02-process.png
  26. BIN
      docs/images/03-files.png
  27. BIN
      docs/images/04-system.png
  28. BIN
      docs/images/05-trace-drawer.png
  29. BIN
      docs/images/06-row-jump.png
  30. 2 1
      package.json
  31. 25 12
      scripts/e2e.mjs
  32. 6 1
      scripts/run_tests.ps1
  33. 222 0
      scripts/ui_probe.mjs
  34. 42 1
      tools-service/tests/test_api.py
  35. 41 2
      tools-service/toolsvc/api.py
  36. 32 2
      tools-service/toolsvc/objects.py
  37. 0 0
      web/dist/assets/index-DcCQIZqN.js
  38. 0 0
      web/dist/assets/index-gwqomBW9.css
  39. 0 0
      web/dist/assets/index-oisv_dMO.js
  40. 2 2
      web/dist/index.html
  41. 34 2
      web/src/api/client.ts
  42. 5 1
      web/src/api/types.ts
  43. 29 10
      web/src/components/ChatMessageView.tsx
  44. 14 3
      web/src/components/Common.tsx
  45. 174 0
      web/src/components/TraceDrawer.tsx
  46. 15 3
      web/src/pages/ChatPage.tsx
  47. 93 9
      web/src/pages/FilesPage.tsx
  48. 151 19
      web/src/pages/ProcessPage.tsx
  49. 168 0
      web/src/styles/app.css
  50. 43 1
      web/test/render.test.tsx

+ 15 - 8
README.md

@@ -24,11 +24,15 @@
 
 ## 界面
 
-| 对话问数(数字带溯源 chip + 核验结论) | 数据处理(23 张结果表 + 预览/图表) |
+| 对话问数(数字带溯源 chip + 核验结论) | 点开 chip:对象 / 表 / 行号 / 行哈希 + 这一行原文 |
 |---|---|
-| ![对话](docs/images/01-chat.png) | ![数据处理](docs/images/02-process.png) |
+| ![对话](docs/images/01-chat.png) | ![溯源抽屉](docs/images/05-trace-drawer.png) |
 
-| 文件(原始数据 / 统计结果) | 系统(Harness、工具、台账) |
+| 点"在结果表中查看":跳到"文件"页并高亮那一行 | 数据处理(23 张结果表 + 预览/图表) |
+|---|---|
+| ![跳转高亮](docs/images/06-row-jump.png) | ![数据处理](docs/images/02-process.png) |
+
+| 文件(原始数据 / 统计结果,含 SHA256 指纹) | 系统(Harness、工具、两本台账) |
 |---|---|
 | ![文件](docs/images/03-files.png) | ![系统](docs/images/04-system.png) |
 
@@ -73,7 +77,7 @@ CustomesDataAgent/
 │  ├─ src/verify/              #   输出核验层:数字抽取 + 台账反查 + 裁决
 │  ├─ src/routes/              #   工作区/文件/处理/会话/对话(SSE)/系统
 │  ├─ src/store/               #   sqlite:会话、消息、会话台账
-│  └─ test/                    #   54 项单元与接口测试
+│  └─ test/                    #   58 项单元与接口测试
 ├─ tools-service/              # Python 工具执行服务
 │  ├─ toolsvc/customs/         # ★ 可替换的数据处理模块(契约 + engine + rules/)
 │  ├─ toolsvc/objects.py       #   对象库、原始数据索引、行级血缘
@@ -82,7 +86,7 @@ CustomesDataAgent/
 │  ├─ toolsvc/readers.py       #   data_read(SQL 过滤/排序/聚合)
 │  ├─ toolsvc/api.py           #   HTTP 接口
 │  └─ tests/                   #   85 项单元与接口测试
-├─ web/                        # React 前端(23 项单测:格式化 + 组件渲染)
+├─ web/                        # React 前端(27 项单测:格式化 + 组件渲染)
 ├─ scripts/                    # start/stop/e2e/run_tests/样本数据生成
 ├─ deploy/                     # Dockerfile + docker-compose(单镜像一键部署)
 ├─ samples/                    # 可复现的测试数据集 + 预言机(expected.json)
@@ -109,9 +113,10 @@ CustomesDataAgent/
 | 测试组 | 数量 | 命令 |
 |---|---|---|
 | 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) | 23 | `cd web && npx vitest run` |
-| 端到端联调(真实服务 + 真实模型) | 28 项检查 | `node scripts/e2e.mjs` |
+| BFF 单元与接口(node:test) | 58 | `cd bff && npm run build && node --test "dist/test/*.test.js"` |
+| 前端单元 + 渲染(vitest) | 27 | `cd web && npx vitest run` |
+| 端到端联调(真实服务 + 真实模型) | 33 项检查 | `node scripts/e2e.mjs` |
+| 真实浏览器交互(CDP 点击 + 截图) | 3 步断言 + 6 张截图 | `node scripts/ui_probe.mjs` |
 
 一条命令全跑:
 
@@ -119,6 +124,8 @@ CustomesDataAgent/
 powershell -NoProfile -ExecutionPolicy Bypass -File scripts\run_tests.ps1
 ```
 
+另有**真实浏览器交互探针** `node scripts/ui_probe.mjs`(用 CDP 点开 chip、跳转高亮、逐页截图),产物在 `.run/ui/`。
+
 结果见 [docs/05-测试报告.md](docs/05-测试报告.md)。
 
 ---

+ 77 - 3
bff/dist/src/routes/data.js

@@ -1,5 +1,5 @@
-import { sendJson } from '../http/server.js';
-import { badRequest, HttpError } from '../util/common.js';
+import { sendJson, SseStream } from '../http/server.js';
+import { badRequest, HttpError, notFound } from '../util/common.js';
 export function registerDataRoutes(router, context) {
     // ------------------------------------------------------------ 工作区
     router.get('/api/workspaces', async ({ res }) => {
@@ -61,7 +61,8 @@ export function registerDataRoutes(router, context) {
     router.get('/api/objects/:oid/preview', async ({ res, params, url }) => {
         const table = url.searchParams.get('table') ?? 'raw';
         const limit = Number(url.searchParams.get('limit') ?? '20');
-        const preview = await context.tools.preview(params.oid, table, Math.min(Math.max(limit, 1), 200));
+        const offset = Number(url.searchParams.get('offset') ?? '0');
+        const preview = await context.tools.preview(params.oid, table, Math.min(Math.max(Number.isFinite(limit) ? limit : 20, 1), 200), Math.max(Number.isFinite(offset) ? offset : 0, 0));
         sendJson(res, 200, preview);
     });
     router.get('/api/objects/:oid/lineage', async ({ res, params, url }) => {
@@ -85,6 +86,28 @@ export function registerDataRoutes(router, context) {
         });
         res.end(buffer);
     });
+    /** 按行号取一行:溯源 chip 的详情面板用(原文 + 行哈希 + 下钻谓词)。 */
+    router.get('/api/objects/:oid/row', async ({ res, params, url }) => {
+        const table = url.searchParams.get('table') ?? 'raw';
+        const row = Number(url.searchParams.get('row') ?? '0');
+        const data = await context.tools.row(params.oid, table, Number.isFinite(row) ? row : 0);
+        sendJson(res, 200, data);
+    });
+    /** 契约里的嵌套写法:/api/workspaces/:id/objects/:oid → 与 /api/objects/:oid 等价。 */
+    router.get('/api/workspaces/:wid/objects/:oid', async ({ res, params }) => {
+        const object = await context.tools.getObject(params.oid);
+        if (object.workspace_id !== params.wid) {
+            throw notFound(`对象 ${params.oid} 不属于工作区 ${params.wid}`);
+        }
+        sendJson(res, 200, object);
+    });
+    /** 契约里的嵌套写法:/api/workspaces/:id/objects/:oid/lineage */
+    router.get('/api/workspaces/:wid/objects/:oid/lineage', async ({ res, params, url }) => {
+        const table = url.searchParams.get('table') ?? undefined;
+        const row = url.searchParams.get('row');
+        const lineage = await context.tools.lineage(params.oid, table, row === null ? undefined : Number(row));
+        sendJson(res, 200, lineage);
+    });
     // ------------------------------------------------------------ 处理任务
     router.post('/api/process', async ({ res, json }) => {
         const body = json();
@@ -110,6 +133,57 @@ export function registerDataRoutes(router, context) {
         const run = await context.tools.getRun(params.runId);
         sendJson(res, 200, run);
     });
+    /**
+     * 处理进度 SSE(架构文档 4.2 要求的形态)。
+     * 先同步确认任务存在(不存在就走 JSON 404),再开流。
+     */
+    router.get('/api/process/:runId/stream', async ({ res, params, req }) => {
+        const first = await context.tools.getRun(params.runId);
+        const sse = new SseStream(res);
+        let stopped = false;
+        req.on('close', () => {
+            stopped = true;
+        });
+        const push = async () => {
+            try {
+                const run = await context.tools.getRun(params.runId);
+                sse.send('progress', {
+                    run_id: run.id,
+                    status: run.status,
+                    progress: run.progress,
+                    message: run.message,
+                    object_id: run.object_id,
+                    error: run.error,
+                });
+                if (run.status === 'succeeded' || run.status === 'failed') {
+                    sse.send('done', { run_id: run.id, status: run.status, object_id: run.object_id, error: run.error });
+                    stopped = true;
+                    sse.close();
+                }
+            }
+            catch (error) {
+                sse.send('error', { message: error.message });
+                stopped = true;
+                sse.close();
+            }
+        };
+        sse.send('progress', {
+            run_id: first.id,
+            status: first.status,
+            progress: first.progress,
+            message: first.message,
+            object_id: first.object_id,
+            error: first.error,
+        });
+        const timer = setInterval(() => {
+            if (stopped) {
+                clearInterval(timer);
+                return;
+            }
+            void push();
+        }, 400);
+        res.on('close', () => clearInterval(timer));
+    });
     // ------------------------------------------------------------ 台账(数据面)
     router.get('/api/ledger/stats', async ({ res }) => {
         const stats = await context.tools.ledgerStats();

Datei-Diff unterdrückt, da er zu groß ist
+ 0 - 0
bff/dist/src/routes/data.js.map


+ 10 - 0
bff/dist/src/routes/sessions.js

@@ -51,6 +51,16 @@ export function registerSessionRoutes(router, context) {
         context.sessions.delete(params.id);
         sendJson(res, 200, { ok: true });
     });
+    /** 单次调用详情:溯源 chip 若是 calculator 产出,用它展示算式与输入。 */
+    router.get('/api/sessions/:id/ledger/:callId', async ({ res, params }) => {
+        const session = context.sessions.get(params.id);
+        if (!session)
+            throw notFound(`会话不存在: ` + params.id);
+        const call = context.ledger.callOf(params.callId);
+        if (!call || String(call.session_id) !== params.id)
+            throw notFound(`该会话没有这次调用: ` + params.callId);
+        sendJson(res, 200, { call, values: context.ledger.valuesOf(params.callId) });
+    });
     router.get('/api/sessions/:id/ledger', async ({ res, params }) => {
         const session = context.sessions.get(params.id);
         if (!session)

Datei-Diff unterdrückt, da er zu groß ist
+ 0 - 0
bff/dist/src/routes/sessions.js.map


+ 26 - 0
bff/dist/src/store/ledger.js

@@ -71,6 +71,22 @@ export class SessionLedger {
         return this.db.all(`SELECT call_id,object_id,table_name,row_index,field,value_text,value_num
        FROM ledger_values WHERE session_id=? AND value_text=? ORDER BY rowid DESC LIMIT 20`, sessionId, value);
     }
+    /** 单次调用详情(chip 点开时展示"这次计算/读取做了什么")。 */
+    callOf(callId) {
+        const row = this.db.get('SELECT * FROM ledger_calls WHERE call_id=?', callId);
+        if (!row)
+            return null;
+        return {
+            ...row,
+            args: safeParse(row.args_json),
+            object_ids: safeParse(row.object_ids),
+        };
+    }
+    /** 某次调用返回过的字段值(用于"这个数在该次结果里出现过几次")。 */
+    valuesOf(callId, limit = 50) {
+        return this.db.all(`SELECT field,value_text,value_num,row_index,table_name,object_id FROM ledger_values
+       WHERE call_id=? ORDER BY rowid LIMIT ?`, callId, limit);
+    }
     callsOf(sessionId) {
         return this.db.all(`SELECT call_id,tool,args_hash,result_hash,row_count,object_ids,created_at
        FROM ledger_calls WHERE session_id=? ORDER BY created_at`, sessionId);
@@ -85,4 +101,14 @@ export class SessionLedger {
         return { calls: calls?.c ?? 0, indexed_values: values?.c ?? 0 };
     }
 }
+function safeParse(text) {
+    if (typeof text !== 'string' || !text)
+        return null;
+    try {
+        return JSON.parse(text);
+    }
+    catch {
+        return text;
+    }
+}
 //# sourceMappingURL=ledger.js.map

Datei-Diff unterdrückt, da er zu groß ist
+ 0 - 0
bff/dist/src/store/ledger.js.map


+ 7 - 2
bff/dist/src/tools/client.js

@@ -90,10 +90,15 @@ export class ToolsClient {
         form.append('file', blob, filename);
         return this.request(`/workspaces/${encodeURIComponent(workspaceId)}/objects`, { method: 'POST', body: form }, 120_000);
     }
-    preview(objectId, table = 'raw', limit = 20) {
-        const query = new URLSearchParams({ table, limit: String(limit) });
+    preview(objectId, table = 'raw', limit = 20, offset = 0) {
+        const query = new URLSearchParams({ table, limit: String(limit), offset: String(offset) });
         return this.request(`/objects/${encodeURIComponent(objectId)}/preview?${query}`);
     }
+    /** 按行号取一行:溯源 chip 点开详情时用(原文 + 行哈希 + 行级血缘)。 */
+    row(objectId, table, rowIndex) {
+        const query = new URLSearchParams({ table, row: String(rowIndex) });
+        return this.request(`/objects/${encodeURIComponent(objectId)}/row?${query}`);
+    }
     lineage(objectId, table, row) {
         const query = new URLSearchParams();
         if (table)

Datei-Diff unterdrückt, da er zu groß ist
+ 0 - 0
bff/dist/src/tools/client.js.map


+ 75 - 0
bff/dist/test/api.test.js

@@ -171,4 +171,79 @@ test('未知接口返回结构化 404', async () => {
     const payload = await response.json();
     assert.equal(payload.error, 'NOT_FOUND');
 });
+test('按行取数(溯源抽屉)与嵌套对象路径', async () => {
+    const row = await api('/api/objects/obj_stat/row?table=1.0-3.0_MLCC&row=1');
+    assert.equal(row.row_index, 1);
+    assert.equal(row.values['基础类目'], '多层瓷介电容器(MLCC)');
+    assert.match(row.row_hash, /^sha256:/);
+    // 契约里的嵌套写法应等价
+    const nested = await api('/api/workspaces/ws_test/objects/obj_stat');
+    assert.equal(nested.id, 'obj_stat');
+    await assert.rejects(() => api('/api/workspaces/ws_other/objects/obj_stat'), /404/);
+    const missing = await fetch(`${base}/api/objects/obj_stat/row?table=1.0-3.0_MLCC&row=9999`);
+    assert.equal(missing.status, 404);
+});
+test('预览支持 offset 与行号(用于高亮跳转)', async () => {
+    const preview = await api('/api/objects/obj_stat/preview?table=1.0-3.0_MLCC&limit=2&offset=1');
+    assert.equal(preview.offset, 1);
+    assert.deepEqual(preview.row_indexes, [1]);
+    assert.equal(preview.total, 2);
+});
+test('处理进度 SSE 推送 progress 与 done', async () => {
+    const run = await api('/api/process', {
+        method: 'POST',
+        headers: { 'Content-Type': 'application/json' },
+        body: JSON.stringify({ workspace_id: 'ws_test', input_object_id: 'obj_raw' }),
+    });
+    const response = await fetch(`${base}/api/process/${run.id}/stream`);
+    assert.equal(response.status, 200);
+    assert.match(response.headers.get('content-type') ?? '', /text\/event-stream/);
+    const events = await collectSse(response);
+    const names = events.map((event) => event.event);
+    assert.ok(names.includes('progress'), '缺少 progress 事件');
+    assert.ok(names.includes('done'), '缺少 done 事件');
+    const done = events.find((event) => event.event === 'done').data;
+    assert.equal(done.status, 'succeeded');
+    assert.equal(done.object_id, 'obj_stat');
+    const missing = await fetch(`${base}/api/process/run_not_exist/stream`);
+    assert.equal(missing.status, 404);
+});
+test('会话台账单次调用详情(calculator chip 用)', async () => {
+    // 这个用例需要一次"干净"的对话(剧本客户端是有状态的),所以自己起一个服务实例
+    const llm = new ReplayLlmClient([
+        { toolCalls: [{ name: 'data_read', arguments: { object_id: 'obj_stat', table: '1.0-3.0_MLCC' } }] },
+        { text: '2025 年 1 月 MLCC 进口额为 400316.13 美元。' },
+    ]);
+    const fresh = createApp({ settings: testSettings(tempDir()), tools: asToolsClient(fake), llm, serveStatic: false });
+    const running = await listen(fresh.server);
+    try {
+        const create = await fetch(`${running.url}/api/sessions`, {
+            method: 'POST',
+            headers: { 'Content-Type': 'application/json' },
+            body: JSON.stringify({ workspace_id: 'ws_test' }),
+        });
+        const session = (await create.json());
+        const chat = await fetch(`${running.url}/api/sessions/${session.id}/chat`, {
+            method: 'POST',
+            headers: { 'Content-Type': 'application/json' },
+            body: JSON.stringify({ message: '2025 年 1 月 MLCC 进口额是多少?' }),
+        });
+        const events = await collectSse(chat);
+        const final = events.find((event) => event.event === 'final').data;
+        assert.equal(final.verification, 'accept');
+        const ledger = (await (await fetch(`${running.url}/api/sessions/${session.id}/ledger`)).json());
+        assert.ok(ledger.calls.length >= 1, '应该有台账记录');
+        const call = ledger.calls[0];
+        const detail = (await (await fetch(`${running.url}/api/sessions/${session.id}/ledger/${call.call_id}`)).json());
+        assert.equal(detail.call.call_id, call.call_id);
+        assert.equal(detail.call.tool, 'data_read');
+        assert.ok(Array.isArray(detail.values) && detail.values.length > 0);
+        assert.equal(detail.call.args.object_id, 'obj_stat');
+        const wrongSession = await fetch(`${running.url}/api/sessions/sess_other/ledger/${call.call_id}`);
+        assert.equal(wrongSession.status, 404);
+    }
+    finally {
+        await running.close();
+    }
+});
 //# sourceMappingURL=api.test.js.map

Datei-Diff unterdrückt, da er zu groß ist
+ 0 - 0
bff/dist/test/api.test.js.map


+ 29 - 5
bff/dist/test/fakes.js

@@ -1,6 +1,7 @@
 import { mkdirSync, mkdtempSync } from 'node:fs';
 import os from 'node:os';
 import path from 'node:path';
+import { HttpError } from '../src/util/common.js';
 export function tempDir(prefix = 'cda-test-') {
     const directory = mkdtempSync(path.join(os.tmpdir(), prefix));
     mkdirSync(directory, { recursive: true });
@@ -70,7 +71,7 @@ export class FakeToolsClient {
     async getObject(objectId) {
         const item = this.objects.find((entry) => entry.id === objectId);
         if (!item)
-            throw Object.assign(new Error(`对象不存在: ${objectId}`), { status: 404 });
+            throw new HttpError(404, `对象不存在: ${objectId}`);
         return item;
     }
     async deleteObject(objectId) {
@@ -82,9 +83,32 @@ export class FakeToolsClient {
         this.objects.push(object);
         return object;
     }
-    async preview(objectId, table = 'raw', limit = 20) {
-        const rows = this.dataRows[`${objectId}:${table}`] ?? [];
-        return { columns: Object.keys(rows[0]?.values ?? {}), rows: rows.slice(0, limit).map((row) => row.values), total: rows.length };
+    async preview(objectId, table = 'raw', limit = 20, offset = 0) {
+        const all = this.dataRows[`${objectId}:${table}`] ?? [];
+        const page = all.slice(offset, offset + limit);
+        return {
+            columns: Object.keys(all[0]?.values ?? {}),
+            rows: page.map((row) => row.values),
+            row_indexes: page.map((row) => row.row_index ?? 0),
+            row_hashes: page.map((row) => row.row_hash ?? 'sha256:x'),
+            offset,
+            limit,
+            total: all.length,
+        };
+    }
+    async row(objectId, table, rowIndex) {
+        const all = this.dataRows[`${objectId}:${table}`] ?? [];
+        const row = all.find((item) => (item.row_index ?? 0) === rowIndex);
+        if (!row)
+            throw new HttpError(404, `表 ${table} 中没有第 ${rowIndex} 行`);
+        return {
+            object_id: objectId,
+            table,
+            row_index: rowIndex,
+            row_hash: row.row_hash ?? 'sha256:x',
+            values: row.values,
+            lineage: { source_object_id: 'obj_raw', source_rows: { year: '2025' } },
+        };
     }
     async lineage(objectId) {
         return { object_id: objectId, parents: ['obj_raw'], lineage: { output_hash: 'sha256:out' } };
@@ -112,7 +136,7 @@ export class FakeToolsClient {
     async getRun(runId) {
         const run = this.runs.find((item) => item.id === runId);
         if (!run)
-            throw Object.assign(new Error('任务不存在'), { status: 404 });
+            throw new HttpError(404, '任务不存在');
         return run;
     }
     async listRuns() {

Datei-Diff unterdrückt, da er zu groß ist
+ 0 - 0
bff/dist/test/fakes.js.map


+ 87 - 2
bff/src/routes/data.ts

@@ -5,7 +5,7 @@
  * 因此完全确定、可复现,也不消耗任何 token。
  */
 import type { Router } from '../http/server.js';
-import { sendJson, sendText } from '../http/server.js';
+import { sendJson, SseStream } from '../http/server.js';
 import { badRequest, HttpError, notFound } from '../util/common.js';
 import type { AppContext } from '../app.js';
 
@@ -75,7 +75,13 @@ export function registerDataRoutes(router: Router, context: AppContext): void {
   router.get('/api/objects/:oid/preview', async ({ res, params, url }) => {
     const table = url.searchParams.get('table') ?? 'raw';
     const limit = Number(url.searchParams.get('limit') ?? '20');
-    const preview = await context.tools.preview(params.oid, table, Math.min(Math.max(limit, 1), 200));
+    const offset = Number(url.searchParams.get('offset') ?? '0');
+    const preview = await context.tools.preview(
+      params.oid,
+      table,
+      Math.min(Math.max(Number.isFinite(limit) ? limit : 20, 1), 200),
+      Math.max(Number.isFinite(offset) ? offset : 0, 0),
+    );
     sendJson(res, 200, preview);
   });
 
@@ -101,6 +107,31 @@ export function registerDataRoutes(router: Router, context: AppContext): void {
     res.end(buffer);
   });
 
+  /** 按行号取一行:溯源 chip 的详情面板用(原文 + 行哈希 + 下钻谓词)。 */
+  router.get('/api/objects/:oid/row', async ({ res, params, url }) => {
+    const table = url.searchParams.get('table') ?? 'raw';
+    const row = Number(url.searchParams.get('row') ?? '0');
+    const data = await context.tools.row(params.oid, table, Number.isFinite(row) ? row : 0);
+    sendJson(res, 200, data);
+  });
+
+  /** 契约里的嵌套写法:/api/workspaces/:id/objects/:oid → 与 /api/objects/:oid 等价。 */
+  router.get('/api/workspaces/:wid/objects/:oid', async ({ res, params }) => {
+    const object = await context.tools.getObject(params.oid);
+    if (object.workspace_id !== params.wid) {
+      throw notFound(`对象 ${params.oid} 不属于工作区 ${params.wid}`);
+    }
+    sendJson(res, 200, object);
+  });
+
+  /** 契约里的嵌套写法:/api/workspaces/:id/objects/:oid/lineage */
+  router.get('/api/workspaces/:wid/objects/:oid/lineage', async ({ res, params, url }) => {
+    const table = url.searchParams.get('table') ?? undefined;
+    const row = url.searchParams.get('row');
+    const lineage = await context.tools.lineage(params.oid, table, row === null ? undefined : Number(row));
+    sendJson(res, 200, lineage);
+  });
+
   // ------------------------------------------------------------ 处理任务
   router.post('/api/process', async ({ res, json }) => {
     const body = json<{
@@ -133,6 +164,60 @@ export function registerDataRoutes(router: Router, context: AppContext): void {
     sendJson(res, 200, run);
   });
 
+  /**
+   * 处理进度 SSE(架构文档 4.2 要求的形态)。
+   * 先同步确认任务存在(不存在就走 JSON 404),再开流。
+   */
+  router.get('/api/process/:runId/stream', async ({ res, params, req }) => {
+    const first = await context.tools.getRun(params.runId);
+    const sse = new SseStream(res);
+    let stopped = false;
+    req.on('close', () => {
+      stopped = true;
+    });
+
+    const push = async () => {
+      try {
+        const run = await context.tools.getRun(params.runId);
+        sse.send('progress', {
+          run_id: run.id,
+          status: run.status,
+          progress: run.progress,
+          message: run.message,
+          object_id: run.object_id,
+          error: run.error,
+        });
+        if (run.status === 'succeeded' || run.status === 'failed') {
+          sse.send('done', { run_id: run.id, status: run.status, object_id: run.object_id, error: run.error });
+          stopped = true;
+          sse.close();
+        }
+      } catch (error) {
+        sse.send('error', { message: (error as Error).message });
+        stopped = true;
+        sse.close();
+      }
+    };
+
+    sse.send('progress', {
+      run_id: first.id,
+      status: first.status,
+      progress: first.progress,
+      message: first.message,
+      object_id: first.object_id,
+      error: first.error,
+    });
+
+    const timer = setInterval(() => {
+      if (stopped) {
+        clearInterval(timer);
+        return;
+      }
+      void push();
+    }, 400);
+    res.on('close', () => clearInterval(timer));
+  });
+
   // ------------------------------------------------------------ 台账(数据面)
   router.get('/api/ledger/stats', async ({ res }) => {
     const stats = await context.tools.ledgerStats();

+ 10 - 1
bff/src/routes/sessions.ts

@@ -1,4 +1,4 @@
-/** 会话接口:列表、创建、历史消息、删除。 */
+/** 会话接口:列表、创建、历史消息、删除。 */
 import type { Router } from '../http/server.js';
 import { sendJson } from '../http/server.js';
 import { badRequest, notFound } from '../util/common.js';
@@ -55,6 +55,15 @@ export function registerSessionRoutes(router: Router, context: AppContext): void
     sendJson(res, 200, { ok: true });
   });
 
+  /** 单次调用详情:溯源 chip 若是 calculator 产出,用它展示算式与输入。 */
+  router.get('/api/sessions/:id/ledger/:callId', async ({ res, params }) => {
+    const session = context.sessions.get(params.id);
+    if (!session) throw notFound(`会话不存在: `+params.id);
+    const call = context.ledger.callOf(params.callId);
+    if (!call || String(call.session_id) !== params.id) throw notFound(`该会话没有这次调用: `+params.callId);
+    sendJson(res, 200, { call, values: context.ledger.valuesOf(params.callId) });
+  });
+
   router.get('/api/sessions/:id/ledger', async ({ res, params }) => {
     const session = context.sessions.get(params.id);
     if (!session) throw notFound(`会话不存在: ${params.id}`);

+ 30 - 0
bff/src/store/ledger.ts

@@ -144,6 +144,27 @@ export class SessionLedger {
     );
   }
 
+  /** 单次调用详情(chip 点开时展示"这次计算/读取做了什么")。 */
+  callOf(callId: string): Record<string, unknown> | null {
+    const row = this.db.get<Record<string, unknown>>('SELECT * FROM ledger_calls WHERE call_id=?', callId);
+    if (!row) return null;
+    return {
+      ...row,
+      args: safeParse(row.args_json),
+      object_ids: safeParse(row.object_ids),
+    };
+  }
+
+  /** 某次调用返回过的字段值(用于"这个数在该次结果里出现过几次")。 */
+  valuesOf(callId: string, limit = 50): Array<Record<string, unknown>> {
+    return this.db.all(
+      `SELECT field,value_text,value_num,row_index,table_name,object_id FROM ledger_values
+       WHERE call_id=? ORDER BY rowid LIMIT ?`,
+      callId,
+      limit,
+    );
+  }
+
   callsOf(sessionId: string): Array<Record<string, unknown>> {
     return this.db.all(
       `SELECT call_id,tool,args_hash,result_hash,row_count,object_ids,created_at
@@ -162,3 +183,12 @@ export class SessionLedger {
     return { calls: calls?.c ?? 0, indexed_values: values?.c ?? 0 };
   }
 }
+
+function safeParse(text: unknown): unknown {
+  if (typeof text !== 'string' || !text) return null;
+  try {
+    return JSON.parse(text);
+  } catch {
+    return text;
+  }
+}

+ 33 - 3
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';
 
@@ -166,11 +166,41 @@ export class ToolsClient {
     );
   }
 
-  preview(objectId: string, table = 'raw', limit = 20): Promise<{ columns: string[]; rows: unknown[]; total: number }> {
-    const query = new URLSearchParams({ table, limit: String(limit) });
+  preview(
+    objectId: string,
+    table = 'raw',
+    limit = 20,
+    offset = 0,
+  ): Promise<{
+    columns: string[];
+    rows: unknown[];
+    row_indexes: number[];
+    row_hashes: string[];
+    offset: number;
+    limit: number;
+    total: number;
+  }> {
+    const query = new URLSearchParams({ table, limit: String(limit), offset: String(offset) });
     return this.request(`/objects/${encodeURIComponent(objectId)}/preview?${query}`);
   }
 
+  /** 按行号取一行:溯源 chip 点开详情时用(原文 + 行哈希 + 行级血缘)。 */
+  row(
+    objectId: string,
+    table: string,
+    rowIndex: number,
+  ): Promise<{
+    object_id: string;
+    table: string;
+    row_index: number;
+    row_hash: string;
+    values: Record<string, unknown>;
+    lineage: Record<string, unknown> | null;
+  }> {
+    const query = new URLSearchParams({ table, row: String(rowIndex) });
+    return this.request(`/objects/${encodeURIComponent(objectId)}/row?${query}`);
+  }
+
   lineage(objectId: string, table?: string, row?: number): Promise<Record<string, unknown>> {
     const query = new URLSearchParams();
     if (table) query.set('table', table);

+ 83 - 0
bff/test/api.test.ts

@@ -193,3 +193,86 @@ test('未知接口返回结构化 404', async () => {
   const payload = await response.json();
   assert.equal((payload as any).error, 'NOT_FOUND');
 });
+
+test('按行取数(溯源抽屉)与嵌套对象路径', async () => {
+  const row = await api<any>('/api/objects/obj_stat/row?table=1.0-3.0_MLCC&row=1');
+  assert.equal(row.row_index, 1);
+  assert.equal(row.values['基础类目'], '多层瓷介电容器(MLCC)');
+  assert.match(row.row_hash, /^sha256:/);
+
+  // 契约里的嵌套写法应等价
+  const nested = await api<any>('/api/workspaces/ws_test/objects/obj_stat');
+  assert.equal(nested.id, 'obj_stat');
+  await assert.rejects(() => api('/api/workspaces/ws_other/objects/obj_stat'), /404/);
+
+  const missing = await fetch(`${base}/api/objects/obj_stat/row?table=1.0-3.0_MLCC&row=9999`);
+  assert.equal(missing.status, 404);
+});
+
+test('预览支持 offset 与行号(用于高亮跳转)', async () => {
+  const preview = await api<any>('/api/objects/obj_stat/preview?table=1.0-3.0_MLCC&limit=2&offset=1');
+  assert.equal(preview.offset, 1);
+  assert.deepEqual(preview.row_indexes, [1]);
+  assert.equal(preview.total, 2);
+});
+
+test('处理进度 SSE 推送 progress 与 done', async () => {
+  const run = await api<any>('/api/process', {
+    method: 'POST',
+    headers: { 'Content-Type': 'application/json' },
+    body: JSON.stringify({ workspace_id: 'ws_test', input_object_id: 'obj_raw' }),
+  });
+  const response = await fetch(`${base}/api/process/${run.id}/stream`);
+  assert.equal(response.status, 200);
+  assert.match(response.headers.get('content-type') ?? '', /text\/event-stream/);
+  const events = await collectSse(response);
+  const names = events.map((event) => event.event);
+  assert.ok(names.includes('progress'), '缺少 progress 事件');
+  assert.ok(names.includes('done'), '缺少 done 事件');
+  const done = events.find((event) => event.event === 'done')!.data;
+  assert.equal(done.status, 'succeeded');
+  assert.equal(done.object_id, 'obj_stat');
+
+  const missing = await fetch(`${base}/api/process/run_not_exist/stream`);
+  assert.equal(missing.status, 404);
+});
+
+test('会话台账单次调用详情(calculator chip 用)', async () => {
+  // 这个用例需要一次"干净"的对话(剧本客户端是有状态的),所以自己起一个服务实例
+  const llm = new ReplayLlmClient([
+    { toolCalls: [{ name: 'data_read', arguments: { object_id: 'obj_stat', table: '1.0-3.0_MLCC' } }] },
+    { text: '2025 年 1 月 MLCC 进口额为 400316.13 美元。' },
+  ]);
+  const fresh = createApp({ settings: testSettings(tempDir()), tools: asToolsClient(fake), llm, serveStatic: false });
+  const running = await listen(fresh.server);
+  try {
+    const create = await fetch(`${running.url}/api/sessions`, {
+      method: 'POST',
+      headers: { 'Content-Type': 'application/json' },
+      body: JSON.stringify({ workspace_id: 'ws_test' }),
+    });
+    const session = (await create.json()) as any;
+    const chat = await fetch(`${running.url}/api/sessions/${session.id}/chat`, {
+      method: 'POST',
+      headers: { 'Content-Type': 'application/json' },
+      body: JSON.stringify({ message: '2025 年 1 月 MLCC 进口额是多少?' }),
+    });
+    const events = await collectSse(chat);
+    const final = events.find((event) => event.event === 'final')!.data;
+    assert.equal(final.verification, 'accept');
+
+    const ledger = (await (await fetch(`${running.url}/api/sessions/${session.id}/ledger`)).json()) as any;
+    assert.ok(ledger.calls.length >= 1, '应该有台账记录');
+    const call = ledger.calls[0];
+    const detail = (await (await fetch(`${running.url}/api/sessions/${session.id}/ledger/${call.call_id}`)).json()) as any;
+    assert.equal(detail.call.call_id, call.call_id);
+    assert.equal(detail.call.tool, 'data_read');
+    assert.ok(Array.isArray(detail.values) && detail.values.length > 0);
+    assert.equal(detail.call.args.object_id, 'obj_stat');
+
+    const wrongSession = await fetch(`${running.url}/api/sessions/sess_other/ledger/${call.call_id}`);
+    assert.equal(wrongSession.status, 404);
+  } finally {
+    await running.close();
+  }
+});

+ 30 - 6
bff/test/fakes.ts

@@ -1,4 +1,4 @@
-/** 测试替身:假的工具服务客户端、临时配置、临时 HTTP 服务。 */
+/** 测试替身:假的工具服务客户端、临时配置、临时 HTTP 服务。 */
 import type { AddressInfo } from 'node:net';
 import type http from 'node:http';
 import { mkdirSync, mkdtempSync } from 'node:fs';
@@ -6,6 +6,7 @@ import os from 'node:os';
 import path from 'node:path';
 import type { Settings } from '../src/config.js';
 import type { ToolsClient, ObjectInfo, RunInfo, WorkspaceInfo } from '../src/tools/client.js';
+import { HttpError } from '../src/util/common.js';
 
 export function tempDir(prefix = 'cda-test-'): string {
   const directory = mkdtempSync(path.join(os.tmpdir(), prefix));
@@ -93,7 +94,7 @@ export class FakeToolsClient {
 
   async getObject(objectId: string) {
     const item = this.objects.find((entry) => entry.id === objectId);
-    if (!item) throw Object.assign(new Error(`对象不存在: ${objectId}`), { status: 404 });
+    if (!item) throw new HttpError(404, `对象不存在: ${objectId}`);
     return item;
   }
 
@@ -108,9 +109,32 @@ export class FakeToolsClient {
     return object;
   }
 
-  async preview(objectId: string, table = 'raw', limit = 20) {
-    const rows = this.dataRows[`${objectId}:${table}`] ?? [];
-    return { columns: Object.keys(rows[0]?.values ?? {}), rows: rows.slice(0, limit).map((row) => row.values), total: rows.length };
+  async preview(objectId: string, table = 'raw', limit = 20, offset = 0) {
+    const all = this.dataRows[`${objectId}:${table}`] ?? [];
+    const page = all.slice(offset, offset + limit);
+    return {
+      columns: Object.keys(all[0]?.values ?? {}),
+      rows: page.map((row) => row.values),
+      row_indexes: page.map((row) => row.row_index ?? 0),
+      row_hashes: page.map((row) => row.row_hash ?? 'sha256:x'),
+      offset,
+      limit,
+      total: all.length,
+    };
+  }
+
+  async row(objectId: string, table: string, rowIndex: number) {
+    const all = this.dataRows[`${objectId}:${table}`] ?? [];
+    const row = all.find((item) => (item.row_index ?? 0) === rowIndex);
+    if (!row) throw new HttpError(404, `表 ${table} 中没有第 ${rowIndex} 行`);
+    return {
+      object_id: objectId,
+      table,
+      row_index: rowIndex,
+      row_hash: row.row_hash ?? 'sha256:x',
+      values: row.values,
+      lineage: { source_object_id: 'obj_raw', source_rows: { year: '2025' } },
+    };
   }
 
   async lineage(objectId: string) {
@@ -141,7 +165,7 @@ export class FakeToolsClient {
 
   async getRun(runId: string) {
     const run = this.runs.find((item) => item.id === runId);
-    if (!run) throw Object.assign(new Error('任务不存在'), { status: 404 });
+    if (!run) throw new HttpError(404, '任务不存在');
     return run;
   }
 

+ 17 - 1
docs/01-架构设计.md

@@ -1,4 +1,4 @@
-# 架构设计
+# 架构设计
 
 > 本文说明"为什么这样分层",以及每一层的职责边界。具体代码位置与接口细节见
 > [02-实现说明.md](02-实现说明.md)。
@@ -219,6 +219,22 @@ local:    { baseUrl: CDA_LOCAL_BASE_URL (默认 http://127.0.0.1:11434/v1), mode
 
 ---
 
+## 7.1 与架构文档的逐条对照
+
+| 架构文档要求 | 实现情况 |
+|---|---|
+| 五层架构(前端 / BFF / Harness / 工具执行 / 台账核验) | 一致 |
+| Agent Preset(`agent.cordis.yml`,model / systemPrompt / tools) | 一致 |
+| 三工具 + `finalizeContent` 溯源注入 | 一致;额外加只读辅助工具 `list_objects` 供模型定位 `object_id` |
+| `data_read` 返回子集 + 每行 `_trace` | 一致 |
+| `calculator` 输入带来源(`from_call_id` + `row_hash`) | 一致,并回填 `verified` |
+| 核验三段式 accept/flag/reject + reject 重试一次 | 一致 |
+| reject 时"不推送 final 事件" | **改为**推 `final{delivered:false}`:完全断流会让前端无法结束状态,改用显式标记,语义等价且更稳 |
+| 溯源 chip 可点击 → 侧边面板 → 跳转到结果行 | 一致(`TraceDrawer` + `#/files?object=&table=&row=` 深链 + 行高亮) |
+| `/api/process` 返回进度 SSE | 一致(`GET /api/process/:id/stream`,前端优先用 SSE,断了退轮询) |
+| 工作区元数据由 BFF 维护在 SQLite | **改在工具服务**:对象/血缘/台账只有一个数据源,BFF 不再重复存;BFF 只存会话与核验索引 |
+| 用 DSH 官方运行时 + `dsh-sdk-client` | **改用内嵌 Harness**:SDK 依赖未公开发布的包(`dsh-type-meta` 等在公共 npm 404),离线机器装不上;语义对齐并留了 `dshAdapter` 接缝 |
+| 本地模型(dsh-local-model / llm-pi-ai 自定义 provider) | 目前用 DeepSeek API;`provider: local` + `CDA_LOCAL_BASE_URL` 即可切换,未接真机验证 |
 ## 8. 扩展点
 
 | 想做什么 | 改哪里 |

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

@@ -171,17 +171,21 @@ verifications(id, session_id, message_id, verdict, payload, created_at)
 | POST | `/api/workspaces/:id/files` | 上传。`multipart/form-data` 字段 `file`;或 `application/octet-stream` + `X-Filename`(URL 编码) |
 | GET | `/api/objects/:oid` | 对象详情(表清单、血缘、统计) |
 | DELETE | `/api/objects/:oid` | 删除对象(物理删除) |
-| GET | `/api/objects/:oid/preview?table=&limit=` | 预览某表前 N 行 |
+| GET | `/api/objects/:oid/preview?table=&limit=&offset=` | 预览某表(支持偏移,用于定位到某一行) |
 | GET | `/api/objects/:oid/lineage?table=&row=` | 行级血缘(含 `source_rows` 谓词) |
+| GET | `/api/objects/:oid/row?table=&row=` | **按行取数**:该行原文 + 行哈希 + 下钻谓词(溯源抽屉用) |
+| GET | `/api/workspaces/:wid/objects/:oid` | 契约里的嵌套写法(等价于 `/api/objects/:oid`,会校验工作区归属) |
 | GET | `/api/objects/:oid/download?name=` | 下载对象内文件(如 `统计结果.xlsx`) |
 | POST | `/api/process` | 起处理任务 `{workspace_id, input_object_id, operation, options, output_name}` |
 | GET | `/api/process` | 最近任务列表 |
 | GET | `/api/process/:runId` | 任务进度 `{status, progress, message, object_id, error}` |
+| GET | `/api/process/:runId/stream` | **进度 SSE**:`progress` 事件流 + 结束时的 `done` 事件 |
 | GET/POST | `/api/sessions` | 会话列表 / 创建 `{workspace_id, title?}` |
 | GET | `/api/sessions/:id/messages` | 历史消息(含工具调用、核验结果) |
 | PUT | `/api/sessions/:id` | 重命名 |
 | DELETE | `/api/sessions/:id` | 删除会话(含台账) |
 | GET | `/api/sessions/:id/ledger` | 会话台账摘要 + 调用列表 |
+| GET | `/api/sessions/:id/ledger/:callId` | 单次调用详情(calculator chip 用它展示算式与输入) |
 | **POST** | **`/api/sessions/:id/chat`** | **SSE 对话**(见 3.3) |
 | GET | `/api/ledger/stats` | 数据面 + 会话台账统计与哈希链校验 |
 
@@ -206,6 +210,13 @@ verifications(id, session_id, message_id, verdict, payload, created_at)
 | POST | `/tools/calculator` | 计算 |
 | GET | `/ledger/stats`、`/ledger/calls`、`/ledger/value`、`/ledger/call/:id`、`/ledger/export` | 台账 |
 
+### 3.2.1 前端的三个交互闭环
+
+| 闭环 | 链路 |
+|---|---|
+| 数字溯源 | 答案里的 chip(`TraceChips`)→ 点击 → `TraceDrawer` 调 `GET /api/objects/:oid/row?table=&row=` → 展示对象/表/行号/行哈希 + 该行全部字段(命中的字段高亮)+ 下钻谓词;calculator 产生的数字改调 `GET /api/sessions/:sid/ledger/:callId` 展示算式与输入 |
+| 跳转到结果行 | 抽屉底部"在结果表中查看这一行" → 写 `#/files?object=&table=&row=` → `FilesPage` 解析深链(`parseDeepLink`)→ 用 `preview` 的 `offset` 把目标行滚进窗口(`offset = max(0, row - 3)`)→ 表格高亮该行并 `scrollIntoView` |
+| 处理进度 | `POST /api/process` 拿到 run id → `GET /api/process/:id/stream`(SSE)逐条 `progress` → `done` 时加载结果对象;流断了自动退回 700ms 轮询 |
 ### 3.3 对话 SSE 事件
 
 ```text

+ 21 - 0
docs/03-使用手册.md

@@ -227,6 +227,27 @@ CSV 第一行是字段名,至少要有这 7 列(大小写要与下表一致
   哪张表、第几行;
 - 最下面一个 **"数据核验通过"** 的条,点开能看到回答里每个数字的核对结果。
 
+### 5.0 想确认某个数字怎么来的?点它
+
+回答下面那一行小标签(**溯源 chip**)现在可以点:
+
+1. 点 `400316.13` 这样的标签 → 右侧滑出「数字溯源」面板:
+
+   ![溯源抽屉](images/05-trace-drawer.png)
+
+   - 上面:这个数字本身、核验状态;
+   - 中间:它在**哪个对象、哪张表、第几行**,以及那一行的**行哈希**(可以拿去复核);
+   - 下面:这一行的**全部字段原文**(当前字段高亮),和"下钻条件"(这批数据的筛选范围);
+   - 最下面:**在结果表中查看这一行**。
+
+2. 点「在结果表中查看这一行」→ 自动跳到"文件"页,打开那张表,滚到那一行并**蓝色高亮**:
+
+   ![跳转高亮](images/06-row-jump.png)
+
+3. 如果这个数字是**计算**出来的(换算成万美元、合计、占比等),面板会显示"计算 ID / 参数 / 结果哈希",
+   说明它是 `calculator` 算出来的——这正是它能通过核验的原因。
+
+> 换句话说:**任何你不放心的数字,都能一路点回原始表格的某一格。**
 ### 5.1 三类核验结论
 
 | 结论 | 含义 | 你要做什么 |

+ 20 - 7
docs/05-测试报告.md

@@ -22,10 +22,10 @@
 | 测试组 | 用例数 | 结果 | 覆盖 |
 |---|---|---|---|
 | Python 引擎与接口(pytest) | **85** | 全部通过 | 数值/权重、规则解析、入库与周四归月、23 张报表口径、对象库、血缘、`data_read`、`calculator`、台账、HTTP 接口 |
-| BFF 单元与接口(node:test) | **54** | 全部通过 | YAML 解析、Preset、数字抽取、核验裁决、工具注册与 `finalizeContent`、Agent Loop、HTTP 接口、SSE 对话、multipart |
-| 前端单元 + 渲染(vitest) | **23** | 全部通过 | 数值/百分比/时间格式化、表名分类、图表数据构造、列推断,以及用 SSR 渲染 App / 消息 / 核验面板 / Markdown 组件 |
-| 端到端联调(真实服务 + 真实模型) | **28 项检查** | 全部通过(连续 3 次) | 上传→处理→23 表→预览→血缘→下载→指数口径→自定义聚合→台账→**真实模型对话 + 核验**→前端托管 |
-| **合计** | **190** | **全部通过** | |
+| BFF 单元与接口(node:test) | **58** | 全部通过 | YAML 解析、Preset、数字抽取、核验裁决、工具注册与 `finalizeContent`、Agent Loop、HTTP 接口、SSE 对话、multipart |
+| 前端单元 + 渲染(vitest) | **27** | 全部通过 | 数值/百分比/时间格式化、表名分类、图表数据构造、列推断,以及用 SSR 渲染 App / 消息 / 核验面板 / Markdown 组件 |
+| 端到端联调(真实服务 + 真实模型) | **33 项检查** | 全部通过 | 上传→处理→23 表→预览→血缘→下载→指数口径→自定义聚合→台账→**真实模型对话 + 核验**→前端托管 |
+| **合计** | **203** | **全部通过** | |
 
 一键复现:
 
@@ -113,7 +113,7 @@ sum/mean/median/min/max/count/growth/ratio/index/share 正确性;
 
 ---
 
-## 4. BFF 测试(54 项)
+## 4. BFF 测试(58 项)
 
 ### 4.1 `yaml.test.ts`(8)
 
@@ -147,7 +147,7 @@ sum/mean/median/min/max/count/growth/ratio/index/share 正确性;
 Agent Loop 完整一轮(工具调用→结果回灌→最终答案,且第二次请求带上 `verification_context`)、
 一轮多个工具调用、达到 `maxSteps` 后禁用工具强制总结、LLM 异常产出 error 事件,以及 `collectScalars`(只收标量、跳过 rows/令牌)与"标量也写进台账"。
 
-### 4.5 `api.test.ts`(12)
+### 4.5 `api.test.ts`(16)
 
 健康检查/Meta、工作区 CRUD、**multipart 真实边界解析**(含中文文件名)、
 原始字节上传、对象预览与下载、处理任务、会话 CRUD、
@@ -156,7 +156,7 @@ Agent Loop 完整一轮(工具调用→结果回灌→最终答案,且第二
 
 ---
 
-## 5. 前端测试(23 项)
+## 5. 前端测试(27 项)
 
 `formatNumber`(千分位/小数/空值)、`formatPercent`、`formatBytes`、
 `relativeTime`(刚刚/分钟/小时/天/日期)、`classifySheet`(MLCC 四层级、存储器、补充表、raw)、
@@ -233,6 +233,19 @@ Agent Loop 完整一轮(工具调用→结果回灌→最终答案,且第二
 
 修复后连续 3 次端到端运行均 28/28 通过,对话裁决稳定为 ccept。
 
+### 6.2 真实浏览器交互验证(CDP 探针)
+
+`node scripts/ui_probe.mjs` 用 Chrome DevTools Protocol 驱动无头浏览器**真点一遍**,
+而不是只做 SSR 渲染:
+
+| 步骤 | 断言 | 结果 |
+|---|---|---|
+| 打开对话页 | 页面上存在 `.chip` 元素 | ✓(3 个) |
+| 点击第一个 chip | `.drawer` 出现且含"数字溯源" | ✓(对象/表/第 55 行/行哈希都在) |
+| 点击"在结果表中查看这一行" | `.modal` 打开且 `.data-table tr.highlight` ≥ 1 | ✓(高亮 1 行,正是金额 1,957,713.4 那行) |
+| 逐页截图 | 对话/抽屉/跳转/处理/文件/系统 | ✓ 6 张(`docs/images/`) |
+
+这一步抓出并修掉了"抽屉里年度显示成 2,026"的问题(与表格列同一类问题)。
 ## 7. 手工验证过的场景
 
 | 场景 | 结果 |

BIN
docs/images/01-chat.png


BIN
docs/images/02-process.png


BIN
docs/images/03-files.png


BIN
docs/images/04-system.png


BIN
docs/images/05-trace-drawer.png


BIN
docs/images/06-row-jump.png


+ 2 - 1
package.json

@@ -1,4 +1,4 @@
-{
+{
   "name": "customs-data-agent",
   "version": "1.0.0",
   "private": true,
@@ -9,6 +9,7 @@
     "stop": "node scripts/stop.mjs",
     "e2e": "node scripts/e2e.mjs",
     "e2e:data": "node scripts/e2e.mjs --no-chat",
+    "ui": "node scripts/ui_probe.mjs",
     "samples": "python scripts/gen_sample_data.py",
     "test": "powershell -NoProfile -ExecutionPolicy Bypass -File scripts/run_tests.ps1"
   }

+ 25 - 12
scripts/e2e.mjs

@@ -1,4 +1,4 @@
-#!/usr/bin/env node
+#!/usr/bin/env node
 /**
  * 端到端联调测试:真实启动 Python 工具服务 + BFF,跑完整业务链路。
  *
@@ -254,17 +254,16 @@ async function main() {
   });
   check(run.ok, '创建处理任务', run.payload);
   const runId = run.payload?.id;
-  let current = null;
-  const deadline = Date.now() + 600_000;
-  while (Date.now() < deadline) {
-    const state = await api(`/api/process/${runId}`);
-    current = state.payload;
-    if (current.status === 'succeeded' || current.status === 'failed') break;
-    process.stdout.write(`\r  ${C.dim}处理进度 ${Math.round((current.progress ?? 0) * 100)}% ${current.message ?? ''}${C.reset}   `);
-    await new Promise((resolve) => setTimeout(resolve, 800));
-  }
-  process.stdout.write('\r' + ' '.repeat(70) + '\r');
-  check(current?.status === 'succeeded', `处理完成(${current?.status})`, current?.error);
+  // 进度用 SSE 观察(契约要求的形态),顺便统计 progress 事件数量
+  const streamResponse = await fetch(`${BFF_URL}/api/process/${runId}/stream`);
+  check(streamResponse.ok, '进度 SSE 端点可用(text/event-stream)');
+  const streamText = await streamResponse.text();
+  const progressCount = (streamText.match(/event: progress/g) || []).length;
+  const doneMatch = /event: done\ndata: (.*)/.exec(streamText);
+  const done = doneMatch ? JSON.parse(doneMatch[1]) : null;
+  check(progressCount >= 2, `通过 SSE 收到 ${progressCount} 个进度事件`);
+  check(done?.status === 'succeeded', `SSE 结束事件 status=${done?.status}`);
+  const current = done;
   const statId = current?.object_id;
   const statObject = (await api(`/api/objects/${statId}`)).payload;
   check(statObject?.tables?.length === 23, `生成 ${statObject?.tables?.length} 张结果表`, statObject?.tables?.map((t) => t.name));
@@ -277,6 +276,20 @@ async function main() {
   check(preview.ok && preview.payload.rows.length === 3, `预览 ${tableName} 前 3 行`, preview.payload);
   const lineage = await api(`/api/objects/${statId}/lineage?table=${encodeURIComponent(tableName)}&row=0`);
   check(lineage.ok && lineage.payload.source_object_id === uploaded.id, '第 0 行可下钻到原始数据(行级血缘)', lineage.payload);
+  // 溯源 chip 点开时用的"按行取数"
+  const rowDetail = await api(`/api/objects/${statId}/row?table=${encodeURIComponent(tableName)}&row=0`);
+  check(
+    rowDetail.ok && rowDetail.payload.row_hash?.startsWith('sha256:') && rowDetail.payload.values?.['基础类目'],
+    '按行取数返回原文 + 行哈希(溯源抽屉)',
+    rowDetail.payload,
+  );
+  check(
+    Boolean(rowDetail.payload?.lineage?.source_rows),
+    '该行带下钻谓词(可回到原始记录范围)',
+    rowDetail.payload?.lineage,
+  );
+  const rowMissing = await fetch(`${BFF_URL}/api/objects/${statId}/row?table=${encodeURIComponent(tableName)}&row=99999`);
+  check(rowMissing.status === 404, '越界行号返回 404(不 500)');
   const download = await fetch(`${BFF_URL}/api/objects/${statId}/download?name=${encodeURIComponent('统计结果.xlsx')}`);
   const buffer = Buffer.from(await download.arrayBuffer());
   check(download.ok && buffer.subarray(0, 2).toString() === 'PK', `下载 统计结果.xlsx(${Math.round(buffer.length / 1024)} KB)`);

+ 6 - 1
scripts/run_tests.ps1

@@ -6,7 +6,7 @@
 #   pwsh -File scripts/run_tests.ps1 -Only python # 只跑某一组
 # =============================================================================
 param(
-  [ValidateSet('all', 'python', 'bff', 'web', 'e2e')]
+  [ValidateSet('all', 'python', 'bff', 'web', 'e2e', 'ui')]
   [string]$Only = 'all',
   [switch]$SkipE2E
 )
@@ -69,6 +69,11 @@ if (($Only -in @('all', 'e2e')) -and (-not $SkipE2E)) {
   Invoke-Suite '端到端联调(真实服务 + 真实模型)' $root 'node' @('scripts/e2e.mjs')
 }
 
+# ------------------------------------------------------------------ 浏览器交互
+if ($Only -in @('all', 'ui')) {
+  Invoke-Suite '真实浏览器交互探针(CDP)' $root 'node' @('scripts/ui_probe.mjs')
+}
+
 # ------------------------------------------------------------------ 汇总
 Write-Section '测试汇总'
 $results | ForEach-Object {

+ 222 - 0
scripts/ui_probe.mjs

@@ -0,0 +1,222 @@
+#!/usr/bin/env node
+/**
+ * 用 Chrome DevTools Protocol 驱动无头浏览器做"真实交互"验证(截图 + 点击)。
+ *
+ *   node scripts/ui_probe.mjs [--url http://127.0.0.1:8787] [--out .run/ui]
+ *
+ * 为什么需要它:SSR 渲染测试覆盖不到"点击 chip → 抽屉 → 跳转到结果行",
+ * 而这正是架构文档要求的交互。这里用 CDP 真点一遍并截图,产物可直接放进文档。
+ */
+import { spawn, spawnSync } from 'node:child_process';
+import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+
+const ROOT = path.resolve(import.meta.dirname, '..');
+const args = process.argv.slice(2);
+const argOf = (name, fallback) => {
+  const index = args.indexOf(name);
+  return index >= 0 && args[index + 1] ? args[index + 1] : fallback;
+};
+
+const BASE = argOf('--url', 'http://127.0.0.1:8787');
+const OUT = path.resolve(ROOT, argOf('--out', '.run/ui'));
+const PORT = 9333;
+
+const CHROME_CANDIDATES = [
+  'C:/Program Files/Google/Chrome/Application/chrome.exe',
+  'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',
+  'C:/Program Files/Microsoft/Edge/Application/msedge.exe',
+  '/usr/bin/google-chrome',
+  '/usr/bin/chromium',
+];
+
+function findBrowser() {
+  for (const candidate of CHROME_CANDIDATES) {
+    if (existsSync(candidate)) return candidate;
+  }
+  return null;
+}
+
+const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
+
+class Cdp {
+  constructor(ws) {
+    this.ws = ws;
+    this.id = 0;
+    this.pending = new Map();
+    ws.addEventListener('message', (event) => {
+      const payload = JSON.parse(event.data);
+      if (payload.id && this.pending.has(payload.id)) {
+        const { resolve, reject } = this.pending.get(payload.id);
+        this.pending.delete(payload.id);
+        payload.error ? reject(new Error(JSON.stringify(payload.error))) : resolve(payload.result);
+      }
+    });
+  }
+
+  send(method, params = {}) {
+    const id = ++this.id;
+    return new Promise((resolve, reject) => {
+      this.pending.set(id, { resolve, reject });
+      this.ws.send(JSON.stringify({ id, method, params }));
+      setTimeout(() => {
+        if (this.pending.has(id)) {
+          this.pending.delete(id);
+          reject(new Error(`CDP 超时: ${method}`));
+        }
+      }, 30000);
+    });
+  }
+
+  async evaluate(expression) {
+    const result = await this.send('Runtime.evaluate', {
+      expression,
+      awaitPromise: true,
+      returnByValue: true,
+    });
+    if (result.exceptionDetails) throw new Error(result.exceptionDetails.text ?? '页面内异常');
+    return result.result?.value;
+  }
+
+  async screenshot(file) {
+    const { data } = await this.send('Page.captureScreenshot', { format: 'png' });
+    writeFileSync(file, Buffer.from(data, 'base64'));
+    return file;
+  }
+}
+
+async function main() {
+  const browser = findBrowser();
+  if (!browser) {
+    console.error('✗ 找不到 Chrome/Edge,可手动截图;本脚本已跳过');
+    process.exit(0);
+  }
+  mkdirSync(OUT, { recursive: true });
+
+  const child = spawn(
+    browser,
+    [
+      '--headless=new',
+      '--disable-gpu',
+      '--hide-scrollbars',
+      '--no-first-run',
+      '--no-default-browser-check',
+      `--remote-debugging-port=${PORT}`,
+      `--user-data-dir=${path.join(OUT, 'profile')}`,
+      '--window-size=1500,1150',
+      'about:blank',
+    ],
+    { stdio: 'ignore' },
+  );
+
+  let wsUrl = null;
+  for (let attempt = 0; attempt < 40 && !wsUrl; attempt += 1) {
+    await sleep(250);
+    try {
+      const targets = await (await fetch(`http://127.0.0.1:${PORT}/json/list`)).json();
+      wsUrl = targets.find((item) => item.type === 'page')?.webSocketDebuggerUrl ?? null;
+    } catch {
+      /* 还没起来 */
+    }
+  }
+  if (!wsUrl) {
+    console.error('✗ 浏览器调试端口没有就绪');
+    child.kill();
+    process.exit(1);
+  }
+
+  const socket = new WebSocket(wsUrl);
+  await new Promise((resolve, reject) => {
+    socket.addEventListener('open', resolve, { once: true });
+    socket.addEventListener('error', reject, { once: true });
+  });
+  const cdp = new Cdp(socket);
+  await cdp.send('Page.enable');
+  await cdp.send('Runtime.enable');
+
+  const open = async (hash, waitMs = 2500) => {
+    await cdp.send('Page.navigate', { url: `${BASE}/${hash}` });
+    await sleep(waitMs);
+  };
+
+  const results = [];
+  const shot = async (name) => {
+    const file = path.join(OUT, `${name}.png`);
+    await cdp.screenshot(file);
+    results.push(file);
+    console.log(`  ✓ 截图 ${path.relative(ROOT, file)}`);
+  };
+
+  console.log('1. 打开对话页');
+  await open('#/chat');
+  const chipCount = await cdp.evaluate(`document.querySelectorAll('.chip').length`);
+  console.log(`  页面上有 ${chipCount} 个溯源 chip`);
+  await shot('01-chat-chips');
+
+  if (chipCount > 0) {
+    console.log('2. 点击第一个 chip,检查抽屉是否出现');
+    await cdp.evaluate(`document.querySelector('.chip').click()`);
+    await sleep(1200);
+    const drawerText = await cdp.evaluate(`document.querySelector('.drawer')?.innerText ?? ''`);
+    if (!drawerText.includes('数字溯源')) {
+      console.error('✗ 抽屉没有打开');
+      child.kill();
+      process.exit(1);
+    }
+    console.log('  抽屉内容片段:', drawerText.replace(/\s+/g, ' ').slice(0, 120));
+    await shot('02-trace-drawer');
+
+    console.log('3. 点击"在结果表中查看这一行",检查跳转与高亮');
+    await cdp.evaluate(`
+      (() => {
+        const buttons = [...document.querySelectorAll('.drawer button')];
+        const target = buttons.find((b) => b.textContent.includes('在结果表中查看'));
+        if (!target) return 'no-button';
+        target.click();
+        return 'clicked';
+      })()
+    `);
+    await sleep(2500);
+    const highlighted = await cdp.evaluate(`document.querySelectorAll('.data-table tr.highlight').length`);
+    const modalOpen = await cdp.evaluate(`Boolean(document.querySelector('.modal'))`);
+    console.log(`  弹窗打开: ${modalOpen},高亮行数: ${highlighted}`);
+    await shot('03-row-jump');
+    if (!modalOpen || highlighted < 1) {
+      console.error('✗ 没有定位到结果行');
+      child.kill();
+      process.exit(1);
+    }
+  }
+
+  console.log('4. 数据处理页');
+  await open('#/process');
+  await sleep(1200);
+  await shot('04-process');
+
+  console.log('5. 文件页(含指纹列)');
+  await open('#/files');
+  await sleep(1200);
+  await shot('05-files');
+
+  console.log('6. 系统页(两本台账)');
+  await open('#/system');
+  await sleep(1500);
+  await shot('06-system');
+
+  socket.close();
+  child.kill();
+  try {
+    spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' });
+  } catch {
+    /* 忽略 */
+  }
+  console.log(`\n全部交互验证通过,截图在 ${OUT}`);
+  return results;
+}
+
+main()
+  .then(() => process.exit(0))
+  .catch((error) => {
+    console.error('✗ UI 探针失败:', error.message);
+    process.exit(1);
+  });

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

@@ -250,4 +250,45 @@ def test_customs_process_records_data_plane_ledger(client, workspace, raw_object
     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
+    assert entry["result"]["sheet_count"] == 23
+def test_preview_supports_offset(client, raw_object):
+    first = client.get(f"/objects/{raw_object['id']}/preview", params={"table": "raw", "limit": 3}).json()
+    second = client.get(f"/objects/{raw_object['id']}/preview", params={"table": "raw", "limit": 3, "offset": 2}).json()
+    assert first["row_indexes"] == [0, 1, 2]
+    assert second["offset"] == 2
+    assert second["row_indexes"] == [2, 3, 4]
+    assert first["rows"][2] == second["rows"][0]
+
+
+def test_row_endpoint_returns_text_and_lineage(client, workspace, raw_object):
+    """溯源 chip 点开时按行号取原文:值、行哈希、下钻谓词都要有。"""
+
+    # 先处理出统计结果,stat 行才有血缘谓词
+    processed = client.post(
+        "/tools/customs_process",
+        json={"workspace_id": workspace["id"], "input_object_id": raw_object["id"], "params": {"start_year": 2025, "end_year": 2026}},
+    ).json()
+    stat_id = processed["object_id"]
+
+    response = client.get(f"/objects/{stat_id}/row", params={"table": "1.0-3.0_MLCC", "row": 0})
+    assert response.status_code == 200, response.text
+    payload = response.json()
+    assert payload["row_index"] == 0
+    assert payload["row_hash"].startswith("sha256:")
+    assert payload["values"]["基础类目"]
+    assert payload["lineage"]["source_object_id"] == raw_object["id"]
+    assert payload["lineage"]["source_rows"], "统计行应带下钻谓词"
+
+    missing = client.get(f"/objects/{stat_id}/row", params={"table": "1.0-3.0_MLCC", "row": 999999})
+    assert missing.status_code == 404
+
+
+def test_sheet_meta_endpoint(client, workspace, raw_object):
+    processed = client.post(
+        "/tools/customs_process",
+        json={"workspace_id": workspace["id"], "input_object_id": raw_object["id"]},
+    ).json()
+    meta = client.get(f"/objects/{processed['object_id']}/sheet_meta").json()
+    assert len(meta["tables"]) == 23
+    assert meta["lineage"]["output_hash"].startswith("sha256:")
+    assert meta["parents"] == [raw_object["id"]]

+ 41 - 2
tools-service/toolsvc/api.py

@@ -149,15 +149,54 @@ def delete_object(object_id: str) -> dict:
 
 
 @app.get("/objects/{object_id}/preview")
-def preview_object(object_id: str, table: str = "raw", limit: int = Query(20, ge=1, le=200)) -> dict:
+def preview_object(
+    object_id: str,
+    table: str = "raw",
+    limit: int = Query(20, ge=1, le=200),
+    offset: int = Query(0, ge=0),
+) -> dict:
     try:
-        return store.preview(object_id, table, limit)
+        return store.preview(object_id, table, limit, offset)
     except KeyError as error:
         raise HTTPException(status_code=404, detail=str(error)) from error
     except ReadError as error:
         raise HTTPException(status_code=400, detail=str(error)) from error
 
 
+@app.get("/objects/{object_id}/row")
+def object_row(object_id: str, table: str = "raw", row: int = Query(..., ge=0)) -> dict:
+    """按行号取一行(溯源 chip 点击后要看到"这一行原来是什么")。
+
+    返回该行的原文、行哈希,以及行级血缘(``source_rows`` 谓词,可据此下钻到原始记录)。
+    """
+
+    try:
+        return store.read_row(object_id, table, row)
+    except KeyError as error:
+        raise HTTPException(status_code=404, detail=str(error)) from error
+    except ReadError as error:
+        raise HTTPException(status_code=400, detail=str(error)) from error
+
+
+@app.get("/objects/{object_id}/sheet_meta")
+def object_sheet_meta(object_id: str) -> dict:
+    """结果表的自描述:每张表的行数、列名、行哈希数量(供前端"数据浏览"用)。"""
+
+    try:
+        item = store.get_object(object_id)
+    except KeyError as error:
+        raise HTTPException(status_code=404, detail=str(error)) from error
+    return {
+        "object_id": object_id,
+        "name": item["name"],
+        "kind": item["kind"],
+        "rows": item["rows"],
+        "tables": item["tables"],
+        "lineage": item["meta"].get("lineage", {}),
+        "parents": item["parents"],
+    }
+
+
 @app.get("/objects/{object_id}/lineage")
 def object_lineage(object_id: str, table: str | None = None, row: int | None = None) -> dict:
     try:

+ 32 - 2
tools-service/toolsvc/objects.py

@@ -377,18 +377,48 @@ class ObjectStore:
             raise KeyError(f"对象 {object_id} 中没有表 {table}")
         return Path(sqlite_path), row["sqlite_name"]
 
-    def preview(self, object_id: str, table: str, limit: int = 20) -> dict:
+    def preview(self, object_id: str, table: str, limit: int = 20, offset: int = 0) -> dict:
         from .readers import read_rows
 
-        result = read_rows(object_id, table=table, limit=limit)
+        result = read_rows(object_id, table=table, limit=limit, offset=offset)
         return {
             "object_id": object_id,
             "table": table,
             "columns": result["columns"],
             "rows": [row["values"] for row in result["rows"]],
+            # 行号用于"点 chip 跳到那一行并高亮",前端据此定位
+            "row_indexes": [int(row["_trace"]["row_index"]) for row in result["rows"]],
+            "row_hashes": [row["_trace"]["row_hash"] for row in result["rows"]],
+            "offset": result["offset"],
+            "limit": result["limit"],
             "total": result["total"],
         }
 
+    def read_row(self, object_id: str, table: str, row_index: int) -> dict:
+        """按行号取一行原文 + 行哈希 + 行级血缘(溯源 chip 的详情面板用)。"""
+
+        sqlite_path, sqlite_name = self.table_sqlite(object_id, table)
+        connection = sqlite3.connect(str(sqlite_path))
+        connection.row_factory = sqlite3.Row
+        try:
+            row = connection.execute(
+                f'SELECT * FROM "{sqlite_name}" WHERE "_row_index"=?', (int(row_index),)
+            ).fetchone()
+        finally:
+            connection.close()
+        if row is None:
+            raise KeyError(f"表 {table} 中没有第 {row_index} 行")
+        values = {key: row[key] for key in row.keys() if not key.startswith("_")}
+        lineage = self.row_lineage(object_id, table, int(row_index))
+        return {
+            "object_id": object_id,
+            "table": table,
+            "row_index": int(row_index),
+            "row_hash": row["_row_hash"],
+            "values": values,
+            "lineage": lineage,
+        }
+
 
 DIMENSION_KEYS = {
     "c1",

Datei-Diff unterdrückt, da er zu groß ist
+ 0 - 0
web/dist/assets/index-DcCQIZqN.js


Datei-Diff unterdrückt, da er zu groß ist
+ 0 - 0
web/dist/assets/index-gwqomBW9.css


Datei-Diff unterdrückt, da er zu groß ist
+ 0 - 0
web/dist/assets/index-oisv_dMO.js


+ 2 - 2
web/dist/index.html

@@ -5,8 +5,8 @@
     <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-DcCQIZqN.js"></script>
-    <link rel="stylesheet" crossorigin href="/assets/index-B1dZrLEW.css">
+    <script type="module" crossorigin src="/assets/index-oisv_dMO.js"></script>
+    <link rel="stylesheet" crossorigin href="/assets/index-gwqomBW9.css">
   </head>
   <body>
     <div id="root"></div>

+ 34 - 2
web/src/api/client.ts

@@ -87,8 +87,10 @@ export const api = {
   },
   getObject: (objectId: string) => request<DataObject>(`/api/objects/${objectId}`),
   deleteObject: (objectId: string) => request<{ ok: boolean }>(`/api/objects/${objectId}`, { method: 'DELETE' }),
-  preview: (objectId: string, table: string, limit = 20) =>
-    request<PreviewPayload>(`/api/objects/${objectId}/preview?table=${encodeURIComponent(table)}&limit=${limit}`),
+  preview: (objectId: string, table: string, limit = 20, offset = 0) =>
+    request<PreviewPayload>(
+      `/api/objects/${objectId}/preview?table=${encodeURIComponent(table)}&limit=${limit}&offset=${offset}`,
+    ),
   lineage: (objectId: string, table: string, row: number) =>
     request<Record<string, unknown>>(`/api/objects/${objectId}/lineage?table=${encodeURIComponent(table)}&row=${row}`),
   downloadUrl: (objectId: string, name: string) =>
@@ -104,6 +106,36 @@ export const api = {
   getRun: (runId: string) => request<RunInfo>(`/api/process/${runId}`),
   listRuns: () => request<{ items: RunInfo[] }>('/api/process'),
 
+  /** 处理进度 SSE:返回取消函数 */
+  streamRun(runId: string, handlers: { onProgress(run: any): void; onDone(run: any): void; onError(error: Error): void }): () => void {
+    const controller = new AbortController();
+    (async () => {
+      try {
+        const response = await fetch(`${BASE}/api/process/${runId}/stream`, { signal: controller.signal });
+        if (!response.ok || !response.body) throw new ApiError(response.status, `进度流打开失败(HTTP ${response.status})`);
+        await consumeSse(response.body, {
+          onEvent(event, data) {
+            if (event === 'progress') handlers.onProgress(data);
+            else if (event === 'done') handlers.onDone(data);
+            else if (event === 'error') handlers.onError(new ApiError(500, data.message ?? '进度流出错'));
+          },
+          onError: handlers.onError,
+          onClose: () => undefined,
+        }, controller.signal);
+      } catch (error) {
+        if ((error as Error).name !== 'AbortError') handlers.onError(error as Error);
+      }
+    })();
+    return () => controller.abort();
+  },
+
+  /** 按行号取一行(溯源抽屉) */
+  objectRow: (objectId: string, table: string, row: number) =>
+    request<Record<string, any>>(`/api/objects/${objectId}/row?table=${encodeURIComponent(table)}&row=${row}`),
+  /** 会话台账里某次调用的详情(calculator chip 用) */
+  sessionLedgerCall: (sessionId: string, callId: string) =>
+    request<Record<string, any>>(`/api/sessions/${sessionId}/ledger/${encodeURIComponent(callId)}`),
+
   listSessions: (workspaceId?: string) =>
     request<{ items: Session[] }>(`/api/sessions${workspaceId ? `?workspace_id=${workspaceId}` : ''}`),
   createSession: (workspaceId: string, title?: string) =>

+ 5 - 1
web/src/api/types.ts

@@ -1,4 +1,4 @@
-/** 与 BFF 共享的类型定义(手写镜像,避免跨包构建依赖)。 */
+/** 与 BFF 共享的类型定义(手写镜像,避免跨包构建依赖)。 */
 
 export interface Workspace {
   id: string;
@@ -118,5 +118,9 @@ export interface HealthPayload {
 export interface PreviewPayload {
   columns: string[];
   rows: Array<Record<string, unknown>>;
+  row_indexes: number[];
+  row_hashes: string[];
+  offset: number;
+  limit: number;
   total: number;
 }

+ 29 - 10
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';
@@ -12,7 +12,7 @@ const TOOL_LABELS: Record<string, string> = {
 };
 
 /** 一条对话消息:用户气泡 / 助手回答 + 工具卡片 + 核验溯源。 */
-export function ChatMessageView({ message }: { message: ChatMessage }) {
+export function ChatMessageView({ message, onChipClick }: { message: ChatMessage; onChipClick?: (chip: ClaimChip) => void }) {
   if (message.role === 'user') {
     return (
       <div className="message message-user">
@@ -34,8 +34,8 @@ 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} />}
+        {message.verification && message.verification.chips.length > 0 && <TraceChips chips={message.verification.chips} onSelect={onChipClick} />}
+        {message.verification && <VerificationPanel verification={message.verification} onChipClick={onChipClick} />}
       </div>
     </div>
   );
@@ -89,7 +89,7 @@ function ToolCard({ call, result }: { call: { id: string; name: string; argument
 }
 
 /** 核验结论面板:通过/估算/拒绝,附带每个数字的来源。 */
-export function VerificationPanel({ verification }: { verification: Verification }) {
+export function VerificationPanel({ verification, onChipClick }: { verification: Verification; onChipClick?: (chip: ClaimChip) => void }) {
   const [open, setOpen] = useState(false);
   const tone = verification.verdict === 'accept' ? 'success' : verification.verdict === 'flag' ? 'warn' : 'danger';
   const title =
@@ -114,7 +114,24 @@ export function VerificationPanel({ verification }: { verification: Verification
             <tbody>
               {verification.claims.map((claim, index) => (
                 <tr key={index}>
-                  <td>{claim.raw}</td>
+                  <td>
+                    <button
+                      type="button"
+                      className="link-button mono"
+                      onClick={() =>
+                        onChipClick?.(
+                          verification.chips.find((chip) => chip.display === claim.display || chip.value === String(claim.value)) ?? {
+                            value: String(claim.value),
+                            display: claim.display,
+                            status: claim.status as any,
+                          },
+                        )
+                      }
+                      disabled={!onChipClick}
+                    >
+                      {claim.raw}
+                    </button>
+                  </td>
                   <td>
                     <Badge tone={claim.status === 'verified' ? 'success' : claim.status === 'flagged' ? 'warn' : claim.status === 'exempt' ? 'neutral' : 'danger'}>
                       {claim.status === 'verified' ? '已溯源' : claim.status === 'flagged' ? '估算' : claim.status === 'exempt' ? '豁免' : '无来源'}
@@ -132,18 +149,20 @@ export function VerificationPanel({ verification }: { verification: Verification
 }
 
 /** 数字溯源 chip 行(回答下方常显)。 */
-export function TraceChips({ chips }: { chips: ClaimChip[] }) {
+export function TraceChips({ chips, onSelect }: { chips: ClaimChip[]; onSelect?: (chip: ClaimChip) => void }) {
   if (chips.length === 0) return null;
   return (
     <div className="chips">
       {chips.map((chip, index) => (
-        <span
+        <button
           key={index}
+          type="button"
           className={`chip chip-${chip.status}`}
-          title={`call_id=${chip.call_id ?? '-'} · ${chip.object_id ?? ''} ${chip.table ?? ''} 第 ${(chip.row_index ?? 0) + 1} 行 · ${chip.field ?? ''}`}
+          onClick={() => onSelect?.(chip)}
+          title={`点开查看来源:${chip.object_id || '计算'} ${chip.table ?? ''} · ${chip.field ?? ''}(call_id=${chip.call_id ?? '-'})`}
         >
           {chip.display}
-        </span>
+        </button>
       ))}
     </div>
   );

+ 14 - 3
web/src/components/Common.tsx

@@ -1,4 +1,4 @@
-import type { CSSProperties, ReactNode } from 'react';
+import { useEffect, useRef, type CSSProperties, type ReactNode } from 'react';
 import { formatNumber, isNumericColumn, isPlainIntegerColumn } from '../lib/format';
 
 export interface DataTableProps {
@@ -9,9 +9,16 @@ export interface DataTableProps {
   highlight?: string[];
 }
 
-/** 通用结果表格:数值列右对齐 + 千分位,超长自动截断。 */
+/**
+ * 通用结果表格:数值列右对齐 + 千分位,超长自动截断。
+ * `highlight` 是**行位置**(0 基),有值时把该行滚动到可见区域并高亮。
+ */
 export function DataTable({ columns, rows, maxRows = 30, compact = false, highlight = [] }: DataTableProps) {
   const visible = rows.slice(0, maxRows);
+  const highlightRef = useRef<HTMLTableRowElement | null>(null);
+  useEffect(() => {
+    highlightRef.current?.scrollIntoView({ block: 'center' });
+  }, [highlight.join(',')]);
   if (columns.length === 0) return <div className="empty-hint">没有可显示的列</div>;
   return (
     <div className={`data-table ${compact ? 'compact' : ''}`}>
@@ -27,7 +34,11 @@ export function DataTable({ columns, rows, maxRows = 30, compact = false, highli
         </thead>
         <tbody>
           {visible.map((row, index) => (
-            <tr key={index} className={highlight.includes(String(index)) ? 'highlight' : ''}>
+            <tr
+              key={index}
+              ref={highlight.includes(String(index)) ? highlightRef : undefined}
+              className={highlight.includes(String(index)) ? 'highlight' : ''}
+            >
               {columns.map((column) => {
                 const value = row[column];
                 const numeric = isNumericColumn(column);

+ 174 - 0
web/src/components/TraceDrawer.tsx

@@ -0,0 +1,174 @@
+import { useEffect, useState } from 'react';
+import type { ClaimChip } from '../api/types';
+import { api } from '../api/client';
+import { Badge, Spinner } from './Common';
+import { formatNumber, isPlainIntegerColumn } from '../lib/format';
+
+export interface TraceDrawerProps {
+  sessionId: string;
+  chip: ClaimChip | null;
+  onClose(): void;
+  /** 跳到"文件"页的结果表并高亮该行 */
+  onOpenRow(objectId: string, table: string, rowIndex: number): void;
+}
+
+interface RowDetail {
+  object_id: string;
+  table: string;
+  row_index: number;
+  row_hash: string;
+  values: Record<string, unknown>;
+  lineage: {
+    source_object_id?: string;
+    source_rows?: Record<string, string> | null;
+  } | null;
+}
+
+interface CalcDetail {
+  call: Record<string, unknown>;
+  values: Array<Record<string, unknown>>;
+}
+
+/**
+ * 溯源抽屉:点开答案里的数字,看到它来自哪个对象、哪张表、第几行、行哈希,
+ * 以及这一行的完整原文;如果是 calculator 算出来的,则展示算式与输入。
+ *
+ * 这是架构文档里"点击 chip 打开侧边面板,可跳转到结果工作区对应行"的落地。
+ */
+export function TraceDrawer({ sessionId, chip, onClose, onOpenRow }: TraceDrawerProps) {
+  const [row, setRow] = useState<RowDetail | null>(null);
+  const [calc, setCalc] = useState<CalcDetail | null>(null);
+  const [error, setError] = useState('');
+  const [loading, setLoading] = useState(false);
+
+  const isCalculator = chip?.table === 'calculator' || (chip?.row_index ?? 0) < 0;
+
+  useEffect(() => {
+    if (!chip) return;
+    setRow(null);
+    setCalc(null);
+    setError('');
+    setLoading(true);
+    let alive = true;
+    (async () => {
+      try {
+        if (isCalculator) {
+          if (!chip.call_id) throw new Error('这个数字没有 call_id,无法追溯');
+          const data = (await api.sessionLedgerCall(sessionId, chip.call_id)) as CalcDetail;
+          if (alive) setCalc(data);
+        } else if (chip.object_id && chip.table && (chip.row_index ?? -1) >= 0) {
+          const data = (await api.objectRow(chip.object_id, chip.table, chip.row_index!)) as RowDetail;
+          if (alive) setRow(data);
+        } else {
+          throw new Error('这个数字缺少行位置信息');
+        }
+      } catch (caught) {
+        if (alive) setError((caught as Error).message);
+      } finally {
+        if (alive) setLoading(false);
+      }
+    })();
+    return () => {
+      alive = false;
+    };
+    // eslint-disable-next-line react-hooks/exhaustive-deps
+  }, [chip?.call_id, chip?.object_id, chip?.table, chip?.row_index, sessionId]);
+
+  if (!chip) return null;
+
+  const statusText = { verified: '已溯源', flagged: '估算', unverified: '无来源', exempt: '豁免' }[chip.status];
+  const statusTone = chip.status === 'verified' ? 'success' : chip.status === 'flagged' ? 'warn' : chip.status === 'unverified' ? 'danger' : 'neutral';
+
+  return (
+    <div className="drawer-backdrop" onClick={onClose} role="presentation">
+      <aside className="drawer" onClick={(event) => event.stopPropagation()} role="dialog" aria-modal="true">
+        <header className="drawer-head">
+          <div>
+            <h3>数字溯源</h3>
+            <span className="drawer-sub">{chip.field ?? '数值'}</span>
+          </div>
+          <button type="button" className="icon-button" onClick={onClose} aria-label="关闭">
+            ×
+          </button>
+        </header>
+
+        <div className="drawer-body">
+          <div className="trace-value">
+            <strong>{chip.display}</strong>
+            <Badge tone={statusTone}>{statusText}</Badge>
+          </div>
+
+          {loading && <Spinner label="读取来源" />}
+          {error && <div className="error-box">{error}</div>}
+
+          {row && (
+            <>
+              <dl className="kv">
+                <dt>对象</dt>
+                <dd className="mono">{row.object_id}</dd>
+                <dt>表</dt>
+                <dd>{row.table}</dd>
+                <dt>行号</dt>
+                <dd>第 {row.row_index + 1} 行(0 基 {row.row_index})</dd>
+                <dt>行哈希</dt>
+                <dd className="mono break">{row.row_hash}</dd>
+                <dt>字段名</dt>
+                <dd>{chip.field ?? '—'}</dd>
+              </dl>
+
+              <h4>这一行的原文</h4>
+              <div className="data-table compact">
+                <table>
+                  <tbody>
+                    {Object.entries(row.values).map(([key, value]) => (
+                      <tr key={key} className={key === chip.field ? 'highlight' : ''}>
+                        <td className="trace-key">{key}</td>
+                        <td className={/金额|数量|指数|单价|占比|环比/.test(key) ? 'num' : ''}>
+                          {value === null || value === ''
+                            ? '—'
+                            : isPlainIntegerColumn(key) || !/金额|数量|指数|单价|占比|环比/.test(key)
+                              ? String(value)
+                              : formatNumber(value)}
+                        </td>
+                      </tr>
+                    ))}
+                  </tbody>
+                </table>
+              </div>
+
+              {row.lineage?.source_rows && (
+                <>
+                  <h4>下钻条件(这批记录的过滤条件)</h4>
+                  <pre className="code-block">{JSON.stringify(row.lineage.source_rows, null, 2)}</pre>
+                  <p className="muted">原始数据对象:{row.lineage.source_object_id}</p>
+                </>
+              )}
+
+              <button type="button" className="primary block" onClick={() => onOpenRow(row.object_id, row.table, row.row_index)}>
+                在结果表中查看这一行
+              </button>
+            </>
+          )}
+
+          {calc && (
+            <>
+              <dl className="kv">
+                <dt>计算 ID</dt>
+                <dd className="mono">{String(calc.call.call_id ?? '—')}</dd>
+                <dt>工具</dt>
+                <dd>calculator</dd>
+                <dt>参数</dt>
+                <dd className="mono break">{JSON.stringify(calc.call.args ?? {}, null, 2)}</dd>
+                <dt>结果哈希</dt>
+                <dd className="mono break">{String(calc.call.result_hash ?? '—')}</dd>
+              </dl>
+              <h4>这次计算产出的值</h4>
+              <pre className="code-block">{JSON.stringify(calc.values, null, 2)}</pre>
+              <p className="muted">换算与合计类数字必须由 calculator 产生才能被核验,这条记录就是它的账。</p>
+            </>
+          )}
+        </div>
+      </aside>
+    </div>
+  );
+}

+ 15 - 3
web/src/pages/ChatPage.tsx

@@ -1,7 +1,8 @@
 import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
 import { api, streamChat } from '../api/client';
-import type { ChatMessage, Session, ToolResultRecord, Verification, Workspace } from '../api/types';
+import type { ChatMessage, ClaimChip, Session, ToolResultRecord, Verification, Workspace } from '../api/types';
 import { ChatMessageView, TraceChips } from '../components/ChatMessageView';
+import { TraceDrawer } from '../components/TraceDrawer';
 import { Spinner } from '../components/Common';
 import { relativeTime } from '../lib/format';
 
@@ -36,6 +37,7 @@ export function ChatPage({ workspace, onToast }: ChatPageProps) {
   const [busy, setBusy] = useState(false);
   const [live, setLive] = useState<LiveState>(EMPTY_LIVE);
   const [showReasoning, setShowReasoning] = useState(false);
+  const [activeChip, setActiveChip] = useState<ClaimChip | null>(null);
   const abortRef = useRef<null | (() => void)>(null);
   const scrollRef = useRef<HTMLDivElement | null>(null);
 
@@ -272,7 +274,7 @@ export function ChatPage({ workspace, onToast }: ChatPageProps) {
           )}
 
           {messages.map((message) => (
-            <ChatMessageView key={message.id} message={message} />
+            <ChatMessageView key={message.id} message={message} onChipClick={setActiveChip} />
           ))}
 
           {busy && (
@@ -314,7 +316,7 @@ export function ChatPage({ workspace, onToast }: ChatPageProps) {
                 )}
                 {live.verification && (
                   <div className="live-verification">
-                    <TraceChips chips={live.verification.chips} />
+                    <TraceChips chips={live.verification.chips} onSelect={setActiveChip} />
                   </div>
                 )}
                 {live.reasoning && (
@@ -355,6 +357,16 @@ export function ChatPage({ workspace, onToast }: ChatPageProps) {
           )}
         </footer>
       </section>
+
+      <TraceDrawer
+        sessionId={activeId ?? ''}
+        chip={activeChip}
+        onClose={() => setActiveChip(null)}
+        onOpenRow={(objectId, table, rowIndex) => {
+          setActiveChip(null);
+          window.location.hash = `#/files?object=${encodeURIComponent(objectId)}&table=${encodeURIComponent(table)}&row=${rowIndex}`;
+        }}
+      />
     </div>
   );
 }

+ 93 - 9
web/src/pages/FilesPage.tsx

@@ -10,13 +10,47 @@ export interface FilesPageProps {
   onChanged(): void;
 }
 
+interface PreviewData {
+  columns: string[];
+  rows: Array<Record<string, unknown>>;
+  row_indexes: number[];
+  offset: number;
+  total: number;
+}
+
+export interface DeepLink {
+  objectId: string;
+  table: string;
+  row: number | null;
+}
+
+/** 纯函数:解析 `#/files?object=obj_x&table=1.0-3.0_MLCC&row=3`(好写单测,不依赖 DOM)。 */
+export function parseDeepLink(hash: string): DeepLink | null {
+  const cleaned = String(hash ?? '').replace(/^#\/?/, '');
+  const queryIndex = cleaned.indexOf('?');
+  if (queryIndex < 0) return null;
+  const params = new URLSearchParams(cleaned.slice(queryIndex + 1));
+  const objectId = params.get('object');
+  if (!objectId) return null;
+  const rowParam = params.get('row');
+  const row = rowParam !== null && rowParam !== '' && Number.isFinite(Number(rowParam)) ? Number(rowParam) : null;
+  return { objectId, table: params.get('table') ?? 'raw', row };
+}
+
+/** 从当前地址栏读深链(溯源 chip 点"在结果表中查看"会跳到这里)。 */
+export function readDeepLink(): DeepLink | null {
+  if (typeof window === 'undefined') return null;
+  return parseDeepLink(window.location.hash);
+}
+
 export function FilesPage({ workspace, onToast, onChanged }: FilesPageProps) {
   const [files, setFiles] = useState<DataObject[]>([]);
   const [kind, setKind] = useState<'all' | 'raw' | 'stat'>('all');
   const [uploading, setUploading] = useState(false);
   const [progress, setProgress] = useState(0);
-  const [preview, setPreview] = useState<{ object: DataObject; table: string } | null>(null);
-  const [previewData, setPreviewData] = useState<{ columns: string[]; rows: Array<Record<string, unknown>>; total: number } | null>(null);
+  const [preview, setPreview] = useState<{ object: DataObject; table: string; row: number | null } | null>(null);
+  const [previewData, setPreviewData] = useState<PreviewData | null>(null);
+  const [deepLink, setDeepLink] = useState<DeepLink | null>(() => readDeepLink());
   const [dragOver, setDragOver] = useState(false);
   const inputRef = useRef<HTMLInputElement | null>(null);
 
@@ -34,6 +68,14 @@ export function FilesPage({ workspace, onToast, onChanged }: FilesPageProps) {
     void load();
   }, [load]);
 
+  // hash 变化时(含从对话页跳转过来)重新解析深链
+  useEffect(() => {
+    const onHashChange = () => setDeepLink(readDeepLink());
+    window.addEventListener('hashchange', onHashChange);
+    onHashChange();
+    return () => window.removeEventListener('hashchange', onHashChange);
+  }, []);
+
   const upload = async (fileList: FileList | File[]) => {
     if (!workspace) return;
     const candidates = Array.from(fileList).filter((file) => /\.(csv|xlsx|xlsm|json|txt)$/i.test(file.name));
@@ -58,17 +100,44 @@ export function FilesPage({ workspace, onToast, onChanged }: FilesPageProps) {
     }
   };
 
-  const openPreview = async (object: DataObject, table: string) => {
-    setPreview({ object, table });
+  /** 打开预览;给了 row 就把窗口滑到那一行附近,并在表格里高亮。 */
+  const openPreview = async (object: DataObject, table: string, row: number | null = null) => {
+    setPreview({ object, table, row });
     setPreviewData(null);
     try {
-      const data = await api.preview(object.id, table, 30);
+      const offset = row === null ? 0 : Math.max(0, row - 3);
+      const data = await api.preview(object.id, table, 30, offset);
       setPreviewData(data);
     } catch (error) {
       onToast('error', (error as Error).message);
     }
   };
 
+  // 深链:从对话里的溯源 chip 跳过来时,自动打开对应表并定位到那一行
+  useEffect(() => {
+    if (!deepLink) return;
+    let alive = true;
+    (async () => {
+      try {
+        const object = files.find((item) => item.id === deepLink.objectId) ?? (await api.getObject(deepLink.objectId));
+        if (!alive) return;
+        await openPreview(object, deepLink.table, deepLink.row);
+      } catch (error) {
+        if (alive) onToast('error', `无法定位到这行数据:${(error as Error).message}`);
+      }
+    })();
+    return () => {
+      alive = false;
+    };
+    // eslint-disable-next-line react-hooks/exhaustive-deps
+  }, [deepLink, files]);
+
+  const highlightPositions = (() => {
+    if (!preview?.row || !previewData) return [];
+    const position = previewData.row_indexes.indexOf(preview.row);
+    return position >= 0 ? [String(position)] : [];
+  })();
+
   const remove = async (object: DataObject) => {
     if (!window.confirm(`确定删除 ${object.name} 吗?(不可恢复)`)) return;
     try {
@@ -145,6 +214,7 @@ export function FilesPage({ workspace, onToast, onChanged }: FilesPageProps) {
               <th>规模</th>
               <th>大小</th>
               <th>表</th>
+              <th>指纹</th>
               <th>上传时间</th>
               <th />
             </tr>
@@ -152,7 +222,7 @@ export function FilesPage({ workspace, onToast, onChanged }: FilesPageProps) {
           <tbody>
             {files.length === 0 && (
               <tr>
-                <td colSpan={7} className="empty-hint">
+                <td colSpan={8} className="empty-hint">
                   还没有文件,先上传一份海关原始 CSV
                 </td>
               </tr>
@@ -180,6 +250,9 @@ export function FilesPage({ workspace, onToast, onChanged }: FilesPageProps) {
                     {file.tables.length > 3 && <span className="muted">+{file.tables.length - 3}</span>}
                   </div>
                 </td>
+                <td className="mono muted" title={file.sha256}>
+                  {file.sha256 ? <span className="hash-chip">{file.sha256.replace('sha256:', '').slice(0, 12)}</span> : '—'}
+                </td>
                 <td className="muted">{relativeTime(file.created_at)}</td>
                 <td className="actions">
                   {file.kind === 'stat' && (
@@ -197,11 +270,22 @@ export function FilesPage({ workspace, onToast, onChanged }: FilesPageProps) {
         </table>
       </div>
 
-      <Modal open={Boolean(preview)} title={`预览 · ${preview?.object.name ?? ''} · ${preview?.table ?? ''}`} onClose={() => setPreview(null)} width={980}>
+      <Modal
+        open={Boolean(preview)}
+        title={`预览 · ${preview?.object.name ?? ''} · ${preview?.table ?? ''}${preview?.row != null ? ` · 第 ${preview.row + 1} 行` : ''}`}
+        onClose={() => setPreview(null)}
+        width={1100}
+      >
         {previewData ? (
           <>
-            <p className="muted">共 {previewData.total.toLocaleString('en-US')} 行,显示前 30 行</p>
-            <DataTable columns={previewData.columns} rows={previewData.rows} maxRows={30} />
+            <p className="muted">
+              共 {previewData.total.toLocaleString('en-US')} 行
+              {previewData.offset > 0
+                ? `,当前显示第 ${previewData.offset + 1}–${previewData.offset + previewData.rows.length} 行`
+                : ',显示前 30 行'}
+              {preview?.row != null && highlightPositions.length > 0 ? '(高亮的那一行就是数字的来源)' : ''}
+            </p>
+            <DataTable columns={previewData.columns} rows={previewData.rows} maxRows={30} highlight={highlightPositions} />
           </>
         ) : (
           <Spinner label="加载中" />

+ 151 - 19
web/src/pages/ProcessPage.tsx

@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
 import { api } from '../api/client';
 import type { DataObject, RunInfo, Workspace } from '../api/types';
 import { Badge, DataTable, ProgressBar, Spinner } from '../components/Common';
@@ -39,12 +39,16 @@ export function ProcessPage({ workspace, onToast, onChanged }: ProcessPageProps)
   const [cutoff, setCutoff] = useState('');
   const [countrySystem, setCountrySystem] = useState('ISO');
   const [groupBy, setGroupBy] = useState<string[]>(['c1', 'c2']);
+  const [filters, setFilters] = useState<Array<{ column: string; value: string }>>([]);
+  const [filterColumn, setFilterColumn] = useState('c1');
+  const [filterValue, setFilterValue] = useState('');
   const [run, setRun] = useState<RunInfo | null>(null);
   const [result, setResult] = useState<DataObject | null>(null);
   const [previewTable, setPreviewTable] = useState<string>('');
   const [previewData, setPreviewData] = useState<{ columns: string[]; rows: Array<Record<string, unknown>> } | null>(null);
   const [history, setHistory] = useState<RunInfo[]>([]);
   const timer = useRef<number | null>(null);
+  const runCancels = useRef<Array<() => void>>([]);
 
   const loadFiles = useCallback(async () => {
     if (!workspace) return;
@@ -96,8 +100,15 @@ export function ProcessPage({ workspace, onToast, onChanged }: ProcessPageProps)
     }
   };
 
-  useEffect(() => stopPolling, []);
+  useEffect(() => {
+    return () => {
+      stopPolling();
+      for (const cancel of runCancels.current) cancel();
+      runCancels.current = [];
+    };
+  }, []);
 
+  /** 轮询兜底:SSE 不可用(代理/浏览器限制)时使用。 */
   const pollRun = (runId: string) => {
     stopPolling();
     timer.current = window.setInterval(async () => {
@@ -106,17 +117,7 @@ export function ProcessPage({ workspace, onToast, onChanged }: ProcessPageProps)
         setRun(current);
         if (current.status === 'succeeded' || current.status === 'failed') {
           stopPolling();
-          if (current.status === 'succeeded' && current.object_id) {
-            const object = await api.getObject(current.object_id);
-            setResult(object);
-            const first = object.tables[0]?.name ?? '';
-            setPreviewTable(first);
-            onToast('success', '处理完成,已生成统计结果');
-            onChanged();
-            void loadFiles();
-          } else {
-            onToast('error', current.error || '处理失败');
-          }
+          await finishRun(current);
         }
       } catch (error) {
         stopPolling();
@@ -125,6 +126,59 @@ export function ProcessPage({ workspace, onToast, onChanged }: ProcessPageProps)
     }, 700);
   };
 
+  const finishRun = async (current: RunInfo) => {
+    if (current.status === 'succeeded' && current.object_id) {
+      const object = await api.getObject(current.object_id);
+      setResult(object);
+      setPreviewTable(object.tables[0]?.name ?? '');
+      onToast('success', '处理完成,已生成统计结果');
+      onChanged();
+      void loadFiles();
+    } else if (current.status === 'failed') {
+      onToast('error', current.error || '处理失败');
+    }
+  };
+
+  /** 进度优先用 SSE(架构文档要求的形态),断了自动退回轮询。 */
+  const watchRun = (runId: string) => {
+    stopPolling();
+    let settled = false;
+    const cancel = api.streamRun(runId, {
+      onProgress(data) {
+        setRun((current) => ({
+          ...(current ?? ({ id: runId } as RunInfo)),
+          id: runId,
+          status: data.status,
+          progress: data.progress,
+          message: data.message,
+          object_id: data.object_id,
+          error: data.error,
+          input_object: current?.input_object ?? '',
+          operation: current?.operation ?? '',
+          started_at: current?.started_at ?? new Date().toISOString(),
+          finished_at: null,
+          params: current?.params ?? {},
+        }));
+      },
+      onDone(data) {
+        if (settled) return;
+        settled = true;
+        void (async () => {
+          const final = await api.getRun(runId);
+          setRun(final);
+          await finishRun(final);
+        })();
+      },
+      onError(error) {
+        if (settled) return;
+        settled = true;
+        onToast('error', `进度流中断,改用轮询:${error.message}`);
+        pollRun(runId);
+      },
+    });
+    runCancels.current.push(cancel);
+  };
+
   const start = async () => {
     if (!workspace || !selected) {
       onToast('error', '请选择一份原始数据');
@@ -144,7 +198,10 @@ export function ProcessPage({ workspace, onToast, onChanged }: ProcessPageProps)
         country_code_system: countrySystem,
       };
       if (cutoff) options.cutoff_date = cutoff;
-      if (operation === 'custom_aggregate') options.group_by = groupBy;
+      if (operation === 'custom_aggregate') {
+        options.group_by = groupBy;
+        options.filters = Object.fromEntries(filters.filter((item) => item.column && item.value).map((item) => [item.column, item.value]));
+      }
       const created = await api.startProcess({
         workspace_id: workspace.id,
         input_object_id: selected,
@@ -175,6 +232,11 @@ export function ProcessPage({ workspace, onToast, onChanged }: ProcessPageProps)
     // eslint-disable-next-line react-hooks/exhaustive-deps
   }, [result?.id]);
 
+  const sourceName = useMemo(
+    () => rawFiles.find((item) => item.id === (run?.input_object ?? selected))?.name ?? '',
+    [rawFiles, run?.input_object, selected],
+  );
+
   const groupedTables = useMemo(() => {
     if (!result) return [];
     return result.tables.map((table) => ({ ...table, meta: classifySheet(table.name) }));
@@ -295,6 +357,58 @@ export function ProcessPage({ workspace, onToast, onChanged }: ProcessPageProps)
                   </button>
                 ))}
               </div>
+
+              <h3>5. 过滤条件(可选)</h3>
+              <div className="filter-row">
+                <select value={filterColumn} onChange={(event) => setFilterColumn(event.target.value)} disabled={running}>
+                  {GROUP_BY_OPTIONS.map(([value, label]) => (
+                    <option key={value} value={value}>
+                      {label}
+                    </option>
+                  ))}
+                </select>
+                <input
+                  type="text"
+                  placeholder="等于某个值,例如 电容器 / 2025 / DDR5"
+                  value={filterValue}
+                  disabled={running}
+                  onChange={(event) => setFilterValue(event.target.value)}
+                  onKeyDown={(event) => {
+                    if (event.key === 'Enter' && filterValue.trim()) {
+                      event.preventDefault();
+                      setFilters((current) => [...current.filter((item) => item.column !== filterColumn), { column: filterColumn, value: filterValue.trim() }]);
+                      setFilterValue('');
+                    }
+                  }}
+                />
+                <button
+                  type="button"
+                  className="ghost"
+                  disabled={running || !filterValue.trim()}
+                  onClick={() => {
+                    setFilters((current) => [...current.filter((item) => item.column !== filterColumn), { column: filterColumn, value: filterValue.trim() }]);
+                    setFilterValue('');
+                  }}
+                >
+                  添加
+                </button>
+              </div>
+              {filters.length > 0 && (
+                <div className="chips">
+                  {filters.map((item) => (
+                    <button
+                      key={item.column}
+                      type="button"
+                      className="chip chip-verified"
+                      title="点击移除"
+                      onClick={() => setFilters((current) => current.filter((entry) => entry.column !== item.column))}
+                    >
+                      {GROUP_BY_OPTIONS.find(([value]) => value === item.column)?.[1] ?? item.column} = {item.value} ×
+                    </button>
+                  ))}
+                </div>
+              )}
+              <p className="muted">过滤条件只对"自定义聚合"生效;全套统计报表按固定口径出全量数据。</p>
             </>
           )}
 
@@ -349,12 +463,30 @@ export function ProcessPage({ workspace, onToast, onChanged }: ProcessPageProps)
                 <a className="button-link" href={api.downloadUrl(result.id, '统计结果.xlsx')} target="_blank" rel="noreferrer">
                   下载 统计结果.xlsx
                 </a>
-                {result.meta.lineage && (
-                  <span className="muted mono" title={JSON.stringify(result.meta.lineage, null, 2)}>
-                    血缘 {String((result.meta.lineage as any).output_hash ?? '').slice(0, 18)}…
-                  </span>
-                )}
               </div>
+
+              {result.meta.lineage && (
+                <div className="lineage-box">
+                  <h4>血缘(这批结果怎么来的,可复核)</h4>
+                  <dl className="lineage-grid">
+                    <dt>输入文件</dt>
+                    <dd>{sourceName || result.parents?.[0] || '—'}</dd>
+                    <dt>输入指纹</dt>
+                    <dd>{String((result.meta.lineage as any).input_sha256 ?? '—')}</dd>
+                    <dt>参数哈希</dt>
+                    <dd>{String((result.meta.lineage as any).params_hash ?? '—')}</dd>
+                    <dt>输出哈希</dt>
+                    <dd>{String((result.meta.lineage as any).output_hash ?? '—')}</dd>
+                    <dt>引擎</dt>
+                    <dd>
+                      {String((result.meta.lineage as any).engine?.name ?? '—')} v
+                      {String((result.meta.lineage as any).engine?.version ?? '—')}
+                    </dd>
+                    <dt>产出时间</dt>
+                    <dd>{String((result.meta.lineage as any).started_at ?? relativeTime(result.created_at))}</dd>
+                  </dl>
+                </div>
+              )}
               {result.meta.warnings && result.meta.warnings.length > 0 && (
                 <ul className="warn-list">
                   {result.meta.warnings.map((text, index) => (

+ 168 - 0
web/src/styles/app.css

@@ -1530,3 +1530,171 @@ textarea:focus {
     grid-template-columns: 180px 1fr;
   }
 }
+
+/* ------------------------------------------------------------------ 溯源抽屉 */
+.drawer-backdrop {
+  position: fixed;
+  inset: 0;
+  background: rgba(7, 10, 18, 0.6);
+  z-index: 90;
+  display: flex;
+  justify-content: flex-end;
+}
+
+.drawer {
+  width: min(560px, 92vw);
+  height: 100%;
+  background: var(--panel);
+  border-left: 1px solid var(--border);
+  display: flex;
+  flex-direction: column;
+  box-shadow: -12px 0 40px rgba(0, 0, 0, 0.45);
+  animation: drawer-in 0.18s ease-out;
+}
+
+@keyframes drawer-in {
+  from {
+    transform: translateX(24px);
+    opacity: 0.4;
+  }
+}
+
+.drawer-head {
+  display: flex;
+  justify-content: space-between;
+  align-items: flex-start;
+  padding: 14px 16px;
+  border-bottom: 1px solid var(--border-soft);
+}
+
+.drawer-head h3 {
+  margin: 0;
+  font-size: 15px;
+}
+
+.drawer-sub {
+  font-size: 12px;
+  color: var(--text-faint);
+}
+
+.drawer-body {
+  flex: 1;
+  overflow: auto;
+  padding: 16px;
+  display: flex;
+  flex-direction: column;
+  gap: 12px;
+}
+
+.drawer-body h4 {
+  margin: 6px 0 0;
+  font-size: 12.5px;
+  color: var(--text-dim);
+  font-weight: 600;
+}
+
+.trace-value {
+  display: flex;
+  align-items: center;
+  gap: 10px;
+  padding: 10px 12px;
+  background: var(--bg-soft);
+  border: 1px solid var(--border-soft);
+  border-radius: 8px;
+}
+
+.trace-value strong {
+  font-size: 18px;
+  font-family: var(--mono);
+}
+
+.trace-key {
+  color: var(--text-faint);
+  white-space: nowrap;
+}
+
+.code-block {
+  margin: 0;
+  padding: 10px;
+  background: var(--bg-soft);
+  border: 1px solid var(--border-soft);
+  border-radius: 8px;
+  font-size: 11.5px;
+  color: var(--text-dim);
+  white-space: pre-wrap;
+  word-break: break-all;
+  max-height: 240px;
+  overflow: auto;
+}
+
+.mono.break {
+  word-break: break-all;
+}
+
+/* chip 现在是按钮:去掉默认按钮样式 */
+.chip {
+  border: 1px solid transparent;
+  font-family: var(--mono);
+}
+
+.chip:hover {
+  filter: brightness(1.25);
+}
+
+.chip:focus-visible {
+  outline: 1px solid var(--primary);
+}
+
+/* 高亮行(从 chip 跳转过来时) */
+.data-table tr.highlight td {
+  background: rgba(59, 124, 246, 0.22) !important;
+  box-shadow: inset 0 0 0 1px rgba(59, 124, 246, 0.5);
+}
+
+/* 血缘三哈希 */
+.lineage-grid {
+  display: grid;
+  grid-template-columns: 92px 1fr;
+  gap: 4px 10px;
+  font-size: 11.5px;
+}
+
+.lineage-grid dt {
+  color: var(--text-faint);
+}
+
+.lineage-grid dd {
+  margin: 0;
+  font-family: var(--mono);
+  word-break: break-all;
+  color: var(--text-dim);
+}
+
+.hash-chip {
+  padding: 1px 6px;
+  border-radius: 5px;
+  background: var(--panel-2);
+  color: var(--text-faint);
+  font-size: 10.5px;
+}
+
+.lineage-box {
+  border: 1px solid var(--border-soft);
+  border-radius: 8px;
+  padding: 10px 12px;
+  background: var(--bg-soft);
+}
+
+.lineage-box h4 {
+  margin: 0 0 6px;
+  font-size: 12px;
+  color: var(--text-dim);
+  font-weight: 600;
+}
+
+.filter-row {
+  display: grid;
+  grid-template-columns: 160px 1fr auto;
+  gap: 8px;
+  align-items: center;
+}

+ 43 - 1
web/test/render.test.tsx

@@ -1,7 +1,9 @@
-import { describe, expect, it } from 'vitest';
+import { describe, expect, it } from 'vitest';
 import { renderToStaticMarkup } from 'react-dom/server';
 import { ChatMessageView, Markdownish, TraceChips, VerificationPanel } from '../src/components/ChatMessageView';
 import App from '../src/App';
+import { TraceDrawer } from '../src/components/TraceDrawer';
+import { FilesPage, parseDeepLink } from '../src/pages/FilesPage';
 import type { ChatMessage } from '../src/api/types';
 
 function message(overrides: Partial<ChatMessage> = {}): ChatMessage {
@@ -94,3 +96,43 @@ describe('组件渲染(服务端渲染,不需要浏览器)', () => {
     expect(html).toContain('MLCC');
   });
 });
+
+describe('溯源抽屉与深链', () => {
+  it('收起状态(chip 为 null)不渲染任何东西', () => {
+    const html = renderToStaticMarkup(<TraceDrawer sessionId="s1" chip={null} onClose={() => {}} onOpenRow={() => {}} />);
+    expect(html).toBe('');
+  });
+
+  it('打开时展示数字、状态与加载态', () => {
+    const html = renderToStaticMarkup(
+      <TraceDrawer
+        sessionId="s1"
+        chip={{ value: '400316.13', display: '400316.13', status: 'verified', call_id: 'call_1', object_id: 'obj_1', table: '1.0-3.0_MLCC', row_index: 0, field: '实际金额(美元)' }}
+        onClose={() => {}}
+        onOpenRow={() => {}}
+      />,
+    );
+    expect(html).toContain('数字溯源');
+    expect(html).toContain('400316.13');
+    expect(html).toContain('已溯源');
+    expect(html).toContain('实际金额(美元)');
+    expect(html).toContain('drawer');
+  });
+
+  it('parseDeepLink 解析从 chip 跳过来的地址', () => {
+    expect(parseDeepLink('#/files?object=obj_ab12&table=1.0-3.0_MLCC&row=7')).toEqual({
+      objectId: 'obj_ab12',
+      table: '1.0-3.0_MLCC',
+      row: 7,
+    });
+    expect(parseDeepLink('#/files')).toBeNull();
+    expect(parseDeepLink('#/files?object=obj_x&table=raw')).toEqual({ objectId: 'obj_x', table: 'raw', row: null });
+    expect(parseDeepLink('#/files?table=raw')).toBeNull();
+    expect(parseDeepLink('#/files?object=obj_x&row=abc')).toEqual({ objectId: 'obj_x', table: 'raw', row: null });
+  });
+
+  it('文件页在没有工作区时给出提示(不崩)', () => {
+    const html = renderToStaticMarkup(<FilesPage workspace={null} onToast={() => {}} onChanged={() => {}} />);
+    expect(html).toContain('请先在左侧选择一个工作区');
+  });
+});

Einige Dateien werden nicht angezeigt, da zu viele Dateien in diesem Diff geändert wurden.