Author SHA1 Message Date
jiang 5f7041ffae fix: recognize class-attached investigation diagram nodes
Generic Container CI/CD / test-build-publish (push) Successful in 1m11s
Frontend CI/CD / build-test-publish-and-deploy (push) Successful in 1m11s
2026-11-02 15:23:34 +08:00
jiang c0e4231b83 feat: expand intelligent investigation workspace
Generic Container CI/CD / test-build-publish (push) Successful in 1m52s
Frontend CI/CD / build-test-publish-and-deploy (push) Successful in 1m52s
2026-10-30 17:30:19 +08:00
jiang ddd03dbff6 style: refine agent composer focus feedback 2026-10-30 17:09:13 +08:00
jiang 185bf31446 fix: preserve investigation execution history by round 2026-10-30 17:07:53 +08:00
jiang 1ee21d1c7f feat: polish intelligent answer interactions 2026-10-29 18:39:50 +08:00
jiang 9474788db6 fix: unify chat process and reply presentation 2026-10-29 17:54:34 +08:00
jiang 7621bf0f86 fix: synchronize task collaboration session titles
Apply creation titles and repaired history names to cached sessions.
Keep messages and reading state intact and preserve title edits received
while a collaboration request is in flight.

Validation: pnpm lint; pnpm typecheck; 604 unit tests; two browser regressions.
2026-10-29 16:55:31 +08:00
jiang 5b710d1247 feat: extend map targeting and overlay controls
Support batch feature targeting and clear map highlights and overlays from the More panel. Remove misleading action chevrons and unused configuration export entries.

Validated the isolated patch with lint, typecheck, 36 focused tests and 5 browser cases using mocked data.
2026-10-28 14:47:33 +08:00
jiang e57e0f099f fix: smooth persona hover transitions
Preserve the original reflection material while adding pointer inertia and a short exit hold. Retain the Rive pointer constraint through the fade and blend rapid re-entry to avoid abrupt changes.

Cover timing, re-entry, cancellation, renderer disposal and native Rive frames. The fade regression fails with the previous resource and passes with the updated resource.
2026-10-28 11:46:14 +08:00
jiang 4f0f34f460 feat: refine supply map layers and workbench branding 2026-10-27 17:56:38 +08:00
jiang 6983ba03f1 docs: record deployed API port 2026-10-23 16:12:26 +08:00
jiang 4010acd414 docs: clarify peripheral proxy upstream 2026-10-23 16:11:34 +08:00
jiang 535b800401 fix: proxy peripheral API through main server 2026-10-23 16:06:01 +08:00
jiang 2d8506fea0 feat: add project-aware agent workspace
Generic Container CI/CD / test-build-publish (push) Successful in 2m9s
Frontend CI/CD / build-test-publish-and-deploy (push) Successful in 2m39s
2026-10-22 18:52:18 +08:00
jiang c6a0e74e72 feat(map): persist city building tiles 2026-10-22 18:24:25 +08:00
jiang 2100353ef5 fix(security): upgrade MapLibre runtime 2026-10-22 14:47:57 +08:00
jiang edeeec3c41 chore(docker): pin patched Node runtime 2026-10-22 13:05:04 +08:00
jiang ec23d44b02 feat(agent): support Responses steering and project-aware tools
Use the dedicated TJWATER_AGENT_URL and Responses stream protocol. Keep running
turns active while users steer or queue follow-ups and edit pending delivery.
Refresh the model catalog before generation and preserve approval mode selection.

Integrate scoped investigation messaging/presentation, geographic place selection,
current Agent composer styles and supporting workbench contracts.

Validation: 77 focused Vitest checks, 21 browser cases, lint, typecheck and
production build. Preserve direct Server/Agent routing and project authentication.
2026-10-19 18:46:58 +08:00
jiang 2c5bf15cce feat(agent): render local interactive answers and fold completed process 2026-10-12 18:54:18 +08:00
jiang e0eb6a721e fix(workbench): align investigation diagram controls 2026-10-10 16:30:20 +08:00
jiang ba78a24384 feat(workbench): redesign investigation reports and diagrams 2026-10-10 16:02:47 +08:00
jiang 85a9a3ab45 fix(ui): refine acrylic controls and timeline interactions
Restore full acrylic materials to stacked task cards and floating controls.
Extend the map behind the navigation header while preserving document and
control insets. Align timeline and scale readouts, refresh dense-marker
hover content, and highlight model and approval menu options.

Keep narrow timeline headers clear of their legend and actions. Update
coupled geometry checks and retain city zoom-12 and menu regression coverage.

Validation: scoped git diff --check and read-only UI geometry inspection.
Test suites were not rerun at the user's request.
2026-10-09 18:11:33 +08:00
jiang 617ba4d87c feat(ui): refine gem-blue acrylic palette and focus borders
Derive the gem-blue palette with OKLCH tonal and complementary-color
rules while preserving acrylic opacity, blur and surface hierarchy.

Darker focus tokens exposed stacked field rings, fallback outlines and
persistent basemap selection rings. Keep fallback focus styles in the
base layer and use one themed field boundary or inset card stroke.
Preserve keyboard focus, invalid states and native input semantics.

Add browser regression coverage for pointer and keyboard focus, all
basemap presentations, narrow layouts and rendered contrast.

Validation in an isolated checkout: pnpm lint, pnpm typecheck,
pnpm test (393 tests), focused browser suites and pnpm build.
2026-10-09 10:57:06 +08:00
jiang d2d705ed4c fix(workbench): refine agent dock and smooth map resizing
Unify dock surfaces, headers and dividers, and remove the visible context strip.
Limit pointer resizing to 400-640px and reveal the edge grip on hover.
Resize and redraw the map in the same layout cycle to prevent blanking and lag.
Preserve horizontal centering during conversation control press feedback.

Validation: isolated lint, typecheck, 21 focused unit tests, and 10 relevant
browser checks passed. Snapshot baselines regenerated from the isolated change.
The existing mobile alert summary test also fails on unchanged HEAD because
the expected demo alert source is unavailable in this environment.
2026-10-08 17:34:42 +08:00
jiang 7c6d06cb43 fix(workbench): share sync reads and retry failed invalidations 2026-10-08 15:41:50 +08:00
jiang 64ef058e0d fix(workbench): refresh work orders after projection events 2026-10-08 11:50:16 +08:00
jiang f2438e4660 refactor(workbench): remove redundant notification state 2026-09-24 17:11:15 +08:00
jiang 66dcb97e1c fix(workbench): keep active notices after reading 2026-09-24 17:00:35 +08:00
jiang 87cc7785da feat(workbench): refine dynamic task collaboration 2026-09-24 16:36:12 +08:00
jiang b64d2b78bb refactor(workbench): remove mock alert generator 2026-09-24 15:20:42 +08:00
jiang a5e5acb03b fix(workbench): suppress unconfigured demo alerts
The not_configured branch previously promoted mock task failures into critical alerts. Return an explicit empty alert source so the exception badge reflects only actionable backend state.
2026-09-24 15:13:14 +08:00
jiang 7e969e7e8c feat(workbench): route actionable notifications 2026-09-24 14:57:47 +08:00
jiang db778e0bac fix(workbench): reuse system reconnect notice 2026-09-24 14:52:56 +08:00
jiang 2191efab2f fix(workbench): hold refresh feedback 2026-09-24 12:57:16 +08:00
jiang 0a53e665eb feat(workbench): add manual task refresh 2026-09-24 12:45:43 +08:00
jiang ddf953b641 refactor(workbench): simplify appointment tasks 2026-09-24 12:01:11 +08:00
jiang 436d5500f1 feat(workbench): integrate operational workflows and map state 2026-09-24 04:34:46 +08:00
jiang 1752b9ef84 feat: extend supply workbench demo and map navigation 2026-09-23 13:19:30 +08:00
jiang bebcf2a06c feat(workbench): integrate runtime data and map tooling 2026-09-22 10:45:46 +08:00
jiang bf44cc0f25 fix: synchronize dynamic GeoServer layer lifecycle
Generic Container CI/CD / test-build-publish (push) Successful in 59s
Frontend CI/CD / build-test-publish-and-deploy (push) Successful in 59s
Optional sources became dynamic while dependent labels and controller state remained static, allowing stale requests to restore removed layers. Register dependent layers through the same lifecycle and invalidate target request generations before release.
2026-09-11 18:25:41 +08:00
jiang 31acd33a2e fix: probe all non-core GeoServer layers
Extend availability checks beyond pumps and tanks so unpublished valve and reservoir layers cannot leave stale controls.
2026-09-11 17:00:54 +08:00
jiang cf699d6207 fix: hide unavailable GeoServer layers 2026-09-11 16:40:24 +08:00
jiang f9c71cc076 feat(workbench): align v2 GIS and SCADA API
Generic Container CI/CD / test-build-publish (push) Successful in 26s
Frontend CI/CD / build-test-publish-and-deploy (push) Successful in 26s
2026-09-08 18:18:40 +08:00
jiang 28287a1447 fix: coordinate mobile workbench overlays
Generic Container CI/CD / test-build-publish (push) Successful in 1m9s
Frontend CI/CD / build-test-publish-and-deploy (push) Successful in 1m40s
Independent fixed offsets caused the timeline, map dock, tool panel, and zoom controls to overlap. Derive them from one layout function and scope collapse to the expanded timeline state.
2026-08-19 18:55:43 +08:00
564 changed files with 64696 additions and 9162 deletions
+11 -3
View File
@@ -2,11 +2,19 @@ TJWATER_AUTH_MODE=required
TJWATER_KEYCLOAK_ISSUER=https://keycloak.example.com/realms/tjwater
TJWATER_KEYCLOAK_CLIENT_ID=next-tjwater
TJWATER_MAPBOX_ACCESS_TOKEN=
TJWATER_TIANDITU_TOKEN=
TJWATER_MAP_URL=https://geoserver.waternetwork.cn/geoserver
TJWATER_GEOSERVER_WORKSPACE=tjwater
TJWATER_AGENT_API_BASE_URL=http://127.0.0.1:8787
TJWATER_GEOSERVER_WORKSPACE=tjwater_next
TJWATER_SERVER_API_BASE_URL=http://127.0.0.1:8000
TJWATER_AGENT_URL=http://127.0.0.1:8787
TJWATER_WORKBENCH_RUNTIME_MODE=auto
TJWATER_PERIPHERAL_SAMPLE_API_BASE_URL=/peripheral
TJWATER_PERIPHERAL_SAMPLE_TIME_MODE=demo
TJWATER_PERIPHERAL_SAMPLE_DEMO_START=2026-09-17T00:00:00Z
TJWATER_PERIPHERAL_SAMPLE_DEMO_END=2026-09-17T12:00:00Z
TJWATER_PERIPHERAL_SAMPLE_RECENT_HOURS=8
TJWATER_ENABLE_DEV_PANEL=false
TJWATER_ENABLE_MSW=false
# Optional server-only Edge TTS voice. Never exposed through runtime-config.js.
# Optional default Mandarin voice. Users can choose another voice in the picker.
EDGE_TTS_VOICE=zh-CN-XiaoxiaoNeural
+8 -2
View File
@@ -26,8 +26,9 @@ execution belong in `next-tjwater-agent`.
- `src/mocks/` owns MSW handlers and fixtures.
- `src/test/` owns shared Vitest setup and repository-wide invariant tests.
- `tests/browser/` owns product-level Playwright regressions.
- `public/` contains static supply-network and SCADA assets plus the
runtime-config placeholder.
- `public/` contains static supply-network, SCADA, bundled city-model release
assets, and the runtime-config placeholder. Keep the city-model manifest,
attribution, and referenced runtime archive content-hash aligned.
- `server/` contains the same-origin Edge TTS adapter used by Vite and the
production container.
@@ -67,6 +68,11 @@ or barrels for private implementation files.
## Component and Module Design
- Follow [the style design guide](docs/style-design-guide.md) for UI changes:
preserve the local shadcn/ui design for all Agent dialogs, panels and menus.
Use Tailwind CSS with shared semantic tokens; apply Acrylic styling to map
and other workbench surfaces as specified by the guide. Keep feature
documents focused on business behavior.
- Use TypeScript and React function components. Export explicit types at
feature and adapter boundaries.
- Use two-space indentation and kebab-case filenames. Use PascalCase for
+2 -1
View File
@@ -8,7 +8,8 @@
@immutableAssets path /assets/*
header @immutableAssets Cache-Control "public, max-age=31536000, immutable"
handle /api/tts/edge {
@edgeTts path /api/tts/edge /api/tts/edge/voices
handle @edgeTts {
reverse_proxy 127.0.0.1:8790
}
+14 -3
View File
@@ -1,4 +1,6 @@
FROM node:24-alpine@sha256:d32cdf619f63fe0471182d08996dd516c6275bb5fd31ae06e55a570bd9e1ad43 AS build
ARG NODE_IMAGE=node:24.22.1-alpine@sha256:06d7adf3e0ef61a13f1d28682726366f97a15aa1888c934d3ecec86c33918b53
FROM ${NODE_IMAGE} AS build
ARG NPM_REGISTRY=https://registry.npmmirror.com
ENV COREPACK_NPM_REGISTRY=${NPM_REGISTRY}
@@ -13,17 +15,26 @@ RUN pnpm install --frozen-lockfile --registry="${NPM_REGISTRY}"
COPY . .
RUN pnpm build
FROM caddy:2.10.2-alpine@sha256:4c6e91c6ed0e2fa03efd5b44747b625fec79bc9cd06ac5235a779726618e530d
FROM caddy:2.10.2-alpine@sha256:4c6e91c6ed0e2fa03efd5b44747b625fec79bc9cd06ac5235a779726618e530d AS caddy-bin
FROM ${NODE_IMAGE} AS runner
ARG ALPINE_MIRROR=mirrors.aliyun.com
RUN sed -i "s|dl-cdn.alpinelinux.org|${ALPINE_MIRROR}|g" /etc/apk/repositories && \
apk add --no-cache jq nodejs
apk add --no-cache ca-certificates jq mailcap && \
mkdir -p /config/caddy /data/caddy /etc/caddy /srv && \
chmod 1777 /config/caddy /data/caddy
ENV XDG_CONFIG_HOME=/config
ENV XDG_DATA_HOME=/data
COPY --from=caddy-bin /usr/bin/caddy /usr/bin/caddy
COPY Caddyfile /etc/caddy/Caddyfile
COPY docker-entrypoint.sh /usr/local/bin/tjwater-frontend-entrypoint
COPY --from=build /app/dist /srv
COPY --from=build /app/dist-server/edge-tts-server.cjs /usr/local/lib/tjwater-frontend/edge-tts-server.cjs
RUN chmod 755 /usr/local/bin/tjwater-frontend-entrypoint
WORKDIR /srv
EXPOSE 80
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD wget --quiet --spider http://127.0.0.1/ || exit 1
+38 -5
View File
@@ -4,6 +4,8 @@ Next TJWater 是供水管网 WebGIS Agent 工作台的前端项目。界面以
项目使用 Vite、React 19、TypeScript 和 Tailwind CSS 4。地图与流向效果基于 MapLibre GL,Agent 消息支持代码高亮、数学公式和 Mermaid 图表。
样式规范统一见 [样式设计指南](docs/style-design-guide.md),Agent 功能与报告交互见 [交互设计](docs/agent-chat-ui-design.md),形象、配色与状态动画见 [Persona 设计](docs/agent-persona-design.md)。
## 主要功能
- 供水管网地图、业务图层和设备状态展示
@@ -13,6 +15,8 @@ Next TJWater 是供水管网 WebGIS Agent 工作台的前端项目。界面以
- 经过 Schema 校验的 UI Envelope 和前端动作执行
- 运行时配置注入、MSW 本地模拟和开发面板
Dev 的“调查测试”提供统一 command 格式的案例、JSONL 校验与本地预览,无需先选择调查;选中调查后还可检查实时地图、图表和报告界面块。操作说明与验证边界见 [调查展示 Dev 测试](docs/investigation-dev-tools.md)。
## 开发环境
需要安装 Node.js、Corepack 和 pnpm。项目声明的包管理器版本为 pnpm 11.8.0。
@@ -32,25 +36,46 @@ Agent 服务默认地址为 `http://127.0.0.1:8787`。需要完整对话能力
浏览器配置通过 `/runtime-config.js` 注入,不使用 `VITE_` 或 `NEXT_PUBLIC_` 前缀。可在 `.env.local` 中设置以下变量:
开发环境使用内网认证服务时,仅在被 Git 忽略的 `.env.development.local` 中覆盖
`TJWATER_KEYCLOAK_ISSUER`,保留 `.env.local` 的 HTTPS issuer。Vite 默认开发模式读取
此覆盖,正常 production 构建不读取。登录 issuer 必须与 Agent、Server MCP 及 worker
一致;更改后重新加载开发服务器并重新登录,不复用旧 issuer 的令牌。
| 变量 | 默认值 | 说明 |
| --- | --- | --- |
| ---------------------------------------- | --------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `TJWATER_AUTH_MODE` | `required` | Keycloak 认证模式;本地测试可显式设为 `disabled` |
| `TJWATER_KEYCLOAK_ISSUER` | 无 | Keycloak Realm issuer,例如 `https://keycloak.example.com/realms/tjwater` |
| `TJWATER_KEYCLOAK_CLIENT_ID` | `next-tjwater` | Keycloak public client ID |
| `TJWATER_MAPBOX_ACCESS_TOKEN` | 空 | Mapbox 底图访问令牌 |
| `TJWATER_TIANDITU_TOKEN` | 空 | 天地图矢量、影像及中文注记访问令牌 |
| `TJWATER_MAP_URL` | `https://geoserver.waternetwork.cn/geoserver` | GeoServer 服务地址 |
| `TJWATER_GEOSERVER_WORKSPACE` | `tjwater` | GeoServer 工作区 |
| `TJWATER_AGENT_API_BASE_URL` | `http://127.0.0.1:8787` | 浏览器访问的 Agent API 地址 |
| `TJWATER_GEOSERVER_WORKSPACE` | `tjwater_next` | GeoServer 工作区 |
| `TJWATER_SERVER_API_BASE_URL` | `http://127.0.0.1:8000` | 浏览器访问的 TJWater 后端 API 地址 |
| `TJWATER_AGENT_URL` | `http://127.0.0.1:8787` | 浏览器访问的 Agent API 地址 |
| `TJWATER_WORKBENCH_RUNTIME_MODE` | `auto` | 工作台时间模式:工况始终使用 mock,预约工单只读取后端投影;`auto` 和 `backend` 使用当天日期;`demo` 与 `history` 定位到最近一个有后端预约工单的日期,并在同一天生成 mock 工况,其中 `demo` 标记为演示时间。分析成果和后端任务状态不作为工况或日期依据 |
| `TJWATER_PERIPHERAL_SAMPLE_API_BASE_URL` | `/peripheral` | 外围工单服务地址;生产推荐使用同源代理路径,留空时不发起连接 |
| `TJWATER_PERIPHERAL_SAMPLE_TIME_MODE` | `demo` | 历史回放默认时间模式:`demo` 使用固定有数据窗口,`recent` 使用最近时段 |
| `TJWATER_PERIPHERAL_SAMPLE_DEMO_START` | `2026-09-17T00:00:00Z` | 演示历史窗口开始时间(UTC、带时区) |
| `TJWATER_PERIPHERAL_SAMPLE_DEMO_END` | `2026-09-17T12:00:00Z` | 演示历史窗口结束时间(UTC、最长 7 天) |
| `TJWATER_PERIPHERAL_SAMPLE_RECENT_HOURS` | `8` | 实时时间模式回看小时数,范围 1—168 |
| `TJWATER_ENABLE_DEV_PANEL` | `false` | 是否显示开发面板 |
| `TJWATER_ENABLE_MSW` | `false` | 是否启用浏览器端 Mock Service Worker |
`.env.local` 已被 Git 忽略,请勿提交令牌或生产环境配置。
`.env.local` 已被 Git 忽略,请勿提交令牌或生产环境配置。Mapbox 和天地图令牌会随底图请求发送到浏览器,应在服务商控制台限制允许的来源域名。
浏览器使用 Keycloak Standard Flow 和 PKCE S256,不需要也不能配置 client secret。生产环境必须提供 Realm issuer;未认证用户会跳转到 Keycloak,同一 Realm 中已有登录会话时会直接完成单点登录。
Keycloak 中的 `next-tjwater` Client 应关闭 Client Authentication,开启 Standard Flow,并关闭 Implicit Flow 与 Direct Access Grants。Valid Redirect URIs 和 Web Origins 只配置实际使用的前端地址。
Agent 请求由浏览器直接访问 `TJWATER_AGENT_API_BASE_URL`,部署环境需要为前端来源配置 CORS。语音播放始终请求同源 `/api/tts/edge`;开发和预览由 Vite 中间件处理,生产镜像会启动仅监听容器回环地址的 Edge TTS 适配器。无需配置 TTS 服务 URL,可选的服务端变量 `EDGE_TTS_VOICE` 用于覆盖默认中文语音。
业务数据与 Agent 请求分别由浏览器直接访问 `TJWATER_SERVER_API_BASE_URL` 和 `TJWATER_AGENT_URL`,部署环境需要为前端来源配置 CORS。外围样板推荐配置 `TJWATER_PERIPHERAL_SAMPLE_API_BASE_URL=/peripheral`;线上 NPMplus 在现有前端 Proxy Host 中增加 `/peripheral` Custom Location,保留该前缀并转发到 `http://192.168.1.114:8001`,Forward Path 留空。容器内部仍监听 `8000`,宿主机使用 `8001` 避免与已有服务冲突。开发和预览模式提供同路径代理,默认使用 `TJWATER_SERVER_API_BASE_URL`。语音播放始终请求同源 `/api/tts/edge`;开发和预览由 Vite 中间件处理,生产镜像会启动仅监听容器回环地址的 Edge TTS 适配器。无需配置 TTS 服务 URL,可选的服务端变量 `EDGE_TTS_VOICE` 用于覆盖默认中文语音。
回复底部的“音色”入口从 `/api/tts/edge/voices` 加载 Edge TTS 当前提供的全部普通话音色,仅接受 `zh-CN`,排除其他语言、粤语、台湾普通话和地方方言。使用本地 shadcn/ui 的 Popover、Command 和 Button 组合,支持搜索和键盘选择。目录在服务端缓存一小时,界面复用 SWR 内存缓存,不随菜单打开重复请求;HTTP 请求和响应使用 `no-store`,避免版本更新后复用格式不兼容的浏览器磁盘缓存。选择保存在当前浏览器,下一次播放生效;同一次分段朗读固定使用开始时的音色。选择“默认音色”时沿用服务端的普通话配置,显式选择的音色必须通过服务端目录校验。目录加载失败可重试,也可继续使用默认音色。开发服务需要重启以加载语音适配器变更,生产环境需重新构建镜像。
真实语音目录与浏览器播放可通过 `TJWATER_TEST_LIVE_TTS=true PLAYWRIGHT_PORT=5397 pnpm test:browser tests/browser/agent-speech-playback.e2e.ts --reporter=line --workers=1` 验证;默认测试使用音色目录和音频模拟,不依赖微软在线服务。
Agent 模型目录由 Agent 服务提供,页面重新获得焦点或网络重连时刷新;发送指令前再次读取当前目录。仍有效的用户选择会保留,失效时改用目录中的默认模型或首个可用模型,并同步更新菜单。目录为空时提示错误并阻止生成请求。前端始终提交目录返回的完整模型 ID。
Agent 运行时仍可发送消息,底栏可选择“引导”(steer,默认)或“排队”(queue)。右下角只有一个操作位置:运行中输入为空时停止,有内容时发送追加消息;空闲时发送新消息。待处理消息并入输入组件顶部,每条展示正文预览、处理方式和消息菜单;长内容可展开全文,菜单可切换处理方式、退回编辑或关闭排队。编辑需服务端确认撤回,保留已有草稿并等待手动重发。处理状态由 Agent 的原生收件箱决定,已处理后不再允许修改;追加消息和模式切换复用当前会话归属及授权,不会先中断执行。
## 常用命令
@@ -69,6 +94,10 @@ pnpm test:browser # 运行 Playwright 浏览器测试
## Docker
生产镜像使用 Node.js 构建静态文件,并通过 Caddy 提供服务。容器启动时会根据环境变量生成 `/runtime-config.js`,同时启动 Edge TTS 适配器。
奉贤三维建筑资源随仓库中的 `public/city-model/` 一起进入镜像:浏览器先读取
`/city-model/manifest.json`,再通过 HTTP Range 按需读取
`/city-model/buildings.pmtiles`。清单中的 `tiles.buildings.sha256` 必须与归档内容一致,
客户端以该摘要隔离 IndexedDB 持久缓存版本。
```bash
docker build -t next-tjwater .
@@ -105,4 +134,8 @@ src/
## 构建说明
调查任务支持样板反馈的人工复核草稿。在“外围样板”显式导入反馈证据后,可读取同一来源的完整反馈集合、确认并保存新修订;已保存草稿也可从“调查任务”的历史草稿中再次打开,不依赖外围服务在线。页面区分待重分析、冲突证据及前后修订,不代表已经重新计算。接口与存储边界见 [复核修订说明](../next-tjwater-server/docs/feedback-review-revisions.md)。
“分析成果”面板只读取当前项目 BizDB 中已持久化的分析历史,不启动分析任务。外围系统面板管理业务工单,新建工单来源为 `system_data`;显式演练数据保留 `synthetic` 标记,历史监测回放仍为只读。部署所需表和边界见 Server 的[外围系统说明](../next-tjwater-server/docs/peripheral-sample.md)。
生产构建可能提示 Shiki、Mermaid 语言包超过 Rollup 默认的 500 kB 阈值。当前构建和浏览器测试可以正常完成,这些提示不影响产物生成。
+30
View File
@@ -0,0 +1,30 @@
{
"name": "冰水蓝",
"bodyColor": "#DCEFFA",
"bodyOpacity": {
"rest": 0.94,
"active": 0.98
},
"colors": [
{
"name": "水体",
"from": "#121014",
"to": "#299FDF"
},
{
"name": "白色高光",
"from": "#ffffff",
"to": "#FFFFFF"
},
{
"name": "同色相暗部",
"from": "#000000",
"to": "#1482BC"
},
{
"name": "水纹",
"from": "#888888",
"to": "#4C9ECC"
}
]
}
+29
View File
@@ -0,0 +1,29 @@
{
"name": "静水待机",
"fps": 24,
"amplitude": 0.25,
"transitionMs": 600,
"layers": [
{
"name": "内层反射与下侧柔光",
"opacity": [
{ "objectId": 97, "name": "下侧柔光", "rest": 0.56, "crest": 0.68 },
{ "objectId": 190, "name": "内层光圈", "rest": 0, "crest": 0 }
]
},
{
"name": "中层反射与内部柔光",
"opacity": [
{ "objectId": 105, "name": "内部柔光", "rest": 0.48, "crest": 0.62 },
{ "objectId": 199, "name": "中层光圈", "rest": 0, "crest": 0 }
]
},
{
"name": "外层反射与上侧柔光",
"opacity": [
{ "objectId": 101, "name": "上侧柔光", "rest": 0.60, "crest": 0.72 },
{ "objectId": 208, "name": "外层光圈", "rest": 0, "crest": 0 }
]
}
]
}
File diff suppressed because it is too large Load Diff
+19 -3
View File
@@ -6,9 +6,17 @@ runtime_config=$(jq -cn \
--arg keycloakIssuer "${TJWATER_KEYCLOAK_ISSUER:-}" \
--arg keycloakClientId "${TJWATER_KEYCLOAK_CLIENT_ID:-next-tjwater}" \
--arg mapboxAccessToken "${TJWATER_MAPBOX_ACCESS_TOKEN:-}" \
--arg tiandituToken "${TJWATER_TIANDITU_TOKEN:-}" \
--arg mapUrl "${TJWATER_MAP_URL:-https://geoserver.waternetwork.cn/geoserver}" \
--arg geoserverWorkspace "${TJWATER_GEOSERVER_WORKSPACE:-tjwater}" \
--arg agentApiBaseUrl "${TJWATER_AGENT_API_BASE_URL:-http://127.0.0.1:8787}" \
--arg geoserverWorkspace "${TJWATER_GEOSERVER_WORKSPACE:-tjwater_next}" \
--arg serverApiBaseUrl "${TJWATER_SERVER_API_BASE_URL:-http://127.0.0.1:8000}" \
--arg agentApiBaseUrl "${TJWATER_AGENT_URL:-http://127.0.0.1:8787}" \
--arg workbenchRuntimeMode "${TJWATER_WORKBENCH_RUNTIME_MODE:-auto}" \
--arg peripheralSampleApiBaseUrl "${TJWATER_PERIPHERAL_SAMPLE_API_BASE_URL:-}" \
--arg peripheralSampleTimeMode "${TJWATER_PERIPHERAL_SAMPLE_TIME_MODE:-demo}" \
--arg peripheralSampleDemoStart "${TJWATER_PERIPHERAL_SAMPLE_DEMO_START:-2026-09-17T00:00:00Z}" \
--arg peripheralSampleDemoEnd "${TJWATER_PERIPHERAL_SAMPLE_DEMO_END:-2026-09-17T12:00:00Z}" \
--arg peripheralSampleRecentHours "${TJWATER_PERIPHERAL_SAMPLE_RECENT_HOURS:-8}" \
--arg enableDevPanel "${TJWATER_ENABLE_DEV_PANEL:-false}" \
--arg enableMsw "${TJWATER_ENABLE_MSW:-false}" \
'{
@@ -16,9 +24,17 @@ runtime_config=$(jq -cn \
TJWATER_KEYCLOAK_ISSUER: $keycloakIssuer,
TJWATER_KEYCLOAK_CLIENT_ID: $keycloakClientId,
TJWATER_MAPBOX_ACCESS_TOKEN: $mapboxAccessToken,
TJWATER_TIANDITU_TOKEN: $tiandituToken,
TJWATER_MAP_URL: $mapUrl,
TJWATER_GEOSERVER_WORKSPACE: $geoserverWorkspace,
TJWATER_AGENT_API_BASE_URL: $agentApiBaseUrl,
TJWATER_SERVER_API_BASE_URL: $serverApiBaseUrl,
TJWATER_AGENT_URL: $agentApiBaseUrl,
TJWATER_WORKBENCH_RUNTIME_MODE: $workbenchRuntimeMode,
TJWATER_PERIPHERAL_SAMPLE_API_BASE_URL: $peripheralSampleApiBaseUrl,
TJWATER_PERIPHERAL_SAMPLE_TIME_MODE: $peripheralSampleTimeMode,
TJWATER_PERIPHERAL_SAMPLE_DEMO_START: $peripheralSampleDemoStart,
TJWATER_PERIPHERAL_SAMPLE_DEMO_END: $peripheralSampleDemoEnd,
TJWATER_PERIPHERAL_SAMPLE_RECENT_HOURS: $peripheralSampleRecentHours,
TJWATER_ENABLE_DEV_PANEL: $enableDevPanel,
TJWATER_ENABLE_MSW: $enableMsw
}')
+389
View File
@@ -0,0 +1,389 @@
# 本地交互式回答
统一样式见 [样式设计指南](style-design-guide.md),聊天布局与报告交互见 [Agent 交互与报告设计](agent-chat-ui-design.md)。本文保留协议、组件参数与业务交互约定。
## 实施进度(2026-10-30 更新)
原生组件版的主要界面与交互状态保存已实现,已完成本地自动化验证;真实授权项目联调和发布尚待完成。下表的“已实现”指当前工作区代码,不代表运行服务已同步更新。相关改动仍未提交、未部署。
| 能力 | 状态 | 已有范围与剩余边界 |
| --- | --- | --- |
| Agent 内容组织 | 已实现 | shadcn/ui 原生组件、内容分区、导航、指标与证据展示;沿用现有对话和工具执行通道 |
| 任务语义与结果表达 | 2026-10-28 已接入工作区 | `Result`、回答用途、分区角色、疏密及具体说明标题;Agent 选择表达语义,宿主统一视觉与动作边界,真实模型联调待完成 |
| 表格与图表 | 已实现 | 搜索、排序、折线/柱状/数据表切换、区间选择和序列显隐;只处理已加载数据 |
| 报告与 Markdown 阅读 | 已实现 | 表格完整内容可横纵滚动;报告与 Mermaid 有界放大、暗色遮罩、图标按钮、焦点恢复及减少动态效果适配 |
| 定位与资料补充 | 已实现 | 保留专用地图定位和补充资料表单;数据组件不提供勾选、分析篮或组件追问 |
| 交互状态持久化(A) | 核心已实现 | 图表、表格、表单与证据状态按会话保存;支持刷新恢复、兼容迁移、失败重试和显式冲突处理 |
| 阅读位置持久化 | 设计待实施 | reader 记录尚未保存到宿主;分析篮已按产品决定移除,旧 basket 设计不再作为实施目标 |
| 提问与回答生命周期 | 2026-10-28 已接入工作区 | 自有 ask_user、独立草稿、答案持久化与固定 ID 续跑;历史 question 权威核对。真实模型完整链路及发布未验收 |
| 压力历史探索(B) | 设计提案 | `HistoryExplorer` 和新时间窗分页查询尚未实现,不能将本地筛选当成重新查询 |
| 自由代码运行时(C) | 未接入 | 仍采用受控原生组件;独立 iframe、生成代码运行及其通信协议需要另行架构评审 |
| 外围与 Dev 窗口交互 | 已修复 | 窗口外地图可点击、拖动和滚轮缩放;窗口内部操作不穿透地图 |
对应根目录研究文档的四个阶段:阶段一的标准组件路线已实现;阶段三的原生组件状态管理已提前落地;阶段四已接入部分地图、报告和追问流程;阶段二的自由代码运行时尚未接入。本文后续 A/B/C 是实施包名称,与研究文档的阶段编号不同。
2026-10-30 展示范围调整已通过 lint、typecheck、146 个文件共 838 项单元测试,以及 25 项浏览器回归(含复跑,使用模拟接口)。浏览器覆盖桌面与窄屏、内联与展开表格、图表动效、会话状态恢复、地图定位和补充表单;不代表真实项目联调或部署完成。
2026-10-30 分区、导航与来源精简已通过 lint、typecheck、842 项单元测试和 20 项浏览器回归(含复跑,使用模拟接口);另覆盖节点追问移除后的详情与地图定位。
以下为 2026-10-26 的历史验证记录,不代表后续工作区变更的验证结果:
| 验证层 | 结果 | 覆盖边界 |
| --- | --- | --- |
| 前端静态检查与单元测试 | lint、typecheck 通过;121 个文件、631 项测试通过 | 当前原生 UI、状态管理和既有前端回归 |
| Agent 检查与聚焦测试 | `bun run check` 通过;33 项测试通过 | 状态存储、权限、版本冲突、重试和会话生命周期 |
| UI 浏览器验收 | 10 项通过 | 当时的交互状态、引用追问、Markdown 阅读,使用模拟接口;引用追问现已移除 |
| 窗口鼠标行为回归 | 4 项通过 | 外围与 Dev 的窗口内外事件、地图拖动与缩放;修复前已复现遮挡 |
| 前端构建 | 通过 | SPA、生产 CSS 校验和 TTS adapter 构建;不等于部署完成 |
当前实现入口为 [原生回答组件](../src/features/agent/answer-ui/answer-ui-view.tsx)、[会话状态同步](../src/features/agent/session-state/answer-view-state-scope.ts) 和 [Agent 状态存储](../../next-tjwater-agent/src/sessions/answer-view-state-store.ts)。验证命令见下文“验证”,后续顺序见“后续待办与验收”。
2026-10-27 已补齐 [交互状态设计](agent-interaction-state-design.md),覆盖阅读位置、分析篮、正式报告私人状态、接口与存储、版本冲突和验收矩阵。其中阅读位置和正式报告状态尚未实施;分析篮于 2026-10-30 移除,旧设计不再适用。正式报告状态需要新增项目 BizDB 状态表,不能沿用聊天核心 A 阶段“无数据库迁移”的交付结论。后续追加的宿主提问实现状态单列如下。
同日补充的宿主提问方案已于 2026-10-28 接入工作区,见上述文档第 11 节:以自有 ask_user 管理等待、草稿、答案与续跑,同时核对历史原生 question 的可用状态。独立完成此项不代表 reader 或正式报告状态已实施;此前历史故障的具体触发条件仍未取得现场响应。
## 接入方式
聊天保留 AI SDK `UIMessage`、AI Elements 与现有 Agent 后端,新增
`@json-render/core` / `@json-render/react` 的本地注册组件。
组件代码随前端构建发布,无 ChatKit iframe、domain key 或 Vercel/OpenAI
托管 UI 请求。模型仍使用 Agent 的既有配置与工具调用能力。
## 可用内容与交互
`Stack`、`Section`、`Text`、`Result`、`Metric`、`Table`、`Chart`、`Evidence`、
`MapLocation`、`FollowUpForm` 共十种组件。图表可切换折线、柱状和数据表;
表格可搜索和排序,图表可切换已加载区间、显隐序列并查看数据点详情;
证据可按类别筛选、折叠并标注来源;地图定位通过现有控制器执行;表单从空值开始,
由用户主动提交,提交形成普通用户消息。业务证据是否保存以 Agent 实际工具结果为准。
数据组件用于展示与本地浏览,不提供勾选、加入分析、分析内容篮或针对组件追问。`MapLocation` 的定位与 `FollowUpForm` 的补充资料提交保留各自入口。
短回答不显示内容导航;含表格、图表、补充表单或达到长内容标准、且包含至少两种可导航组件的回答才提供目录。单个证据或表单使用组件自身标题,多个独立条目才增加分组折叠;不叠加固定的分区说明。
### 按任务表达内容
Agent 选择组件、内容顺序与受控语义,前端负责实际视觉、响应式布局和可执行动作。新增字段均为 `answer-ui@1` 的兼容扩展,旧记录保持可读;Agent、Server 与前端需同步交付生成目录。
| 组件 | 可配置语义 | 前端行为 |
| --- | --- | --- |
| `Result` | `title`、`summary`、`status`、`source` | 用小面积状态图标和文字区分 `success`、`partial`、`unconfirmed`、`error`;保留摘要及依据,不自动执行操作 |
| `Stack` | 可选 `intent=response/comparison/report`、`density=compact/comfortable` | 指定简短回答、并列比较或报告;比较内容按可用宽度切换双列/单列;密度只调整内容间距 |
| `Section` | 可选 `role=result/analysis/evidence/follow_up` | 将独立分区放入结果、分析、依据或补充资料区域,保留分区内部的顺序 |
| `Text` | 可选 `title`,原有 `tone` 不变 | 使用具体说明标题,例如“能力限制”,避免所有说明都叫“注意事项” |
`Stack` 原有 `columns`、`gap` 与其他组件原有必填参数不变。未给新语义时沿用既有布局;显式 `intent=comparison` 保留作者编排,不再拆成分析与依据区域。`density` 不改变字体、控件大小和触屏命中区域,也不折叠或截断原始数据。颜色、CSS、脚本及任意动作不属于模型可配置参数。
已有执行结果适合 `Result`,批量对象适合表格,真实时间序列适合图表,后续定位适合 `MapLocation`,可选资料补充适合 `FollowUpForm`。模型只能以已有工具结果或明确事实表达成功;未确认的执行或现场状态应保持 `unconfirmed`。演练记录成功与实际业务处置分别说明,`Result` 状态本身不构成执行凭据。正文保留关键结论与边界,辅助组件补充数据和依据,避免重复整段文字。
短结果及说明直接在对话内阅读;包含表格、图表、补充表单或长正文的回答提供展开入口。窗口尺寸、滚动与放大由宿主管理,不作为模型输出样式。
`Chart` 的页签、图例、区间摘要与数据点详情由前端固定实现,Agent 只提供标题、初始图形类型、类别、序列和来源。鼠标切换折线、柱状和数据表时使用 180ms Motion 滑块与内容过渡;键盘操作与减少动态效果模式即时完成。数据点详情只在点击图中数据点,或聚焦图形后按回车、方向键、Home/End 选点时出现,关闭后焦点回到图形;数据表页签不重复展示区间摘要和点详情,搜索与排序在视图切换后保留。
其余组件使用 `answer-motion.tsx` 统一交互过渡,沿用现有实体面板、字体、语义颜色和圆角。首次加载即时显示;鼠标展开、收起使用 180ms 透明度和位移,键盘与减少动态效果模式即时完成。折叠中的内容立即设为 `inert` 并退出无障碍树,动画结束后隐藏;保留原 React 内容实例,反向操作中断旧动画,避免旧退出回调隐藏重新展开的表单。
| 组件 | 交互与内容处理 |
| --- | --- |
| `Stack`、`Section` | 保留既有布局,不为静态分区附加动画 |
| `Text`、`Result` | 静态说明和已有结果直接阅读,不反复播放入场或宣告历史状态 |
| `Metric` | 直接展示原始数值、单位与来源 |
| `Table` | 搜索排序即时响应;无勾选列、选行提示或操作栏 |
| `Evidence` | 正文展开收起和箭头转动使用统一过渡;保留来源、记录时间与资料编号 |
| `MapLocation` | 关联要素详情使用统一折叠;定位中的反馈及结果短时淡入 |
| `FollowUpForm` | 精简与外层重复的补充提示;保留标题、说明、校验及草稿,提交反馈短时淡入 |
| 报告辅助分区 | 分区使用统一展开收起;保留补充表单草稿 |
定位与资料提交的即时状态由用户操作及宿主回调驱动,不读取模型声明的成功状态。定位区分处理中、成功、部分缺失、零结果失败与回执未确认;失败可重试,不支持定位时说明原因。表单提交中阻止重复发送,失败保留草稿;修改字段后清除上一版发送反馈,必填错误与对应字段关联。即时反馈随组件实例存在,刷新后不恢复为本地操作成功;已实现的表单草稿、筛选与图表状态继续使用会话保存通道。
Agent 通过 `present_answer` 发布完整的局部界面块,可在两块之间继续输出文字。
消息顺序为文字、`data-answer_ui`、后续文字与最终报告。同一轮内相同
`block_id` 更新原块,块内稳定的元素 ID 标识同一图表、表格和表单;下一轮不会修改上一轮回答。
这是按内容块逐步出现的界面,不是逐 token 编译 JSX 或每个 JSON 属性都立即显示。
结构化消息与普通聊天共用持久化、历史与断线恢复通道。
新发布的块使用 `phase: "process" | "final"`,省略时按 `process` 发布。同一轮相同 `block_id` 的阶段不可改变;需要最终界面时使用独立 ID 发布 `phase: "final"`。过程块始终留在处理过程,即使误列最终引用也不能进入最终答复或读取、写入最终交互状态。
`final_answer.answer` 中用独立一行的 `[[ui:block_id]]` 固定最终组件的位置,`ui_block_ids` 是允许引用的块 ID 列表,必须与标记去重后的顺序一致。例如:
```text
已完成本次记录核对,结果如下。
[[ui:pressure-summary]]
下面解释异常时间和后续核验建议。
[[ui:pressure-trend]]
```
两个示例 ID 都必须先以 `phase: "final"` 发布,再调用最终答复工具。代码围栏、缩进代码和引用中的标记保持字面文本,不执行引用。重复有效标记只挂载一次;不存在、未授权或过程块的标记显示内容不可用,不泄露过程摘要。
生成期间按原始顺序显示内容;`final_answer` 到达后,正文按标记位置穿插最终组件,其余文字、界面与工具轨迹折叠在“查看处理过程”中。完成态只保留这一层过程折叠,展开后直接列出步骤及状态图标,不再嵌套执行进度卡片、计数和折叠按钮。工具调用按独立行展示状态图标、工具图标及名称,具体参数默认收起。过程与工具参数展开前停止底部自动跟随,以当前消息位置作为锚点;鼠标操作使用短时淡入与位移动画,键盘与减少动态效果模式即时完成。外层箭头与步骤状态使用相同的 24px 图标占位;工具名换行时,状态、工具图标和右侧箭头对齐标题首行,参数说明沿用正文缩进。复制和语音使用相同的最终顺序,以组件摘要替代标记,并排除过程资料。旧历史中没有 `phase` 的块仍按明确引用兼容读取;没有位置标记的旧答复继续在正文后追加引用块,新发布不再依赖这一兼容路径。
同一最终块从生成切换到状态保存时保持组件实例,不因启用持久化而重挂载;尚未完成的编辑先留在内存,最终答复完成后读取远端并合并本地变更。过程块不访问最终状态接口,关闭或切换会话也不产生远端写入。
已发布交互界面的普通/协作聊天在最终答复完成、且没有待完成工具时停止本轮原生
生成,防止最终报告之后反复自动修改界面。该收尾不标记后台调查任务完成;
后台执行继续等待其原有运行生命周期与 Server 完成/失败接口。
后台调查执行继续走任务报告与任务展示通道,聊天界面块不构成业务完成或浏览器回执。
## 正式报告与主工作区
正式报告可携带 `ui_blocks?: Array<{ block: AnswerUiBlock; evidence_refs: string[] }>`,最多 8 块,总 UTF-8 JSON 不超过 400000 字节。每块绑定报告中的已有证据,Server 验证任务归属;事实字段与审批不由 UI 块替代。组件树与聊天共用 `answer-ui@1`。
正式报告块只接受 `phase: "final"` 或未标阶段的旧块,拒绝 `process`;读取旧记录时继续省略阶段字段,不将其改写为 `null`。例如:
```json
{
"ui_blocks": [{
"evidence_refs": ["saved-evidence-id"],
"block": {
"version": "answer-ui@1",
"block_id": "pressure-summary",
"fallback_text": "已保存记录中的压力为 0.30 MPa。",
"spec": {
"root": "pressure",
"elements": {
"pressure": { "type": "Metric", "children": [], "props": {
"label": "压力", "value": "0.30", "unit": "MPa", "source": "已保存监测记录"
} }
}
}
}
}]
}
```
此片段仅展示新增字段,发布时仍需完整报告与真实存在的证据编号。保存沿用 `agent-artifacts`、报告 JSON、幂等键和 revision;读取沿用报告列表、指定版本、任务详情及 Agent context,不新增写入端点或数据库表。
`InvestigationReportBlocks` 将正式报告接入 `AnswerUiView`,证据组件使用保存记录中的摘要、来源、时间与类别;块外只补充尚未在证据卡中展示的引用依据,表格和降级内容仍保留来源。未知版本或无法解析的块展示 fallback,报告固定事实仍可读。补充表单带入会话时携带 `report_revision`、`reportGeneration` 和资料文本,确认后才发送;不提供通用组件追问入口。
`ExpandableReading` 将同一个 React 内容实例移至主工作区,保留图表视图、搜索、排序、表单草稿。关闭恢复入口焦点,重开恢复阅读位置。主工作区宽度至少 960px 可对照地图,其余宽度在两者之间切换;原地图实例保留。
## 扩展组件
1. 在 `src/features/agent/answer-ui/catalog.ts` 增加严格的 Zod 参数定义、用途描述与必要的数据上限。
2. 在 `answer-ui-view.tsx` 注册 React 组件。需要工作台交互时通过 Agent 公共 API 的回调接入,保持依赖方向。
3. 从本仓库运行 `pnpm export:answer-ui-contract`,更新相邻 Agent 仓库的
`src/chat/answer-ui-catalog.json` 和 Server 的 `contracts/answer-ui-catalog.json`。组件目录是唯一参数定义源,生成文件需随三端一起交付。
4. 如新组件存在跨字段约束,同时更新三端的协议校验并加边界和交互测试。
导出脚本接受可选目标文件:
```bash
node scripts/export-answer-ui-contract.mjs /path/to/agent/src/chat/answer-ui-catalog.json
```
前端沿用 Zod 3,json-render 0.21 两个包通过作用域 override 使用相同 schema
运行时;实际组件渲染和参数校验已有聚焦测试。升级 json-render 时必须保留这组
兼容性测试,不能只根据包版本判断可用。Agent 原生插件仍使用其 Zod 4 工具边界,
执行后再按生成的 JSON Schema 校验组件参数。
## 校验边界
三端拒绝未知组件、额外属性、任意脚本/事件定义、缺失引用、循环、重复或游离节点。
每块最多 48 节点、深度 12、完整序列化结果不超过 100000 个 JavaScript UTF-16 代码单元,图表必须对齐且数值有限;表格每行与列数
一致,表单字段名唯一。组件只消费明确的 props,没有动态代码、网络 URL 或任意动作 DSL。
无法解析的历史内容显示该块的 `fallback_text`。
## 验证
```bash
pnpm lint
pnpm typecheck
pnpm test
pnpm test:browser tests/browser/agent-answer-state.e2e.ts tests/browser/agent-answer-ui.e2e.ts tests/browser/agent-intelligent-workspace.e2e.ts --workers=1
pnpm test:browser tests/browser/floating-panel-pointer.e2e.ts tests/browser/peripheral-sample-panel.e2e.ts --grep 'panel keeps outside|项目分析成果打开时|外围面板只读取' --workers=1
pnpm build
```
Agent 仓库:
```bash
bun run check
bun test tests/sessions/answerViewState.test.ts tests/routes/answerViewStateRoutes.test.ts tests/sessions/workspaceStore.test.ts tests/routes/chatSession.test.ts
bun test tests/chat/answer-stream-projection.test.ts tests/chat/answer-ui.test.ts tests/routes/chatStream.test.ts tests/routes/taskCollaboration.test.ts tests/runtime/opencode.test.ts
bun run tests/integration/answer-ui-smoke.ts
```
原生 smoke 使用独立临时数据库,不发模型推理请求。浏览器用例用明确标注的演练
事件验证组件、更新、历史恢复、键盘展开证据、表单提交和 320/375px 布局,不能当作
真实模型已正确选择组件或现场资料已核验的证明。
前端、Agent 与 Server 需同步更新;Agent 进程需重新加载原生插件,Server 需加载新报告 schema。无需新增环境变量、
domain key 或数据库迁移。本轮不重启既有服务;浏览器演练和本地测试不代表运行中的服务已完成同步。
## 真实模型验收(显式启用)
以下浏览器用例直接连接本机 Agent,输入均为明确的演练资料。工作台地图与项目
读取使用测试数据,聊天、模型工具调用、流式 UI、聊天持久化与表单回传使用真实
服务。每次创建独立验收会话,结束后仅删除该会话,不删除既有用户记录。此用例
会发送模型请求,默认浏览器测试不执行它。
```bash
TJWATER_ANSWER_UI_REAL_AGENT_URL=http://127.0.0.1:18787 \
TJWATER_ANSWER_UI_REAL_MODEL_LABEL=专家 \
pnpm test:browser tests/browser/agent-answer-ui-real.e2e.ts --workers=1
```
先在 Agent 仓库启动隔离实例,可指定独立 INTEGRATION_DATA_DIR 保留联调数据。
可省略模型标签来使用默认模型。该用例不是生产 OAuth 登录或真实供水业务核验。
Vite 统一解析 React/React DOM,Playwright 按端口使用独立的依赖缓存,避免同时
运行的开发服务将旧临时目录的 React 预构建写回测试缓存。
消息入口为 `POST /api/v1/responses`,采用 Responses 文本输入、Response 输出和标准 SSE 生命周期。前端 `ResponsesChatTransport` 将网络事件转换为已有 UIMessage 渲染数据;审批、凭据续期、地图动作及 answer-ui 走 `tjwater.*` 扩展事件,不将 AI SDK 的 UIMessage 流作为网络协议。会话、模型及动作回执等接口统一使用 `/api/v1` 前缀,原 `/agent/chat` 路径已移除;Agent 服务和现有会话数据保留。
## 可持续分析工作区:实现与后续设计
状态:2026-10-30 更新。A 的控件状态保存已实现,阅读位置持久化待补齐;分析篮已移除;B 为尚未实现的受控查询方案;C 为独立架构扩展的接入条件。
### 目标与实施次序
以工作区根目录的 [Intelligent UI 研究文档](../../intelligent%20UI.md) 为方向,下一阶段让用户能够保留探索状态、在回答内查询新时间窗、联动地图,再带着明确的对象与范围继续分析。视觉规范仍只引用 [样式设计指南](style-design-guide.md)。
原生组件已具备宿主状态保存,下一步优先验证真实项目中的恢复流程,再推进受控数据查询。自由代码运行时在原生组件无法满足具体场景时单独评审。当前实现沿用既有 Agent 框架与存储,没有新增独立 UI Planner、新数据库或环境变量。
原共享架构 `agent_ui_architecture_without_sandbox.md` 明确排除生成代码执行。本提案的可实施范围仍是原生组件;研究文档中的 sandbox 路线列为独立架构扩展,不借此改变当前运行时约束。
### 已解决问题与剩余缺口
| 问题或约束 | 当前状态 |
| --- | --- |
| 按完整数据设置 React key 导致控件重建 | 已改为稳定节点身份和显式兼容迁移 |
| 控件状态仅在组件内存中,刷新后丢失 | 已接入受控 store 与宿主保存;阅读位置仍未持久化;分析篮已移除 |
| 流式消息写入可能覆盖交互状态 | 已独立保存到 `chat/answer-view-state.json`,复用宿主串行队列、身份及删除校验 |
| `answer-ui@1` 仅接受固定组件与 props | 保留此边界;新交互通过注册组件和受控回调扩展 |
| Server 已有历史查询服务、项目连接与 scada.view 校验 | 新数据查询可以复用原服务,无须让每次选区都调用模型 |
| 公开历史查询接口目前未暴露分页,而服务与 MCP 已支持 row_limit/row_offset | 交互探索需要增加有界的公开分页入口,不能把无限读取的风险留给浏览器 |
这些结论来自源码核对;本轮未请求真实项目数据、模型或生产服务。
### B 阶段目标工作区(尚未实现)
首个场景选择“压力历史分析”。Agent 获取真实监测对象和资料后选择原生组件,简单解释仍只显示文字。聊天流保留结论、判断边界与轻量内容;用户主动展开后,在原工作区内探索。
```text
对话:结论、判断边界、关键读数、展开入口
|
v
压力历史分析 来源与记录时间
对象选择 起止时间 [更新数据] 当前探索 / 原回答快照
趋势 / 数据 [筛选已加载数据]
选中对象的读数、单位、缺测说明 [定位地图]
依据与说明 [以此继续分析]
```
- `更新数据` 明确查询新时间窗;图内的范围选择、搜索与排序只处理已加载数据。参数改动先成为草稿,按按钮提交一次,不随每次键入发请求。
- 桌面继续复用现有地图对照工作区,手机使用同一个实例切换地图与内容。沿用 `Card`、`Tabs`、`Select`、`DateTimeField`、`Table`、`Alert` 和 `Button`;不在窄聊天列内增加固定多栏仪表盘。
- 地图联动以点击为触发,不因悬停、恢复历史或数据到达改变视角。所选对象由明确的图层与 feature ID 表示;名字和数组序号不能充当资产标识。
- `以此继续分析` 将对象、时间窗、来源类别与引用的回答版本带入输入区,由用户确认发送。Agent 重新核验所需数据,不把浏览器传入的数值自动当成服务端事实。
- 历史回答是生成时的快照。探索新时间窗不重写原结论;重新分析产生新的回复。正式报告版本与证据也保持不可变。
### A. 保存交互状态(核心已实现)
下述控件状态与 GET/PUT 接口已接入 Agent 对话中完成的最终回答。前端使用稳定节点标识、受控 store 和按登录范围持有的会话缓存;500ms 防抖保存,恢复期间按字段合并新编辑,保存失败可重试,冲突须明确选择保留本地或重载远端。正式报告的同实例展开保留内存交互,但尚未接入这套聊天状态持久化。
本阶段不扩展模型可生成的组件协议。宿主新增 `answer-view-state@1`,状态身份由当前登录主体、业务项目、sessionId、assistantMessageId、blockId、nodeId 共同确定;主体和项目只能从认证上下文取得。
前端在验证成功后,按 spec.elements 的键建立 nodeId。通过本地渲染适配注入状态句柄,不把 nodeId 注入字段或状态表达式开放给模型。使用 json-render 已有受控 store/StateProvider 接口,将控件改为受控状态,避免第二份组件本地状态与宿主状态竞争。库提供状态绑定机制,但允许持久化哪些字段由本地组件目录决定,见 [json-render 数据绑定](https://json-render.dev/docs/data-binding)。
| 内容 | 保存字段 | 新数据到达时的处理 |
| --- | --- | --- |
| 图表 | 视图、隐藏序列、区间、选中点、详情展开 | 保留视图;序列名与顺序一致才复用显隐;唯一时间标签可重定位选点;无法匹配时清除选择并提示 |
| 图表内数据表 | 搜索、排序 | 切换序列时清理排序;视图切换和状态恢复保留兼容的搜索与排序 |
| 表格 | 搜索、排序 | 搜索保留;列变化清除无效排序;不恢复历史选行 |
| 资料表单 | 字段草稿 | 同 nodeId、同字段名和类型才合并;删除或变更类型的字段不迁移,不自动提交 |
| 证据 | 类别筛选、展开项 | 保留仍存在的证据;不存在的筛选回到全部 |
为兼容已部署的 `answer-view-state@1` 严格校验,表格与图表数据表仍在传输时携带 `selection: []`;前端丢弃旧快照中的选行,不提供相关界面。
尚未持久化:阅读锚点与相对偏移。当前同实例展开/收起的内存保留,不等于刷新后的宿主恢复。
补齐方案见 [Intelligent UI 交互状态补齐设计](agent-interaction-state-design.md):保留现有 controls 接口,计划新增独立 reader 记录;旧 basket 部分已停止实施;正式报告按当前读者及报告版本保存到 Server,不使用发布报告的 Agent 会话充当读者身份。
状态记录附带完整 spec 摘要 `schema_digest`、单块 `revision` 与最后请求 ID。`schema_digest` 由服务端从会话里已保存的块计算;客户端摘要只用于检查过期。摘要变化后执行上表的兼容迁移,再写新版本。按数据整体设置 key 的逻辑改为稳定节点身份加显式兼容处理,不能只删除 key 而沿用越界索引。
已实现的 Agent 接口:
| 接口 | 输入与行为 |
| --- | --- |
| `GET /api/v1/session/:sessionId/ui-state?message_id=…&block_id=…` | 校验会话归属和块存在;返回对应状态、revision、schema_digest;未保存返回空状态及 revision 0 |
| `PUT /api/v1/session/:sessionId/ui-state` | 输入 message_id、block_id、schema_digest、expected_revision、request_id、nodes、block;只接受对应组件允许的状态字段 |
写入在同一串行队列内读取旧记录、检查 expected_revision、校验并原子替换。回执保留最近 32 条且总量不超过 128 KiB;窗口内相同 request_id 且内容一致返回原结果,相同 ID 携带不同内容拒绝。回执过期后,旧请求仍受版本检查保护。版本冲突返回 409 及当前版本,前端保留未保存草稿并提供重载或重新保存,不静默覆盖另一个窗口的状态。保存失败显示“未保存”,不声称刷新后可恢复。
初次恢复完成前允许阅读和编辑,但不以 revision 0 覆盖未知的已保存状态;记录本地变更字段,读取成功后按字段合并,用户刚输入的内容优先于迟到的恢复结果。失败时保留草稿并允许重试,重载远端状态必须明确提示会替换哪些本地改动。
持久化使用宿主 `chat/answer-view-state.json`,独立于 messages.json;文件已加入 SessionWorkspaceStore 的受控记录列表,读取消息、检查版本和原子写入均在宿主队列内执行。状态来自用户交互及其兼容迁移,不进入模型可写的 workspace/,不进入默认推理上下文。删除会话沿用宿主删除标记和串行清理,迟到写入不能复活记录;分叉会话不继承未提交表单。
当前限制:每块状态最多 32 KiB UTF-8,单会话状态文件最多 1 MiB;只保存控件字段及迁移依据,不复制原始时序读数、授权凭据或错误堆栈。服务端超限返回 413,前端单块预检超限时不发送;两者均保留当前内存草稿并提示未保存。前端 500ms 防抖,切换会话时对已完成初次读取的改动发起保存;退出时清空内存,不能依赖页面卸载请求保证保存成功。无须迁移旧 messages.json,旧会话首次保存时惰性创建状态记录。
### B. 压力历史探索(设计提案,未实现)
新增注册组件 `HistoryExplorer`,作为拥有固定业务语义的原生组件,不开放模型编写请求 URL、工具名或任意 action。其 props 为 title、targets、initial_start、initial_end、source;targets 只允许查询结果中明确关联的 junction ID 与 device ID,最多 5 组;source 首批只允许 scada_raw 或 scada_cleaned。时间为带时区 ISO 字符串,单次范围不超过 24 小时。缺少对象关联时继续展示原有 Chart 与数据缺口说明,不生成猜测绑定。
该组件仍通过 answer-ui@1 的目录扩展交付,保持 envelope 与快照格式不变;前端为参数唯一来源,导出 Agent、Server 的 props schema,并在三端增加相同的交叉校验。旧客户端遇到新组件显示 fallback_text,不能执行未知组件。Agent 和 Server 先支持校验,前端发布后再启用该组件的生成指令;旧客户端仍可阅读摘要。
前端 `agent` 模块只声明 `onQueryHistory` 回调与数据结果类型,`workbench` 实现身份、项目头、请求和地图控制器。不能从 agent 深入导入 workbench,也不在 Agent 服务里新建通用查询代理。
```text
已有 Agent Harness -> present_answer -> 现有校验与消息通道
|
v
原生回答 + 交互状态
|
用户显式操作
|
Workbench 适配器
/ \
地图控制器 Server 历史服务
|
查询结果回到当前探索视图
```
Server 拟新增 `POST /api/v1/timeseries/views/element-history/page`,复用 TimeseriesHistoryService.query 的 row_limit/row_offset 路径及当前项目数据库连接,保留 scada.view 授权。请求包含上述明确对象与时间窗,以及 limit、offset;首批只支持 observed。limit 默认 500、最大 1000,offset 为非负整数,最多 5 个对象、24 小时。返回 series、page.limit、page.offset、page.has_more、queried_at;不改变原无分页接口。
每次“更新数据”最多读取 5000 个点或 10 页,以先到者为准;超过预算保留已读部分并明确“时间窗未完整覆盖”,提示缩小范围。Server 每页有界,浏览器也限制累计体积;到达 2 MiB 停止继续加载。不能用前 100 点冒充完整 24 小时。分页是在有数据写入的系统中逐页读取,不承诺跨页一致快照;按对象、设备、来源、时间去重,保留查询时刻和查询参数,正式证据仍由后端报告流程形成。
新请求取消旧请求并提升 request generation;结果只有在项目、会话、节点和 generation 均匹配时可应用。超时或服务失败保留旧图,并同时显示旧图的实际时间窗与失败原因;无数据与请求失败分开表达。返回 null 的点显示缺测断线,不补零;按 source_unit 展示,转换需有明确单位规则;原始、清洗、实时模型和分析结果不能混为同一种来源。
刷新数据不修改消息快照。查询参数和控件状态可以保存,未固化的探索数据只留在当前会话内存;刷新页面后先显示原回答或待加载状态,用户点击“更新数据”重新取数。需要跨日保存的业务结论仍通过现有正式报告与证据通道发布。
### C. 自由代码运行时(未接入,需独立评审)
本轮只确定接入条件:出现标准组件难以表达、且确有使用价值的交互图解或模拟,再单独评审 sandbox 协议与运行环境。阀门工况计算必须复用实际仿真服务;可拖动示意图不等同于水力模型。
后续设计参考 [MCP Apps 的 AppBridge](https://github.com/modelcontextprotocol/ext-apps/blob/main/src/app-bridge.ts) 的初始化、能力协商、结果推送和 teardown,把动态程序当作独立实例管理。其工具转发能力不能原样映射为“允许调用全部供水工具”。iframe 本身也不能证明资源消耗或业务权限已受控。
接入前须完成:独立来源与 CSP/网络策略、消息来源与实例校验、显式能力列表、宿主中止与生命周期、版本替换及状态迁移、崩溃后的文本回退、真实浏览器资源预算验证。生产控制、业务写入和审批继续由既有服务执行。本阶段不新增 sandbox 入口、依赖或服务器,因此不会留下无法使用的占位 UI。
### 后续待办与验收
A 与 B 可独立交付,B 尚未实现不影响已有聊天控件的状态保存。建议按以下顺序推进,正式提交和发布按各仓库分别执行。
| 顺序 | 待办 | 完成标准 |
| --- | --- | --- |
| 1 | 已实现能力的真实联调与交付 | 在隔离 Agent 与已授权项目中验证保存读回、刷新恢复、会话隔离、报告/表单回传;补充真实模型组件选择验收,再整理提交与发布记录 |
| 2 | B 阶段压力历史探索 | 用户选择对象和时间窗后显式查询;分页有上限、缺测不补零、旧响应不覆盖新请求;定位地图并携带查询范围继续分析 |
| 3 | 实施已补齐的状态设计 | 优先独立交付宿主提问生命周期;聊天 reader 和正式报告私人状态另分两批,分别验证恢复、清理与版本隔离 |
| 4 | C 阶段架构评审 | 先确认原生组件无法满足的具体场景,再决定是否引入沙箱及其权限、通信、资源预算和生命周期 |
| 阶段 | 主要修改位置 | 必须验证 |
| --- | --- | --- |
| A 前端(已实现) | answer-ui/answer-ui-view.tsx、answer-parts-view.tsx、answer-view-state.ts、answer-view-state-provider.tsx;agent/session-state/;workbench/hooks/use-workbench-agent.ts;agent/api/client.ts | 状态注入、同块更新、无效选择清理、迟到恢复不覆盖新输入、会话隔离 |
| A Agent(已实现) | sessions/workspace-store.ts、sessions/answer-view-state-store.ts、routes/answer-view-state-routes.ts、routes/chat.ts | 身份和块归属、原子版本检查、幂等重试、冲突、字节限制、会话删除竞态 |
| B 前端 | answer-ui/catalog.ts、contract.ts、answer-ui-view.tsx;新增 history-explorer.tsx、workbench/api/element-history-client.ts;现有 workbench-agent-panels.tsx 的回调装配 | 参数校验、请求与本地筛选区分、取消和旧响应、缺测、单位、地图定位失败 |
| B Agent / Server | 导出的 answer-ui-catalog.json;三端 answer-ui 校验;Server timeseries/composite.py、timeseries_history.py 的分页请求/响应模型;Agent instruction.md | 旧消息降级、新组件约束一致、Server 分页限制、scada.view 和项目隔离 |
前端执行 `pnpm lint`、`pnpm typecheck`、`pnpm test`,并扩充 `tests/browser/agent-answer-ui.e2e.ts` 的 320/375/1440px 用例。A 在 Agent 执行 `bun run check` 及 `tests/sessions/workspaceStore.test.ts`、新增状态存储/路由测试、`tests/routes/chatSession.test.ts`。B 追加 Agent `tests/chat/answer-ui.test.ts`,Server `tests/unit/test_timeseries_history.py`、`test_timeseries_history_schema.py`、`test_report_ui.py` 与新增分页 API 授权测试。新增 schema 后运行 `pnpm export:answer-ui-contract`;发布前完成前端构建和真实授权项目的有界读查询验收。
验收场景必须包含:保存后刷新、两窗口编辑冲突、数据更新时仍在填写表单、重复序列标签、数据集换序、断网与 403、切换项目后旧响应返回、删除会话后迟到保存、未知组件回退、减少动态效果、键盘焦点与窄屏无溢出。保存成功必须有读回证据,不能仅以组件没报错作为通过。
最关键的前提是查询结果能明确关联监测设备与管网对象;现有数据若缺少关联,地图入口应显示不可定位并保留读数,不能使整个分析失效。真实模型选型与数据质量均需独立验收,组件测试不替代它们。
发布 A 时先部署 Agent 的可选状态接口,再部署前端;没有接口或保存失败时保持可读和内存交互,并显示未保存。回退保留新状态文件和已有消息,不清理用户资料。B 回退时停止生成 HistoryExplorer,旧客户端按已有 fallback 读取,保留原查询接口。上述两阶段均不需要新账号、密钥或环境变量。
### 地图与外部展示动作
`answer-ui@1` 继续描述可保留的回答内容;动作统一为 `{command: {action, ...字段}}`。Chat 的 `present_view` 使用 `frontend-action@2` 和 `frontend-action-result@2`,调查任务事件及 Dev JSONL 使用相同 command,由共用执行器处理。定位按钮也使用该执行器。十种动作和验证步骤见 [调查任务展示与 Dev 测试](investigation-dev-tools.md#统一展示动作)。动作是一次性过程副作用,不因 final_answer 引用 UI 或历史渲染而重放;block_id/phase/正文锚点规则不变。
+249
View File
@@ -0,0 +1,249 @@
# Agent 交互与报告设计
本文维护供水前端 Agent 对话、正式调查报告和展开阅读的功能、布局与业务交互。组件基础、配色、材质、排版和无障碍样式统一遵循 [样式设计指南](style-design-guide.md),阶段验证结果见 [实现记录](history/agent-chat-ui-implementation-notes.md)。
Agent 相关弹窗、面板及菜单统一保持本地 shadcn/ui 设计,具体外观规则由样式设计指南维护。本文规定的历史全屏、展开阅读、审批和主题管理等布局均遵循该规则。
## Intelligent UI 的目标
本文中的 Intelligent UI 参考 [ChatGPT Intelligent UI](https://help.openai.com/en/articles/20001598-intelligent-ui-in-chatgpt):回答根据内容选择交互呈现,用户在阅读中探索数据、核查来源并继续提问。Vercel AI Elements 和 shadcn/ui 提供组件与布局参考,功能通过本项目本地组件实现。
当前落地为“左侧对话 + 主工作区”。聊天回答与正式调查报告共用指标、图表、表格、证据、定位和资料表单。复杂内容由用户点击展开到主工作区;调查状态、结论边界、证据、审批和版本仍由 Server 保存的事实驱动。模型只在注册组件中选择呈现方式。
## 功能梳理
以当前组件、回调和消息契约核对功能,再决定它们出现的位置,不继承原有界面分区。
| 功能组 | 已有能力 | 新布局中的位置 |
| --- | --- | --- |
| 会话管理 | 新建、历史加载、重命名、删除、折叠和关闭 | 顶部会话栏,历史通过独立窗口按需打开 |
| 上下文 | 会话标题、主题选择及管理 | 主题收于助手导航区;会话标题独占下方宽度,最多两行 |
| 输入 | 多行文字、引用报告或任务、语音输入、草稿 | 底部统一输入区,空会话使用独立欢迎状态 |
| 模型与权限 | 模型选择、审批模式 | 输入组件底栏,保留当前选项反馈 |
| 运行控制 | 停止、运行中引导、排队消息、投递方式和未消费消息撤回编辑 | 输入组件顶部的紧凑队列与底栏发送方式 |
| 消息阅读 | 流式文字、Markdown、历史恢复、滚动跟随 | 主阅读流,用户消息与助手回复分层 |
| 过程与状态 | 执行进度、工具结果、待办、错误、连接状态 | 回复内的过程区域及顶部真实连接状态 |
| 人工参与 | 权限审批、问题回答和跳过、补充资料 | 对应回复内保留可操作表单,确认前不执行 |
| 分析结果 | 指标、表格、折线和柱状图、证据 | 回复中的交互内容,可搜索、排序、选点、筛选序列及已加载区间 |
| 展开阅读 | 聊天回答与正式报告进入主工作区 | 明确点击进入,保留唯一组件实例、筛选、表单草稿和阅读位置 |
| 数据浏览 | 指标、数据点、表格、证据 | 展示与本地查看;不提供行勾选、分析篮或组件追问 |
| 正式报告 | 当前结论、结论边界、证据、缺口、待办、审批与历史版本 | 固定事实区与可选交互分析模块组合 |
| 地图联动 | 定位实际要素、显示定位结果 | 对应内容内的明确按钮 |
| 回复工具 | 复制正文及交互摘要、朗读和选段朗读 | 回复底部低强调操作及文字选择入口 |
| 任务协作 | 任务引用、报告轮次、协作问答模式 | 输入引用区和回复依据,保留协作语义 |
普通用户的阅读路径为:确认当前项目,提出问题,阅读回答,核查来源,再按需要定位地图或补充资料。审批和队列在有实际内容时出现,历史与处理过程按需展开。
任务协作以对应任务名称作为初始标题,随后由 Agent 根据任务名称与对话内容生成具体标题;生成失败或仅返回通用名称时保留现有标题。“任务协作”仅作为历史列表中的类型标记。旧的通用标题随历史分页和详情读取逐步补齐,保留手动重命名及原有顺序;标题更新不重载消息或打断当前对话。
运行中的输入区使用一个外框:顶部显示待处理消息,正文最多预览两行,溢出时提供“展开全文”;每条消息只保留正文、简短的处理方式和一个菜单。编辑、处理方式切换、关闭排队统一进入该菜单。底栏在生成期间用“引导 / 排队”替代暂时不能切换的模型选择,生成完成后恢复模型选择。右下角的同一个按钮在运行且输入为空时停止,有内容时发送追加消息,空闲时发送新消息。输入正文默认高 64px,随多行内容自动增高至视口高度的 24%,最多 160px;超出后在输入区内部滚动,清空后恢复 64px;队列单独限制滚动高度,工作台支持的窄屏和短窗口保留可见的输入操作。
## 1. 交互参考
[AI Elements](https://elements.ai-sdk.dev/) 基于 shadcn/ui,提供组合式的 AI 应用组件。它将对话容器、消息、输入、过程、来源和工具状态拆成独立组件,适合在同一条消息中呈现文字与交互内容。官方当前提示组件正在迁入 shadcn/ui;本项目维护本地源码,参考交互方式,按需要适配组件。本文不要求整体替换现有依赖。
| 官方参考 | 采用的设计方式 | 本项目对应内容 |
| --- | --- | --- |
| [Chatbot 示例](https://elements.ai-sdk.dev/examples/chatbot) | 以消息阅读为主体,输入区独立,辅助操作低强调 | 左侧会话布局、空会话入口和回复操作 |
| [Conversation](https://elements.ai-sdk.dev/components/conversation) | 自动跟随消息,离开底部后提供返回入口 | 保留本地滚动管理与“滚动到最新消息” |
| [Message](https://elements.ai-sdk.dev/components/message) | 用户与助手分层,正文、流式 Markdown、操作栏组合 | 用户气泡、开放式助手正文、复制和朗读 |
| [Prompt Input](https://elements.ai-sdk.dev/components/prompt-input) | 输入、模型、工具和发送组成同一个输入组件 | 统一输入面、权限模式、模型、语音、停止与发送 |
| [Reasoning](https://elements.ai-sdk.dev/components/reasoning) | 生成过程可展开,完成后收起 | 已有执行摘要与“查看处理过程” |
| [Tool](https://elements.ai-sdk.dev/components/tool) | 工具状态与输入、输出按需展开 | 真实执行进度、审批与用户问题 |
| [Sources](https://elements.ai-sdk.dev/components/sources) | 来源单独呈现,详情按需展开 | 来源名称、证据类别、记录时间及资料编号 |
| [shadcn/ui Tabs](https://ui.shadcn.com/docs/components/radix/tabs) | 同一内容的视图用键盘可操作的页签切换 | 图表折线、柱状、原始数据切换 |
用户消息与助手回复分层组织,图表、证据与资料输入按内容用途组合。交互内容表达已有数据和可执行动作,不用虚构指标或装饰性进度制造智能感。
## 2. 组件规则
| 区域 | 组件组合 | 展示与行为 |
| --- | --- | --- |
| 消息列表 | AI Elements `Conversation`、`Message`、`MessageContent` | 用户右对齐,助手使用完整阅读宽度 |
| 助手标识 | 共享 `AgentPersona`、shadcn `Badge` | 角色、真实回复状态及交互内容标记 |
| 回复操作 | AI Elements `MessageActions`、`MessageAction` | 复制正文与结构化摘要,保留朗读能力 |
| 指标 | shadcn `Card`、`CardContent` | 名称、值、单位、来源;同组指标使用紧凑对照条,提问入口采用有名称的图标按钮 |
| 图表 | `Card`、`Tabs`、`Collapsible`、现有图表渲染器 | 折线、柱状、数据三种视图;范围筛选按需展开,收起时仍显示已选范围 |
| 表格 | 本地 shadcn/ui `Table` 组件组合 | 列头、标题、数值、键盘可达的滚动容器 |
| 证据 | `Collapsible`、`Button`、`Badge` | 收起时可读来源与类别,展开显示完整摘要和编号 |
| 地图定位 | `Button`、位置图标 | 由用户点击触发,显示依据和实际定位结果 |
| 补充资料 | `Input`、`Textarea`、`DateTimeField`、`Button` | 从空值开始,明确必填和提交状态 |
| 历史对话 | `Dialog`、`Input`、会话列表 | 跨主题标题及正文搜索、时间分组、游标分页与会话操作 |
| 模型与主题 | `DropdownMenu` | 模型选择、主题归类与管理;数据权限跟随当前业务项目 |
| 报告目录 | `nav`、`Button` | 展开阅读时固定于阅读区顶部,仅显示实际章节;支持键盘跳转和滚动位置提示 |
| 工作区分栏 | `ResizablePanelGroup`、`ResizablePanel`、`ResizableHandle` | Agent 与主工作区、地图与报告均可拖拽;分隔线可通过 Tab 聚焦,方向键及 Home / End 调整宽度 |
尺寸、圆角和交互状态按样式设计指南选用共享变体。尚未接入的附件、网页搜索和回答重试不展示可点击占位按钮。
## 3. 布局
```text
桌面
┌───────────────────────┬──────────────────────────────────────┐
│ Agent 对话 │ 主工作区 │
│ 会话 / 上下文 │ 默认地图 │
│ 消息、交互摘要 │ 点击展开 → 报告与分析 │
│ 待答问题与权限审批 │ 宽度足够 → 地图对照 / 专注阅读 │
│ 队列摘要 / 引用 / 输入│ 宽度不足 → 查看地图 / 返回报告 │
└───────────────────────┴──────────────────────────────────────┘
```
主工作区可用宽度至少 960px 时开放地图与报告双列;较窄窗口在地图与报告之间切换。地图实例保留,不重新初始化。手机只显示当前阅读面;展开时保留原抽屉内容实例,收起后恢复。
2026-10-21 分栏实现更新:采用 [shadcn/ui Resizable](https://ui.shadcn.com/docs/components/radix/resizable),通过本地 [resizable.tsx](../src/shared/ui/resizable.tsx) 封装 `react-resizable-panels` v4。外层直接承载 Agent 和主工作区,替代手写 Pointer Events 拖拽;内层直接承载地图和报告,替代固定的双列 Grid。
Agent 保留 400px 最小宽度与按窗口计算的最大宽度,上限 640px。收起、临时缩窄窗口及恢复桌面后沿用本次页面内的用户选择。地图与正式报告默认等分,每栏至少 360px;已有分析成果沿用每栏至少 600px 的限制。切换专注阅读后再次分栏,恢复上次调整的比例。手机隐藏分隔线,继续使用抽屉和地图 / 报告切换。尺寸记忆保存在当前页面内,不写入持久化存储。
两级分栏的容器保持挂载,地图 canvas 跟随实际容器尺寸更新;报告内容继续通过单实例移动保留草稿和阅读位置。手柄使用浅灰细线与可见拖拽标记,键盘焦点使用主题蓝色轮廓;连续调宽不附加布局过渡动画。
展开操作移动同一个内容实例,避免两份表单、重复提交和草稿分歧;关闭或 Escape 后回到原入口并恢复键盘焦点。阅读位置随文档保留。报告版本改变时切换到该版本自己的内容状态。会话或报告卸载时关闭对应工作区。
```text
Agent 面板
├─ 会话栏:助手标识 / 连接状态 / 新建与历史 / 折叠或关闭
├─ 上下文条:会话标题 / 主题
├─ 可滚动消息区
│ ├─ 用户问题
│ └─ 助手回复
│ ├─ 角色和真实生成状态
│ ├─ 正文与指标、趋势、表格
│ ├─ 证据、地图入口、资料表单
│ ├─ 可展开的处理过程
│ └─ 复制与朗读
└─ 输入区:引用 / 多行输入 / 权限、模型、语音、发送或停止
```
纯指标的双列 `Stack` 合并为紧凑摘要区,容器宽度达到 240px 即可并排;名称、原始数值、单位和来源完整保留,不用省略号截断。指标仅展示名称、数值、单位和来源。混合内容的双列仍使用 440px 断点。助手正文直接进入消息流,证据按需折叠,补充表单保留独立操作区;表面与间距统一引用样式设计指南。
图表首先显示标题、视图切换、序列和趋势。范围选择默认收起,展开后可选择起止点及重置;收起只改变展示,不取消已选范围。序列按钮使用低强调色,图例颜色保留数据对应关系;至少一条序列可见。数据点的各序列值分行对齐,保留原始精度。
正式报告展开后采用连续文档排版,章节之间使用细分隔线。目录跟随阅读区滚动,包含实际存在的结论、分析、调查进展、待办、处置、缺口、脉络、依据、时间线和版本。目录使用导航语义,点击或键盘激活后立即滚动并将焦点交给目标章节;手机目录可横向滚动。接近文档末尾、目标无法滚至顶部时,保留主动选择的章节标记,直到用户再次滚动。该导航只改变阅读位置,不控制任务执行或审批。
空会话采用“简短引导、首次输入、推荐问题”的顺序,整组在 Agent 面板内横向居中,放在会话栏下方可用区域的中部。居中容器最多 600px,桌面内边距 24px,手机左右内边距 16px;短屏内容超过可用高度时从顶部排列并允许滚动。判断依据是当前会话有无消息,不取决于帐号是否保存其他历史会话。加载历史、引用任务或已有工具权限审批、结构化结果时保留正常阅读区,不覆盖为欢迎页。
输入文字区初始高度 64px,按内容增长至视口允许的高度。首次发送后同一个输入组件回到底部;新建空会话后恢复居中布局。使用 `motion/react` 的位置布局动画处理这两种状态,沿用项目的 180ms 缓动,不缩放输入文字,也不对 Resizable 连续调宽添加动画。系统开启减少动态效果时直接切换位置。表单实例和草稿在布局变化时保留。
推荐由现有接口生成,排列在首次输入框下方,使用低强调的圆角按钮,窄屏自动换行显示完整问题,实际来源仍可通过 hover 或键盘焦点提示查看。点击发送完整原始问题。加载或生成失败时显示简短状态,也不影响普通输入。材质与边界复用共享样式,输入底栏保留现有操作。
Agent 形象基于 [Obsidian 原版动画资源](https://ejiidnob33g9ap1r.public.blob.vercel-storage.com/obsidian-2.0.riv),通过本地定制的 `obsidian-water-v1.riv` 使用已确认的 02「冰水蓝」材质并增加离线水纹,以高遮蔽度的浅冰蓝底色和白色高光保留柔和羽化、流动反射与不规则边缘水纹。完整视觉与交互规格见 [Persona 设计](agent-persona-design.md)。默认形象与悬浮入口使用 64 × 64px,画布填满点击范围;入口距地图左侧、顶部导航下沿均为 12px,由同一层内边距控制。桌面及手机面板标题栏中的形象也使用 64px,手机地图入口使用 40px。三处通过同一个 `AgentPersona` 组件显示,保留原版资源自身的羽化留白。悬浮形象不附加状态文案、状态点、箭头、卡片或按钮底圈。完整业务状态继续通过按钮无障碍名称与原生悬停提示提供,点击或 Enter / Space 展开对话。
标题区分为导航与标题两层。导航行高 80px:左侧为 64px persona,其右侧首行并列助手名称与连接状态,状态位于名称右侧;下方间隔 6px 放置主题下拉,使用文件夹图标与名称,不再另列“主题”标签。连接状态保留共享状态点和文字,主题按钮使用本地 `Button` 的 `outline` / `sm` 变体,高 32px,使用文件夹和 Lucide 上下切换箭头。右侧集中放置新建、历史及折叠或关闭按钮,命中范围均为 40px。导航与会话标题之间只保留一条本地 `Separator`,使用 1px、`bg-border/40` 的低对比度分界线。默认空白会话不渲染“新对话”占位标题,也不保留空标题行。有实际会话时,标题区四周留白 12px,只显示当前会话标题,独占宽度、最多两行,不再增加下边框。长主题名在导航剩余空间内收缩,完整名称通过提示与可访问描述保留;320px 手机宽度下不挤压三个操作按钮。
在线动画由 Rive WebGL2 播放原资源的 `default` 状态机。沿用原生 `thinking`、`listening`、`speaking` 和 `hover` 控制项,状态过渡及水纹细节由资源自身完成。原版公开组件可见 [AI Elements Persona 源码](https://github.com/vercel/ai-elements/blob/main/packages/elements/src/persona.tsx);图形制作数据位于运行资源中,可编辑设计文件是 `.rev`,见 [作者的定制说明](https://elements.surge.studio/docs/customization)。已移除之前自行生成球缘曲线、光带和局部高光的实现,也移除改写原版明暗的 CSS 滤镜。配色直接写入 Rive 材质,暗部保持蓝色倾向,高光使用白色。
离线通过同一 Rive 资源中的 `asleep` 状态呈现“静水待机”:关闭外围三层光圈,保留完整蓝色球体及内部柔光的低速、小幅度流动。在线与离线切换保持同一个动画实例,通过资源内的状态混合衔接,恢复连接后回到在线光圈与节奏。参数和图层说明统一维护在 [Agent 动画资源说明](agent-persona-resource.md)。首次加载、加载失败和系统开启减少动态效果时显示从当前资源渲染的在线或离线静态帧,离线静态帧同样不带外围光圈;兜底形象与按钮功能持续可用。
鼠标悬停沿用原生 `hover` 动画和光圈尺寸;进入、移动、离开坐标通过共享组件交给 Rive 原生监听,使白色高光跟随鼠标局部移动,避免只开 hover 却使反射固定在中心。移出后恢复常态。球体组件移除 Motion,取消按压缩放、弹簧回弹和明暗变化;触摸按下不触发额外动画。点击、触摸轻点及 Enter / Space 继续展开对话,离线时同样可用。系统开启减少动态效果时显示静态帧,不初始化 Rive。强制颜色模式显示高对比圆形轮廓,保留键盘操作。球体动画与面板布局独立,不对 Resizable 连续调宽增加动画。
渲染生命周期继续遵守 [Rive 内存问题记录](rive-persona-incident.md):延迟一帧初始化,元素离开视口或页面隐藏时卸载渲染实例,不绑定 View Model;仅缓存不可变的 `.riv` 字节,展开、折叠和不同入口复用一次成功下载。失败下载不永久缓存,后续挂载可重试。动态组件准备完成前保留本地静态帧,原生进入动画在显示切换前完成。静态帧与动画通过 180ms CSS 透明度渐变衔接,结束后才隐藏静态帧,避免首次加载瞬间切换造成的跳动;画布的位置与尺寸始终固定。本轮没有新增依赖,也没有恢复已知存在内存问题的颜色绑定。
### 离线动画的资源改造
已解析原版的图形、属性、关键帧和状态机,保存为可读的运行时 JSON,并验证可以逐字节恢复原始 `.riv`。修改后的资源保留 5 个原生状态输入,在原有 20 段动画后增加 3 段离线循环,修正 `asleep` / `wake` 中隐藏和缩小球体的关键帧。修改、再生成及保真验证见 [Agent 动画资源说明](agent-persona-resource.md)。这份 JSON 是运行时数据,不是完整恢复的 `.rev` 编辑器工程。
### 历史窗口、缓存与后台会话
“主题”参考 [ChatGPT Projects 的会话组织方式](https://help.openai.com/en/articles/10169521-projects-in-chatgpt),作为会话组织单元,用于归集相关事件和问题;与决定数据权限的业务项目分开。Agent 的主题下拉参考 shadcn [TeamSwitcher 模板](https://github.com/shadcn-ui/ui/blob/main/apps/v4/registry/new-york-v4/blocks/sidebar-07/components/team-switcher.tsx)的起始对齐、触发器宽度与最小菜单宽度,配合本地 `DropdownMenuRadioGroup` 表示主题单选。菜单标注“切换主题”,主题列表独立滚动,新建与管理操作保留在底部;支持未分类、主题选择、新建和管理;原无处理逻辑的“新建项目”入口移除。Agent 默认访问当前工作台业务项目的数据,移除聊天面板中的“个人/项目数据”切换入口及前端个人会话分支。数据访问权限由项目身份和服务端授权决定,后续按角色限制可访问范围,主题选择不改变数据权限;业务项目切换仍从工作台入口进入。选择主题开启该主题的新对话,当前会话草稿和后台生成继续保留;新建对话沿用当前主题。主题名可修改,删除主题时会话保留为未分类;历史行操作可将已有会话移入其他主题或移出为未分类。主题列表内存缓存 5 分钟,登录和业务项目隔离,并发复用。旧会话默认未分类,不移动现有业务数据。本轮主题用于组织记录,不自动合并其他会话上下文、共享指令或附件。
主题新建、重命名、管理与删除确认使用标准 `DialogHeader`、`DialogDescription`、`Input` 和 `DialogFooter`。表单显示名称标签、80 字符限制、错误与取消/提交按钮;管理页使用可滚动的平面列表,每行保留重命名与删除入口,底部提供新建与完成。重命名和删除进入有明确标题的独立步骤,删除前确认会话保留规则。打开表单聚焦名称输入,打开管理页聚焦新建入口;失败保留输入,关闭后恢复主题按钮焦点。主题增删改先完成共享列表读取,再更新服务端与缓存,防止旧列表请求晚返回覆盖刚创建或修改的主题。
历史按钮打开独立模态窗口,桌面最大宽度 760px、高度不超过视口的 80%;小于 640px 时使用全屏窗口,保留安全区和独立滚动。窗口包含当前业务项目、标题及正文搜索、主题筛选、时间分组、会话状态和关闭入口。标题最多两行,重命名和删除进入每行操作菜单,删除需明确确认。选择会话成功后关闭窗口,失败时保留当前聊天与列表并显示错误。关闭、Escape 及取消操作恢复触发按钮焦点;模态期间底层地图和通知不覆盖窗口。
会话列表每页 30 条,标题及可见消息正文搜索在服务端覆盖当前用户及当前业务项目下的全部主题及未分类记录,结果显示所属主题和正文命中摘要,输入防抖 250ms,按更新时间及 ID 排序;时间按浏览器本地时区分为今天、昨天、近 7 天和更早。窗口浏览期间保持条目顺序,运行状态原位更新;有新的排序结果时由用户点击更新。关闭窗口保留已加载页和搜索缓存。历史统一包含普通对话和手动任务协作,不展示后台执行会话。主题筛选独立于搜索词,默认“全部主题”,不随当前对话主题隐式收窄。
正文首次读取最近 40 条,向上滚动或点击“加载更早消息”继续读取。插入旧页保持当前可见消息的位置。用户向上阅读后停止自动跟随,点击返回最新消息恢复跟随。恢复流也使用最近消息页,客户端按稳定消息 ID 合并旧页和实时尾部,断线区间缺口通过分页补齐。服务端仍保留完整历史,续聊只发送本轮输入;UI 分页不截断原生会话和保存记录。当前磁盘存储仍整份读取 JSON,分页主要减少网络传输和浏览器渲染。
缓存属于当前登录生命周期,按业务项目隔离并跨工作台重挂载复用;退出登录后释放。历史列表和已读正文缓存 60 秒,授权项目列表 5 分钟,推荐问题 10 分钟,推荐生成失败缓存 30 秒。有效期内打开窗口和面板不重复请求。过期刷新保留已有内容,并发消费者共用请求,单个消费者关闭不取消共享请求。主动刷新及真实数据变更按需更新缓存,项目进入操作仍核验访问上下文。
推荐依据使用独立的近期会话页,历史搜索和翻页不改变输入。缓存摘要按活动 ID、标题、内容、状态及来源计算,单纯心跳时间变化不触发推理。生成新推荐时保留上一组问题。
推荐失败后,面板保持打开时在错误缓存到期后重试,同一轮最多请求三次;服务从离线恢复时立即重试失败项,也提供“重试推荐”入口。成功缓存继续复用,重试不改变输入草稿,模型目录尚未加载时不发送空模型请求。
Agent 面板、历史和主题窗口及正文阅读窗口共用选区复制处理,仅移除浏览器附加的末尾段落换行。正文内部段落、代码缩进、表格制表符与用户输入的有效换行保留;输入框沿用原生复制。
每个会话持有独立 Chat 实例、生成连接、草稿、引用、阅读位置和审批状态。切换历史或新建对话保留原会话后台生成;后台需要审批或回答时,通过历史入口提示返回处理。模型、项目头和凭据续期绑定原会话。后台浏览器动作返回 `SESSION_NOT_ACTIVE`,提示用户回到会话后重新请求;切换时取消原会话尚在执行的浏览器动作。切换业务项目由工作台统一处理,会话、主题及缓存按业务项目隔离。
头部在线状态由 Agent 公共 `/health` 的就绪结果独立决定,单次业务失败、提问等待、主动停止和新建对话不直接改为离线或在线。在线时每 15 秒探测,失败后按 1、2、4、8、15 秒退避,单次超时 5 秒;浏览器恢复联网、窗口聚焦或页面重新可见时立即重检。服务恢复后刷新初始化信息和当前会话的提问、输入队列,保留草稿与阅读位置。
已知会话的 Responses 流意外断开后,改用该会话的只读订阅恢复;订阅中断同样按 1 至 15 秒退避重连,合并权威消息尾部并保留已加载历史。重连不重发问题、不重启模型、不重做工具操作,也不将断流视为任务完成。权限失效、会话不存在、主动停止和所属工作台销毁时终止重连;切换到其他对话仍由原会话持有后台恢复连接。
## 4. 内容与状态
### 任务驱动的回答表达
按 Intelligent UI 的声明式组件路线增强当前对话:Agent 使用既有 Harness 与 `present_answer` 决定文字、指标、趋势、对照表、证据及补充表单的组合,前端负责本地交互和视觉层次。简单回答保留文字;说明和判断边界使用本地 shadcn/ui `Alert` 的图标、标题与正文组合,静态历史内容使用 `note` 语义,避免恢复会话时反复播报警告。
包含两类及以上可导航组件,且含表格、图表、补充表单或达到长内容标准时,回答上方出现“浏览回答”菜单,按实际组件显示类别和数量。选中项目在当前内容实例内滚动并交接键盘焦点;Escape 关闭菜单后回到触发按钮。导览沿用 `DropdownMenu`、`Button`、`Badge`,不切换页面、不重建图表或表单。只有一种可导航组件或内容较短时不增加导览。导航入口与内容类别摘要在窄屏保持紧凑,长标签自然换行。
图表保留折线、柱状和数据页签;范围筛选收进标题右侧的控件,所选非完整区间仍明确显示。数据点详情按需展开,点击图上数据点自动展开对应读数;键盘用户通过“查看数据点”及选择器完成同等操作。收起详情保留所选点。当前界面交互均只影响已加载数据;新查询与仿真仍走原业务工具。
消息标题区明确助手身份和真实生成状态。指标保留原始精度、单位与来源;证据继续区分事实和推断;资料表单通过 `CardHeader`、`CardContent` 划分说明和输入,提交是明确的主操作,失败保留填写内容。颜色、字体与表面沿用样式设计指南,交互状态不冒充业务状态。
本次无需新增 UI 协议、环境变量或数据库迁移。自由代码沙箱、跨会话保存控件状态和参数驱动的新数据查询属于后续能力;当前表单、筛选与选择在聊天和展开工作区之间移动时保留,历史恢复仍从已保存的回答结构重新建立控件。
后续的状态保存、压力历史探索与沙箱接入条件见 [可持续分析工作区设计](agent-answer-ui.md#下一阶段设计可持续分析工作区)。该部分是未实现的提案,不能作为当前功能清单。
`answer-ui@1` 仍由严格参数校验与本地注册组件驱动。已有的 `Stack`、`Section`、`Text`、`Metric`、`Table`、`Chart`、`Evidence`、`MapLocation`、`FollowUpForm` 使用新外观。聊天继续使用现有 Responses 事件;正式报告增加可选 `ui_blocks` 字段,复用相同的内容块协议。实现契约见 [本地交互式回答](agent-answer-ui.md)。
处理过程统一位于回复正文下方。生成中,文字与回答内容块在前,公开执行摘要、标记为过程的内容块和待办在后;最终答复到达或回复流结束后,过程收起为底部“查看处理过程”,入口位于语音播放左侧,没有 `final_answer` 标记的历史回复也遵循同一布局。最终答复明确引用的回答内容块留在主阅读流,其他记录进入处理过程。待回答问题、权限审批和失败状态在正文下方保持可见,不能因回复结束而被隐藏。这里借鉴 Reasoning 的折叠行为,呈现的数据是服务端已发布的过程信息,不额外生成思考文本,也不根据耗时推算完成比例。
最终答复到达后,正文、回复状态与语音/复制操作在同一次交接中切换,网络流的后续收尾不再改变这条回复的展示阶段。输入框仍根据真实执行状态接受引导或排队消息。过程复用生成时的容器和步骤实例,保留工具详情的展开状态;无论用户是否向上滚动或查看过工具详情,交接后默认收起过程并优先让结果正文可读;用户可通过“查看处理过程”重新展开。历史回放直接显示保存的结果,不重新播放交接。
补充问题打断后继续执行时,依据提问记录的 `message_id` 和补充回答的 `delivery.native_message_id` 将前后过程归到续接答复下方;连续补充时沿同一关联链顺序归组。没有正文的旧过程消息不再单独占位,原有正文和用户补充回答仍保留。尚未出现续接答复、历史分页缺少关联消息、仍有待回答问题或审批、关联之间出现新用户请求时,保留原位置。该归组仅影响展示,不改原始记录或消息标识。
生成中、补充后续接和历史恢复共用一个处理过程容器,边框、背景和内边距保持一致;各段执行记录合并为一份列表,不再嵌套另一张“执行进度”卡片。步骤显示身份包含来源消息,避免前后轮次的同名步骤互相覆盖;生成时统一控制整个过程的最近三项与展开全部,完成后由底部入口统一折叠。
已提交的回答以原生用户消息 ID 保存纯净文本和 `data-interaction_reply` 快照,首屏即可还原同一张“已回答”卡片并归组前后过程,不等待独立提问接口。该接口返回较新修订后更新投递状态和重试操作。旧历史由 Agent 按所属会话中已保存的投递 ID 补齐相同表示,不通过文本前缀猜测对应关系,也不改写历史文件。给模型的“用户提交的提问回复”协议前缀只用于推理输入。
提问等待和续接失败不禁用消息发送。生成中或存在未解决的提问/续接时,输入区提供“引导当前任务”和“排队处理”;消息通过既有 Responses 输入接口进入原生收件箱。没有宿主执行轮次时只保存输入,不自行启动模型,也不把消息当作提问表单的答案。读取续接状态时,服务端可以依据已消费的原生回答和已完成的原生输出恢复丢失的确认;仅有部分文字或原生状态不可用时保留未确认状态。若输入在入队前被明确告知当前轮次已结束,客户端刷新状态后作为新一轮发送;其他错误不自动重发。
证据类别明确区分查询记录、用户提供、分析推断和演练数据。地图定位的按钮结果以实际回调为准;资料表单提交后只表示发送消息,业务证据是否保存取决于后端实际结果。最终回复不等于后台调查任务完成。
## 5. 实现边界
保留 Vite 和 React SPA。通用 AI 展示组件位于 `src/shared/ai-elements/`,基础组件位于 `src/shared/ui/`;消息业务组合位于 `src/features/agent/components/`,结构化回答位于 `src/features/agent/answer-ui/`。
不引入 Next.js 路由、服务端组件或第二套聊天接口。地图控制器、会话存储和审批流程沿用已有实现。报告内容扩展同时进入 Agent 校验、Server 校验、现有报告 JSON 存储和 OpenAPI。组件按需加入本地源码,避免批量覆盖已定制的共享组件。AI Elements 负责展示组合,现有 Responses transport 负责消息传输,两者的职责分开。
## 6. 响应式与业务验收
桌面验证 1280px 及以上窗口,并检查面板宽度 400px、640px 的真实布局;手机验证 320px、375px。手机 Agent 默认打开全高抽屉,输入区进入正常布局,阅读内容不藏在悬浮输入框下面;抽屉仍可手动调低查看地图。混合内容在手机上使用单列,短指标按容器宽度保留双列。输入、发送、模型菜单、证据展开和滚动返回均需可操作。
本轮聚焦验收包括图表页签与方向键、证据键盘展开、历史恢复、表单提交、复制回复、流式结束和面板缩放。检查文字与背景对比度、减少动态效果和强制颜色模式。运行 lint、类型检查、相关单测、聚焦浏览器测试;依赖变化额外运行构建。浏览器演练数据必须标明来源,截图不代表真实业务核验。
当前文档描述本轮目标与实现约定,实际通过的检查和预览截图以交付记录为准。
## 7. 交互规则与范围
数据组件按展示与本地浏览组织:短内容不附加目录;单个证据或补充表单不叠加分组标题与固定提示;来源已在证据卡中显示时,报告外层只列出其余依据。调查脉络节点保留详情、缩放和地图定位,不提供节点追问按钮。
| 内容 | 本轮实现 | 数据与操作边界 |
| --- | --- | --- |
| 指标 | 值、单位、来源 | 不补造变化率、单位或精度 |
| 表格 | 搜索、三态排序 | 只处理当前数据;不提供勾选与引用操作 |
| 图表 | 折线 / 柱状 / 数据,序列显隐,加载区间,点击或键盘选点 | 最少保留一条序列;区间不触发查询或重算 |
| 证据 | 来源、类别、时间、编号,展开与类别筛选 | 正式报告使用已保存证据覆盖生成的摘要、来源和类别 |
| 地图 | 显式定位,地图对照或切换 | 使用真实定位结果与失败反馈 |
| 表单 | 空白初始值、必填校验、提交中禁用、失败保留 | 聊天表单主动发送;报告表单先带入对话,确认后发送 |
| 任务与报告对话 | 输入区引用卡片、详情、移除 | 保留专用任务、报告和补充表单入口;通用数据组件不产生引用 |
| 历史内容 | 固定报告事实可读,不支持的块显示摘要 | 降级不执行未知组件或事件 |
本轮未包含参数重算、新数据查询控件、附件上传、导出、报告版本差异比较。后续扩展时需要独立定义参数校验、数据来源和执行反馈;不能把本地筛选当作重新分析。后台任务完成、业务审批和证据写入继续以各自服务端状态为准。
## 8. 正式报告契约
`InvestigationReport.ui_blocks` 可省略;每项包含 `block: AnswerUiBlock` 和 `evidence_refs: string[]`。最多 8 块,总 UTF-8 JSON 不超过 400000 字节;单块完整序列化结果不超过 100000 个 JavaScript UTF-16 代码单元,最多 48 节点、深度 12。每块绑定至少一条报告证据,`Evidence` 节点只能引用该块的依据。Server 发布时再检查这些证据确属当前任务。
固定报告字段不变:阶段、结果、结论、边界、数据缺口、证据和建议仍独立校验。新字段通过原有报告 JSON 保存,跟随 revision 与 execution_generation 读取;请求幂等沿用原有机制。旧报告缺省为空,不因缺省字段而产生虚假的报告更新通知。无需数据库表或环境变量迁移。
组件参数唯一来源为前端 `catalog.ts`,导出到 Agent 与 Server;跨字段约束在三端分别验证。Agent `publish_task_report` 使用正式报告通道,聊天 `present_answer` 使用聊天通道。实现与生成命令见 [本地交互式回答](agent-answer-ui.md)。
任务业务审核统一从 header 的“状态和提醒”进入对应任务详情,由关联的负责节点或动作卡承接人工审核。会话只保留任务引用、讨论和消息,不注入固定的任务状态、人工事实或业务审核表单;调查详情继续负责草稿编辑、批准、拒绝及执行回执。工具执行权限审批和用户问题仍按会话交互协议处理。
## 调查报告与自由对话的分工
后台调查的固定问答放在右侧调查报告的“补充回答”中,支持选项、自定义文字、提交状态和历史回答。任务通知打开该报告;提交直接保存到原任务并接续调查,无需创建或发送左侧聊天消息。数据缺口旁的“回答当前调查问题”定位到报告内待答表单。
左侧 Agent 保留自由讨论、追问和进一步分析。“Agent 协作”和“讨论此缺口”是明确的讨论入口;固定任务回答不经过这些入口转发。
+375
View File
@@ -0,0 +1,375 @@
# Intelligent UI 交互状态补齐设计
> 2026-10-30 产品决定:数据组件仅用于展示与本地浏览,已移除表格勾选、分析内容篮及组件追问;专用地图定位和补充资料表单保留。本文分析篮、行选择和引用操作的方案属于历史设计,不再作为当前实施目标。阅读位置、表单草稿及宿主提问的独立设计仍可参考,当前行为以 [本地交互式回答](agent-answer-ui.md) 为准。
历史设计状态:2026-10-27 设计稿;2026-10-28 第 11 节宿主提问已接入工作区代码,其余补齐项仍待实现。当前代码进度见 [本地交互式回答](agent-answer-ui.md)。本设计补齐阅读位置、分析篮和正式报告的私人交互状态,不改变模型可生成的 `answer-ui@1` 组件协议。第 11 节单独处理 question 的执行生命周期。
## 1. 目标与方案
用户刷新后,再次打开同一回答或同一版报告,可以继续阅读、筛选和填写资料。恢复只改变当前用户的界面,不发送消息、不提交表单、不调用业务工具、不定位地图,也不自动打开窗口。
推荐保留已实现的聊天控件状态接口,新增阅读与分析篮的补充记录;正式报告的状态由 Server 按当前读者保存。三种记录独立比较版本,避免滚动保存与表单输入、选行互相冲突。前端继续复用受控 store 和现有保存协调器,只由来源适配器决定请求 Agent 还是 Server。
最小方案是仅增加会话内存缓存,但刷新后仍会丢失,不能满足目标。把全部状态塞入原接口会破坏旧客户端的严格校验,也会让分析篮挤占控件的 32 KiB 限额,因此采用补充记录。正式报告不能借用 `source_session_id` 保存:它指向发布报告的执行会话,报告读者未必拥有这个会话。
新增服务、账号、密钥和环境变量均为零;正式报告需要在已有项目 BizDB 增加一张私人状态表。预计涉及三个仓库、超过 8 个实现文件,按第 10 节拆成可独立交付的两批。
```text
聊天最终回答 -> Agent 来源适配器 -> 已授权会话 / 控件记录 + 补充记录
^
|
读取/编辑 -> 前端状态协调器 -> 受控组件、阅读位置、分析篮
|
v
指定版本报告 -> Workbench 来源适配器 -> Server 报告权限 / 当前读者状态
用户主动“带入对话” -> 现有输入区 -> 用户确认发送 -> 既有 Agent 流程
```
基础能力沿用 [json-render 的运行时状态支持](https://json-render.dev/docs/data-binding) 和 [React 的外部 store 订阅](https://react.dev/reference/react/useSyncExternalStore)。阅读容器尺寸变化使用 [ResizeObserver](https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver) 观测;这些机制不替代宿主的权限、持久化和版本校验。实现以仓库当前安装版本为准,不因本设计升级依赖。
## 2. 当前依据与状态分工
| 当前实现 | 补齐方式 |
| --- | --- |
| `answer-view-state@1` 保存图表、表格、表单、证据状态 | 保留接口、32 KiB 限额和迁移规则;复用其保存/恢复机制 |
| `ExpandableReading` 用 `useId()` 标识实例;阅读偏移放在 DOM dataset | 注入业务来源身份;只保存可序列化的阅读位置,DOM、host、focus 回调留在内存 |
| Markdown 表格的行内和放大视图是两份 DOM,图示可移动同一个 host | 按阅读面分别记录位置,不假设搬动 DOM 等于持久化 |
| `AnswerUiView` 的分析篮只存 `{title,text}`,意图由 Tray 的 `useState` 保存 | 增加来源、选择描述和摘要;篮与意图一起受控保存 |
| `InvestigationReportBlocks` 接收报告快照,并用任务证据覆盖 Evidence 展示 | 按报告版本及当前读者加载状态;两端核对实际渲染内容摘要 |
| 正式报告属于项目任务,读取使用 `operational_task.view` | 私人状态沿用报告读取权限,不要求读者拥有发布会话,不写回正式报告 |
| 记录 | 持久化内容 | 保持临时的内容 |
| --- | --- | --- |
| controls,按块 | 现有节点控件状态和证据类别筛选 | 请求中的 loading/error、悬停、菜单和下拉框开关 |
| reader,按文档 | 阅读面的位置、锚点、局部偏移和内容摘要 | 是否打开弹窗、当前焦点、地图相机、窗口尺寸、DOM 引用 |
| basket,按块 | 有序选择项、来源描述、选取时文本快照、分析意图 | 正在带入对话、临时提示、浏览器文本选区 |
说明:分析篮仍以一个回答块为边界,本次不扩展为跨消息、跨报告的全局收藏。证据大分区、范围工具栏的折叠开关沿用当前内存行为;它们不决定所选数据。Mermaid 平移/缩放也只在当前实例内保留,重新打开时按可用空间适配,不保存会随图形重新布局失效的像素变换。
## 3. 身份与版本
| 来源 | 文档身份 | 块身份 | 权威校验 |
| --- | --- | --- | --- |
| 聊天 | 当前主体、个人/项目范围、sessionId、assistantMessageId | 文档身份 + blockId | Agent 校验会话归属、已保存的助手消息及最终回答引用;旧版没有 final 的记录沿用既有兼容规则 |
| 正式报告 | 当前 user_id、project_id、task_id、report_revision | 文档身份 + blockId | Server 校验当前成员身份、`operational_task.view` 和指定报告是否存在 |
`nodeId` 来自验证后的 `spec.elements` 键;不得使用标题、数组当前序号、React `useId()` 或 DOM selector 作为业务身份。客户端不能指定状态所有者,主体和项目必须来自服务端认证上下文。
报告的 `revision` 在任务内唯一,`execution_generation` 由服务端从报告推导并回传,不作为另一个客户端命名空间。历史 `null` 保留为 `null`,不能替换为 0 或任务当前轮次。文档与块的 `state_revision` 是私人交互版本,不能与报告 revision 混用。
打开任务仍默认查看当前报告,不自动恢复为上次选中的历史版本。用户主动选择某个版本后才恢复该版本的状态。新报告使用新的身份和空状态,不自动复制旧版表单或分析篮;旧版记录保留供用户回看。放大窗口保留旧版内容时,状态写入也绑定当时的旧版,直到用户点击“查看最新内容”。
最容易失效的前提是“相同 blockId 就是相同数据”。本设计用内容摘要、节点类型和选择描述复核,无法唯一匹配时保留可核对的草稿并清理无效选择,不将旧数组下标套到新数据。
## 4. 记录与接口
### 4.1 保留现有接口,新增补充接口
| 所属服务 | 接口 | 状态范围 |
| --- | --- | --- |
| Agent,已有 | `GET/PUT /api/v1/session/:sessionId/ui-state` | 聊天 controls,保持原 `answer-view-state@1` 协议 |
| Agent,拟新增 | `GET/PUT /api/v1/session/:sessionId/interaction-state` | 聊天 reader 或 basket;以 message_id、kind 和 basket 所需的 block_id 定位 |
| Server,拟新增 | `GET/PUT /api/v1/operational-tasks/:taskId/reports/:reportRevision/interaction-state` | 正式报告 controls、reader 或 basket;controls/basket 需要 block_id |
GET 的 kind 只有 `reader`、`basket`,Server 额外允许 `controls`。reader 属于整个文档,不接受 block_id;其内部阅读面可以引用块。GET 无记录返回对应空 payload、state_revision 0 和当前内容摘要,不写入空记录。未知 kind、无效字段或不存在的块返回 400/404,不隐式建立来源。
GET 选择器放在 query,PUT 放在 body;Agent 两种方法均要求 message_id,Server 报告身份只取 URL。PUT 另要求 `version="ui-interaction-state@1"`。两端错误在前端适配器内统一为 code、message、current:Agent 沿用顶层 code/detail,Server 沿用现有 detail envelope,不让通用组件处理两套响应形状。所有响应使用 private/no-store。
新接口的记录版本为 `ui-interaction-state@1`。字段固定如下;不接受任意对象透传。
| 字段 | 规则 |
| --- | --- |
| `source` | 只出现在响应中,返回服务端确认的聊天或报告身份;不返回用户 token、宿主路径 |
| `kind`、`block_id` | 标识记录种类及块;reader 的 block_id 不存在 |
| `state_revision` | 每个记录独立的非负整数,只出现在响应中 |
| `source_digest` | 服务端规范化内容的 SHA-256;PUT 原样带回,用于拒绝过期内容上的保存 |
| `payload` | 由 kind 选择严格 schema,字段见第 5、6 节;report controls 使用已有 nodes/block 的允许字段与迁移规则 |
| `updated_at` | 服务端写入时间;空记录为 null,不用客户端时间决定覆盖顺序 |
| `item_status` | 仅 basket 响应包含,按 item_id 返回当前有效性与原因;不接受客户端写入 |
| `expected_revision`、`request_id` | 只用于 PUT;版本比较和最近请求重试沿用现有规则 |
选择器对应的身份摘要、version、revision 和请求标识均受限长与整数范围校验。source_digest 为 64 位小写十六进制;request_id 为 1 至 128 字符;message_id 为 1 至 200 字符;block_id 沿用原协议。state_revision/expected_revision 使用 JavaScript 安全整数范围,禁止负数或溢出。
`source_digest` 的材料:聊天 reader 为已发布报告文字与引用块,basket 为所在块的实际 spec;报告 reader 为指定版本的报告正文及其可见证据投影,controls/basket 为对应块的实际渲染 spec。规范化 JSON 对对象键排序,数组顺序不变,摘要算法跨语言使用同一组固定测试样例。摘要是过期检查依据,不是客户端提交文字的真实性证明。
### 4.2 正式报告的 Evidence 投影
报告原 spec 与实际显示的 Evidence 可能不同:当前实现从任务证据补充摘要、来源、时间、类别,找不到证据时显示提示文本。Server 与前端必须采用相同投影规则,控件验证及摘要计算以投影后的 spec 为准。
Server 状态读取先按现有报告/证据访问规则取得来源,计算投影及 source_digest;前端对已经加载的报告与证据执行同一规则并计算摘要。两者不一致时,不把旧状态应用到当前节点:对指定报告和任务证据做一次有界刷新,再核对摘要;仍不一致则显示“内容已更新,交互状态暂未恢复”,允许用户重试,禁止无限刷新。无需在状态响应中再复制整份报告或原始图表数据。
PUT 在事务中重读报告和证据,投影变化返回 409 `UI_INTERACTION_SOURCE_CHANGED`,并返回当前记录和摘要。前端先更新来源,再迁移合法控件;无权访问的证据不以篮子快照重新显示。此投影规则需要前后端共用测试样例,不能各自猜测字段映射。
### 4.3 存储与容量
聊天补充记录放在宿主 `chat/answer-interaction-state.json`,加入 `SessionWorkspaceStore` 允许列表,复用同一队列、所有权校验、删除标记及原子写入。已有 controls 文件保持不变,旧客户端读写不会抹掉新状态。新文件每个 document reader、每个 block basket 独立版本,文件总量最多 1 MiB,包含回执;与已有 controls 文件合计最多 2 MiB/会话。
正式报告新增项目 BizDB 表 `workbench.report_user_view_states`,每个 `(project_id,user_id,task_id,report_revision)` 一行,JSONB document 内分别保存 controls、reader、baskets 和最近回执。每个子记录有独立 state_revision;行锁只用于版本比较、容量检查和原子替换,不把滚动和表单合并成一个逻辑版本。报告外键 `(project_id,task_id,report_revision)` 使用物理删除级联;user_id 来自 `ProjectContext`,不建立跨数据库外键。
首次写入采用插入空行且忽略唯一键冲突,再锁定同一私人状态行,避免两个 revision 0 请求同时成功。事务失败回滚空行和状态修改;报告删除由外键与事务约束阻止迟到写入复活。状态表不是报告事实表,保存私人状态只要求报告读权限,不借此授予任务写入或审批权限。
拟新增迁移 `next-tjwater-server/resources/sql/026_report_user_view_states.sql`,沿用项目 BizDB 显式迁移流程。当前最高编号为 025,实施时若编号已占用,顺延编号。接口不执行建表;未迁移的项目返回安全的 503,报告仍可阅读,草稿留在当前内存。
| 项目 | 限额 |
| --- | --- |
| controls payload | 32 KiB UTF-8/块,沿用现有节点数量和字段限制 |
| reader payload | 8 KiB UTF-8/文档,最多 16 个阅读面 |
| basket payload | 64 KiB UTF-8/块,最多 8 项;正文组合不超过现有 8000 个 UTF-16 代码单元;分析意图最多 800 个 UTF-16 代码单元 |
| 正式报告私人状态行 | 1 MiB,计入所有子记录和回执 |
| 补充记录重试回执 | 每个聊天补充文件或报告私人状态行,最近 32 条且最多 128 KiB;过期请求仍受旧 expected_revision 阻止重放 |
大小检查包括标识与元数据的序列化体积,不截断表单或选择内容来勉强保存。超限返回 413,保留当前草稿,提示先减少分析篮内容或清除不再需要的记录。业务限制 8000/800 由三端按相同 UTF-16 计数规则校验,不能用 Python 字符数直接替代。发送消息时仍检查问题、意图、引用及来源说明的完整文本是否超过现有 10000 限额。
不按每次滚动追加历史;当前快照覆盖、回执有界。记录数量随实际访问的用户/报告组合增长,使用上述复合主键直接读写,不扫描全部用户状态;本版本不增加自动 TTL,避免无提示删除草稿。
## 5. 阅读位置
reader payload 为 `positions` 和 `recent_reader_keys`,前者按宿主生成的 readerKey 保存位置,后者是最近使用顺序。两者最多 16 项且键集合一致;位置键、锚点 id 最多 200 个字符,不接受 DOM selector 或脚本。每项位置字段如下。
| 字段 | 含义 |
| --- | --- |
| `content_digest` | 该阅读面实际内容的摘要;用于判断是否可复用整体滚动比例 |
| `anchor` | 可空的 `{kind,id,occurrence}`;kind 为 section、node、markdown,id 来自稳定业务键或规范化 Markdown 块摘要 |
| `anchor_offset_ratio` | 锚点内部偏移,有限数值,范围 0 到 1 |
| `scroll_y_ratio`、`scroll_x_ratio` | 容器可滚动距离的比例,范围 0 到 1;无可滚动距离时为 0 |
readerKey 只由宿主注册:`workspace`、`report-result`、原生 `blockId/nodeId` 对应阅读面,以及 Markdown 内容块摘要派生的表格/图示阅读面。纯文本最终回答也可建立 document reader,无须伪造 answer-ui 块。标题或“第 n 个表”不是跨内容更新的稳定键;相同内容重复出现时 occurrence 只在摘要相同的文档内使用。
这里只保存版本明确的内容。当前调查进展、实时任务时间线、审批卡和报告版本选择器仍属于实时任务界面,不绑定到某个报告 revision 的阅读状态。用户输入、审批焦点和地图位置均不通过 reader 恢复。
恢复流程:
1. 用户主动打开对应阅读面,绑定不可变的 source 身份并订阅状态。尚未加载历史消息/报告时不为了恢复位置自动翻完全部历史,也不自动切换会话或报告版本。
2. 内容挂载、控件恢复和必要字体准备完成后,用连续两帧相同尺寸判断可定位;最多等待 1500ms。`ResizeObserver` 仅用于这次定位,不能持续把用户拉回旧位置。
3. 优先定位仍唯一存在的锚点,再恢复锚点内部偏移。没有锚点但 content_digest 相同,则使用整体滚动比例;内容已变化且锚点无法对应,回到本阅读面起点,提示“内容已变化,原阅读位置无法恢复”。
4. 比例始终按当前实际滚动范围计算并夹紧;窄屏和宽屏互切不能直接复用旧像素 scrollTop。Markdown 行内与放大表格使用不同 readerKey,横向位置也分别记录。
5. 每次主动打开最多执行一次自动定位。等待期间出现用户滚轮、触摸、指针按下、滚动键、文本选择、编辑或内容导航,则取消自动定位;迟到 GET 只进入缓存,不移动当前视口。需要回到上次位置时由用户点击入口。
阅读保存使用 1000ms 防抖,连续滚动每 5 秒最多提交一次;关闭阅读面或切换来源时保存最后位置。位置未变化不发送;程序恢复产生的 scroll 事件不标记为用户编辑,不反向触发保存循环。最多 16 个位置,超出时只淘汰最久未使用的阅读位置,保留当前阅读面;分析篮和表单不参与此淘汰。
reader 冲突不弹出阻断窗口:保留当前视口,接收远端的新 revision 供下一次真实用户滚动保存,显示轻量“阅读位置未同步”状态;不自动覆盖远端,也不因远端更新跳动当前页面。下次用户操作只更新对应位置,合并远端其他阅读面的位置和最近使用顺序,不能用整个旧 positions 覆盖它们。网络失败可随下一次用户滚动重试或由用户手动重试。
## 6. 分析篮与表单草稿
basket payload 为同一份 `{items,intent}`。items 是有序数组,新增、移除、清空和意图编辑由一份受控状态管理;不拆成八个各自保存的项目。
| 选择项字段 | 规则 |
| --- | --- |
| `item_id` | 本地生成的稳定 UUID,保存与重排时保持;不用于权限证明 |
| `node_id`、`selection_kind` | 必须对应来源中的真实节点;首批 kind 为 metric、table_rows、chart_point、chart_range |
| `selector` | table_rows 为原始行索引及数据摘要;chart 为点/区间索引、对应标签、可见序列索引与名称;metric 不带行索引 |
| `source_digest` | 选取时所在块的有效内容摘要,由已读取来源取得 |
| `title`、`snapshot_text` | 选取时的纯文本显示快照,title 最多 200 个 UTF-16 代码单元;正文计入组合总限额 |
服务端校验节点类型、索引上限和选择描述,并校验来源摘要;快照文本是用户引用内容,不提升为事实证据,不执行其中指令。它是“不复制原始数据”原则的有界例外,只保存用户明确选取的文本,不保存整份时序数据。正式报告的 evidence_refs 及报告身份由宿主从块与报告补充,不信任客户端伪造来源。
去重依据是节点、选择描述和选取时内容摘要;不同节点即使文本相同也可分别选取。每个选项保留当时的文本,不随筛选、排序或数据更新悄悄重算。服务器计算恢复状态为 valid、stale 或 unavailable,客户端不能提交该标记:
- 内容仍一致为 valid,正常使用。
- 节点仍存在但数据/结构摘要变化为 stale,显示“内容已变化,此项为先前快照”;保留快照供核对,整篮“带入对话”暂不可用,须移除该项或从当前内容重新选择。不会自动迁移篮中行索引。
- 来源节点或证据已不可用时为 unavailable,停止返回相关快照文本,只保留可移除的占位;不得通过篮子绕过当前来源访问规则。整个文档失去权限时按第 8 节处理。
新增选择只接受当前 source_digest;已保存的 stale 项可以原样保留或移除,不能借保存意图修改它的快照/来源。兼容校验先按 item_id 对比已存项,再检查新增项。无法自动迁移时不将 stale 项冒充当前数据。
GET 响应另有 `item_status`,按 item_id 返回状态及简短原因,不混入可写 payload。unavailable 项以相同 item_id 和来源标识返回,title/snapshot_text 使用固定不可用提示;PUT 只能保留这个经过屏蔽的占位或删除它。幂等重试返回回执前也要重新检查当前来源可用性并屏蔽不可用文本,不能直接回放旧的含文本响应。回执确认原写入版本,不构成允许再次显示旧快照的授权。
items 与 intent 分别记录 dirty 路径;清空动作原子设置 `items=[]`、`intent=""`,即使值为空也保留 dirty 标记,迟到 GET 不得把旧项目重新并入。清空保存期间又新增内容时,旧回执只能确认它发送时对应的修改序号,新内容继续保留并按新 revision 保存。
“带入对话”只复制捕获的篮内容和意图到现有输入区,成功后仍保留篮子。异步回调同时捕获 source、目标 session 和当前作用域代次;用户已切换项目/会话时,旧回调不得填入新的输入区。实际发送继续由用户确认,失败不清空篮或表单。
表单草稿沿用现有控件存储。普通聊天发送成功后,只清除与该次发送快照仍相同的字段;发送期间新输入的字段保留。正式报告的表单默认带入对话,未获得实际发送确认前不清草稿。恢复只填充字段,不调用提交回调,不把报告表单写入正式证据。
## 7. 保存与冲突规则
共同流程为读取、合并本地编辑、待保存、保存中、已保存;异常分为未保存、冲突、来源变化和失去访问权限。展示不要求网络先成功,写入必须等已知 revision 和来源摘要。控件及分析篮继续使用 500ms 防抖,读取失败只保留一次首次编辑触发的补读,其余由显式重试触发,不轮询。
| 情况 | 处理 |
| --- | --- |
| GET 比用户编辑晚到 | 按 dirty 字段合并;items 是一个整体,不做数组 union;清空和删除也不能被恢复覆盖 |
| PUT 尚未返回又发生编辑 | 保留更新的 changeSeq;回执只清除已确认的旧 dirty 字段,再保存后续版本 |
| 响应丢失,无法判断写入是否成功 | 先以原 request_id 和原始 payload 重试;确认后再发后续编辑 |
| 409 `UI_INTERACTION_STATE_CONFLICT` | controls/basket 保留本地草稿,停止自动重试;允许“保留本地并重新保存”或确认后“加载远端” |
| 409 `UI_INTERACTION_SOURCE_CHANGED` | 先有界刷新来源并兼容迁移;不可直接拿新摘要覆盖旧索引;stale 篮项目按第 6 节处理 |
| 同 request_id 携带不同 payload | 409 `UI_INTERACTION_REQUEST_CONFLICT`;视为客户端错误,保留草稿,不能自动换 ID 继续重放 |
| 413 或服务不可用 | 保留内存草稿,说明未保存;不切片、截断或循环提交 |
| 服务端确认目标回答正在生成或等待落盘 | 返回 503 `UI_INTERACTION_SOURCE_NOT_READY`,保留草稿;首次用户编辑可触发一次补读,之后显式重试,不等同于来源被删除;仅会话存在不能证明回答正在落盘,不存在的来源仍返回 404 |
| 临时 401 | 沿用现有认证刷新机制;不能因此扩大权限或换用其他主体保存 |
来源摘要冲突必须先解决来源变化,再决定是否覆盖交互版本;“保留本地”不是绕过数据校验。不同浏览器不增加 WebSocket 或后台同步:打开来源时读取,保存时发现冲突。自动读取到较新状态也不能改动用户正在操作的视口或表单。
状态提示按记录聚合:“已保存”表示本界面当前脏记录全部已确认;控件已保存而篮子未保存时明确标出分析篮。纯阅读位置同步异常只在阅读面显示轻量状态,不让每次滚动占据对话通知区。
“加载远端”的确认绑定当前记录和确认时的 changeSeq;确认后又出现新的本地输入,旧确认结果不得覆盖它,应保留新输入并重新呈现冲突选择。
## 8. 清理、权限与删除
- 切换会话时,未失败的待保存写入仍使用捕获的旧 source;新来源创建独立订阅。组件卸载不立即丢掉同一认证作用域内的草稿。
- 登出、切换主体或项目时,取消未发送计时器、移除旧订阅并清理对应缓存。已发出的请求不能撤销既成写入,但回执不得进入新的作用域。
- 401 经认证处理确认失效、403 或来源不存在的 404,关闭来源恢复通道,清除该来源缓存中的正文快照和草稿,不在新用户界面显示;不能将这些响应当普通离线错误长期保留敏感快照。后续重新获得访问权限时重新授权读取。
- 显式“清空”使用带 expected_revision 的空 payload 写入,并增加 state_revision;保留空记录和近期回执,不删成 revision 0,防止迟到保存使已清内容复活。表单、篮和 reader 各自清空,不连带删除业务报告。
- 聊天删除沿用宿主删除标记与队列,清除两个状态文件;聊天分叉不复制私人控件、篮和阅读位置。
- 正式报告物理删除时由外键级联删除私人状态。任务取消、源撤回或进入新轮次不等于报告删除;只要旧报告仍按现有规则可读,其私人状态继续按旧 revision 保留。
- 每次 GET/PUT 重新检查报告权限。成员撤权对后续请求生效;已经通过鉴权的在途请求可能按当时权限完成,不承诺跨 metadata 与 BizDB 事务的即时强撤回。错误响应不能返回其他用户状态或证据快照。
## 9. 验收矩阵
| 场景 | 必须满足的结果 |
| --- | --- |
| 刷新后主动打开同一回答/报告 | 恢复控件、篮意图和阅读位置;不自动打开弹窗、定位地图或发送消息 |
| 桌面与 320px 窄屏互换 | 锚点/比例按新布局恢复,表格横纵滚动均有效,无越界和全页横向溢出 |
| 阅读恢复晚到、字体/图表延迟渲染 | 用户未操作时最多定位一次;用户已滚动或导航后不抢位置;1500ms 后不无限等待 |
| 同一 Markdown 内有重复标题/表格 | 同内容版本可按 occurrence 恢复;内容改变后匹配不唯一只清该位置 |
| 篮清空后 GET 或旧 PUT 回来 | 已清项目不复活,清空之后的新编辑不丢失 |
| 数据换序、重复标签、列变化或 Evidence 消失 | 控件执行明确迁移;篮快照标为 stale/unavailable,不静默换成别的数据 |
| 报告当前版变成下一版 | 旧阅读窗仍向旧版保存;用户选择新版本才加载其独立状态 |
| 两位有报告权限的用户 | 可分别保存同一报告,不能互读或互相冲突;均不要求拥有 source_session_id |
| 同一用户两窗口修改 | 控件/篮出现明确冲突;阅读位置不跳动;原请求重试不增加重复版本 |
| 状态保存中切换用户、项目或来源 | 旧响应和带入对话回调不污染新作用域;失去权限不返回缓存快照 |
| 32/64 KiB 边界、emoji/CJK、文件或报告行满额 | 字节和 UTF-16 限制一致,失败不截断、不丢当前草稿 |
| 会话删除、报告删除、空记录清除竞态 | 不复活删除对象,不把空记录误当从未保存 |
| Server 项目未迁移或接口回退 | 保持可读和当前内存交互,明确未保存;旧版聊天 controls 接口继续工作 |
| 回答正在落盘与来源已删除 | 前者保留草稿并有界重试,后者清理来源缓存;不能将普通 404 无限转成等待 |
| reduced motion、键盘打开和关闭 | 定位不增加动画;恢复不抢焦点,关闭回到触发按钮 |
单元测试覆盖状态归一化、dirty/tombstone、字节预算和迁移;浏览器使用有意延迟、响应丢失和冲突的模拟接口验证行为;Server/Agent 聚焦测试验证真实存储事务、权限和删除。最后以隔离 Agent、已授权项目和真实报告完成保存读回,明确区分模拟接口与真实服务结果。
## 10. 实施顺序与文件交接
第一批补齐聊天 reader/basket,可独立上线,不等待报告表迁移。
| 仓库 | 修改位置 | 工作 |
| --- | --- | --- |
| frontend | `src/features/agent/session-state/`、`src/features/agent/api/` | 增加补充记录 schema 与来源适配器,复用现有队列/dirty/retry;保持旧 controls 接口 |
| frontend | `answer-ui/answer-selection.ts`、`answer-selection-tray.tsx`、`answer-ui-interactions.tsx`、`answer-ui-view.tsx` | 选择描述、稳定项目身份、受控 items/intent、快照有效性及带入对话保护 |
| frontend | `src/shared/ui/reading-workspace-context.ts`、`reading-workspace.tsx`、`src/shared/ai-elements/markdown-reading.tsx` | 只接收通用 source key 和位置读写回调;锚点、容器测量与恢复取消,不导入业务模块 |
| Agent | `src/sessions/workspace-store.ts`;拟新增 `src/sessions/answer-interaction-state-store.ts`、`src/routes/answer-interaction-state-routes.ts`;`src/routes/chat.ts`、`src/server.ts` | 受控补充文件与新接口、来源校验、CAS、容量和删除 |
第二批接入正式报告,复用第一批组件和补充记录协议。
| 仓库 | 修改位置 | 工作 |
| --- | --- | --- |
| Server | 拟新增 `resources/sql/026_report_user_view_states.sql` | 项目 BizDB 私人状态表及报告删除外键 |
| Server | 拟新增 `app/domain/schemas/report_view_state.py`、`app/services/report_view_states.py`、`app/infra/db/postgresql/report_view_states.py`;`app/api/v1/endpoints/operational_tasks.py` | 状态模型、Evidence 投影、读者权限、行锁、独立子记录版本和错误契约 |
| frontend | `src/features/workbench/api/operational-task-client.ts`;拟新增 `api/report-view-state-client.ts` | 读取指定报告版本、通过现有项目请求头访问私人状态接口,解析 Server 错误 envelope |
| frontend | `components/investigation-report-blocks.tsx`、`investigation-task-report.tsx`、`investigation-expand-card.tsx` | 显式报告身份、冻结阅读版本对应的状态绑定、投影摘要核对和只读者状态接线 |
Workbench 通过 Agent 公共 API 注入保存适配器,Agent 组件不能反向导入 Workbench;shared 阅读组件只处理通用锚点与滚动,不接触 token、taskId 或业务请求。
验证命令沿用各仓库 AGENTS:前端 `pnpm lint`、`pnpm typecheck`、`pnpm test`,新增 `tests/browser/agent-interaction-state.e2e.ts` 并回归既有阅读/状态用例;Agent `bun run check`,新增 `tests/sessions/answerInteractionState.test.ts`、`tests/routes/answerInteractionStateRoutes.test.ts`;Server 新增 `tests/unit/test_report_view_states.py`、`tests/api/test_report_view_states.py`,覆盖本节矩阵的存储与权限分支。新测试文件在实现时创建,本设计不将它们标为已存在或已通过。
发布顺序:聊天先 Agent 补充接口、后前端;报告先对目标项目备份并应用迁移,再发布 Server 和前端。迁移必须包含可重复执行与旧报告外键校验,不能对未授权项目批量执行。回退前端保留两类状态文件与报告状态表;回退 Server 关闭新接口即可,不需要删除数据。每批完成后记录实际提交、迁移项目、服务版本和读回结果,不以本地测试代替发布验收。
## 11. 宿主管理提问与回复
2026-10-28 实施记录:已接入宿主存储、工具桥与门禁、问题卡、草稿保存、Responses 续跑及历史原生 question 核对。当前实现通过独立列表恢复问题,明确重试继续;尚未将全部历史请求嵌入会话详情的分页投影。已使用隔离原生实例验证固定输入 ID 去重与重启持久化,未调用付费模型验证实际工具选择和完整推理续跑。下述契约保留为设计与验收依据;未提交、未部署。
原生验证发现:已回答或取消的 form 在重启后可能返回不存在。因此兼容入口优先保留宿主已知终态,未知且原生缺失的历史卡片显示失效;不能仅凭 form 缺失推断用户已经回答。新协议不依赖原生 form 保持等待状态。
本次验证:Agent 静态检查及 67 项聚焦测试通过,追加边界修改后对应 13 项回归通过;前端 lint、typecheck、125 个文件共 655 项测试及生产构建通过。桌面和 320px 浏览器场景通过,一次重复运行在打开面板前超时,独立重跑通过。构建使用 Node 24.13.0,低于 package.json 要求的 24.22.1,发布前还需在规定 Node 版本复验。隔离原生检查不调用模型,不替代真实授权项目完整推理验收。
### 11.1 决策与当前证据
用户允许在必要时自行设计提问机制,不依赖 OpenCode 内置 question。推荐新增受控工具 `ask_user`:模型提出问题,Agent 宿主保存请求并结束当前模型轮次;用户提交答案后,宿主在原会话启动一次有身份绑定的续跑。等待人的时间不占用一个原生 question Promise,问题是否可回答也不由前端卡片判断。
这不是替换推理引擎。继续使用 OpenCode 执行模型和既有工具,但提问协议、草稿、答案、取消及投递记录由宿主管理。正式报告 FollowUpForm 仍是补充资料入口,不自动变成阻塞提问;Shell/MCP 权限审批继续走原有审批通道,不由 ask_user 代替。
当前代码依据:
- 前端 `QuestionRequestCard` 的选项草稿在组件 `useState` 中;切换后重建组件会重新初始化草稿。
- Agent 的 `chatInteractionRoutes.ts` 要求内存 `activeRuns` 和 `pendingQuestions` 存在;`runtime/opencode.ts` 随后读取并回复原生 form。历史卡片存在不能证明原生请求仍有效。
- 当前切换会话不直接终止旧运行,尚未复现用户此前的错误,因此不能将历史故障确定归因为切换动作。
- `ResponseInputTracker` 本身是内存 Map,不能直接当作持久化队列。可复用的是 runtime 中固定消息 ID、inbox 与 message 读回的投递核对,以及 `chatStream.ts` 在工具完成后中断并等待 idle 的已有轮次结束机制。
最小替代方案是补原生 form 状态核对与选项缓存,改动较少,但恢复仍受原生请求生命周期约束。选择宿主方案是为了独立保存等待状态,不再为每次运行状态丢失拼接恢复逻辑。官方支持[自定义工具及独立工具名称](https://opencode.ai/docs/custom-tools/);本站示例 API 与当前仓库 OpenCode 2 插件 API 不完全相同,实施使用本地 `.opencode/tool.ts` 和插件注册方式,不照搬官网导入路径。
### 11.2 请求与草稿分离
首批仅用于 `ordinary_chat` 和 `task_collaboration`,一个会话最多一个未解决的提问组,每组最多 3 个问题。后台 `task_execution` 不等待浏览器,继续使用缺失资料报告及人工证据流程。工具和浏览器都不能指定所有者、项目或目标续跑会话。
新增宿主记录协议 `agent-interaction-request@1`,身份为已授权 actor/project/session + 宿主生成的 interaction_id。绑定原始消息、宿主 turn_id、工具 call_id;用 session/turn/call 唯一键去重创建,原生 form_id 不参与新协议。
| 记录 | 字段和规则 |
| --- | --- |
| 提问定义 | 不可变的 questions;每题包含稳定 question_id、标题、正文、选项 id/label、single/multiple、allow_custom、required;每题最多 12 个选项 |
| 请求状态 | revision、pending/answered/skipped/cancelled/invalidated、创建时间、解决时间;已回答答案不可覆盖,修正需发新消息 |
| 草稿 | 独立 draft_revision、各题 selected_option_ids/custom_text;请求待回答时可保存;迟到草稿回执不能恢复终态请求 |
| 用户答案 | 按 question_id 提交选项 ID 和自定义文字;宿主按原始定义补齐标签,拒绝不存在的选项、重复 ID 和非法多选 |
| 续跑记录 | 稳定 native_message_id、queued/dispatching/delivered/blocked/cancelled、错误码和关联 response_id;与答案在同一次原子写入中建立 |
所有 schema 严格校验。标识最多 128 字符;标题、问题正文、选项标签分别最多 200、2000、200 个 UTF-16 代码单元;每题自定义输入最多 2000,问题或答案的完整文本各最多 10000。定义最多 32 KiB,答案和草稿各最多 16 KiB UTF-8。默认选中不是已提交,也不能触发自动回复。
新增 `chat/interaction-requests.json`,复用宿主所有权、原子替换、串行更新及删除标记,最多 2 MiB、1000 个请求,先到限额者生效;连同第 4 节两类状态文件,交互文件预算最多 4 MiB/会话。已解决记录保留用于重试和审计,不自动淘汰未回答项;满额拒绝新提问并返回普通文字说明,不截断已有答案。首次实现沿用单宿主进程拥有会话的部署边界,不能把进程内队列宣传为跨实例锁。
### 11.3 提问、等待与续跑
```text
模型 ask_user -> 可信工具桥 -> 宿主原子保存请求 -> 问题卡片
|
本轮结束,等待回答
|
用户提交 -> 宿主保存答案和投递记录 -> 既有运行协调器 -> OpenCode 原会话续跑
^ |
+--- 按固定消息 ID 核对回执 ---+
```
1. 工具桥复用现有内部桥认证及运行会话上下文,session/turn/call 从可信上下文获得,模型参数只包含问题定义。严格注册工具 schema,拒绝模型传入身份、URL、命令或恢复回调。首次发布前确认没有其他正在执行的工具;同组并行调用时拒绝创建提问并要求在结果收齐后重试,不能把已开始的业务动作说成已撤销。
2. 先原子保存 pending 请求,再发布含 interaction_id/revision 的事件。保存失败不显示可提交卡片。工具立即返回“已登记,等待用户”的结果,不挂起 Promise;宿主在原生工具结果完成后结束该轮并等待 idle,记录专门的 `waiting_input` 结束原因,不显示为执行失败或最终报告完成。
3. 从登记成功到模型 idle,插件和宿主都拒绝该轮新工具调用,避免模型尚未收到答案就继续依赖答案执行。已有 final_answer 结束机制可复用,但 ask_user 的结束原因、落盘及重连投影需要单独实现;仅增加一句“请等待”提示词不满足验收。创建后崩溃时,宿主从持久记录重建等待状态并核对旧轮次,不继续旧的工具链。
4. 浏览器显式提交答案,宿主比较请求 revision、验证答案并原子写入 answered 和 queued 投递记录,返回已保存回执。原轮次尚未 idle 时只排队,不并发启动第二轮。提交不能依赖 `activeRuns` 必须仍有旧对象。
5. 抽取并复用既有 `/responses` 的会话启动、事件订阅、鉴权上下文、消息持久化和模型选择,建立单一运行协调入口,不从路由外直接裸调用 runtime.prompt。新轮次采用宿主固定 native_message_id,通过已有原生 prompt 的 id 能力投递结构化问题与答案,标注为用户回答,不伪装成原 question 工具返回值。
6. 投递前先按固定 ID 查原生 inbox/message:已入队则接续观察,已消费则补记 delivered,仅确认不存在才投递。网络失败保留 dispatching 并核对,不生成新 ID。已消费后生成失败只允许继续该轮结果处理,不能再次注入同一答案;不承诺跨系统恰好执行一次业务动作。
7. 宿主重启不会丢掉已保存答案。恢复在下一次已授权的会话打开、回复或用户重试时触发,先恢复事件订阅,再核对投递与原生运行状态;不持久保存 Bearer,也不在无有效用户上下文时自动发起推理。OpenCode 会话不可恢复时标记 blocked,允许复制答案,但不能悄悄创建新会话、重放整段业务操作或伪造工具结果。
本方案最脆弱的前提是固定消息 ID 的核对能够区分未投递与已消费,以及提问后能形成可靠的轮次结束边界。上线门槛是用当前原生版本验证这两个行为;若无法确认,保持“答案已保存,继续失败”并停止自动重试,不回退到不受控的重复执行。当前设计没有执行这些原生故障注入验证。
### 11.4 接口与 UI 行为
接口均拟新增在 Agent 的 `/api/v1/session/:sessionId/interactions` 下,沿用会话鉴权;不建立 Server 表或引入新服务。内部创建桥为 `/internal/chat-interactions`,不对浏览器开放创建权限。会话详情增加未解决请求和当前消息页涉及的请求投影;独立列表使用稳定游标,默认 20、最多 50 条,不为恢复卡片拉取全部历史。
| 方法与相对路径 | 行为 |
| --- | --- |
| GET 根路径;GET `/:interactionId` | 返回权威请求、当前草稿和续跑状态;以 interaction_id 去重,读取不自动回答 |
| PUT `/:interactionId/draft` | 带 expected_draft_revision、request_id 和草稿;500ms 防抖,终态拒绝写入;与正式提交使用不同版本 |
| POST `/:interactionId/reply` | 带 expected_revision、request_id 和完整答案;同请求同内容返回原回执,不重复建续跑记录 |
| POST `/:interactionId/skip` | 所有问题均非必填时允许;原子记录 skipped 并安排一次明确的跳过输入,不编造默认答案 |
| POST `/:interactionId/cancel` | 仅 pending 可取消;关闭提问且不续跑,用户可以改发普通消息 |
| POST `/:interactionId/resume` | 只核对并继续原投递记录;不修改答案、不创建新的投递 ID |
写接口均使用严格 version、expected_revision 和 request_id 校验,draft 使用自己的 revision;resume 比较续跑记录 revision。400 表示定义或答案非法,409 区分版本冲突、请求已解决与幂等键内容不一致,413 表示容量不足,503 表示服务暂不可用。回复已落盘但模型暂不可用时返回已保存状态及 queued/blocked,不把答案当作提交失败让用户反复重发。GET 使用 private/no-store,权限失效与删除沿用第 8 节。
前端复用 shadcn 的 RadioGroup、Checkbox、Textarea、Button、状态提示和现有卡片布局,独立封装宿主提问卡,不新增任意代码渲染。可恢复的状态如下。
| 状态 | 界面和操作 |
| --- | --- |
| 核对中 | 显示问题与草稿,提交暂不可用;不能凭历史 pending 直接放行 |
| 待回答 | 支持单选、多选、自定义输入,草稿保存提示;必填项不提供跳过 |
| 提交中 | 禁止双击;保留完整输入;响应丢失按同请求 ID 核对 |
| 已回答,等待继续 | 只读显示已确认答案和续跑状态;重试只操作续跑记录 |
| 已回答并继续 | 显示答案摘要和后续回复;不再展示提交按钮 |
| 已跳过、已取消、已失效 | 展示对应原因,不显示可点击的过期选项;不统一称为“状态丢失” |
切换对话只切换订阅,旧回执绑定旧 session/interaction,不改变新对话;切回与刷新时先读权威状态,再合并当前作用域未保存的草稿。打开页面不自动提交、弹窗、聚焦或滚动。两窗口提交不同答案只有一个成功,另一窗口显示服务端已接受答案;保留冲突输入供复制,不覆盖已经提交的答案。
有 pending 提问时,普通输入区提示先回答或取消;服务端也拒绝绕过等待直接启动新一轮。已提交答案的续跑排队时同样阻止抢占,避免问答顺序错乱。“停止”会显式取消仍 pending 的提问;已经提交的答案仍保留,未投递记录可停止,已投递的运行沿用既有停止语义,不伪造未执行状态。停止与投递通过同一会话协调入口串行化。
### 11.5 兼容、实施与验收
新请求使用独立类型和 ID,不把历史原生 question 卡片直接改成宿主 pending。旧请求读取时核对原生状态:仍待回答才保留旧回复入口,已回复/取消则同步终态,明确不存在时显示已失效;503 时显示暂不可核对,不能误判失效。用户可以复制旧问题另起交互,但不会自动替旧工具伪造回答。
前端通过 `host-question@1` 能力声明支持新卡片,宿主在每轮启动时固定能力快照。有能力的新轮次注册 ask_user 并禁用内置 question;旧客户端不生成其无法操作的新卡片。既有原生请求的回复路由保留。灰度按新轮次边界生效,不热替换正在等待的工具。旧客户端打开新记录至少能看到文本和已解决状态,待回答请求提示使用支持该能力的客户端,不能静默降级后绕过等待。
该项可在 reader/basket 和正式报告持久化之前独立交付。预计涉及 Agent 与 frontend 两个仓库、超过 8 个文件;新增服务、数据库、账号、环境变量均为零,内部桥复用现有服务凭据。
| 位置 | 交付内容 |
| --- | --- |
| Agent `.opencode/tools/ask_user.ts`、`.opencode/plugins/tjwater-tools.ts`、工具与 instruction 策略 | 新工具、严格 schema、轮次能力判断和等待期工具约束;前者为拟新增文件 |
| Agent 拟新增 `src/sessions/interaction-request-store.ts`、`src/routes/interaction-request-routes.ts`、`src/routes/chat-interaction-bridge.ts` | 单文件事务、草稿版本、原子答案/投递记录、内部创建与用户接口 |
| Agent `src/sessions/workspace-store.ts`、`src/routes/chatStreamRoute.ts`、`chatStream.ts`、`chatSessionRoutes.ts`、`src/runtime/opencode.ts` | 文件允许列表、提问轮次结束、共享运行入口、重连核对、稳定消息 ID、删除及旧请求兼容 |
| frontend `src/features/agent/api/`、拟新增 `components/agent-interaction-request-card.tsx`、`src/features/workbench/hooks/agent-session-runtime.ts`、`use-workbench-agent.ts` | 协议解析、受控提问卡、草稿保存、请求状态核对与会话隔离 |
验收必须包括:A 会话提问后切到 B 再切回提交;刷新恢复草稿;两窗口同时提交;清空草稿后的迟到 GET;提交成功但回执丢失;原生已消费但宿主未记回执时崩溃;宿主重启后授权恢复;原生会话丢失;提问与另一工具并行;提问后模型继续调用工具;停止与续跑竞争;旧客户端及旧 question;权限失效和会话删除。前端覆盖键盘操作、320px 窄屏、焦点及 reduced motion。
实现时运行前端 `pnpm lint`、`pnpm typecheck`、`pnpm test` 和拟新增浏览器 `tests/browser/agent-question-lifecycle.e2e.ts`;Agent 运行 `bun run check`,为状态存储、路由及原生续跑新增聚焦测试。浏览器模拟通过后,还需隔离原生运行验证固定 ID 与故障恢复,不能把模拟 Map 的幂等行为当作 OpenCode 的保证。
发布先增加服务端读写、文本投影与旧请求核对,再上线客户端,最后在支持能力的新轮次启用 ask_user。回退时先停止创建新请求,保留新协议的读取、提交和续跑兼容接口,直到待回答及待投递请求被解决或用户取消;不能直接删除接口把已发布问题遗留成死卡片。记录和答案始终保留,不因回退重置 revision。
+100
View File
@@ -0,0 +1,100 @@
# Agent Persona 设计
更新日期:2026-10-28。本文保存供水前端当前的 Persona 视觉与交互规格,作为后续调整的基线。资源解析、再生成及缓存实现见 [动画资源说明](agent-persona-resource.md);通用控件和语义表面继续遵循 [样式设计指南](style-design-guide.md)。
## 1. 形象与材质
采用 Obsidian 原生 Rive 水纹球,保留柔和羽化、流动反射、不规则边缘水纹和状态机。配色采用已选定的 02「冰水蓝」:浅色水体承载白色高光,暗部保持蓝色,外围水纹提供地图上的辨识度。主体底色具有较高遮蔽度,减少地图道路穿过球体的现象。
| 角色 | 当前值 | 用途 |
| --- | --- | --- |
| 球面底色 | `#DCEFFA` | 浅冰蓝底层,独立于流动反射 |
| 底色不透明度 | 待机 94%,活动 98% | 保持主体清楚,避免背景纹理干扰 |
| 水体反射 | `#299FDF` | 提供蓝色层次与流动感 |
| 同色相暗部 | `#1482BC` | 保留体积,避免灰黑混色 |
| 高光 | `#FFFFFF` | 保留清晰、干净的反射 |
| 外围水纹 | `#4C9ECC` | 提高浅色地图上的辨识度 |
颜色直接写入 Rive 资源,不使用 CSS 色相、亮度或对比度滤镜。通用 UI 仍引用共享语义颜色;上表仅定义动画资源本身的材质。参数源为 [obsidian-material.json](../design/agent/obsidian-material.json)。
以下为当前资源的实际静态帧,用于辨认在线与离线外观;运动行为以第 4 节为准。
| 在线待机 | 离线静水待机 |
| --- | --- |
| <img src="../public/agent/obsidian-water-idle.png" width="64" height="64" alt="冰水蓝在线 Persona,有外围水纹"> | <img src="../public/agent/obsidian-water-offline.png" width="64" height="64" alt="冰水蓝离线 Persona,无外围光圈"> |
## 2. 尺寸与定位
| 使用位置 | 画布尺寸 | 布局要求 |
| --- | --- | --- |
| `AgentPersona` 默认 | 64 × 64px | 固定尺寸,不随状态变化 |
| 桌面收起入口 | 64 × 64px | 画布填满按钮命中范围 |
| 桌面与手机面板标题栏 | 64 × 64px | 与名称、状态共同形成身份区 |
| 手机地图入口 | 40 × 40px | 使用同一资源,适应地图工具栏 |
桌面收起入口距地图左侧 **12px**,距顶部导航下沿 **12px**。两个方向由同一定位层的内边距控制;当前导航高 56px,因此入口左上角为视口中的 `(12px, 68px)`。这里的顶部距离以导航下沿为起点。
尺寸指整个 Rive 画布,包含资源固有的羽化留白。放大时保留画板比例,不裁掉外围水纹。悬浮入口仅显示 Persona;状态通过按钮名称与悬停提示提供,避免增加卡片、状态点、箭头或底圈。
## 3. Agent 标题区
身份行高 **80px**,左右内边距 12px、上下 8px。左侧为 64px Persona,旁边上下排列名称“供水助手”和连接状态;右侧集中排列对话操作。
| 内容 | 规格与行为 |
| --- | --- |
| 名称 | 14px、半粗,与现有标题排版一致 |
| 连接状态 | 12px 辅助文字配共享 `StatusDot`;显示实际的“连接中 / 在线 / 离线” |
| 操作 | 新建对话、历史、折叠;手机末项为关闭,每项命中范围 40 × 40px |
| 上下文行 | 高 36px,保留会话标题与项目或个人范围切换 |
身份行与上下文行保持连续的浅色表面,在标题区底部使用分隔线。历史展开、键盘导航和关闭后焦点恢复沿用现有行为。320px 手机宽度下,名称、状态和三个操作均应完整显示且互不重叠。
## 4. 动画与状态
动画由 Rive WebGL2 的同一个 `default` 状态机驱动,业务层提供真实状态。在线水纹持续流动;离线保持完整球体,通过节奏与光圈变化表达连接不可用。
| 状态 | 呈现 |
| --- | --- |
| `idle` | 原生待机流动与外围水纹 |
| `thinking` | 原生处理状态动画 |
| `listening` | 原生等待输入动画,具体含义由业务映射决定,不单凭形象表示麦克风录音 |
| `speaking` | 原生输出状态动画 |
| `asleep` | 内部柔光低速、小幅流动,外围三层光圈透明度为 0 |
| `hover` | 鼠标附近的局部白色反射随指针移动,与当前业务状态叠加 |
离线设计称为“静水待机”。在线与离线以 **600ms** 混合切换,可见实例保持挂载;离线球体持续运动,恢复在线后恢复外围光圈。离线悬停也不重新打开外围光圈。
离线三层循环周期为 **15s / 19.25s / 31.375s**,位移与呼吸振幅为原来的 25%,完整旋转保持循环闭合。时间轴速率由 60 调至 24,约为原速 40%;此值不代表屏幕渲染帧率上限。详细图层参数见 [obsidian-offline.json](../design/agent/obsidian-offline.json)。
## 5. 悬停与点击
悬停沿用原版三层反射的尺寸、渐变和亮度。进入以约 150ms 渐显;白色高光以约 80ms 的跟随时间常数趋近鼠标位置,保留轻微惯性。鼠标移出后先停留 100ms,再以约 600ms 淡出,退场期间保留最后的跟随位置。不能只打开 `hover` 布尔值而遗漏坐标,否则原生指针目标停在默认中心,造成球体中间大片变白。球体、点击范围和常态外围水纹尺寸均保持原定义。
共享 `Persona` 保留 Rive 原生指针监听,经由 `persona-hover.ts` 平滑 CSS 坐标后,将主指针的进入、移动、离开和取消转交给画布;坐标转换与资源内的跟随约束由 Rive 完成。150ms / 600ms 渐变由 Rive 时间轴负责,进出切换以 100ms 状态混合衔接;所有时间参数集中在 [persona-hover-timing.json](../src/shared/ai-elements/persona-hover-timing.json)。100ms 停留内重新进入会取消退场,淡出过程中重新进入从当前坐标继续跟随;取消事件立即释放悬停,卸载时清理动画帧和计时器。触摸及按压不转交动画,不绑定 View Model。悬浮入口和标题形象共用这条通路,画布就绪后才接收交互。
点击、触摸轻点及 Enter / Space 展开对话,离线时同样可用。球体不添加 Motion 按压缩放、弹簧回弹或按下变暗;触摸按下不模拟 hover。外层面板的布局动画独立维护,Resizable 连续调宽保持直接响应。
## 6. 加载、降级与缓存
首次加载显示当前资源导出的静态帧。Rive 加载后先等待 600ms 完成原生进入动画,再以 **180ms CSS 透明度渐变**衔接,尺寸和位置保持固定。在线、离线分别使用相应的本地 PNG,避免银灰占位与蓝色动画之间的突变。
系统开启“减少动态效果”时显示静态帧,不初始化 Rive;资源失败时保留相应静态形象与按钮功能。强制颜色模式显示高对比轮廓,保留焦点和键盘操作。元素离开视口或页面隐藏时卸载渲染实例,可见后恢复。
客户端按页面内存、Cache Storage、网络的顺序取得资源。仅共享不可变 `.riv` 字节,每个可见入口独立创建动画实例;不共享实例或绑定 View Model。资源重建时同步生成 SHA-256 版本,URL 带版本参数,使旧缓存自然更新。缓存范围与校验逻辑见 [动画资源说明](agent-persona-resource.md)。
## 7. 实现与维护
| 入口 | 文件 |
| --- | --- |
| 业务形象与降级 | [AgentPersona](../src/features/agent/components/agent-persona.tsx) |
| 原生状态机接入 | [Persona](../src/shared/ai-elements/persona.tsx) |
| 桌面悬浮按钮 | [AgentCollapsedRail](../src/features/agent/components/agent-collapsed-rail.tsx) |
| 标题区 | [AgentCommandPanel](../src/features/agent/components/agent-command-panel.tsx) |
| 资源生成与原版还原 | [build-agent-persona.mjs](../scripts/build-agent-persona.mjs) |
| 资源版本与缓存 | [persona-resource.ts](../src/shared/ai-elements/persona-resource.ts) |
材质与离线参数以对应 JSON 为准,悬停沿用原始资源中的几何与指针约束,仅调整时间轴与指针跟随节奏;改动时同步本文与资源说明。原始解析数据保留以便逐字节还原 `.riv`;该数据不等于作者完整的 `.rev` 编辑器工程。
验收时检查 64px 桌面入口、64px 标题形象与 40px 手机入口,覆盖默认、悬停进入与退出、快速切换、离线和恢复在线。桌面检查 1024/1440px 视口及 400/640px 面板,手机检查 320/375px。确认左上间距一致、按压无缩放、首次加载无画面硬切、底色能遮蔽地图、离线无外围光圈、缓存刷新后仍加载当前版本。
资源级检查使用固定时间步对照原版与修改版:在线状态保持相同材质下的逐像素一致;悬停检查左右移动时局部高光跟随指针,移出后完全恢复。工作台检查鼠标坐标实际到达悬浮入口和标题形象的 Rive 监听器,不能仅断言 hover 开关变化。离线检查完整球体、持续变化和光圈关闭。运行命令见 [资源说明](agent-persona-resource.md),各次实际验证结果记录在 [实施记录](history/agent-chat-ui-implementation-notes.md)。
+93
View File
@@ -0,0 +1,93 @@
# Agent 动画资源与离线水纹
Agent 保留原版 Obsidian 图形与运动结构,采用经实际动画对比选定的 02「冰水蓝」配色,并在 Rive 文件内部增加“静水待机”离线设计。在线保留外围水纹光圈;离线关闭外围三层光圈,仅保留球体内部的缓慢流动。在线、离线和交互使用同一个 `default` 状态机。
当前视觉规格、尺寸、标题区与交互约定统一见 [Persona 设计](agent-persona-design.md)。本文维护资源结构、生成过程与缓存实现。
## 文件与再生成
| 文件 | 用途 |
| --- | --- |
| [运行时源数据](../design/agent/obsidian-runtime.json) | 从原版解析的 775 个对象,包含图形、属性、关键帧、状态机和绑定数据 |
| [冰水蓝材质参数](../design/agent/obsidian-material.json) | 已确认的水体、暗部、白色高光和水纹颜色,以及球面底色遮蔽度 |
| [离线设计参数](../design/agent/obsidian-offline.json) | 可编辑的播放速度、振幅、混合时长和三层柔光/反射强度 |
| [悬停时间参数](../src/shared/ai-elements/persona-hover-timing.json) | 150ms 渐显、80ms 跟随、100ms 停留、600ms 淡出及 100ms 状态混合 |
| [生成脚本](../scripts/build-agent-persona.mjs) | 验证原版重编码、修改离线动画,生成本地资源 |
| [应用资源](../public/agent/obsidian-water-v1.riv) | 前端加载的 9,929 字节资源 |
| [缓存版本清单](../src/shared/ai-elements/persona-resource-manifest.json) | 生成脚本同步输出的路径、SHA-256 和字节数,用于客户端缓存更新 |
| [静态帧生成脚本](../scripts/render-agent-persona-stills.mjs) | 从实际资源渲染在线、离线 PNG,供首次加载、减少动态效果和失败兜底使用 |
| [资源对照测试](../tests/browser/agent-persona-resource.e2e.ts) | 真实 WebGL2 运行时定时推进,比较原版与修改版画面 |
在前端仓库运行:
```bash
node scripts/build-agent-persona.mjs
node scripts/render-agent-persona-stills.mjs
node scripts/build-agent-persona.mjs --check
# 将原版还原到一个尚不存在的文件,应用资源不会被替换
node scripts/build-agent-persona.mjs --restore-original /tmp/obsidian-original.riv
pnpm test:browser tests/browser/agent-persona-resource.e2e.ts tests/browser/agent-orb.e2e.ts --workers=1
```
JSON 保存原始运行数据;脚本负责可审查的定制。`--check` 验证原始数据能逐字节恢复,并检查生成结果与应用资源一致。基线 SHA-256 为 `c6ae7d08f5787a560e38d3453ba155c28250acf2db75e6acf2b0d1a0cd6017db`。替换上游基线时需重新解析和验证,不应只修改散列值跳过检查。
配色编辑 `obsidian-material.json`,其中 `bodyColor` 只控制球面底色,`bodyOpacity` 控制它在待机/活动时的遮蔽度,其他蓝色反射沿用 `colors` 映射;离线动画编辑 `obsidian-offline.json`;重新生成 `.riv` 和静态帧后刷新前端。静态帧脚本使用已安装的 Playwright、esbuild 与 Rive WASM,无需访问外部动画服务。`fps` 控制离线时间轴速度,`amplitude` 控制位移与缩放的变化幅度,`transitionMs` 控制在线/离线的混合时长。各层 `opacity` 中的 `rest` 和 `crest` 是相对原始透明度的比例,分别对应循环开始/结束与中点。数值需满足 `0 ≤ rest ≤ crest ≤ 1`;保留循环端点一致,避免接缝。外围三个光圈均固定为 `0`。
`--restore-original` 使用只创建模式,目标文件已存在时会报错,避免覆盖已有编辑。原版还原文件与基线逐字节相同,包含原版离线消失的行为;前端继续加载带离线设计的应用资源。
## 冰水蓝与离线设计
材质采用经原生 Rive 预览选定的 02 方案:水体 `#299FDF`、同色相暗部 `#1482BC`、白色高光 `#FFFFFF`、外围水纹 `#4C9ECC`。外围水纹从初选时的 `#B0E3FF` 加深,以提高浅色地图上的辨识度;光圈粗细、渐变 alpha 和运动保持原定义。球面底色独立设置为 `#DCEFFA`,待机/活动时的不透明度为 94%/98%,同步调整对应的活动状态关键帧。浅色且高遮蔽度的底层减少地图道路穿过球体的现象,蓝色反射仍由原来的运动图层呈现;暗部沿用蓝色调,避免叠加灰黑阴影。渐变位置、羽化、裁剪、运动曲线及其他节点的原有 alpha 保留,不添加 CSS 滤镜或 View Model 绑定。
此前 A「水务蓝」使用灰蓝主体、浅蓝高光与 78%/90% 的底色不透明度,在白底实际动画中显得发灰、浑浊,已被本方案替换。后续调整以同一背景下的真实动画及 40/64px 入口效果为准,不以色卡单独判断材质。
离线以“水面逐渐平静”表达连接不可用:外围三层光圈在 600ms 混合期间消退至完全不可见,内部柔光降低并保持缓慢流动。球体整体透明度和缩放保持完整;悬停不会重新打开离线光圈。恢复在线时重新显现光圈与在线节奏。业务状态仍由入口按钮的可访问名称和提示提供。
| 层 | 柔光强度 | 反射强度 | 循环周期 |
| --- | --- | --- | --- |
| 内层与下侧柔光 | 56%–68% | 0,关闭 | 15 秒 |
| 中层与内部柔光 | 48%–62% | 0,关闭 | 19.25 秒 |
| 外层与上侧柔光 | 60%–72% | 0,关闭 | 31.375 秒 |
上表是设计参数当前值的解释。内部柔光以原版贝塞尔缓动从 `rest` 升到 `crest` 再回落,周期错开,避免同步闪烁;光圈透明度保持为零。40/64px 入口共用同一资源,状态切换不改变布局尺寸。
参数中的图层名称是根据运行时结构补充的语义别名,不是恢复出的作者原始命名。`objectId` 是画板组件编号,不能用 JSON 对象数组的索引替代:绑定记录不占组件编号。
## 解析结果与修改
原版有 1 个 `Obsidian` 画板、20 段动画、13 个状态机层和 5 个布尔输入。`asleep` 动画在第 45 帧将节点 4 的透明度从 1 降至 0,并将节点 3、190、199、208 的缩放降至 0.6–0.8,因此离线时球体消失。
修改版保留原有图形、渐变结构、羽化、裁剪和在线运动,改变以下部分:
- 根据已选定的配色映射 RGB,并独立设置底色填充节点 189 的颜色、节点 186 的静止及活动透明度;原始 JSON 不改动,仍可完整还原银灰原版 `.riv`。
- `asleep` / `wake` 的透明度与缩放关键帧保持 1,避免隐藏或缩小球体。
- 在原有 20 段动画后追加 `offline_loop_1`、`offline_loop_2`、`offline_loop_3`,保持原有动画编号。
- 离线循环复用原版三层水纹,时间轴速率从 60 改为 24,约为原速的 40%;这是时间轴播放速度,不是将屏幕渲染限制为 24fps。
- 位移和呼吸振幅缩至原来的 25%;完整旋转保留首尾角度,避免循环接缝。
- 离线循环增加六个柔光/光圈节点的透明度轨道,其中节点 190、199、208 的光圈透明度固定为零;在线循环对应增加原始透明度常量轨道,确保恢复连接后完整恢复。
- 三个循环层根据既有 `asleep` 输入切换,使用 600ms 状态混合。
- 悬停保持原版反射几何、渐变与亮度,将 `hover_in` / `hover_out` 分别调整为 9 / 36 帧,即 150ms / 600ms,并使用原有贝塞尔插值器。退出时间轴持续保持节点 129 的指针约束,完全淡出后才释放;进出切换使用 100ms 混合。
生成结果包含 960 个对象、23 段动画。调整设计参数后需再生成并运行对照测试;无需修改前端组件或安装额外依赖。
## 前端接入与生命周期
悬停沿用原版节点 110 的反射尺寸,以及节点 129 对指针目标 1 的跟随约束。`Persona` 保留 Rive 监听器,通过外层 Pointer Events 与 `persona-hover.ts` 向画布转交鼠标的进入、移动和离开坐标;移动坐标以 80ms 时间常数平滑,移出延迟 100ms 后交给资源淡出,Rive 自行完成画布与画板坐标转换。画布内部不直接命中鼠标或触摸,只有就绪的外层接收并筛选主指针;不转交触摸和按压,因此手机点击不会触发白色高光。仅手动设置 `hover` 而禁用原生监听,会使目标停在中心,造成中央大片变白。这个问题由事件通路修复,不通过缩小光圈或改变材质补偿。
`persona-resource.ts` 加载同源的 `/agent/obsidian-water-v1.riv?v=<SHA-256>`。同一页面共用下载 Promise,跨刷新、再次打开页面使用浏览器 Cache Storage 的 `tjwater-agent-persona-v1` 缓存;只共享不可变字节,不共享 Rive 实例或 View Model。
读取顺序为页面内存、当前版本的持久缓存、网络。下载及缓存命中均检查字节数和 `RIVE` 文件头;支持 Web Crypto 时进一步验证 SHA-256。损坏缓存重新下载,错误页或不匹配的资源不写入缓存。新版本成功保存后,只删除本缓存中该资源路径的旧版本,不清理其他应用数据。重新生成动画时同步更新版本清单,`--check` 同时验证资源与清单。
持久缓存不可用、被禁用或空间不足时仍可下载并在当前页面复用。Cache Storage 需要安全上下文,生产环境使用 HTTPS,本机 localhost 开发可用;浏览器清理站点数据也可能移除缓存,见 [Cache API 说明](https://developer.mozilla.org/en-US/docs/Web/API/Cache)。缓存测试覆盖真实页面刷新,并阻断资源网络路径验证动画仍能播放。
Agent 服务不可用不妨碍前端读取该资源。这项缓存仅覆盖 `.riv`,Rive WASM、应用代码与其他资源沿用各自的加载策略;不构成整站离线支持。浏览器完全断网且应用或运行时尚未加载时,仍可能无法播放动画。
在线与离线切换不卸载可见的 Rive 实例,由状态机处理过渡。静态帧仅用于首次加载、资源失败、减少动态效果及未挂载动画的情况:在线使用 `obsidian-water-idle.png`,离线使用无外围光圈的 `obsidian-water-offline.png`。两张 192px PNG 均由当前 Rive 材质直接渲染,URL 携带资源版本;首次加载维持 180ms 淡入,不再出现银灰占位图。保留可见性卸载、Strict Mode 延迟初始化和原版悬停;没有重新加入 Motion 按压效果或 View Model 绑定。历史约束见 [Rive 内存记录](rive-persona-incident.md)。
## 验证边界与来源
运行时 JSON 能恢复当前 `.riv`,但不等于作者的 `.rev` 编辑器工程;导出时省略的编辑信息没有凭空恢复。原作者提供可编辑 `.rev` 的说明见 [资源定制文档](https://elements.surge.studio/docs/customization),格式差异见 [Rive 备份说明](https://rive.app/docs/editor/exporting/exporting-for-backup)。
原始图形来源为 [Surge Obsidian 动画](https://ejiidnob33g9ap1r.public.blob.vercel-storage.com/obsidian-2.0.riv)。解析时参考了 [rive-rs-cli 的格式读取实现](https://github.com/George-RD/rive-rs-cli/blob/main/src/validator/parser.rs)及其从 Rive 定义生成的类型/属性表;应用不依赖或包含该工具。原图形的作者归属不因解析和局部修改而改变。
对照测试在同一 WebGL2 运行时以固定时间步推进。就绪、思考、待回复、输出和稳定悬停状态要求与“仅应用相同冰水蓝材质的原版”采样画面逐像素一致,并验证主色由灰变蓝、合成到白底后仍保有蓝色,球体中心采样区域的不透明度不低于 90%。悬停另外比较左右指针位置对应的高光重心,要求局部反射随指针移动且移出后完全恢复。时间采样另外验证 150ms 渐显与 600ms 淡出,中途保持可见且最终恢复常态。指针定时测试覆盖惯性跟随、停留、快速进出与卸载清理;工作台测试验证平滑后的实际坐标最终到达原生监听器。离线检查完整球体、持续变化、初始离线和反复恢复;通过外围像素计数验证光圈完全消失,悬停不会重新出现,恢复在线后再次可见。另用相同运动轨迹、取消离线光照变化的对照资源,验证快速切换后在线明暗完整恢复。该检查覆盖固定采样时刻,不是所有设备、运行时间和状态序列的穷举验证。
+27
View File
@@ -0,0 +1,27 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1120" height="490" viewBox="0 0 1120 490">
<rect width="1120" height="490" fill="#F5F7FA"/>
<g font-family="Noto Sans SC Variable,Noto Sans CJK SC,Microsoft YaHei,sans-serif" fill="#232935">
<text x="32" y="46" font-size="24" font-weight="600">宝石蓝 · 银灰亚克力</text>
<text x="32" y="76" font-size="14" fill="#4E5566">同色相色阶 + 低彩度互补色 · 色板为不透明基准,亚克力透明度独立设置</text>
<rect x="32" y="102" width="192" height="236" rx="8" fill="#4263C7" stroke="#BEC2CD"/>
<text x="32" y="373" font-size="20" font-family="Consolas,monospace">#4263C7</text>
<text x="32" y="402" font-size="16">宝石蓝 · 主操作 · 品牌</text>
<text x="32" y="430" font-size="12" fill="#4E5566" font-family="Consolas,monospace">L 0.529 C 0.160 h 267.06</text>
<rect x="248" y="102" width="192" height="236" rx="8" fill="#E6E9F2" stroke="#BEC2CD"/>
<text x="248" y="373" font-size="20" font-family="Consolas,monospace">#E6E9F2</text>
<text x="248" y="402" font-size="16">银霜 · 亚克力材质</text>
<text x="248" y="430" font-size="12" fill="#4E5566" font-family="Consolas,monospace">L 0.935 C 0.012 h 267.06</text>
<rect x="464" y="102" width="192" height="236" rx="8" fill="#F5F7FA" stroke="#BEC2CD"/>
<text x="464" y="373" font-size="20" font-family="Consolas,monospace">#F5F7FA</text>
<text x="464" y="402" font-size="16">冷瓷 · 阅读 · 表单</text>
<text x="464" y="430" font-size="12" fill="#4E5566" font-family="Consolas,monospace">L 0.975 C 0.005 h 267.06</text>
<rect x="680" y="102" width="192" height="236" rx="8" fill="#D6C294" stroke="#BEC2CD"/>
<text x="680" y="373" font-size="20" font-family="Consolas,monospace">#D6C294</text>
<text x="680" y="402" font-size="16">香槟 · 互补暖色点缀</text>
<text x="680" y="430" font-size="12" fill="#4E5566" font-family="Consolas,monospace">L 0.820 C 0.065 h 87.06</text>
<rect x="896" y="102" width="192" height="236" rx="8" fill="#232935" stroke="#BEC2CD"/>
<text x="896" y="373" font-size="20" font-family="Consolas,monospace">#232935</text>
<text x="896" y="402" font-size="16">深墨 · 标题 · 正文</text>
<text x="896" y="430" font-size="12" fill="#4E5566" font-family="Consolas,monospace">L 0.280 C 0.025 h 267.06</text>
<text x="32" y="468" font-size="13" fill="#4E5566">主色 h = 267.06°;同色色阶保持 h;香槟色 h = (267.06° + 180°) mod 360° = 87.06°</text>
</g></svg>

After

Width:  |  Height:  |  Size: 2.4 KiB

@@ -0,0 +1,87 @@
# Agent 聊天与报告实现记录
本页归档原设计文档中的阶段记录,仅反映各次验证范围,不作为当前样式或验收结论。现行样式见 [样式设计指南](../style-design-guide.md),交互与报告规则见 [Agent 交互与报告设计](../agent-chat-ui-design.md)。
2026-10-20 本地验证:前端 lint、类型检查、514 项单测和构建通过;23 项聚焦浏览器用例通过,涵盖聊天、历史、流式稳定、表单、图表、展开阅读、报告版本、320/375px、键盘与强制颜色。最终引用来源调整另通过组件测试,并重新运行 5 项聊天及报告工作区浏览器用例。
Agent 类型检查及 16 项相关测试通过;隔离 OpenCode 工具发现验证通过,未调用模型推理。Server 的报告 schema、发布幂等、证据归属、历史读取和报告 API 共 76 项聚焦测试通过;OpenAPI 检查通过,Agent 类型与副本同步,三端组件参数目录一致。
另有原有 API 测试 `test_approved_task_source_uses_server_delegation` 失败:测试期待 `delegated=True`,当前接口返回 False;使用 HEAD 中的原版测试复现相同结果。该问题未混入本轮 UI 修改。
浏览器截图使用明确标注的演练数据。此次没有重启既有 Agent/Server、部署、调用真实模型生成报告或连接真实数据库验收;正式运行前需要同步三端版本并验证实际报告生成与落库。构建仍有大 chunk 提示。参数重算、附件、导出与版本差异比较属于后续范围。
同日后续细化:合并指标摘要区、收起图表范围筛选、对齐数据点读数,并增加正式报告章节导航。当前结果的状态标签与标题并排;当前最终结论去除重复的“调查结论”标题,历史、阶段性判断和证据不足的说明继续显示。
320px 浏览器实测,聊天展开视图的指标区从 310px 降为 118px;趋势图距阅读区顶部从 596px 降为 396px。测量使用同一演练数据,图表仍保留 220px 高度,文本内容与数值未裁剪。检查并更新聊天内嵌、聊天展开、报告内嵌、报告展开共 4 类视图(checked 4 / changed 4 / left 0)。
本次增量验证:lint、类型检查、515 项单测、18 项聚焦浏览器用例及 `git diff --check` 通过。浏览器覆盖 320/375px 与桌面、范围筛选和重置、章节键盘跳转与吸顶、滚动章节提示、草稿保留、版本引用、原有审批内容和强制颜色。改动限于前端展示与导航,没有新增依赖或更改接口;本次未重跑构建和 Agent/Server 测试。
2026-10-21 Resizable 分栏验证:新增 `react-resizable-panels@4.14.7`,移除手写 Agent 拖拽 Hook。`pnpm lint`、`pnpm typecheck`、`pnpm test`(100 个文件、515 项测试)、`pnpm build` 和 `git diff --check` 通过;构建仍有原有大 chunk 提示。25 项聚焦浏览器用例通过,覆盖 Agent 与地图/报告两级拖拽、键盘方向键及 Home / End、最小/最大宽度、折叠恢复、320/375px 与桌面往返、报告比例记忆、表单草稿及地图 canvas 连续绘制。运行命令:`pnpm exec playwright test tests/browser/agent-panel-resize.e2e.ts tests/browser/agent-answer-ui.e2e.ts tests/browser/agent-report-workspace.e2e.ts tests/browser/workspace-main-frame.e2e.ts tests/browser/workbench-resizable.e2e.ts --workers=1`。
键盘调宽回调可能早于 DOM 宽度更新,Agent 的尺寸记忆使用回调中的新比例计算,避免记录上一帧宽度;回归用例已先复现失败再验证通过。两处分栏回调均已核对,内层直接保存布局比例,不读取旧 DOM 尺寸。浏览器预览采用演练数据,本轮仅改动前端,未提交、部署或进行真实业务验收。
2026-10-21 首次提问与 Motion 增量验证:lint、类型检查、519 项单测(100 个文件)及 `git diff --check` 通过。10 项相关浏览器用例分批通过,覆盖居中提问、400/640px 调宽、首次发送与新建对话、表单实例保留、Motion 逐帧位移、减少动态效果、320/375px 与短屏输入、悬浮入口及历史富内容恢复。并行任务期间发生过整例超时,动画用例随后单独复核通过;截图辅助逻辑已修复通知退出导致的定位漂移。验证使用演练数据,未新增依赖,本轮未重跑构建或后台测试,未提交或部署。
2026-10-21 悬浮入口白色材质验证:lint、类型检查、519 项单测及 2 项聚焦浏览器用例通过,覆盖桌面折叠恢复、键盘展开、减少透明度降级和 375px 窄屏。检查了实际渲染截图;本轮只调整入口材质,未新增依赖。
2026-10-21 悬浮入口精简验证:入口改为 56 × 56px 圆形按钮,移除附加状态文案、状态点、箭头和详情提示卡片。lint、类型检查、519 项单测及 `git diff --check` 通过。桌面 1024/1440px 尺寸、键盘展开、减少透明度和 375px 手机共 2 项浏览器用例分批通过;桌面首次验证在展开后的布局断言超时,未改业务代码单独复测通过。截图采用浏览器演练环境。
2026-10-21 水纹球与交互验证:形象改为本地 CSS 与 Motion 绘制的水纹球,加入指针跟随、按压形变和触点水波;离线保留完整球体与操作反馈。lint、类型检查、519 项单测及 9 项聚焦浏览器用例通过,覆盖状态切换、离线可见与展开、鼠标移出复位、手机触摸及取消、减少动态效果、强制颜色、键盘、桌面尺寸和 320/375px。此前 3 项首次加载等待超时,已将连接状态首次就绪的等待上限调整为 30 秒,交互断言保持原有超时。检查了实际工作台与交互预览截图,使用演练数据,未新增依赖、提交或部署。
同日高光跟随修正:固定球体位置与边缘反光,改为在固定高光层内移动渐变中心,并缩小、柔化亮斑。720px 预览视口内,48px 球体右下角悬停时,高光层相对球面的偏移从横向 5.34px、纵向 5.34px 降为 0;32/40/48px 的左上、右下悬停均保持贴合。悬浮入口、标题栏、手机入口共检查 3 处、更新 3 处、遗留 0 处(checked 3 / changed 3 / left 0)。lint、类型检查、519 项单测、6 项水纹球浏览器用例和 `git diff --check` 通过;触摸取消、按压水波、离线可见与互动、键盘及减少动态效果保持有效。
同日球缘涟漪补充:实际渲染并对照 Obsidian 原资源的就绪、待回复、思考、输出和悬停状态,增加三层错峰向外传播的球缘水波,触碰改为三道渐弱涟漪;移除球内固定同心纹理,保留柔和流光与已修正的局部高光。检查 32/40/48px 及离线预览,三处共享入口同步更新。lint、类型检查、519 项单测、6 项浏览器用例和 `git diff --check` 通过;浏览器逐帧确认波纹半径实际增大,并检查离线与减少动态效果停止循环、鼠标及手机操作。仅变更前端形象与设计说明,未引入远程资源依赖或新增包。
2026-10-21 Motion 曲线细化:三层球缘改为闭合贝塞尔带状轮廓,内部改为两道持续形变的宽幅明暗光带;状态切换保留相位,悬停只扰动靠近指针的球缘,保留局部高光和三道按压水波。增加几何单测验证循环连续、曲线边界、状态差异及局部扰动。lint、类型检查、526 项单测(101 个文件)及 6 项水纹球浏览器用例通过,覆盖实际路径变化、视口外暂停恢复、处理状态、离线可见、鼠标与触摸取消、减少动态效果、强制颜色和键盘展开。原版 / 上一版 / 新版动态对照页已检查五种状态和 32/40/48px;高光层与球面最大偏差小于 0.03px,多个实例的 SVG ID 无重复,375px 预览无横向溢出。对照页为本地预览产物;工作台仅使用本地 Motion 实现,没有新增包或更改业务状态映射。`git diff --check` 通过,本轮未提交或部署。
2026-10-21 Obsidian 原版恢复:根据源码和实际资源核对,改回 Rive WebGL2 原动画,保留原版羽化、反射、水纹和 hover 状态。删除自绘 Motion 几何实现及对应几何单测;Motion 用于外层按压。离线、减少动态效果及加载失败显示从原动画导出的静态帧。三个入口共检查 3 处、更新 3 处、遗留 0 处(checked 3 / changed 3 / left 0)。lint、类型检查、523 项单测(101 个文件)、构建及 7 项聚焦浏览器用例通过,覆盖真实原版画面变化、单次资源下载、移出视口释放、状态切换、鼠标与触摸取消、离线、资源失败、键盘和强制颜色。构建保留已有的大 chunk 提示。本轮未新增包、提交或部署。
原版 / 接入版动态对照已检查五种状态和 32/40/48px,375px 预览无横向溢出;在线保留原版动画,离线切为原版静态帧。独立对照预览的 35 秒浏览器渲染进程 RSS 从约 193.3 MiB 回落至 177.2 MiB,未观察到持续增长;这是单次短时预览观察,不代表长时间运行或真实业务负载验收。`git diff --check` 通过。
2026-10-21 取消球体按压反馈:`AgentPersona` 移除 Motion,取消缩放、回弹、变暗及触摸触发 hover,保留原版鼠标悬停、水纹和状态动画。减少动态效果改用系统媒体查询监听;离线仍显示原版静态帧。lint、类型检查、523 项单测、7 项球体浏览器用例及 `git diff --check` 通过,覆盖桌面点击、手机触摸、离线、键盘和强制颜色。另在组件预览中验证减少动态效果的实时切换,以及按下前后静态图片一致;未新增依赖或重跑构建。
2026-10-21 首次加载衔接与尺寸修正:逐帧复现静态帧到 Rive 的透明度从 0 直接变为 1,球体位置和尺寸保持不变,确认跳动来自画面硬切。改为 180ms CSS 渐变,结束后隐藏占位;新浏览器用例在修改前失败、修改后通过。悬浮画布从 48px 放大至 56px,桌面标题栏从 40px 放大至 48px,手机入口从 32px 放大至 40px,三个入口均复核。lint、类型检查、523 项单测及 8 项聚焦浏览器用例分批通过,检查了 320/375px 实际画面、加载衔接、原版动画、按压无反馈、离线、触摸和键盘。未新增依赖、提交或部署。
## 2026-10-21 Rive 资源内离线水纹
解析原版 775 个运行时对象,JSON 重新编码与原文件逐字节一致。保留原图形和在线动画,新增三段离线循环,并修正 asleep / wake 的透明度与缩放关键帧;同源资源为 `public/agent/obsidian-water-v1.riv`。实现与再生成说明见 [Agent 动画资源](../agent-persona-resource.md)。
验证通过:生成一致性检查、lint、类型检查、547 项单测、构建、`git diff --check`。10 项相关浏览器用例分批通过,包含真实 WebGL2 在线状态采样逐像素对照、原版离线消失与修改版离线持续运动、初始离线、反复恢复、工作台单实例、加载衔接、按压无反馈、资源失败、减少动态效果、键盘及 320/375px。首次运行有 1 项动画就绪等待超时;未修改运行代码,带 trace 复测通过,首次超时根因未确认。
独立预览检查 5 种状态及 40/48/56px,离线仍为实时 canvas;30 秒渲染进程 RSS 约 209 MiB 至 176 MiB,未见持续增长。这是本地短时观察,不替代长时间运行验证。构建保留原有大 chunk 提示,本轮未新增依赖、提交或部署。
## 2026-10-21 静水待机与客户端资源缓存
在资源内为六个柔光/反射节点增加离线强度循环,保留原版整体轮廓与在线画面,在线/离线混合时长调整为 600ms。可编辑参数独立保存为 `design/agent/obsidian-offline.json`;生成脚本增加原始 `.riv` 还原命令,实测输出 SHA-256 与原版一致。浏览器对照覆盖在线采样逐像素一致、离线持续变化、正常恢复与快速反复切换后的原版光照恢复。
`.riv` 增加页面内存与 Cache Storage 两级缓存,使用生成脚本同步输出的内容 SHA-256 作为版本。下载和缓存读取验证内容,损坏缓存重新获取,写入新版本后仅清理该动画的旧条目;缓存不可用、权限或配额失败不阻止网络资源播放。真实工作台刷新后阻断动画文件的网络路径,仍能加载并持续播放,下载次数保持为一次。缓存仅覆盖动画资源,不代表应用和 Rive WASM 的完整离线支持。
最终验证通过:lint、类型检查、554 项单测、11 项聚焦浏览器用例、构建、资源与缓存清单再生成一致性、生产资源与打包版本核对、文档链接及 `git diff --check`。实际预览检查 5 种状态及 40/48/56px,浏览器用例覆盖桌面和 320/375px。构建仍有已有大 chunk 提示;未新增依赖、提交或部署。
## 2026-10-21 冰水蓝与光圈辨识度
初版 A「水务蓝」在实际动画中出现灰蓝混色、底色过厚的观感问题。将三个新配色放入原生 Rive 动画,在白底、五种状态与 40/48/56px 下对比后,采用用户选定的 02「冰水蓝」:水体 `#299FDF`、暗部 `#1482BC`、白色高光,底色不透明度为 12%/32%。根据工作台截图反馈,外围水纹进一步从 `#B0E3FF` 加深为 `#4C9ECC`,提升浅色地图上的轮廓辨识度;光圈粗细、渐变 alpha、羽化与运动曲线保持原定义。
离线仍关闭三层外围光圈,保留内部缓慢水纹。在线、离线兜底 PNG 从实际资源重新渲染,内容版本与客户端缓存清单同步更新;仅加深光圈前后,离线 PNG 逐字节一致。悬浮入口、标题栏和手机入口共享资源,检查 3 处、更新 3 处、遗留 0 处(checked 3 / changed 3 / left 0)。
验证通过:lint、类型检查、12 项相关单测及 12 项聚焦浏览器用例分批通过。初次资源对照的深蓝显色阈值不适用于新选定的浅色方案,已调整白底合成后的蓝色检查,并保留原版几何及在线动画的逐像素对照。光圈加深后,重新通过 7 项聚焦浏览器用例,覆盖原版运动、离线无光圈及悬停、恢复在线、缓存刷新、工作台入口和 320/375px。最终构建、资源再生成一致性、生产副本与缓存版本、文档链接及 `git diff --check` 通过;构建保留已有大 chunk 提示。此次未新增依赖、提交或部署。
## 2026-10-21 64px 入口、主体遮蔽与标题区重排
默认 persona、悬浮入口和面板标题区形象统一为 64px,手机地图入口保留 40px。悬浮入口通过同一层 12px 内边距定位,替换原来左侧 12px、导航下方 20px 的独立偏移;1440px 和 1024px 视口实测入口为 64 × 64px,距左侧和顶部导航下沿均为 12px。三个组件调用位置均检查,修改两处呈现尺寸,遗留零处(checked 3 / changed 2 / left 0)。
根据地图道路穿透球体的截图,为球面底色增加独立 `bodyColor`,设为浅冰蓝 `#DCEFFA`,待机/活动不透明度提高至 94%/98%。反射层继续使用选定的冰水蓝配色,外围光圈颜色及离线关闭规则保持。真实 Rive 前后对比检查了带线条背景,中心区域的运行时 alpha 采样不低于 90%;静态帧与缓存版本重新生成,原版几何与在线运动对照仍通过。
标题区身份行重排为 64px persona、上下排列的名称与连接状态,以及右侧三个 40px 操作按钮。上下文行继续提供会话标题与项目切换;两个区域共用白色背景,仅在底部保留分隔线。400px、640px 桌面面板和 320px 手机截图已检查,名称与操作按钮无重叠。历史展开、重命名取消、键盘焦点恢复、新建、折叠和手机关闭入口保留。
最终验证通过:lint、类型检查、556 项单测(102 个文件)、构建和 17 项相关浏览器用例分批通过。浏览器覆盖资源及主体遮蔽、离线、缓存、加载衔接、布局与标题区、320/375px、短屏输入,以及首次发送与新建会话的居中恢复。生产资源、PNG 副本、缓存版本清单、文档链接和 `git diff --check` 通过。构建保留已有大 chunk 提示;未新增依赖、提交或部署。
## 2026-10-22 Persona 设计归档与悬停坐标修复
当前视觉规格保存为 [Persona 设计](../agent-persona-design.md),记录冰水蓝材质、主体遮蔽、64px 默认尺寸、12px 等距定位、标题区、状态动画、交互、降级与缓存边界,并从 README、交互设计和资源说明关联。
悬停中央大片变白的原因是共享 `Persona` 禁用了 Rive 指针监听,仅手动设置 `hover`,导致原生反射的指针目标始终位于中心。恢复原生监听并通过 Pointer Events 转交主指针的进入、移动、离开与取消;Rive 完成坐标转换和原生约束更新。触摸、按压和触摸生成的鼠标事件不进入动画通路。撤销此前的 80% 光圈缩放,应用 `.riv` 与此次调整前逐字节一致。
三个调用位置均复核(checked 3 / changed 3 via shared component / left 0):桌面悬浮入口、面板标题区、手机地图入口。新增工作台回归在修复前收到空坐标并失败,修复后通过,覆盖悬浮入口和标题区的左右移动。资源级对照验证高光重心跟随左右指针移动,且画面与相同材质的原版逐像素一致;鼠标移出后完全恢复。实际组件的 64px 与 160px 放大画面已检查,手机 320/375px、离线、键盘、减少动态效果、失败降级和无按压反馈由相关浏览器用例覆盖。
lint、构建内类型检查、558 项单测(103 个文件)及构建通过;14 项相关浏览器用例分批通过。首次综合运行中,加载衔接的 5 秒前置等待和多次挂载缓存检查的整例 30 秒时限超时,未改代码或断言,单独复测两项均通过。资源还原与再生成校验、本文涉及的文档链接和 `git diff --check` 通过。构建仍有已有大 chunk 提示;未新增依赖、提交或部署。
+106
View File
@@ -0,0 +1,106 @@
# 调查任务展示与 Dev 测试
可直接打开顶部 Dev 入口载入、编辑、校验并执行本地测试案例,无需先选择调查或开启实时跟随。纯数据和界面块可独立预览,包含地图或图表展示指令时需等待地图就绪。验证实际调查联动时,在“工况任务 → 调查任务”选择一项任务,再打开 Dev。Dev 默认打开“调查测试”页签,保留当前选择,显示调查代次、实时图表数、已保存报告中的图表/表格/地图入口数,以及最近的展示动作。上一轮报告会明确标注,不当成本轮新成果。
Dev 分为“调查测试”和“地图调试”两个页签:前者按“准备数据 → 校验与执行 → 检查结果”组织 JSONL 流程,后者保留要素定位、水流、图层和标注工具。切换页签保留输入与展示状态,不清除当前预览。地图重置操作仅显示在地图调试页。
## 当前识别链路
| 内容 | 来源和行为 |
| --- | --- |
| 实时地图、图表和覆盖层 | 从工作台事件流读取 `operational.presentation.requested`,核对所选 task、run 和 generation,验证命令后使用调查展示控制器执行 |
| 已保存的结构化界面 | 任务报告的 `ui_blocks` 使用既有 `answer-ui@1` 校验及 json-render 组件;未知或不合法的内容不作为可执行界面 |
| JSONL 数据 | Dev 中显式载入、校验后在展示面板预览;调查数据行仅展示,只有受控展示指令行会在点击“执行本地预览”后操作地图或图表 |
选中调查任务时,通过只读 `GET /api/v1/operational-tasks/{task_id}/presentation-events` 分页读取该任务保存的展示事件,并载入左下列表;同时载入本轮最新报告中已保存的有效界面块。已完成任务、关闭实时跟随时也可读取。历史报告仍在任务详情可读。开启跟随或重连时先建立固定事件游标,载入不超过该游标的历史,期间到达的新事件暂存,历史完成后再顺序消费,避免间隙或重复。“载入当前报告”加载该任务最新保存的报告界面块,供本地检查,不重新发布报告。
Dev 与工况详情共用右侧工具位置,切换调查时先关闭 Dev 回到任务列表,再打开 Dev 检查新的选择。实时展示面板位于地图左下方,打开 Dev 后仍可看见。新图表进入其滚动区时会滚动到图表,保留标题;手动收起面板后仍接收指令,展开再查看。切换项目、调查或执行代次会清理临时效果并取消未完成的本地预览。上述清理保留本次页面会话内的动作快照,只有切换项目会同时清空历史。已绑定调查时关闭跟随也会清理该调查的当前临时展示;未选择调查的本地预览不受跟随开关影响。面板外仍可操作地图,手动拖拽或滚轮暂停镜头自动跟随。
## 本地测试步骤
1. 在默认展开的“调查测试”页签准备数据。“载入合成样例”在当前地图中心生成合成空间展示、压力曲线、候选表格和一条候选数据;所选调查进度存在地图目标时,另加入该目标的高亮测试。所有合成结果均有明确标记。
2. 可选:点击“校验 JSONL”单独查看识别出的展示指令、界面块、调查数据数量。也可直接执行本地预览,执行入口会自动校验当前全部内容。
3. 点击“执行本地预览”,自动校验通过后对照地图和左下展示面板中的图表、结构化界面与数据摘要;Dev 的“原始数据检查”可点击对象查看原始行内容。动作记录区分“实时指令”和“本地测试”,显示应用或失败结果。
4. 按需“下载测试 JSONL”保存当前已校验输入;“清除临时展示”清除当前浏览器的高亮、图表和覆盖层。测试不改变服务端事件游标,不发起调查、审批、工单或设备写入。
样例与导出仅存在当前页面或用户下载的文件中,不写 Agent 工作区,不伪造已保存证据。Dev 不会自动枚举 Agent 生成的本地文件;要检查已有 JSONL,可将通过受控入口取得的文件内容粘贴到编辑区。当前最多 200 KB、40 行、8 个界面块;地图与图表继续遵守原展示协议的数量、几何及序列约束。
## 可切换测试案例
“JSONL 测试案例”选择框不依赖调查选择;地图就绪后即可切换并载入内容,显示该案例的预期结果。本地预览无需选择调查或开启跟随,表格、卡片、数据摘要、图表与范围统一在地图左下方的“本地预览展示”中显示,Dev 只保留输入、校验、原始数据检查与执行记录;“载入合成样例”重新生成当前案例,尚未选择时载入组合联动。修改输入会重置案例选择与校验状态,仍可继续手工测试。“载入当前报告”继续加载所选任务已保存的界面块。
| 案例 | 核对内容 |
| --- | --- |
| 组合联动 | 地图点、调查现有目标高亮、压力曲线、候选表格与数据 |
| 地图定位与高亮 | 有目标时高亮真实关联目标;无目标时只显示合成点,不虚构资产查询编号 |
| 压力趋势对比 | 两条合成压力曲线、时间轴、单位与图例 |
| 影响用户统计 | 合成用户数柱状图,不作为真实停水统计 |
| 合成影响范围 | 当前地图中心附近的合成 Polygon |
| 投诉热力分布 | 三个具有非负权重的合成投诉点 |
| 候选管段对比 | 合成候选表格及两条 candidate 数据,不查询虚拟管段 |
| 隔离阀门清单 | 合成阀门表格及两条 valve 数据,不执行关阀 |
| 纯 JSONL 数据 | 只显示数据;内嵌 action 字段不作为动作执行 |
| 错误:JSON 语法 | 第二行语法错误时整批拒绝,不执行第一行合法动作 |
| 错误:不支持的动作 | 拒绝协议未支持的动作 |
| 错误:图表数据不齐 | 拒绝时间轴和序列长度不一致的图表 |
切换前若执行过本地预览,会先清除它的当前临时地图、图表和业务结果,保留动作历史供回看;仅选择或编辑 JSONL 不执行新指令。有内容时即可点击“执行本地预览”,无需先点单独校验;每次执行都会重新校验当前全部输入。任何一行错误都会拦截整批,显示具体错误,不执行部分指令;地图尚未就绪时也显示原因。仅空输入或正在执行时禁用按钮,不以调查选择或实时跟随作为本地执行前提。测试不会写入 Server、重启调查或发送 Agent 对话。案例定义位于 [investigation-dev-cases.ts](../src/features/workbench/utils/investigation-dev-cases.ts)。
## JSONL 格式
以下每行都是独立对象。第一行只在点击执行后清理本地高亮;第二行预览合成说明;第三行仅为候选数据,不触发高亮、定位或计算。
```jsonl
{"record_type":"presentation","command":{"action":"clear_highlights"}}
{"record_type":"ui_block","evidence_refs":[],"block":{"version":"answer-ui@1","block_id":"dev-note","fallback_text":"本地合成格式示例","spec":{"root":"note","elements":{"note":{"type":"Text","props":{"text":"本地合成格式示例,不代表调查成果。","tone":"warning"},"children":[]}}}}}
{"record_type":"candidate","origin":"synthetic","source_evidence_refs":[],"element_id":"DEMO-PIPE-01","status":"example_only"}
```
仓库内的可复制数据示例为 [unified-presentation.jsonl](../tests/fixtures/unified-presentation.jsonl),覆盖十种 command、一个 `phase: final` 界面块和带来源的普通数据行;`P1` 是浏览器测试夹具中的测点,业务项目应使用已核实的实际编号。内置案例从同一个记录生成器输出,并在生成时通过当前校验器。错误案例单独保留,专门验证拒绝行为。
每行必须显式使用 `record_type: presentation`、`record_type: ui_block`,或带来源的调查数据类型。裸 command、裸 `answer-ui@1` block 和旧 chat 的 name/params 格式均拒绝。展示指令统一接受 `locate_features/zoom_to_map/highlight_features/clear_highlights/open_chart/close_chart/set_overlay/clear_overlay/render_scada_analysis/clear_scada_analysis`,不能加入项目、运行身份、URL、脚本或任意命令。Dev 的覆盖层样例直接提供合成几何,仅用于本地渲染测试;任务 Agent 的 `set_overlay` 可只传证据编号,由 Server 提取几何;传入 data 时必须与保存的证据快照一致。Chat 和 Dev 执行已提供并校验的 data。不能把 Dev 格式当成 Server 写入接口。
数据行需要 `record_type`、`origin`、`source_evidence_refs`,其余字段按实际内容保留。`origin` 接受 system_data、synthetic、derived、human_input,仅说明本地数据来源,不构成 Server 证据认证。显示合成表格不等于运行过定位或完成现场处置。
## 验证范围
聚焦测试:
```bash
pnpm exec vitest run src/features/workbench/utils/investigation-dev-preview.test.ts src/features/workbench/components/map-dev-panel.test.tsx src/features/workbench/hooks/investigation-presentation-follower.test.ts
PLAYWRIGHT_PORT=5194 pnpm exec playwright test tests/browser/investigation-dev-tools.e2e.ts tests/browser/floating-panel-pointer.e2e.ts --workers=1 --reporter=line
```
浏览器用隔离 API/SSE fixture 验证所选任务到真实 MapLibre/React 展示的消费链、Dev 开启与收起、JSONL 校验和下载、任务切换清理、紧凑窗口及面板外地图输入;不调用付费模型或真实工单、设备接口。真实 Agent 是否发布了正确的事件、报告或 JSONL 文件,仍需按实际项目运行记录核对。
## 统一展示动作
Chat 使用 `present_view({command, reason})`,在线通过 SSE 的 `tjwater.frontend_action` 承载 `frontend-action@2`,动作字段为 command,不再接收 name/params。浏览器回传 `frontend-action-result@2`。任务事件和 Dev JSONL 的 command 使用相同结构,并进入同一执行器。Chat、调查和 Dev 预览分别拥有地图源、SCADA 图层及图表状态;清理、切换会话和切换任务不会误清其他入口。Chat 动作按接收顺序执行,切换会话取消正在执行及排队动作;过期动作不会执行。任务仍只记录发布状态,不等待浏览器。查看历史回答不会重放动作。
动作 schema 的维护源是 `src/features/agent/presentation/command-schema.ts`。修改后在前端仓库运行 `node scripts/export-view-command-contract.mjs`,同步 Agent 主机/原生工具共用的 TypeScript schema 和 Agent/Server JSON Schema;运行同一命令加 `--check` 检查一致性。Server 任务入口继续执行证据归属和快照校验。
## 已有案例与示例迁移
仓库内正向示例统一使用以下格式;测试输入中的旧格式仅用于明确的拒绝用例。
| 内容 | 当前格式 |
| --- | --- |
| 地图、图表和 SCADA 动作 | `{"record_type":"presentation","command":{"action":"动作名",…}}` |
| 图表动作 | `open_chart`,图表数据位于 `command.chart`,明确提供 `chart_id` 和 `evidence_refs` |
| 结构化界面 | `{"record_type":"ui_block","block":{"version":"answer-ui@1","block_id":"…","phase":"final",…},"evidence_refs":[]}` |
| 调查数据 | 保留 `record_type/origin/source_evidence_refs`,不把内嵌 action 提升为指令 |
| Chat 调用 | `present_view({command, reason})`,不再调用旧的独立展示工具 |
本轮迁移只覆盖仓库内的内置案例、夹具和文档示例,未修改历史会话、数据库或外部下载文件。没有增加运行时旧格式转换。
## 展示动作历史
调查实时展示按所选任务读取 Server 已保存的展示动作,各任务的历史在浏览器中分别保留、切换时按任务展示。对话展示和本地预览展示继续保留当前项目、本次页面会话内收到的动作。清除类动作不纳入历史。展示面板的“切换展示动作”以最新优先倒序排列,“当前(最新)”始终置顶,动作编号保留发生顺序。可选择任一已完成、未完成或取消的动作,也可用上一步/下一步逐步回看;进行中的动作显示状态但不可选择。“回到当前”恢复最新展示。 当前结果与最后一条已完成动作相同时,合并显示为“当前(最新)”,下拉和前后导航不再重复这一项。清理后当前结果与最后快照不同,最后一条仍作为历史结果可选。切换任务、切换案例、关闭图表和清除当前展示都会保留历史;切换项目或刷新页面后清空浏览器缓存,重新选择调查任务可再次读取 Server 保存的事件。不设最近若干条的截断。载入和回看不向 Server 发布事件,不重启调查、审批或现场操作;重复选择同一任务按任务编号和事件序号去重。
本地快照保存图表、界面块、数据、证据摘要、地图几何及镜头。Server 历史保留原发布指令和空间证据快照;只有要素编号的旧定位指令在首次载入时按当前项目读取可访问几何,不声称这些是历史时刻的资产位置。载入后回看使用本地快照,不重复查询。上一轮结果可作为历史查看,不混入本轮当前状态。单条过期或不合法指令显示失败记录,其他有效结果继续载入。历史导航直接渲染快照,不重新查询资产、执行原指令或发送调查请求。关闭图表、显示/隐藏及定位覆盖层、界面块关联要素定位等操作会产生记录;清除临时展示、清除地图展示,以及 `clear_highlights/clear_overlay/clear_scada_analysis` 指令只更新当前状态,不创建历史条目,已有结果快照仍保留;地图手动拖拽和证据展开属于查看操作,不逐帧记录。记录不是完整底图或外部实时数据的离线副本。
回看期间,新动作继续更新“当前”,面板保留正在查看的历史并提示后续动作数。“回到当前”恢复这些最新结果。历史画面禁止关闭图表、修改覆盖层和发起新的关联要素查询,仍可查看依据、检查表格并定位已有覆盖层。地图与界面使用已有过渡,并尊重减少动画设置。Dev 原始数据检查对应编辑器最近一次执行的输入,不随展示历史切换;历史结果及快照以展示面板为准。
历史接口按 `after`、`through` 游标和 `limit` 分页,返回 `task_id/event_cursor/items/next_after`;客户端固定首次授权游标,不截断为最近一页。Server 按项目、任务及展示事件类型读取现有事件日志,不需要新增数据表。新接口需与前端一起发布;测试覆盖的是当前源码的服务/仓储/API 单元检查与浏览器模拟 API 联动,未替代真实项目验收。
+115
View File
@@ -0,0 +1,115 @@
# 非地图面板整理
2026-09-17,范围限供水前端,不改变地图业务、OpenCode、数据库表或环境配置。
## 视觉与交互
沿用现有浅色阅读面、Noto Sans SC 中文字体、蓝色操作强调和状态徽标。优先修复可读性、对齐和窄屏裁切,不引入第二套主题、字体或组件库。
- `FieldSelect` 复用现有 Radix Select:统一标签、40px 最小高度、长选项换行、禁用态、键盘选择和弹层层级。清空受控值后回到占位提示,不触发额外业务动作。
- `Checkbox` 保留原生输入与标签语义,统一勾选、焦点和禁用样式。反馈确认仍须用户主动勾选。
- `Disclosure` 保留原生 details/summary 语义,统一展开箭头、焦点和点击区域。
- 调查目标和外围历史回放的日期字段单列展示,避免窄面板内日期与时分被裁切。两处均已使用共享自定义日期时间弹窗,保留各自本地时间/UTC 的业务语义。
- 手机端 Agent 欢迎区改为紧凑横排,避免被底部输入区遮挡。
- 桌面成果专注视图为 Agent 折叠栏预留空间,标题不再被覆盖,仍可重新展开助手。
- 成果图表显式使用页面的中文字体栈。此前 ECharts 画布仍以 `11px sans-serif` 绘制中文图例,在测试环境显示方框;浏览器画布探针已验证修复前失败、修复后在 1280/375px 通过,截图可见完整“调度下限”。源码只有这一处 ReactECharts 入口。
## 检查覆盖
| 面板 | 本次检查 |
| --- | --- |
| 调查任务、生命周期、运行与历史结果 | 表单、确认区、折叠内容、长标识、320/375/1280px |
| 已保存比较结论、Evidence 查看 | 四分支、加载/空/错误态、只读重试、键盘下拉、320/375/1280px |
| 外围样板、模拟数据、历史回放 | 下拉、日期、状态徽标、任务历史、375px |
| 反馈关联、人工复核 | 确认勾选、展开内容、禁用与只读边界、窄屏 |
| Agent 对话与历史 | 桌面抽屉、320/375px 欢迎区与滚动容器边界 |
| 工况列表与详情 | 375px 抽屉布局 |
| 成果预览与文档 | 1280/375px,桌面标题与折叠栏几何边界 |
| 图层、测量、标注、更多、开发面板 | 非地图浮层边界,开发面板表单控件统一 |
实际要素详情使用地图上的 `FeaturePopover`;未接入运行入口的 `FeatureInsightPanel` 已在冗余清理中移除。
## 验证与限制
最终代码检查:`pnpm typecheck`、`pnpm lint`、全量 68 文件 / 350 项 Vitest、`pnpm build` 通过。生产构建仍提示部分 chunk 超过 500kB,本次未扩展打包优化范围。调查/反馈/外围/比较/生命周期的 29 项与非地图布局的 5 项专项浏览器用例通过,比较区新增的弹层不透明度和背景色检查另行重跑 6 项通过。非地图布局用例同时覆盖开发面板键盘选项和成果图表画布字体。
浏览器用例使用显式模拟接口,不代表真实账号、Agent 和 PG 的全链路验收。主要回归在 `tests/browser/non-map-panels-layout.e2e.ts`、`run-comparison.e2e.ts` 及既有调查、反馈、外围与生命周期测试中;截图保存在忽略的 `test-results/non-map-panels/`、`test-results/run-comparison/` 等目录,不作为发布资源。
本次也运行了完整浏览器套件,当次为 66 通过、33 失败,不能宣称全量通过。已确认的失败包括旧用例依赖 Agent 初始展开或已不存在的“工作台导航”、旧截图基线,以及新移动用例当时选择器不唯一。后者已改为语义化 `role=log` 并在专项回归中通过;其他旧用例与真实地图依赖仍需单独梳理,不通过修改产品默认行为或批量更新截图掩盖失败。
运行内容来自现有接口,无需手动替换界面占位数据。人工验收时请在桌面全宽与 375px 下检查长任务名称、日期输入、下拉键盘操作和成果标题。
## 后续交互回归
继续核查旧失败用例时发现并修复了两处真实缺陷:
- 窄桌面展开工况详情会自动收起 Agent;此前聊天草稿存在被卸载的面板内部,重新展开时丢失。现在由稳定的工作台 hook 持有草稿,桌面和手机面板共享受控值,新建会话仍清空。此状态只在当前页面内保留,不是刷新后的持久化草稿,也没有新增存储层。面板仍可卸载,避免为了保留文字让隐藏的语音控件继续活动。
- 新增调查/外围入口后,1536px 顶栏的异常处置与调查按钮发生重叠。现在保留按钮宽度、收紧组间距,仅在 1800px 以上展开次要按钮文字;较窄桌面省略模型只读提示,完整操作名称仍通过无障碍标签提供。手机标题显示短称“供水”,而不是省略号。
`workspace-main-frame.e2e.ts` 现在验证默认收起、主动展开后的相邻布局、收起恢复、成果 split/focus 切换,并检查 320/375/1024/1280/1440/1536/1600/1800/1920px 顶栏按钮不重叠、标题不截断。顶栏几何断言修复前失败,修复后通过。截图位于 `test-results/workspace-regression/`。
`agent-voice-hydration.e2e.ts` 与 `agent-panel-resize.e2e.ts` 改为先通过真实按钮打开助手,再检查语音、几何和草稿状态;不再假定 Agent 初始展开或折叠后保留旧版 72px 导航宽度。工况自动收起场景使用其实际适用的 1280px 宽度,保留了未发送草稿不丢失的断言。布局测试按实时几何等待入场动画完成,不固定动画中途的坐标,也没有加入固定 sleep。
该轮完整浏览器套件为 79 通过、21 失败,共 100 项。仍有旧导航/默认展开假设、截图基线与动画时机相关失败,不能宣称全量通过,也未批量更新基线。
## 调查任务日期时间补充
根因是原先只统一了 `datetime-local` 输入框外观,其日历和时间弹窗仍由浏览器绘制。调查任务的开始、结束时窗已替换为共享 `DateTimeField`:沿用浅色面板、蓝色选中态和现有 Radix 弹层/下拉,不引入新依赖。
- 日历、月份、年份、小时和分钟均在应用内绘制,窄屏弹窗限制宽高并允许纵向滚动。
- 点击确认才更新值,取消或 Esc 放弃草稿并将焦点返回字段;日历支持方向键和 PageUp/PageDown。
- 年份编辑保持输入焦点,支持闰年和真实月份天数;无效源值不会被静默截断后保存。
- 已关闭任务不可编辑。组件仍输出本地 `YYYY-MM-DDTHH:mm`,原有目标保存逻辑负责转换 UTC,不改变业务时区语义。
- `date-time-field.test.tsx` 覆盖组件边界。
调查任务两个日期字段均已替换;同类的外围历史回放已在后续批次统一,见下节。
补充后的验证:`pnpm typecheck`、`pnpm lint`、69 文件 / 357 项单元测试和 `pnpm build` 全部通过;日期时间、调查面板、非地图布局、运行控制及任务生命周期的 20 项浏览器回归通过。生产构建仍有既有大 chunk 提示。上述浏览器检查使用模拟接口,不替代真实系统验收。
日期回归用例做过红绿验证:临时将调查时窗重新接回原生 `datetime-local`,确认/提交用例因缺少自定义字段入口失败;恢复 `DateTimeField` 后重新运行全部 3 项日期用例通过。代码未提交。
按用户要求,每轮 Playwright 结束后检查其浏览器和临时 Vite 服务是否退出,不关闭用户已有的 5173 开发服务。
## 外围历史回放日期补充
外围面板的 `HistoryTime` 同样仍由浏览器绘制日期时间弹窗,已删除该包装并复用 `DateTimeField`。保留“开始(UTC)/结束(UTC)”标签和原来的 UTC 查询拼接,不套用调查任务的本地时间转换。扫描 `src/` 已无原生 date/time/datetime-local 输入入口。
`peripheral-sample-panel.e2e.ts` 新增实际交互断言:修改起止日期时间后只有点击“读取历史读数”才发送 GET;浏览器为 Asia/Shanghai 时,08:15 仍按 08:15Z 查询;取消不改值、不发查询,也没有任何外围写请求。320/375/1280px 弹窗边界与无横向溢出通过,截图位于忽略的 `test-results/peripheral-datetime/`。
红绿验证:替换前该用例因缺少自定义日期入口失败,替换后外围面板、调查日期时间、反馈导入共 14 项浏览器测试通过。类型检查、Lint、69 文件 / 357 项单元测试与生产构建通过,构建仍提示既有大 chunk。仍使用模拟接口,不代表真实外围服务验收;完整浏览器套件的失败不因本轮专项通过而视为消除。
## 问答与流式测试入口修订
重新运行确认旧问答/流式用例默认寻找尚未展开的 Agent 输入框;显式展开后还暴露了授权项目模拟缺失。请求失败探针记录 `/api/v1/projects` 连接拒绝,Agent 客户端因此未进入回复与模型查询。现在使用明确的测试运行配置和已有项目/SCADA mock,不改产品授权流程;临时日志已移除。
流式用例另外仍断言旧浮动简报和浮动输入区。当前 `desktop-dock` 分支将简报和输入区放入正常布局,已改为验证简报在对话区上方、输入框在滚动区域下方、分析中操作禁用及区域不重叠;进度窗口几何采样、计划卡片、结束滚动、保持展开、选中文本朗读等原断言仍保留。问答回复的精确请求号与 payload 断言未放宽。两个文件共 3 项重跑通过,其中问答桌面和流式用例此前失败。
本轮最终完整浏览器套件:103 项中 85 通过、18 失败,耗时 2.7 分钟。失败分布为 `app.e2e.ts` 4 项、`agent-acrylic.e2e.ts` 4 项、开发面板/地图通知/移动转桌面/窄桌面工况/地图相机稳定性各 1 项、视觉基线 5 项。不得将全部失败归因于旧断言,仍需逐项核查实际行为。此前工况动画时机失败在本轮未复现,未作修复,仍作为时序风险保留;问答与流式是本轮明确修订后通过的两项。完整结果与失败上下文位于忽略的 `test-results/non-map-followup-full/`。
## 历史菜单、Esc 分层与全量回归收尾
继续核查上述 18 个失败后,确认并修复了以下真实行为问题:
- 手机 Agent 内的 Radix 模型菜单和权限模式菜单已处理 Esc,并将事件标记为 `defaultPrevented`,但外层 `MobileWorkbenchSheet` 的 window 监听仍无条件关闭抽屉。外层现在只处理未被内层消费的 Esc。模型和权限菜单各自关闭后,焦点返回原触发按钮;没有内层菜单时,Esc 仍关闭抽屉。
- Dev Panel 有相同的事件分层缺陷。`FieldSelect` 打开时第一次 Esc 只关闭选择菜单并返回焦点,第二次 Esc 才关闭开发面板。
- 手机端已打开 Agent 时跨越 1024px 进入桌面,原逻辑先清空移动抽屉状态,导致用户打开 Agent 的意图丢失。现在先将移动 Agent 状态迁移为桌面展开状态,再清空移动抽屉。
- Dev Panel 打开时,地图工具栏仍在面板下面渲染。现在开发面板显示期间不挂载桌面地图工具栏与其工具面板。
- 1024px 下展开工况任务会自动折叠 Agent,但 880px 工况面板与 72px 折叠栏重叠 4px。布局变量现显式记录折叠栏宽度,工况面板在该宽度下收敛到 852px,二者保留 24px 间距。
同时修正了三类失真的回归断言。地图容器变宽或变窄时,MapLibre 的 `resize()` 会发出 `movestart`,但经纬度、缩放、方位角和俯仰并未改变;相机稳定性用例现在直接比较这五项参数。地图通知位置测试改用确定会生成通知的“操作参考”入口。工况材质测试等待入场动画结束后再读取 transform 和 will-change,不再采样动画中间帧。焦点、几何和业务请求断言均保留。
320px 与 375px 的模型菜单截图位于 `test-results/agent-history-ui/320-model-menu.png` 和 `375-model-menu.png`,长标题重命名截图位于同一目录。模型名称、说明和菜单边界完整,权限模式、模型、语音和发送控件没有重叠。五张过期的工作台视觉基线经逐张检查后更新,覆盖桌面浅色/卫星底图、1920px Agent 收起状态、手机启动器和手机 Agent 半屏;手机工况卫星图无需更新。视觉用例更新后再次无更新参数运行,6/6 通过。
最终验证结果:`pnpm typecheck`、`pnpm lint`、69 文件 / 357 项 Vitest、`pnpm build` 全部通过。构建继续报告既有的 500kB 以上 chunk 提示,CSS 校验和 TTS bundle 通过。完整 Playwright 套件为 104/104 通过,耗时 2.4 分钟,结果位于忽略的 `test-results/non-map-followup-final-green/`。这些浏览器用例仍使用模拟接口,不替代真实账号、Agent、PG 和外围服务的全链路验收。
## 新增业务组件统一设计
2026-09-18 对调查任务与外围样板的新组件完成统一重构。现行规则见 [样式设计指南](style-design-guide.md),视觉方向是浅色专业调度台,保留地图为主工作区,并将侧栏内容稳定为“定位、状态、下一步、证据”的阅读顺序。
- 新增 `WorkbenchSection`、`WorkbenchNotice` 和 `WorkbenchEmptyState`,统一标题、状态、提示和空态,减少同级彩色卡片与大面积空白。
- 生命周期确认、定时计划、目标编译、运行控制、运行对比、人工复核和 Evidence 导入统一状态语言与操作层级。
- 外围样板将连接与场景、历史回放、待提交来源、已有任务放在前面;测试工单、测试数据和 request_id 查询移到辅助区并默认折叠。外围工单统一按系统数据处理。
- `FieldSelect`、`Checkbox`、`Disclosure` 和 `DateTimeField` 统一焦点、hover、按压和禁用反馈。日期时间弹层继续支持 Esc 取消并返回焦点。
- 数据表使用等宽数字并将数值右对齐;320、375 和 1280px 下均无横向溢出。
本轮最终检查为 `pnpm typecheck`、`pnpm lint`、76 文件 / 395 项 Vitest 和 `pnpm build` 通过。新增组件相关的 17 文件 / 118 项单测通过,核心业务面板 Playwright 为 31/31 通过。完整浏览器套件共 110 项,并发运行 108 项通过;2 项在等待 Toast 退出时超过 15 秒,随后单进程精确复跑 2/2 通过。截图位于忽略的 `test-results/task-lifecycle/`、`run-control/`、`run-comparison/`、`peripheral-datetime/` 和 `/tmp/feedback-*.png`。
+54
View File
@@ -0,0 +1,54 @@
# 工作台项目切换
2026-10-21:新增用户菜单内的项目切换,首批核对 `tjwater_v2` 与 `fengyang_v2`。
## 启动与加载状态
身份认证和授权项目加载共用启动界面:左对齐平台标识与标题,中性浅色表面和宝石蓝状态标识。认证阶段显示“检查登录状态”;项目阶段依次显示“读取授权项目”和“准备项目环境”。项目列表返回后才将第一步标为完成,并显示实际选中的授权项目名称;项目配置与访问上下文返回前不挂载工作台,不用计时器或百分比模拟进度。
加载中提供图形反馈和文字说明,系统开启减少动态效果时停止旋转。失败后移除加载状态,展示错误原因和单一重试操作;项目重试回到读取列表阶段,认证重试重新连接。桌面与手机使用同一组件,长项目名和错误信息自然换行。外观与组件选择遵循 [样式设计指南](style-design-guide.md)。
## 用户入口与选择规则
打开右上角用户菜单,点击“切换项目”进入弹窗。弹窗恢复中性乳白亚克力表面、小型平台标识、左对齐标题、当前项目说明和通栏“进入项目”按钮的布局。弹窗与下拉浮层使用 82% 中性白色亚克力底色,沿用模糊、噪点和边缘高光;遮罩保留轻微压暗与 3px 背景模糊。降低透明度或不支持背景模糊时回退为不透明白色。选择框与禁用按钮使用中性白色表面和低对比灰色边框;主按钮和选中态恢复工作台宝石蓝。
共享 Select 下拉列表显示项目名称与当前使用标记,选择区补充可用状态,后端返回角色时显示中文角色。首次打开和重新打开弹窗时,焦点显式落在“项目环境”选择框,不自动展开列表;Tab 与 Shift+Tab 保留正常焦点顺序。点击主按钮后才提交切换;选择相同项目时主按钮禁用。关闭按钮或 Escape 关闭弹窗并恢复用户菜单按钮焦点。下拉列表只列出后端授权列表中的活动项目;弹窗及下拉浮层覆盖地图工具栏,适配 1440、375 和 320px 视口。
动效使用 `motion/react`:遮罩淡入淡出,弹窗以 8px 位移进入并保留退出动画,项目列表以 4px 位移展开;键盘操作和系统“减少动态效果”设置下即时呈现。列表关闭后直接恢复选择框焦点并保留蓝色焦点边框;弹窗容器不显示浏览器默认 outline,避免选择项变化时焦点临时回落导致黑边。下拉外层只负责裁切,实际滚动统一由 Radix Viewport 管理,避免 4px 入场位移触发外层滚动条;长列表仍支持滚动与键盘定位。
浏览器保存最近一次成功选择的项目 ID。刷新后先重新加载授权列表,只有仍在列表中的 ID 才会恢复;否则使用部署默认工作空间对应的授权项目,再退到列表中的首个项目。项目查询失败显示重试入口,不凭本地存储获得权限。
切换前查询目标项目元数据和访问上下文,两者均通过项目 ID 核对后才提交选择。失败时保留原工作台、弹窗和目标选择,并显示错误提示;请求期间禁用选择与关闭操作。切换只改变浏览器正在查看的项目,不取消服务端工况任务。
## 数据与生命周期
`project-workbench.tsx` 持有唯一选中项目。它将 `WorkbenchRequestContext` 传入工作台,其中包含项目元数据、认证令牌提供器以及已取得的展示信息。现有 API 参数名 `getAccessToken` 为兼容保留,类型 `WorkbenchAccess` 同时接受旧认证提供器和显式项目上下文;主应用始终传显式上下文。
地图瓦片、WFS 定位与可用图层探测读取当前项目的 `gs_workspace`。SCADA、实时流量、运行态、事件流、任务、成果、GIS 属性与 Agent 项目会话读取同一个项目 ID。业务请求继续由后端通过 Bearer 与 `X-Project-Id` 校验权限。
项目 ID 作为工作台 SWR 边界的 React key;切换时新建业务缓存并重新挂载工作台,清理地图选择、报告、绘图和旧业务订阅,当前 Agent 视图进入新项目的空会话。登录级资源位于该边界之外,保留按归属隔离的历史、推荐、项目列表缓存和后台 Agent 会话;原会话生成、草稿及阅读位置继续由其会话实例持有。实现依据 [React 状态重置](https://react.dev/learn/preserving-and-resetting-state) 与 [SWR 缓存提供器](https://swr.vercel.app/docs/advanced/cache)。地图销毁后,绘图及要素交互不再访问旧样式;异步设施与 SCADA 图片注册受地图生命周期 AbortSignal 约束。
## 凤阳的数据边界
凤阳使用已有的 `fengyang_v2` 工作空间及元数据地图范围。固定奉贤演示工况、场景与空间覆盖不会在凤阳兜底显示。奉贤原始 GIS 图层不复制,图层入口根据当前工作空间中的实际数据探测。
地址定位支持文字搜索及地图取点反编码,两者复用当前项目的配置与服务端 Key。取点结果保留点击坐标,关闭工具或切换项目取消未完成查询。地名搜索读取 Metadata DB 的 `projects.map_config.place_search`,按当前项目的 `enabled`、`provider`、`admin_code` 和 `region` 启用查询并显示区域文案。奉贤、凤阳和其他项目使用同一实现;未配置、关闭或配置无效时显示“当前项目暂未配置地名搜索”。区域由后端从授权项目读取,浏览器不能在搜索请求中覆盖行政区。外围样板服务仍有独立项目配置;本次复制其空表结构,不复制奉贤工单,也不扩大外部服务的访问范围。
## 验证
```bash
pnpm lint
pnpm typecheck
pnpm test
pnpm build
pnpm test:browser tests/browser/project-switching.e2e.ts tests/browser/project-presentation-backend.e2e.ts --workers=2 --reporter=line
```
浏览器覆盖用户菜单切换、地图工作空间、业务与 Agent 请求项目、元数据视角、刷新恢复、切回原项目及目标访问失败;同时检查切换期间无页面异常。浏览器接口使用隔离测试数据,不代表生产身份登录验收。
数据库补齐方法与备份记录见 Server 仓库的 `docs/workbench-database-rollout.md`。
## 项目列表缓存
授权项目列表按当前登录的凭据提供器隔离,内存缓存 5 分钟,分页结果完整合并后缓存;并发读取复用同一请求,单个消费者退出只取消自身等待。窗口直接展示已加载项目,有效期内反复打开不会重新查询。目标项目进入操作继续核验其元数据及访问上下文,复用这次已验证的展示信息,避免工作台挂载后再次读取相同上下文。缓存不替代业务接口授权,退出登录清理本次登录缓存。
+10
View File
@@ -79,3 +79,13 @@ pnpm build
- 不要移除 Strict Mode 延迟初始化,除非重新验证开发和生产生命周期。
- 更新 Rive 版本时,至少验证单次 `.riv` 请求、状态机切换、页面切换后的实例清理和
30 秒以上的浏览器进程内存趋势。
## 2026-10-21 原版恢复后的现状
Agent 入口使用基于原版 Obsidian 定制的冰水蓝资源。继续保留 Strict Mode 延迟初始化、按可见性挂载和禁止 View Model 绑定;配色直接写入资源,不应用旧版的 brightness / contrast 滤镜。`persona-resource.ts` 在页面内存与浏览器 Cache Storage 中缓存动画字节,按内容版本更新,不共享 Rive 实例或 View Model。
业务离线由本地 `obsidian-water-v1.riv` 的 `asleep` 状态播放内部缓慢水纹并关闭外围光圈,在线/离线切换保留同一实例。减少动态效果、加载和失败时显示从当前资源渲染的 `obsidian-water-idle.png` 或无光圈的 `obsidian-water-offline.png`。隐藏和减少动态效果会卸载实例,不通过 CSS 同时隐藏多个仍运行的 Persona。资源改造见 [Agent 动画资源说明](agent-persona-resource.md)。`hover` 输入由外层交互控制,Rive 自带的 DOM 监听关闭,避免和原生入口按钮及触摸操作重复响应。
回归验证已覆盖原始字节缓存、失败后的重试、无 View Model 绑定、原生状态及 hover 切换、真实 canvas 动画和桌面/手机单实例。
独立原版 / 接入版预览进行了 35 秒浏览器渲染进程 RSS 观察:约 193.3 MiB 至 177.2 MiB,未观察到持续增长。该结果仅覆盖本地短时对照预览;本轮没有重新引入 View Model 绑定,也未更新 Rive 版本。
+201
View File
@@ -0,0 +1,201 @@
# 样式设计指南
供水前端统一以本地 shadcn/ui 为组件基础,使用 Tailwind CSS、共享变体和语义变量。Agent 相关弹窗、面板与菜单,以及 Dev 测试面板、外围系统面板、调查与本地预览展示面板保持 shadcn/ui 设计;其他地图控件与工作台浮层使用本文规定的 Acrylic 视觉。适用于工作台、地图控件、Agent、报告、表单和弹层。
本文是唯一的样式规范。业务交互见 [Agent 交互与报告设计](agent-chat-ui-design.md),状态含义见 [状态语言](status-language.md)。本文规定统一目标;历史局部配色和样式覆盖需在后续组件修改中逐步对齐,文档合并不代表运行样式已全部迁移。
## 1. 组件基础
- 优先复用 [src/shared/ui](../src/shared/ui/) 的本地组件;缺少能力时,按需引入与现有 Radix 技术栈匹配的 shadcn/ui 源码,再做样式适配。
- shadcn/ui 提供组件结构与组合方式,Radix 提供相应的基础交互。定制外观时保留语义、键盘操作、焦点管理、禁用和加载行为。
- 业务模块组合共享组件,负责数据、权限和动作;共享组件保持通用。AI Elements 用于聊天展示组合,与 Agent 的 shadcn/ui 组件使用同一套主题变量。
- 不批量覆盖已有组件,不引入第二套 UI 或样式体系。使用 CLI 前先核对 `components.json`;配置继续指向 Vite、TypeScript、Tailwind 4、`@/shared/ui` 和 `@/shared/ui/cn`,关闭 React Server Components。
- 界面图标统一从 `lucide-react` 按名称引入,使用其默认 2px 描边,不复制图标 SVG 路径或用字符替代操作图标。常规控件图标为 16px,紧凑说明可用 12px 至 14px;图标尺寸与按钮命中区域分别设置。图标按钮提供中文可访问名称,装饰性图标使用 `aria-hidden`。
- 界面动画统一使用 Motion,React 动画组件与 Hook 从 `motion/react` 引入,覆盖入场、退出、位置与布局变化及交互过渡。尊重 `prefers-reduced-motion`,减少动态效果时关闭非必要动画;连续拖拽调宽不附加布局动画。
- 保留本地 shadcn/ui 组件自带的基础动效,避免重复叠加。`AgentPersona` 等已有 Rive 专用资源动画继续按其功能文档维护,Motion 不替代资源内部的状态机与动画。
### Agent 弹窗与面板
回答正文与注意事项、表格等结构块之间使用 20px 的布局间距。Markdown 复制容器使用 `display: contents` 时,不使用直接子元素 margin 实现这段间距,避免间距丢失。
回复生成期间只在正文左侧显示一处“正在回复”状态,状态组与正文左边缘对齐;不再在空正文中重复显示“正在生成”。
过程切换为正式结果时,先将旧内容淡出,再统一切换正文、过程归档与底部操作,最后淡入结果,整体约 200ms;只改变透明度,不对长内容高度做插值。切换期间保护阅读锚点,用户滚动或操作后停止自动位置补偿。系统要求减少动态效果时直接交接,仍保留阅读位置和工具展开状态。
面板头部使用紧凑字号:助手名称为 14px/20px,在线状态和主题选择为 12px/16px,保留原有按钮点击区域。对话中的用户消息、回答正文与输入文字为 16px,消息正文与输入行高为 28px;回复状态、依据轮次、输入引用、协作标签及操作文字为 14px,说明行高为 20px。引用标题通过字重区分,说明与标题间隔 4px。输入框顶部不重复显示等待回答的常驻提示,提问与继续状态由对应提问卡片呈现。
起始推荐问题及其加载、失败提示统一使用 14px/20px、常规字重,窄屏下允许完整换行。
输入框按上方引用、中间编辑、下方工具栏排列,外壳使用 22px 圆角和轻边框。任务引用使用无独立底色的紧凑行,引用图标为 14px,文字为 14px/20px;任务名称与轮次、报告版本放在同一文字流中,窄屏在完整短语之间换行。上下内边距各 4px,不在输入底栏重复显示“任务协作问答”标签。内容引用复用紧凑行,原文与分析方向按需展开。权限、模型和消息发送方式的下拉入口沿用 10px 圆角矩形,箭头不设独立圆形区域;悬停和打开时使用整行的淡底色,箭头保持中性颜色;整行保持可点击。语音与发送按钮继续使用圆形。
Agent 输入框使用 `--shadow-agent-composer` 的柔和双层阴影区分白色阅读背景,桌面、窄屏和浮动输入框复用同一规则。聚焦与未聚焦保持相同边框和阴影,不显示蓝色外圈;工具按钮保留键盘焦点提示。左侧始终显示权限模式与文字,任务协作会话同样保留该入口,运行期间按原规则禁用。右侧依次放模型、语音和发送操作;运行时模型位置切换为引导或排队方式,主按钮沿用原有停止与发送切换;停止使用柔和红底和深红图标,悬停时红底略深,发送保持蓝色。工具图标统一为 16px、2px 描边,下拉箭头统一为 12px 单箭头;语音使用声波图标,监听时保留动态声波反馈。发送使用左右对称的 20px 上箭头和 40px 圆形按钮,图标通过网格居中;禁用时使用浅底、灰色图标,启用时使用蓝底、白色图标。模型名称按输入框实际宽度显示。待处理消息队列位于编辑框上方,区别于尚未发送的草稿。
助手回复底部使用单行操作栏:“查看处理过程”靠左,语音与复制组成右侧操作组,复制位于最右。展开区域使用白色背景、细边框和完整圆角,与回答正文区分;外边缘与过程入口左侧对齐,普通进度与工具调用的状态图标统一左对齐;工具调用平铺显示,不额外包裹卡片、边框或背景,参数内容按文字列对齐。过程入口保留标准 hover 反馈,使用对称的水平留白。普通步骤和工具调用复用同一状态图标组件:24px 圆形容器、14px 线性图标,完成为圆圈勾选、失败为圆圈叉号、进行中为加载图标。操作图标统一为 16px、2px 描边,按钮高 32px;窄容器下语音与复制收起可见标签,保留中文可访问名称和提示。复制反馈不改变操作栏布局,过程展开、语音播放与复制各自独立。
Dev 测试、外围系统、调查实时展示与本地预览展示面板也遵循本节:使用实体表面、语义颜色、细边框和标准控件,复用 `workbench-shadcn-surface` 主题;日期与选择菜单通过 Portal 渲染时继续传递这一主题。外围面板内的工单、SCADA 和 Dev 内的 JSONL 测试区采用同一规则。Dev 按调查测试与地图调试两个页签组织;工单用分类标题和摘要列表组织,完整报告按需展开,避免多层边框挤压表单;SCADA 先展示最新值,再提供异常演练。调查与本地展示面板使用固定标题和状态、独立滚动区、紧凑的地图操作及图表 Card;图表标题与关闭按钮同行,嵌入式渲染不再叠加旧灰色图表容器,长标题与图例可换行。面板与图表进入退出、依据展开使用 Motion 的短时透明度和位移过渡,布局变化采用 transform 投影;键盘操作及减少动态效果模式即时完成。地图定位采用可中断的 450ms 平滑 fit,覆盖层以 180ms 淡入淡出,减少动态效果时关闭这些过渡。两个浮层保持非模态,仅自身表面接收指针输入,外部地图保留点击、拖拽和滚轮操作。 展示面板的动作切换放在固定标题区,使用紧凑的 Select、前后按钮和“回到当前”;历史状态与后续动作数可见。回看切换保留短时淡入淡出,退出画面立即设为 inert 并从无障碍树隐藏,避免旧操作仍可点击。Dev 只显示测试输入、校验与原始数据,业务表格、卡片与图表统一进入展示面板。
Agent 相关界面保持项目本地 shadcn/ui 组件的设计,包括背景、边框、圆角、阴影、排版、间距及交互状态。该规则覆盖主对话面板、手机 Agent 面板、历史对话、主题新建与管理、模型菜单、权限与问题确认、Agent 回答的展开阅读面板,以及这些界面的子弹窗和提示。
| 场景 | 组件与组合 |
|---|---|
| 历史、主题表单、独立详情与确认 | `Dialog`、`DialogTitle`、`DialogDescription`,组合 `Input`、`Button` 和列表 |
| 对话、审批、问答与展开阅读面板 | 本地 shadcn/ui 面板布局,按需组合 `Card`、`Separator`、`Tabs`、`ResizablePanelGroup` 与 AI Elements |
| 模型、主题与会话操作菜单 | `DropdownMenu` 及其菜单项、分组和分隔线 |
| 辅助说明与状态 | `Alert`、`Tooltip`、`HoverCard`、`Badge` 及共享状态组件 |
- 使用已配置的 shadcn/ui 主题变量:`bg-background`、`bg-card`、`bg-popover`、`text-foreground`、`text-muted-foreground`、`border-border`、`ring-ring` 等。按钮、输入和菜单项优先使用本地默认样式及 `variant`、`size`,不为 Agent 另建配色和控件外观。
- 历史和主题弹窗使用 `bg-card`,与 Agent 主对话区保持白色实体表面,标题区和列表不另铺灰色底。通过 Portal 渲染的弹窗及菜单标记 `data-agent-theme="chat"`,复用主面板的现有主题变量,避免继承工作台银灰色底板;保留本地 `Dialog` 的遮罩、边框、阴影与交互样式。
- Agent 表面不套用 `acrylic-panel`、`acrylic-panel-white`、`acrylic-control`、`glass-transient` 等地图材质类,也不以 `surface-dock`、`surface-reading` 等材质类替换 shadcn/ui 面板背景。不叠加毛玻璃、噪点、渐变高光、发光边缘或额外阴影。
- 业务适配可调整宽高、最大高度、滚动、分栏、层级和响应式布局;手机全屏历史与抽屉布局仍沿用相同的组件设计。保留组件的标题、说明、关闭、焦点、键盘和禁用行为,避免用全局 CSS 重绘 Agent 内的按钮、输入、菜单或弹窗。
- 危险操作使用明确的确认步骤和 `destructive` 按钮变体;失败保留输入与原内容。审批、提问与历史操作的业务规则由对应功能文档维护。
- Agent 打开的既有地图或业务工具仍遵循其所属模块规范。`AgentPersona` 动画资源按专用设计文档维护,周边面板与控件遵循本节。
## 2. Tailwind 定制方式
样式统一进入 [src/styles.css](../src/styles.css)。Tailwind 工具类负责布局、间距、尺寸、排版、响应式及交互状态;共享变量负责颜色和材质参数,共享变体负责重复的组件外观。
1. 先选组件,再选语义表面,最后调整布局与状态。常用差异通过组件的 `variant`、`size` 表达;局部差异通过 `className` 与 [cn](../src/shared/ui/cn.ts) 合并。
2. 使用 `bg-background`、`bg-card`、`bg-popover`、`text-foreground`、`border-border` 和 `ring-ring` 等语义工具类。`@theme inline` 将它们映射到项目变量;背景与前景成对维护。
3. 地图与工作台 Acrylic 的混合层、噪点和回退集中封装为材质类,组件内不重复拼装颜色、模糊和阴影配方,也不把整个控件设置为半透明而降低文字对比度。
4. 需要允许工具类覆盖的复合样式放入 `@layer components`;需要支持 Tailwind 变体的自定义工具使用 `@utility`。修改现有未分层规则前,先核对层叠关系及回退,不直接搬移整段样式。
5. 避免同一属性的冲突类;`cn` 处理已知 Tailwind 类的合并,不负责解决任意 CSS 的层叠。自定义材质类不应依赖 `className` 的书写先后来决定优先级,也不靠持续增加选择器权重或 `!important` 定制外观。
6. 显式颜色仅用于主题定义、图表与地图 API、资源固有颜色和必要的动态值;业务 JSX 优先引用语义变量。
```tsx
import { Button } from "@/shared/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/ui/card";
// 独立地图浮层;放入已有 Acrylic 外壳时改用内部内容表面。
<Card className="acrylic-panel w-full max-w-sm">
<CardHeader className="p-3">
<CardTitle className="text-sm">分析结果</CardTitle>
</CardHeader>
<CardContent className="surface-reading space-y-3 p-3">
<p className="text-sm text-foreground">展示已有结论与证据。</p>
<Button variant="outline" size="sm">查看依据</Button>
</CardContent>
</Card>
```
## 3. 颜色与状态
地图与工作台 Acrylic 界面的视觉方向为宝石蓝操作、银灰外壳、冷瓷阅读面和少量香槟提示。完整色阶见 [宝石蓝配色](gem-blue-palette.svg)。下表为其材质基线,实际使用通过变量引用;Agent 弹窗与面板沿用已配置的 shadcn/ui 主题变量,不从下表另建局部色板。
| 角色 | 语义变量 | 基线 |
|---|---|---|
| 主操作 | `--action-blue` | `#4263C7` |
| 主操作 hover / 按压 | `--action-blue-hover` / `--action-blue-pressed` | `#3653B0` / `#2B469C` |
| 外壳色调 | `--surface-panel` | 银霜 `#E6E9F2` |
| 常驻底板、普通控件 | `--surface-dock` / `--surface-subtle` | `#EBEEF5` |
| 正文与表单 | `--surface-reading` | 冷瓷 `#F5F7FA`,按阅读场景保持高遮蔽度 |
| 选中背景 | `--action-selection-soft` | `#DAE5FD` |
| 正文 / 辅助文字 | `--ink` / `--ink-muted` | `#232935` / `#4E5566` |
| 边框 / 分隔线 | `--surface-border` / `--surface-divider` | `#BEC2CD` / `#D5D9E1` |
| 警告与确认提示 | `--status-warning-*` | 香槟色系,小面积使用 |
状态使用 `status-tone-neutral/info/success/warning/danger` 与共享 `StatusBadge`、`StatusIcon`、`StatusDot`,同时提供文字或图标。业务状态、交互选中和数据系列颜色各自独立;`material-tone-agent` 只标记 Agent 解释或建议,原始监测值和人工资料继续使用普通阅读面。
地图中的管线一起显示,以管径对应的颜色和线宽体现差异。水库、泵站、水箱和水质监测点保持清晰;阀门、普通节点与常规 SCADA 使用随缩放连续变化的大小和透明度。密集设施的工程符号自动避让,底层保留轻量圆点以表达位置和支持点选。选中与异常分析标记单独突出,普通设施以连续变化为主;普通节点从 12 级、阀门从 13 级开始显示,图标、标注与命中范围同步限制。
Agent、调查展示和 Dev 本地预览的要素定位复用地图调试的选中样式,按原业务源保留线宽、边框、圆环半径、设备类型过滤和缩放规则。展示覆盖层从当前地图样式派生,独立管理高亮与清理范围;闪烁只改变强调透明度,结束后恢复静态样式。
管道透明度不随缩放变化,缩放渐变体现在管线与描边的宽度上,远看纤细、放大清晰;图层开关时仍使用透明度淡入淡出。
图层开关统一使用约 320ms 的透明度淡入淡出,覆盖管线、设施、监测点、GIS 原始数据和模拟结果。矢量瓦片可绘制后才开始淡入计时,避免加载期间耗尽过渡时间。淡入淡出只临时叠加透明度系数,结束后恢复图层原有样式;快速反向切换从当前进度继续。隐藏时立即关闭命中层与交互强调层,淡入结束后恢复;减少动态效果偏好下直接切换。管线用过滤器区分开关状态,透明度保持统一数值,避免逐帧重写属性表达式触发瓦片重算。
重要设施也使用连续缩放插值,但图标的最低透明度保持较高,衬底更轻,保证概览可辨识。按需开启的数值标签随缩放渐变字号与透明度;使用者设置的字号作为放大后的目标字号。
水质、压力和流量监测点统一从 11 级开始显示,图标、圆点、交互层和图层面板提示共用缩放起点。水质与压力监测点使用一致的圆点、衬底尺寸和图标屏幕像素宽度。图标缩放系数需结合原图尺寸换算,水质图标 128px、压力图标 96px,不直接使用相同系数。
GIS 原始图层与对应业务类型共用起始级别:GIS 管线与 DN100+ 台账从 8.5 级显示,流量仪从 11 级显示,消火栓、接水点、用户及非居民水表从 12 级显示,GIS 阀门与排水阀从 13 级显示。图层提示、图形和点击范围保持一致。
Agent 使用 shadcn/ui 的实体表面和现有主题色,不将这种外观列为待迁移到 Acrylic 的差异。已有 Agent 专用配色、材质和控件 CSS 覆盖应在对应组件调整时收敛到本地 shadcn/ui 样式;是否完成以运行界面验收为准。
## 4. 材质与层级
本节的 Acrylic 材质规则适用于地图与其他工作台界面;Agent、Dev 测试、外围系统、调查与本地展示面板按前述 shadcn/ui 规则执行。Acrylic 通过半透明色调、背景模糊、混合层和细噪点建立层级,边缘高光与阴影保持克制。常驻、参与布局的业务区域使用实体底板;Mica 仅作为这一底板角色的设计参考,Web CSS 实体色不等同于原生系统 Mica。
| 表面类 | 用途 |
|---|---|
| `acrylic-navigation` | 透出地图背景的顶部导航 |
| `acrylic-panel` | 图层、图例、工况、要素详情和菜单等独立地图浮层 |
| `acrylic-panel-white` | 与 `acrylic-panel` 配合的白色变体,如项目切换对话框 |
| `acrylic-control` | 工具栏、缩放、比例尺和底图入口 |
| `glass-transient` | 活动任务浮条和地图临时通知 |
| `surface-dock` | 非 Agent 的常驻业务面板、分析成果及业务报告外壳与标题区 |
| `surface-control` | 内部按钮、筛选器和紧凑操作区 |
| `surface-well` | 低密度分组、空白支撑区和内部凹槽 |
| `surface-reading` | 消息、报告、表格、属性、证据和表单 |
一个浮动区域只由最外层承担背景模糊,内部使用内容表面。同一区域的工具面板相互替换,避免叠加 Acrylic。常驻底板可以承载独立临时浮层,标题栏按背景关系选择材质。
地图纹理可影响外壳空白区,不能穿透密集文字。透明度、模糊和阴影由全局变量及 `data-basemap-tone` 适配;具体参数以 CSS 为准,不在多份文档重复维护固定数值。入场动画与定位容器需保证背景采样正常,结束后不保留不必要的合成提示。
减少透明度偏好或不支持 `backdrop-filter` 时,切换高遮蔽度背景并关闭模糊;强制颜色模式使用系统色,关闭纹理与阴影。项目已有浅色主题是当前基线,暗色类名不代表已完成暗色验收。
地图组件继续复用 [map-control-styles.ts](../src/features/map/core/components/map-control-styles.ts):
| 共享常量 | 材质类 |
|---|---|
| `MAP_CONTROL_SURFACE_CLASS_NAME` | `acrylic-control border` |
| `MAP_TOOL_PANEL_SURFACE_CLASS_NAME` | `acrylic-panel border` |
| `MAP_FOCUS_SURFACE_CLASS_NAME` | `acrylic-panel border` |
| `MAP_READABLE_SURFACE_CLASS_NAME` | `surface-well border` |
| `MAP_READABLE_SURFACE_STRONG_CLASS_NAME` | `surface-control border` |
## 5. 排版、密度与布局
沿用 Noto Sans SC,中文正文自然换行,不额外拉开字距。编号、时间和数值使用等宽数字,标签左对齐,数值列右对齐。
| 场景 | 排版约定 |
|---|---|
| 侧栏标题、业务分组标题 | 分别为 14px、13px |
| 紧凑正文与字段标签、辅助信息 | 分别为 12px、11px |
| Agent 消息正文 | 14px,行高 24px |
| 欢迎提示与展开报告标题 | 20px,行高 28px |
| 指标值、单位 | 分别为 24px、12px,数值使用等宽数字 |
业务区间距为 12px 至 14px,Agent 消息之间保留 24px。地图与业务面板的普通控件和内部区域沿用 8px、12px 圆角,独立大面板使用共享 16px 圆角;具体值复用组件变体和地图圆角常量。Agent 弹窗、面板和表单控件沿用本地 shadcn/ui 的默认圆角、间距及尺寸变体。
地图与业务表单的主要按钮目标高度为 40px;基础 `Input` 当前默认 36px,这些业务场景通过 `h-10` 或适配后的字段组件统一。Agent 控件优先沿用 shadcn/ui 默认尺寸和 `size` 变体。紧凑控件保留至少 40px 的互不重叠命中区域,可通过周边留白适配触屏。
地图保持主工作区。浮层、导航、时间轴和正文预留各自安全区,地图背景可延伸到 56px 顶部导航背后。业务内容按“定位、状态、下一步、证据”排列,原始对象与历史按需展开;移动端单列,表格只在自己的容器内横向滚动。
Agent 与主工作区、地图与报告使用共享 `Resizable` 分栏;连续调宽不增加布局过渡。报告展开保留同一组件实例、草稿、筛选与阅读位置。具体尺寸、切换条件和任务交互由 [Agent 交互与报告设计](agent-chat-ui-design.md) 维护。
## 6. 组件与交互规则
| 用途 | 优先组件 |
|---|---|
| 操作 | `Button`,复用 `default`、`outline`、`secondary`、`ghost`、`link` 和 `destructive` 变体 |
| 输入与选择 | `Input`、`Textarea`、`InputGroup`、`FieldSelect`、`Select`、`Checkbox`、`Radio`、`DateTimeField` |
| 分组、状态、数据 | `Card`、`Separator`、共享状态组件、`Table`、`Tabs` |
| 证据与过程 | `Disclosure`、`Accordion`、`Collapsible` |
| 菜单、弹层、解释 | `DropdownMenu`、`Dialog`、`Tooltip`、`HoverCard` |
| 可调工作区 | `ResizablePanelGroup`、`ResizablePanel`、`ResizableHandle` |
`WorkbenchSection` 统一标题、说明、状态和操作;`WorkbenchNotice` 使用局部状态线;`WorkbenchEmptyState` 只说明为空原因与下一步。以分隔线、留白和浅色差组织内容,避免重复嵌套同级卡片。
每个业务区最多一个醒目的主操作。按钮覆盖默认、hover、按压、焦点、禁用和加载态;hover 仅用于支持 hover 的设备,加载时阻止重复提交并保留可读状态。地图与业务控件沿用共享按压反馈,Agent 控件保留本地 shadcn/ui 交互状态;具有专用资源交互的 `AgentPersona` 保留原版悬停,不额外缩放或变暗。
地图与业务表单字段复用 `.form-field`,聚焦只改变原有 1px 边框;组合输入由外层承担焦点边界,无边框输入使用内描边。Agent 字段保留本地 shadcn/ui 输入组件的边框、焦点和错误样式。错误通过文字、`aria-invalid` 和关联说明表达,失败后保留输入。选中与焦点不改变控件尺寸,底图选择卡片使用主题边框和勾选标记,键盘焦点使用共享内描边。
弹层保留标题、关闭入口、焦点管理及触发控件的焦点返回。表单弹窗显式将初始焦点放在首要业务字段,选择框获焦不自动展开。Esc 从内到外处理,外层尊重已消费事件;弹窗容器可承接程序焦点,业务控件仍保留可见焦点。模态遮罩阻断底层地图操作。
状态必须区分无数据、加载中、失败、无权限、未配置与结果未知;保留完整证据、修订及请求号的可读入口。演练数据明确标记,前端展示不能暗示已经完成业务执行或写入。
## 7. 验证与维护
文档修改检查引用路径、示例中的本地组件与属性、命令及 `git diff --check`。运行代码变更执行 `pnpm lint`、`pnpm typecheck`、`pnpm test`;可见 UI 变化增加聚焦的 `pnpm test:browser`,依赖、构建或运行集成变化增加 `pnpm build`。
界面验收覆盖 1280px 及以上桌面和 320px、375px 窄屏,检查长内容、按钮与命中区域、弹层边界、Tab、方向键、Esc、焦点返回及减少动态效果。普通文字与实际合成背景对比度至少 4.5:1,焦点与必要非文字状态至少 3:1,并验证强制颜色、减少透明度与模糊不可用时的回退。
Agent 界面另检查所有弹窗、面板及其子菜单是否沿用本地 shadcn/ui 设计,是否存在地图材质类、额外模糊和阴影、独立 Agent 配色或重绘基础控件的 CSS。尺寸和层级适配不能改变这些组件的视觉规范。
设计规则只在本文维护;业务协议与动作留在功能文档,历史测试结果留在交付记录,不作为当前全量验收结论。
## 官方参考
- [shadcn/ui 组件原则](https://ui.shadcn.com/docs)、[主题变量](https://ui.shadcn.com/docs/theming)、[Vite 接入](https://ui.shadcn.com/docs/installation/vite)、[CLI 配置](https://ui.shadcn.com/docs/components-json)。
- [Tailwind CSS 主题变量](https://tailwindcss.com/docs/theme)、[自定义样式与层叠](https://tailwindcss.com/docs/adding-custom-styles)。
- [Fluent Acrylic](https://learn.microsoft.com/en-us/windows/apps/design/style/acrylic)、[Mica](https://learn.microsoft.com/en-us/windows/apps/design/style/mica)。
+2 -1
View File
@@ -3,13 +3,14 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link
rel="preload"
as="fetch"
href="https://demotiles.maplibre.org/font/Noto%20Sans%20Regular/0-255.pbf"
crossorigin="anonymous"
/>
<title>供水管网</title>
<title>供水管网智慧运维系统</title>
</head>
<body>
<div id="root"></div>
+15 -6
View File
@@ -4,8 +4,12 @@
"private": true,
"type": "module",
"packageManager": "pnpm@11.8.0",
"engines": {
"node": ">=24.22.1 <25"
},
"scripts": {
"dev": "vite",
"export:answer-ui-contract": "node scripts/export-answer-ui-contract.mjs",
"build": "tsc --noEmit && vite build && pnpm build:verify-css && pnpm build:tts",
"build:verify-css": "node scripts/verify-production-css.mjs",
"build:tts": "esbuild server/edge-tts-server.ts --bundle --platform=node --format=cjs --outfile=dist-server/edge-tts-server.cjs",
@@ -20,14 +24,18 @@
"dependencies": {
"@ai-sdk/react": "^4.0.9",
"@fontsource-variable/noto-sans-sc": "5.3.0",
"@json-render/core": "^0.21.0",
"@json-render/react": "^0.21.0",
"@maplibre/maplibre-gl-style-spec": "26.4.4",
"@radix-ui/react-accordion": "^1.2.14",
"@radix-ui/react-collapsible": "^1.1.14",
"@radix-ui/react-dialog": "^1.1.17",
"@radix-ui/react-dropdown-menu": "^2.1.18",
"@radix-ui/react-hover-card": "^1.1.17",
"@radix-ui/react-popover": "^1.3.1",
"@radix-ui/react-select": "^2.3.1",
"@radix-ui/react-separator": "^1.1.10",
"@radix-ui/react-slot": "^1.3.0",
"@radix-ui/react-tabs": "^1.2.1",
"@radix-ui/react-tooltip": "^1.2.10",
"@rive-app/react-webgl2": "^4.29.3",
"@streamdown/cjk": "^1.0.3",
@@ -41,16 +49,16 @@
"cmdk": "^1.1.1",
"echarts": "^6.0.0",
"echarts-for-react": "^3.0.2",
"edge-tts-ts": "^1.0.0",
"katex": "^0.17.0",
"keycloak-js": "26.2.4",
"lucide-react": "^0.468.0",
"maplibre-gl": "^4.7.1",
"maplibre-gl": "^6.4.1",
"motion": "^12.40.0",
"nanoid": "^5.1.14",
"node-edge-tts": "1.2.12",
"pmtiles": "4.3.0",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"shiki": "^4.2.0",
"react-resizable-panels": "^4.14.7",
"sonner": "^2.0.7",
"streamdown": "^2.5.0",
"swr": "^2.4.2",
@@ -84,7 +92,8 @@
"tw-animate-css": "^1.4.0",
"typescript": "^7.0.0",
"vite": "^7.0.0",
"vitest": "^4.1.9"
"vitest": "^4.1.9",
"zod-to-json-schema": "^3.25.2"
},
"msw": {
"workerDirectory": [
+1 -1
View File
@@ -20,7 +20,7 @@ export default defineConfig({
trace: "on-first-retry"
},
webServer: {
command: `TJWATER_AUTH_MODE=disabled TJWATER_AGENT_API_BASE_URL=http://127.0.0.1:8787 pnpm dev --port ${testPort} --strictPort`,
command: `TJWATER_VITE_CACHE_DIR=node_modules/.vite-playwright-${testPort} TJWATER_AUTH_MODE=disabled TJWATER_AGENT_URL=http://127.0.0.1:8787 pnpm dev --port ${testPort} --strictPort`,
url: baseURL,
reuseExistingServer: false
},
+662 -320
View File
File diff suppressed because it is too large Load Diff
+5
View File
@@ -1,6 +1,11 @@
packages:
- .
# Keep the catalog and json-render on the existing application schema runtime.
overrides:
'@json-render/core>zod': 3.25.76
'@json-render/react>zod': 3.25.76
allowBuilds:
'@swc/core': true
esbuild: true
Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.
+10
View File
@@ -0,0 +1,10 @@
# 数据来源与许可
- 建筑和行政边界:© OpenStreetMap contributors,ODbL 1.0。https://www.openstreetmap.org/copyright
- 补充建筑:Overture Maps Foundation,2026-08-19.0 版本建筑主题,2026-09-22 下载。主题许可 ODbL。https://docs.overturemaps.org/attribution/
- 补充建筑的主要上游:Qian Shi 等,A First High-quality Vector Data of Buildings in East Asian Countries Based on a Comprehensive Large-scale Mapping Framework,2023,CC BY 4.0。https://doi.org/10.5281/zenodo.8174931
- 本项目对公开建筑做了奉贤行政区裁剪、重叠过滤和高度估算。原始来源记录保存在本地数据快照,不能把估算高度解释为测量值。
- 供水数据:用户提供的 tjwater_v2.gis 已发布物化视图,只读快照,不属于公开 OSM 数据。公开建筑许可不授权向外发布用户供水数据。
- 简化设备构件:本项目程序生成,外观和尺寸为示意,不代表具体厂家型号。
建筑参考与私人供水图层分开存储、独立切片。
Binary file not shown.
+52
View File
@@ -0,0 +1,52 @@
{
"schema_version": 1,
"name": "奉贤供水数字城市场景",
"crs": "EPSG:3857",
"geojson_crs": "EPSG:4326",
"bbox": [
121.3467333,
30.6803212,
121.8495682,
31.0182303
],
"building_count": 154085,
"pipe_count": 90805,
"building_sources": {
"OpenStreetMap": 3617,
"Overture": 150468
},
"asset_count": 63968,
"generated_at": "2026-09-22T09:09:36.585868+00:00",
"notice": "建筑高度多为估算;管道为地表专题展示,埋深未知。2020 年资料存在头桥覆盖缺口。",
"attribution": "© OpenStreetMap contributors · Overture Maps Foundation · 用户提供的供水 GIS",
"license_url": "https://www.openstreetmap.org/copyright",
"tiles": {
"buildings": {
"minzoom": 12,
"maxzoom": 16,
"layer": "buildings",
"sha256": "e00ebbc98d1cf86a18147317e53813b24a9975915c38d4778ca42df1bf5f3ad8"
},
"pipes": {
"minzoom": 10,
"maxzoom": 17,
"layer": "pipes"
},
"assets": {
"minzoom": 12,
"maxzoom": 17,
"layer": "assets"
},
"pipe-solids": {
"minzoom": 16,
"maxzoom": 18,
"layer": "pipe_solids"
}
},
"models": {
"hydrant": "models/hydrant.glb",
"valve": "models/valve.glb",
"control_valve": "models/valve.glb",
"flow_meter": "models/flow-meter.glb"
}
}
+14
View File
@@ -0,0 +1,14 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">
<rect width="64" height="64" rx="14" fill="#4263c7" />
<g
fill="none"
stroke="#fff"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="1.75"
transform="translate(8 8) scale(2)"
>
<path d="M7 16.3c2.2 0 4-1.83 4-4.05 0-1.16-.57-2.26-1.71-3.19S7.29 6.75 7 5.3c-.29 1.45-1.14 2.84-2.29 3.76S3 11.1 3 12.25c0 2.22 1.8 4.05 4 4.05z" />
<path d="M12.56 6.6A10.97 10.97 0 0 0 14 3.02c.5 2.5 2 4.9 4 6.5s3 3.5 3 5.5a6.98 6.98 0 0 1-11.91 4.97" />
</g>
</svg>

After

Width:  |  Height:  |  Size: 585 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

+6
View File
@@ -0,0 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96" viewBox="0 0 96 96">
<circle cx="48" cy="48" r="38" fill="#6F8292" stroke="#fff" stroke-width="5"/>
<rect x="25" y="29" width="46" height="38" rx="9" fill="none" stroke="#fff" stroke-width="5"/>
<circle cx="48" cy="47" r="10" fill="none" stroke="#fff" stroke-width="4"/>
<path d="m48 47 7-6M36 67v7m24-7v7" fill="none" stroke="#fff" stroke-width="5" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 453 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96" viewBox="0 0 96 96">
<circle cx="48" cy="48" r="38" fill="#6D7F8C" stroke="#fff" stroke-width="5"/>
<path d="M29 29h38M48 29v31m-12-12 12 12 12-12" fill="none" stroke="#fff" stroke-width="6" stroke-linecap="round" stroke-linejoin="round"/>
<path d="M25 70c6-5 12-5 18 0s12 5 18 0 12-5 18 0" fill="none" stroke="#fff" stroke-width="5" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 435 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

+7
View File
@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96" viewBox="0 0 96 96">
<circle cx="48" cy="48" r="38" fill="#287A89" stroke="#fff" stroke-width="5"/>
<circle cx="48" cy="48" r="20" fill="none" stroke="#fff" stroke-width="5"/>
<path d="m48 48 12-11M22 48h6m40 0h6" fill="none" stroke="#fff" stroke-width="6" stroke-linecap="round"/>
<circle cx="48" cy="48" r="4" fill="#fff"/>
<path d="M37 62h22" stroke="#fff" stroke-width="5" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 482 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96" viewBox="0 0 96 96">
<circle cx="48" cy="48" r="38" fill="#A15F55" stroke="#fff" stroke-width="5"/>
<path d="M38 33c0-7 4-11 10-11s10 4 10 11M35 34h26M38 34v32h20V34M29 46h9m20 0h9M26 42h7v9h-7m44-9h-7v9h7M32 68h32" fill="none" stroke="#fff" stroke-width="5" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 382 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

+6
View File
@@ -0,0 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96" viewBox="0 0 96 96">
<rect x="10" y="10" width="76" height="76" rx="20" fill="#526F83" stroke="#fff" stroke-width="5"/>
<path d="M28 69V37l20-11 20 11v32M24 69h48" fill="none" stroke="#fff" stroke-width="5" stroke-linecap="round" stroke-linejoin="round"/>
<circle cx="48" cy="46" r="8" fill="none" stroke="#fff" stroke-width="4"/>
<path d="m48 46 5-4M39 69V58h18v11" fill="none" stroke="#fff" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 537 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

+8
View File
@@ -0,0 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96" viewBox="0 0 96 96">
<circle cx="48" cy="48" r="38" fill="#70818F" stroke="#fff" stroke-width="5"/>
<path d="M23 61h50M48 61V36h18" fill="none" stroke="#fff" stroke-width="6" stroke-linecap="round" stroke-linejoin="round"/>
<circle cx="23" cy="61" r="5" fill="#fff"/>
<circle cx="73" cy="61" r="5" fill="#fff"/>
<circle cx="67" cy="36" r="5" fill="#fff"/>
<circle cx="48" cy="61" r="6" fill="#70818F" stroke="#fff" stroke-width="4"/>
</svg>

After

Width:  |  Height:  |  Size: 516 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96" viewBox="0 0 96 96">
<circle cx="48" cy="48" r="38" fill="#737988" stroke="#fff" stroke-width="5"/>
<path d="M24 32 46 48 24 64V32Zm48 0L50 48l22 16V32Z" fill="none" stroke="#fff" stroke-width="6" stroke-linejoin="round"/>
<circle cx="48" cy="48" r="5" fill="#fff"/>
</svg>

After

Width:  |  Height:  |  Size: 343 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

+1
View File
@@ -0,0 +1 @@
<svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="128" height="128"><path d="M511.948675 512.025215m-486.374101 0a486.374101 486.374101 0 1 0 972.748201 0 486.374101 486.374101 0 1 0-972.748201 0Z" fill="#FFFFFF"></path><path d="M149.958351 874.041137A511.972737 511.972737 0 1 1 511.974273 1023.997952a508.644915 508.644915 0 0 1-362.015922-149.956815zM51.19881 512.025215a460.775464 460.775464 0 1 0 460.775463-460.775464 461.313035 461.313035 0 0 0-460.775463 460.775464z m263.358776 232.794003a258.77662 258.77662 0 0 1-16.8951-363.500643 1179.175609 1179.175609 0 0 1 197.903061-193.62809l20.09493-16.306331 20.043733 16.306331a1178.535643 1178.535643 0 0 1 197.92866 193.62809 258.725423 258.725423 0 0 1-16.869502 363.500643 286.704733 286.704733 0 0 1-402.205782 0z m295.792249-168.055051v126.58526h62.486273v-125.894096a85.62744 85.62744 0 0 0-83.349162-86.728182h-2.841449a86.113814 86.113814 0 0 0-85.934624 81.198876v41.904968a23.29476 23.29476 0 1 1-46.56392 0v-8.319556h-63.075041v8.319556a86.395399 86.395399 0 1 0 172.7652 0v-37.015628a23.269161 23.269161 0 1 1 46.538322 0z m-174.070731-21.426059l77.615067-111.789247h-33.278228v-22.296413h-88.648079v22.296413H358.382452z m122.156695-95.815698a9.522693 9.522693 0 0 0-2.559863 7.449204 10.828223 10.828223 0 0 0 10.393046 10.469842h51.990832a10.469842 10.469842 0 1 0 0-20.939685h-52.937981a9.599489 9.599489 0 0 0-7.014027 3.046238z m-166.391139-49.507763h88.648079v-22.322012h-88.648079z m0-33.483017h88.648079v-11.212203h-88.648079z" fill="#13A8A8"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

+6 -1
View File
@@ -1,5 +1,10 @@
globalThis.__TJWATER_CONFIG__ = {
TJWATER_AUTH_MODE: "required",
TJWATER_KEYCLOAK_ISSUER: "",
TJWATER_KEYCLOAK_CLIENT_ID: "next-tjwater"
TJWATER_KEYCLOAK_CLIENT_ID: "next-tjwater",
TJWATER_MAPBOX_ACCESS_TOKEN: "",
TJWATER_TIANDITU_TOKEN: "",
TJWATER_AGENT_URL: "http://127.0.0.1:8787",
TJWATER_SERVER_API_BASE_URL: "http://127.0.0.1:8000",
TJWATER_WORKBENCH_RUNTIME_MODE: "auto"
};
+306
View File
@@ -0,0 +1,306 @@
import { Buffer } from "node:buffer";
import { createHash } from "node:crypto";
import { readFile, writeFile } from "node:fs/promises";
import { argv, stdout } from "node:process";
import { pathToFileURL, URL } from "node:url";
import { parseArgs } from "node:util";
const sourceUrl = new URL("../design/agent/obsidian-runtime.json", import.meta.url);
const outputUrl = new URL("../public/agent/obsidian-water-v1.riv", import.meta.url);
const manifestUrl = new URL("../src/shared/ai-elements/persona-resource-manifest.json", import.meta.url);
const designUrl = new URL("../design/agent/obsidian-offline.json", import.meta.url);
const defaultDesign = JSON.parse(await readFile(designUrl, "utf8"));
const materialUrl = new URL("../design/agent/obsidian-material.json", import.meta.url);
const defaultMaterial = JSON.parse(await readFile(materialUrl, "utf8"));
const hoverTiming = JSON.parse(await readFile(new URL("../src/shared/ai-elements/persona-hover-timing.json", import.meta.url), "utf8"));
function uint(value) {
if (!Number.isSafeInteger(value) || value < 0) throw new Error(`Invalid Rive uint: ${value}`);
const bytes = [];
do {
const next = value % 128;
value = Math.floor(value / 128);
bytes.push(next | (value > 0 ? 128 : 0));
} while (value > 0);
return Buffer.from(bytes);
}
export function encodeSource(source, objects = source.objects) {
const parts = [Buffer.from(source.headerHex, "hex")];
for (const object of objects) {
parts.push(uint(object.type));
for (const [key, value] of object.values) {
parts.push(uint(key));
const type = source.properties[key]?.type;
if (type === "UInt") parts.push(uint(value));
else if (type === "Float" || type === "Color") {
const bytes = Buffer.alloc(4);
if (type === "Float") bytes.writeFloatLE(value);
else bytes.writeUInt32LE(value);
parts.push(bytes);
} else if (type === "String") {
const bytes = typeof value === "string" ? Buffer.from(value) : Buffer.from(value.hex, "hex");
parts.push(uint(bytes.length), bytes);
} else throw new Error(`Unknown Rive property: ${key}`);
}
parts.push(uint(0));
}
return Buffer.concat(parts);
}
const clone = (value) => JSON.parse(JSON.stringify(value));
const valueOf = (object, key, fallback) => object.values.find(([id]) => id === key)?.[1] ?? fallback;
function setValue(object, key, value) {
const property = object.values.find(([id]) => id === key);
if (property) property[1] = value;
else object.values.push([key, value]);
}
// Rive type/property keys are recorded alongside their names in the source JSON.
function transition(stateId, asleep, duration) {
return [
{ type: 65, values: [[151, stateId], [158, duration]] },
{ type: 71, values: [[155, 1], [156, asleep ? 0 : 1]] }
];
}
function restoreOriginal(source) {
const original = encodeSource(source);
if (createHash("sha256").update(original).digest("hex") !== source.sourceSha256) {
throw new Error("The decoded baseline no longer reproduces the original Obsidian file.");
}
return original;
}
function materialObjects(source, material) {
const colors = new Map();
for (const { from, to } of material.colors) {
if (!/^#[\da-f]{6}$/i.test(from) || !/^#[\da-f]{6}$/i.test(to)) {
throw new Error("Material colors must use six-digit hex RGB.");
}
colors.set(parseInt(from.slice(1), 16), parseInt(to.slice(1), 16));
}
const objects = clone(source.objects);
for (const object of objects) {
for (const property of object.values) {
if (source.properties[property[0]]?.type !== "Color") continue;
const color = colors.get(property[1] & 0xffffff);
// Keep alpha, gradient positions, feathering and all geometry intact.
if (color !== undefined) property[1] = ((property[1] & 0xff000000) | color) >>> 0;
}
}
const artboard = objects.findIndex((object) => object.type === 1);
const components = objects.slice(artboard).filter((object) => object.type !== 447);
// The backing color is independent of the moving blue reflections. A pale,
// opaque backing keeps map features from showing through the sphere.
if (material.bodyColor !== undefined) {
if (!/^#[\da-f]{6}$/i.test(material.bodyColor) || components[189]?.type !== 18) {
throw new Error("Invalid body color or missing original body fill.");
}
const alpha = valueOf(components[189], 37) & 0xff000000;
setValue(components[189], 37, (alpha | parseInt(material.bodyColor.slice(1), 16)) >>> 0);
}
// Keep the configured base opacity and its active-state keyframes in sync.
if (material.bodyOpacity) {
const { rest, active } = material.bodyOpacity;
if (![rest, active].every((value) => Number.isFinite(value) && value >= 0 && value <= 1)) {
throw new Error("Body opacity must be between zero and one.");
}
if (components[186]?.type !== 2) throw new Error("Missing original body node.");
setValue(components[186], 18, rest);
let objectId, propertyKey;
for (const object of objects) {
if (object.type === 25) objectId = valueOf(object, 51);
if (object.type === 26) propertyKey = valueOf(object, 53);
if (object.type === 30 && objectId === 186 && propertyKey === 18) {
const value = valueOf(object, 70, 0);
if (Math.abs(value - 0.1) < 0.000001) setValue(object, 70, rest);
else if (Math.abs(value - 0.3) < 0.000001) setValue(object, 70, active);
else throw new Error("Unexpected body opacity keyframe.");
}
}
}
return objects;
}
// A recolored baseline allows visual checks of geometry and online timelines.
export function buildMaterialPersona(source, material = defaultMaterial) {
restoreOriginal(source);
return encodeSource(source, materialObjects(source, material));
}
function opacityTrack(objectId, values, duration) {
return [
{ type: 25, values: [[51, objectId]] },
{ type: 26, values: [[53, 18]] },
...values.map((value, index) => ({
type: 30,
values: [[67, Math.round(duration * index / (values.length - 1))], [68, 2], [69, 261], [70, value]]
}))
];
}
function validateDesign(offline) {
if (!Number.isInteger(offline.fps) || offline.fps < 1 || offline.fps > 60 ||
!Number.isFinite(offline.amplitude) || offline.amplitude < 0 || offline.amplitude > 1 ||
!Number.isInteger(offline.transitionMs) || offline.transitionMs < 1 || offline.transitionMs > 5000 ||
!Array.isArray(offline.layers) || offline.layers.length !== 3) {
throw new Error("Invalid offline timing, amplitude or layer count.");
}
const ids = new Set();
for (const layer of offline.layers) {
if (!Array.isArray(layer.opacity)) throw new Error("Missing offline opacity tracks.");
for (const { objectId, rest, crest } of layer.opacity) {
if (!Number.isInteger(objectId) || ids.has(objectId) ||
!Number.isFinite(rest) || !Number.isFinite(crest) || rest < 0 || rest > crest || crest > 1) {
throw new Error(`Invalid or repeated opacity track: ${objectId}`);
}
ids.add(objectId);
}
}
}
export function buildOfflinePersona(source, offline = defaultDesign, material = defaultMaterial) {
restoreOriginal(source);
validateDesign(offline);
const objects = materialObjects(source, material);
const animations = objects.filter((object) => object.type === 31);
if (animations.length !== 20) throw new Error("Unexpected original animation count.");
// Component IDs start at the artboard; binding records do not consume IDs.
const artboard = objects.findIndex((object) => object.type === 1);
const firstAnimation = objects.findIndex((object) => object.type === 31);
const components = objects.slice(artboard, firstAnimation).filter((object) => object.type !== 447);
let animation;
let machineLayer;
for (const object of objects) {
if (object.type === 31) {
animation = valueOf(object, 55);
if (animation === "hover_in" || animation === "hover_out") {
setValue(object, 57, Math.round((animation === "hover_in" ? hoverTiming.enterMs : hoverTiming.exitMs) * 60 / 1000));
}
}
// Change timing only, keeping the original reflection geometry and color.
if ((animation === "hover_in" || animation === "hover_out") && object.type === 30) {
const durationMs = animation === "hover_in" ? hoverTiming.enterMs : hoverTiming.exitMs;
setValue(object, 67, Math.round(valueOf(object, 67, 0) * durationMs / 1000));
setValue(object, 68, 2);
setValue(object, 69, 261);
}
if (object.type === 57) machineLayer = valueOf(object, 138);
if (machineLayer === "hover" && object.type === 65 && valueOf(object, 152, 0) === 12) {
setValue(object, 158, hoverTiming.blendMs);
}
// These tracks only control opacity and scale. Keep the complete sphere.
if ((animation === "asleep" || animation === "wake") && object.type === 30) {
setValue(object, 70, 1);
}
}
const hoverOutEnd = objects.findIndex((object) => object.type === 31 && valueOf(object, 55) === "on_loop_1");
// Keep the pointer constraint active until the outgoing reflection is fully
// transparent. The original hover_off timeline releases it afterwards.
objects.splice(hoverOutEnd, 0,
{ type: 25, values: [[51, 129]] },
{ type: 26, values: [[53, 172]] },
{ type: 30, values: [[68, 1], [70, 1]] }
);
const loops = [];
for (let number = 1; number <= 3; number++) {
const start = objects.findIndex((object) => object.type === 31 && valueOf(object, 55) === `on_loop_${number}`);
const end = objects.findIndex((object, index) => index > start && (object.type === 31 || object.type === 53));
if (start < 0 || end < 0) throw new Error(`Missing original water loop ${number}.`);
const loop = clone(objects.slice(start, end));
setValue(loop[0], 55, `offline_loop_${number}`);
setValue(loop[0], 56, offline.fps);
let propertyKey;
let baseline;
for (const object of loop.slice(1)) {
if (object.type === 26) {
propertyKey = valueOf(object, 53);
baseline = undefined;
}
// Full rotations must close at 2π; reduce only displacement and breathing.
if (object.type === 30 && propertyKey !== 15) {
const value = valueOf(object, 70, 0);
baseline ??= value;
setValue(object, 70, baseline + (value - baseline) * offline.amplitude);
}
}
const duration = valueOf(loop[0], 57);
const onlineTracks = [];
for (const { objectId, rest, crest } of offline.layers[number - 1].opacity) {
const component = components[objectId];
if (!component || ![2, 3].includes(component.type)) throw new Error(`Invalid light node: ${objectId}`);
const opacity = valueOf(component, 18, 1);
loop.push(...opacityTrack(objectId, [opacity * rest, opacity * crest, opacity * rest], duration));
// Both sides key opacity so reconnecting restores the original material.
onlineTracks.push(...opacityTrack(objectId, [opacity, opacity], duration));
}
objects.splice(end, 0, ...onlineTracks);
loops.push(...loop);
}
const machine = objects.findIndex((object) => object.type === 53);
// Append timelines so all original animation IDs remain unchanged.
objects.splice(machine, 0, ...loops);
const result = [];
let layer;
let changedLayers = 0;
for (const object of objects) {
if (object.type === 57) {
if (/^loop[123]$/.test(layer)) {
const number = Number(layer.at(-1));
result.push({ type: 61, values: [[149, 19 + number]] });
result.push(...transition(number === 1 ? 3 : 0, false, offline.transitionMs));
changedLayers++;
}
layer = valueOf(object, 138);
}
result.push(object);
if (/^loop[123]$/.test(layer) && object.type === 61) {
result.push(...transition(4, true, offline.transitionMs));
}
}
if (changedLayers !== 3) throw new Error("The original loop layers have changed.");
// These standard properties were omitted from the original because of defaults.
const schema = { ...source, properties: {
...source.properties,
56: { name: "fps", type: "UInt" },
158: { name: "duration", type: "UInt" }
} };
return encodeSource(schema, result);
}
if (argv[1] && import.meta.url === pathToFileURL(argv[1]).href) {
const { values } = parseArgs({ options: {
check: { type: "boolean" },
"restore-original": { type: "string" }
} });
const source = JSON.parse(await readFile(sourceUrl, "utf8"));
if (values["restore-original"]) {
if (values.check) throw new Error("Choose --check or --restore-original, not both.");
// Never overwrite an existing resource when extracting the original.
await writeFile(values["restore-original"], restoreOriginal(source), { flag: "wx" });
stdout.write(`Restored original Obsidian to ${values["restore-original"]}.\n`);
} else {
const bytes = buildOfflinePersona(source);
const manifest = JSON.stringify({
path: "/agent/obsidian-water-v1.riv",
sha256: createHash("sha256").update(bytes).digest("hex"),
byteLength: bytes.length
}, null, 2) + "\n";
if (values.check) {
if (!bytes.equals(await readFile(outputUrl))) throw new Error("Agent animation is stale; rebuild it.");
if (manifest !== await readFile(manifestUrl, "utf8")) throw new Error("Agent cache version is stale; rebuild it.");
stdout.write("Verified original round trip and reproducible Agent animation.\n");
} else {
await writeFile(outputUrl, bytes);
await writeFile(manifestUrl, manifest);
stdout.write(`Built Agent animation (${bytes.length} bytes).\n`);
}
}
}
+29
View File
@@ -0,0 +1,29 @@
import process from "node:process";
import { writeFile } from "node:fs/promises";
import { resolve } from "node:path";
import { zodToJsonSchema } from "zod-to-json-schema";
import { answerUiCatalog, ANSWER_UI_VERSION } from "../src/features/agent/answer-ui/catalog.ts";
const targets = process.argv[2]
? [resolve(process.argv[2])]
: [
resolve("../next-tjwater-agent/src/chat/answer-ui-catalog.json"),
resolve("../next-tjwater-server/contracts/answer-ui-catalog.json")
];
const contract = {
version: ANSWER_UI_VERSION,
description:
"Generated from supply frontend src/features/agent/answer-ui/catalog.ts. Regenerate after catalog changes.",
schema: answerUiCatalog.jsonSchema(),
components: answerUiCatalog.componentNames,
props: Object.fromEntries(
Object.entries(answerUiCatalog.data.components).map(([name, definition]) => [
name,
zodToJsonSchema(definition.props, { $refStrategy: "none" })
])
)
};
for (const target of targets) {
await writeFile(target, `${JSON.stringify(contract, null, 2)}\n`);
process.stdout.write(`Exported ${contract.components.length} components to ${target}\n`);
}
+35
View File
@@ -0,0 +1,35 @@
import process from "node:process";
import { readFile, writeFile } from "node:fs/promises";
import { fileURLToPath, URL } from "node:url";
import { zodToJsonSchema } from "zod-to-json-schema";
import { viewCommandSchema } from "../src/features/agent/presentation/command-schema.ts";
const sourceUrl = new URL("../src/features/agent/presentation/command-schema.ts", import.meta.url);
const source = await readFile(sourceUrl, "utf8");
const schema =
JSON.stringify(zodToJsonSchema(viewCommandSchema, { $refStrategy: "none" }), null, 2) + "\n";
const targets = [
[
new URL("../../next-tjwater-agent/src/frontendAction/command.ts", import.meta.url),
"// Generated by next-tjwater-frontend/scripts/export-view-command-contract.mjs.\n" + source
],
[
new URL(
"../../next-tjwater-agent/src/frontendAction/view-command.schema.json",
import.meta.url
),
schema
],
[new URL("../../next-tjwater-server/contracts/view-command.schema.json", import.meta.url), schema]
];
for (const [url, content] of targets) {
if (process.argv.includes("--check")) {
if ((await readFile(url, "utf8")) !== content)
throw new Error(`View command contract differs: ${fileURLToPath(url)}`);
} else {
await writeFile(url, content);
}
}
process.stdout.write(
`View command contract ${process.argv.includes("--check") ? "checked" : "exported"}.\n`
);
+75
View File
@@ -0,0 +1,75 @@
import { Buffer } from "node:buffer";
import { readFile, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { cwd, stdout } from "node:process";
import { URL } from "node:url";
import { chromium } from "@playwright/test";
import { build } from "esbuild";
const require = createRequire(import.meta.url);
const riveRequire = createRequire(require.resolve("@rive-app/react-webgl2"));
const wasm = await readFile(riveRequire.resolve("@rive-app/webgl2/rive.wasm"));
const resource = await readFile(new URL("../public/agent/obsidian-water-v1.riv", import.meta.url));
const harness = `import { RuntimeLoader } from '@rive-app/react-webgl2';
RuntimeLoader.setWasmUrl('/runtime.wasm');
window.stills = new Promise(resolve => RuntimeLoader.getInstance(resolve)).then(async runtime => {
const bytes = new Uint8Array(await (await fetch('/resource.riv')).arrayBuffer());
const file = await runtime.load(bytes, undefined, false);
const canvas = document.querySelector('canvas');
const renderer = runtime.makeRenderer(canvas, true);
const images = {};
try {
for (const state of ['idle', 'asleep']) {
const artboard = file.defaultArtboard();
const machine = new runtime.StateMachineInstance(artboard.stateMachineByName('default'), artboard);
try {
for (let i = 0; i < machine.inputCount(); i++) {
const input = machine.input(i);
input.asBool().value = input.name === state;
}
for (let frame = 0; frame < (state === 'idle' ? 90 : 180); frame++) {
machine.advance(1 / 60);
artboard.advance(1 / 60);
}
renderer.clear();
renderer.save();
renderer.align(runtime.Fit.contain, runtime.Alignment.center,
{ minX: 0, minY: 0, maxX: 192, maxY: 192 }, artboard.bounds);
artboard.draw(renderer);
renderer.restore();
renderer.flush();
runtime.resolveAnimationFrame();
images[state] = canvas.toDataURL('image/png');
} finally { machine.delete(); artboard.delete(); }
}
return images;
} finally { renderer.delete(); file.delete(); }
});`;
const bundled = await build({
stdin: { contents: harness, resolveDir: cwd() },
bundle: true, write: false, format: "iife"
});
const browser = await chromium.launch({ args: ["--enable-unsafe-swiftshader"] });
try {
const page = await browser.newPage();
await page.route("http://persona-render.local/**", async (route) => {
const path = new URL(route.request().url()).pathname;
if (path.endsWith(".wasm")) return route.fulfill({ body: wasm, contentType: "application/wasm" });
if (path.endsWith(".riv")) return route.fulfill({ body: resource });
if (path.endsWith(".js")) return route.fulfill({ body: bundled.outputFiles[0].text, contentType: "application/javascript" });
return route.fulfill({
contentType: "text/html",
body: '<canvas width="192" height="192"></canvas><script src="/render.js"></script>'
});
});
await page.goto("http://persona-render.local/");
const images = await page.evaluate("window.stills");
for (const [state, image] of Object.entries(images)) {
const name = state === "asleep" ? "offline" : state;
const path = new URL(`../public/agent/obsidian-water-${name}.png`, import.meta.url);
await writeFile(path, Buffer.from(image.split(",")[1], "base64"));
}
stdout.write("Rendered current Rive material into online and ring-free offline fallback images.\n");
} finally {
await browser.close();
}
+53
View File
@@ -7,6 +7,13 @@ import {
type EdgeTtsMiddlewareOptions,
type EdgeTtsSynthesizer
} from "./edge-tts-service";
import type { SpeechVoice } from "../src/shared/tts/voices";
const voices: SpeechVoice[] = [
{ id: "zh-CN-XiaoxiaoNeural", name: "Xiaoxiao", locale: "zh-CN", gender: "Female" },
{ id: "zh-CN-YunyangNeural", name: "Yunyang", locale: "zh-CN", gender: "Male" },
{ id: "zh-CN-XiaoyiNeural", name: "Xiaoyi", locale: "zh-CN", gender: "Female" }
];
const servers: ReturnType<typeof createServer>[] = [];
@@ -39,6 +46,52 @@ function postSpeech(baseUrl: string, body: unknown, headers = true) {
}
describe("Edge TTS adapter", () => {
it("falls back to Mandarin when a non-Mandarin default is configured", async () => {
const synthesize = vi.fn<EdgeTtsSynthesizer>(async () => Uint8Array.from([1]));
const baseUrl = await startServer({ defaultVoice: "en-US-AriaNeural", synthesize });
expect((await postSpeech(baseUrl, { text: "测试" })).status).toBe(200);
expect(synthesize).toHaveBeenCalledWith("测试", "zh-CN-XiaoxiaoNeural");
});
it("returns all voices and the default, sharing the catalog with selection validation", async () => {
const listVoices = vi.fn(async () => voices);
const synthesize = vi.fn<EdgeTtsSynthesizer>(async () => Uint8Array.from([1]));
const baseUrl = await startServer({ listVoices, synthesize, defaultVoice: voices[0].id });
const response = await fetch(`${baseUrl}/api/tts/edge/voices`);
expect(response.status).toBe(200);
expect(response.headers.get("cache-control")).toBe("no-store");
expect(await response.json()).toEqual({ voices, defaultVoice: voices[0].id });
expect((await postSpeech(baseUrl, { text: "测试", voice: voices[1].id })).status).toBe(200);
expect(synthesize).toHaveBeenLastCalledWith("测试", voices[1].id);
expect((await postSpeech(baseUrl, { text: "test", voice: voices[2].id })).status).toBe(200);
expect(synthesize).toHaveBeenLastCalledWith("test", voices[2].id);
expect(listVoices).toHaveBeenCalledOnce();
});
it("rejects unknown and malformed voice choices before synthesis", async () => {
const synthesize = vi.fn<EdgeTtsSynthesizer>(async () => Uint8Array.from([1]));
const baseUrl = await startServer({ listVoices: async () => voices, synthesize });
for (const voice of ["zh-CN-UnknownNeural", "en-US-AriaNeural", "zh-TW-HsiaoChenNeural", "zh-CN-liaoning-XiaobeiNeural", "<voice name='bad'>", null, 12, {}]) {
expect((await postSpeech(baseUrl, { text: "测试", voice })).status).toBe(400);
}
expect(synthesize).not.toHaveBeenCalled();
});
it("can use the default when the catalog is unavailable and retry a failed catalog load", async () => {
const listVoices = vi.fn().mockRejectedValueOnce(new Error("offline")).mockResolvedValue(voices);
const synthesize = vi.fn<EdgeTtsSynthesizer>(async () => Uint8Array.from([1]));
const baseUrl = await startServer({ listVoices, synthesize });
expect((await fetch(`${baseUrl}/api/tts/edge/voices`)).status).toBe(503);
expect((await postSpeech(baseUrl, { text: "默认" })).status).toBe(200);
expect((await fetch(`${baseUrl}/api/tts/edge/voices`)).status).toBe(200);
expect(listVoices).toHaveBeenCalledTimes(2);
});
it("refuses a chosen voice when its availability cannot be verified", async () => {
const synthesize = vi.fn<EdgeTtsSynthesizer>(async () => Uint8Array.from([1]));
const baseUrl = await startServer({ listVoices: async () => { throw new Error("offline"); }, synthesize });
expect((await postSpeech(baseUrl, { text: "测试", voice: voices[1].id })).status).toBe(503);
expect(synthesize).not.toHaveBeenCalled();
});
it("returns synthesized MP3 audio with the server-owned voice", async () => {
const synthesize = vi.fn<EdgeTtsSynthesizer>(async () => Uint8Array.from([73, 68, 51]));
const baseUrl = await startServer({ synthesize, defaultVoice: "zh-CN-XiaoxiaoNeural" });
+54 -17
View File
@@ -1,7 +1,10 @@
import type { IncomingMessage, ServerResponse } from "node:http";
import { Communicate } from "edge-tts-ts";
import { EdgeTTS } from "node-edge-tts";
import { speechVoiceIdSchema, type SpeechVoice } from "../src/shared/tts/voices";
import { createEdgeTtsVoiceCatalog } from "./edge-tts-voices";
const EDGE_TTS_PATH = "/api/tts/edge";
const EDGE_TTS_VOICES_PATH = `${EDGE_TTS_PATH}/voices`;
const DEFAULT_VOICE = "zh-CN-XiaoxiaoNeural";
const MAX_REQUEST_BYTES = 8 * 1024;
const MAX_TEXT_LENGTH = 520;
@@ -32,6 +35,7 @@ export type EdgeTtsMiddlewareOptions = {
synthesize?: EdgeTtsSynthesizer;
timeoutMs?: number;
trustProxy?: boolean;
listVoices?: () => Promise<SpeechVoice[]>;
};
function sendJson(response: ServerResponse, status: number, message: string) {
@@ -76,14 +80,15 @@ function getClientKey(request: IncomingMessage, trustProxy: boolean) {
}
export async function synthesizeEdgeSpeech(text: string, voice: string): Promise<Uint8Array> {
const communicate = new Communicate(text, { voice });
const communicate = new EdgeTTS({ voice, timeout: DEFAULT_TIMEOUT_MS });
const chunks: Uint8Array[] = [];
let byteLength = 0;
for await (const chunk of communicate.stream()) {
if (chunk.type !== "audio") continue;
chunks.push(chunk.data);
byteLength += chunk.data.byteLength;
for await (const chunk of communicate.streamAudio(text)) {
if (!Buffer.isBuffer(chunk)) continue;
chunks.push(chunk);
byteLength += chunk.byteLength;
if (byteLength > MAX_AUDIO_BYTES) throw new Error("语音服务返回的音频过大");
}
if (!byteLength) throw new Error("语音服务返回了空音频");
@@ -99,27 +104,32 @@ export async function synthesizeEdgeSpeech(text: string, voice: string): Promise
export function createEdgeTtsMiddleware(options: EdgeTtsMiddlewareOptions = {}) {
const synthesize = options.synthesize ?? synthesizeEdgeSpeech;
const defaultVoice = options.defaultVoice ?? process.env.EDGE_TTS_VOICE ?? DEFAULT_VOICE;
const configuredVoice = options.defaultVoice ?? process.env.EDGE_TTS_VOICE ?? DEFAULT_VOICE;
const defaultVoice = speechVoiceIdSchema.safeParse(configuredVoice).success ? configuredVoice : DEFAULT_VOICE;
const maxConcurrent = options.maxConcurrent ?? DEFAULT_MAX_CONCURRENT;
const maxRequestsPerWindow = options.maxRequestsPerWindow ?? DEFAULT_RATE_LIMIT;
const rateWindowMs = options.rateWindowMs ?? DEFAULT_RATE_WINDOW_MS;
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const trustProxy = options.trustProxy ?? false;
const now = options.now ?? Date.now;
const listVoices = createEdgeTtsVoiceCatalog(options.listVoices, now);
const rateBuckets = new Map<string, RateBucket>();
let activeRequests = 0;
return async (request: IncomingMessage, response: ServerResponse, next?: () => void) => {
if (request.url?.split("?", 1)[0] !== EDGE_TTS_PATH) {
const path = request.url?.split("?", 1)[0];
const voicesRequest = path === EDGE_TTS_VOICES_PATH;
if (path !== EDGE_TTS_PATH && !voicesRequest) {
next?.();
return;
}
if (request.method !== "POST") {
response.setHeader("Allow", "POST");
sendJson(response, 405, "仅支持 POST 请求");
const method = voicesRequest ? "GET" : "POST";
if (request.method !== method) {
response.setHeader("Allow", method);
sendJson(response, 405, `仅支持 ${method} 请求`);
return;
}
if (!request.headers["content-type"]?.toLowerCase().startsWith("application/json")) {
if (!voicesRequest && !request.headers["content-type"]?.toLowerCase().startsWith("application/json")) {
sendJson(response, 415, "请求必须使用 application/json");
return;
}
@@ -143,6 +153,19 @@ export function createEdgeTtsMiddleware(options: EdgeTtsMiddlewareOptions = {})
return;
}
if (voicesRequest) {
try {
const voices = await listVoices();
response.statusCode = 200;
response.setHeader("Content-Type", "application/json; charset=utf-8");
response.setHeader("Cache-Control", "no-store");
response.end(JSON.stringify({ voices, defaultVoice }));
} catch {
sendJson(response, 503, "音色列表暂时不可用,请稍后重试");
}
return;
}
let payload: EdgeTtsPayload;
try {
payload = await readJson(request);
@@ -151,10 +174,6 @@ export function createEdgeTtsMiddleware(options: EdgeTtsMiddlewareOptions = {})
return;
}
if (Object.prototype.hasOwnProperty.call(payload, "voice")) {
sendJson(response, 400, "语音角色只能由服务端配置");
return;
}
const text = typeof payload.text === "string" ? payload.text.trim() : "";
if (!text) {
sendJson(response, 400, "缺少待朗读文本");
@@ -164,6 +183,24 @@ export function createEdgeTtsMiddleware(options: EdgeTtsMiddlewareOptions = {})
sendJson(response, 413, `单次文本不能超过 ${MAX_TEXT_LENGTH} 字`);
return;
}
let voice = defaultVoice;
if (Object.prototype.hasOwnProperty.call(payload, "voice")) {
const selectedVoice = speechVoiceIdSchema.safeParse(payload.voice);
if (!selectedVoice.success) {
sendJson(response, 400, "请选择有效音色");
return;
}
try {
if (!(await listVoices()).some((item) => item.id === selectedVoice.data)) {
sendJson(response, 400, "所选音色不可用,请重新选择");
return;
}
voice = selectedVoice.data;
} catch {
sendJson(response, 503, "无法确认音色是否可用,请稍后重试");
return;
}
}
if (activeRequests >= maxConcurrent) {
response.setHeader("Retry-After", "1");
sendJson(response, 429, "语音服务繁忙,请稍后重试");
@@ -171,7 +208,7 @@ export function createEdgeTtsMiddleware(options: EdgeTtsMiddlewareOptions = {})
}
activeRequests += 1;
const synthesisTask = Promise.resolve().then(() => synthesize(text, defaultVoice));
const synthesisTask = Promise.resolve().then(() => synthesize(text, voice));
void synthesisTask.finally(() => {
activeRequests -= 1;
}).catch(() => undefined);
+42
View File
@@ -0,0 +1,42 @@
import { EdgeTTS } from "node-edge-tts";
import { afterEach, expect, it, vi } from "vitest";
import { synthesizeEdgeSpeech } from "./edge-tts-service";
afterEach(() => vi.restoreAllMocks());
it("collects streamed MP3 bytes with the configured voice and a bounded timeout", async () => {
const stream = vi.spyOn(EdgeTTS.prototype, "streamAudio").mockImplementation(async function* (this: EdgeTTS) {
expect(this).toMatchObject({ voice: "zh-CN-XiaoxiaoNeural", timeout: 30_000 });
yield Buffer.from([73, 68]);
yield { part: "测试", start: 0, end: 1 };
yield Buffer.from([51]);
});
expect(await synthesizeEdgeSpeech("测试", "zh-CN-XiaoxiaoNeural"))
.toEqual(Uint8Array.from([73, 68, 51]));
expect(stream).toHaveBeenCalledWith("测试");
});
it("rejects empty audio and propagates upstream failures", async () => {
const stream = vi.spyOn(EdgeTTS.prototype, "streamAudio").mockImplementation(async function* () {});
await expect(synthesizeEdgeSpeech("测试", "zh-CN-XiaoxiaoNeural")).rejects.toThrow("空音频");
stream.mockImplementation(async function* () {
yield { part: "测试", start: 0, end: 1 };
throw new Error("upstream unavailable");
});
await expect(synthesizeEdgeSpeech("测试", "zh-CN-XiaoxiaoNeural"))
.rejects.toThrow("upstream unavailable");
});
it("stops consuming an oversized audio stream", async () => {
const closed = vi.fn();
vi.spyOn(EdgeTTS.prototype, "streamAudio").mockImplementation(async function* () {
try {
yield Buffer.alloc(5 * 1024 * 1024 + 1);
throw new Error("must stop before consuming more audio");
} finally {
closed();
}
});
await expect(synthesizeEdgeSpeech("测试", "zh-CN-XiaoxiaoNeural")).rejects.toThrow("音频过大");
expect(closed).toHaveBeenCalledOnce();
});
+35
View File
@@ -0,0 +1,35 @@
import { afterEach, expect, it, vi } from "vitest";
import { createEdgeTtsVoiceCatalog, fetchEdgeTtsVoices } from "./edge-tts-voices";
afterEach(() => vi.unstubAllGlobals());
it("deduplicates simultaneous catalog loads and refreshes after one hour", async () => {
let now = 0;
const load = vi.fn(async () => [{ id: "zh-CN-XiaoxiaoNeural", name: "Xiaoxiao", locale: "zh-CN" as const, gender: "Female" as const }]);
const catalog = createEdgeTtsVoiceCatalog(load, () => now);
const [first, second] = await Promise.all([catalog(), catalog()]);
expect(first).toBe(second);
expect(await catalog()).toBe(first);
expect(load).toHaveBeenCalledOnce();
now = 3_600_001;
await catalog();
expect(load).toHaveBeenCalledTimes(2);
});
it("requests v2 authentication and only exposes validated mainland Mandarin voices", async () => {
const upstream = [
{ ShortName: "zh-CN-XiaoxiaoNeural", FriendlyName: "Xiaoxiao", Locale: "zh-CN", Gender: "Female" },
{ ShortName: "en-US-AriaNeural", FriendlyName: "Aria", Locale: "en-US", Gender: "Female" },
{ ShortName: "zh-HK-HiuMaanNeural", FriendlyName: "HiuMaan", Locale: "zh-HK", Gender: "Female" },
{ ShortName: "zh-TW-HsiaoChenNeural", FriendlyName: "HsiaoChen", Locale: "zh-TW", Gender: "Female" },
{ ShortName: "zh-CN-liaoning-XiaobeiNeural", FriendlyName: "Xiaobei", Locale: "zh-CN-liaoning", Gender: "Female" }
];
const fetchMock = vi.fn(async () => new Response(JSON.stringify(upstream)));
vi.stubGlobal("fetch", fetchMock);
expect(await fetchEdgeTtsVoices()).toEqual([{ id: upstream[0].ShortName, name: "Xiaoxiao", locale: "zh-CN", gender: "Female" }]);
const [url] = fetchMock.mock.calls[0] as unknown as [URL];
expect(url.searchParams.get("Sec-MS-GEC-Version")).toMatch(/^2-/);
expect(url.searchParams.get("Sec-MS-GEC")).toMatch(/^[0-9A-F]{16}-[0-9A-F]{64}$/);
fetchMock.mockImplementation(async () => new Response(JSON.stringify([{ ...upstream[0], ShortName: "bad<xml>" }])));
await expect(fetchEdgeTtsVoices()).rejects.toThrow();
});
+44
View File
@@ -0,0 +1,44 @@
import { z } from "zod";
import { generateSecMsGecToken_V2, SEC_MS_GEC_VERSION_V2, TRUSTED_CLIENT_TOKEN } from "node-edge-tts/dist/drm";
import { speechVoiceSchema, type SpeechVoice } from "../src/shared/tts/voices";
const upstreamVoicesSchema = z.array(z.object({
ShortName: z.string().min(1).max(120),
FriendlyName: z.string().min(1).max(200),
Locale: z.string().min(2).max(40),
Gender: z.enum(["Female", "Male"])
})).min(1).max(2_000);
export async function fetchEdgeTtsVoices(): Promise<SpeechVoice[]> {
const url = new URL("https://speech.platform.bing.com/consumer/speech/synthesize/readaloud/voices/list");
url.searchParams.set("trustedclienttoken", TRUSTED_CLIENT_TOKEN);
url.searchParams.set("Sec-MS-GEC", generateSecMsGecToken_V2());
url.searchParams.set("Sec-MS-GEC-Version", SEC_MS_GEC_VERSION_V2);
const response = await fetch(url, { signal: AbortSignal.timeout(10_000) });
if (!response.ok) throw new Error(`Edge TTS voice catalog returned ${response.status}`);
const voices = upstreamVoicesSchema.parse(await response.json()).filter((voice) => voice.Locale === "zh-CN");
if (!voices.length) throw new Error("Edge TTS returned no Mandarin voices");
return voices.map((voice) => speechVoiceSchema.parse({
id: voice.ShortName, name: voice.FriendlyName, locale: voice.Locale, gender: voice.Gender
}));
}
export function createEdgeTtsVoiceCatalog(
load: () => Promise<SpeechVoice[]> = fetchEdgeTtsVoices,
now: () => number = Date.now
) {
let cached: SpeechVoice[] | undefined;
let expiresAt = 0;
let pending: Promise<SpeechVoice[]> | undefined;
return () => {
if (cached && now() < expiresAt) return Promise.resolve(cached);
if (!pending) {
pending = Promise.resolve().then(load).then((voices) => {
cached = voices;
expiresAt = now() + 60 * 60 * 1_000;
return voices;
}).finally(() => { pending = undefined; });
}
return pending;
};
}
+36 -15
View File
@@ -1,4 +1,12 @@
import { readThemeColor } from "../../tests/browser/support/theme-colors";
import { expect, test } from "@playwright/test";
import { mockAgentApi } from "../../tests/browser/support/mock-agent-api";
import { mockWorkbenchContext } from "../../tests/browser/support/mock-workbench-context";
test.beforeEach(async ({ page }) => {
await mockWorkbenchContext(page);
await mockAgentApi(page);
});
test("renders the migrated WebGIS workbench shell", async ({ page }) => {
const riveRequests: string[] = [];
@@ -9,15 +17,25 @@ test("renders the migrated WebGIS workbench shell", async ({ page }) => {
});
await page.goto("/");
await expect(page.getByText("供水管网智能调度系统")).toBeVisible();
await expect(page.getByText("调度工作台")).toBeVisible();
await expect(page).toHaveTitle("供水管网智慧运维系统");
const faviconHref = await page.locator('link[rel="icon"]').getAttribute("href");
expect(faviconHref).toBe("/favicon.svg");
const favicon = await page.request.get(faviconHref!);
expect(favicon.ok()).toBe(true);
expect(favicon.headers()["content-type"]).toContain("image/svg+xml");
await expect(page.getByText("供水管网智慧运维系统")).toBeVisible();
await expect(page.getByText("运维工作台")).toBeVisible();
await expect(page.getByLabel("Agent 折叠栏")).toBeVisible();
await expect(page.getByLabel("Agent 命令面板")).toHaveCount(0);
await page.getByRole("button", { name: /展开 Agent 助手面板/ }).click();
await expect(page.getByLabel("推荐问题")).toBeVisible();
const runtimeConfig = await page.evaluate(() => globalThis.__TJWATER_CONFIG__);
expect(runtimeConfig).toMatchObject({
TJWATER_MAP_URL: expect.any(String),
TJWATER_GEOSERVER_WORKSPACE: expect.any(String),
TJWATER_AGENT_API_BASE_URL: expect.any(String)
TJWATER_SERVER_API_BASE_URL: expect.any(String),
TJWATER_AGENT_URL: expect.any(String)
});
expect(Object.keys(runtimeConfig as Record<string, unknown>)).not.toContainEqual(
expect.stringMatching(/^(NEXT_PUBLIC_|VITE_)/)
@@ -37,7 +55,7 @@ test("animates the compact header menu without overflowing", async ({ page }) =>
await page.setViewportSize({ width: 375, height: 812 });
await page.goto("/");
await page.locator('button[aria-label^="查看异常处置面板"]:visible').click();
await page.locator('button[aria-label^="查看待办与告警"]:visible').click();
const menu = page.locator('[role="menu"][data-state="open"]');
await expect(menu).toBeVisible();
@@ -71,20 +89,24 @@ test("renders map notices through a single toaster", async ({ page }) => {
test("preserves compact typography in header and agent controls", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 });
await page.goto("/");
await page.getByRole("button", { name: /展开 Agent 助手面板/ }).click();
const headerControl = page.locator("header.acrylic-navigation button.font-semibold:visible").first();
const headerControl = page
.locator("header.acrylic-navigation button.font-semibold:visible")
.first();
const approvalControl = page.getByRole("button", { name: "权限批准模式" });
const suggestion = page.locator("[aria-label=推荐问题] button").first();
await expect(headerControl).toHaveCSS("font-weight", "600");
await expect(approvalControl).toHaveCSS("font-size", "12px");
await expect(approvalControl).toHaveCSS("line-height", "16px");
await expect(suggestion).toHaveCSS("font-size", "12px");
await expect(suggestion).toHaveCSS("font-weight", "600");
await expect(approvalControl).toHaveCSS("font-size", "14px");
await expect(approvalControl).toHaveCSS("line-height", "20px");
await expect(suggestion).toHaveCSS("font-size", "14px");
await expect(suggestion).toHaveCSS("font-weight", "400");
});
test("lets interactive utilities override surface materials", async ({ page }) => {
await page.goto("/");
await page.getByRole("button", { name: /展开 Agent 助手面板/ }).click();
await page.addStyleTag({ content: "*,*::before,*::after{transition:none!important}" });
const suggestion = page.locator("[aria-label=推荐问题] button").first();
@@ -112,18 +134,17 @@ test("keeps menu origin and the solid Main Frame styling through Tailwind v4", a
expect(menuTransformOrigin).not.toBe("50% 50%");
await page.keyboard.press("Escape");
const navigation = page.getByRole("complementary", { name: "工作台导航" });
const navigationMaterial = await navigation.evaluate(
(element) => {
await page.getByRole("button", { name: /展开 Agent 助手面板/ }).click();
const navigation = page.getByRole("complementary", { name: "Agent 命令面板" });
const navigationMaterial = await navigation.evaluate((element) => {
const style = window.getComputedStyle(element);
return {
backdropFilter: style.backdropFilter,
backgroundColor: style.backgroundColor
};
}
);
});
expect(navigationMaterial.backdropFilter).toBe("none");
expect(navigationMaterial.backgroundColor).toBe("rgb(237, 241, 245)");
expect(navigationMaterial.backgroundColor).toBe(await readThemeColor(navigation, "--surface-navigation"));
await expect(page.locator("#main-workspace")).toHaveAttribute("data-layout-mode", "default");
await expect(page.getByRole("toolbar", { name: "工作区窗口任务栏" })).toHaveCount(0);
});
+2 -2
View File
@@ -1,12 +1,12 @@
import { MapToaster } from "@/features/map/core";
import { MapWorkbenchPage } from "@/features/workbench";
import { ProjectWorkbench } from "@/features/workbench";
import type { Authentication } from "@/shared/auth/keycloak-auth";
import { AppProviders } from "./providers";
export function App({ authentication }: { authentication: Authentication }) {
return (
<AppProviders>
<MapWorkbenchPage
<ProjectWorkbench
user={authentication.user ?? undefined}
onLogout={authentication.logout}
getAccessToken={authentication.getAccessToken}
+12 -21
View File
@@ -1,26 +1,17 @@
import { Droplets, RefreshCw } from "lucide-react";
import { Button } from "@/shared/ui/button";
import { Droplet } from "lucide-react";
import { StartupScreen } from "@/shared/ui/startup-screen";
export function AuthStartupScreen({ error }: { error?: boolean }) {
return (
<main className="grid min-h-[100dvh] place-items-center bg-slate-100 px-5 text-slate-900">
<section className="surface-reading w-full max-w-md p-6 text-center shadow-xl shadow-slate-900/5">
<span className="mx-auto grid h-11 w-11 place-items-center rounded-xl bg-blue-600 text-white">
<Droplets size={22} aria-hidden="true" />
</span>
<h1 className="mt-4 text-lg font-semibold">
{error ? "统一身份认证连接失败" : "正在连接统一身份认证"}
</h1>
<p className="mt-2 text-sm leading-6 text-slate-500">
{error ? "请检查网络或 Keycloak 配置后重试。" : "正在检查登录状态,请稍候。"}
</p>
{error ? (
<Button className="mt-5" onClick={() => window.location.reload()}>
<RefreshCw size={15} aria-hidden="true" />
重新连接
</Button>
) : null}
</section>
</main>
<StartupScreen
brand={{ name: "TJWater", description: "智慧水务平台", icon: <Droplet strokeWidth={1.5} /> }}
title={error ? "统一身份认证连接失败" : "正在连接统一身份认证"}
description={error ? "连接恢复后,可以重新尝试登录。" : "正在确认登录状态,完成后自动继续。"}
progressLabel="身份认证进度"
steps={[{ id: "identity", label: "检查登录状态", detail: "连接认证服务,确认登录状态", state: "loading" }]}
error={error ? "暂时无法连接登录服务,请检查网络连接后重试。" : null}
retryLabel="重新连接"
onRetry={() => window.location.reload()}
/>
);
}
@@ -0,0 +1,70 @@
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { AnswerUiView } from "./answer-ui-view";
import { parseAnswerUiBlock } from "./contract";
vi.mock("echarts-for-react", () => ({ default: () => <div /> }));
function block(type: string, props: Record<string, unknown>) {
const result = parseAnswerUiBlock({ version: "answer-ui@1", block_id: "actions", fallback_text: "资料", spec: { root: "action", elements: { action: { type, props, children: [] } } } });
if (!result) throw new Error("invalid fixture");
return result;
}
const location = block("MapLocation", { label: "定位要素", source: "查询结果", layer: "pipes", feature_ids: ["P1", "P2"] });
const form = block("FollowUpForm", { title: "现场资料", description: "用户补充", fields: [{ name: "record", label: "记录", kind: "text", required: true }] });
describe("answer action states", () => {
it.each([
[{ located_ids: ["P1", "P2"], missing_ids: [] }, "success", "已定位 2 个"],
[{ located_ids: ["P1"], missing_ids: ["P2"] }, "partial", "另有 1 个未找到"],
[{ located_ids: [], missing_ids: ["P1", "P2"] }, "error", "未找到可定位"],
[undefined, "unconfirmed", "未返回定位结果"]
])("reports verified location outcomes %j", async (result, state, text) => {
render(<AnswerUiView block={location} onLocate={vi.fn().mockResolvedValue(result)} />);
fireEvent.click(screen.getByRole("button", { name: "定位要素" }));
await waitFor(() => expect(screen.getByRole("group", { name: "定位要素" })).toHaveAttribute("data-state", state));
expect(screen.getByRole("status")).toHaveTextContent(text);
});
it("explains unsupported location", () => {
render(<AnswerUiView block={location} />);
expect(screen.getByRole("button", { name: "定位要素" })).toBeDisabled();
expect(screen.getByText("当前视图不支持地图定位,可查看关联要素编号。")).toBeInTheDocument();
});
it("locks pending location and supports retry after rejection", async () => {
let reject!: (error: Error) => void;
const locate = vi.fn().mockImplementationOnce(() => new Promise((_, fail) => { reject = fail; })).mockResolvedValue({ located_ids: ["P1"], missing_ids: ["P2"] });
render(<AnswerUiView block={location} onLocate={locate} />);
fireEvent.click(screen.getByRole("button", { name: "定位要素" }));
expect(screen.getByRole("group", { name: "定位要素" })).toHaveAttribute("aria-busy", "true");
expect(screen.getByRole("button", { name: "正在定位…" })).toBeDisabled();
await act(async () => reject(new Error("网络失败")));
fireEvent.click(screen.getByRole("button", { name: "重试定位要素" }));
await waitFor(() => expect(locate).toHaveBeenCalledTimes(2));
});
it("associates required errors, retains failed drafts and clears success when editing", async () => {
let complete!: () => void;
const submit = vi.fn().mockRejectedValueOnce(new Error("发送失败")).mockImplementationOnce(() => new Promise<void>((resolve) => { complete = resolve; }));
render(<AnswerUiView block={form} onSubmit={submit} />);
const editor = screen.getByLabelText("记录(必填)");
const formElement = screen.getByRole("form", { name: "现场资料" });
fireEvent.submit(formElement);
expect(editor).toHaveAttribute("aria-invalid", "true");
expect(editor).toHaveAccessibleDescription("请填写记录。");
fireEvent.change(editor, { target: { value: "草稿" } });
fireEvent.submit(formElement);
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("发送失败"));
expect(editor).toHaveValue("草稿");
fireEvent.submit(formElement);
fireEvent.submit(formElement);
expect(submit).toHaveBeenCalledTimes(2);
expect(formElement).toHaveAttribute("aria-busy", "true");
await act(async () => complete());
expect(screen.getByRole("status")).toHaveTextContent("资料已发送");
fireEvent.change(editor, { target: { value: "更新后的草稿" } });
expect(screen.queryByRole("status")).not.toBeInTheDocument();
expect(screen.getByRole("group", { name: "现场资料" })).toHaveAttribute("data-state", "idle");
});
it("confirms draft transfer without claiming submission", async () => {
render(<AnswerUiView block={form} submitMode="draft" onSubmit={vi.fn()} />);
fireEvent.change(screen.getByLabelText("记录(必填)"), { target: { value: "草稿" } });
fireEvent.click(screen.getByRole("button", { name: "带入对话" }));
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("资料已带入对话,请确认后发送"));
});
});
@@ -0,0 +1,232 @@
import { useContext, useId, useRef, useState } from "react";
import { ArrowUpRight, CheckCircle2, FileCheck2, Info, LoaderCircle, MapPin, TriangleAlert } from "lucide-react";
import { useAnswerMotion } from "./answer-motion-context";
import { motion } from "motion/react";
import { agentEase } from "../components/agent-motion";
import { AnswerDisclosure, AnswerDisclosureChevron } from "./answer-motion";
import { Button } from "@/shared/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/shared/ui/card";
import { DateTimeField } from "@/shared/ui/date-time-field";
import { Input } from "@/shared/ui/input";
import { Textarea } from "@/shared/ui/textarea";
import { AnswerInteractionContext as InteractionContext, type AnswerUiMapTarget } from "./answer-ui-interaction-context";
import { useAnswerNodeState } from "./answer-view-state-provider";
import { answerStatePointer, type AnswerFormState } from "./answer-view-state";
type ActionState = "idle" | "pending" | "success" | "partial" | "unconfirmed" | "error";
function ActionFeedback({ state, children }: { state: ActionState; children: string }) {
const shouldAnimate = useAnswerMotion();
const animate = shouldAnimate();
const Icon = state === "pending" ? LoaderCircle : state === "success" ? CheckCircle2 : state === "error" || state === "partial" ? TriangleAlert : Info;
return <motion.p key={state} initial={animate ? { opacity: 0, y: 3 } : false} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.18, ease: agentEase }} role={state === "idle" ? undefined : "status"} className="mt-1 flex items-start gap-1.5 text-xs leading-5 text-muted-foreground"><Icon size={14} className={`mt-0.5 shrink-0 ${state === "pending" && animate ? "motion-safe:animate-spin" : ""}`} aria-hidden />{children}</motion.p>;
}
export function LocateButton({
label,
source,
...target
}: AnswerUiMapTarget & { label: string; source: string }) {
const { disabled, onLocate } = useContext(InteractionContext);
const runningRef = useRef(false);
const [showIds, setShowIds] = useState(false);
const [state, setState] = useState<ActionState>("idle");
const running = state === "pending";
const [feedback, setFeedback] = useState<string | null>(null);
return (
<Card className="answer-ui-location" role="group" aria-label={label} data-state={state} aria-busy={running}>
<MapPin size={17} className="mt-1 shrink-0 text-muted-foreground" aria-hidden="true" />
<div className="min-w-0 flex-1">
<Button
size="sm"
variant="outline"
disabled={disabled || running || !onLocate}
onClick={async () => {
if (!onLocate || disabled || runningRef.current) return;
runningRef.current = true;
setState("pending");
setFeedback(null);
try {
const result = await onLocate(target);
if (result === false) throw new Error("关联要素暂不可定位,请检查地图提示。");
const output = result as { located_ids?: string[]; missing_ids?: string[] } | undefined;
if (!output || !Array.isArray(output.located_ids)) {
setState("unconfirmed");
setFeedback("定位请求已处理,未返回定位结果,请查看地图确认。");
} else {
const located = output.located_ids.length;
const missing = output.missing_ids?.length ?? 0;
setState(!located ? "error" : missing ? "partial" : "success");
setFeedback(!located ? "未找到可定位的关联要素,请检查要素编号后重试。" : missing ? `已定位 ${located} 个,另有 ${missing} 个未找到` : `已定位 ${located} 个关联要素到地图`);
}
} catch (error) {
setState("error");
setFeedback(error instanceof Error ? error.message : "地图定位失败,请重试。");
} finally {
runningRef.current = false;
}
}}
>
{running ? "正在定位…" : state === "error" ? `重试${label}` : label}
<ArrowUpRight size={14} aria-hidden="true" />
</Button>
<p className="mt-2 break-words text-xs leading-5 text-muted-foreground">{target.feature_ids.length} 个关联要素 · 依据:{source}</p>
<AnswerDisclosure open={showIds} onOpenChange={setShowIds} className="mt-1 text-[11px] leading-5 text-muted-foreground"
trigger={<Button type="button" variant="ghost" size="sm" className="h-9 gap-1 px-0 text-[11px] font-normal">查看关联要素<AnswerDisclosureChevron open={showIds} /></Button>}>
<p className="mt-1 break-words font-mono">{target.feature_ids.join("、")}</p>
</AnswerDisclosure>
{feedback || running || !onLocate ? <ActionFeedback state={state}>{running ? "正在查找关联要素…" : feedback ?? "当前视图不支持地图定位,可查看关联要素编号。"}</ActionFeedback> : null}
</div>
</Card>
);
}
type FormField = {
name: string;
label: string;
kind: "text" | "datetime" | "number";
required: boolean;
};
export function FollowUpForm({
title,
description,
fields
}: {
title: string;
description: string;
fields: FormField[];
}) {
const { disabled, onSubmit, submitMode } = useContext(InteractionContext);
const prefix = useId();
const [{ values }, patch] = useAnswerNodeState<AnswerFormState>("FollowUpForm", { title, description, fields });
const submittingRef = useRef(false);
const [state, setState] = useState<ActionState>("idle");
const submitting = state === "pending";
const [invalidFields, setInvalidFields] = useState<string[]>([]);
const setValue = (name: string, value: string) => {
patch({ values: { ...values, [name]: value } }, [`values/${answerStatePointer(name)}`]);
setState("idle");
setFeedback(null);
setInvalidFields((current) => current.filter((field) => field !== name));
};
const [feedback, setFeedback] = useState<string | null>(null);
return (
<Card className="answer-ui-form" role="group" aria-label={title} data-state={state} aria-busy={submitting}>
<CardHeader className="gap-2 border-b border-border p-3.5">
<CardTitle className="flex items-center gap-2 text-sm leading-6 tracking-normal"><FileCheck2 size={14} className="shrink-0 text-muted-foreground" aria-hidden />{title}</CardTitle>
<CardDescription className="text-xs leading-5">{description}</CardDescription>
</CardHeader>
<CardContent className="p-3.5">
<form
className="space-y-3"
aria-label={title}
aria-busy={submitting}
noValidate
onSubmit={async (event) => {
event.preventDefault();
if (!onSubmit || disabled || submittingRef.current) return;
const missing = fields.filter((field) => field.required && !values[field.name]?.trim()).map((field) => field.name);
setInvalidFields(missing);
if (missing.length) {
setState("error");
setFeedback("请填写必填资料。");
return;
}
const entries = fields
.filter((field) => values[field.name]?.trim())
.map(
(field) =>
`${field.label}:${values[field.name].trim()}${field.kind === "datetime" ? "(北京时间)" : ""}`
);
if (!entries.length) {
setState("error");
setFeedback("请至少填写一项资料。");
return;
}
if (entries.join("\n").length > 9000) {
setState("error");
setFeedback("补充资料过长,请分次发送。");
return;
}
submittingRef.current = true;
setState("pending");
setFeedback(null);
try {
await onSubmit(
`我补充以下资料,请按用户提供的信息处理,说明保存或调查的实际结果:\n${entries.join("\n")}`
);
setState("success");
setFeedback(submitMode === "draft" ? "资料已带入对话,请确认后发送。" : "资料已发送,请查看 Agent 回复。");
} catch (error) {
setState("error");
setFeedback(error instanceof Error ? error.message : "资料发送失败,请重试。");
} finally {
submittingRef.current = false;
}
}}
>
{fields.map((field) => (
<div key={field.name} role={field.kind === "datetime" ? "group" : undefined} aria-label={field.kind === "datetime" ? `${field.label}${field.required ? "(必填)" : ""}` : undefined} aria-invalid={invalidFields.includes(field.name) || undefined} aria-describedby={invalidFields.includes(field.name) ? `${prefix}-${field.name}-error` : undefined}>
{field.kind === "datetime" ? (
<DateTimeField
key={field.name}
label={`${field.label}${field.required ? "(必填)" : ""}`}
value={values[field.name] ?? ""}
disabled={disabled || submitting || !onSubmit}
onChange={(value) => setValue(field.name, value)}
/>
) : (
<div key={field.name} className="space-y-1.5">
<label htmlFor={`${prefix}-${field.name}`} className="block text-xs font-medium">
{field.label}
{field.required ? "(必填)" : ""}
</label>
{field.kind === "text" ? (
<Textarea
id={`${prefix}-${field.name}`}
aria-required={field.required}
aria-invalid={invalidFields.includes(field.name) || undefined}
aria-describedby={invalidFields.includes(field.name) ? `${prefix}-${field.name}-error` : undefined}
value={values[field.name] ?? ""}
maxLength={500}
disabled={disabled || submitting || !onSubmit}
onChange={(event) => {
const value = event.currentTarget.value;
setValue(field.name, value);
}}
/>
) : (
<Input
className="h-10"
id={`${prefix}-${field.name}`}
aria-required={field.required}
aria-invalid={invalidFields.includes(field.name) || undefined}
aria-describedby={invalidFields.includes(field.name) ? `${prefix}-${field.name}-error` : undefined}
type="number"
value={values[field.name] ?? ""}
maxLength={500}
disabled={disabled || submitting || !onSubmit}
onChange={(event) => {
const value = event.currentTarget.value;
setValue(field.name, value);
}}
/>
)}
</div>
)}
{invalidFields.includes(field.name) ? <p id={`${prefix}-${field.name}-error`} className="mt-1 text-xs leading-5 text-destructive">请填写{field.label}。</p> : null}
</div>
))}
<Button
type="submit"
size="sm"
variant="default"
disabled={disabled || submitting || !onSubmit}
>
{submitting ? submitMode === "draft" ? "正在处理…" : "正在发送…" : submitMode === "draft" ? "带入对话" : "发送补充资料"}
</Button>
{feedback || submitting || !onSubmit ? <ActionFeedback state={state}>{submitting ? submitMode === "draft" ? "正在带入对话…" : "正在发送补充资料…" : feedback ?? "当前视图无法提交资料。"}</ActionFeedback> : null}
</form>
</CardContent>
</Card>
);
}
@@ -0,0 +1,73 @@
import { useRef, type RefObject } from "react";
import { ChartNoAxesCombined, ClipboardPenLine, Gauge, MapPin, BookOpenCheck, Table2, ListTree, ChevronDown, CircleCheck } from "lucide-react";
import { Badge } from "@/shared/ui/badge";
import { Button } from "@/shared/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/shared/ui/dropdown-menu";
import type { AnswerUiBlock } from "./contract";
import { canExpandAnswer } from "./answer-presentation";
const contentKinds = [
{ type: "Result", label: "结果", icon: CircleCheck, selector: "[data-answer-result]" },
{ type: "Metric", label: "指标", icon: Gauge, selector: ".answer-ui-metric" },
{ type: "Chart", label: "趋势", icon: ChartNoAxesCombined, selector: ".answer-ui-chart" },
{ type: "Table", label: "表格", icon: Table2, selector: "[data-answer-table]" },
{ type: "Evidence", label: "依据", icon: BookOpenCheck, selector: ".answer-ui-evidence" },
{ type: "MapLocation", label: "地图", icon: MapPin, selector: ".answer-ui-location" },
{ type: "FollowUpForm", label: "补充资料", icon: ClipboardPenLine, selector: ".answer-ui-form" }
] as const;
/** Navigate the mounted answer so chart selections and unsent forms survive. */
export function AnswerContentNav({ block, contentRef }: {
block: AnswerUiBlock;
contentRef: RefObject<HTMLDivElement | null>;
}) {
const navigationTarget = useRef<HTMLElement | null>(null);
const elements = Object.values(block.spec.elements);
const items = contentKinds.map((kind) => ({
...kind, count: elements.filter((element) => element.type === kind.type).length
})).filter((item) => item.count > 0);
if (items.length < 2 || !canExpandAnswer([{ type: "answer-ui", block }])) return null;
return (
<nav aria-label="回答内容导航" className="answer-content-nav">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button type="button" variant="ghost" size="sm" className="h-9 gap-1.5 px-2 text-xs font-normal">
<ListTree size={14} aria-hidden />浏览回答<ChevronDown size={12} aria-hidden />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" data-agent-theme="chat" className="min-w-48"
onCloseAutoFocus={(event) => {
const target = navigationTarget.current;
navigationTarget.current = null;
if (!target?.isConnected) return;
event.preventDefault();
target.tabIndex = -1;
target.focus({ preventScroll: true });
target.scrollIntoView({ block: "start", behavior: "instant" });
}}>
{items.map(({ type, label, icon: Icon, selector, count }) => (
<DropdownMenuItem key={type} className="min-h-10 gap-2 text-xs"
aria-label={`查看${label},${count}项`}
onSelect={() => {
const target = contentRef.current?.querySelector<HTMLElement>(selector) ?? null;
const section = target?.closest(".answer-task-support-section[data-state=closed]");
section?.querySelector<HTMLButtonElement>(":scope > button")?.click();
navigationTarget.current = target;
}}>
<Icon size={14} aria-hidden />{label}
<Badge variant="secondary" className="ml-auto min-w-4 justify-center rounded-sm border-0 px-1 py-0 text-[10px] tabular-nums">
{count}
</Badge>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
<span className="text-[11px] text-muted-foreground">
{items.map((item, index) => <span key={item.type} className="inline-block whitespace-nowrap">
{index > 0 ? <span aria-hidden> · </span> : null}{item.label}
</span>)}
</span>
</nav>
);
}
@@ -0,0 +1,4 @@
import { createContext, useContext } from "react";
export const AnswerMotionContext = createContext<() => boolean>(() => false);
export const useAnswerMotion = () => useContext(AnswerMotionContext);
@@ -0,0 +1,72 @@
import { forwardRef, useCallback, useLayoutEffect, useRef, useState, type ComponentProps, type ReactElement, type ReactNode } from "react";
import { motion, useAnimationControls, useReducedMotion } from "motion/react";
import { ChevronDown } from "lucide-react";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/shared/ui/collapsible";
import { agentEase } from "../components/agent-motion";
import { AnswerMotionContext, useAnswerMotion } from "./answer-motion-context";
/** Initial rendering is instant; subsequent transitions follow pointer or keyboard modality. */
export function AnswerMotionScope({ children, ...props }: ComponentProps<"div">) {
const pointer = useRef(false);
const reducedMotion = useReducedMotion();
const shouldAnimate = useCallback(() => pointer.current && !reducedMotion, [reducedMotion]);
return <AnswerMotionContext.Provider value={shouldAnimate}>
<div {...props} onPointerDownCapture={() => { pointer.current = true; }}
onKeyDownCapture={() => { pointer.current = false; }}
onClickCapture={(event) => { if (event.detail === 0) pointer.current = false; }}>{children}</div>
</AnswerMotionContext.Provider>;
}
/** Keep the same mounted editors; retiring content is immediately inert and hidden from AT. */
export const AnswerReveal = forwardRef<HTMLDivElement, ComponentProps<typeof motion.div> & { open: boolean }>(
function AnswerReveal({ open, children, ...props }, ref) {
const shouldAnimate = useAnswerMotion();
const reducedMotion = useReducedMotion();
const controls = useAnimationControls();
const previous = useRef(open);
const [retained, setRetained] = useState(open);
useLayoutEffect(() => {
const changed = previous.current !== open;
previous.current = open;
controls.stop();
if (!changed || !shouldAnimate() || reducedMotion) {
controls.set({ opacity: 1, y: 0 });
setRetained(open);
return;
}
let cancelled = false;
if (open) {
setRetained(true);
controls.set({ opacity: 0, y: -4 });
}
void controls.start(open ? { opacity: 1, y: 0 } : { opacity: 0, y: -4 }, {
duration: 0.18, ease: agentEase
}).then(() => { if (!cancelled) setRetained(open); });
return () => { cancelled = true; controls.stop(); };
}, [controls, open, reducedMotion, shouldAnimate]);
return <motion.div {...props} ref={ref} data-answer-reveal data-open={open}
hidden={!open && !retained} inert={!open} aria-hidden={!open || undefined}
initial={false} animate={controls}>{children}</motion.div>;
}
);
export function AnswerDisclosure({ open, onOpenChange, trigger, children, contentClassName, ...props }: {
open: boolean; onOpenChange: (open: boolean) => void; trigger: ReactElement; children: ReactNode;
contentClassName?: string;
} & Omit<ComponentProps<typeof Collapsible>, "children" | "open" | "onOpenChange">) {
return <Collapsible {...props} open={open} onOpenChange={onOpenChange}>
<CollapsibleTrigger asChild>{trigger}</CollapsibleTrigger>
<CollapsibleContent forceMount asChild>
<AnswerReveal open={open} className={contentClassName}>{children}</AnswerReveal>
</CollapsibleContent>
</Collapsible>;
}
export function AnswerDisclosureChevron({ open }: { open: boolean }) {
const shouldAnimate = useAnswerMotion();
return <motion.span aria-hidden className="inline-flex shrink-0" initial={false}
animate={{ rotate: open ? 180 : 0 }} transition={{ duration: shouldAnimate() ? 0.18 : 0, ease: agentEase }}>
<ChevronDown size={14} />
</motion.span>;
}
@@ -0,0 +1,67 @@
import { act, fireEvent, render, screen, cleanup } from "@testing-library/react";
import { afterEach, expect, it, vi } from "vitest";
import type { AnswerViewStateRecord, AnswerViewStateWrite } from "../api/answer-view-state";
import { AnswerViewStateScope } from "../session-state/answer-view-state-scope";
import { AnswerViewPersistenceContext } from "../session-state/answer-view-persistence-context";
import type { AnswerUiBlock } from "./contract";
import { AnswerPartsView } from "./answer-parts-view";
vi.mock("../components/streaming-token-response", () => ({ StreamingTokenResponse: () => null }));
afterEach(() => { cleanup(); vi.useRealTimers(); });
const block: AnswerUiBlock = {
version: "answer-ui@1", block_id: "block", phase: "final", fallback_text: "资料",
spec: { root: "form", elements: { form: { type: "FollowUpForm", children: [], props: {
title: "资料", description: "补充", fields: [{ name: "note", label: "现场记录", kind: "text", required: false }]
} } } }
};
const remote: AnswerViewStateRecord = {
version: "answer-view-state@1", message_id: "message", block_id: "block", revision: 4,
schema_digest: "digest", updated_at: null, nodes: { form: { type: "FollowUpForm", values: { note: "远端" } } }, block: { evidenceFilter: "all" }
};
function fixture() {
let restore!: (value: AnswerViewStateRecord) => void;
const client = { getAnswerViewState: vi.fn(() => new Promise<AnswerViewStateRecord>((resolve) => { restore = resolve; })),
putAnswerViewState: vi.fn(async (_session: string, write: AnswerViewStateWrite) => ({ ...remote, revision: 5, nodes: write.nodes, block: write.block })) };
const scope = new AnswerViewStateScope("actor:project", client);
const view = (persist: boolean, value = block) => <AnswerViewPersistenceContext.Provider value={{ scope, sessionId: "session" }}>
<AnswerPartsView parts={[{ type: "answer-ui", block: value }]} messageId="message" disabled={false} streaming={!persist} streamDone={persist} persist={persist} />
</AnswerViewPersistenceContext.Provider>;
return { scope, client, view, restore: (record: AnswerViewStateRecord) => restore(record) };
}
it("keeps the same form DOM and selection when persistence starts, preserving edits against late restore", async () => {
vi.useFakeTimers();
const f = fixture();
const rendered = render(f.view(false));
const input = screen.getByLabelText("现场记录") as HTMLInputElement;
fireEvent.change(input, { target: { value: "本地草稿" } });
input.focus(); input.setSelectionRange(1, 3);
rendered.rerender(f.view(false, structuredClone(block)));
expect(screen.getByLabelText("现场记录")).toBe(input);
expect(f.client.getAnswerViewState).not.toHaveBeenCalled();
rendered.rerender(f.view(true, structuredClone(block)));
expect(screen.getByLabelText("现场记录")).toBe(input);
expect(input.value).toBe("本地草稿");
expect(input.selectionStart).toBe(1);
expect(input.selectionEnd).toBe(3);
expect(f.client.getAnswerViewState).toHaveBeenCalledTimes(1);
await act(async () => f.restore(remote));
expect(input.value).toBe("本地草稿");
await act(async () => vi.advanceTimersByTimeAsync(500));
expect(f.client.putAnswerViewState.mock.calls[0][1]).toMatchObject({ expected_revision: 4, nodes: { form: { values: { note: "本地草稿" } } } });
rendered.unmount(); f.scope.dispose();
});
it("never reads or writes process blocks even when persistence is requested", async () => {
vi.useFakeTimers();
const f = fixture();
const rendered = render(f.view(true, { ...block, phase: "process" }));
fireEvent.change(screen.getByLabelText("现场记录"), { target: { value: "过程草稿" } });
expect(screen.queryByText("正在恢复交互状态")).toBeNull();
await act(async () => vi.advanceTimersByTimeAsync(2000));
rendered.unmount();
await act(async () => vi.advanceTimersByTimeAsync(1000));
expect(f.client.getAnswerViewState).not.toHaveBeenCalled();
expect(f.client.putAnswerViewState).not.toHaveBeenCalled();
f.scope.dispose();
});
@@ -0,0 +1,91 @@
import { useState, type ComponentProps } from "react";
import { X } from "lucide-react";
import { Button } from "@/shared/ui/button";
import { useAnswerViewPersistence, useAnswerViewState } from "../session-state/use-answer-view-state";
import type { AnswerViewStateScope } from "../session-state/answer-view-state-scope";
import { StreamingTokenResponse } from "../components/streaming-token-response";
import { AnswerUiView, type AnswerUiMapTarget } from "./answer-ui-view";
import type { AnswerUiPart } from "./contract";
export function AnswerPartsView({
parts,
messageId,
disabled,
streaming,
streamDone,
persist = false,
onLocate,
onSubmit,
}: {
parts: AnswerUiPart[];
messageId: string;
disabled: boolean;
streaming: boolean;
streamDone: boolean;
persist?: boolean;
onLocate?: (target: AnswerUiMapTarget) => Promise<unknown> | void;
onSubmit?: (text: string) => Promise<void> | void;
}) {
const persistence = useAnswerViewPersistence();
return (
<div className="flex min-w-0 flex-col gap-5" data-answer-parts>
{parts.map((part, index) =>
part.type === "answer-ui" ? (
<PersistableAnswerUiView
key={`ui-${part.block.block_id}`}
block={part.block}
persistence={persistence}
active={persist && part.block.phase !== "process"}
messageId={messageId}
disabled={disabled}
onLocate={onLocate}
onSubmit={onSubmit}
/>
) : (
<StreamingTokenResponse
key={`text-${index}`}
className="leading-6"
content={part.text}
messageId={`${messageId}-${index}`}
streamDone={streamDone}
streaming={streaming}
/>
)
)}
</div>
);
}
type PersistableProps = ComponentProps<typeof AnswerUiView> & {
messageId: string;
active: boolean;
persistence: { scope: AnswerViewStateScope; sessionId: string } | null;
};
function PersistableAnswerUiView({ persistence, messageId, active, ...props }: PersistableProps) {
if (!persistence) return <AnswerUiView {...props} />;
return <SavedAnswerUiView key={`${persistence.scope.scope}:${persistence.sessionId}:${messageId}:${props.block.block_id}`}
{...props} messageId={messageId} active={active} persistence={persistence} />;
}
function SavedAnswerUiView({ persistence, messageId, active, ...props }: PersistableProps & { persistence: NonNullable<PersistableProps["persistence"]> }) {
const saved = useAnswerViewState(persistence.scope, persistence.sessionId, messageId, props.block.block_id, props.block.spec, active);
const [confirmReload, setConfirmReload] = useState(false);
const label = { loading: "正在恢复交互状态", saving: "正在保存", saved: "已保存", unsaved: "未保存", conflict: "保存冲突" }[saved.status];
return <div className="space-y-2" data-answer-state={active ? saved.status : undefined}>
<AnswerUiView {...props} viewState={saved.state} onViewStateChange={saved.update} />
{active ? <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
<span role="status">{label}</span>
{saved.error ? <span>{saved.error}</span> : null}
{saved.status === "unsaved" ? <Button size="sm" variant="ghost" onClick={saved.retry}>重试保存</Button> : null}
{saved.status === "conflict" && !confirmReload ? <>
<Button size="sm" variant="ghost" onClick={() => setConfirmReload(true)}>重新加载远端</Button>
<Button size="sm" variant="ghost" onClick={saved.resave}>保留本地并重新保存</Button>
</> : null}
{confirmReload ? <div role="alert" className="flex flex-wrap items-center gap-2">
<span>重新加载将替换本块的本地筛选与表单草稿。</span>
<Button size="sm" variant="outline" onClick={() => { setConfirmReload(false); saved.reload(); }}>确认替换本地草稿</Button>
<Button size="icon-sm" variant="ghost" aria-label="取消重新加载" onClick={() => setConfirmReload(false)}><X aria-hidden /></Button>
</div> : null}
</div> : null}
</div>;
}
@@ -0,0 +1,130 @@
import { describe, expect, it } from "vitest";
import type { AgentChatMessage } from "../types";
import { canExpandAnswer, getAnswerPresentation, getFinalAnswerTranscript } from "./answer-presentation";
import type { AnswerUiPart } from "./contract";
const ui = (id: string): AnswerUiPart => ({
type: "answer-ui",
block: {
version: "answer-ui@1",
block_id: id,
fallback_text: id,
spec: {
root: "text",
elements: { text: { type: "Text", props: { text: id, tone: "neutral" }, children: [] } }
}
}
});
const parts: AnswerUiPart[] = [
{ type: "text", text: "正在核对资料。" },
ui("report-chart"),
ui("temporary"),
{ type: "text", text: "查询结束。" }
];
const message: AgentChatMessage = {
id: "a",
role: "assistant",
content: "正在核对资料。",
answerParts: parts
};
describe("final report and collapsible process", () => {
it("keeps short warnings and location confirmations inline while retaining report readers", () => {
const note = ui("note");
if (note.type !== "answer-ui") throw new Error("invalid fixture");
note.block.spec.elements.text.props = { text: "当前工具不能确认高亮。", tone: "warning" };
expect(canExpandAnswer([{ type: "text", text: "已定位管道。" }, note])).toBe(false);
expect(canExpandAnswer([{ type: "text", text: "完整报告".repeat(300) }])).toBe(true);
for (const type of ["Table", "Chart", "FollowUpForm"]) {
note.block.spec.elements.text.type = type;
expect(canExpandAnswer([note])).toBe(true);
}
});
it("shows all incremental content while waiting for final_answer", () => {
expect(getAnswerPresentation(message)).toEqual({ report: parts, process: [], final: false });
});
it("keeps only the final report and explicitly selected components expanded", () => {
const view = getAnswerPresentation({
...message,
finalAnswer: {
content: "最后的报告内容。",
uiBlockIds: ["report-chart", "report-chart", "missing"]
}
});
expect(view.report).toEqual([{ type: "text", text: "最后的报告内容。" }, parts[1]]);
expect(view.process).toEqual([parts[0], parts[2], parts[3]]);
expect(view.final).toBe(true);
});
it("folds every UI block when the final report does not reference any", () => {
const view = getAnswerPresentation({
...message,
finalAnswer: { content: "报告", uiBlockIds: [] }
});
expect(view.report).toEqual([{ type: "text", text: "报告" }]);
expect(view.process).toEqual(parts);
});
});
function phasedUi(id: string, phase: "process" | "final"): AnswerUiPart {
const part = ui(id);
if (part.type === "answer-ui") {
part.block.phase = phase;
part.block.fallback_text = `摘要 ${id}`;
}
return part;
}
describe("final UI anchors", () => {
const chart = phasedUi("chart", "final");
const progress = phasedUi("progress", "process");
it("separates explicit process blocks from the report before a final answer arrives", () => {
const view = getAnswerPresentation({ ...message, answerParts: [parts[0], progress, chart, parts[3]] });
expect(view.report).toEqual([parts[0], chart, parts[3]]);
expect(view.process).toEqual([progress]);
expect(view.final).toBe(false);
});
const anchoredMessage = (content: string, uiBlockIds = ["chart", "progress"]): AgentChatMessage => ({
...message,
answerParts: [parts[0], progress, chart, parts[3]],
finalAnswer: { content, uiBlockIds }
});
it("places final UI between the original Markdown sections and mounts duplicates once", () => {
const content = "# 分析\n\n- 第一项\n\n[[ui:chart]]\n\n## 建议\n保留换行\n[[ui:chart]]\n";
const view = getAnswerPresentation(anchoredMessage(content));
expect(view.report).toEqual([
{ type: "text", text: "# 分析\n\n- 第一项\n\n" },
chart,
{ type: "text", text: "\n## 建议\n保留换行\n" }
]);
expect(view.process).toEqual([parts[0], progress, parts[3]]);
expect(getFinalAnswerTranscript(anchoredMessage(content))).toBe("# 分析\n\n- 第一项\n\n摘要 chart\n## 建议\n保留换行\n");
});
it("never includes process UI even when referenced and anchored", () => {
const value = anchoredMessage("结论\n[[ui:progress]]\n[[ui:missing]]\n[[ui:chart]]", ["progress", "missing"]);
const view = getAnswerPresentation(value);
expect(view.report.every((part) => part.type === "text")).toBe(true);
expect(view.process).toEqual([parts[0], progress, chart, parts[3]]);
const transcript = getFinalAnswerTranscript(value);
expect(transcript).not.toContain("progress");
expect(transcript).not.toContain("missing");
expect(transcript).not.toContain("chart");
expect(transcript).toContain("暂不可用");
});
it("preserves fenced, indented, and quoted markers as literal Markdown", () => {
const literal = "```md\n[[ui:chart]]\n```\n\n~~~\n[[ui:chart]]\n~~~\n\n [[ui:chart]]\n\n> [[ui:chart]]\n";
const view = getAnswerPresentation(anchoredMessage(literal, []));
expect(view.report).toEqual([{ type: "text", text: literal }]);
});
it("retains legacy references and appends final references without anchors", () => {
const view = getAnswerPresentation(anchoredMessage("报告"));
expect(view.report).toEqual([{ type: "text", text: "报告" }, chart]);
expect(getFinalAnswerTranscript(anchoredMessage("报告"))).toBe("报告\n\n摘要 chart");
});
it("does not expand a short answer because of marker identifiers", () => {
expect(canExpandAnswer([{ type: "text", text: `结论\n[[ui:${"x".repeat(1500)}]]` }])).toBe(false);
});
});
@@ -0,0 +1,103 @@
import type { AgentChatMessage } from "../types";
import type { AnswerUiPart } from "./contract";
/** Short notes and map confirmations stay inline; dense data and reports can expand. */
export function canExpandAnswer(parts: AnswerUiPart[]): boolean {
let textLength = 0;
for (const part of parts) {
if (part.type === "text") {
textLength += part.text.replace(/\[\[ui:[^\]\r\n]*\]\]/g, "").length;
} else {
for (const node of Object.values(part.block.spec.elements)) {
if (["Table", "Chart", "FollowUpForm"].includes(node.type)) return true;
if (node.type === "Text" && typeof node.props.text === "string") textLength += node.props.text.length;
if (node.type === "Evidence" && typeof node.props.summary === "string") textLength += node.props.summary.length;
if (node.type === "Result" && typeof node.props.summary === "string") textLength += node.props.summary.length;
}
}
}
return textLength >= 1200;
}
/** Readable copy/TTS text for the same ordered parts shown in the answer. */
export function getAnswerPartsTranscript(parts: AnswerUiPart[]): string {
return parts.reduce((text, part) => {
const next = part.type === "text" ? part.text : part.block.fallback_text;
if (!text || !next) return text + next;
return text + (text.endsWith("\n") || next.startsWith("\n") ? "" : "\n\n") + next;
}, "");
}
/** Final report transcript excludes process blocks and resolves authorized anchors. */
export function getFinalAnswerTranscript(message: AgentChatMessage): string {
return getAnswerPartsTranscript(getAnswerPresentation(message).report);
}
function splitAnchors(content: string): Array<{ text: string } | { id: string }> {
const result: Array<{ text: string } | { id: string }> = [];
let buffer = "";
let fence: { character: string; length: number } | undefined;
for (const line of content.match(/[^\n]*\n|[^\n]+$/g) ?? []) {
const bare = line.replace(/\r?\n$/, "");
const delimiter = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(bare);
if (fence) {
buffer += line;
if (delimiter && delimiter[1][0] === fence.character && delimiter[1].length >= fence.length && !delimiter[2].trim()) fence = undefined;
continue;
}
if (delimiter) {
fence = { character: delimiter[1][0], length: delimiter[1].length };
buffer += line;
continue;
}
const anchor = /^ {0,3}\[\[ui:([^\]\r\n]*)\]\][ \t]*$/.exec(bare);
if (!anchor) { buffer += line; continue; }
if (buffer.trim()) result.push({ text: buffer });
buffer = "";
result.push({ id: anchor[1] });
}
if (buffer.trim()) result.push({ text: buffer });
return result;
}
export function getAnswerPresentation(message: AgentChatMessage): {
report: AnswerUiPart[];
process: AnswerUiPart[];
final: boolean;
} {
const parts = message.answerParts ??
(message.content ? [{ type: "text" as const, text: message.content }] : []);
if (!message.finalAnswer) {
const isProcess = (part: AnswerUiPart) => part.type === "answer-ui" && part.block.phase === "process";
return { report: parts.filter((part) => !isProcess(part)), process: parts.filter(isProcess), final: false };
}
const selected = new Set(message.finalAnswer.uiBlockIds);
const available = new Map(parts.flatMap((part) =>
part.type === "answer-ui" ? [[part.block.block_id, part] as const] : []));
const mounted = new Set<string>();
const anchored = new Set<string>();
const report: AnswerUiPart[] = [];
for (const segment of splitAnchors(message.finalAnswer.content)) {
if ("text" in segment) { report.push({ type: "text", text: segment.text }); continue; }
anchored.add(segment.id);
const part = available.get(segment.id);
if (!selected.has(segment.id) || !part || part.block.phase === "process") {
report.push({ type: "text", text: "交互内容暂不可用。\n" });
} else if (!mounted.has(segment.id)) {
mounted.add(segment.id);
report.push(part);
}
}
// Old reports carried references without positional anchors.
for (const id of selected) {
const part = available.get(id);
if (part && part.block.phase !== "process" && !mounted.has(id) && !anchored.has(id)) {
mounted.add(id);
report.push(part);
}
}
const process = parts.filter((part) => part.type === "answer-ui"
? !mounted.has(part.block.block_id)
: part.text.trim() !== message.finalAnswer!.content.trim());
return { report, process, final: true };
}
@@ -0,0 +1,29 @@
import { CircleCheck, CircleHelp, CircleX, TriangleAlert } from "lucide-react";
import { Badge } from "@/shared/ui/badge";
const resultStatuses = {
success: { label: "成功", icon: CircleCheck, color: "text-[var(--status-success-foreground)]" },
partial: { label: "部分完成", icon: TriangleAlert, color: "text-[var(--status-warning-foreground)]" },
unconfirmed: { label: "未确认", icon: CircleHelp, color: "text-muted-foreground" },
error: { label: "失败", icon: CircleX, color: "text-destructive" }
};
/** A summary of recorded evidence, never an executable operation or approval. */
export function AnswerResult({ title, summary, status, source }: {
title: string;
summary: string;
status: keyof typeof resultStatuses;
source: string | null;
}) {
const { label, icon: Icon, color } = resultStatuses[status];
return <section data-answer-result data-result-status={status} role="group" aria-label={title}
className="min-w-0 rounded-lg border border-border bg-card px-3.5 py-3 text-card-foreground">
<div className="flex flex-wrap items-start gap-x-2 gap-y-1.5">
<Icon className={`mt-1 size-4 shrink-0 ${color}`} aria-hidden />
<h3 className="min-w-0 flex-1 text-sm font-medium leading-6">{title}</h3>
<Badge variant="outline" className="mt-0.5 shrink-0 px-1.5 py-0 text-[11px] font-normal shadow-none">{label}</Badge>
</div>
<p className="mt-2 whitespace-pre-wrap text-base leading-7">{summary}</p>
{source ? <p className="mt-2 whitespace-pre-wrap text-xs leading-5 text-muted-foreground">依据:{source}</p> : null}
</section>;
}
@@ -0,0 +1,40 @@
import { describe, expect, it } from "vitest";
import type { Spec } from "@json-render/core";
import { getAnswerTaskLayout } from "./answer-task-layout";
describe("answer task composition", () => {
const nodes: Spec["elements"] = {
root: { type: "Stack", props: { columns: "one" }, children: ["comparison", "data", "evidence", "mixed", "form"] },
comparison: { type: "Stack", props: { columns: "two" }, children: ["metric-a", "metric-b"] },
"metric-a": { type: "Metric", props: {} },
"metric-b": { type: "Metric", props: {} },
data: { type: "Section", props: { title: "趋势" }, children: ["chart", "table"] },
chart: { type: "Chart", props: {} },
table: { type: "Table", props: {} },
evidence: { type: "Evidence", props: {} },
mixed: { type: "Section", props: { title: "判断与依据" }, children: ["note", "basis"] },
note: { type: "Text", props: {} },
basis: { type: "Evidence", props: {} },
form: { type: "FollowUpForm", props: {} }
};
it("composes independent content while keeping authored comparisons and mixed sections together", () => {
expect(getAnswerTaskLayout({ root: "root", elements: nodes })).toEqual({
overview: ["comparison", "mixed"], analysis: ["data"], evidence: ["evidence"], followUp: ["form"]
});
});
it("preserves an explicitly authored comparison as the root", () => {
expect(getAnswerTaskLayout({ root: "comparison", elements: nodes })).toBeNull();
});
it("keeps explicit content roles and comparison intent instead of guessing from component types", () => {
const elements: Spec["elements"] = { ...nodes,
data: { ...nodes.data, props: { title: "读数依据", role: "evidence" } },
mixed: { ...nodes.mixed, props: { title: "处理结果", role: "result" } }
};
expect(getAnswerTaskLayout({ root: "root", elements })).toEqual({
overview: ["comparison", "mixed"], analysis: [], evidence: ["data", "evidence"], followUp: ["form"]
});
expect(getAnswerTaskLayout({ root: "root", elements: { ...elements,
root: { ...elements.root, props: { ...elements.root.props, intent: "comparison" } }
} })).toBeNull();
});
});
@@ -0,0 +1,35 @@
import type { Spec } from "@json-render/core";
export type AnswerTaskLayout = {
overview: string[];
analysis: string[];
evidence: string[];
followUp: string[];
};
type ContentRole = keyof AnswerTaskLayout;
/** Keep authored comparisons and mixed sections intact. Only compose independent roots. */
export function getAnswerTaskLayout(spec: Spec): AnswerTaskLayout | null {
const root = spec.elements[spec.root];
if (root.type !== "Stack" || root.props.columns !== "one" || root.props.intent === "comparison") return null;
const roleFor = (id: string): ContentRole => {
const node = spec.elements[id];
if (node.type === "Section") {
const roles: Record<string, ContentRole> = { result: "overview", analysis: "analysis", evidence: "evidence", follow_up: "followUp" };
const role = typeof node.props.role === "string" ? roles[node.props.role] : undefined;
if (role) return role;
}
if (node.type === "Evidence") return "evidence";
if (node.type === "FollowUpForm") return "followUp";
if (["Chart", "Table", "MapLocation"].includes(node.type)) return "analysis";
if (node.children?.length) {
const roles = new Set(node.children.map(roleFor));
if (roles.size === 1) return [...roles][0];
}
return "overview";
};
const groups: AnswerTaskLayout = { overview: [], analysis: [], evidence: [], followUp: [] };
for (const id of root.children ?? []) groups[roleFor(id)].push(id);
return groups;
}
@@ -0,0 +1,15 @@
import { createContext } from "react";
export type AnswerUiSelection = { title: string; text: string };
export type AnswerUiMapTarget = {
layer: "junctions" | "pipes" | "valves" | "pumps" | "tanks" | "reservoirs" | "scada";
feature_ids: string[];
};
export type AnswerUiInteractions = {
disabled: boolean;
onLocate?: (target: AnswerUiMapTarget) => Promise<unknown> | void;
onSubmit?: (text: string) => Promise<void> | void;
evidenceFilter?: string;
submitMode?: "send" | "draft";
};
export const AnswerInteractionContext = createContext<AnswerUiInteractions>({ disabled: true });
@@ -0,0 +1,105 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { AnswerUiView } from "./answer-ui-view";
import { parseAnswerUiBlock } from "./contract";
import { normalizeAnswerViewState, type AnswerViewState } from "./answer-view-state";
vi.mock("echarts-for-react", () => ({ default: () => <div aria-label="测试图形" /> }));
function block(type: string, props: Record<string, unknown>, id = "node") {
const value = parseAnswerUiBlock({ version: "answer-ui@1", block_id: "state", fallback_text: "演练", spec: { root: id, elements: { [id]: { type, props, children: [] } } } });
if (!value) throw new Error("Invalid fixture");
return value;
}
const chart = (labels = ["一", "二"]) => block("Chart", { title: "压力", chart_type: "line", x_data: labels, series: [{ name: "入口", data: labels.map((_, index) => index) }], source: "测试" });
const form = (kind = "text") => block("FollowUpForm", { title: "补充", description: "主动填写", fields: [{ name: "record", kind, label: "现场记录", required: false }, { name: "other", kind: "text", label: "其他资料", required: false }] });
describe("controlled native answer state", () => {
it("keeps independent drafts for identically shaped nodes and never changes model props", () => {
const current = form();
const node = current.spec.elements.node;
current.spec = { root: "root", elements: { root: { type: "Stack", props: { columns: "one", gap: "normal" }, children: ["first", "second"] }, first: structuredClone(node), second: structuredClone(node) } };
const changed = vi.fn();
const original = JSON.stringify(current.spec);
render(<AnswerUiView block={current} onViewStateChange={changed} onSubmit={vi.fn()} />);
const inputs = screen.getAllByLabelText("现场记录");
fireEvent.change(inputs[0], { target: { value: "第一份草稿" } });
fireEvent.change(inputs[1], { target: { value: "第二份草稿" } });
expect(inputs[0]).toHaveValue("第一份草稿");
expect(inputs[1]).toHaveValue("第二份草稿");
expect(changed).toHaveBeenLastCalledWith(expect.objectContaining({ nodes: { first: { type: "FollowUpForm", values: { record: "第一份草稿" } }, second: { type: "FollowUpForm", values: { record: "第二份草稿" } } } }), ["/nodes/second/values/record"]);
expect(JSON.stringify(current.spec)).toBe(original);
});
it("records only the edited form field and restores it after remount", () => {
const current = form();
let saved: AnswerViewState = normalizeAnswerViewState(current.spec);
const changed = vi.fn((next: AnswerViewState) => { saved = next; });
const rendered = render(<AnswerUiView block={current} viewState={saved} onViewStateChange={changed} onSubmit={vi.fn()} />);
fireEvent.change(screen.getByLabelText("现场记录"), { target: { value: "尚未提交的草稿" } });
expect(changed).toHaveBeenLastCalledWith(expect.objectContaining({ nodes: { node: { type: "FollowUpForm", values: { record: "尚未提交的草稿" } } } }), ["/nodes/node/values/record"]);
rendered.unmount();
render(<AnswerUiView block={current} viewState={saved} onSubmit={vi.fn()} />);
expect(screen.getByLabelText("现场记录")).toHaveValue("尚未提交的草稿");
expect(screen.getByLabelText("其他资料")).toHaveValue("");
});
it("keeps chart data-tab search across data refresh without remounting", () => {
const current = chart();
const state = normalizeAnswerViewState(current.spec);
if (state.nodes.node.type === "Chart") state.nodes.node.view = "table";
const { rerender } = render(<AnswerUiView block={current} viewState={state} />);
const search = screen.getByRole("textbox", { name: "搜索压力" });
fireEvent.change(search, { target: { value: "一" } });
// A local owner can omit the external snapshot while keeping the same block instance.
rerender(<AnswerUiView block={chart(["一", "三"])} />);
expect(screen.getByRole("textbox", { name: "搜索压力" })).toBe(search);
expect(search).toHaveValue("一");
expect(screen.queryByRole("checkbox")).not.toBeInTheDocument();
expect(screen.getByRole("tab", { name: "数据" })).toHaveAttribute("aria-selected", "true");
});
it("restores chart search and sort while discarding legacy row selection", () => {
const current = block("Chart", { title: "压力", chart_type: "line", x_data: ["08:00", "09:00", "10:00"], series: [{ name: "入口", data: [1, 2, 3] }, { name: "出口", data: [3, 4, 5] }], source: "测试" });
const changed = vi.fn();
const { rerender } = render(<AnswerUiView block={current} viewState={normalizeAnswerViewState(current.spec)} onViewStateChange={changed} />);
const restored = normalizeAnswerViewState(current.spec, { nodes: { node: { type: "Chart", view: "table", hidden: [1], range: [0, 1], point: 1, inspecting: true,
table: { query: "09:00", sort: { column: 1, descending: true }, selection: [1] } } } });
rerender(<AnswerUiView block={current} viewState={restored} onViewStateChange={changed} />);
expect(screen.getByRole("textbox", { name: "搜索压力" })).toHaveValue("09:00");
expect(screen.queryByRole("checkbox")).not.toBeInTheDocument();
expect(screen.getByRole("columnheader", { name: "入口" })).toHaveAttribute("aria-sort", "descending");
expect(screen.queryByRole("columnheader", { name: "出口" })).not.toBeInTheDocument();
expect(changed).not.toHaveBeenCalled();
// A subsequent deliberate series change clears the derived table sort.
fireEvent.click(screen.getByRole("button", { name: "出口" }));
expect(screen.queryByRole("checkbox")).not.toBeInTheDocument();
expect(screen.getByRole("textbox", { name: "搜索压力" })).toHaveValue("09:00");
expect(changed).toHaveBeenLastCalledWith(expect.anything(), ["/nodes/node/hidden", "/nodes/node/table/sort"]);
});
it("preserves form drafts during streaming repeats and drops a draft when the field kind changes", () => {
const { rerender } = render(<AnswerUiView block={form()} onSubmit={vi.fn()} />);
const input = screen.getByLabelText("现场记录");
fireEvent.change(input, { target: { value: "未发送" } });
rerender(<AnswerUiView block={form()} onSubmit={vi.fn()} />);
expect(screen.getByLabelText("现场记录")).toBe(input);
expect(input).toHaveValue("未发送");
rerender(<AnswerUiView block={form("number")} onSubmit={vi.fn()} />);
expect(screen.getByLabelText("现场记录")).toHaveValue(null);
});
it("restores evidence expansion and reports ambiguous chart label migration", () => {
const evidence = block("Evidence", { title: "依据", summary: "记录内容", source: "测试", kind: "observed", observed_at: null, evidence_id: null });
const saved = normalizeAnswerViewState(evidence.spec, { nodes: { node: { type: "Evidence", open: true } } });
const { unmount } = render(<AnswerUiView block={evidence} viewState={saved} />);
expect(screen.getByText("记录内容")).toBeVisible();
unmount();
const original = chart();
const state = normalizeAnswerViewState(original.spec);
if (state.nodes.node.type === "Chart") { state.nodes.node.point = 1; state.nodes.node.inspecting = true; }
const mounted = render(<AnswerUiView block={original} viewState={state} />);
mounted.rerender(<AnswerUiView block={chart(["一", "二", "二"])} />);
expect(screen.getByRole("status")).toHaveTextContent("无法唯一对应,已清除选择");
expect(screen.queryByRole("region", { name: "数据点详情" })).not.toBeInTheDocument();
});
});
@@ -0,0 +1,277 @@
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import userEvent from "@testing-library/user-event";
import { AnswerUiView } from "./answer-ui-view";
import { parseAnswerUiBlock } from "./contract";
vi.mock("echarts-for-react", () => ({ default: () => <div aria-label="测试图形" /> }));
function block(type: string, props: Record<string, unknown>) {
const parsed = parseAnswerUiBlock({
version: "answer-ui@1",
block_id: "test",
fallback_text: "演练",
spec: { root: "node", elements: { node: { type, props, children: [] } } }
});
if (!parsed) throw new Error("invalid test fixture");
return parsed;
}
function taskBlock(includeData = true) {
const children = ["metric", ...(includeData ? ["table"] : []), "evidence", "form"];
const fixture = {
version: "answer-ui@1", block_id: "task", fallback_text: "演练分析",
spec: { root: "root", elements: {
root: { type: "Stack", props: { columns: "one", gap: "normal" }, children },
metric: { type: "Metric", props: { label: "当前压力", value: "0.2130", unit: "MPa", source: "监测快照" }, children: [] },
...(includeData ? { table: { type: "Table", props: { title: "入口记录", columns: ["对象", "压力(MPa)"], rows: [["北区入口", "0.2130"], ["南区入口", "0.2870"]] }, children: [] } } : {}),
evidence: { type: "Evidence", props: { title: "读数依据", summary: "仅用于演练", source: "测试查询", kind: "demo", evidence_id: "DEMO-26", observed_at: null }, children: [] },
form: { type: "FollowUpForm", props: { title: "核验资料", description: "主动补充", fields: [{ name: "record", label: "现场记录", kind: "text", required: true }] }, children: [] }
} }
};
const parsed = parseAnswerUiBlock(fixture);
if (!parsed) throw new Error("invalid task fixture");
return parsed;
}
describe("local interactive answer renderer", () => {
it("shows navigation for long answers while keeping short metric and evidence replies quiet", () => {
const fixture = taskBlock(false);
fixture.spec.elements.root.children = ["metric", "evidence"];
delete fixture.spec.elements.form;
const { rerender } = render(<AnswerUiView block={fixture} />);
expect(screen.getByRole("group", { name: "当前压力" })).toBeVisible();
expect(screen.queryByRole("navigation", { name: "回答内容导航" })).not.toBeInTheDocument();
const longer = structuredClone(fixture);
longer.spec.elements.evidence.props.summary = "待核对的监测资料。".repeat(150);
rerender(<AnswerUiView block={longer} />);
expect(screen.getByRole("navigation", { name: "回答内容导航" })).toBeVisible();
});
it("uses a single form and evidence card's own headings without fixed wrapper instructions", () => {
render(<AnswerUiView block={taskBlock()} onSubmit={vi.fn()} />);
expect(screen.getByLabelText("现场记录(必填)")).toBeVisible();
expect(screen.getByRole("button", { name: /读数依据/ })).toBeVisible();
expect(screen.queryByRole("button", { name: "收起补充资料" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "收起核查依据" })).not.toBeInTheDocument();
expect(screen.queryByText("直接探索已加载数据")).not.toBeInTheDocument();
expect(screen.queryByText("区分记录、推断与用户资料")).not.toBeInTheDocument();
});
it("adapts response and report composition without replacing a reader's form draft", async () => {
const user = userEvent.setup();
const fixture = taskBlock();
fixture.spec.elements.root.props = { columns: "one", gap: "normal", intent: "response", density: "compact" };
const { rerender, container } = render(<AnswerUiView block={fixture} onSubmit={vi.fn()} />);
const editor = screen.getByLabelText("现场记录(必填)");
await user.type(editor, "保留的现场草稿");
expect(container.querySelector("[data-answer-task-layout]")).toBeNull();
const report = { ...fixture, spec: { ...fixture.spec, elements: { ...fixture.spec.elements,
root: { ...fixture.spec.elements.root, props: { columns: "one", gap: "normal", intent: "report", density: "comfortable" } }
} } };
rerender(<AnswerUiView block={report} onSubmit={vi.fn()} />);
expect(container.querySelector("[data-answer-task-layout]")).not.toBeNull();
expect(screen.getByLabelText("现场记录(必填)")).toBe(editor);
expect(editor).toHaveValue("保留的现场草稿");
});
it("renders evidence-bound result states without treating historical results as live alerts", () => {
const fixture = (status: string) => block("Result", { title: "管道定位结果", summary: "已定位 3 根管道;高亮尚未确认。", status, source: "地图定位回执" });
const { rerender } = render(<AnswerUiView block={fixture("partial")} />);
const result = screen.getByRole("group", { name: "管道定位结果" });
expect(result).toHaveTextContent("部分完成");
expect(result).toHaveTextContent("依据:地图定位回执");
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
expect(screen.queryByRole("button")).not.toBeInTheDocument();
for (const [status, label] of [["success", "成功"], ["unconfirmed", "未确认"], ["error", "失败"]]) {
rerender(<AnswerUiView block={fixture(status)} />);
expect(result).toHaveTextContent(label);
expect(result).toHaveAttribute("data-result-status", status);
}
});
it("uses the supplied note title without changing the warning meaning", () => {
render(<AnswerUiView block={block("Text", { text: "当前工具未提供高亮操作。", tone: "warning", title: "能力限制" })} />);
expect(screen.getByRole("note")).toHaveTextContent("能力限制");
expect(screen.getByRole("note")).not.toHaveTextContent("注意事项");
});
it("shows data and evidence without row selection, quoting or analysis controls", async () => {
const user = userEvent.setup();
const submit = vi.fn();
render(<AnswerUiView block={taskBlock()} onSubmit={submit} />);
expect(screen.getByRole("group", { name: "当前压力" })).toHaveTextContent("0.2130MPa");
expect(screen.getByRole("table")).toHaveTextContent("北区入口");
expect(screen.getAllByRole("columnheader")).toHaveLength(2);
await user.click(screen.getByRole("button", { name: /读数依据.*测试查询/ }));
await waitFor(() => expect(screen.getByText("仅用于演练")).toBeVisible());
expect(screen.getByText("DEMO-26")).toBeVisible();
expect(screen.queryByRole("checkbox")).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: /加入分析|针对.*提问|取消选行/ })).not.toBeInTheDocument();
expect(screen.queryByRole("region", { name: "分析内容篮" })).not.toBeInTheDocument();
expect(submit).not.toHaveBeenCalled();
});
it("keeps the same form when more data arrives and support sections collapse", async () => {
const user = userEvent.setup();
const { rerender } = render(<AnswerUiView block={taskBlock(false)} onSubmit={vi.fn()} />);
const editor = screen.getByLabelText("现场记录(必填)");
await user.type(editor, "未发送的现场草稿");
const grouped = taskBlock();
grouped.spec.elements.root.children = [...(grouped.spec.elements.root.children ?? []), "extra-form"];
grouped.spec.elements["extra-form"] = { ...grouped.spec.elements.form, props: {
title: "其他资料", description: "可选补充", fields: [{ name: "extra", label: "其他记录", kind: "text", required: false }]
} };
rerender(<AnswerUiView block={grouped} onSubmit={vi.fn()} />);
expect(screen.getByLabelText("现场记录(必填)")).toBe(editor);
expect(editor).toHaveValue("未发送的现场草稿");
await user.click(screen.getByRole("button", { name: "收起补充资料" }));
expect(editor.closest("[data-answer-reveal]")).toHaveAttribute("inert");
await waitFor(() => expect(editor).not.toBeVisible());
await user.click(screen.getByRole("button", { name: "展开补充资料" }));
await waitFor(() => expect(editor).toBeVisible());
expect(editor).toHaveValue("未发送的现场草稿");
await user.click(screen.getByRole("button", { name: "收起补充资料" }));
const updated = taskBlock();
updated.spec.elements.table.props.rows = [["新增入口", "0.24"]];
rerender(<AnswerUiView block={updated} onSubmit={vi.fn()} />);
expect(screen.getByLabelText("现场记录(必填)")).toBe(editor);
await waitFor(() => expect(editor).toBeVisible());
expect(editor).toHaveValue("未发送的现场草稿");
});
it("preserves long original cell values without requiring a selection or quote action", () => {
const fixture = taskBlock();
fixture.spec.elements.table.props.rows = Array.from({ length: 12 }, (_, index) => [String(index), "长".repeat(800)]);
render(<AnswerUiView block={fixture} />);
expect(screen.getAllByText("长".repeat(800))).toHaveLength(12);
expect(screen.queryByRole("checkbox")).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: /加入分析|针对.*提问/ })).not.toBeInTheDocument();
});
it("expresses supplied context and cautions as readable notes without announcing historical alerts", () => {
const { rerender } = render(<AnswerUiView block={block("Text", {
text: "压力记录尚未经过现场核验。", tone: "warning",
})} />);
expect(screen.getByRole("note")).toHaveTextContent("注意事项");
expect(screen.getByRole("note")).toHaveTextContent("压力记录尚未经过现场核验。");
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
expect(screen.queryByRole("navigation")).not.toBeInTheDocument();
rerender(<AnswerUiView block={block("Text", { text: "仅展示已加载的记录。", tone: "info" })} />);
expect(screen.getByRole("note")).toHaveTextContent("补充说明");
rerender(<AnswerUiView block={block("Text", { text: "普通回答", tone: "neutral" })} />);
expect(screen.queryByRole("note")).not.toBeInTheDocument();
expect(screen.getByText("普通回答")).toBeInTheDocument();
});
it("retains a metric's exact value, unit and source without action buttons", () => {
render(<AnswerUiView block={block("Metric", {
label: "当前压力", value: "0.3000", unit: "MPa", source: "已加载记录",
})} />);
const metric = screen.getByRole("group", { name: "当前压力" });
expect(metric).toHaveTextContent("0.3000MPa");
expect(metric).toHaveTextContent("来源:已加载记录");
expect(screen.queryByRole("button")).not.toBeInTheDocument();
});
it("renders through json-render and lets readers inspect exact chart data with keyboard tabs", async () => {
const user = userEvent.setup();
render(
<AnswerUiView
block={block("Chart", {
title: "演练压力",
chart_type: "line",
source: "演练数据",
x_data: ["08:00", "09:00"],
series: [{ name: "压力", data: [0.3, 0.2] }]
})}
/>
);
await user.click(screen.getByRole("tab", { name: /^数据$/ }));
expect(screen.getByRole("table")).toHaveTextContent("0.3");
expect(screen.getByRole("table")).toHaveTextContent("09:00");
expect(screen.getByRole("tab", { name: /^数据$/ })).toHaveAttribute("aria-selected", "true");
await user.keyboard("{ArrowLeft}");
expect(screen.getByRole("tab", { name: /^柱状$/ })).toHaveFocus();
expect(screen.getByRole("tab", { name: /^柱状$/ })).toHaveAttribute("aria-selected", "true");
expect(screen.queryByRole("table")).not.toBeInTheDocument();
});
it("runs map location only after a user click and reports missing IDs", async () => {
const locate = vi
.fn()
.mockResolvedValue({ located_ids: ["DEMO-P001"], missing_ids: ["DEMO-P002"] });
render(
<AnswerUiView
block={block("MapLocation", {
label: "定位演练监测点",
layer: "scada",
feature_ids: ["DEMO-P001", "DEMO-P002"],
source: "演练数据"
})}
onLocate={locate}
/>
);
expect(locate).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "定位演练监测点" }));
await waitFor(() => expect(screen.getByRole("status")).toHaveTextContent("另有 1 个未找到"));
expect(locate).toHaveBeenCalledWith({
layer: "scada",
feature_ids: ["DEMO-P001", "DEMO-P002"]
});
});
it("filters and sorts loaded rows without selecting or sending content", async () => {
const user = userEvent.setup();
const submit = vi.fn();
render(<AnswerUiView block={block("Table", {
title: "监测记录", columns: ["监测点", "压力"],
rows: [["南站", "0.32"], ["北站", "0.21"], ["南站二号", "0.26"]]
})} onSubmit={submit} />);
await user.type(screen.getByRole("textbox", { name: "搜索监测记录" }), "南站");
expect(screen.getByText("2 / 3 行")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "按压力排序" }));
const rows = screen.getAllByRole("row");
expect(rows[1]).toHaveTextContent("南站二号");
expect(rows[1]).toHaveTextContent("0.26");
expect(screen.queryByRole("checkbox")).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: /加入分析|针对.*提问/ })).not.toBeInTheDocument();
expect(submit).not.toHaveBeenCalled();
});
it("keeps form values after a failed submission", async () => {
const user = userEvent.setup();
render(<AnswerUiView block={block("FollowUpForm", {
title: "现场事实", description: "用户填写",
fields: [{ name: "detail", label: "记录", kind: "text", required: true }]
})} onSubmit={async () => { throw new Error("暂未发送"); }} />);
await user.type(screen.getByLabelText("记录(必填)"), "北站现场记录");
await user.click(screen.getByRole("button", { name: "发送补充资料" }));
expect(await screen.findByRole("status")).toHaveTextContent("暂未发送");
expect(screen.getByLabelText("记录(必填)")).toHaveValue("北站现场记录");
});
it("starts blank, requires input and sends one user message without claiming evidence is saved", async () => {
let complete!: () => void;
const submit = vi.fn(
() =>
new Promise<void>((resolve) => {
complete = resolve;
})
);
render(
<AnswerUiView
block={block("FollowUpForm", {
title: "补充现场资料",
description: "由用户提供",
fields: [{ name: "location", label: "现场位置", kind: "text", required: true }]
})}
onSubmit={submit}
/>
);
expect(screen.getByLabelText("现场位置(必填)")).toHaveValue("");
fireEvent.submit(screen.getByRole("form", { name: "补充现场资料" }));
expect(submit).not.toHaveBeenCalled();
expect(screen.getByRole("status")).toHaveTextContent("请填写必填资料");
fireEvent.change(screen.getByLabelText("现场位置(必填)"), {
target: { value: "用户指定位置" }
});
fireEvent.submit(screen.getByRole("form", { name: "补充现场资料" }));
expect(submit).toHaveBeenCalledTimes(1);
expect(submit.mock.calls[0]).toEqual([expect.stringContaining("现场位置:用户指定位置")]);
expect(screen.getByRole("button", { name: "正在发送…" })).toBeDisabled();
complete();
await waitFor(() =>
expect(screen.getByRole("status")).toHaveTextContent("资料已发送,请查看 Agent 回复")
);
});
});
@@ -0,0 +1,231 @@
import { LocateButton, FollowUpForm } from "./answer-action-components";
import { Renderer, defineRegistry } from "@json-render/react";
import { useContext, useRef, useState, type ReactNode } from "react";
import {
Info,
TriangleAlert,
ClipboardList,
Database,
FileCheck2,
FlaskConical,
Lightbulb,
MessageSquare
} from "lucide-react";
import { Button } from "@/shared/ui/button";
import { Badge } from "@/shared/ui/badge";
import { Alert, AlertDescription, AlertTitle } from "@/shared/ui/alert";
import { Card, CardContent } from "@/shared/ui/card";
import { AnswerDisclosure, AnswerDisclosureChevron, AnswerMotionScope } from "./answer-motion";
import { cn } from "@/shared/ui/cn";
import { InteractiveChart } from "./interactive-chart";
import { InteractiveDataTable } from "./interactive-data-table";
import { AnswerResult } from "./answer-result";
import { AnswerInteractionContext as InteractionContext, type AnswerUiInteractions } from "./answer-ui-interaction-context";
export type { AnswerUiMapTarget, AnswerUiSelection } from "./answer-ui-interaction-context";
import { answerUiCatalog } from "./catalog";
import type { AnswerUiBlock } from "./contract";
import { AnswerContentNav } from "./answer-content-nav";
import { getAnswerTaskLayout } from "./answer-task-layout";
import { AnswerViewStateProvider, useAnswerBlockState, useAnswerNodeState, withAnswerNodeIdentity, withAnswerNodeIds } from "./answer-view-state-provider";
import { type AnswerEvidenceState, type AnswerViewState, type AnswerViewStateChange } from "./answer-view-state";
const { registry: baseRegistry } = defineRegistry(answerUiCatalog, {
actions: {},
components: {
Stack: ({ props, children }) => (
<div
className={cn(
"answer-ui-stack",
(props.columns === "two" || props.intent === "comparison") && "answer-ui-stack-comparison",
props.gap === "compact" && "answer-ui-stack-compact"
)}
data-answer-intent={props.intent}
data-answer-density={props.density}
>
{children}
</div>
),
Section: ({ props, children }) => (
<section className="answer-ui-section" data-answer-role={props.role}>
<h3 className="flex items-center gap-2 text-sm font-semibold text-foreground">
<ClipboardList size={15} aria-hidden="true" />
{props.title}
</h3>
{props.description ? (
<p className="mt-1 text-xs leading-5 text-muted-foreground">{props.description}</p>
) : null}
<div className="mt-3 space-y-3">{children}</div>
</section>
),
Text: ({ props }) => props.tone === "neutral" ? (
<div className="space-y-1">
{props.title ? <h4 className="text-sm font-medium leading-6 text-foreground">{props.title}</h4> : null}
<p className="whitespace-pre-wrap text-sm leading-6 text-foreground">{props.text}</p>
</div>
) : (
<Alert role="note" className="border-border bg-card px-3.5 py-3 text-card-foreground has-[>svg]:gap-x-2.5">
{props.tone === "warning" ? <TriangleAlert className="text-[var(--status-warning-foreground)]" aria-hidden /> : <Info className="text-muted-foreground" aria-hidden />}
<AlertTitle className="text-[13px]">{props.title ?? (props.tone === "warning" ? "注意事项" : "补充说明")}</AlertTitle>
<AlertDescription className="whitespace-pre-wrap text-muted-foreground">{props.text}</AlertDescription>
</Alert>
),
Result: ({ props }) => <AnswerResult {...props} />,
Metric: ({ props }) => (
<Card className="answer-ui-metric" role="group" aria-label={props.label}>
<CardContent className="answer-ui-metric-content p-3">
<p className="answer-ui-metric-label text-xs leading-5 text-muted-foreground">{props.label}</p>
<p className="answer-ui-metric-value break-words text-2xl font-semibold tabular-nums text-foreground">
{props.value}
{props.unit ? (
<span className="ml-1.5 text-xs font-normal text-muted-foreground">{props.unit}</span>
) : null}
</p>
{props.source ? (
<p className="answer-ui-metric-source text-[11px] leading-5 text-muted-foreground">来源:{props.source}</p>
) : null}
</CardContent>
</Card>
),
Table: ({ props }) => (
<section data-answer-table aria-label={props.title} className="min-w-0">
<InteractiveDataTable title={props.title} columns={props.columns} rows={props.rows} />
</section>
),
Chart: ({ props }) => <InteractiveChart {...props} />,
Evidence: ({ props }) => <EvidenceCard {...props} />,
MapLocation: ({ props }) => <LocateButton {...props} />,
FollowUpForm: ({ props }) => <FollowUpForm {...props} />
}
});
const registry = withAnswerNodeIdentity(baseRegistry);
type AnswerUiViewProps = { block: AnswerUiBlock; viewState?: AnswerViewState; onViewStateChange?: AnswerViewStateChange } & Partial<AnswerUiInteractions>;
export function AnswerUiView({ viewState, onViewStateChange, ...props }: AnswerUiViewProps) {
return <AnswerViewStateProvider key={props.block.block_id} spec={props.block.spec} registry={registry} viewState={viewState} onViewStateChange={onViewStateChange}>
<AnswerUiBody {...props} block={{ ...props.block, spec: withAnswerNodeIds(props.block.spec) }} />
</AnswerViewStateProvider>;
}
function AnswerUiBody({
block,
disabled = false,
onLocate,
onSubmit,
submitMode = "send"
}: { block: AnswerUiBlock } & Partial<AnswerUiInteractions>) {
const [{ evidenceFilter: filter }, setFilter] = useAnswerBlockState();
const contentRef = useRef<HTMLDivElement>(null);
const taskLayout = getAnswerTaskLayout(block.spec);
const root = block.spec.elements[block.spec.root];
const density = root.type === "Stack" ? root.props.density : undefined;
const intent = root.type === "Stack" ? root.props.intent : undefined;
const hasTaskLayout = intent !== "response" && Boolean(taskLayout?.analysis.length && (taskLayout.evidence.length || taskLayout.followUp.length));
const kinds = [...new Set(Object.values(block.spec.elements).filter((node) => node.type === "Evidence").map((node) => String(node.props.kind)))];
const evidenceFilters = kinds.length > 1 ? <div className="mb-3 flex flex-wrap gap-1.5" aria-label="筛选证据类别">
{["all", ...kinds].map((kind) => <Button key={kind} variant={filter === kind ? "secondary" : "outline"} size="sm" className="h-8 text-xs" aria-pressed={filter === kind} onClick={() => setFilter(kind)}>
{kind === "all" ? "全部依据" : evidenceKinds[kind as keyof typeof evidenceKinds].label}
</Button>)}
</div> : null;
const isGroup = (ids: string[]) => hasTaskLayout && ids.length > 1 && !ids.every((id) => block.spec.elements[id].type === "Section");
const renderNodes = (ids: string[]) => ids.map((id) => <Renderer key={id} spec={{ ...block.spec, root: id }} registry={registry} />);
return (
<InteractionContext.Provider value={{ disabled, onLocate, onSubmit, submitMode, evidenceFilter: filter }}>
<AnswerMotionScope className="answer-ui-root" data-answer-ui={block.block_id} data-answer-phase={block.phase} data-answer-intent={intent} data-answer-density={density}>
<AnswerContentNav block={block} contentRef={contentRef} />
<div ref={contentRef}>
<>
{taskLayout ? <div className={hasTaskLayout ? "answer-task-layout" : "answer-task-layout-simple"} data-answer-task-layout={hasTaskLayout || undefined}>
{taskLayout.overview.length ? <div className="answer-task-overview grid gap-3" aria-label="回答概览">{renderNodes(taskLayout.overview)}</div> : null}
{taskLayout.analysis.length ? <section className="answer-task-analysis grid min-w-0 gap-3" aria-label="分析内容">
{renderNodes(taskLayout.analysis)}
</section> : null}
{taskLayout.evidence.length || taskLayout.followUp.length ? <div className="answer-task-support grid min-w-0 gap-4">
{taskLayout.evidence.length ? <TaskSupport grouped={isGroup(taskLayout.evidence)} title="核查依据" icon={<Database size={15} aria-hidden />}>
{evidenceFilters}{renderNodes(taskLayout.evidence)}
</TaskSupport> : null}
{taskLayout.followUp.length ? <TaskSupport grouped={isGroup(taskLayout.followUp)} title="补充资料" icon={<FileCheck2 size={15} aria-hidden />}>
{renderNodes(taskLayout.followUp)}
</TaskSupport> : null}
</div> : null}
</div> : <>{evidenceFilters}<Renderer spec={block.spec} registry={registry} /></>}
</>
</div>
</AnswerMotionScope>
</InteractionContext.Provider>
);
}
function TaskSupport({ title, icon, children, grouped }: { title: string; icon: ReactNode; children: ReactNode; grouped: boolean }) {
const [open, setOpen] = useState(true);
return <AnswerDisclosure open={grouped ? open : true} onOpenChange={setOpen} className="answer-task-support-section" data-grouped={grouped || undefined}
contentClassName={cn("answer-task-support-content space-y-2.5", grouped && "pt-2")}
trigger={<Button type="button" variant="ghost" hidden={!grouped} className={cn("h-auto min-h-11 w-full justify-start gap-2 px-0 text-left", !grouped && "hidden")} aria-label={`${open ? "收起" : "展开"}${title}`}>
{icon}<span className="min-w-0 flex-1 text-xs font-medium">{title}</span>
<AnswerDisclosureChevron open={open} />
</Button>}>{children}</AnswerDisclosure>;
}
const evidenceKinds = {
observed: { label: "查询记录", icon: Database },
human_input: { label: "用户提供", icon: MessageSquare },
inference: { label: "分析推断", icon: Lightbulb },
demo: { label: "演练数据", icon: FlaskConical }
};
function EvidenceCard(props: {
title: string;
summary: string;
source: string;
kind: keyof typeof evidenceKinds;
observed_at: string | null;
evidence_id: string | null;
}) {
const [{ open }, patch] = useAnswerNodeState<AnswerEvidenceState>("Evidence", props);
const setOpen = (open: boolean) => patch({ open });
const meta = evidenceKinds[props.kind];
const Icon = meta.icon;
const { evidenceFilter } = useContext(InteractionContext);
if (evidenceFilter && evidenceFilter !== "all" && evidenceFilter !== props.kind) return null;
return (
<AnswerDisclosure open={open} onOpenChange={setOpen} className="answer-ui-evidence" role="group" aria-label={props.title}
contentClassName="px-3 pb-3 text-xs leading-6" trigger={
<Button
variant="ghost"
type="button"
className="h-auto min-h-12 w-full justify-start gap-2.5 whitespace-normal rounded-xl px-3 py-3 text-left shadow-none"
>
<span className="answer-ui-evidence-icon">
<Icon size={16} aria-hidden="true" />
</span>
<span className="min-w-0 flex-1">
<span className="block text-xs font-medium">{props.title}</span>
<span className="mt-0.5 block break-words text-[11px] font-normal text-muted-foreground">
{props.source}
</span>
</span>
<Badge variant="outline" className="shrink-0 px-1.5 text-[10px] font-normal">
{meta.label}
</Badge>
<AnswerDisclosureChevron open={open} />
</Button>}>
<p className="whitespace-pre-wrap border-t border-border pt-3">{props.summary}</p>
{props.observed_at || props.evidence_id ? (
<dl className="mt-3 grid gap-1 text-[11px] text-muted-foreground">
{props.observed_at ? (
<div>
<dt className="inline">记录时间:</dt>
<dd className="inline tabular-nums">{props.observed_at}</dd>
</div>
) : null}
{props.evidence_id ? (
<div>
<dt className="inline">资料编号:</dt>
<dd className="inline break-all font-mono">{props.evidence_id}</dd>
</div>
) : null}
</dl>
) : null}
</AnswerDisclosure>
);
}
@@ -0,0 +1,92 @@
/* eslint-disable react-refresh/only-export-components -- Local rendering adapter and its state hooks share private contexts. */
import { createContext, useContext, useLayoutEffect, useState, type ReactNode } from "react";
import { createStateStore, JSONUIProvider, useStateStore, type ComponentRegistry } from "@json-render/react";
import type { Spec } from "@json-render/core";
import {
answerStatePointer, answerViewStateDirtyPaths, migrateAnswerViewState, normalizeAnswerNodeState, normalizeAnswerViewState,
type AnswerUiNodeState, type AnswerViewState, type AnswerViewStateChange
} from "./answer-view-state";
const NodeContext = createContext<string | undefined>(undefined);
const ChangeContext = createContext<AnswerViewStateChange | undefined>(undefined);
/** The renderer clones props; local element metadata survives that adaptation. Never modify model props. */
export function withAnswerNodeIds(spec: Spec): Spec {
return { ...spec, elements: Object.fromEntries(Object.entries(spec.elements).map(([id, node]) => [id, { ...node, __answerNodeId: id }])) };
}
export function withAnswerNodeIdentity(registry: ComponentRegistry): ComponentRegistry {
return Object.fromEntries(Object.entries(registry).map(([type, Component]) => [type, function AnswerNodeRenderer(props) {
const id = (props.element as typeof props.element & { __answerNodeId?: string }).__answerNodeId;
return <NodeContext.Provider value={id}><Component {...props} /></NodeContext.Provider>;
}]));
}
export function AnswerViewStateProvider({ spec, registry, viewState, onViewStateChange, children }: {
spec: Spec; registry: ComponentRegistry; viewState?: AnswerViewState; onViewStateChange?: AnswerViewStateChange; children: ReactNode;
}) {
const [store] = useState(() => createStateStore(normalizeAnswerViewState(spec, viewState)));
// Capture the full prior schema, including in-place updates from callers.
const [previous, setPrevious] = useState(() => JSON.stringify(spec));
const serialized = JSON.stringify(spec);
useLayoutEffect(() => {
const current = store.getSnapshot() as AnswerViewState;
const source = viewState ?? current;
const next = previous === serialized ? normalizeAnswerViewState(spec, source) : migrateAnswerViewState(JSON.parse(previous) as Spec, spec, source);
const dirty = answerViewStateDirtyPaths(source, next);
const previousSpec = JSON.parse(previous) as Spec;
const resetCharts = Object.entries(next.nodes).filter(([id, node]) => {
const old = source.nodes[id];
if (node.type !== "Chart" || old?.type !== "Chart" || previous === serialized) return false;
const before = previousSpec.elements[id], after = spec.elements[id];
if (before?.type !== "Chart" || JSON.stringify([before.props.x_data, before.props.series]) === JSON.stringify([after.props.x_data, after.props.series])) return false;
const previousLabels = before.props.x_data as string[], labels = after.props.x_data as string[];
const relocate = (position: number) => {
const label = previousLabels[position];
return label !== undefined && previousLabels.filter((value) => value === label).length === 1 && labels.filter((value) => value === label).length === 1 ? labels.indexOf(label) : -1;
};
return relocate(old.point) < 0 || relocate(old.range[0]) < 0 || relocate(old.range[1]) < relocate(old.range[0]);
}).map(([id]) => id);
store.update({ "/nodes": next.nodes, "/block": next.block });
if (previous !== serialized) {
store.set("/notices", Object.fromEntries(resetCharts.map((id) => [id, "数据标签已变化,原选点或区间无法唯一对应,已清除选择。仍可查看当前数据。"])));
setPrevious(serialized);
}
if (dirty.length) onViewStateChange?.(next, dirty);
}, [store, previous, serialized, spec, viewState, onViewStateChange]);
const change: AnswerViewStateChange = (next, dirty) => {
store.update({ "/nodes": next.nodes, "/block": next.block });
onViewStateChange?.(next, dirty);
};
return <ChangeContext.Provider value={change}>
<JSONUIProvider registry={registry} store={store}>{children}</JSONUIProvider>
</ChangeContext.Provider>;
}
export function useAnswerNodeState<T extends AnswerUiNodeState>(type: T["type"], props: Record<string, unknown>) {
const id = useContext(NodeContext);
const store = useStateStore();
const onChange = useContext(ChangeContext);
// Derived controls (such as a chart's data table) have no schema node of their own.
const [local, setLocal] = useState(() => normalizeAnswerNodeState({ type, props, children: [] }) as T);
const owned = id && (store.get(`/nodes/${answerStatePointer(id)}`) as AnswerUiNodeState | undefined)?.type === type;
const state = (owned ? normalizeAnswerNodeState({ type, props, children: [] }, store.get(`/nodes/${answerStatePointer(id!)}`)) : local) as T;
const patch = (updates: Partial<Omit<T, "type">>, fields?: string[]) => {
const live = owned ? store.get(`/nodes/${answerStatePointer(id!)}`) as T : state;
const next = { ...live, ...updates } as T;
if (!owned || !onChange) { setLocal(next); return; }
const snapshot = store.getSnapshot() as AnswerViewState;
onChange({ nodes: { ...snapshot.nodes, [id!]: next }, block: snapshot.block },
(fields ?? Object.keys(updates)).map((field) => `/nodes/${answerStatePointer(id!)}/${field}`));
};
return [state, patch, id ? store.get(`/notices/${answerStatePointer(id)}`) as string | undefined : undefined] as const;
}
export function useAnswerBlockState() {
const store = useStateStore(), onChange = useContext(ChangeContext);
const block = store.get("/block") as AnswerViewState["block"];
return [block, (evidenceFilter: string) => {
const snapshot = store.getSnapshot() as AnswerViewState;
onChange?.({ nodes: snapshot.nodes, block: { evidenceFilter } }, ["/block/evidenceFilter"]);
}] as const;
}
@@ -0,0 +1,53 @@
import { describe, expect, it } from "vitest";
import type { Spec } from "@json-render/core";
import { answerViewStateDirtyPaths, migrateAnswerViewState, normalizeAnswerViewState } from "./answer-view-state";
function spec(type: string, props: Record<string, unknown>): Spec {
return { root: "node", elements: { node: { type, props, children: [] } } };
}
const chart = (labels = ["a", "b", "c"], names = ["入口", "出口"]) => spec("Chart", { chart_type: "line", x_data: labels, series: names.map((name) => ({ name, data: labels.map((_, index) => index) })) });
const table = (rows = [["a", "1"], ["b", "2"]], columns = ["对象", "读数"]) => spec("Table", { rows, columns });
const form = (fields = [{ name: "record", kind: "text" }]) => spec("FollowUpForm", { fields });
describe("answer view state compatibility", () => {
it("ignores legacy row selection, retains search, and clears sort when columns change", () => {
const before = table();
const state = normalizeAnswerViewState(before, { nodes: { node: { type: "Table", query: "a", sort: { column: 1, descending: true }, selection: [0] } } });
expect(migrateAnswerViewState(before, table([["b", "2"], ["a", "1"]]), state).nodes.node).toEqual({ type: "Table", query: "a", sort: { column: 1, descending: true }, selection: [] });
expect(migrateAnswerViewState(before, table(undefined, ["读数", "对象"]), state).nodes.node).toMatchObject({ query: "a", sort: null, selection: [] });
expect(migrateAnswerViewState(before, structuredClone(before), state)).toEqual(state);
});
it("relocates chart ranges and points only by unique labels and resets hidden series after renaming", () => {
const before = chart();
const state = normalizeAnswerViewState(before, { nodes: { node: { type: "Chart", view: "bar", hidden: [1], range: [1, 2], point: 2, inspecting: true, table: { query: "b", sort: { column: 1, descending: false }, selection: [0] } } } });
expect(migrateAnswerViewState(before, chart(["z", "a", "b", "c"]), state).nodes.node).toMatchObject({ view: "bar", hidden: [1], range: [2, 3], point: 3, inspecting: true, table: { query: "b", selection: [] } });
expect(migrateAnswerViewState(before, chart(undefined, ["出口", "入口"]), state).nodes.node).toMatchObject({ view: "bar", hidden: [], table: { query: "b", sort: null, selection: [] } });
for (const labels of [["a", "b", "b"], ["a", "b"]]) expect(migrateAnswerViewState(before, chart(labels), state).nodes.node).toMatchObject({ range: [0, labels.length - 1], point: 0, inspecting: false });
});
it("preserves same-name same-kind drafts across equivalent streaming schemas and drops replaced fields", () => {
const before = form([{ name: "record", kind: "text" }, { name: "deleted", kind: "text" }]);
const state = normalizeAnswerViewState(before, { nodes: { node: { type: "FollowUpForm", values: { record: "尚未提交", deleted: "旧值" } } } });
expect(migrateAnswerViewState(before, structuredClone(before), state)).toEqual(state);
expect(migrateAnswerViewState(before, form([{ name: "record", kind: "number" }, { name: "added", kind: "text" }]), state).nodes.node).toEqual({ type: "FollowUpForm", values: {} });
expect(migrateAnswerViewState(before, form(), state).nodes.node).toEqual({ type: "FollowUpForm", values: { record: "尚未提交" } });
});
it("only accepts supported state, bounds indices, preserves draft text, and resets missing evidence filters", () => {
const current = table();
const result = normalizeAnswerViewState(current, { nodes: { node: { type: "Table", query: "查".repeat(2000), sort: { column: 99, descending: true }, selection: [-1, 0, 0, 2] }, unknown: { type: "Evidence", open: true } }, block: { evidenceFilter: "gone" }, action: "ignored" });
expect(result).toEqual({ nodes: { node: { type: "Table", query: "查".repeat(2000), sort: null, selection: [] } }, block: { evidenceFilter: "all" } });
});
it("tracks form and nested chart-table edits at field granularity", () => {
const current = form([{ name: "record", kind: "text" }, { name: "other", kind: "text" }]);
const before = normalizeAnswerViewState(current);
const after = normalizeAnswerViewState(current, { nodes: { node: { type: "FollowUpForm", values: { record: "草稿" } } } });
expect(answerViewStateDirtyPaths(before, after)).toEqual(["/nodes/node/values/record"]);
const chartState = normalizeAnswerViewState(chart());
const updated = structuredClone(chartState);
if (updated.nodes.node.type === "Chart") updated.nodes.node.table!.query = "a";
expect(answerViewStateDirtyPaths(chartState, updated)).toEqual(["/nodes/node/table/query"]);
});
});
@@ -0,0 +1,127 @@
import type { Spec } from "@json-render/core";
// `selection` is an empty legacy v1 wire field, never an interactive row selection.
export type AnswerTableState = { type: "Table"; query: string; sort: { column: number; descending: boolean } | null; selection: number[] };
export type AnswerChartState = { type: "Chart"; view: "line" | "bar" | "table"; hidden: number[]; range: [number, number]; point: number; inspecting: boolean; table?: Omit<AnswerTableState, "type"> };
export type AnswerFormState = { type: "FollowUpForm"; values: Record<string, string> };
export type AnswerEvidenceState = { type: "Evidence"; open: boolean };
export type AnswerUiNodeState = AnswerChartState | AnswerTableState | AnswerFormState | AnswerEvidenceState;
export type AnswerViewState = { nodes: Record<string, AnswerUiNodeState>; block: { evidenceFilter: string } };
export type AnswerViewStateChange = (next: AnswerViewState, dirtyPaths: string[]) => void;
export type AnswerViewStateRecord = AnswerViewState & {
version: "answer-view-state@1"; message_id: string; block_id: string; revision: number; schema_digest: string; updated_at: string | null;
};
type Node = Spec["elements"][string];
const record = (value: unknown): Record<string, unknown> => value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);
const indices = (value: unknown, length: number) => Array.isArray(value) ? [...new Set(value.filter((index): index is number => Number.isInteger(index) && index >= 0 && index < length))].slice(0, 100) : [];
const index = (value: unknown, length: number, fallback = 0) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value < length ? value : fallback;
export const answerStatePointer = (value: string) => value.replace(/~/g, "~0").replace(/\//g, "~1");
/** Only the local component allowlist can contribute state. Model props stay unchanged. */
export function normalizeAnswerNodeState(node: Node, input?: unknown): AnswerUiNodeState | undefined {
const value = record(input);
const state = value.type === node.type ? value : {};
if (node.type === "Chart") {
const labels = node.props.x_data as string[];
const series = node.props.series as unknown[];
const proposed = Array.isArray(state.range) ? state.range : [];
const start = index(proposed[0], labels.length);
const end = Math.max(start, index(proposed[1], labels.length, labels.length - 1));
const hidden = indices(state.hidden, series.length);
const chart: AnswerChartState = { type: "Chart", view: ["line", "bar", "table"].includes(String(state.view)) ? state.view as AnswerChartState["view"] : node.props.chart_type as "line" | "bar",
hidden: hidden.length < series.length ? hidden : [], range: [start, end], point: index(state.point, labels.length), inspecting: state.inspecting === true };
const data = answerChartTableData(node, chart);
const table = normalizeAnswerNodeState({ type: "Table", props: data, children: [] }, { ...record(state.table), type: "Table" }) as AnswerTableState;
const { type: _type, ...tableState } = table;
chart.table = tableState;
return chart;
}
if (node.type === "Table") {
const columns = node.props.columns as unknown[];
const sort = record(state.sort);
return { type: "Table", query: typeof state.query === "string" ? state.query : "",
sort: Number.isInteger(sort.column) && Number(sort.column) >= 0 && Number(sort.column) < columns.length && typeof sort.descending === "boolean" ? { column: Number(sort.column), descending: sort.descending } : null,
selection: [] };
}
if (node.type === "FollowUpForm") {
const values = record(state.values);
return { type: "FollowUpForm", values: Object.fromEntries((node.props.fields as Array<{ name: string }>).filter(({ name }) => typeof values[name] === "string").map(({ name }) => [name, String(values[name])])) };
}
if (node.type === "Evidence") return { type: "Evidence", open: state.open === true };
}
export function answerChartTableData(node: Node, state: AnswerChartState) {
const labels = node.props.x_data as string[], series = node.props.series as Array<{ name: string; data: number[] }>;
const visible = series.filter((_, index) => !state.hidden.includes(index));
return { columns: ["时间或类别", ...visible.map(({ name }) => name)], rows: labels.slice(state.range[0], state.range[1] + 1).map((label, index) => [label, ...visible.map(({ data }) => String(data[state.range[0] + index]))]) };
}
export function normalizeAnswerViewState(spec: Spec, input?: unknown): AnswerViewState {
const state = record(input), nodes = record(state.nodes), block = record(state.block);
const kinds = Object.values(spec.elements).filter((node) => node.type === "Evidence").map((node) => node.props.kind);
return { nodes: Object.fromEntries(Object.entries(spec.elements).flatMap(([id, node]) => {
const value = normalizeAnswerNodeState(node, nodes[id]);
return value ? [[id, value]] : [];
})), block: { evidenceFilter: typeof block.evidenceFilter === "string" && kinds.includes(block.evidenceFilter) ? block.evidenceFilter : "all" } };
}
/** Migrate by explicit data identity, never by assuming old indices identify new data. */
export function migrateAnswerViewState(previous: Spec, next: Spec, input: AnswerViewState): AnswerViewState {
const state = normalizeAnswerViewState(next, input);
for (const [id, value] of Object.entries(state.nodes)) {
const before = previous.elements[id], after = next.elements[id], old = input.nodes[id];
if (!before || before.type !== after.type || !old || old.type !== value.type) continue;
if (value.type === "Table") {
if (!same(before.props.columns, after.props.columns)) value.sort = null;
}
if (value.type === "FollowUpForm") {
const fields = before.props.fields as Array<{ name: string; kind: string }>;
const nextFields = after.props.fields as Array<{ name: string; kind: string }>;
value.values = Object.fromEntries(Object.entries(value.values).filter(([name]) => fields.some((field) => field.name === name && nextFields.some((nextField) => nextField.name === name && nextField.kind === field.kind))));
}
if (value.type === "Chart" && old.type === "Chart") {
const names = (node: Node) => (node.props.series as Array<{ name: string }>).map(({ name }) => name);
if (!same(names(before), names(after))) value.hidden = [];
const previousLabels = before.props.x_data as string[], labels = after.props.x_data as string[];
if (!same(previousLabels, labels) || !same(before.props.series, after.props.series)) {
const relocate = (position: number) => {
const label = previousLabels[position];
return label !== undefined && previousLabels.filter((item) => item === label).length === 1 && labels.filter((item) => item === label).length === 1 ? labels.indexOf(label) : -1;
};
const point = relocate(old.point), start = relocate(old.range[0]), end = relocate(old.range[1]);
if (point < 0 || start < 0 || end < start) {
value.point = 0; value.range = [0, labels.length - 1]; value.inspecting = false;
} else { value.point = point; value.range = [start, end]; }
}
if (value.table) {
const oldData = answerChartTableData(before, old), newData = answerChartTableData(after, value);
if (!same(oldData.columns, newData.columns)) value.table.sort = null;
}
}
}
return state;
}
export function answerViewStateDirtyPaths(before: AnswerViewState, after: AnswerViewState): string[] {
const paths: string[] = [];
for (const [id, value] of Object.entries(after.nodes)) {
const old = before.nodes[id];
if (old && old.type !== value.type) { paths.push(`/nodes/${answerStatePointer(id)}`); continue; }
for (const [field, next] of Object.entries(value)) {
if (field === "type") continue;
const prefix = `/nodes/${answerStatePointer(id)}/${field}`;
if (field === "values" && value.type === "FollowUpForm") {
const oldValues = old?.type === "FollowUpForm" ? old.values : {};
for (const name of new Set([...Object.keys(oldValues), ...Object.keys(value.values)])) if (oldValues[name] !== value.values[name]) paths.push(`${prefix}/${answerStatePointer(name)}`);
} else if (field === "table" && value.type === "Chart" && value.table) {
const oldTable = old?.type === "Chart" ? old.table : undefined;
for (const [key, item] of Object.entries(value.table)) if (!same(oldTable?.[key as keyof typeof oldTable], item)) paths.push(`${prefix}/${key}`);
} else if (!same(old && (old as unknown as Record<string, unknown>)[field], next)) paths.push(prefix);
}
}
if (before.block.evidenceFilter !== after.block.evidenceFilter) paths.push("/block/evidenceFilter");
for (const id of Object.keys(before.nodes)) if (!Object.hasOwn(after.nodes, id)) paths.push(`/nodes/${answerStatePointer(id)}`);
return paths;
}
+132
View File
@@ -0,0 +1,132 @@
import { defineCatalog } from "@json-render/core";
import { schema } from "@json-render/react/schema";
import { z } from "zod";
const shortText = z.string().max(200);
const text = z.string().max(4000);
const optionalText = shortText.nullable();
const featureId = z.string().min(1).max(128);
/** This is the source of the generated Agent contract, not a remotely hosted registry. */
export const answerUiCatalog = defineCatalog(schema, {
actions: {},
components: {
Stack: {
props: z
.object({
columns: z.enum(["one", "two"]), gap: z.enum(["compact", "normal"]),
intent: z.enum(["response", "comparison", "report"]).optional(),
density: z.enum(["compact", "comfortable"]).optional()
})
.strict(),
slots: ["default"],
description: "组织内容。intent 表达简短答复、并列比较或报告;density 表达疏密,不控制字体和颜色。comparison 与双列在窄面板自动改单列。"
},
Section: {
props: z.object({
title: shortText, description: text.nullable(),
role: z.enum(["result", "analysis", "evidence", "follow_up"]).optional()
}).strict(),
slots: ["default"],
description: "带标题的资料分区。role 标记结果、分析、依据或补充资料;前端据此组织任务内容,保留分区内部的原有顺序。"
},
Text: {
props: z.object({ text, tone: z.enum(["neutral", "info", "warning"]), title: shortText.optional() }).strict(),
description: "简短说明、判断边界或资料缺口。"
},
Result: {
props: z.object({
title: shortText,
summary: text,
status: z.enum(["success", "partial", "unconfirmed", "error"]),
source: optionalText
}).strict(),
description: "概括已有工具结果:成功、部分完成、未确认或失败。source 标注真实依据;无依据用 unconfirmed。此组件不执行操作,不证明浏览器展示、业务写入或现场处置完成。"
},
Metric: {
props: z
.object({ label: shortText, value: shortText, unit: optionalText, source: optionalText })
.strict(),
description: "展示真实指标及其单位、来源;不能臆造读数。"
},
Table: {
props: z
.object({
title: shortText,
columns: z.array(shortText).min(1).max(8),
rows: z.array(z.array(z.string().max(1000)).max(8)).max(50)
})
.strict(),
description: "按相同字段比较资料,避免无法比较的指标混列。"
},
Chart: {
props: z
.object({
title: shortText,
chart_type: z.enum(["line", "bar"]),
x_data: z.array(shortText).min(1).max(100),
series: z
.array(
z
.object({ name: shortText, data: z.array(z.number().finite()).min(1).max(100) })
.strict()
)
.min(1)
.max(8),
source: text
})
.strict(),
description:
"展示查询或用户提供的真实数据;series 必须与 x_data 对齐。浏览者可切换图形与数据表。"
},
Evidence: {
props: z
.object({
title: shortText,
summary: text,
source: shortText,
evidence_id: optionalText,
observed_at: optionalText,
kind: z.enum(["observed", "human_input", "inference", "demo"])
})
.strict(),
description: "展示证据依据;明确区分查询记录、用户事实、推断和演练数据。"
},
MapLocation: {
props: z
.object({
label: shortText,
layer: z.enum(["junctions", "pipes", "valves", "pumps", "tanks", "reservoirs", "scada"]),
feature_ids: z.array(featureId).min(1).max(100),
source: shortText
})
.strict(),
description: "用户点击后定位已有要素;ID 必须来自查询或用户明确提供,不绘制臆测影响范围。"
},
FollowUpForm: {
props: z
.object({
title: shortText,
description: text,
fields: z
.array(
z
.object({
name: z.string().regex(/^[a-z][a-z0-9_]{0,39}$/),
label: shortText,
kind: z.enum(["text", "datetime", "number"]),
required: z.boolean()
})
.strict()
)
.min(1)
.max(12)
})
.strict(),
description:
"让用户主动填写并提交补充资料;无默认事实。提交产生用户消息,是否写入业务证据由现有 Agent 工具处理。"
}
}
});
export const ANSWER_UI_VERSION = "answer-ui@1" as const;
@@ -0,0 +1,105 @@
import { describe, expect, it } from "vitest";
import { parseAnswerUiBlock } from "./contract";
const block = {
version: "answer-ui@1",
block_id: "reading",
fallback_text: "仍待核对",
spec: {
root: "note",
elements: { note: { type: "Text", props: { text: "仍待核对", tone: "neutral" }, children: [] } }
}
};
describe("untrusted answer components", () => {
it("keeps explicit UI phases and rejects invalid phase values", () => {
expect(parseAnswerUiBlock(block)?.phase).toBeUndefined();
expect(parseAnswerUiBlock({ ...block, phase: "process" })?.phase).toBe("process");
expect(parseAnswerUiBlock({ ...block, phase: "final" })?.phase).toBe("final");
expect(parseAnswerUiBlock({ ...block, phase: "other" })).toBeNull();
expect(parseAnswerUiBlock({ ...block, phase: null })).toBeNull();
});
it("accepts controlled task semantics and result states without accepting arbitrary presentation code", () => {
const result = { type: "Result", props: { title: "定位结果", summary: "3 根管道已定位,高亮未确认。", status: "partial", source: "地图工具回执" }, children: [] };
const spec = {
root: "root", elements: {
root: { type: "Stack", props: { columns: "one", gap: "normal", intent: "response", density: "compact" }, children: ["section"] },
section: { type: "Section", props: { title: "本次结果", description: null, role: "result" }, children: ["result"] },
result
}
};
expect(parseAnswerUiBlock({ ...block, spec })).not.toBeNull();
for (const props of [
{ ...result.props, status: "running" },
{ ...result.props, css: "display:none" },
{ ...result.props, onClick: "fetch('/write')" }
]) expect(parseAnswerUiBlock({ ...block, spec: { ...spec, elements: { ...spec.elements, result: { ...result, props } } } })).toBeNull();
expect(parseAnswerUiBlock({ ...block, spec: { root: "note", elements: { note: { ...block.spec.elements.note, props: { text: "高亮操作未提供。", tone: "warning", title: "能力限制" } } } } })).not.toBeNull();
});
it("accepts registered text and rejects arbitrary code, URLs and unknown components", () => {
expect(parseAnswerUiBlock(block)).not.toBeNull();
for (const node of [
{ type: "iframe", props: { src: "https://example.com" }, children: [] },
{
...block.spec.elements.note,
props: { ...block.spec.elements.note.props, script: "alert(1)" }
},
{ ...block.spec.elements.note, on: { click: { action: "fetch" } } }
])
expect(
parseAnswerUiBlock({ ...block, spec: { root: "note", elements: { note: node } } })
).toBeNull();
});
it("rejects missing, duplicate, cyclic, unreachable and excessive trees", () => {
const stack = { type: "Stack", props: { columns: "one", gap: "normal" }, children: ["note"] };
for (const children of [["missing"], ["note", "note"], ["root"]])
expect(
parseAnswerUiBlock({
...block,
spec: { root: "root", elements: { root: { ...stack, children }, ...block.spec.elements } }
})
).toBeNull();
expect(
parseAnswerUiBlock({
...block,
spec: {
...block.spec,
elements: { ...block.spec.elements, unused: block.spec.elements.note }
}
})
).toBeNull();
});
it("requires aligned, finite chart values and unambiguous form fields", () => {
const chart = {
type: "Chart",
props: {
title: "演练压力",
chart_type: "line",
source: "演练数据",
x_data: ["08:00"],
series: [{ name: "压力", data: [0.3] }]
},
children: []
};
const withNode = (node: unknown) => ({
...block,
spec: { root: "note", elements: { note: node } }
});
expect(parseAnswerUiBlock(withNode(chart))).not.toBeNull();
for (const data of [[0.3, 0.2], [Infinity], [NaN]])
expect(
parseAnswerUiBlock(
withNode({ ...chart, props: { ...chart.props, series: [{ name: "压力", data }] } })
)
).toBeNull();
const field = { name: "location", label: "位置", kind: "text", required: true };
expect(
parseAnswerUiBlock(
withNode({
type: "FollowUpForm",
props: { title: "核验", description: "用户补充", fields: [field, field] },
children: []
})
)
).toBeNull();
});
});
+79
View File
@@ -0,0 +1,79 @@
import type { Spec } from "@json-render/core";
import { z } from "zod";
import { answerUiCatalog, ANSWER_UI_VERSION } from "./catalog";
const key = z.string().regex(/^[a-zA-Z0-9_-]{1,80}$/);
const element = z
.object({ type: z.string(), props: z.record(z.unknown()), children: z.array(key).max(48) })
.strict();
const specSchema = z.object({ root: key, elements: z.record(element) }).strict();
const payloadSchema = z
.object({
version: z.literal(ANSWER_UI_VERSION),
block_id: key,
phase: z.enum(["process", "final"]).optional(),
fallback_text: z.string().min(1).max(4000),
spec: specSchema
})
.strict();
// Stored reports remain readable if one presentation component is no longer supported.
export const storedAnswerUiBlockSchema = z.object({
version: z.string(),
block_id: key,
phase: z.enum(["process", "final"]).optional(),
fallback_text: z.string().min(1).max(4000),
spec: z.unknown()
});
export const reportUiBlocksSchema = z.array(z.object({
block: storedAnswerUiBlockSchema,
evidence_refs: z.array(z.string().min(1).max(128)).min(1).max(100)
}).strict().refine((item) => item.block.phase !== "process", "过程界面不能发布为正式报告")).max(8);
export type StoredReportUiBlock = z.infer<typeof reportUiBlocksSchema>[number];
export type AnswerUiBlock = {
version: typeof ANSWER_UI_VERSION;
block_id: string;
phase?: "process" | "final";
fallback_text: string;
spec: Spec;
};
export type AnswerUiPart =
{ type: "text"; text: string } | { type: "answer-ui"; block: AnswerUiBlock };
export function parseAnswerUiBlock(value: unknown): AnswerUiBlock | null {
const parsed = payloadSchema.safeParse(value);
if (!parsed.success || JSON.stringify(parsed.data).length > 100000) return null;
const { spec } = parsed.data;
const nodes = Object.keys(spec.elements);
if (!nodes.length || nodes.length > 48 || nodes.some((name) => !key.safeParse(name).success))
return null;
const definitions = answerUiCatalog.data.components;
for (const node of Object.values(spec.elements)) {
const definition = Object.hasOwn(definitions, node.type)
? definitions[node.type as keyof typeof definitions]
: undefined;
if (!definition?.props.safeParse(node.props).success) return null;
if (!["Stack", "Section"].includes(node.type) && node.children.length) return null;
if (node.type === "Chart") {
const data = node.props as { x_data: unknown[]; series: Array<{ data: unknown[] }> };
if (data.series.some((series) => series.data.length !== data.x_data.length)) return null;
}
if (node.type === "Table") {
const data = node.props as { columns: unknown[]; rows: unknown[][] };
if (data.rows.some((row) => row.length !== data.columns.length)) return null;
}
if (node.type === "FollowUpForm") {
const data = node.props as { fields: Array<{ name: string }> };
if (new Set(data.fields.map((field) => field.name)).size !== data.fields.length) return null;
}
}
const visited = new Set<string>();
const visit = (id: string, depth: number): boolean => {
if (depth > 12 || visited.has(id) || !Object.hasOwn(spec.elements, id)) return false;
visited.add(id);
return spec.elements[id].children.every((child) => visit(child, depth + 1));
};
if (!visit(spec.root, 0) || visited.size !== nodes.length) return null;
return parsed.data;
}
@@ -0,0 +1,195 @@
import { useLayoutEffect, useRef, useState } from "react";
import { motion, useAnimationControls, useReducedMotion } from "motion/react";
import ReactECharts from "echarts-for-react";
import { BarChart3, X, Database, SlidersHorizontal, Table2, TrendingUp } from "lucide-react";
import { Card, CardContent, CardHeader, CardTitle } from "@/shared/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/shared/ui/tabs";
import { Button } from "@/shared/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/shared/ui/select";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/shared/ui/collapsible";
import { InteractiveDataTable } from "./interactive-data-table";
import { agentEase } from "../components/agent-motion";
export type AnswerChartProps = {
title: string;
chart_type: "line" | "bar";
x_data: string[];
series: Array<{ name: string; data: number[] }>;
source: string;
};
import { useAnswerNodeState } from "./answer-view-state-provider";
import type { AnswerChartState } from "./answer-view-state";
const colors = ["#2563eb", "#059669", "#d97706", "#7c3aed", "#0891b2", "#e11d48", "#475569", "#a16207"];
function PointSelect({ label, value, labels, onChange }: {
label: string; value: number; labels: string[]; onChange: (value: number) => void;
}) {
return <Select value={String(value)} onValueChange={(next) => onChange(Number(next))}>
<SelectTrigger aria-label={label} className="h-9 min-w-0 flex-1 text-xs"><SelectValue /></SelectTrigger>
<SelectContent>{labels.map((text, index) => <SelectItem key={index} value={String(index)}>{text}</SelectItem>)}</SelectContent>
</Select>;
}
export function InteractiveChart(props: AnswerChartProps) {
const [{ view, hidden, range, point, inspecting, table }, patch, migrationNotice] = useAnswerNodeState<AnswerChartState>("Chart", props);
const reducedMotion = useReducedMotion();
const pointer = useRef(false);
const plot = useRef<HTMLDivElement>(null);
const [animateInteraction, setAnimateInteraction] = useState(false);
const contentMotion = useAnimationControls();
const pendingTransition = useRef(false);
useLayoutEffect(() => {
// Start after the new ECharts view has mounted, so rendering cannot consume
// the transition before the browser gets a chance to paint it.
if (pendingTransition.current) {
pendingTransition.current = false;
void contentMotion.start({ opacity: 1, y: 0 }, { duration: 0.18, ease: agentEase });
} else contentMotion.set({ opacity: 1, y: 0 });
}, [contentMotion, view]);
const setView = (next: string) => {
if (next === view) return;
const animate = pointer.current && !reducedMotion;
setAnimateInteraction(animate);
contentMotion.stop();
contentMotion.set(animate ? { opacity: 0, y: 4 } : { opacity: 1, y: 0 });
pendingTransition.current = animate;
patch({ view: next as AnswerChartState["view"] });
};
const setRange = (range: [number, number]) => patch({ range, table: { query: "", sort: null, ...table, selection: [] } }, ["range"]);
const setPoint = (point: number) => patch({ point });
const setInspecting = (inspecting: boolean) => patch({ inspecting });
const visible = props.series.filter((_, index) => !hidden.includes(index));
const labels = props.x_data.slice(range[0], range[1] + 1);
const pointIndex = Math.min(range[1], Math.max(range[0], point));
const fullRange = range[0] === 0 && range[1] === props.x_data.length - 1;
const summaries = visible.map((series) => {
const values = series.data.slice(range[0], range[1] + 1);
return { name: series.name, first: values[0], last: values.at(-1)!, min: Math.min(...values), max: Math.max(...values) };
});
const option = (type: "line" | "bar") => ({
animation: animateInteraction && !reducedMotion,
animationDuration: 180,
animationDurationUpdate: 180,
color: colors.filter((_, index) => !hidden.includes(index)),
aria: { enabled: true },
tooltip: { trigger: "axis", renderMode: "richText" },
grid: { top: 16, right: 12, bottom: 38, left: 12, containLabel: true },
xAxis: { type: "category", data: labels, axisLabel: { fontSize: 11, color: "#64748b", hideOverlap: true } },
yAxis: { type: "value", axisLabel: { fontSize: 11, color: "#64748b" }, splitLine: { lineStyle: { color: "#e2e8f0" } } },
series: visible.map((series) => ({ name: series.name, type, data: series.data.slice(range[0], range[1] + 1),
showSymbol: true, symbolSize: 7, emphasis: { focus: "series" } }))
});
return <Collapsible asChild><Card className="answer-ui-chart overflow-hidden" role="group" aria-label={props.title}
onPointerDownCapture={() => { pointer.current = true; }}
onKeyDownCapture={() => {
pointer.current = false;
setAnimateInteraction(false);
contentMotion.stop();
contentMotion.set({ opacity: 1, y: 0 });
}}>
<CardHeader className="flex-row items-center justify-between gap-2 space-y-0 px-3.5 py-2.5">
<CardTitle className="flex min-w-0 items-center gap-2 text-xs leading-5 tracking-normal"><TrendingUp size={15} className="shrink-0" aria-hidden />{props.title}</CardTitle>
<CollapsibleTrigger asChild>
<Button type="button" variant="ghost" size="icon-sm" aria-label="筛选数据范围" title="筛选数据范围"
className="shrink-0 text-muted-foreground">
<SlidersHorizontal size={14} aria-hidden />
</Button>
</CollapsibleTrigger>
</CardHeader>
<CardContent className="space-y-3 px-3.5 pb-3.5 pt-0">
{migrationNotice ? <p role="status" className="text-xs leading-5 text-muted-foreground">{migrationNotice}</p> : null}
<Tabs value={view} onValueChange={setView}>
<TabsList aria-label={`${props.title}显示方式`} className="relative mb-3 grid w-full grid-cols-3 [&>[role=tab]]:relative [&>[role=tab]]:z-10 [&>[role=tab][data-state=active]]:bg-transparent [&>[role=tab][data-state=active]]:shadow-none">
<motion.span aria-hidden className="pointer-events-none absolute inset-y-1 left-1 rounded-md bg-card shadow-xs"
style={{ width: "calc((100% - 0.5rem) / 3)" }}
initial={false} animate={{ x: view === "line" ? "0%" : view === "bar" ? "100%" : "200%" }}
transition={{ duration: animateInteraction && !reducedMotion ? 0.18 : 0, ease: agentEase }} />
<TabsTrigger value="line"><TrendingUp size={13} />折线</TabsTrigger>
<TabsTrigger value="bar"><BarChart3 size={13} />柱状</TabsTrigger>
<TabsTrigger value="table"><Table2 size={13} />数据</TabsTrigger>
</TabsList>
<div className="answer-ui-chart-series mb-2 flex flex-wrap gap-2" aria-label="显示的数据序列">
{props.series.map((series, index) => <Button key={index} size="sm" variant="outline"
className="h-8 gap-1.5 text-[11px]" aria-pressed={!hidden.includes(index)}
disabled={visible.length === 1 && !hidden.includes(index)}
onClick={() => { setAnimateInteraction(pointer.current && !reducedMotion); patch({ hidden: hidden.includes(index) ? hidden.filter((item) => item !== index) : [...hidden, index],
table: { query: "", ...table, sort: null, selection: [] } }, ["hidden", "table/sort"]); }}>
<span className="size-2 rounded-full" style={{ background: hidden.includes(index) ? "#cbd5e1" : colors[index] }} />{series.name}
</Button>)}
</div>
{!fullRange ? <p className="mb-2 text-[11px] text-muted-foreground">{props.x_data[range[0]]} 至 {props.x_data[range[1]]}</p> : null}
<CollapsibleContent className="mb-2 space-y-2 rounded-lg border bg-muted/30 p-2.5">
<div className="flex items-center gap-2">
<PointSelect label="区间起点" value={range[0]} labels={props.x_data}
onChange={(start) => setRange([start, Math.max(start, range[1])])} />
<span className="text-xs text-muted-foreground">至</span>
<PointSelect label="区间终点" value={range[1]} labels={props.x_data}
onChange={(end) => setRange([Math.min(range[0], end), end])} />
</div>
<Button type="button" variant="ghost" size="sm" disabled={fullRange}
onClick={() => setRange([0, props.x_data.length - 1])}>重置范围</Button>
</CollapsibleContent>
<motion.div data-chart-view={view} initial={false} animate={contentMotion}>
{(["line", "bar"] as const).map((type) => <TabsContent key={type} value={type}>
<div ref={view === type ? plot : undefined} role="group" aria-label={`${props.title},按回车查看数据点,方向键切换数据点`} tabIndex={0}
className="rounded-md focus-visible:outline-2 focus-visible:outline-ring"
onKeyDown={(event) => {
if (event.target !== event.currentTarget) return;
if (["Enter", "ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) {
event.preventDefault();
const next = event.key === "Home" ? range[0] : event.key === "End" ? range[1]
: Math.min(range[1], Math.max(range[0], pointIndex + (event.key === "ArrowRight" ? 1 : event.key === "ArrowLeft" ? -1 : 0)));
patch({ point: next, inspecting: true });
}
if (event.key === "Escape") setInspecting(false);
}}>
<span className="sr-only">点击图中数据点查看详情,也可使用回车和左右方向键。</span>
<ReactECharts option={option(type)} opts={{ renderer: "svg" }} notMerge style={{ height: 220 }}
onEvents={{ click: (event: { componentType?: string; dataIndex?: number }) => {
if (event.componentType === "series" && typeof event.dataIndex === "number") {
patch({ point: range[0] + event.dataIndex, inspecting: true });
}
} }} />
</div>
</TabsContent>)}
<TabsContent value="table" forceMount style={view === "table" ? undefined : { display: "none" }}>
<InteractiveDataTable title={props.title} columns={["时间或类别", ...visible.map((series) => series.name)]}
rows={labels.map((label, index) => [label, ...visible.map((series) => String(series.data[range[0] + index]))])}
state={table} onStateChange={(updates) => patch({ table: { query: "", sort: null, selection: [], ...table, ...updates } }, Object.keys(updates).map((key) => `table/${key}`))} />
</TabsContent>
</motion.div>
</Tabs>
{view !== "table" ? <div className="rounded-lg bg-muted/40 p-2.5" role="group" aria-label="当前区间摘要">
<div className="mb-2 flex flex-wrap items-center justify-between gap-1">
<span className="text-[11px] font-medium">区间摘要 <span className="font-normal text-muted-foreground">· 本地统计</span></span>
</div>
<div className="space-y-2">
{summaries.map((item) => <div key={item.name} className="answer-chart-range-summary text-[11px] leading-5">
<span className="min-w-0 break-words text-muted-foreground">{item.name}</span>
<span className="tabular-nums">{item.first} → {item.last}</span>
<span className="text-muted-foreground">最小 {item.min} · 最大 {item.max}</span>
</div>)}
</div>
</div> : null}
{view !== "table" && inspecting ? <motion.section aria-label="数据点详情" className="rounded-lg border border-border p-2.5"
initial={pointer.current && !reducedMotion ? { opacity: 0, y: 4 } : false}
animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.18, ease: agentEase }}>
<div className="mb-2 flex items-center justify-between gap-2">
<span className="text-xs font-medium">数据点详情</span>
<Button type="button" variant="ghost" size="icon-sm" aria-label="关闭数据点详情" onClick={() => { setInspecting(false); plot.current?.focus(); }}><X size={14} aria-hidden /></Button>
</div>
<div className="flex items-center gap-2"><span className="text-xs text-muted-foreground">时间或类别</span>
<PointSelect label="选择数据点" value={pointIndex - range[0]} labels={labels} onChange={(index) => setPoint(range[0] + index)} />
</div>
<dl className="my-2 space-y-1.5 text-xs">
{visible.map((series, index) => <div key={index} className="flex items-baseline justify-between gap-3">
<dt className="min-w-0 text-muted-foreground">{series.name}</dt>
<dd className="shrink-0 font-medium tabular-nums">{series.data[pointIndex]}</dd>
</div>)}
</dl>
</motion.section> : null}
<p className="flex items-start gap-1.5 border-t pt-2.5 text-[11px] leading-5 text-muted-foreground">
<Database size={12} className="mt-1 shrink-0" /><span>{fullRange ? labels.length : `${labels.length} / ${props.x_data.length}`} 个数据点 · {visible.length} 组序列<br />来源:{props.source}</span>
</p>
</CardContent>
</Card></Collapsible>;
}
@@ -0,0 +1,65 @@
import { useMemo } from "react";
import { ArrowDown, ArrowUp, ArrowUpDown } from "lucide-react";
import { Input } from "@/shared/ui/input";
import { Button } from "@/shared/ui/button";
import { cn } from "@/shared/ui/cn";
import { Table, TableBody, TableCaption, TableCell, TableHead, TableHeader, TableRow } from "@/shared/ui/table";
import { useAnswerNodeState } from "./answer-view-state-provider";
import type { AnswerTableState } from "./answer-view-state";
export function InteractiveDataTable({ title, columns, rows, state: controlledState, onStateChange }: {
title: string; columns: string[]; rows: string[][];
state?: Omit<AnswerTableState, "type">;
onStateChange?: (patch: Partial<Omit<AnswerTableState, "type">>) => void;
}) {
const [localState, patchLocal] = useAnswerNodeState<AnswerTableState>("Table", { title, columns, rows });
const state = controlledState ?? localState;
const patch = onStateChange ?? patchLocal;
const { query, sort } = state;
const filtered = useMemo(() => {
const items = rows.map((cells, id) => ({ cells, id }))
.filter(({ cells }) => cells.join(" ").toLocaleLowerCase().includes(query.trim().toLocaleLowerCase()));
if (sort) items.sort((a, b) => {
const aValue = a.cells[sort.column], bValue = b.cells[sort.column];
const compared = /^[-+]?\d+(\.\d+)?%?$/.test(aValue) && /^[-+]?\d+(\.\d+)?%?$/.test(bValue)
? Number.parseFloat(aValue) - Number.parseFloat(bValue)
: aValue.localeCompare(bValue, "zh-CN", { numeric: true });
return sort.descending ? -compared : compared;
});
return items;
}, [rows, sort, query]);
return <div className="min-w-0 space-y-2" data-interactive-table>
<div className="flex flex-wrap items-center gap-2">
<Input aria-label={`搜索${title}`} placeholder="搜索当前数据" value={query} className="h-9 min-w-0 flex-1 text-xs"
onChange={(event) => { patch({ query: event.currentTarget.value }); }} />
<span className="text-[11px] tabular-nums text-muted-foreground">{filtered.length} / {rows.length} 行</span>
</div>
<div role="region" aria-label={title} tabIndex={0}
className="answer-ui-table overflow-x-auto rounded-lg border border-border focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring">
<Table>
<TableCaption className="caption-top font-medium">{title}</TableCaption>
<TableHeader className="bg-muted/50"><TableRow>
{columns.map((column, index) => <TableHead key={index} scope="col" className="whitespace-nowrap"
aria-sort={sort?.column === index ? sort.descending ? "descending" : "ascending" : "none"}>
<Button size="sm" variant="ghost" className="h-9 gap-1 px-1 text-xs" aria-label={`按${column}排序`}
onClick={() => patch({ sort: sort?.column === index
? sort.descending ? null : { column: index, descending: true }
: { column: index, descending: false } })}>
{column}{sort?.column === index ? sort.descending ? <ArrowDown size={12} /> : <ArrowUp size={12} /> : <ArrowUpDown size={12} />}
</Button>
</TableHead>)}
</TableRow></TableHeader>
<TableBody>
{filtered.map(({ cells, id }) => <TableRow key={id}>
{cells.map((cell, index) => <TableCell key={index}
className={cn("min-w-24", /^[-+]?\d+(\.\d+)?%?$/.test(cell) && "text-right tabular-nums")}>{cell}</TableCell>)}
</TableRow>)}
{!filtered.length ? <TableRow><TableCell colSpan={columns.length} className="py-6 text-center text-xs text-muted-foreground">
{rows.length ? "当前筛选没有匹配的数据。" : "没有已加载的数据。"}
</TableCell></TableRow> : null}
</TableBody>
</Table>
</div>
</div>;
}
@@ -0,0 +1,33 @@
import { afterEach, expect, it, vi } from "vitest";
import { createAgentApiClient } from "./client";
afterEach(() => vi.unstubAllGlobals());
it("reads mailbox pages without sending or consuming messages and validates the contract", async () => {
const message = { message_id: "m1", task_id: "t1", run_id: "r1", source_session_id: "task-session", target_session_id: "chat-session", direction: "to_chat", text: "现场记录已核对", status: "pending", in_reply_to: null, created_at: "2026-10-13T00:00:00Z", source_owner_id: "private-owner" };
const fetchMock = vi.fn().mockResolvedValue(Response.json({ items: [message], next_cursor: "m1" }));
vi.stubGlobal("fetch", fetchMock);
const client = createAgentApiClient("http://agent.local", { getAccessToken: async () => "token", getProjectId: async () => "p1" });
const page = await client.listAgentMessages("chat-session", { cursor: "previous" });
expect(page.items[0]).not.toHaveProperty("source_owner_id");
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe("http://agent.local/api/v1/session/chat-session/agent-messages?limit=50&cursor=previous");
expect(init.method).toBeUndefined();
expect(init.body).toBeUndefined();
expect(new Headers(init.headers).get("X-Project-Id")).toBe("p1");
fetchMock.mockResolvedValue(Response.json({ items: [{ ...message, target_session_id: null, direction: "to_task" }], next_cursor: null }));
expect((await client.listAgentMessages("chat-session")).items[0].target_session_id).toBeNull();
fetchMock.mockResolvedValue(Response.json({ items: [{ ...message, status: "invented" }], next_cursor: null }));
await expect(client.listAgentMessages("chat-session")).rejects.toThrow();
});
it("accepts inbox notifications only for the subscribed session", async () => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response([
'event: agent_message\ndata: {"session_id":"other"}\n\n',
'event: agent_message\ndata: {"session_id":"main"}\n\n',
': heartbeat\n\n'
].join(""))));
const onMessage = vi.fn();
await createAgentApiClient("http://agent.local").streamAgentMessages("main", { onMessage });
expect(onMessage).toHaveBeenCalledOnce();
});
+21
View File
@@ -0,0 +1,21 @@
import { z } from "zod";
export const agentMessageSchema = z.object({
message_id: z.string().min(1),
task_id: z.string().min(1),
run_id: z.string().min(1),
source_session_id: z.string().min(1),
target_session_id: z.string().min(1).nullable(),
direction: z.enum(["to_task", "to_chat"]),
text: z.string(),
status: z.enum(["pending", "enqueued", "delivered", "failed"]),
in_reply_to: z.string().nullable(),
created_at: z.string(),
failure_detail: z.string().nullable().optional()
});
export const agentMessagePageSchema = z.object({
items: z.array(agentMessageSchema),
next_cursor: z.string().nullable()
});
export type AgentMailboxMessage = z.infer<typeof agentMessageSchema>;
export type AgentMessagePage = z.infer<typeof agentMessagePageSchema>;
@@ -0,0 +1,51 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { createAgentApiClient } from "./client";
import type { AnswerViewStateWrite } from "./answer-view-state";
const remote = { version: "answer-view-state@1", message_id: "message", block_id: "block", revision: 2,
schema_digest: "digest", nodes: {}, block: { evidenceFilter: "all" }, updated_at: null };
const write: AnswerViewStateWrite = { message_id: "message", block_id: "block", expected_revision: 2, schema_digest: "digest", request_id: "intent", nodes: {}, block: { evidenceFilter: "all" } };
const token = (subject: string) => `header.${btoa(JSON.stringify({ iss: "https://identity.local", sub: subject }))}.signature`;
afterEach(() => vi.unstubAllGlobals());
describe("authorized answer view state API", () => {
it("keeps the message and block identity and uses the configured auth/project context", async () => {
const fetcher = vi.fn().mockImplementation(async () => Response.json(remote)); vi.stubGlobal("fetch", fetcher);
const api = createAgentApiClient("https://agent.local", { getAccessToken: async () => token("alice"), getProjectId: async () => "project" });
await expect(api.getAnswerViewState("session/one", "message", "block")).resolves.toEqual(remote);
await api.putAnswerViewState("session/one", write);
expect(fetcher.mock.calls[0][0]).toBe("https://agent.local/api/v1/session/session%2Fone/ui-state?message_id=message&block_id=block");
expect(fetcher.mock.calls[1][0]).toBe("https://agent.local/api/v1/session/session%2Fone/ui-state");
expect(fetcher.mock.calls[1][1].body).toBe(JSON.stringify(write));
for (const [, init] of fetcher.mock.calls) {
expect(new Headers(init.headers).get("Authorization")).toBe(`Bearer ${token("alice")}`);
expect(new Headers(init.headers).get("X-Project-Id")).toBe("project");
}
});
it("retains structured conflict details for the explicit user choices", async () => {
vi.stubGlobal("fetch", vi.fn(async () => Response.json({ code: "ANSWER_VIEW_STATE_CONFLICT", detail: "new revision", current: remote }, { status: 409 })));
await expect(createAgentApiClient("https://agent.local").putAnswerViewState("session", write)).rejects.toMatchObject({
status: 409, code: "ANSWER_VIEW_STATE_CONFLICT", current: remote,
});
});
it("rejects writes if a mutable token provider changes subject in the same project", async () => {
const fetcher = vi.fn(async () => Response.json(remote)); vi.stubGlobal("fetch", fetcher);
let subject = "alice";
const api = createAgentApiClient("https://agent.local", { getAccessToken: async () => token(subject), getProjectId: async () => "same-project" });
await api.getAnswerViewState("session", "message", "block"); subject = "bob";
await expect(api.putAnswerViewState("session", write)).rejects.toMatchObject({ code: "ANSWER_VIEW_IDENTITY_CHANGED" });
expect(fetcher).toHaveBeenCalledTimes(1);
});
it("rejects a late read if identity changes while the request is in flight", async () => {
let finish!: (response: Response) => void;
const fetcher = vi.fn(() => new Promise<Response>((resolve) => { finish = resolve; })); vi.stubGlobal("fetch", fetcher);
let subject = "alice";
const api = createAgentApiClient("https://agent.local", { getAccessToken: async () => token(subject) });
const read = api.getAnswerViewState("session", "message", "block");
await vi.waitFor(() => expect(fetcher).toHaveBeenCalledTimes(1)); subject = "bob"; finish(Response.json(remote));
await expect(read).rejects.toMatchObject({ code: "ANSWER_VIEW_IDENTITY_CHANGED" });
});
it("rejects remote state containing unknown executable fields", async () => {
vi.stubGlobal("fetch", vi.fn(async () => Response.json({ ...remote, nodes: { x: { type: "Evidence", open: true, script: "bad" } } })));
await expect(createAgentApiClient("https://agent.local").getAnswerViewState("session", "message", "block")).rejects.toThrow();
});
});
@@ -0,0 +1,44 @@
import { z } from "zod";
import type { AnswerViewState } from "../answer-ui/answer-view-state";
const index = z.number().int().nonnegative();
const chartTable = z.object({ query: z.string(), sort: z.object({ column: index, descending: z.boolean() }).strict().nullable(), selection: z.array(index) }).strict();
const node = z.discriminatedUnion("type", [
z.object({ type: z.literal("Chart"), view: z.enum(["line", "bar", "table"]), hidden: z.array(index), range: z.tuple([index, index]), point: index, inspecting: z.boolean(), table: chartTable.optional() }).strict(),
z.object({ type: z.literal("Table"), query: z.string(), sort: z.object({ column: index, descending: z.boolean() }).strict().nullable(), selection: z.array(index) }).strict(),
z.object({ type: z.literal("FollowUpForm"), values: z.record(z.string()) }).strict(),
z.object({ type: z.literal("Evidence"), open: z.boolean() }).strict(),
]);
const record = z.object({
version: z.literal("answer-view-state@1"), message_id: z.string(), block_id: z.string(),
revision: index, schema_digest: z.string().min(1), nodes: z.record(node),
block: z.object({ evidenceFilter: z.string() }).strict(), updated_at: z.string().nullable(),
}).strict();
export type AnswerViewStateRecord = AnswerViewState & {
version: "answer-view-state@1"; message_id: string; block_id: string;
revision: number; schema_digest: string; updated_at: string | null;
};
export type AnswerViewStateWrite = AnswerViewState & {
message_id: string; block_id: string; schema_digest: string;
expected_revision: number; request_id: string;
};
export class AnswerViewStateApiError extends Error {
constructor(message: string, readonly status: number, readonly code?: string, readonly current?: AnswerViewStateRecord) {
super(message);
this.name = "AnswerViewStateApiError";
}
}
export function parseAnswerViewStateRecord(value: unknown): AnswerViewStateRecord {
return record.parse(value) as AnswerViewStateRecord;
}
export async function readAnswerViewStateResponse(response: Response): Promise<AnswerViewStateRecord> {
const data: unknown = await response.json();
if (!response.ok) {
const error = z.object({ code: z.string().optional(), detail: z.string().optional(), current: z.unknown().optional() }).passthrough().safeParse(data);
const current = error.success && error.data.current ? record.safeParse(error.data.current) : null;
throw new AnswerViewStateApiError(error.success ? error.data.detail ?? "交互状态未保存,请重试" : "交互状态暂不可用,请重试", response.status,
error.success ? error.data.code : undefined, current?.success ? current.data as AnswerViewStateRecord : undefined);
}
return parseAnswerViewStateRecord(data);
}
@@ -0,0 +1,34 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { createAgentApiClient } from "./client";
afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); });
describe("authenticated session exports", () => {
it("fetches only Agent session files with identity and project headers", async () => {
const fetchMock = vi.fn(async () => new Response("ZIP", { headers: { "Content-Type": "application/zip" } }));
vi.stubGlobal("fetch", fetchMock);
vi.stubGlobal("URL", class extends URL {
static createObjectURL = vi.fn(() => "blob:fixture");
static revokeObjectURL = vi.fn();
});
const click = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
const client = createAgentApiClient("https://agent.test", { getAccessToken: async () => "FIXTURE", getProjectId: async () => "project-a" });
const path = "/api/v1/session/session-a/files/mcp-11111111-1111-1111-1111-111111111111.zip";
await client.downloadFile(path);
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
expect(url).toBe(`https://agent.test${path}`);
expect(new Headers(init.headers).get("Authorization")).toBe("Bearer FIXTURE");
expect(new Headers(init.headers).get("X-Project-Id")).toBe("project-a");
expect(init.redirect).toBe("error");
expect(click).toHaveBeenCalledOnce();
});
it("rejects arbitrary URLs and paths before requesting any credential", async () => {
const getAccessToken = vi.fn();
const client = createAgentApiClient("https://agent.test", { getAccessToken });
for (const path of ["https://foreign.test/file.zip", "/api/v1/admin/files/a.zip", "/api/v1/session/s/files/secret.env", "/api/v1/session/s/files/../owner.json"]) {
await expect(client.downloadFile(path)).rejects.toThrow("无效");
}
expect(getAccessToken).not.toHaveBeenCalled();
});
});
+199 -6
View File
@@ -1,7 +1,108 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { createAgentApiClient } from "./client";
import { AgentResponseFinishedError, createAgentApiClient } from "./client";
describe("Agent prompt suggestions", () => {
it("probes public readiness without loading identity or project credentials", async () => {
const getAccessToken = vi.fn(async () => "private-token");
const getProjectId = vi.fn(async () => "project");
const fetcher = vi.fn().mockResolvedValueOnce(Response.json({ ok: true, ready: true }))
.mockResolvedValueOnce(Response.json({ ok: true, ready: false }));
vi.stubGlobal("fetch", fetcher);
const client = createAgentApiClient("https://agent.local/prefix", { getAccessToken, getProjectId });
const signal = new AbortController().signal;
await expect(client.getHealth(signal)).resolves.toBeUndefined();
expect(fetcher).toHaveBeenCalledWith("https://agent.local/prefix/health", { signal, cache: "no-store" });
expect(getAccessToken).not.toHaveBeenCalled();
expect(getProjectId).not.toHaveBeenCalled();
await expect(client.getHealth(signal)).rejects.toThrow("尚未就绪");
});
it("distinguishes a proven pre-admission idle response from ambiguous input conflicts", async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce(Response.json({ code: "RESPONSE_FINISHED", message: "finished" }, { status: 409 }))
.mockResolvedValueOnce(Response.json({ message: "unknown conflict" }, { status: 409 }));
vi.stubGlobal("fetch", fetchMock);
const client = createAgentApiClient("http://agent.local");
await expect(client.submitResponseInput("s", "next", "queue", `msg_${"1".repeat(32)}`)).rejects.toBeInstanceOf(AgentResponseFinishedError);
const uncertain = client.submitResponseInput("s", "next", "queue", `msg_${"2".repeat(32)}`);
await expect(uncertain).rejects.not.toBeInstanceOf(AgentResponseFinishedError);
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it("uses owned topic endpoints and retains full-text hits from another topic", async () => {
const topic = { id: "topic-a", name: "城南压力问题", createdAt: "2026-10-22T01:00:00Z", updatedAt: "2026-10-22T01:00:00Z" };
const fetchMock = vi.fn()
.mockResolvedValueOnce(Response.json({ topics: [topic] }))
.mockResolvedValueOnce(Response.json({ sessions: [{ id: "session-b", title: "另一段对话", topic_id: "topic-b", topic_name: "检修事件", search_snippet: "正文中的南桥阀门", purpose: "task_collaboration" }], has_more: false }))
.mockResolvedValueOnce(Response.json({ session_id: "session-b", topic_id: "topic-a" }))
.mockResolvedValueOnce(new Response(null, { status: 204 }));
vi.stubGlobal("fetch", fetchMock);
const client = createAgentApiClient("http://agent.local", { getAccessToken: async () => "token", getProjectId: async () => "project-a" });
expect(await client.listTopics()).toEqual([topic]);
const result = await client.listSessionPage({ q: "南桥阀门", includeCollaboration: true });
expect(result.sessions[0]).toMatchObject({ title: "另一段对话", topicId: "topic-b", topicName: "检修事件", searchSnippet: "正文中的南桥阀门", purpose: "task_collaboration" });
const query = new URL(String(fetchMock.mock.calls[1]?.[0])).searchParams;
expect(query.get("q")).toBe("南桥阀门");
expect(query.has("topic_id")).toBe(false);
expect(query.get("include_collaboration")).toBe("true");
await client.moveSessionToTopic("session-b", "topic-a");
expect(JSON.parse(String(fetchMock.mock.calls[2]?.[1]?.body))).toEqual({ topic_id: "topic-a" });
await client.deleteTopic("topic-a");
expect(String(fetchMock.mock.calls[3]?.[0])).toContain("/topics/topic-a");
for (const [, init] of fetchMock.mock.calls) {
expect(new Headers(init?.headers).get("Authorization")).toBe("Bearer token");
expect(new Headers(init?.headers).get("X-Project-Id")).toBe("project-a");
}
});
it("submits and edits pending input through the scoped Responses and session endpoints", async () => {
const input = { id: `msg_${"1".repeat(32)}`, text: "补充压力测点", delivery: "steer", status: "pending" };
const fetchMock = vi.fn().mockResolvedValueOnce(Response.json(input)).mockResolvedValueOnce(Response.json({ items: [input] }))
.mockResolvedValueOnce(Response.json({ ...input, delivery: "queue" }))
.mockResolvedValueOnce(Response.json({ ...input, status: "cancelled" }));
vi.stubGlobal("fetch", fetchMock);
const client = createAgentApiClient("http://agent.local", { getAccessToken: async () => "token", getProjectId: async () => "project" });
await expect(client.submitResponseInput("session-1", input.text, "steer", input.id)).resolves.toEqual(input);
expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toEqual({ input: input.text, conversation: "session-1", stream: false, tjwater: { delivery: "steer", input_id: input.id } });
await expect(client.listResponseInputs("session-1")).resolves.toEqual([input]);
await expect(client.updateResponseInput("session-1", input.id, "queue")).resolves.toEqual({ ...input, delivery: "queue" });
await expect(client.cancelResponseInput("session-1", input.id)).resolves.toEqual({ ...input, status: "cancelled" });
expect(fetchMock.mock.calls[3]?.[1]?.method).toBe("DELETE");
expect(String(fetchMock.mock.calls[0]?.[0])).toBe("http://agent.local/api/v1/responses");
expect(String(fetchMock.mock.calls[2]?.[0])).toContain(`/api/v1/session/session-1/inputs/${input.id}`);
for (const [, request] of fetchMock.mock.calls) {
expect(new Headers(request?.headers).get("Authorization")).toBe("Bearer token");
expect(new Headers(request?.headers).get("X-Project-Id")).toBe("project");
}
});
it("uses the scoped Agent request and rejects invented activity references", async () => {
const fetchMock = vi.fn().mockResolvedValue(Response.json({ suggestions: [{ question: "核对城南压力告警的证据", activity_id: "alert:pressure" }] }));
vi.stubGlobal("fetch", fetchMock);
const client = createAgentApiClient("http://agent.local", { getAccessToken: async () => "token", getProjectId: async () => "project" });
const activities = [{ id: "alert:pressure", kind: "alert" as const, title: "城南压力告警", occurred_at: "2026-10-09T07:00:00Z", origin: "backend" as const }];
const controller = new AbortController();
expect(await client.generatePromptSuggestions(activities, "test/model", controller.signal)).toEqual([{ question: "核对城南压力告警的证据", activityId: "alert:pressure" }]);
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe("http://agent.local/api/v1/suggestions");
expect(new Headers(init.headers).get("Authorization")).toBe("Bearer token");
expect(new Headers(init.headers).get("X-Project-Id")).toBe("project");
expect(init.signal).toBe(controller.signal);
fetchMock.mockResolvedValue(Response.json({ suggestions: [{ question: "引用其他项目", activity_id: "unknown" }] }));
await expect(client.generatePromptSuggestions(activities, "test/model")).rejects.toThrow("Invalid Agent suggestion");
vi.unstubAllGlobals();
});
});
describe("Agent API client sessions", () => {
it("forces renewal and sends only the refresh request id with verified context headers", async () => {
const getAccessToken = vi.fn(async () => "TEST_NEW_TOKEN");
const fetchMock = vi.fn(async () => Response.json({ accepted: true }, { status: 202 }));
vi.stubGlobal("fetch", fetchMock);
await createAgentApiClient("http://agent.local", { getAccessToken, getProjectId: async () => "p" }).refreshCredential("s", "request-1");
expect(getAccessToken).toHaveBeenCalledWith(true);
const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
expect(new Headers(init.headers).get("Authorization")).toBe("Bearer TEST_NEW_TOKEN");
expect(JSON.parse(String(init.body))).toEqual({ request_id: "request-1" });
});
afterEach(() => {
vi.unstubAllGlobals();
});
@@ -33,7 +134,11 @@ describe("Agent API client sessions", () => {
status: undefined,
parentSessionId: undefined,
isStreaming: undefined,
runStatus: "running"
runStatus: "running",
purpose: "ordinary_chat",
taskId: undefined,
trigger: undefined,
topicId: null, topicName: undefined, searchSnippet: undefined
},
{
id: "old",
@@ -43,7 +148,11 @@ describe("Agent API client sessions", () => {
status: undefined,
parentSessionId: undefined,
isStreaming: undefined,
runStatus: undefined
runStatus: undefined,
purpose: "ordinary_chat",
taskId: undefined,
trigger: undefined,
topicId: null, topicName: undefined, searchSnippet: undefined
}
]);
});
@@ -54,6 +163,76 @@ describe("Agent API client sessions", () => {
await expect(createAgentApiClient("http://agent.local").loadSession("missing")).resolves.toBeNull();
});
it("loads a task execution history through its exact task and run binding", async () => {
const fetchMock = vi.fn(async (..._args: Parameters<typeof fetch>) => Response.json({
id: "execution-session",
session_id: "execution-session",
title: "南桥管道爆管调查 · 执行记录",
purpose: "task_execution",
task_id: "50000000-0000-4000-8000-000000000001",
created_at: "2026-10-30T01:00:00Z",
updated_at: "2026-10-30T01:05:00Z",
messages: [{ id: "assistant", role: "assistant", parts: [{ type: "text", text: "调查完成" }] }],
is_streaming: false,
run_status: "completed"
}));
vi.stubGlobal("fetch", fetchMock);
const client = createAgentApiClient("http://agent.local", {
getAccessToken: async () => "token",
getProjectId: async () => "project"
});
const loaded = await client.loadTaskExecutionSession(
"50000000-0000-4000-8000-000000000001",
"70000000-0000-4000-8000-000000000001",
"execution-session"
);
expect(loaded).toMatchObject({
sessionId: "execution-session",
title: "南桥管道爆管调查 · 执行记录",
purpose: "task_execution",
taskId: "50000000-0000-4000-8000-000000000001",
runStatus: "completed"
});
const url = new URL(String(fetchMock.mock.calls[0]?.[0]));
expect(url.pathname).toBe("/api/v1/task/50000000-0000-4000-8000-000000000001/execution-session");
expect(url.searchParams.get("run_id")).toBe("70000000-0000-4000-8000-000000000001");
expect(url.searchParams.get("session_id")).toBe("execution-session");
const headers = new Headers(fetchMock.mock.calls[0]?.[1]?.headers);
expect(headers.get("Authorization")).toBe("Bearer token");
expect(headers.get("X-Project-Id")).toBe("project");
});
it("creates a debug branch bound to an exact task execution history", async () => {
const fetchMock = vi.fn(async (..._args: Parameters<typeof fetch>) => Response.json({
session_id: "debug-session",
title: "南桥管道爆管调查 · 调试",
purpose: "task_collaboration",
task_id: "50000000-0000-4000-8000-000000000001",
parent_session_id: "execution-session",
created: true
}, { status: 201 }));
vi.stubGlobal("fetch", fetchMock);
const client = createAgentApiClient("http://agent.local", {
getAccessToken: async () => "token",
getProjectId: async () => "project"
});
await expect(client.createTaskExecutionDebugSession(
"50000000-0000-4000-8000-000000000001",
"70000000-0000-4000-8000-000000000001",
"execution-session"
)).resolves.toMatchObject({ session_id: "debug-session", purpose: "task_collaboration" });
const [url, init] = fetchMock.mock.calls[0] ?? [];
expect(new URL(String(url)).pathname).toBe("/api/v1/task/50000000-0000-4000-8000-000000000001/execution-session/debug");
expect(JSON.parse(String(init?.body))).toEqual({
run_id: "70000000-0000-4000-8000-000000000001",
session_id: "execution-session"
});
});
it("falls back when a candidate is not the agent service", async () => {
const fetchMock = vi
.fn()
@@ -79,10 +258,10 @@ describe("Agent API client sessions", () => {
});
expect(fetchMock).toHaveBeenNthCalledWith(
1,
"http://not-agent.local/api/v1/agent/chat/ui-registry",
"http://not-agent.local/api/v1/ui-registry",
undefined
);
expect(fetchMock).toHaveBeenNthCalledWith(2, "http://agent.local/api/v1/agent/chat/ui-registry", undefined);
expect(fetchMock).toHaveBeenNthCalledWith(2, "http://agent.local/api/v1/ui-registry", undefined);
});
it("sends title update payloads using backend field names", async () => {
@@ -94,7 +273,7 @@ describe("Agent API client sessions", () => {
});
expect(fetchMock).toHaveBeenCalledWith(
"http://agent.local/api/v1/agent/chat/session/session-1/title",
"http://agent.local/api/v1/session/session-1/title",
expect.objectContaining({
method: "PATCH",
body: JSON.stringify({
@@ -122,6 +301,20 @@ describe("Agent API client sessions", () => {
expect(headers.get("Content-Type")).toBe("application/json");
});
it("sends the authorized project context on Agent requests", async () => {
const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) =>
new Response(JSON.stringify({ sessions: [] }), { status: 200 })
);
vi.stubGlobal("fetch", fetchMock);
const getProjectId = vi.fn().mockResolvedValue("project-117");
await createAgentApiClient("http://agent.local", { getProjectId }).listSessions();
expect(getProjectId).toHaveBeenCalledOnce();
const headers = new Headers(fetchMock.mock.calls[0]?.[1]?.headers);
expect(headers.get("X-Project-Id")).toBe("project-117");
});
it("streams session events from the backend SSE endpoint", async () => {
vi.stubGlobal(
"fetch",
+355 -34
View File
@@ -1,7 +1,30 @@
import { createInteractionRequestApi, type InteractionRequestApi } from "./interaction-requests";
import { env } from "@/shared/config/env";
import type { AccessTokenProvider } from "@/shared/auth/keycloak-auth";
import { agentMessagePageSchema, type AgentMessagePage } from "./agent-messages";
import { AnswerViewStateApiError, readAnswerViewStateResponse, type AnswerViewStateRecord, type AnswerViewStateWrite } from "./answer-view-state";
export type AgentRunStatus = "running" | "completed" | "error" | "aborted";
export type AgentRunStatus = "running" | "completed" | "error" | "aborted" | "waiting_input";
export type AgentSessionPurpose = "ordinary_chat" | "task_execution" | "task_collaboration";
export type AgentEventTriggerContext = {
schema_version: "agent-trigger@1";
kind: "event";
trigger_id: string;
occurred_at: string;
source: "peripheral_sample";
subject_type: "work_order";
subject_id: string;
workflow: "water_quality_complaint";
payload: {
title: string;
summary: string;
location?: string | null;
priority: "low" | "normal" | "high" | "urgent";
scenario_code?: string | null;
origin: "system_data";
};
};
export type AgentPermissionReply = "once" | "always" | "reject";
@@ -17,10 +40,20 @@ export type AgentModelsResponse = {
models: AgentModelOption[];
};
export type AgentInputDelivery = "steer" | "queue";
export type AgentResponseInput = { id: string; text: string; delivery: AgentInputDelivery; status: "pending" | "delivered" | "cancelled" };
export class AgentResponseFinishedError extends Error {}
export class AgentSessionStreamError extends Error {
constructor(message: string, readonly status: number) { super(message); }
}
export type AgentTopic = { id: string; name: string; createdAt: string; updatedAt: string };
export type AgentChatSession = {
id?: string;
session_id: string;
title?: string;
topic_id?: string | null;
status?: string;
run_status?: AgentRunStatus;
is_streaming?: boolean;
@@ -29,45 +62,88 @@ export type AgentChatSession = {
updated_at?: number | string;
is_title_manually_edited?: boolean;
parent_session_id?: string;
created?: boolean;
event_duplicate?: boolean;
trigger_id?: string;
purpose?: AgentSessionPurpose;
task_id?: string;
};
export type AgentChatSessionSummary = {
trigger?: { subjectId: string; workflow: "water_quality_complaint"; occurredAt: string };
id: string;
title: string;
topicId?: string | null;
topicName?: string;
searchSnippet?: string;
createdAt: number;
updatedAt: number;
status?: string;
parentSessionId?: string;
isStreaming?: boolean;
runStatus?: AgentRunStatus;
needsInput?: boolean;
purpose: AgentSessionPurpose;
taskId?: string;
};
export type AgentRecentActivity = {
id: string;
kind: "alert" | "task" | "analysis" | "session";
title: string;
occurred_at: string;
summary?: string;
status?: string;
origin: "backend" | "agent" | "demo";
};
export type AgentPromptSuggestion = {
question: string;
activityId: string | null;
};
export type AgentMessagePagination = { hasMore: boolean; beforeCursor: string | null };
export type AgentSessionPage = { sessions: AgentChatSessionSummary[]; hasMore: boolean; nextCursor: string | null };
export type AgentHistoryMessagePage = { messages: unknown[]; messagePage: AgentMessagePagination };
export type AgentLoadedChatSession = AgentChatSessionSummary & {
sessionId: string;
isTitleManuallyEdited: boolean;
messages: unknown[];
messagePage?: AgentMessagePagination;
};
export type AgentSessionStreamDataEventType =
| "execution_plan"
| "final_answer"
| "token"
| "progress"
| "todo_update"
| "permission_request"
| "permission_response"
| "interaction_request"
| "question_request"
| "question_response"
| "tool_call"
| "frontend_action"
| "frontend_action_result"
| "answer_ui"
| "ui_envelope"
| "session_title"
| "done"
| "error"
| "auth_required";
| "auth_required"
| "credential_refresh_required"
| "credential_refreshed"
| "credential_refresh_failed"
| "agent_message"
| "user_input";
export type AgentSessionStreamEvent =
| {
type: "state";
executionPlans?: unknown[];
messagePage?: AgentMessagePagination;
sessionId: string;
messages: unknown[];
isStreaming: boolean;
@@ -79,14 +155,36 @@ export type AgentSessionStreamEvent =
data: Record<string, unknown>;
};
export type AgentApiClient = {
createSession: () => Promise<AgentChatSession>;
listSessions: () => Promise<AgentChatSessionSummary[]>;
loadSession: (sessionId: string) => Promise<AgentLoadedChatSession | null>;
export type AgentApiClient = InteractionRequestApi & {
getHealth: (signal: AbortSignal) => Promise<void>;
getAnswerViewState: (sessionId: string, messageId: string, blockId: string) => Promise<AnswerViewStateRecord>;
putAnswerViewState: (sessionId: string, state: AnswerViewStateWrite) => Promise<AnswerViewStateRecord>;
downloadFile: (path: string) => Promise<void>;
submitResponseInput: (sessionId: string, text: string, delivery: AgentInputDelivery, id: string) => Promise<AgentResponseInput>;
listResponseInputs: (sessionId: string) => Promise<AgentResponseInput[]>;
updateResponseInput: (sessionId: string, id: string, delivery: AgentInputDelivery) => Promise<AgentResponseInput>;
cancelResponseInput: (sessionId: string, id: string) => Promise<AgentResponseInput>;
listAgentMessages: (sessionId: string, options?: { cursor?: string; signal?: AbortSignal }) => Promise<AgentMessagePage>;
streamAgentMessages: (sessionId: string, options: { signal?: AbortSignal; onMessage: () => void }) => Promise<void>;
generatePromptSuggestions: (activities: AgentRecentActivity[], model: string, signal?: AbortSignal) => Promise<AgentPromptSuggestion[]>;
createSession: (options?: { triggerContext?: AgentEventTriggerContext; topicId?: string }) => Promise<AgentChatSession>;
listSessions: (options?: { purpose?: AgentSessionPurpose; taskId?: string }) => Promise<AgentChatSessionSummary[]>;
listSessionPage: (options?: { q?: string; cursor?: string; limit?: number; purpose?: AgentSessionPurpose; topicId?: string; includeCollaboration?: boolean; signal?: AbortSignal }) => Promise<AgentSessionPage>;
listTopics: () => Promise<AgentTopic[]>;
createTopic: (name: string) => Promise<AgentTopic>;
renameTopic: (id: string, name: string) => Promise<AgentTopic>;
deleteTopic: (id: string) => Promise<void>;
moveSessionToTopic: (sessionId: string, topicId: string | null) => Promise<void>;
loadOlderMessages: (sessionId: string, before: string, signal?: AbortSignal) => Promise<AgentHistoryMessagePage>;
createTaskCollaborationSession: (taskId: string) => Promise<AgentChatSession>;
createTaskExecutionDebugSession: (taskId: string, runId: string, sessionId: string) => Promise<AgentChatSession>;
loadTaskExecutionSession: (taskId: string, runId: string, sessionId: string, signal?: AbortSignal) => Promise<AgentLoadedChatSession | null>;
loadSession: (sessionId: string, options?: { messageLimit?: number; signal?: AbortSignal }) => Promise<AgentLoadedChatSession | null>;
streamSession: (
sessionId: string,
options: {
signal?: AbortSignal;
messageLimit?: number;
onEvent: (event: AgentSessionStreamEvent) => void;
}
) => Promise<void>;
@@ -105,21 +203,24 @@ export type AgentApiClient = {
requestId: string,
options: { sessionId: string; reply: AgentPermissionReply; message?: string }
) => Promise<void>;
getQuestionStatus: (sessionId: string, requestId: string) => Promise<{ status: "pending" | "answered" | "rejected" | "invalidated" }>;
replyQuestion: (
requestId: string,
options: { sessionId: string; answers: string[][] }
) => Promise<void>;
rejectQuestion: (requestId: string, options: { sessionId: string }) => Promise<void>;
refreshCredential: (sessionId: string, requestId: string) => Promise<void>;
abort: (sessionId: string) => Promise<void>;
};
export type AgentApiClientOptions = {
getAccessToken?: AccessTokenProvider;
getProjectId?: () => Promise<string | undefined>;
};
const AGENT_API_BASE_URLS = [env.TJWATER_AGENT_API_BASE_URL.replace(/\/$/, "")];
const AGENT_API_BASE_URLS = [env.TJWATER_AGENT_URL.replace(/\/$/, "")];
const CHAT_PATH = "/api/v1/agent/chat";
const API_PATH = "/api/v1";
export function createAgentApiClient(
baseUrls: string | string[] = AGENT_API_BASE_URLS,
@@ -137,7 +238,8 @@ export function createAgentApiClient(
setActiveBaseUrl,
path,
init,
options.getAccessToken
options.getAccessToken,
options.getProjectId
);
const requestJson = async <T,>(path: string, init?: RequestInit) => {
const response = await request(path, init);
@@ -150,21 +252,175 @@ export function createAgentApiClient(
return data as T;
};
let answerStateActor: string | undefined;
const checkedAnswerStateToken = options.getAccessToken ? async () => {
const token = await options.getAccessToken!();
const actor = answerStateTokenActor(token);
if (answerStateActor !== undefined && actor !== answerStateActor) {
throw new AnswerViewStateApiError("登录身份已变化,请刷新后继续。", 403, "ANSWER_VIEW_IDENTITY_CHANGED");
}
answerStateActor = actor;
return token;
} : undefined;
const answerStateRequest = async (path: string, init?: RequestInit) => {
const response = await fetchWithFallback(candidates, activeBaseUrl, setActiveBaseUrl, path, init,
checkedAnswerStateToken, options.getProjectId);
// An identity change while awaiting the network also invalidates the result.
await checkedAnswerStateToken?.();
return response;
};
return {
async createSession() {
...createInteractionRequestApi(answerStateRequest),
async getHealth(signal) {
const response = await fetchWithFallback(candidates, activeBaseUrl, setActiveBaseUrl, "/health", { signal, cache: "no-store" }, undefined, undefined, "");
if (!response.ok) throw new Error("Agent 服务暂不可用");
const data: unknown = await response.json();
if (!isRecord(data) || data.ok !== true || data.ready !== true) throw new Error("Agent 服务尚未就绪");
},
async getAnswerViewState(sessionId, messageId, blockId) {
const query = new URLSearchParams({ message_id: messageId, block_id: blockId });
return readAnswerViewStateResponse(await answerStateRequest(`/session/${encodeURIComponent(sessionId)}/ui-state?${query}`));
},
async putAnswerViewState(sessionId, state) {
return readAnswerViewStateResponse(await answerStateRequest(`/session/${encodeURIComponent(sessionId)}/ui-state`, {
method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(state)
}));
},
async downloadFile(path) {
const match = /^\/api\/v1(\/session\/[^/?#]+\/files\/mcp-[a-f0-9-]{36}\.(?:zip|xlsx))$/.exec(path);
if (!match) throw new Error("无效的会话文件地址");
const response = await request(match[1], { redirect: "error" });
if (!response.ok) throw new Error("文件不可用或当前账号无权下载");
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = path.split("/").at(-1) ?? "export.zip";
anchor.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
},
async submitResponseInput(sessionId, text, delivery, id) {
const response = await request("/responses", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ input: text, conversation: sessionId, stream: false, tjwater: { delivery, input_id: id } })
});
const data = await response.json();
if (response.status === 409 && data?.code === "RESPONSE_FINISHED") throw new AgentResponseFinishedError("当前回复已结束");
if (!response.ok) throw new Error(getResponseErrorMessage(data, response.status));
return data as AgentResponseInput;
},
async listResponseInputs(sessionId) {
const result = await requestJson<{ items: AgentResponseInput[] }>(`/session/${encodeURIComponent(sessionId)}/inputs`);
return result.items;
},
async updateResponseInput(sessionId, id, delivery) {
return requestJson<AgentResponseInput>(`/session/${encodeURIComponent(sessionId)}/inputs/${encodeURIComponent(id)}`, {
method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ delivery })
});
},
async cancelResponseInput(sessionId, id) {
return requestJson<AgentResponseInput>(`/session/${encodeURIComponent(sessionId)}/inputs/${encodeURIComponent(id)}`, {
method: "DELETE"
});
},
async generatePromptSuggestions(activities, model, signal) {
const result = await requestJson<unknown>("/suggestions", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ activities, model }),
signal,
});
if (!isRecord(result) || !Array.isArray(result.suggestions) || result.suggestions.length < 1 || result.suggestions.length > 3) {
throw new Error("Invalid Agent suggestions");
}
const ids = new Set(activities.map((item) => item.id));
const questions = new Set<string>();
return result.suggestions.map((item): AgentPromptSuggestion => {
if (!isRecord(item) || typeof item.question !== "string" || !item.question.trim() || item.question.length > 180 ||
(item.activity_id !== null && (typeof item.activity_id !== "string" || !ids.has(item.activity_id)))) {
throw new Error("Invalid Agent suggestion");
}
const question = item.question.trim();
if (questions.has(question)) throw new Error("Duplicate Agent suggestion");
questions.add(question);
return { question, activityId: item.activity_id as string | null };
});
},
async createSession(options) {
return requestJson<AgentChatSession>("/session", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({})
body: JSON.stringify({ trigger_context: options?.triggerContext, topic_id: options?.topicId })
});
},
async listSessions() {
const payload = await requestJson<{ sessions?: unknown[] }>("/sessions");
async listSessions(listOptions) {
const params = new URLSearchParams();
if (listOptions?.purpose) params.set("purpose", listOptions.purpose);
if (listOptions?.taskId) params.set("task_id", listOptions.taskId);
const payload = await requestJson<{ sessions?: unknown[] }>(
`/sessions${params.size ? `?${params.toString()}` : ""}`
);
return (payload.sessions ?? []).map(toSessionSummary).filter(isPresent).sort(compareSessionSummaries);
},
async listSessionPage(options) {
const params = new URLSearchParams({ purpose: options?.purpose ?? "ordinary_chat", limit: String(options?.limit ?? 30) });
if (options?.q) params.set("q", options.q);
if (options?.topicId) params.set("topic_id", options.topicId);
if (options?.includeCollaboration) params.set("include_collaboration", "true");
if (options?.cursor) params.set("cursor", options.cursor);
const payload = await requestJson<{ sessions?: unknown[]; has_more?: boolean; next_cursor?: string | null }>(
`/sessions?${params}`, { signal: options?.signal });
return { sessions: (payload.sessions ?? []).map(toSessionSummary).filter(isPresent),
hasMore: payload.has_more === true, nextCursor: typeof payload.next_cursor === "string" ? payload.next_cursor : null };
},
async listTopics() { return (await requestJson<{ topics: AgentTopic[] }>("/topics")).topics; },
async createTopic(name) { return requestJson<AgentTopic>("/topics", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name }) }); },
async renameTopic(id, name) { return requestJson<AgentTopic>(`/topics/${encodeURIComponent(id)}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name }) }); },
async deleteTopic(id) { await requestJson(`/topics/${encodeURIComponent(id)}`, { method: "DELETE" }); },
async moveSessionToTopic(sessionId, topicId) { await requestJson(`/session/${encodeURIComponent(sessionId)}/topic`, {
method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ topic_id: topicId }),
}); },
async loadOlderMessages(sessionId, before, signal) {
const query = new URLSearchParams({ limit: "40", before });
const payload = await requestJson<{ messages?: unknown[]; message_page?: unknown }>(
`/session/${encodeURIComponent(sessionId)}/messages?${query}`, { signal });
return { messages: payload.messages ?? [], messagePage: readMessagePagination(payload.message_page) ?? { hasMore: false, beforeCursor: null } };
},
async createTaskCollaborationSession(taskId) {
return requestJson<AgentChatSession>(
`/task/${encodeURIComponent(taskId)}/collaboration/session`,
{ method: "POST" }
);
},
async createTaskExecutionDebugSession(taskId, runId, sessionId) {
return requestJson<AgentChatSession>(
`/task/${encodeURIComponent(taskId)}/execution-session/debug`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ run_id: runId, session_id: sessionId })
}
);
},
async loadTaskExecutionSession(taskId, runId, sessionId, signal) {
const query = new URLSearchParams({ run_id: runId, session_id: sessionId });
const response = await request(
`/task/${encodeURIComponent(taskId)}/execution-session?${query}`,
{ signal }
);
const text = await response.text();
const data = text ? JSON.parse(text) : null;
if (response.status === 404) return null;
if (!response.ok) throw new Error(getResponseErrorMessage(data, response.status));
return toLoadedSession(data);
},
async getFrontendActionRegistry() {
return requestJson<unknown>("/frontend-action-registry");
},
@@ -177,8 +433,9 @@ export function createAgentApiClient(
});
},
async loadSession(sessionId) {
const response = await request(`/session/${encodeURIComponent(sessionId)}`);
async loadSession(sessionId, options) {
const query = options?.messageLimit ? `?message_limit=${options.messageLimit}` : "";
const response = await request(`/session/${encodeURIComponent(sessionId)}${query}`, { signal: options?.signal });
const text = await response.text();
const data = text ? JSON.parse(text) : null;
@@ -194,19 +451,35 @@ export function createAgentApiClient(
async streamSession(sessionId, options) {
const response = await request(
`/session/${encodeURIComponent(sessionId)}/stream`,
`/session/${encodeURIComponent(sessionId)}/stream${options.messageLimit ? `?message_limit=${options.messageLimit}` : ""}`,
{ signal: options.signal }
);
if (!response.ok) {
const text = await response.text();
const data = text ? JSON.parse(text) : null;
throw new Error(getResponseErrorMessage(data, response.status));
throw new AgentSessionStreamError(getResponseErrorMessage(data, response.status), response.status);
}
await readSessionSseStream(response, options.onEvent);
},
async listAgentMessages(sessionId, options) {
const query = new URLSearchParams({ limit: "50" });
if (options?.cursor) query.set("cursor", options.cursor);
return agentMessagePageSchema.parse(await requestJson<unknown>(
`/session/${encodeURIComponent(sessionId)}/agent-messages?${query}`, { signal: options?.signal }
));
},
async streamAgentMessages(sessionId, options) {
const response = await request(`/session/${encodeURIComponent(sessionId)}/agent-messages/stream`, { signal: options.signal });
if (!response.ok) throw new Error(getResponseErrorMessage(await response.json(), response.status));
await readSessionSseStream(response, (event) => {
if (event.type === "agent_message" && event.sessionId === sessionId) options.onMessage();
});
},
async updateSessionTitle(sessionId, title, options) {
const normalizedTitle = title.trim();
if (!normalizedTitle) {
@@ -261,6 +534,11 @@ export function createAgentApiClient(
});
},
async getQuestionStatus(sessionId, requestId) {
const value = await requestJson<{ status: "pending" | "answered" | "rejected" | "invalidated" }>(`/session/${encodeURIComponent(sessionId)}/questions/${encodeURIComponent(requestId)}`, { cache: "no-store" });
if (!["pending", "answered", "rejected", "invalidated"].includes(value.status)) throw new Error("问题状态核对失败");
return value;
},
async replyQuestion(requestId, options) {
await requestJson<unknown>(`/question/${encodeURIComponent(requestId)}/reply`, {
method: "POST",
@@ -282,6 +560,13 @@ export function createAgentApiClient(
});
},
async refreshCredential(sessionId, requestId) {
await options.getAccessToken?.(true);
await requestJson(`/session/${encodeURIComponent(sessionId)}/credentials`, {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ request_id: requestId })
});
},
async abort(sessionId) {
await requestJson<unknown>("/abort", {
method: "POST",
@@ -298,22 +583,24 @@ async function fetchWithFallback(
setActiveBaseUrl: (baseUrl: string) => void,
path: string,
init?: RequestInit,
getAccessToken?: AccessTokenProvider
getAccessToken?: AccessTokenProvider,
getProjectId?: () => Promise<string | undefined>,
prefix = API_PATH
) {
const orderedBaseUrls = [activeBaseUrl, ...baseUrls.filter((item) => item !== activeBaseUrl)];
let lastError: unknown;
let lastResponse: Response | null = null;
const accessToken = await getAccessToken?.();
const requestInit = accessToken
? {
...init,
headers: withBearerToken(init?.headers, accessToken)
}
: init;
const projectId = await getProjectId?.();
const hasContextHeaders = Boolean(accessToken || projectId);
const headers = hasContextHeaders ? new Headers(init?.headers) : undefined;
if (accessToken) headers?.set("Authorization", `Bearer ${accessToken}`);
if (projectId) headers?.set("X-Project-Id", projectId);
const requestInit = hasContextHeaders ? { ...init, headers } : init;
for (const baseUrl of orderedBaseUrls) {
try {
const response = await fetch(`${baseUrl}${CHAT_PATH}${path}`, requestInit);
const response = await fetch(`${baseUrl}${prefix}${path}`, requestInit);
if (response.ok) {
setActiveBaseUrl(baseUrl);
return response;
@@ -337,12 +624,6 @@ async function fetchWithFallback(
throw lastError instanceof Error ? lastError : new Error("Agent API unavailable");
}
function withBearerToken(headersInit: HeadersInit | undefined, accessToken: string) {
const headers = new Headers(headersInit);
headers.set("Authorization", `Bearer ${accessToken}`);
return headers;
}
function shouldFallbackOnHttpStatus(status: number) {
return status === 404 || status === 405 || status === 502 || status === 503 || status === 504;
}
@@ -408,11 +689,15 @@ function normalizeTitle(value: unknown) {
}
function readRunStatus(value: unknown): AgentRunStatus | undefined {
return value === "running" || value === "completed" || value === "error" || value === "aborted"
return value === "waiting_input" || value === "running" || value === "completed" || value === "error" || value === "aborted"
? value
: undefined;
}
function readSessionPurpose(value: unknown): AgentSessionPurpose {
return value === "task_execution" || value === "task_collaboration" ? value : "ordinary_chat";
}
function toSessionSummary(value: unknown): AgentChatSessionSummary | null {
if (!isRecord(value)) {
return null;
@@ -426,12 +711,22 @@ function toSessionSummary(value: unknown): AgentChatSessionSummary | null {
return {
id,
title: normalizeTitle(value.title),
topicId: typeof value.topic_id === "string" ? value.topic_id : null,
topicName: typeof value.topic_name === "string" ? value.topic_name : undefined,
searchSnippet: typeof value.search_snippet === "string" ? value.search_snippet : undefined,
createdAt: toMillis(value.created_at),
updatedAt: toMillis(value.updated_at),
status: typeof value.status === "string" ? value.status : undefined,
parentSessionId: typeof value.parent_session_id === "string" ? value.parent_session_id : undefined,
isStreaming: typeof value.is_streaming === "boolean" ? value.is_streaming : undefined,
runStatus: readRunStatus(value.run_status)
runStatus: readRunStatus(value.run_status),
purpose: readSessionPurpose(value.purpose),
taskId: typeof value.task_id === "string" ? value.task_id : undefined,
trigger: isRecord(value.trigger) && value.trigger.workflow === "water_quality_complaint" &&
typeof value.trigger.subject_id === "string" && typeof value.trigger.occurred_at === "string" &&
Number.isFinite(Date.parse(value.trigger.occurred_at))
? { subjectId: value.trigger.subject_id, workflow: "water_quality_complaint", occurredAt: value.trigger.occurred_at }
: undefined
};
}
@@ -446,7 +741,8 @@ function toLoadedSession(value: unknown): AgentLoadedChatSession {
sessionId: typeof value.session_id === "string" ? value.session_id : summary.id,
isTitleManuallyEdited:
typeof value.is_title_manually_edited === "boolean" ? value.is_title_manually_edited : false,
messages: Array.isArray(value.messages) ? value.messages : []
messages: Array.isArray(value.messages) ? value.messages : [],
messagePage: readMessagePagination(value.message_page)
};
}
@@ -511,6 +807,8 @@ function emitSessionSseEvent(
const sessionId = typeof data.session_id === "string" ? data.session_id : "";
onEvent({
type: "state",
executionPlans: Array.isArray(data.execution_plans) ? data.execution_plans : undefined,
messagePage: readMessagePagination(data.message_page),
sessionId,
messages: Array.isArray(data.messages) ? data.messages : [],
isStreaming: data.is_streaming === true,
@@ -532,21 +830,30 @@ function emitSessionSseEvent(
function isSessionStreamDataEventType(value: string): value is AgentSessionStreamDataEventType {
return (
value === "final_answer" ||
value === "token" ||
value === "progress" ||
value === "todo_update" ||
value === "execution_plan" ||
value === "permission_request" ||
value === "permission_response" ||
value === "interaction_request" ||
value === "question_request" ||
value === "question_response" ||
value === "tool_call" ||
value === "frontend_action" ||
value === "frontend_action_result" ||
value === "answer_ui" ||
value === "ui_envelope" ||
value === "session_title" ||
value === "done" ||
value === "error" ||
value === "credential_refresh_required" ||
value === "credential_refreshed" ||
value === "credential_refresh_failed" ||
value === "auth_required"
|| value === "agent_message"
|| value === "user_input"
);
}
@@ -563,3 +870,17 @@ function compareSessionSummaries(left: AgentChatSessionSummary, right: AgentChat
return right.id.localeCompare(left.id);
}
function readMessagePagination(value: unknown): AgentMessagePagination | undefined {
if (!isRecord(value)) return undefined;
return { hasMore: value.has_more === true, beforeCursor: typeof value.before_cursor === "string" ? value.before_cursor : null };
}
function answerStateTokenActor(token: string | null): string {
if (!token) return "development-context";
try {
const payload: unknown = JSON.parse(atob(token.split(".")[1].replaceAll("-", "+").replaceAll("_", "/")));
if (isRecord(payload) && typeof payload.sub === "string") return JSON.stringify([payload.iss, payload.sub]);
} catch { /* Non-JWT development credentials use the enclosing workbench owner. */ }
return "development-context";
}
@@ -0,0 +1,13 @@
import { expect, it, vi } from "vitest";
import { createInteractionRequestApi, interactionRequestSchema } from "./interaction-requests";
it("rejects malformed host requests and scopes escaped URLs with no-store reads", async () => {
expect(interactionRequestSchema.safeParse({ version: "agent-interaction-request@1", questions: [] }).success).toBe(false);
const request = vi.fn(async () => new Response(JSON.stringify({ items: [] }), { status: 200 }));
const api = createInteractionRequestApi(request);
await expect(api.listInteractionRequests("session/other")).resolves.toEqual({ items: [] });
expect(request).toHaveBeenCalledWith("/session/session%2Fother/interactions", { cache: "no-store" });
});
it("keeps denied status available to purge the scope even with an empty response", async () => {
const api = createInteractionRequestApi(async () => new Response(null, { status: 403 }));
await expect(api.listInteractionRequests("session")).rejects.toMatchObject({ status: 403 });
});
@@ -0,0 +1,51 @@
import { z } from "zod";
const id = z.string().min(1).max(128);
const revision = z.number().int().nonnegative();
const option = z.object({ id, label: z.string().max(200) }).strict();
export const interactionAnswerSchema = z.object({ question_id: id, selected_option_ids: z.array(id).max(12), custom_text: z.string().max(2000) }).strict();
export const interactionRequestSchema = z.object({
version: z.literal("agent-interaction-request@1"), interaction_id: id, message_id: id, turn_id: id, call_id: id,
questions: z.array(z.object({ question_id: id, title: z.string().max(200), body: z.string().max(2000), options: z.array(option).max(12), mode: z.enum(["single", "multiple"]), allow_custom: z.boolean(), required: z.boolean() }).strict()).min(1).max(3),
status: z.enum(["pending", "answered", "skipped", "cancelled", "invalidated"]), revision, draft_revision: revision,
draft: z.array(interactionAnswerSchema).max(3), answers: z.array(interactionAnswerSchema.extend({ selected_options: z.array(option) }).strict()).optional(),
created_at: z.string(), resolved_at: z.string().optional(),
delivery: z.object({ native_message_id: id, revision, status: z.enum(["queued", "dispatching", "delivered", "blocked", "cancelled"]), error_code: z.string().optional(), response_id: z.string().optional() }).strict().optional(),
}).strict();
export type InteractionRequest = z.infer<typeof interactionRequestSchema>;
export const canReplaceInteractionRequest = (next: InteractionRequest, current: InteractionRequest) =>
(next.delivery?.revision ?? -1) >= (current.delivery?.revision ?? -1)
&& (next.revision > current.revision || (next.revision === current.revision && next.draft_revision >= current.draft_revision));
export function readInteractionReply(data: unknown, messageId: string): InteractionRequest | undefined {
const parsed = interactionRequestSchema.safeParse(data);
return parsed.success && ["answered", "skipped"].includes(parsed.data.status)
&& parsed.data.delivery?.native_message_id === messageId ? parsed.data : undefined;
}
export type InteractionAnswer = z.infer<typeof interactionAnswerSchema>;
export type InteractionWrite = { version: "agent-interaction-request@1"; request_id: string; expected_revision: number; answers?: InteractionAnswer[] };
export type InteractionDraftWrite = { version: "agent-interaction-request@1"; request_id: string; expected_draft_revision: number; answers: InteractionAnswer[] };
export class InteractionRequestApiError extends Error {
constructor(message: string, readonly status: number, readonly current?: InteractionRequest) { super(message); }
}
export function createInteractionRequestApi(request: (path: string, init?: RequestInit) => Promise<Response>) {
const path = (sessionId: string, interactionId?: string) => `/session/${encodeURIComponent(sessionId)}/interactions${interactionId ? `/${encodeURIComponent(interactionId)}` : ""}`;
const read = async (response: Response) => {
const value: unknown = await response.json().catch(() => {
throw new InteractionRequestApiError("提问状态暂不可用", response.status);
});
if (!response.ok) {
const error = z.object({ detail: z.string().optional(), current: z.unknown().optional() }).passthrough().safeParse(value);
const current = interactionRequestSchema.safeParse(error.success ? error.data.current : null);
throw new InteractionRequestApiError(error.success ? error.data.detail ?? "提问状态暂不可用" : "提问状态暂不可用", response.status, current.success ? current.data : undefined);
}
return value;
};
return {
async listInteractionRequests(sessionId: string) { return z.object({ items: z.array(interactionRequestSchema), next_cursor: z.string().optional() }).strict().parse(await read(await request(path(sessionId), { cache: "no-store" }))); },
async getInteractionRequest(sessionId: string, interactionId: string) { return interactionRequestSchema.parse(await read(await request(path(sessionId, interactionId), { cache: "no-store" }))); },
async writeInteractionRequest(sessionId: string, interactionId: string, action: "draft" | "reply" | "skip" | "cancel" | "resume", body: InteractionWrite | InteractionDraftWrite) {
return interactionRequestSchema.parse(await read(await request(`${path(sessionId, interactionId)}/${action}`, { method: action === "draft" ? "PUT" : "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) })));
},
};
}
export type InteractionRequestApi = ReturnType<typeof createInteractionRequestApi>;
@@ -0,0 +1,65 @@
import { describe, expect, it } from "vitest";
import type { UIMessage, UIMessageChunk } from "ai";
import { createResponseRequest, responsesToUiStream } from "./responses-transport";
const bytes = (events: Record<string, unknown>[], partial = false) => {
const text = events.map((event) => `event: ${String(event.type)}\r\ndata: ${JSON.stringify(event)}\r\n\r\n`).join("");
const encoded = new TextEncoder().encode(text);
return new ReadableStream<Uint8Array>({ start(controller) {
if (partial) for (let i = 0; i < encoded.length; i += 7) controller.enqueue(encoded.slice(i, i + 7));
else controller.enqueue(encoded);
controller.close();
} });
};
const collect = async (stream: ReadableStream<UIMessageChunk>) => {
const parts: UIMessageChunk[] = [];
const reader = stream.getReader();
while (true) { const next = await reader.read(); if (next.done) break; parts.push(next.value); }
return parts;
};
const events = (): Record<string, unknown>[] => [
{ type: "response.created", sequence_number: 0, response: { id: "resp_1" } },
{ type: "response.output_item.added", sequence_number: 1, item: { type: "message", id: "msg_1", role: "assistant", content: [] } },
{ type: "response.content_part.added", sequence_number: 2, item_id: "msg_1", content_index: 0, part: { type: "output_text", text: "" } },
{ type: "response.output_text.delta", sequence_number: 3, item_id: "msg_1", content_index: 0, delta: "压力待核验" },
{ type: "tjwater.permission_request", sequence_number: 4, response_id: "resp_1", data: { request_id: "permission_1" } },
{ type: "response.output_text.done", sequence_number: 5, item_id: "msg_1", content_index: 0, text: "压力待核验" },
{ type: "response.completed", sequence_number: 6, response: { id: "resp_1", status: "completed" } },
];
describe("Responses transport", () => {
it("sends only the latest user input and keeps business options explicit", () => {
const messages = [{ id: "old", role: "assistant", parts: [{ type: "text", text: "旧回答" }] }, { id: "new", role: "user", parts: [{ type: "text", text: "继续核查" }] }] as UIMessage[];
expect(createResponseRequest(messages, { conversation: "owned", approvalMode: "always" })).toEqual({
input: [{ role: "user", content: [{ type: "input_text", text: "继续核查" }] }], stream: true, conversation: "owned",
tjwater: { client_message_id: "new", approval_mode: "always", capabilities: [] },
});
});
it("decodes split UTF-8 and CRLF while retaining approval events", async () => {
expect(await collect(responsesToUiStream(bytes(events(), true)))).toEqual([
{ type: "start", messageId: "msg_1" }, { type: "text-start", id: "msg_1:0" },
{ type: "text-delta", id: "msg_1:0", delta: "压力待核验" },
{ type: "data-permission_request", data: { request_id: "permission_1" } },
{ type: "text-end", id: "msg_1:0" }, { type: "finish", finishReason: "stop" },
]);
});
it("reports premature disconnects, mismatched owners and invalid event order", async () => {
await expect(collect(responsesToUiStream(bytes(events().slice(0, 5))))).rejects.toThrow("断开");
const wrong = events(); wrong[4] = { ...wrong[4], response_id: "other" };
await expect(collect(responsesToUiStream(bytes(wrong)))).rejects.toThrow("归属");
await expect(collect(responsesToUiStream(bytes([events()[0]!, events()[3]!])))).rejects.toThrow();
});
it("turns failed and cancelled Responses into visible errors", async () => {
const failed = events();
failed[6] = { type: "response.failed", sequence_number: 6, response: { id: "resp_1", error: { message: "数据源不可用" } } };
expect((await collect(responsesToUiStream(bytes(failed)))).at(-2)).toEqual({ type: "error", errorText: "数据源不可用" });
});
});
it("binds a saved interaction continuation to the owning conversation", () => {
const request = createResponseRequest([{ id: "continuation", role: "user", parts: [{ type: "text", text: "继续处理已保存回答" }] }], {
conversation: "original-session", interactionId: "saved-interaction", capabilities: ["host-question@1"],
});
expect(request.conversation).toBe("original-session");
expect(request.tjwater).toMatchObject({ interaction_id: "saved-interaction", capabilities: ["host-question@1"] });
});
@@ -0,0 +1,112 @@
import { HttpChatTransport, type UIMessage, type UIMessageChunk } from "ai";
const record = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value);
export class AgentStreamDisconnectedError extends Error {}
export function createResponseRequest(messages: UIMessage[], options: {
conversation?: string; model?: string; approvalMode?: string; capabilities?: string[];
interactionId?: string; triggerContext?: unknown; taskContext?: unknown; topicId?: string;
}) {
const latest = [...messages].reverse().find((message) => message.role === "user");
const text = latest?.parts.filter((part) => part.type === "text").map((part) => part.text).join("\n").trim();
if (!text) throw new Error("Responses 请求需要用户文本");
return {
input: [{ role: "user", content: [{ type: "input_text", text }] }], stream: true,
...(options.model ? { model: options.model } : {}),
...(options.conversation ? { conversation: options.conversation } : {}),
tjwater: { ...(options.interactionId ? { interaction_id: options.interactionId } : {}), ...(options.topicId ? { topic_id: options.topicId } : {}), ...(latest?.id ? { client_message_id: latest.id } : {}), approval_mode: options.approvalMode ?? "request", capabilities: options.capabilities ?? [],
...(options.triggerContext ? { trigger_context: options.triggerContext } : {}),
...(options.taskContext ? { task_context: options.taskContext } : {}),
},
};
}
/** Keep UI rendering independent of the public Responses wire protocol. */
export function responsesToUiStream(stream: ReadableStream<Uint8Array>): ReadableStream<UIMessageChunk> {
const decoder = new TextDecoder();
let buffer = "";
let responseId: string | undefined;
let messageStarted = false;
let messageId: string | undefined;
let terminal = false;
let sequence = -1;
const texts = new Set<string>();
const parse = (block: string, controller: TransformStreamDefaultController<UIMessageChunk>) => {
if (block.length > 1024 * 1024) throw new Error("Responses 单个流事件过大");
const lines = block.split(/\r?\n/);
const data = lines.filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
if (!data) return;
if (terminal) throw new Error("Responses 流在结束后仍返回事件");
const value: unknown = JSON.parse(data);
if (!record(value) || typeof value.type !== "string" || !Number.isInteger(value.sequence_number) || (value.sequence_number as number) <= sequence) throw new Error("Responses 流事件格式不正确");
sequence = value.sequence_number as number;
const named = lines.find((line) => line.startsWith("event:"))?.slice(6).trim();
if (named && named !== value.type) throw new Error("Responses 流事件类型不一致");
if (value.type === "response.created") {
if (responseId || !record(value.response) || typeof value.response.id !== "string") throw new Error("Responses 创建事件不正确");
responseId = value.response.id;
if (record(value.response.conversation) && typeof value.response.conversation.id === "string") {
controller.enqueue({ type: "data-session_created", data: { session_id: value.response.conversation.id }, transient: true });
}
return;
}
if (!responseId) throw new Error("Responses 流缺少创建事件");
const textId = () => {
if (value.item_id !== messageId || !Number.isInteger(value.content_index) || (value.content_index as number) < 0) throw new Error("Responses 文本归属不正确");
return `${messageId}:${String(value.content_index)}`;
};
if (value.type === "response.output_item.added" && record(value.item) && value.item.type === "message") {
if (messageStarted || typeof value.item.id !== "string") throw new Error("Responses 回答消息不正确");
messageStarted = true;
messageId = value.item.id;
controller.enqueue({ type: "start", messageId: value.item.id });
} else if (value.type === "response.content_part.added" && record(value.part) && value.part.type === "output_text") {
if (!messageStarted) throw new Error("Responses 流缺少回答消息");
texts.add(textId());
controller.enqueue({ type: "text-start", id: textId() });
} else if (value.type === "response.output_text.delta") {
if (!texts.has(textId()) || typeof value.delta !== "string") throw new Error("Responses 文本事件顺序不正确");
controller.enqueue({ type: "text-delta", id: textId(), delta: value.delta });
} else if (value.type === "response.output_text.done") {
if (!texts.delete(textId())) throw new Error("Responses 文本结束事件不正确");
controller.enqueue({ type: "text-end", id: textId() });
} else if (value.type.startsWith("tjwater.")) {
if (value.response_id !== responseId || !/^tjwater\.[a-z][a-z0-9_]*$/.test(value.type)) throw new Error("业务流事件归属不正确");
controller.enqueue({ type: `data-${value.type.slice(8)}`, data: value.data,
...(typeof value.id === "string" ? { id: value.id } : {}), ...(value.transient === true ? { transient: true } : {}) } as UIMessageChunk);
} else if (["response.completed", "response.failed", "response.incomplete"].includes(value.type)) {
if (!record(value.response) || value.response.id !== responseId || texts.size) throw new Error("Responses 结束事件不正确");
terminal = true;
if (!messageStarted) controller.enqueue({ type: "start", messageId: responseId });
if (value.type !== "response.completed") {
const failure = value.response.error;
controller.enqueue({ type: "error", errorText: record(failure) && typeof failure.message === "string" ? failure.message : "请求未完成或已中止" });
}
controller.enqueue({ type: "finish", finishReason: value.type === "response.completed" ? "stop" : "error" });
}
};
const flushBlocks = (controller: TransformStreamDefaultController<UIMessageChunk>) => {
let match: RegExpExecArray | null;
while ((match = /\r?\n\r?\n/.exec(buffer))) {
const block = buffer.slice(0, match.index);
buffer = buffer.slice(match.index + match[0].length);
parse(block, controller);
}
if (buffer.length > 1024 * 1024) throw new Error("Responses 单个流事件过大");
};
return stream.pipeThrough(new TransformStream<Uint8Array, UIMessageChunk>({
transform(chunk, controller) { buffer += decoder.decode(chunk, { stream: true }); flushBlocks(controller); },
flush(controller) {
buffer += decoder.decode();
flushBlocks(controller);
if (buffer.trim()) parse(buffer, controller);
if (!terminal) throw new AgentStreamDisconnectedError("Responses 流在完成前断开,正在恢复会话连接");
},
}));
}
export class ResponsesChatTransport<Message extends UIMessage> extends HttpChatTransport<Message> {
protected processResponseStream(stream: ReadableStream<Uint8Array>) {
return responsesToUiStream(stream);
}
}
+18 -3
View File
@@ -1,8 +1,21 @@
import { describe, expect, it, vi } from "vitest";
import type { AgentApiClient } from "./client";
import { fetchAgentBootstrap, fetchAgentSessions } from "./swr";
import { fetchAgentBootstrap, fetchAgentSessions, resolveAgentModelSelection } from "./swr";
describe("Agent API SWR helpers", () => {
it("preserves valid model choices and resolves removed choices against the current catalog", () => {
const models = [
{ id: "primary/fast", label: "快速", description: "Primary", icon: "bolt" as const },
{ id: "secondary/expert", label: "专家", description: "Secondary", icon: "sparkle" as const }
];
const catalog = { defaultModel: "secondary/expert", models };
expect(resolveAgentModelSelection(catalog, "primary/fast")).toBe("primary/fast");
expect(resolveAgentModelSelection(catalog, "retired/fast")).toBe("secondary/expert");
expect(resolveAgentModelSelection(catalog)).toBe("secondary/expert");
expect(resolveAgentModelSelection({ ...catalog, defaultModel: "missing/model" }, "retired/fast")).toBe("primary/fast");
expect(resolveAgentModelSelection({ defaultModel: "primary/fast", models: [] }, "primary/fast")).toBe("");
});
it("loads bootstrap data with a normalized UI registry", async () => {
const client = {
getUiRegistry: vi.fn(async () => ({
@@ -35,13 +48,15 @@ describe("Agent API SWR helpers", () => {
id: "session-1",
title: "会话",
createdAt: 1,
updatedAt: 2
updatedAt: 2,
purpose: "ordinary_chat" as const
}
];
const client = {
listSessions: vi.fn(async () => sessions)
} as Pick<AgentApiClient, "listSessions"> as AgentApiClient;
await expect(fetchAgentSessions(client)).resolves.toBe(sessions);
await expect(fetchAgentSessions(client)).resolves.toEqual(sessions);
expect(client.listSessions).toHaveBeenCalledWith({ purpose: "ordinary_chat" });
});
});
+11 -2
View File
@@ -1,7 +1,8 @@
import type {
AgentApiClient,
AgentChatSessionSummary,
AgentModelOption
AgentModelOption,
AgentModelsResponse
} from "./client";
import { parseUiRegistry, type UIRegistry } from "../ui-envelope";
import { parseFrontendActionRegistry, type FrontendActionRegistry } from "../frontend-action";
@@ -16,6 +17,12 @@ export type AgentBootstrapData = {
defaultModel: string;
};
export function resolveAgentModelSelection(catalog: AgentModelsResponse, current = ""): string {
if (catalog.models.some((model) => model.id === current)) return current;
if (catalog.models.some((model) => model.id === catalog.defaultModel)) return catalog.defaultModel;
return catalog.models[0]?.id ?? "";
}
export async function fetchAgentBootstrap(client: AgentApiClient): Promise<AgentBootstrapData> {
const [rawRegistry, rawFrontendActionRegistry, modelsResponse] = await Promise.all([
client.getUiRegistry(),
@@ -32,5 +39,7 @@ export async function fetchAgentBootstrap(client: AgentApiClient): Promise<Agent
}
export async function fetchAgentSessions(client: AgentApiClient): Promise<AgentChatSessionSummary[]> {
return client.listSessions();
const sessions = await client.listSessions({ purpose: "ordinary_chat" });
// Keep the product boundary even while an older Agent service is rolling forward.
return sessions.filter((session) => session.purpose === "ordinary_chat");
}

Some files were not shown because too many files have changed in this diff Show More