Compare commits

..
Author SHA1 Message Date
jiang 7a304a91a8 feat(workbench): dock task and chart workspaces
Generic Container CI/CD / test-build-publish (push) Successful in 1m13s
Frontend CI/CD / build-test-publish-and-deploy (push) Successful in 1m14s
2026-11-12 11:42:25 +08:00
jiang 33f0b90a7d fix: preserve SCADA comparison device coverage 2026-11-12 10:38:55 +08:00
jiang a617aa95e9 fix(workbench): stabilize investigation presentation rendering
Keep investigation graphs stable during updates, defer expensive chart rendering, and prevent stale results when switching tasks. Adopt reference annotations and consolidate frontend documentation.
2026-11-11 19:10:41 +08:00
63 changed files with 2163 additions and 922 deletions
+5 -3
View File
@@ -6,13 +6,15 @@ Next TJWater 是供水管网 WebGIS Agent 工作台的前端项目。界面以
样式规范统一见 [样式设计指南](docs/style-design-guide.md),Agent 功能与报告交互见 [交互设计](docs/agent-chat-ui-design.md),形象、配色与状态动画见 [Persona 设计](docs/agent-persona-design.md)。 样式规范统一见 [样式设计指南](docs/style-design-guide.md),Agent 功能与报告交互见 [交互设计](docs/agent-chat-ui-design.md),形象、配色与状态动画见 [Persona 设计](docs/agent-persona-design.md)。
完整索引、历史归档与合并去向见 [文档目录](docs/README.md)。
## 主要功能 ## 主要功能
- 供水管网地图、业务图层和设备状态展示 - 供水管网地图、业务图层和设备状态展示
- 地图缩放、测量、绘制、图层控制和视图导出 - 地图缩放、测量、绘制、图层控制和视图导出
- 异常工况列表、详情分析和调度任务跟踪 - 异常工况列表、详情分析和调度任务跟踪
- Agent 流式对话、推荐问题、会话管理和权限批准 - Agent 流式对话、推荐问题、会话管理和权限批准
- 经过 Schema 校验的 UI Envelope 和前端动作执行 - 经过 Schema 校验的 `answer-ui@1` 内容与受控前端动作,兼容旧 UI Envelope
- 运行时配置注入、MSW 本地模拟和开发面板 - 运行时配置注入、MSW 本地模拟和开发面板
Dev 的“调查测试”提供统一 command 格式的案例、JSONL 校验与本地预览,无需先选择调查;选中调查后还可检查实时地图、图表和报告界面块。操作说明与验证边界见 [调查展示 Dev 测试](docs/investigation-dev-tools.md)。 Dev 的“调查测试”提供统一 command 格式的案例、JSONL 校验与本地预览,无需先选择调查;选中调查后还可检查实时地图、图表和报告界面块。操作说明与验证边界见 [调查展示 Dev 测试](docs/investigation-dev-tools.md)。
@@ -52,7 +54,7 @@ Agent 服务默认地址为 `http://127.0.0.1:8787`。需要完整对话能力
| `TJWATER_GEOSERVER_WORKSPACE` | `tjwater_next` | GeoServer 工作区 | | `TJWATER_GEOSERVER_WORKSPACE` | `tjwater_next` | GeoServer 工作区 |
| `TJWATER_SERVER_API_BASE_URL` | `http://127.0.0.1:8000` | 浏览器访问的 TJWater 后端 API 地址 | | `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_AGENT_URL` | `http://127.0.0.1:8787` | 浏览器访问的 Agent API 地址 |
| `TJWATER_WORKBENCH_RUNTIME_MODE` | `auto` | 工作台时间模式:工况始终使用 mock,预约工单只读取后端投影;`auto` 和 `backend` 使用当天日期;`demo` 与 `history` 定位到最近一个有后端预约工单的日期,并在同一天生成 mock 工况,其中 `demo` 标记为演示时间。分析成果和后端任务状态不作为工况或日期依据 | | `TJWATER_WORKBENCH_RUNTIME_MODE` | `auto` | 前端定时工况的日期与演示模式;定时工况仍由 mock 生成。`auto` 和 `backend` 使用当天日期,`demo` 和 `history` 优先使用兼容运行态中的工单日期,`demo` 标记演示时间;不决定 Server 持久任务的调度或执行状态 |
| `TJWATER_PERIPHERAL_SAMPLE_API_BASE_URL` | `/peripheral` | 外围工单服务地址;生产推荐使用同源代理路径,留空时不发起连接 | | `TJWATER_PERIPHERAL_SAMPLE_API_BASE_URL` | `/peripheral` | 外围工单服务地址;生产推荐使用同源代理路径,留空时不发起连接 |
| `TJWATER_PERIPHERAL_SAMPLE_TIME_MODE` | `demo` | 历史回放默认时间模式:`demo` 使用固定有数据窗口,`recent` 使用最近时段 | | `TJWATER_PERIPHERAL_SAMPLE_TIME_MODE` | `demo` | 历史回放默认时间模式:`demo` 使用固定有数据窗口,`recent` 使用最近时段 |
| `TJWATER_PERIPHERAL_SAMPLE_DEMO_START` | `2026-09-17T00:00:00Z` | 演示历史窗口开始时间(UTC、带时区) | | `TJWATER_PERIPHERAL_SAMPLE_DEMO_START` | `2026-09-17T00:00:00Z` | 演示历史窗口开始时间(UTC、带时区) |
@@ -135,7 +137,7 @@ src/
## 构建说明 ## 构建说明
调查任务支持样板反馈的人工复核草稿。在“外围样板”显式导入反馈证据后,可读取同一来源的完整反馈集合、确认并保存新修订;已保存草稿也可从“调查任务”的历史草稿中再次打开,不依赖外围服务在线。页面区分待重分析、冲突证据及前后修订,不代表已经重新计算。接口与存储边界见 [复核修订说明](../next-tjwater-server/docs/feedback-review-revisions.md)。 调查任务以 Server 保存的轮次、报告、证据和审批动作展示进展。人工补充事实与外围工单反馈按各自契约触发续调,不沿用旧“反馈导入后保存复核草稿”的页面说明。当前边界见 [调查轮次与协作](../next-tjwater-server/docs/operational-tasks.md#调查轮次与协作边界)。
“分析成果”面板只读取当前项目 BizDB 中已持久化的分析历史,不启动分析任务。外围系统面板管理业务工单,新建工单来源为 `system_data`;显式演练数据保留 `synthetic` 标记,历史监测回放仍为只读。部署所需表和边界见 Server 的[外围系统说明](../next-tjwater-server/docs/peripheral-sample.md)。 “分析成果”面板只读取当前项目 BizDB 中已持久化的分析历史,不启动分析任务。外围系统面板管理业务工单,新建工单来源为 `system_data`;显式演练数据保留 `synthetic` 标记,历史监测回放仍为只读。部署所需表和边界见 Server 的[外围系统说明](../next-tjwater-server/docs/peripheral-sample.md)。
+31
View File
@@ -0,0 +1,31 @@
# 供水前端文档目录
当前功能与交互以本目录的维护文档和源码为准,环境、命令与发布入口见 [仓库 README](../README.md),开发边界见 [AGENTS.md](../AGENTS.md)。整理日期:2026-11-10。
## 当前维护文档
| 主题 | 维护入口 |
| --- | --- |
| 样式、组件、材质、字体、图标与动效 | [样式设计指南](style-design-guide.md),唯一的通用样式规范 |
| Agent 聊天布局、会话、输入、报告与阅读 | [Agent 交互与报告](agent-chat-ui-design.md) |
| `answer-ui@1`、组件语义、生成契约与验证 | [本地交互式回答](agent-answer-ui.md) |
| 聊天控件状态、宿主提问与尚未实施的阅读位置 | [交互状态持久化](agent-interaction-state-design.md) |
| Persona 视觉、Rive 状态、资源再生成与缓存 | [Persona 设计与资源维护](agent-persona-design.md) |
| 调查展示、滚动图表窗口、自动弹出、回看及 Dev | [调查任务展示与 Dev 测试](investigation-dev-tools.md) |
| 项目启动、切换与授权项目缓存 | [项目切换](project-switching.md) |
| 风险、状态与错误文案 | [状态语言](status-language.md) |
三端职责见 [工作区受控 UI 架构](../../agent_ui_architecture_without_sandbox.md);正式任务和报告契约由 [Server 文档目录](../../next-tjwater-server/docs/README.md) 管理。自由代码运行时、HistoryExplorer、聊天阅读位置和报告私人状态在功能文档中明确标注为提案或待实施,不能作为现有能力。
## 历史与合并去向
| 原文档或记录 | 当前去向 |
| --- | --- |
| `agent-persona-resource.md` | 已合并到 [Persona 第 8 节](agent-persona-design.md#8-资源生成与维护),不再单独维护 |
| `non-map-ui.md` | [2026 年 9 月面板整理记录](history/non-map-ui-2026-09.md),现行样式归样式设计指南 |
| `rive-persona-incident.md` | [Rive 历史排查](history/rive-persona-incident.md),保留故障依据,当前行为见 Persona |
| 回答 UI 的阶段测试数量与发布状态 | [2026 年 10 月验证记录](history/answer-ui-validation-2026-10.md) |
| 含分析篮的旧交互状态方案 | [原始提案](history/agent-interaction-state-proposal-2026-10.md),分析篮已取消 |
| 聊天与 Persona 的阶段实现 | [实现记录](history/agent-chat-ui-implementation-notes.md) |
历史文档保留当时的测试证据与限制,不代表当前全量测试、真实账号验收或线上服务状态。修改代码后按本仓库要求重新验证,不能只更新文档中的日期或测试数量。
+14 -22
View File
@@ -2,45 +2,31 @@
统一样式见 [样式设计指南](style-design-guide.md),聊天布局与报告交互见 [Agent 交互与报告设计](agent-chat-ui-design.md)。本文保留协议、组件参数与业务交互约定。 统一样式见 [样式设计指南](style-design-guide.md),聊天布局与报告交互见 [Agent 交互与报告设计](agent-chat-ui-design.md)。本文保留协议、组件参数与业务交互约定。
## 实施进度(2026-10-30 更新) ## 实现范围与后续设计
原生组件版的主要界面与交互状态保存已实现,已完成本地自动化验证;真实授权项目联调和发布尚待完成。下表的“已实现”指当前工作区代码,不代表运行服务已同步更新。相关改动仍未提交、未部署。 下表区分当前源码已具备的能力与独立设计提案。“已实现”不证明运行服务已加载此版本;提交、发布与真实项目验收需核对对应交付记录。整理日期为 2026-11-10。
| 能力 | 状态 | 已有范围与剩余边界 | | 能力 | 状态 | 已有范围与剩余边界 |
| --- | --- | --- | | --- | --- | --- |
| Agent 内容组织 | 已实现 | shadcn/ui 原生组件、内容分区、导航、指标与证据展示;沿用现有对话和工具执行通道 | | Agent 内容组织 | 已实现 | shadcn/ui 原生组件、内容分区、导航、指标与证据展示;沿用现有对话和工具执行通道 |
| 任务语义与结果表达 | 2026-10-28 已接入工作区 | `Result`、回答用途、分区角色、疏密及具体说明标题;Agent 选择表达语义,宿主统一视觉与动作边界,真实模型联调待完成 | | 任务语义与结果表达 | 已实现 | `Result`、回答用途、分区角色、疏密及具体说明标题;Agent 选择表达语义,宿主统一视觉与动作边界,真实模型联调待完成 |
| 表格与图表 | 已实现 | 搜索、排序、折线/柱状/数据表切换、区间选择和序列显隐;只处理已加载数据 | | 表格与图表 | 已实现 | 搜索、排序、折线/柱状/数据表切换、区间选择和序列显隐;只处理已加载数据 |
| 报告与 Markdown 阅读 | 已实现 | 表格完整内容可横纵滚动;报告与 Mermaid 有界放大、暗色遮罩、图标按钮、焦点恢复及减少动态效果适配 | | 报告与 Markdown 阅读 | 已实现 | 表格完整内容可横纵滚动;报告与 Mermaid 有界放大、暗色遮罩、图标按钮、焦点恢复及减少动态效果适配 |
| 定位与资料补充 | 已实现 | 保留专用地图定位和补充资料表单;数据组件不提供勾选、分析篮或组件追问 | | 定位与资料补充 | 已实现 | 保留专用地图定位和补充资料表单;数据组件不提供勾选、分析篮或组件追问 |
| 交互状态持久化(A) | 核心已实现 | 图表、表格、表单与证据状态按会话保存;支持刷新恢复、兼容迁移、失败重试和显式冲突处理 | | 交互状态持久化(A) | 核心已实现 | 图表、表格、表单与证据状态按会话保存;支持刷新恢复、兼容迁移、失败重试和显式冲突处理 |
| 阅读位置持久化 | 设计待实施 | reader 记录尚未保存到宿主;分析篮已按产品决定移除,旧 basket 设计不再作为实施目标 | | 阅读位置持久化 | 设计待实施 | reader 记录尚未保存到宿主;分析篮已按产品决定移除,旧 basket 设计不再作为实施目标 |
| 提问与回答生命周期 | 2026-10-28 已接入工作区 | 自有 ask_user、独立草稿、答案持久化与固定 ID 续跑;历史 question 权威核对。真实模型完整链路及发布未验收 | | 提问与回答生命周期 | 已实现 | 自有 ask_user、独立草稿、答案持久化与固定 ID 续跑;历史 question 权威核对。真实模型完整链路及发布未验收 |
| 压力历史探索(B) | 设计提案 | `HistoryExplorer` 和新时间窗分页查询尚未实现,不能将本地筛选当成重新查询 | | 压力历史探索(B) | 设计提案 | `HistoryExplorer` 和新时间窗分页查询尚未实现,不能将本地筛选当成重新查询 |
| 自由代码运行时(C) | 未接入 | 仍采用受控原生组件;独立 iframe、生成代码运行及其通信协议需要另行架构评审 | | 自由代码运行时(C) | 未接入 | 仍采用受控原生组件;独立 iframe、生成代码运行及其通信协议需要另行架构评审 |
| 外围与 Dev 窗口交互 | 已修复 | 窗口外地图可点击、拖动和滚轮缩放;窗口内部操作不穿透地图 | | 外围与 Dev 窗口交互 | 已修复 | 窗口外地图可点击、拖动和滚轮缩放;窗口内部操作不穿透地图 |
对应根目录研究文档的四个阶段:阶段一的标准组件路线已实现;阶段三的原生组件状态管理已提前落地;阶段四已接入部分地图、报告和追问流程;阶段二的自由代码运行时尚未接入。本文后续 A/B/C 是实施包名称,与研究文档的阶段编号不同。 对应根目录研究文档的四个阶段:阶段一的标准组件路线已实现;阶段三的原生组件状态管理已提前落地;阶段四已接入部分地图、报告和追问流程;阶段二的自由代码运行时尚未接入。本文后续 A/B/C 是实施包名称,与研究文档的阶段编号不同。
2026-10-30 展示范围调整已通过 lint、typecheck、146 个文件共 838 项单元测试,以及 25 项浏览器回归(含复跑,使用模拟接口)。浏览器覆盖桌面与窄屏、内联与展开表格、图表动效、会话状态恢复、地图定位和补充表单;不代表真实项目联调或部署完成。 历史静态、浏览器和模型验证分开记录,见 [2026 年 10 月验证记录](history/answer-ui-validation-2026-10.md)。当前验证命令见下文,不能将历史测试数量作为当前通过结论。
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)。验证命令见下文“验证”,后续顺序见“后续待办与验收”。 当前实现入口为 [原生回答组件](../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 阶段“无数据库迁移”的交付结论。后续追加的宿主提问实现状态单列如下。 状态保存、宿主提问与后续阅读位置设计统一见 [交互状态](agent-interaction-state-design.md)。分析篮、行选择和组件追问已取消;聊天阅读位置和正式报告私人状态仍属待实施范围,不能沿用聊天控件状态“无需数据库迁移”的结论。
同日补充的宿主提问方案已于 2026-10-28 接入工作区,见上述文档第 11 节:以自有 ask_user 管理等待、草稿、答案与续跑,同时核对历史原生 question 的可用状态。独立完成此项不代表 reader 或正式报告状态已实施;此前历史故障的具体触发条件仍未取得现场响应。
## 接入方式 ## 接入方式
@@ -84,10 +70,16 @@ SCADA 的压力、水头(m)及流量、管流(m³/h)数值轴使用对
图表发布及 Dev 示例的对象聚合、同期校验和历史读取边界统一见 [调查展示 Dev 测试](investigation-dev-tools.md#对象复合图与验证规则)。结构化 Chart 保持单图语义,对象聚合通过 open_chart 的独立对象数据集实现。 图表发布及 Dev 示例的对象聚合、同期校验和历史读取边界统一见 [调查展示 Dev 测试](investigation-dev-tools.md#对象复合图与验证规则)。结构化 Chart 保持单图语义,对象聚合通过 open_chart 的独立对象数据集实现。
[图表和窗口管理](investigation-dev-tools.md#图表和窗口管理)由浏览器宿主负责:总窗口收纳过程图组与报告 Chart,子图表保留独立弹窗放大。总窗口提供单图、左右、四宫格固定槽位,全部图表沿纵向连续排列,末行按列数补齐空槽;整条位置栏提供拖拽和悬停反馈,拖放到目标位置交换内容。窄窗口使用单图,快速定位会滚动到目标位置。同一图表更新保留位置,删图留空,新图先填空槽。顶部窗口列表可定位、置顶已打开的总窗口、子图表和表格,并统一关闭。窗口缩放期间,图表按窗口实际尺寸适配并保留图表实例与筛选状态;松开后确认最终尺寸,Escape 或指针取消恢复原尺寸。 [图表和窗口管理](investigation-dev-tools.md#图表和窗口管理)由浏览器宿主负责:管理区占用右侧分析区域,收纳过程图组与报告 Chart,子图表保留独立弹窗放大。管理区提供单图、左右、四宫格固定槽位,全部图表沿纵向连续排列,末行按列数补齐空槽;整条位置栏提供拖拽和悬停反馈,拖放到目标位置交换内容。窄区域使用单图,快速定位会滚动到目标位置。同一图表更新保留位置,删图留空,新图先填空槽。顶部窗口列表仅定位、置顶和统一关闭独立子图表与表格浮窗,不包含图表管理区。拖动分隔条或缩放独立浮窗时,图表按实际尺寸适配并保留图表实例与筛选状态;独立浮窗缩放支持 Escape 或指针取消恢复原尺寸。
任务打开、切换、刷新、已完成任务载入和历史恢复只更新内容,不弹窗;运行中新收到的 open_chart 由总窗口统一处理,关闭后的实时更新不重新弹出。排列、布局和窗口操作不新增模型输出或 wire 协议字段,也不改变图表校验与证据规则。具体自动弹出与关闭边界以上述管理说明为准。 任务打开、切换、刷新、已完成任务载入和历史恢复只更新内容,不弹窗;运行中新收到的 open_chart 由总窗口统一处理,关闭后的实时更新不重新弹出。排列、布局和窗口操作不新增模型输出或 wire 协议字段,也不改变图表校验与证据规则。具体自动弹出与关闭边界以上述管理说明为准。
切换调查任务时,报告内容立即替换,展示数据先与新任务范围对齐,再读取其历史结果;旧任务图表不在新任务范围下重新挂载。
历史请求未完成时显示骨架,失败时显示具体错误;图表接近可视区域后分帧挂载,离开任务会取消尚未执行的绘制。
骨架改善等待反馈,不缩短接口响应时间,也不表示调查已经完成。流程图按源码和渲染配置复用最多 32 份浏览器内 SVG,
复用时重新分配实例标识,配置变化和失败重试会重新绘制;报告版本、证据引用和实际任务状态仍以保存的数据为准。
流程图首次排版显示骨架,后续更新保留旧图直到新排版完成,维持阅读位置与缩放;连续更新时忽略迟到的旧排版结果。
其余组件使用 `answer-motion.tsx` 统一交互过渡,沿用现有实体面板、字体、语义颜色和圆角。首次加载即时显示;鼠标展开、收起使用 180ms 透明度和位移,键盘与减少动态效果模式即时完成。折叠中的内容立即设为 `inert` 并退出无障碍树,动画结束后隐藏;保留原 React 内容实例,反向操作中断旧动画,避免旧退出回调隐藏重新展开的表单。 其余组件使用 `answer-motion.tsx` 统一交互过渡,沿用现有实体面板、字体、语义颜色和圆角。首次加载即时显示;鼠标展开、收起使用 180ms 透明度和位移,键盘与减少动态效果模式即时完成。折叠中的内容立即设为 `inert` 并退出无障碍树,动画结束后隐藏;保留原 React 内容实例,反向操作中断旧动画,避免旧退出回调隐藏重新展开的表单。
| 组件 | 交互与内容处理 | | 组件 | 交互与内容处理 |
@@ -308,7 +300,7 @@ Vite 统一解析 React/React DOM,Playwright 按端口使用独立的依赖缓
尚未持久化:阅读锚点与相对偏移。当前同实例展开/收起的内存保留,不等于刷新后的宿主恢复。 尚未持久化:阅读锚点与相对偏移。当前同实例展开/收起的内存保留,不等于刷新后的宿主恢复。
补齐方案见 [Intelligent UI 交互状态补齐设计](agent-interaction-state-design.md):保留现有 controls 接口,计划新增独立 reader 记录;旧 basket 部分已停止实施;正式报告按当前读者及报告版本保存到 Server,不使用发布报告的 Agent 会话充当读者身份。 后续补齐范围见 [交互状态](agent-interaction-state-design.md):保留现有 controls 接口,阅读位置计划独立保存;正式报告按当前读者及报告版本保存到 Server,不使用发布报告的 Agent 会话充当读者身份。
状态记录附带完整 spec 摘要 `schema_digest`、单块 `revision` 与最后请求 ID。`schema_digest` 由服务端从会话里已保存的块计算;客户端摘要只用于检查过期。摘要变化后执行上表的兼容迁移,再写新版本。按数据整体设置 key 的逻辑改为稳定节点身份加显式兼容处理,不能只删除 key 而沿用越界索引。 状态记录附带完整 spec 摘要 `schema_digest`、单块 `revision` 与最后请求 ID。`schema_digest` 由服务端从会话里已保存的块计算;客户端摘要只用于检查过期。摘要变化后执行上表的兼容迁移,再写新版本。按数据整体设置 key 的逻辑改为稳定节点身份加显式兼容处理,不能只删除 key 而沿用越界索引。
+7 -5
View File
@@ -134,15 +134,17 @@ Agent 形象基于 [Obsidian 原版动画资源](https://ejiidnob33g9ap1r.public
在线动画由 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 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)。首次加载、加载失败和系统开启减少动态效果时显示从当前资源渲染的在线或离线静态帧,离线静态帧同样不带外围光圈;兜底形象与按钮功能持续可用。 离线通过同一 Rive 资源中的 `asleep` 状态呈现“静水待机”:关闭外围三层光圈,保留完整蓝色球体及内部柔光的低速、小幅度流动。在线与离线切换保持同一个动画实例,通过资源内的状态混合衔接,恢复连接后回到在线光圈与节奏。参数和图层说明统一维护在 [Agent 动画资源说明](agent-persona-design.md#8-资源生成与维护)。首次加载、加载失败和系统开启减少动态效果时显示从当前资源渲染的在线或离线静态帧,离线静态帧同样不带外围光圈;兜底形象与按钮功能持续可用。
鼠标悬停沿用原生 `hover` 动画和光圈尺寸;进入、移动、离开坐标通过共享组件交给 Rive 原生监听,使白色高光跟随鼠标局部移动,避免只开 hover 却使反射固定在中心。移出后恢复常态。球体组件移除 Motion,取消按压缩放、弹簧回弹和明暗变化;触摸按下不触发额外动画。点击、触摸轻点及 Enter / Space 继续展开对话,离线时同样可用。系统开启减少动态效果时显示静态帧,不初始化 Rive。强制颜色模式显示高对比圆形轮廓,保留键盘操作。球体动画与面板布局独立,不对 Resizable 连续调宽增加动画。 鼠标悬停沿用原生 `hover` 动画和光圈尺寸;进入、移动、离开坐标通过共享组件交给 Rive 原生监听,使白色高光跟随鼠标局部移动,避免只开 hover 却使反射固定在中心。移出后恢复常态。球体组件移除 Motion,取消按压缩放、弹簧回弹和明暗变化;触摸按下不触发额外动画。点击、触摸轻点及 Enter / Space 继续展开对话,离线时同样可用。系统开启减少动态效果时显示静态帧,不初始化 Rive。强制颜色模式显示高对比圆形轮廓,保留键盘操作。球体动画与面板布局独立,不对 Resizable 连续调宽增加动画。
渲染生命周期继续遵守 [Rive 内存问题记录](rive-persona-incident.md):延迟一帧初始化,元素离开视口或页面隐藏时卸载渲染实例,不绑定 View Model;仅缓存不可变的 `.riv` 字节,展开、折叠和不同入口复用一次成功下载。失败下载不永久缓存,后续挂载可重试。动态组件准备完成前保留本地静态帧,原生进入动画在显示切换前完成。静态帧与动画通过 180ms CSS 透明度渐变衔接,结束后才隐藏静态帧,避免首次加载瞬间切换造成的跳动;画布的位置与尺寸始终固定。本轮没有新增依赖,也没有恢复已知存在内存问题的颜色绑定。 渲染生命周期继续遵守 [Rive 内存问题记录](history/rive-persona-incident.md):延迟一帧初始化,元素离开视口或页面隐藏时卸载渲染实例,不绑定 View Model;仅缓存不可变的 `.riv` 字节,展开、折叠和不同入口复用一次成功下载。失败下载不永久缓存,后续挂载可重试。动态组件准备完成前保留本地静态帧,原生进入动画在显示切换前完成。静态帧与动画通过 180ms CSS 透明度渐变衔接,结束后才隐藏静态帧,避免首次加载瞬间切换造成的跳动;画布的位置与尺寸始终固定。本轮没有新增依赖,也没有恢复已知存在内存问题的颜色绑定。
### 离线动画的资源改造 ### Persona 资源与生命周期
已解析原版的图形、属性、关键帧和状态机,保存为可读的运行时 JSON,并验证可以逐字节恢复原始 `.riv`。修改后的资源保留 5 个原生状态输入,在原有 20 段动画后增加 3 段离线循环,修正 `asleep` / `wake` 中隐藏和缩小球体的关键帧。修改、再生成及保真验证见 [Agent 动画资源说明](agent-persona-resource.md)。这份 JSON 是运行时数据,不是完整恢复的 `.rev` 编辑器工程。 Persona 的视觉、尺寸、离线状态、悬停、缓存和再生成统一维护在 [Persona 设计](agent-persona-design.md)。聊天面板与悬浮入口复用同一资源和指针通路,保留静态降级、减少动态效果和可见性卸载。
历史 Rive 内存问题的触发条件与修复依据见 [排查记录](history/rive-persona-incident.md);不根据历史记录重建已经替换的悬停通路或 View Model 绑定。
### 历史窗口、缓存与后台会话 ### 历史窗口、缓存与后台会话
@@ -184,7 +186,7 @@ Agent 面板、历史和主题窗口及正文阅读窗口共用选区复制处
本次无需新增 UI 协议、环境变量或数据库迁移。自由代码沙箱、跨会话保存控件状态和参数驱动的新数据查询属于后续能力;当前表单、筛选与选择在聊天和展开工作区之间移动时保留,历史恢复仍从已保存的回答结构重新建立控件。 本次无需新增 UI 协议、环境变量或数据库迁移。自由代码沙箱、跨会话保存控件状态和参数驱动的新数据查询属于后续能力;当前表单、筛选与选择在聊天和展开工作区之间移动时保留,历史恢复仍从已保存的回答结构重新建立控件。
后续的状态保存、压力历史探索与沙箱接入条件见 [可持续分析工作区设计](agent-answer-ui.md#下一阶段设计可持续分析工作区)。该部分是未实现的提案,不能作为当前功能清单。 后续的状态保存、压力历史探索与沙箱接入条件见 [可持续分析工作区设计](agent-answer-ui.md#可持续分析工作区实现与后续设计)。该部分是未实现的提案,不能作为当前功能清单。
`answer-ui@1` 仍由严格参数校验与本地注册组件驱动。已有的 `Stack`、`Section`、`Text`、`Metric`、`Table`、`Chart`、`Evidence`、`MapLocation`、`FollowUpForm` 使用新外观。聊天继续使用现有 Responses 事件;正式报告增加可选 `ui_blocks` 字段,复用相同的内容块协议。实现契约见 [本地交互式回答](agent-answer-ui.md)。 `answer-ui@1` 仍由严格参数校验与本地注册组件驱动。已有的 `Stack`、`Section`、`Text`、`Metric`、`Table`、`Chart`、`Evidence`、`MapLocation`、`FollowUpForm` 使用新外观。聊天继续使用现有 Responses 事件;正式报告增加可选 `ui_blocks` 字段,复用相同的内容块协议。实现契约见 [本地交互式回答](agent-answer-ui.md)。
+35 -355
View File
@@ -1,375 +1,55 @@
# Intelligent UI 交互状态补齐设计 # 交互状态持久化与后续设计
> 2026-10-30 产品决定:数据组件仅用于展示与本地浏览,已移除表格勾选、分析内容篮及组件追问;专用地图定位和补充资料表单保留。本文分析篮、行选择和引用操作的方案属于历史设计,不再作为当前实施目标。阅读位置、表单草稿及宿主提问的独立设计仍可参考,当前行为以 [本地交互式回答](agent-answer-ui.md) 为准。 整理日期:2026-11-10。本文只维护已实现的状态边界和仍有效的后续工作。2026 年 10 月原提案保存于 [历史设计](history/agent-interaction-state-proposal-2026-10.md),其中分析篮、行选择和组件追问已取消,不再作为实施目标。组件内容与交互入口见 [本地交互式回答](agent-answer-ui.md)。
历史设计状态:2026-10-27 设计稿;2026-10-28 第 11 节宿主提问已接入工作区代码,其余补齐项仍待实现。当前代码进度见 [本地交互式回答](agent-answer-ui.md)。本设计补齐阅读位置、分析篮和正式报告的私人交互状态,不改变模型可生成的 `answer-ui@1` 组件协议。第 11 节单独处理 question 的执行生命周期。 ## 当前能力
## 1. 目标与方案 | 范围 | 状态 | 边界 |
| --- | --- | --- |
| 聊天图表、表格、表单和证据控件状态 | 已实现 | 按用户、会话和内容身份保存;包含版本比较、失败重试和冲突处理 |
| 宿主 `ask_user` 请求、草稿、答案和续跑投递 | 已实现 | 使用独立请求与投递记录;历史原生 question 仍需核对当前原生请求是否有效 |
| 阅读位置 reader | 待实施 | 当前页面的阅读状态不等于刷新后的持久记录 |
| 正式报告私人状态 | 待实施 | 需要按读者、任务及报告版本独立保存,不借用报告发布会话 |
| 分析篮、行勾选、组件追问 | 已取消 | 不恢复旧 basket 协议或为其新增存储 |
用户刷新后,再次打开同一回答或同一版报告,可以继续阅读、筛选和填写资料。恢复只改变当前用户的界面,不发送消息、不提交表单、不调用业务工具、不定位地图,也不自动打开窗口。 ## 聊天控件状态
推荐保留已实现的聊天控件状态接口,新增阅读与分析篮的补充记录;正式报告的状态由 Server 按当前读者保存。三种记录独立比较版本,避免滚动保存与表单输入、选行互相冲突。前端继续复用受控 store 和现有保存协调器,只由来源适配器决定请求 Agent 还是 Server。 控件状态与回答内容分别保存。内容由消息或报告持有,状态仅改变当前读者的本地浏览方式;恢复不能发送消息、提交表单、调用业务工具、定位地图或自动打开窗口。
最小方案是仅增加会话内存缓存,但刷新后仍会丢失,不能满足目标。把全部状态塞入原接口会破坏旧客户端的严格校验,也会让分析篮挤占控件的 32 KiB 限额,因此采用补充记录。正式报告不能借用 `source_session_id` 保存:它指向发布报告的执行会话,报告读者未必拥有这个会话。 状态身份需要保持会话、block 和内容版本边界。同块数据更新时清理已经失效的选择;迟到的恢复结果不能覆盖用户的新输入。失败保存保留内存交互并明确提示未保存,冲突需显式处理,不静默覆盖其他窗口的新版本。
新增服务、账号、密钥和环境变量均为零;正式报告需要在已有项目 BizDB 增加一张私人状态表。预计涉及三个仓库、超过 8 个实现文件,按第 10 节拆成可独立交付的两批。 当前实现入口:
- [前端状态同步](../src/features/agent/session-state/answer-view-state-scope.ts) 与 [原生回答组件](../src/features/agent/answer-ui/answer-ui-view.tsx)。
- [Agent 状态路由](../../next-tjwater-agent/src/routes/answer-view-state-routes.ts) 与 [状态存储](../../next-tjwater-agent/src/sessions/answer-view-state-store.ts)。
- [会话归属与存储](../../next-tjwater-agent/docs/user-isolation.md),负责授权、删除及持久目录边界。
## 宿主提问与回复
聊天及人工任务协作通过宿主 `ask_user` 保存等待状态。问题定义、表单草稿、已提交答案和续跑投递是不同记录;工具和浏览器不能自行指定所有者、项目或目标会话。后台调查的任务提问由 Server 管理,见 [工况任务契约](../../next-tjwater-server/docs/operational-tasks.md),不以浏览器存活为条件。
```text ```text
聊天最终回答 -> Agent 来源适配器 -> 已授权会话 / 控件记录 + 补充记录 模型 ask_user → 可信工具桥 → 宿主保存请求 → 显示问题卡,等待回答
^ 用户提交 → 保存答案与投递记录 → 运行协调器 → 原会话续跑
| ↑ 固定消息 ID 核对投递状态
读取/编辑 -> 前端状态协调器 -> 受控组件、阅读位置、分析篮
|
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) 观测;这些机制不替代宿主的权限、持久化和版本校验。实现以仓库当前安装版本为准,不因本设计升级依赖。 浏览器通过 `/api/v1/session/:session_id/interactions` 读取请求,按 `interaction_id` 保存草稿并执行 `reply`、`skip`、`cancel` 或 `resume`。独立列表用于恢复问题;不能据此认定所有历史请求已经嵌入会话详情的分页投影。
## 2. 当前依据与状态分工 保存答案成功与推理继续成功分开反馈。投递结果不明时核对固定原生消息 ID,不生成新 ID 重复注入。宿主恢复需要有效用户上下文,不持久保存 Bearer,也不悄悄创建新会话重放业务过程。旧 question 卡片能显示,不代表原生请求仍可回答。
| 当前实现 | 补齐方式 | 实现入口为 [请求路由](../../next-tjwater-agent/src/routes/interaction-request-routes.ts)、[请求存储](../../next-tjwater-agent/src/sessions/interaction-request-store.ts) 与 [投递核对](../../next-tjwater-agent/src/sessions/interaction-delivery-reconciliation.ts)。原始字段设计、故障假设和当时的验证边界见历史设计第 11 节;“拟新增”和“尚未验证”仅反映提案阶段,不能替代当前代码核对。
| --- | --- |
| `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. 身份与版本 正式报告私人状态应绑定当前读者、项目、任务和报告版本,并在每次读写时检查当前读取权限。`source_session_id` 是报告的发布会话,不能作为读者授权或私人状态存储身份。该能力需要 Server API 与项目 BizDB 表及逐项目迁移,尚无可直接调用的已交付接口。
| 来源 | 文档身份 | 块身份 | 权威校验 | 历史提案中的接口草案和容量数值仍是设计参考;实施前重新核对当前契约,不提前对外宣布可用。无需为已经取消的分析篮新增表、记录或权限。
| --- | --- | --- | --- |
| 聊天 | 当前主体、个人/项目范围、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 混用。 前端与 Agent 的检查命令统一见 [回答 UI 验证](agent-answer-ui.md#验证)。重点覆盖刷新恢复、同块数据更新、两窗口冲突、保存失败、会话切换后迟到响应、删除后的迟到写入、问题提交与续跑结果不明,以及窄屏和键盘操作。
打开任务仍默认查看当前报告,不自动恢复为上次选中的历史版本。用户主动选择某个版本后才恢复该版本的状态。新报告使用新的身份和空状态,不自动复制旧版表单或分析篮;旧版记录保留供用户回看。放大窗口保留旧版内容时,状态写入也绑定当时的旧版,直到用户点击“查看最新内容”。 模拟 HTTP、浏览器交互、隔离原生投递验证、真实模型完整续跑和部署验收分别记录。此轮文档整理不重新执行推理、迁移或发布,也不将历史检查更新为当前验收结论。
最容易失效的前提是“相同 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。
+80 -4
View File
@@ -1,6 +1,6 @@
# Agent Persona 设计 # Agent Persona 设计
更新日期:2026-10-28。本文保存供水前端当前的 Persona 视觉与交互规格,作为后续调整的基线。资源解析、再生成及缓存实现见 [动画资源说明](agent-persona-resource.md);通用控件和语义表面继续遵循 [样式设计指南](style-design-guide.md)。 整理日期:2026-11-10。本文保存供水前端当前的 Persona 视觉与交互规格,作为后续调整的基线。资源解析、再生成及缓存实现见 [动画资源说明](agent-persona-design.md#8-资源生成与维护);通用控件和语义表面继续遵循 [样式设计指南](style-design-guide.md)。
## 1. 形象与材质 ## 1. 形象与材质
@@ -80,7 +80,7 @@
系统开启“减少动态效果”时显示静态帧,不初始化 Rive;资源失败时保留相应静态形象与按钮功能。强制颜色模式显示高对比轮廓,保留焦点和键盘操作。元素离开视口或页面隐藏时卸载渲染实例,可见后恢复。 系统开启“减少动态效果”时显示静态帧,不初始化 Rive;资源失败时保留相应静态形象与按钮功能。强制颜色模式显示高对比轮廓,保留焦点和键盘操作。元素离开视口或页面隐藏时卸载渲染实例,可见后恢复。
客户端按页面内存、Cache Storage、网络的顺序取得资源。仅共享不可变 `.riv` 字节,每个可见入口独立创建动画实例;不共享实例或绑定 View Model。资源重建时同步生成 SHA-256 版本,URL 带版本参数,使旧缓存自然更新。缓存范围与校验逻辑见 [动画资源说明](agent-persona-resource.md)。 客户端按页面内存、Cache Storage、网络的顺序取得资源。仅共享不可变 `.riv` 字节,每个可见入口独立创建动画实例;不共享实例或绑定 View Model。资源重建时同步生成 SHA-256 版本,URL 带版本参数,使旧缓存自然更新。缓存范围与校验逻辑见 [动画资源说明](agent-persona-design.md#8-资源生成与维护)。
## 7. 实现与维护 ## 7. 实现与维护
@@ -93,8 +93,84 @@
| 资源生成与原版还原 | [build-agent-persona.mjs](../scripts/build-agent-persona.mjs) | | 资源生成与原版还原 | [build-agent-persona.mjs](../scripts/build-agent-persona.mjs) |
| 资源版本与缓存 | [persona-resource.ts](../src/shared/ai-elements/persona-resource.ts) | | 资源版本与缓存 | [persona-resource.ts](../src/shared/ai-elements/persona-resource.ts) |
材质与离线参数以对应 JSON 为准,悬停沿用原始资源中的几何与指针约束,仅调整时间轴与指针跟随节奏;改动时同步本文与资源说明。原始解析数据保留以便逐字节还原 `.riv`;该数据不等于作者完整的 `.rev` 编辑器工程。 材质与离线参数以对应 JSON 为准,悬停沿用原始资源中的几何与指针约束,仅调整时间轴与指针跟随节奏;改动时同步本文的设计规格与资源维护章节。原始解析数据保留以便逐字节还原 `.riv`;该数据不等于作者完整的 `.rev` 编辑器工程。
验收时检查 64px 桌面入口、64px 标题形象与 40px 手机入口,覆盖默认、悬停进入与退出、快速切换、离线和恢复在线。桌面检查 1024/1440px 视口及 400/640px 面板,手机检查 320/375px。确认左上间距一致、按压无缩放、首次加载无画面硬切、底色能遮蔽地图、离线无外围光圈、缓存刷新后仍加载当前版本。 验收时检查 64px 桌面入口、64px 标题形象与 40px 手机入口,覆盖默认、悬停进入与退出、快速切换、离线和恢复在线。桌面检查 1024/1440px 视口及 400/640px 面板,手机检查 320/375px。确认左上间距一致、按压无缩放、首次加载无画面硬切、底色能遮蔽地图、离线无外围光圈、缓存刷新后仍加载当前版本。
资源级检查使用固定时间步对照原版与修改版:在线状态保持相同材质下的逐像素一致;悬停检查左右移动时局部高光跟随指针,移出后完全恢复。工作台检查鼠标坐标实际到达悬浮入口和标题形象的 Rive 监听器,不能仅断言 hover 开关变化。离线检查完整球体、持续变化和光圈关闭。运行命令见 [资源说明](agent-persona-resource.md),各次实际验证结果记录在 [实施记录](history/agent-chat-ui-implementation-notes.md)。 资源级检查使用固定时间步对照原版与修改版:在线状态保持相同材质下的逐像素一致;悬停检查左右移动时局部高光跟随指针,移出后完全恢复。工作台检查鼠标坐标实际到达悬浮入口和标题形象的 Rive 监听器,不能仅断言 hover 开关变化。离线检查完整球体、持续变化和光圈关闭。运行命令见 [资源说明](agent-persona-design.md#8-资源生成与维护),各次实际验证结果记录在 [实施记录](history/agent-chat-ui-implementation-notes.md)。
## 8. 资源生成与维护
### 文件与再生成
| 文件 | 用途 |
| --- | --- |
| [运行时源数据](../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` 使用只创建模式,目标文件已存在时会报错,避免覆盖已有编辑。原版还原文件与基线逐字节相同,包含原版离线消失的行为;前端继续加载带离线设计的应用资源。
### 离线图层参数
内部柔光的三层强度分别为 56%–68%、48%–62%、60%–72%,反射强度均为 0;周期与外观以第 4 节和 `obsidian-offline.json` 为准。参数中的图层名称是运行时结构的语义别名,不是作者原始命名。`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 内存记录](history/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 淡出,中途保持可见且最终恢复常态。指针定时测试覆盖惯性跟随、停留、快速进出与卸载清理;工作台测试验证平滑后的实际坐标最终到达原生监听器。离线检查完整球体、持续变化、初始离线和反复恢复;通过外围像素计数验证光圈完全消失,悬停不会重新出现,恢复在线后再次可见。另用相同运动轨迹、取消离线光照变化的对照资源,验证快速切换后在线明暗完整恢复。该检查覆盖固定采样时刻,不是所有设备、运行时间和状态序列的穷举验证。
-93
View File
@@ -1,93 +0,0 @@
# 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 淡出,中途保持可见且最终恢复常态。指针定时测试覆盖惯性跟随、停留、快速进出与卸载清理;工作台测试验证平滑后的实际坐标最终到达原生监听器。离线检查完整球体、持续变化、初始离线和反复恢复;通过外围像素计数验证光圈完全消失,悬停不会重新出现,恢复在线后再次可见。另用相同运动轨迹、取消离线光照变化的对照资源,验证快速切换后在线明暗完整恢复。该检查覆盖固定采样时刻,不是所有设备、运行时间和状态序列的穷举验证。
@@ -44,7 +44,7 @@ Agent 类型检查及 16 项相关测试通过;隔离 OpenCode 工具发现验
## 2026-10-21 Rive 资源内离线水纹 ## 2026-10-21 Rive 资源内离线水纹
解析原版 775 个运行时对象,JSON 重新编码与原文件逐字节一致。保留原图形和在线动画,新增三段离线循环,并修正 asleep / wake 的透明度与缩放关键帧;同源资源为 `public/agent/obsidian-water-v1.riv`。实现与再生成说明见 [Agent 动画资源](../agent-persona-resource.md)。 解析原版 775 个运行时对象,JSON 重新编码与原文件逐字节一致。保留原图形和在线动画,新增三段离线循环,并修正 asleep / wake 的透明度与缩放关键帧;同源资源为 `public/agent/obsidian-water-v1.riv`。实现与再生成说明见 [Agent 动画资源](../agent-persona-design.md#8-资源生成与维护)。
验证通过:生成一致性检查、lint、类型检查、547 项单测、构建、`git diff --check`。10 项相关浏览器用例分批通过,包含真实 WebGL2 在线状态采样逐像素对照、原版离线消失与修改版离线持续运动、初始离线、反复恢复、工作台单实例、加载衔接、按压无反馈、资源失败、减少动态效果、键盘及 320/375px。首次运行有 1 项动画就绪等待超时;未修改运行代码,带 trace 复测通过,首次超时根因未确认。 验证通过:生成一致性检查、lint、类型检查、547 项单测、构建、`git diff --check`。10 项相关浏览器用例分批通过,包含真实 WebGL2 在线状态采样逐像素对照、原版离线消失与修改版离线持续运动、初始离线、反复恢复、工作台单实例、加载衔接、按压无反馈、资源失败、减少动态效果、键盘及 320/375px。首次运行有 1 项动画就绪等待超时;未修改运行代码,带 trace 复测通过,首次超时根因未确认。
@@ -0,0 +1,377 @@
# Intelligent UI 交互状态补齐设计
> 历史记录:2026 年 10 月交互状态原始提案,其中分析篮、行选择和组件追问已取消,当前范围见 [交互状态](../agent-interaction-state-design.md)。测试数量、失败列表与未提交状态只对应原记录时间,不代表当前回归结果。
> 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。
@@ -0,0 +1,17 @@
# 回答 UI 的 2026 年 10 月验证记录
> 历史快照,仅保留当时的验证范围,不证明当前工作区或线上服务已通过同样检查。当前协议见 [本地交互式回答](../agent-answer-ui.md)。
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 构建;不等于部署完成 |
@@ -1,5 +1,7 @@
# 非地图面板整理 # 非地图面板整理
> 历史记录:2026 年 9 月的面板整理过程,当前规范见 [样式设计指南](../style-design-guide.md)。测试数量、失败列表与未提交状态只对应原记录时间,不代表当前回归结果。
2026-09-17,范围限供水前端,不改变地图业务、OpenCode、数据库表或环境配置。 2026-09-17,范围限供水前端,不改变地图业务、OpenCode、数据库表或环境配置。
## 视觉与交互 ## 视觉与交互
@@ -104,7 +106,7 @@
## 新增业务组件统一设计 ## 新增业务组件统一设计
2026-09-18 对调查任务与外围样板的新组件完成统一重构。现行规则见 [样式设计指南](style-design-guide.md),视觉方向是浅色专业调度台,保留地图为主工作区,并将侧栏内容稳定为“定位、状态、下一步、证据”的阅读顺序。 2026-09-18 对调查任务与外围样板的新组件完成统一重构。现行规则见 [样式设计指南](../style-design-guide.md),视觉方向是浅色专业调度台,保留地图为主工作区,并将侧栏内容稳定为“定位、状态、下一步、证据”的阅读顺序。
- 新增 `WorkbenchSection`、`WorkbenchNotice` 和 `WorkbenchEmptyState`,统一标题、状态、提示和空态,减少同级彩色卡片与大面积空白。 - 新增 `WorkbenchSection`、`WorkbenchNotice` 和 `WorkbenchEmptyState`,统一标题、状态、提示和空态,减少同级彩色卡片与大面积空白。
- 生命周期确认、定时计划、目标编译、运行控制、运行对比、人工复核和 Evidence 导入统一状态语言与操作层级。 - 生命周期确认、定时计划、目标编译、运行控制、运行对比、人工复核和 Evidence 导入统一状态语言与操作层级。
@@ -1,5 +1,7 @@
# Rive Persona 内存问题排查记录 # Rive Persona 内存问题排查记录
> 历史记录:保留 Rive 内存故障与修复依据,当前指针通路、缓存与离线行为见 [Persona 设计](../agent-persona-design.md)。测试数量、失败列表与未提交状态只对应原记录时间,不代表当前回归结果。
日期:2026-07-21 日期:2026-07-21
## 背景 ## 背景
@@ -84,7 +86,7 @@ pnpm build
Agent 入口使用基于原版 Obsidian 定制的冰水蓝资源。继续保留 Strict Mode 延迟初始化、按可见性挂载和禁止 View Model 绑定;配色直接写入资源,不应用旧版的 brightness / contrast 滤镜。`persona-resource.ts` 在页面内存与浏览器 Cache Storage 中缓存动画字节,按内容版本更新,不共享 Rive 实例或 View Model。 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 监听关闭,避免和原生入口按钮及触摸操作重复响应。 业务离线由本地 `obsidian-water-v1.riv` 的 `asleep` 状态播放内部缓慢水纹并关闭外围光圈,在线/离线切换保留同一实例。减少动态效果、加载和失败时显示从当前资源渲染的 `obsidian-water-idle.png` 或无光圈的 `obsidian-water-offline.png`。隐藏和减少动态效果会卸载实例,不通过 CSS 同时隐藏多个仍运行的 Persona。资源改造见 [Agent 动画资源说明](../agent-persona-design.md#8-资源生成与维护)。`hover` 输入由外层交互控制,Rive 自带的 DOM 监听关闭,避免和原生入口按钮及触摸操作重复响应。
回归验证已覆盖原始字节缓存、失败后的重试、无 View Model 绑定、原生状态及 hover 切换、真实 canvas 动画和桌面/手机单实例。 回归验证已覆盖原始字节缓存、失败后的重试、无 View Model 绑定、原生状态及 hover 切换、真实 canvas 动画和桌面/手机单实例。
+6 -4
View File
@@ -22,7 +22,9 @@ Dev 与工况详情共用右侧工具位置,切换调查时先关闭 Dev 回
## 图表和窗口管理 ## 图表和窗口管理
调查、本地预览与对话展示面板提供“图表窗口”入口,在一个可拖动、缩放、最大化的总窗口中集中查看所有子图表,包括 open_chart 形成的对象图组与报告中的 Chart。每张子图表保留自身的独立弹窗放大入口,可同时打开多个放大窗口;关闭总窗口收起其内部开启的放大窗口,关闭子窗口只收起该放大视图。普通趋势总览、柱状图和报告 Chart 保持各自的图表语义。 调查、本地预览与对话展示面板提供“图表窗口”入口,在右侧分析区域打开图表管理区,集中查看所有子图表,包括 open_chart 形成的对象图组与报告中的 Chart。管理区不提供浮窗拖动、边缘缩放或最大化按钮,通过工作区底部入口切换地图对照与专注图表。每张子图表保留自身的独立弹窗放大入口,可同时打开多个放大窗口;关闭管理区收起其内部开启的放大窗口,关闭子窗口只收起该放大视图。普通趋势总览、柱状图和报告 Chart 保持各自的图表语义。
图表管理区与地图分栏时,两侧最小宽度均为 600px;空间不足时显示专注图表。工况任务沿用展开按钮,展开后占用右侧分析区域,任务区最小宽度为 880px;普通打开或重新打开时默认不选择条目。切换工况任务与图表管理区保留已加载的图表、布局和筛选状态。
总窗口使用固定槽位布局,提供“单图布局”“左右布局”“四宫格布局”,每行分别显示 1、2、2 个固定位置,单图与左右布局每行约占一个可视区高度,四宫格每个可视区约显示两行。全部图表沿纵向连续排列,通过滚动查看;图表随槽位尺寸适配,末行按列数补齐空槽。窄窗口使用单图布局,调宽后恢复先前选择的布局。头部定位、布局和重置控件置于同一条浅底工具栏,控件保持等高,窄窗口允许自然换行。“快速定位图表”列出全部图表,选择后滚动到对应位置并聚焦目标;目标的位置栏短暂显示淡色背景和“已定位”,不使用整卡外框,避免高亮被滚动区域裁切。 总窗口使用固定槽位布局,提供“单图布局”“左右布局”“四宫格布局”,每行分别显示 1、2、2 个固定位置,单图与左右布局每行约占一个可视区高度,四宫格每个可视区约显示两行。全部图表沿纵向连续排列,通过滚动查看;图表随槽位尺寸适配,末行按列数补齐空槽。窄窗口使用单图布局,调宽后恢复先前选择的布局。头部定位、布局和重置控件置于同一条浅底工具栏,控件保持等高,窄窗口允许自然换行。“快速定位图表”列出全部图表,选择后滚动到对应位置并聚焦目标;目标的位置栏短暂显示淡色背景和“已定位”,不使用整卡外框,避免高亮被滚动区域裁切。
@@ -32,11 +34,11 @@ Dev 与工况详情共用右侧工具位置,切换调查时先关闭 Dev 回
槽位映射依据稳定的子图表标识:同一图表实时更新时保留位置,删除图表后保留中间空槽并移除末尾空行,新图优先填补空槽,再追加位置与行。同一次任务查看期间,关闭并重新打开总窗口保留槽位与布局;任务、项目或执行代次切换后重新建立当前内容。交换位置不改变图表数据、对象选择或服务端的展示事件顺序。 槽位映射依据稳定的子图表标识:同一图表实时更新时保留位置,删除图表后保留中间空槽并移除末尾空行,新图优先填补空槽,再追加位置与行。同一次任务查看期间,关闭并重新打开总窗口保留槽位与布局;任务、项目或执行代次切换后重新建立当前内容。交换位置不改变图表数据、对象选择或服务端的展示事件顺序。
工作台顶部的窗口列表入口列出已打开的总图表窗口、独立子图表和表格窗口,选择条目可将对应窗口置顶并定位到标题栏。列表中的“关闭全部窗口”统一收起当前打开的窗口,不删除已加载的图表、表格或任务结果;图表窗口可从原展示入口重新打开。 工作台顶部的窗口列表入口仅列出已打开的独立子图表和表格浮窗,图表管理区不计入列表和窗口数量。选择条目可将对应浮窗置顶并定位到标题栏。“关闭全部窗口”收起独立浮窗,保留图表管理区和已加载结果;图表管理区可从原展示入口重新打开。
总窗口与子图表使用同一缩放交互:指针拖动窗口边缘时,图表按窗口实际尺寸适配,保持已有图表实例与筛选、序列显隐和对象选择;松开后确认最终尺寸。拖动期间按 Escape 或发生 pointercancel 时取消调整、恢复原尺寸;标题栏的 Shift 加方向键继续用于逐步调整大小。 拖动地图与分析区域的分隔条时,管理区图表随实际尺寸适配,保持已有图表实例与筛选、序列显隐和对象选择。独立子图表仍支持拖动窗口边缘缩放;松开后确认最终尺寸,拖动期间按 Escape 或发生 pointercancel 时取消调整、恢复原尺寸,标题栏的 Shift 加方向键用于逐步调整大小。
只有正在跟随的运行中调查新收到 open_chart 时,才自动弹出一次总窗口,不自动弹出各子图表,不抢走键盘焦点;后续指令按 chart_id 更新其中的数据。打开、切换、刷新任务、SSE 重连补载、历史回看和回到当前都只恢复内容,已完成任务也不弹窗。用户关闭总窗口后,本次任务查看期间的后续更新不使其再次弹出;手动收起展示面板期间的新指令也不请求弹窗。总窗口已经打开时,历史回看只更新其中的快照,实时数据不覆盖正在查看的历史。切换任务、项目或执行代次关闭原窗口并重新静默载入,返回之前看过的任务也不重放自动弹出意图。Chat 与本地 Dev 预览使用手动入口。 只有正在跟随的运行中调查新收到 open_chart 时,才自动弹出一次总窗口,不自动弹出各子图表,不抢走键盘焦点;后续指令按 chart_id 更新其中的数据。打开、切换、刷新任务、SSE 重连补载、历史回看和回到当前都只恢复内容,已完成任务也不弹窗。用户关闭总窗口后,本次任务查看期间的后续更新不使其再次弹出;手动收起展示面板期间的新指令也不请求弹窗。总窗口已经打开时,切换历史动作或播放回看会同步更新窗口内的快照;窗口关闭时不自动打开,手动打开后显示当前回看位置。实时数据继续记录,但不覆盖正在查看的历史;“回到当前”显示最新结果。切换任务、项目或执行代次关闭原窗口并重新静默载入,返回之前看过的任务也不重放自动弹出意图。Chat 与本地 Dev 预览使用手动入口。
open_chart 仍只提交 chart_id/chart/evidence_refs,close_chart 仍按 chart_id 移除对象;不新增 display 或 objects 字段。排列、布局与窗口打开意图仅存在当前浏览器中,不进入保存的展示快照或事件。displayed 回执表示展示内容已加载,不保证弹出了独立窗口。 open_chart 仍只提交 chart_id/chart/evidence_refs,close_chart 仍按 chart_id 移除对象;不新增 display 或 objects 字段。排列、布局与窗口打开意图仅存在当前浏览器中,不进入保存的展示快照或事件。displayed 回执表示展示内容已加载,不保证弹出了独立窗口。
@@ -9,6 +9,7 @@ export function createChartSampleTimeSchema(zod: typeof z = z) {
type PublicationChart = { type PublicationChart = {
chart_type: string; chart_type: string;
scada?: { role: "current" | "comparison"; window_start: string };
x_data: string[]; x_data: string[];
series: Array<{ type?: string; data: Array<number | null>; sample_times?: Array<string | null> }>; series: Array<{ type?: string; data: Array<number | null>; sample_times?: Array<string | null> }>;
}; };
@@ -56,8 +57,12 @@ export function chartPublicationError(chart: PublicationChart): string | null {
if ((series.type ?? "line") === "line") for (const base of bases) current.add(base); if ((series.type ?? "line") === "line") for (const base of bases) current.add(base);
else historical.push(...bases); else historical.push(...bases);
} }
if (current.size !== 1) return "当前 line 必须包含真实采样时间,且所有当前曲线使用同一窗口"; const emptyScada = current.size === 0 && chart.scada?.role === "comparison";
const start = [...current][0]; if (current.size !== 1 && !emptyScada) return "当前 line 必须包含真实采样时间,且所有当前曲线使用同一窗口";
const windowStart = emptyScada ? Date.parse(chart.scada!.window_start) + 8 * 3600_000 : 0;
const midnight = Math.floor(windowStart / 86400_000) * 86400_000;
const firstSlot = midnight + seconds[0] * 1000;
const start = emptyScada ? firstSlot + (firstSlot < windowStart ? 86400_000 : 0) : [...current][0];
return historical.some((base) => start <= base || (start - base) % 86400_000 !== 0) return historical.some((base) => start <= base || (start - base) % 86400_000 !== 0)
? "历史 scatter 必须来自当前窗口之前的对应日期" : null; ? "历史 scatter 必须来自当前窗口之前的对应日期" : null;
} }
@@ -67,9 +72,25 @@ export function createViewSchemas(zod: typeof z = z, publication = false, valida
const z = zod; const z = zod;
const presentationIdentifierSchema = z.string().trim().min(1).max(128); const presentationIdentifierSchema = z.string().trim().min(1).max(128);
const scadaChartSchema = z.object({
role: z.enum(["current", "comparison"]),
metric: z.enum(["pressure", "flow"]),
unit: presentationIdentifierSchema,
window_start: createChartSampleTimeSchema(z),
window_end: createChartSampleTimeSchema(z),
value_field: z.enum(["monitored_value", "cleaned_value"]).optional(),
// Populated by Server after checking observations, never a display exemption.
gaps: z.array(z.object({
device_id: presentationIdentifierSchema,
day_offset: z.number().int().min(0).max(7),
missing_count: z.number().int().min(1).max(100),
reason: z.enum(["no_readings", "outside_frozen_scope", "outside_frozen_window", "no_scheduled_samples"])
}).strict()).max(8).optional()
}).strict();
const chartSchema = z const chartSchema = z
.object({ .object({
title: z.string().max(200), title: z.string().max(200),
scada: scadaChartSchema.optional(),
chart_type: z.enum(["line", "bar", "time_comparison"]), chart_type: z.enum(["line", "bar", "time_comparison"]),
x_axis_name: z.string().max(128).optional(), x_axis_name: z.string().max(128).optional(),
y_axis_name: z.string().max(128).optional(), y_axis_name: z.string().max(128).optional(),
@@ -79,6 +100,8 @@ export function createViewSchemas(zod: typeof z = z, publication = false, valida
z z
.object({ .object({
name: z.string().max(128), name: z.string().max(128),
device_id: presentationIdentifierSchema.optional(),
day_offset: z.number().int().min(0).max(7).optional(),
type: z.enum(["line", "bar", "scatter"]).optional(), type: z.enum(["line", "bar", "scatter"]).optional(),
data: z.array(z.number().finite().nullable()).min(1).max(100), data: z.array(z.number().finite().nullable()).min(1).max(100),
sample_times: z.array(createChartSampleTimeSchema(z).nullable()).min(1).max(100).optional() sample_times: z.array(createChartSampleTimeSchema(z).nullable()).min(1).max(100).optional()
@@ -0,0 +1,19 @@
import { z } from "zod";
export const investigationNodeAnnotations = ["reference", "recorded", "needs_input", "failed", "not_taken"] as const;
export type InvestigationNodeAnnotation = (typeof investigationNodeAnnotations)[number];
const legacyAnnotations = {
pending: "reference", running: "reference", completed: "recorded",
waiting: "needs_input", waiting_human: "needs_input", skipped: "not_taken", cancelled: "not_taken"
} as const satisfies Record<string, InvestigationNodeAnnotation>;
export function normalizeInvestigationNodeAnnotation(status: string | null | undefined): InvestigationNodeAnnotation {
if (status == null) return "reference";
if (status in legacyAnnotations) return legacyAnnotations[status as keyof typeof legacyAnnotations];
return investigationNodeAnnotations.includes(status as InvestigationNodeAnnotation) ? status as InvestigationNodeAnnotation : "reference";
}
/** Decode saved diagrams without rewriting historical documents. */
export const investigationNodeAnnotationReadSchema = z.enum([
...investigationNodeAnnotations, "pending", "running", "completed", "waiting", "waiting_human", "skipped", "cancelled"
]).nullish().transform((status) => status == null ? status : normalizeInvestigationNodeAnnotation(status));
@@ -59,14 +59,24 @@ describe("investigation report read contract", () => {
expect(value.diagram?.node_refs[0]?.action_refs).toEqual([]); expect(value.diagram?.node_refs[0]?.action_refs).toEqual([]);
expect(value.data_gaps?.[0]?.node_id).toBeNull(); expect(value.data_gaps?.[0]?.node_id).toBeNull();
}); });
it("distinguishes waiting for dependencies from human feedback without inventing missing states", () => { it("reads legacy waits as saved input conditions without inferring live waiting", () => {
const value = investigationReportSchema.parse({ ...base, diagram: { const value = investigationReportSchema.parse({ ...base, diagram: {
title: "等待结果", mermaid: "flowchart LR\nA[外部回执] --> B[人工复核] --> C[下一步]", title: "等待结果", mermaid: "flowchart LR\nA[外部回执] --> B[人工复核] --> C[下一步]",
node_refs: [{ node_id: "A", label: "外部回执", status: "waiting" }, node_refs: [{ node_id: "A", label: "外部回执", status: "waiting" },
{ node_id: "B", label: "人工复核", status: "waiting_human" }, { node_id: "B", label: "人工复核", status: "waiting_human" },
{ node_id: "C", label: "下一步" }] { node_id: "C", label: "下一步" }]
} }); } });
expect(value.diagram?.node_refs.map((node) => node.status)).toEqual(["waiting", "waiting_human", undefined]); expect(value.diagram?.node_refs.map((node) => node.status)).toEqual(["needs_input", "needs_input", undefined]);
});
it("reads host-generated cumulative graphs with failed attempts and failure reasons", () => {
const value = investigationReportSchema.parse({ ...base, diagram: {
title: "累计调查脉络", mermaid: 'flowchart TD\nold["首次读取(失败)"] --> retry["重新读取"]',
node_refs: [{ node_id: "old", label: "首次读取", status: "failed", detail: "接口超时" },
{ node_id: "retry", label: "重新读取", status: "completed" }],
edges: [{ source: "old", target: "retry", label: "重试" }]
} });
expect(value.diagram?.node_refs[0]).toMatchObject({ status: "failed", detail: "接口超时" });
expect(value.diagram?.edges).toEqual([{ source: "old", target: "retry", label: "重试" }]);
}); });
it.each([ it.each([
{ outcome: "other" }, { outcome: "other" },
@@ -1,6 +1,7 @@
import { z } from "zod"; import { z } from "zod";
import type { AgentTaskDiscussionContext, AnswerUiSelection } from "@/features/agent"; import type { AgentTaskDiscussionContext, AnswerUiSelection } from "@/features/agent";
import { reportUiBlocksSchema } from "@/features/agent"; import { reportUiBlocksSchema } from "@/features/agent";
import { investigationNodeAnnotationReadSchema } from "./investigation-node-state";
export type InvestigationDiscussion = { export type InvestigationDiscussion = {
prompt?: string; prompt?: string;
@@ -28,13 +29,20 @@ export const investigationDiagramSchema = z
!/(?:^|[;\n])\s*click\b/.test(source), !/(?:^|[;\n])\s*click\b/.test(source),
"调查图只接受不含指令或回调的 Mermaid 流程描述" "调查图只接受不含指令或回调的 Mermaid 流程描述"
), ),
edges: z.array(z.object({
source: z.string().regex(/^[A-Za-z_][A-Za-z0-9_-]{0,79}$/),
target: z.string().regex(/^[A-Za-z_][A-Za-z0-9_-]{0,79}$/),
label: text.max(200).nullish()
}).strict()).max(200).nullish(),
source_mermaid: text.max(20000).nullish(),
node_refs: z node_refs: z
.array( .array(
z z
.object({ .object({
node_id: z.string().regex(/^[A-Za-z_][A-Za-z0-9_-]{0,79}$/), node_id: z.string().regex(/^[A-Za-z_][A-Za-z0-9_-]{0,79}$/),
label: text, label: text,
status: z.enum(["pending", "running", "completed", "waiting", "waiting_human", "failed", "skipped", "cancelled"]).nullish(), detail: text.max(2000).nullish(),
status: investigationNodeAnnotationReadSchema,
map_targets: z.array(investigationMapTargetSchema).max(100).optional(), map_targets: z.array(investigationMapTargetSchema).max(100).optional(),
evidence_refs: z.array(text).default([]), evidence_refs: z.array(text).default([]),
action_refs: z.array(z.string().uuid()).default([]) action_refs: z.array(z.string().uuid()).default([])
@@ -77,7 +85,8 @@ export const investigationReportSchema = z
stop_reason: text.nullish(), stop_reason: text.nullish(),
data_gaps: z.array(dataGapSchema).nullish(), data_gaps: z.array(dataGapSchema).nullish(),
diagram: investigationDiagramSchema.nullish(), diagram: investigationDiagramSchema.nullish(),
ui_blocks: reportUiBlocksSchema.optional() ui_blocks: reportUiBlocksSchema.optional(),
scada_device_ids: z.array(text).max(1000).nullish()
}) })
.strict() .strict()
.superRefine((report, ctx) => { .superRefine((report, ctx) => {
@@ -175,7 +175,7 @@ describe("operational task contract", () => {
const progress = { revision: 1, run_id: id, execution_generation: 2, published_at: time, source_session_id: "session", const progress = { revision: 1, run_id: id, execution_generation: 2, published_at: time, source_session_id: "session",
progress: { summary: "正在核对投诉时段记录", diagram: { title: "当前核查", mermaid: "flowchart TD\nA[读取记录]", node_refs: [{ node_id: "A", label: "读取记录", status: "running", map_targets: [{ source_id: "scada", feature_id: "P1" }] }] } } }; progress: { summary: "正在核对投诉时段记录", diagram: { title: "当前核查", mermaid: "flowchart TD\nA[读取记录]", node_refs: [{ node_id: "A", label: "读取记录", status: "running", map_targets: [{ source_id: "scada", feature_id: "P1" }] }] } } };
const parsed = parseOperationalTask({ ...task(), latest_plan: null, latest_report: null, latest_progress: progress }); const parsed = parseOperationalTask({ ...task(), latest_plan: null, latest_report: null, latest_progress: progress });
expect(parsed.latest_progress?.progress.diagram?.node_refs[0].status).toBe("running"); expect(parsed.latest_progress?.progress.diagram?.node_refs[0].status).toBe("reference");
expect(parsed.latest_progress?.progress.diagram?.node_refs[0].map_targets?.[0].feature_id).toBe("P1"); expect(parsed.latest_progress?.progress.diagram?.node_refs[0].map_targets?.[0].feature_id).toBe("P1");
expect(() => parseOperationalTask({ ...task(), latest_progress: { ...progress, execution_generation: 0 } })).toThrow(); expect(() => parseOperationalTask({ ...task(), latest_progress: { ...progress, execution_generation: 0 } })).toThrow();
}); });
@@ -1,6 +1,7 @@
import { useLayoutEffect, useRef, useState, type ReactNode } from "react"; import { useLayoutEffect, useRef, useState, type ReactNode } from "react";
import { Check, FileText, X } from "lucide-react"; import { Check, FileText, X } from "lucide-react";
import { AgentChartView } from "@/features/agent"; import { AgentChartView } from "@/features/agent";
import { DeferredRender } from "@/shared/ui/deferred-render";
import { formatChartDisplayText } from "@/shared/utils/date-time-text"; import { formatChartDisplayText } from "@/shared/utils/date-time-text";
import { Button } from "@/shared/ui/button"; import { Button } from "@/shared/ui/button";
import { Card, CardContent, CardHeader } from "@/shared/ui/card"; import { Card, CardContent, CardHeader } from "@/shared/ui/card";
@@ -33,6 +34,14 @@ export function InvestigationChartGroup({ group, reviewing, onCloseChart, refere
const selected = group.items.find((item) => item.command.chart_id === selectedId) ?? group.items[0]; const selected = group.items.find((item) => item.command.chart_id === selectedId) ?? group.items[0];
const multiple = group.items.length > 1; const multiple = group.items.length > 1;
const title = formatChartDisplayText(multiple ? group.title : selected.command.chart.title); const title = formatChartDisplayText(multiple ? group.title : selected.command.chart.title);
const gaps = selected.command.chart.scada?.gaps ?? [];
const missingCurrent = gaps.filter((gap) => gap.day_offset === 0 && gap.reason !== "no_scheduled_samples").reduce((sum, gap) => sum + gap.missing_count, 0);
const missingHistory = gaps.filter((gap) => gap.day_offset > 0 && gap.reason !== "no_scheduled_samples").reduce((sum, gap) => sum + gap.missing_count, 0);
const gapNotice = gaps.length ? <p role="status" aria-label="监测数据缺口" className="shrink-0 text-xs text-muted-foreground">
{[missingCurrent ? `当前缺测 ${missingCurrent} 点` : "", missingHistory ? `历史缺测 ${missingHistory} 点` : "",
gaps.some((gap) => gap.reason.startsWith("outside_frozen_")) ? "部分数据不在冻结范围内" : "",
gaps.some((gap) => gap.reason === "no_scheduled_samples") ? "窗口内无计划采样点" : ""].filter(Boolean).join(";")},已保留空槽。
</p> : null;
const objectButtons = (compact = false) => <aside aria-label="选择图表对象" const objectButtons = (compact = false) => <aside aria-label="选择图表对象"
className={compact ? "hidden min-h-0 min-w-0 overflow-auto border-l border-border pl-2 @min-[420px]:block" : "min-h-0 min-w-0 overflow-auto border-t border-border pt-3 @min-[560px]:border-t-0 @min-[560px]:border-l @min-[560px]:pl-3 @min-[560px]:pt-0"}> className={compact ? "hidden min-h-0 min-w-0 overflow-auto border-l border-border pl-2 @min-[420px]:block" : "min-h-0 min-w-0 overflow-auto border-t border-border pt-3 @min-[560px]:border-t-0 @min-[560px]:border-l @min-[560px]:pl-3 @min-[560px]:pt-0"}>
<div className={`${compact ? "mb-1" : "mb-2"} flex items-center justify-between text-[11px] text-muted-foreground`}> <div className={`${compact ? "mb-1" : "mb-2"} flex items-center justify-between text-[11px] text-muted-foreground`}>
@@ -50,6 +59,7 @@ export function InvestigationChartGroup({ group, reviewing, onCloseChart, refere
</div> </div>
</aside>; </aside>;
const content = (expanded: boolean, compact = false) => compact ? <div className="@container flex h-full min-h-0 min-w-0 flex-col gap-1"> const content = (expanded: boolean, compact = false) => compact ? <div className="@container flex h-full min-h-0 min-w-0 flex-col gap-1">
{gapNotice}
{multiple ? <div className="shrink-0 @min-[420px]:hidden"> {multiple ? <div className="shrink-0 @min-[420px]:hidden">
<Select value={selected.command.chart_id} onValueChange={setSelectedId}> <Select value={selected.command.chart_id} onValueChange={setSelectedId}>
<SelectTrigger aria-label="选择图表对象" className="h-7 text-xs"><SelectValue /></SelectTrigger> <SelectTrigger aria-label="选择图表对象" className="h-7 text-xs"><SelectValue /></SelectTrigger>
@@ -61,6 +71,7 @@ export function InvestigationChartGroup({ group, reviewing, onCloseChart, refere
{multiple ? objectButtons(true) : null} {multiple ? objectButtons(true) : null}
</div> </div>
</div> : <div className={`@container min-w-0 ${expanded ? "flex h-full min-h-0 flex-col" : ""}`}> </div> : <div className={`@container min-w-0 ${expanded ? "flex h-full min-h-0 flex-col" : ""}`}>
{gapNotice}
<div className={`grid min-w-0 grid-cols-1 gap-3 ${expanded ? multiple ? "flex-none @min-[560px]:min-h-0 @min-[560px]:flex-1" : "min-h-0 flex-1 grid-rows-1" : ""} ${multiple ? "@min-[560px]:grid-cols-[minmax(0,1fr)_176px] @min-[560px]:grid-rows-1" : ""}`}> <div className={`grid min-w-0 grid-cols-1 gap-3 ${expanded ? multiple ? "flex-none @min-[560px]:min-h-0 @min-[560px]:flex-1" : "min-h-0 flex-1 grid-rows-1" : ""} ${multiple ? "@min-[560px]:grid-cols-[minmax(0,1fr)_176px] @min-[560px]:grid-rows-1" : ""}`}>
<div className={`min-w-0 ${expanded ? `flex min-h-0 flex-col ${multiple ? "h-[480px] @min-[560px]:h-full" : "h-full"}` : ""}`}> <div className={`min-w-0 ${expanded ? `flex min-h-0 flex-col ${multiple ? "h-[480px] @min-[560px]:h-full" : "h-full"}` : ""}`}>
{multiple ? <p className="mb-1 shrink-0 text-xs font-medium tabular-nums">{selected.label}<span className="ml-2 font-normal text-muted-foreground">{selected.command.chart.x_data[0]} 至 {selected.command.chart.x_data.at(-1)}</span></p> : null} {multiple ? <p className="mb-1 shrink-0 text-xs font-medium tabular-nums">{selected.label}<span className="ml-2 font-normal text-muted-foreground">{selected.command.chart.x_data[0]} 至 {selected.command.chart.x_data.at(-1)}</span></p> : null}
@@ -82,13 +93,13 @@ export function InvestigationChartGroup({ group, reviewing, onCloseChart, refere
{tile && selected.command.evidence_refs.length ? <Popover><PopoverTrigger asChild><Button type="button" variant="ghost" size="icon-sm" aria-label={`查看图表依据 ${title}`} title="查看图表依据"><FileText size={14} aria-hidden /></Button></PopoverTrigger> {tile && selected.command.evidence_refs.length ? <Popover><PopoverTrigger asChild><Button type="button" variant="ghost" size="icon-sm" aria-label={`查看图表依据 ${title}`} title="查看图表依据"><FileText size={14} aria-hidden /></Button></PopoverTrigger>
<PopoverContent align="end" className="workbench-shadcn-surface z-[90] max-h-72 overflow-auto p-2">{references(selected.command.evidence_refs)}</PopoverContent> <PopoverContent align="end" className="workbench-shadcn-surface z-[90] max-h-72 overflow-auto p-2">{references(selected.command.evidence_refs)}</PopoverContent>
</Popover> : null} </Popover> : null}
<FloatingWindow title={title} fillContent>{() => content(true)}</FloatingWindow> <FloatingWindow title={title} fillContent>{() => <DeferredRender label={`正在加载图表 ${title}`} className="h-full min-h-0">{content(true)}</DeferredRender>}</FloatingWindow>
<Button type="button" variant="ghost" size="icon-sm" disabled={reviewing} aria-label={`关闭图表 ${title}`} <Button type="button" variant="ghost" size="icon-sm" disabled={reviewing} aria-label={`关闭图表 ${title}`}
onClick={() => group.items.forEach((item) => onCloseChart(item.command.chart_id))}><X size={14} aria-hidden /></Button> onClick={() => group.items.forEach((item) => onCloseChart(item.command.chart_id))}><X size={14} aria-hidden /></Button>
</div> </div>
</CardHeader> </CardHeader>
<CardContent className={tile ? "flex min-h-0 flex-1 flex-col px-2 pb-2 pt-0" : "px-3 pb-2 pt-0"}> <CardContent className={tile ? "flex min-h-0 flex-1 flex-col px-2 pb-2 pt-0" : "px-3 pb-2 pt-0"}>
{content(tile, tile)} <DeferredRender label={`正在加载图表 ${title}`} className={tile ? "h-full min-h-0" : undefined}>{content(tile, tile)}</DeferredRender>
</CardContent> </CardContent>
</Card>; </Card>;
} }
@@ -11,6 +11,7 @@ import type { InvestigationChartGroup } from "../utils/investigation-chart-group
import { presentationChartBlocks } from "../utils/presentation-chart-blocks"; import { presentationChartBlocks } from "../utils/presentation-chart-blocks";
import { InvestigationChartGroup as ChartGroup } from "./investigation-chart-group"; import { InvestigationChartGroup as ChartGroup } from "./investigation-chart-group";
import { ChartDropSlot, ManagedChartSlot } from "./investigation-chart-slot"; import { ChartDropSlot, ManagedChartSlot } from "./investigation-chart-slot";
import { useChartWorkspace } from "../workspace/chart-workspace-context";
type ManagedChart = { id: string; title: string } & ({ group: InvestigationChartGroup; block?: never } | { block: AnswerUiBlock; group?: never }); type ManagedChart = { id: string; title: string } & ({ group: InvestigationChartGroup; block?: never } | { block: AnswerUiBlock; group?: never });
const layouts = [{ id: "one", label: "单图布局", icon: Square }, { id: "two", label: "左右布局", icon: Columns2 }, { id: "four", label: "四宫格布局", icon: LayoutGrid }] as const; const layouts = [{ id: "one", label: "单图布局", icon: Square }, { id: "two", label: "左右布局", icon: Columns2 }, { id: "four", label: "四宫格布局", icon: LayoutGrid }] as const;
@@ -25,6 +26,7 @@ export function InvestigationChartManager({ groups, blocks, autoOpen, taskTitle,
onCloseChart: (id: string) => void; onCloseChart: (id: string) => void;
references: (ids: string[]) => ReactNode; references: (ids: string[]) => ReactNode;
}) { }) {
const dock = useChartWorkspace();
const entries = useMemo<ManagedChart[]>(() => [ const entries = useMemo<ManagedChart[]>(() => [
...groups.map((group) => ({ id: `command:${group.id}`, title: formatChartDisplayText(group.title), group })), ...groups.map((group) => ({ id: `command:${group.id}`, title: formatChartDisplayText(group.title), group })),
...presentationChartBlocks(blocks).map((block) => ({ id: `report:${block.block_id}`, title: formatChartDisplayText(String(block.spec.elements[block.spec.root].props.title)), block })) ...presentationChartBlocks(blocks).map((block) => ({ id: `report:${block.block_id}`, title: formatChartDisplayText(String(block.spec.elements[block.spec.root].props.title)), block }))
@@ -54,13 +56,13 @@ export function InvestigationChartManager({ groups, blocks, autoOpen, taskTitle,
const count = entries.length; const count = entries.length;
return <span className="inline-flex shrink-0 [&>button]:w-8 [&>button]:px-0 @min-[340px]:[&>button]:w-auto @min-[340px]:[&>button]:px-2"> return <span className="inline-flex shrink-0 [&>button]:w-8 [&>button]:px-0 @min-[340px]:[&>button]:w-auto @min-[340px]:[&>button]:px-2">
<FloatingWindow title="图表管理" navigationTitle={`${taskTitle} · 图表管理`} triggerLabel="打开图表管理" triggerContent={<span className="hidden @min-[340px]:inline">图表窗口 <span className="tabular-nums">{count}</span></span>} <FloatingWindow title="图表管理" navigationTitle={`${taskTitle} · 图表管理`} triggerLabel="打开图表管理" triggerContent={<span className="hidden @min-[340px]:inline">图表窗口 <span className="tabular-nums">{count}</span></span>}
initialSize={{ width: 1120, height: 760 }} fillContent initialSize={{ width: 1120, height: 760 }} fillContent dock={dock}
// A session gets one automatic request. Updates never revoke a user's dismissal. // A session gets one automatic request. Updates never revoke a user's dismissal.
openRequestKey={autoOpen ? "live-charts" : undefined}> openRequestKey={autoOpen ? "live-charts" : undefined}>
{() => <section ref={arrangement.containerRef} aria-label="全部图表" className="@container flex h-full min-h-0 min-w-0 flex-col gap-2"> {() => <section ref={arrangement.containerRef} aria-label="全部图表" className="@container flex h-full min-h-0 min-w-0 flex-col gap-2">
<div className="shrink-0 space-y-2 border-b border-border pb-2"> <div className="shrink-0 space-y-2 border-b border-border pb-2">
<div className="flex items-start justify-between gap-2"> <div className="flex items-start justify-between gap-2">
<div className="min-w-0 flex-1"><p className="break-words text-sm font-medium">{taskTitle}</p><p className="mt-1 text-xs text-muted-foreground">{reviewing ? "历史回看" : "当前结果"} · 拖到固定位置交换,支持单图放大</p></div> <div className="min-w-0 flex-1"><p className="break-words text-sm font-medium">{taskTitle}</p><p className="mt-1 text-xs text-muted-foreground">{reviewing ? "历史回看" : "当前结果"} · 拖动交换位置,支持单图放大</p></div>
<span className="shrink-0 text-xs text-muted-foreground tabular-nums">{count} 张图表</span> <span className="shrink-0 text-xs text-muted-foreground tabular-nums">{count} 张图表</span>
</div> </div>
<div role="toolbar" aria-label="图表管理工具" className="flex min-w-0 flex-wrap items-center gap-1 rounded-lg bg-muted/50 p-1"> <div role="toolbar" aria-label="图表管理工具" className="flex min-w-0 flex-wrap items-center gap-1 rounded-lg bg-muted/50 p-1">
@@ -1,8 +1,9 @@
import { useEffect, useLayoutEffect, useRef, useState, type ReactNode, type SVGProps } from "react"; import { cloneElement, isValidElement, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode, type SVGProps } from "react";
import { RotateCcw, ZoomIn, ZoomOut, type LucideIcon } from "lucide-react"; import { RotateCcw, ZoomIn, ZoomOut, type LucideIcon } from "lucide-react";
import { MessageResponse } from "@/shared/ai-elements/message"; import { MessageResponse } from "@/shared/ai-elements/message";
import { Button } from "@/shared/ui/button"; import { Button } from "@/shared/ui/button";
import { cn } from "@/shared/ui/cn"; import { cn } from "@/shared/ui/cn";
import { LoadingSkeleton } from "@/shared/ui/deferred-render";
import type { InvestigationDiagram, InvestigationMapTarget } from "../api/investigation-report"; import type { InvestigationDiagram, InvestigationMapTarget } from "../api/investigation-report";
import { InvestigationExpandCard } from "./investigation-expand-card"; import { InvestigationExpandCard } from "./investigation-expand-card";
import { import {
@@ -48,34 +49,62 @@ function DiagramUnavailable() {
export function InvestigationDiagramView({ export function InvestigationDiagramView({
diagram, diagram,
renderDetails, renderDetails,
running = false,
onLocate onLocate
}: { }: {
diagram: InvestigationDiagram; diagram: InvestigationDiagram;
renderDetails: (node: InvestigationDiagram["node_refs"][number]) => ReactNode; renderDetails: (node: InvestigationDiagram["node_refs"][number]) => ReactNode;
running?: boolean;
onLocate?: (targets: InvestigationMapTarget[]) => Promise<unknown> | void; onLocate?: (targets: InvestigationMapTarget[]) => Promise<unknown> | void;
}) { }) {
const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null); const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null);
const [hasRendered, setHasRendered] = useState(false);
const source = styleInvestigationDiagram(diagram);
const latestSource = useRef({ source, revision: 0 });
if (latestSource.current.source !== source) latestSource.current = { source, revision: latestSource.current.revision + 1 };
const components = useMemo(() => ({ pre: ({ children }: { children?: ReactNode }) => {
if (!isValidElement<{ className?: string; "data-block"?: string }>(children)) return children;
// Streamdown memoizes code by class and source position. A same-line edit
// needs a new revision class to update the mounted Mermaid without a reset.
return cloneElement(children, { "data-block": "true",
className: `${children.props.className ?? ""} investigation-diagram-revision-${latestSource.current.revision}` });
} }), []);
const plugins = useMemo(() => ({ mermaid: {
...investigationDiagramPlugins.mermaid,
getMermaid(config?: Parameters<typeof investigationDiagramPlugins.mermaid.getMermaid>[0]) {
const renderer = investigationDiagramPlugins.mermaid.getMermaid(config);
return { ...renderer, async render(id: string, nextSource: string) {
const result = await renderer.render(id, nextSource);
// Keep the mounted graph during refresh without allowing a late layout
// to overwrite a newer source (including an immediately cached result).
// Markdown code blocks append a newline to their text content.
if (nextSource.trimEnd() !== latestSource.current.source.trimEnd()) throw new Error("调查图示已更新,忽略旧排版结果");
return result;
} };
}
} }), []);
const diagramRoot = useRef<HTMLDivElement>(null); const diagramRoot = useRef<HTMLDivElement>(null);
const pointerStart = useRef<{ nodeId: string; x: number; y: number } | null>(null); const pointerStart = useRef<{ nodeId: string; x: number; y: number } | null>(null);
const selected = diagram.node_refs.find((node) => node.node_id === selectedNodeId); const selected = diagram.node_refs.find((node) => node.node_id === selectedNodeId);
const displayedStates = [...new Set(diagram.node_refs.map((node) => investigationNodeState(node, running)))]; const displayedStates = [...new Set(diagram.node_refs.map((node) => investigationNodeState(node)))];
if (!displayedStates.length) displayedStates.push("unknown"); if (!displayedStates.length) displayedStates.push("reference");
const [fontsReady, setFontsReady] = useState( const [fontsReady, setFontsReady] = useState(
() => typeof document === "undefined" || !document.fonts () => typeof document === "undefined" || !document.fonts
); );
useLayoutEffect(() => { useLayoutEffect(() => {
const root = diagramRoot.current; const root = diagramRoot.current;
if (!root) return; if (!root) return;
const paint = () => paintInvestigationDiagramStates(root, diagram, running); const paint = () => {
paintInvestigationDiagramStates(root, diagram);
if (root.querySelector("[data-investigation-renderer] svg, [data-investigation-renderer] [role=status]")) {
setHasRendered(true);
}
};
paint(); paint();
// Mermaid renders asynchronously. Reapply the latest snapshot when it // Mermaid renders asynchronously. Reapply the latest snapshot when it
// replaces the SVG; observing children avoids reacting to our own styles. // replaces the SVG; observing children avoids reacting to our own styles.
const observer = new MutationObserver(paint); const observer = new MutationObserver(paint);
observer.observe(root, { childList: true, subtree: true }); observer.observe(root, { childList: true, subtree: true });
return () => observer.disconnect(); return () => observer.disconnect();
}, [diagram, running]); }, [diagram]);
useEffect(() => { useEffect(() => {
if (!document.fonts) return; if (!document.fonts) return;
let active = true; let active = true;
@@ -92,11 +121,11 @@ export function InvestigationDiagramView({
const content = (close: (restoreFocus?: boolean) => void) => ( const content = (close: (restoreFocus?: boolean) => void) => (
<> <>
<p className="mt-1 text-xs leading-5 text-[var(--ink-muted)]"> <p className="mt-1 text-xs leading-5 text-[var(--ink-muted)]">
核查方向与判断分支。可放大查看,点击节点阅读关联依据。 调查路线与分支参考,标记来自最近整理,不实时同步执行状态。点击节点查看说明与依据。
</p> </p>
<div <div
ref={diagramRoot} ref={diagramRoot}
className="investigation-diagram mt-3" className="investigation-diagram relative mt-3"
onPointerDownCapture={(event) => { onPointerDownCapture={(event) => {
const node = (event.target as Element).closest?.(".node"); const node = (event.target as Element).closest?.(".node");
const ref = diagram.node_refs.find((item) => getNodeId(node) === item.node_id); const ref = diagram.node_refs.find((item) => getNodeId(node) === item.node_id);
@@ -116,11 +145,14 @@ export function InvestigationDiagramView({
if (ref) setSelectedNodeId(ref.node_id); if (ref) setSelectedNodeId(ref.node_id);
}} }}
> >
{!hasRendered ? <LoadingSkeleton label="正在加载调查流程图" className="border-0" /> : null}
<div data-investigation-renderer="" aria-hidden={!hasRendered || undefined}
className={hasRendered ? undefined : "pointer-events-none absolute inset-x-0 top-0 opacity-0"}>
{fontsReady ? ( {fontsReady ? (
<MessageResponse <MessageResponse
key={diagram.mermaid}
icons={diagramControlIcons} icons={diagramControlIcons}
plugins={investigationDiagramPlugins} plugins={plugins}
components={components}
mermaid={{ mermaid={{
errorComponent: DiagramUnavailable, errorComponent: DiagramUnavailable,
config: investigationDiagramConfig config: investigationDiagramConfig
@@ -128,10 +160,9 @@ export function InvestigationDiagramView({
controls={{ controls={{
mermaid: { fullscreen: false, download: false, copy: false, panZoom: true } mermaid: { fullscreen: false, download: false, copy: false, panZoom: true }
}} }}
>{`\`\`\`mermaid\n${styleInvestigationDiagram(diagram, running)}\n\`\`\``}</MessageResponse> >{`\`\`\`mermaid\n${source}\n\`\`\``}</MessageResponse>
) : ( ) : null}
<p className="p-4 text-xs text-[var(--ink-muted)]">正在排版调查图示。</p> </div>
)}
</div> </div>
<div <div
className="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-xs text-[var(--ink-muted)]" className="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-xs text-[var(--ink-muted)]"
@@ -165,7 +196,7 @@ export function InvestigationDiagramView({
} }
> >
{node.label} {node.label}
<span className="text-[var(--ink-muted)]"> · {investigationDiagramStates[investigationNodeState(node, running)].label}</span> <span className="text-[var(--ink-muted)]"> · {investigationDiagramStates[investigationNodeState(node)].label}</span>
{node.evidence_refs.length ? ` · ${node.evidence_refs.length} 条依据` : ""} {node.evidence_refs.length ? ` · ${node.evidence_refs.length} 条依据` : ""}
</button> </button>
))} ))}
@@ -177,7 +208,8 @@ export function InvestigationDiagramView({
aria-label={`节点详情 ${selected.label}`} aria-label={`节点详情 ${selected.label}`}
> >
<p className="text-sm font-medium text-[var(--ink)]">{selected.label}</p> <p className="text-sm font-medium text-[var(--ink)]">{selected.label}</p>
<p className="text-xs text-[var(--ink-muted)]">{investigationDiagramStates[investigationNodeState(selected, running)].label}</p> <p className="text-xs text-[var(--ink-muted)]">{investigationDiagramStates[investigationNodeState(selected)].label}</p>
{selected.detail ? <p className="whitespace-pre-wrap break-words text-xs leading-5 text-[var(--ink-muted)]">{selected.detail}</p> : null}
{renderDetails(selected)} {renderDetails(selected)}
{onLocate && selected.map_targets?.length ? <Button size="sm" variant="outline" onClick={() => { close(false); onLocate(selected.map_targets!); }}>在地图查看</Button> : null} {onLocate && selected.map_targets?.length ? <Button size="sm" variant="outline" onClick={() => { close(false); onLocate(selected.map_targets!); }}>在地图查看</Button> : null}
</div> </div>
@@ -5,6 +5,7 @@ import type { AnswerUiBlock } from "@/features/agent";
import { Badge } from "@/shared/ui/badge"; import { Badge } from "@/shared/ui/badge";
import { Button } from "@/shared/ui/button"; import { Button } from "@/shared/ui/button";
import { Card, CardContent, CardHeader } from "@/shared/ui/card"; import { Card, CardContent, CardHeader } from "@/shared/ui/card";
import { LoadingSkeleton } from "@/shared/ui/deferred-render";
import { import {
PresentationItem, PresentationItem,
PresentationViewport, PresentationViewport,
@@ -211,6 +212,9 @@ export function InvestigationPresentationPanel({
{error} {error}
</p> </p>
) : null} ) : null}
{!reviewing && !localPreview && status === "connecting" && !charts.length && !blocks.length ? (
<LoadingSkeleton label="正在加载调查展示" />
) : null}
<AnimatePresence initial={false} mode="popLayout"> <AnimatePresence initial={false} mode="popLayout">
{cameraPaused ? ( {cameraPaused ? (
<PresentationItem key="camera" immediate={immediate}> <PresentationItem key="camera" immediate={immediate}>
@@ -318,6 +322,7 @@ export function InvestigationPresentationPanel({
!overlay && !overlay &&
!blocks.length && !blocks.length &&
!records.length && !records.length &&
status !== "connecting" &&
!relatedLayers.length ? ( !relatedLayers.length ? (
<p className="text-xs leading-5 text-muted-foreground"> <p className="text-xs leading-5 text-muted-foreground">
当前没有展示结果,可切换历史动作回看地图与结果。 当前没有展示结果,可切换历史动作回看地图与结果。
@@ -181,10 +181,11 @@ export function InvestigationTaskReport({
// progress snapshot owns its whole graph, including an explicit null. A prior // progress snapshot owns its whole graph, including an explicit null. A prior
// round's final report must never hide the new round's progress. // round's final report must never hide the new round's progress.
const { currentFinalReport, previousRound, olderRevision, insufficient } = getReportPresentationState(task, snapshot); const { currentFinalReport, previousRound, olderRevision, insufficient } = getReportPresentationState(task, snapshot);
const savedDiagram = task.latest_progress?.progress.diagram;
const cumulativeDiagram = savedDiagram?.edges != null ? savedDiagram : null;
const diagram = live const diagram = live
? progress && !currentFinalReport ? progress.progress.diagram : investigationDiagram(task, snapshot) ? cumulativeDiagram ?? (progress && !currentFinalReport ? progress.progress.diagram : investigationDiagram(task, snapshot))
: selection.diagram; : selection.diagram;
const diagramRunning = Boolean(live && !currentFinalReport && progress && task.active_run?.run_id === progress.run_id && task.active_run.status === "running");
const latestAvailable = !live; const latestAvailable = !live;
const { currentInsufficient } = getReportPresentationState(task, task.latest_report); const { currentInsufficient } = getReportPresentationState(task, task.latest_report);
const pendingActions = task.actions.filter(isPendingInvestigationAction); const pendingActions = task.actions.filter(isPendingInvestigationAction);
@@ -531,7 +532,6 @@ export function InvestigationTaskReport({
<InvestigationDiagramView <InvestigationDiagramView
key={live ? `live:${task.task_id}` : `report:${snapshot?.revision}`} key={live ? `live:${task.task_id}` : `report:${snapshot?.revision}`}
diagram={diagram} diagram={diagram}
running={diagramRunning}
onLocate={onLocate} onLocate={onLocate}
renderDetails={(node) => ( renderDetails={(node) => (
<> <>
@@ -99,8 +99,9 @@ export function PresentationHistorySwitcher({
</div> </div>
{playback ? ( {playback ? (
<div className="flex min-w-0 items-center gap-2" role="group" aria-label="历史播放"> <div className="flex min-w-0 items-center gap-2" role="group" aria-label="历史播放">
<Button type="button" variant="outline" size="icon-sm" className="size-8 shrink-0" <Button type="button" variant="ghost" size="icon-sm" className="size-8 shrink-0 text-muted-foreground after:inset-0"
aria-label={playback.playing ? "暂停历史播放" : "播放历史"} aria-label={playback.playing ? "暂停历史播放" : "播放历史"}
title={playback.playing ? "暂停历史播放" : "播放历史"}
disabled={!playable.length} onClick={playback.onToggle}> disabled={!playable.length} onClick={playback.onToggle}>
{playback.playing ? <Pause size={14} aria-hidden /> : <Play size={14} aria-hidden />} {playback.playing ? <Pause size={14} aria-hidden /> : <Play size={14} aria-hidden />}
</Button> </Button>
@@ -113,8 +114,11 @@ export function PresentationHistorySwitcher({
{selectedId === null ? playable.length : playable.length ? progress + 1 : 0}/{playable.length} {selectedId === null ? playable.length : playable.length ? progress + 1 : 0}/{playable.length}
</span> </span>
<Select value={String(playback.speed)} onValueChange={(value) => playback.onSpeedChange(Number(value))}> <Select value={String(playback.speed)} onValueChange={(value) => playback.onSpeedChange(Number(value))}>
<SelectTrigger aria-label="历史播放速度" className="h-8 w-[68px] shrink-0 gap-1 px-2 text-xs"><SelectValue /></SelectTrigger> <SelectTrigger aria-label="历史播放速度"
<SelectContent position="popper" className="workbench-shadcn-surface z-[90]"> className="form-field-inset h-8 w-[54px] shrink-0 justify-center gap-1 border-0 px-1.5 text-xs tabular-nums text-muted-foreground shadow-none hover:bg-muted hover:text-foreground data-[state=open]:bg-muted data-[state=open]:text-foreground [&>svg]:size-3">
<SelectValue />
</SelectTrigger>
<SelectContent position="popper" align="end" sideOffset={4} className="workbench-shadcn-surface z-[90] min-w-[72px]">
{[0.5, 1, 2].map((speed) => <SelectItem key={speed} value={String(speed)} className="text-xs">{speed}×</SelectItem>)} {[0.5, 1, 2].map((speed) => <SelectItem key={speed} value={String(speed)} className="text-xs">{speed}×</SelectItem>)}
</SelectContent> </SelectContent>
</Select> </Select>
@@ -216,18 +216,7 @@ export function ConditionDetailPanel({
); );
return ( return (
<AnimatePresence initial={false} mode="wait"> <div key={detailKey} className="relative h-full min-h-0">{content}</div>
<motion.div
key={detailKey}
className="relative h-full min-h-0"
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -6 }}
transition={{ duration: 0.22, ease: [0.22, 1, 0.36, 1] }}
>
{content}
</motion.div>
</AnimatePresence>
); );
} }
@@ -4,6 +4,8 @@ import {
ChevronRight, ChevronRight,
ClipboardList, ClipboardList,
History, History,
Maximize2,
Minimize2,
RefreshCw, RefreshCw,
X, X,
XCircle XCircle
@@ -61,6 +63,7 @@ const CONDITION_CONTROL_SURFACE_CLASS_NAME =
const MINIMUM_REFRESH_FEEDBACK_MS = 3_000; const MINIMUM_REFRESH_FEEDBACK_MS = 3_000;
export type ScheduledConditionFeedPresentation = export type ScheduledConditionFeedPresentation =
| "workspace"
| "desktop-dock" | "desktop-dock"
| "desktop-floating" | "desktop-floating"
| "mobile-sheet"; | "mobile-sheet";
@@ -82,6 +85,7 @@ type ScheduledConditionFeedProps = {
onSelectedConditionChange?: (conditionId: string | null) => void; onSelectedConditionChange?: (conditionId: string | null) => void;
onExpandAgent: () => void; onExpandAgent: () => void;
onClose?: () => void; onClose?: () => void;
reserveAgentRail?: boolean;
onLoadHistorySession: (sessionId: string) => void | Promise<void>; onLoadHistorySession: (sessionId: string) => void | Promise<void>;
onSubmitPrompt: (prompt: string) => void | Promise<void>; onSubmitPrompt: (prompt: string) => void | Promise<void>;
onOpenTaskCollaboration?: (taskId: string, discussion?: InvestigationDiscussion) => Promise<void>; onOpenTaskCollaboration?: (taskId: string, discussion?: InvestigationDiscussion) => Promise<void>;
@@ -124,6 +128,7 @@ export function ScheduledConditionFeed({
onSelectedConditionChange, onSelectedConditionChange,
onExpandAgent, onExpandAgent,
onClose, onClose,
reserveAgentRail = false,
onLoadHistorySession, onLoadHistorySession,
onSubmitPrompt, onSubmitPrompt,
onOpenTaskCollaboration, onOpenTaskCollaboration,
@@ -160,8 +165,10 @@ export function ScheduledConditionFeed({
const desktopDock = presentation === "desktop-dock"; const desktopDock = presentation === "desktop-dock";
const compactPresentation = mobileSheet || desktopDock; const compactPresentation = mobileSheet || desktopDock;
const desktopFloating = presentation === "desktop-floating"; const desktopFloating = presentation === "desktop-floating";
const workspace = presentation === "workspace";
const expanded = controlledExpanded ?? uncontrolledExpanded; const expanded = controlledExpanded ?? uncontrolledExpanded;
const selectedConditionId = controlledSelectedConditionId ?? uncontrolledSelectedConditionId; const selectedConditionId = controlledSelectedConditionId === undefined
? uncontrolledSelectedConditionId : controlledSelectedConditionId;
const conditionsByCategory = useMemo( const conditionsByCategory = useMemo(
() => groupConditionsByTaskCategory(conditions), () => groupConditionsByTaskCategory(conditions),
[conditions] [conditions]
@@ -219,17 +226,14 @@ export function ScheduledConditionFeed({
: `定时 ${conditionsByCategory.scheduled.length} · 调查 ${conditionsByCategory.investigation.length} · 预约 ${conditionsByCategory.appointment.length}`; : `定时 ${conditionsByCategory.scheduled.length} · 调查 ${conditionsByCategory.investigation.length} · 预约 ${conditionsByCategory.appointment.length}`;
const selectedCondition = const selectedCondition =
timelineConditions.find((condition) => condition.id === selectedConditionId) ?? timelineConditions.find((condition) => condition.id === selectedConditionId) ??
timelineConditions[0] ??
null; null;
const showCompactDetail = expanded && Boolean(selectedCondition);
const focusConditionId = focusRequest?.conditionId; const focusConditionId = focusRequest?.conditionId;
const focusRequestId = focusRequest?.requestId; const focusRequestId = focusRequest?.requestId;
const [focusedAction, setFocusedAction] = useState<{ conditionId: string; actionId: string } | null>(null); const [focusedAction, setFocusedAction] = useState<{ conditionId: string; actionId: string } | null>(null);
const updateExpanded = useCallback( const updateExpanded = useCallback(
(nextExpanded: boolean) => { (nextExpanded: boolean) => {
if (controlledExpanded === undefined) { if (controlledExpanded === undefined) setUncontrolledExpanded(nextExpanded);
setUncontrolledExpanded(nextExpanded);
}
onExpandedChange?.(nextExpanded); onExpandedChange?.(nextExpanded);
}, },
[controlledExpanded, onExpandedChange] [controlledExpanded, onExpandedChange]
@@ -256,10 +260,7 @@ export function ScheduledConditionFeed({
}, [taskFilter, taskFilterOptions]); }, [taskFilter, taskFilterOptions]);
useEffect(() => { useEffect(() => {
if (!expanded) { if (!expanded) return;
return;
}
// A controlled task selection survives panel remounts and detail-loading windows. // A controlled task selection survives panel remounts and detail-loading windows.
const selected = conditions.find((condition) => condition.id === controlledSelectedConditionId); const selected = conditions.find((condition) => condition.id === controlledSelectedConditionId);
if (selected) { if (selected) {
@@ -308,9 +309,6 @@ export function ScheduledConditionFeed({
function handleToggleExpanded() { function handleToggleExpanded() {
updateExpanded(!expanded); updateExpanded(!expanded);
updateSelectedConditionId(
selectedConditionId ?? timelineConditions[0]?.id ?? null
);
} }
function handleTaskCategoryChange(nextCategory: WorkbenchTaskCategory) { function handleTaskCategoryChange(nextCategory: WorkbenchTaskCategory) {
@@ -318,9 +316,7 @@ export function ScheduledConditionFeed({
setTaskFilter(CONDITION_FILTER_ALL); setTaskFilter(CONDITION_FILTER_ALL);
setStatusFilter(CONDITION_FILTER_ALL); setStatusFilter(CONDITION_FILTER_ALL);
setRetainedScheduledCondition(null); setRetainedScheduledCondition(null);
updateSelectedConditionId( updateSelectedConditionId(null);
sortConditionsNewestFirst(conditionsByCategory[nextCategory])[0]?.id ?? null
);
} }
async function handleRefresh() { async function handleRefresh() {
@@ -360,9 +356,7 @@ export function ScheduledConditionFeed({
); );
} }
updateSelectedConditionId(conditionId); updateSelectedConditionId(conditionId);
if (!expanded) { if (!expanded) updateExpanded(true);
updateExpanded(true);
}
} }
function handleContinueConversation(condition: ScheduledConditionItem, discussion?: InvestigationDiscussion) { function handleContinueConversation(condition: ScheduledConditionItem, discussion?: InvestigationDiscussion) {
@@ -427,22 +421,20 @@ export function ScheduledConditionFeed({
<section <section
aria-label="工况任务" aria-label="工况任务"
data-task-category={taskCategory} data-task-category={taskCategory}
data-presentation={presentation}
aria-hidden={!visible} aria-hidden={!visible}
className={cn( className={cn(
"scheduled-feed-panel-shell pointer-events-auto overflow-hidden p-3 motion-reduce:transition-none", "scheduled-feed-panel-shell pointer-events-auto overflow-hidden p-3 motion-reduce:transition-none",
visible ? "scheduled-feed-shell-enter" : "scheduled-feed-shell-exit", visible ? "scheduled-feed-shell-enter" : "scheduled-feed-shell-exit",
mobileSheet workspace
? "surface-dock flex h-full w-full min-w-0 flex-col border-l border-[var(--surface-divider)] pb-16"
: mobileSheet
? "scheduled-feed-mobile flex h-full w-full max-w-none flex-col border-0 bg-transparent shadow-none" ? "scheduled-feed-mobile flex h-full w-full max-w-none flex-col border-0 bg-transparent shadow-none"
: cn( : cn(
MAP_TOOL_PANEL_SURFACE_CLASS_NAME, MAP_TOOL_PANEL_SURFACE_CLASS_NAME,
"max-w-[calc(100vw-7rem)]", "max-w-[calc(100vw-7rem)]",
desktopFloating desktopFloating
? cn( ? cn("rounded-2xl", expanded ? "h-[calc(100dvh-8rem)]" : "max-h-[calc(100dvh-8rem)]")
"rounded-2xl",
expanded
? "h-[calc(100dvh-8rem)]"
: "max-h-[calc(100dvh-8rem)]"
)
: "h-full rounded-l-2xl rounded-r-none", : "h-full rounded-l-2xl rounded-r-none",
expanded && !desktopDock expanded && !desktopDock
? "scheduled-feed-panel-expanded flex flex-col" ? "scheduled-feed-panel-expanded flex flex-col"
@@ -453,7 +445,8 @@ export function ScheduledConditionFeed({
<header <header
className={cn( className={cn(
"flex items-center gap-2.5 px-2.5 py-2", "flex items-center gap-2.5 px-2.5 py-2",
CONDITION_CONTROL_SURFACE_CLASS_NAME CONDITION_CONTROL_SURFACE_CLASS_NAME,
workspace && reserveAgentRail && "pl-20"
)} )}
> >
<span <span
@@ -486,18 +479,13 @@ export function ScheduledConditionFeed({
) : null} ) : null}
<button <button
type="button" type="button"
data-condition-dock-toggle
aria-expanded={expanded} aria-expanded={expanded}
title={expanded ? "收起工况任务" : "展开工况任务"}
onClick={handleToggleExpanded} onClick={handleToggleExpanded}
className={cn( className="grid h-8 w-8 shrink-0 place-items-center rounded-lg text-[var(--ink-muted)] transition-colors hover:bg-[var(--action-soft)] hover:text-[var(--action-blue-hover)] active:scale-95 focus-visible:outline-2 focus-visible:outline-[var(--action-blue)]"
"grid h-8 w-8 shrink-0 place-items-center text-[var(--ink-muted)] transition hover:bg-[var(--action-soft)] hover:text-[var(--action-blue-hover)]",
"rounded-lg"
)}
> >
<ChevronDown {expanded ? <Minimize2 size={17} aria-hidden="true" /> : <Maximize2 size={17} aria-hidden="true" />}
size={17}
aria-hidden="true"
className={cn("transition-transform duration-150", expanded && "rotate-180")}
/>
<span className="sr-only">{expanded ? "收起工况任务" : "展开工况任务"}</span> <span className="sr-only">{expanded ? "收起工况任务" : "展开工况任务"}</span>
</button> </button>
{mobileSheet && onClose ? ( {mobileSheet && onClose ? (
@@ -513,8 +501,7 @@ export function ScheduledConditionFeed({
) : null} ) : null}
</header> </header>
{expanded ? ( {expanded ? <TaskCategorySwitch
<TaskCategorySwitch
activeCategory={taskCategory} activeCategory={taskCategory}
counts={{ counts={{
scheduled: conditionsByCategory.scheduled.length, scheduled: conditionsByCategory.scheduled.length,
@@ -522,29 +509,22 @@ export function ScheduledConditionFeed({
appointment: conditionsByCategory.appointment.length appointment: conditionsByCategory.appointment.length
}} }}
onChange={handleTaskCategoryChange} onChange={handleTaskCategoryChange}
/> /> : null}
) : null}
<div <div
className={cn( className={cn(
"scheduled-feed-layout mt-3 grid min-h-0", "scheduled-feed-layout mt-3 grid min-h-0",
compactPresentation compactPresentation
? "flex flex-1" ? "flex flex-1"
: expanded : expanded ? "scheduled-feed-layout-expanded flex-1" : "scheduled-feed-layout-collapsed"
? "scheduled-feed-layout-expanded flex-1"
: "scheduled-feed-layout-collapsed"
)} )}
> >
<div <div
className={cn( className={cn(
"relative min-h-0 min-w-0 overflow-hidden", "relative min-h-0 min-w-0 overflow-hidden",
compactPresentation compactPresentation
? expanded ? showCompactDetail ? "scheduled-feed-detail-enter h-full w-full" : "hidden"
? "scheduled-feed-detail-enter h-full w-full" : expanded ? "scheduled-feed-detail-enter h-full" : "pointer-events-none opacity-0"
: "hidden"
: expanded
? "scheduled-feed-detail-enter h-full"
: "pointer-events-none opacity-0"
)} )}
aria-hidden={!expanded} aria-hidden={!expanded}
> >
@@ -571,12 +551,19 @@ export function ScheduledConditionFeed({
onReportViewed={onReportViewed} onReportViewed={onReportViewed}
focusActionId={focusedAction?.conditionId === selectedConditionId ? focusedAction.actionId : undefined} focusActionId={focusedAction?.conditionId === selectedConditionId ? focusedAction.actionId : undefined}
/> />
) : expanded && !compactPresentation ? (
<div className={cn("flex h-full items-center justify-center p-6 text-center", CONDITION_CONTENT_SURFACE_CLASS_NAME)}>
<div>
<p className="text-sm font-medium text-slate-700">请选择工况任务</p>
<p className="mt-1 text-xs text-[var(--ink-muted)]">从右侧列表选择条目后查看详情。</p>
</div>
</div>
) : null} ) : null}
</div> </div>
<div <div
className={cn( className={cn(
"min-h-0 min-w-0 overflow-hidden", "min-h-0 min-w-0 overflow-hidden",
compactPresentation && (expanded ? "hidden" : "h-full w-full") compactPresentation && (showCompactDetail ? "hidden" : "h-full w-full")
)} )}
> >
<ConditionTimelinePanel <ConditionTimelinePanel
@@ -720,9 +707,7 @@ function ConditionTimelinePanel({
"flex min-h-0 flex-col overflow-hidden p-2.5", "flex min-h-0 flex-col overflow-hidden p-2.5",
presentation === "mobile-sheet" presentation === "mobile-sheet"
? "h-full max-h-none" ? "h-full max-h-none"
: expanded : expanded ? "h-full max-h-none" : "h-[420px] max-h-[420px]",
? "h-full max-h-none"
: "h-[420px] max-h-[420px]",
CONDITION_CONTENT_SURFACE_CLASS_NAME CONDITION_CONTENT_SURFACE_CLASS_NAME
)} )}
> >
@@ -0,0 +1,37 @@
import { useLayoutEffect, useRef, useState, type ReactNode, type RefObject } from "react";
import { createPortal } from "react-dom";
/** Move the live panel without resetting filters, report state or pending input. */
export function ScheduledConditionWorkspace({
docked, dockTarget, hidden, children
}: {
docked: boolean;
dockTarget: RefObject<HTMLDivElement | null>;
hidden: boolean;
children: ReactNode;
}) {
const floating = useRef<HTMLDivElement>(null);
const restoreFocus = useRef(false);
const [host] = useState(() => {
const element = document.createElement("div");
element.className = "h-full min-h-0 min-w-0";
return element;
});
useLayoutEffect(() => {
const target = docked ? dockTarget.current : floating.current;
target?.append(host);
// Moving the host can drop keyboard focus. Restore the corresponding control.
if (restoreFocus.current && !hidden) host.querySelector<HTMLButtonElement>("[data-condition-dock-toggle]")?.focus({ preventScroll: true });
return () => {
restoreFocus.current = host.contains(document.activeElement);
host.remove();
};
}, [dockTarget, docked, hidden, host]);
return <>
<div ref={floating}
className="pointer-events-none absolute bottom-[calc(var(--workbench-timeline-height)+1.25rem)] right-16 top-24 z-50 hidden lg:block 2xl:[--workbench-condition-width:var(--workbench-condition-width-wide)]"
style={hidden || docked ? { display: "none" } : undefined} />
{createPortal(children, host)}
</>;
}
@@ -1,6 +1,6 @@
import { act, cleanup, renderHook, waitFor } from "@testing-library/react"; import { act, cleanup, renderHook, waitFor } from "@testing-library/react";
import { afterEach, expect, it, vi } from "vitest"; import { afterEach, expect, it, vi } from "vitest";
import type { RefObject } from "react"; import { useLayoutEffect, type RefObject } from "react";
import type { Map as MapLibreMap } from "maplibre-gl"; import type { Map as MapLibreMap } from "maplibre-gl";
import type { WorkbenchMapController } from "../map/workbench-map-controller"; import type { WorkbenchMapController } from "../map/workbench-map-controller";
import type { WorkbenchSyncState } from "./use-workbench-sync"; import type { WorkbenchSyncState } from "./use-workbench-sync";
@@ -15,6 +15,21 @@ const options = { scope: "preview" as const, enabled: false, task: null, project
afterEach(() => { cleanup(); vi.useRealTimers(); }); afterEach(() => { cleanup(); vi.useRealTimers(); });
it("never commits a previous task's display under the newly selected task scope", async () => {
const commits: Array<{ scope: string; records: unknown[] }> = [];
const { result, rerender } = renderHook(({ scopeId }) => {
const presentation = useInvestigationPresentation({ ...options, scopeId });
useLayoutEffect(() => {
commits.push({ scope: scopeId, records: presentation.records });
});
return presentation;
}, { initialProps: { scopeId: "task-a" } });
await act(() => result.current.runPreview({ blocks: [], records: [{ value: "old task" }], commands: [] }));
expect(result.current.records).toEqual([{ value: "old task" }]);
rerender({ scopeId: "task-b" });
expect(commits.filter((entry) => entry.scope === "task-b").every((entry) => entry.records.length === 0)).toBe(true);
});
it("restores the last successful result when an unfinished display is aborted", async () => { it("restores the last successful result when an unfinished display is aborted", async () => {
const { result } = renderHook(() => useInvestigationPresentation(options)); const { result } = renderHook(() => useInvestigationPresentation(options));
await act(() => result.current.runPreview({ blocks: [], records: [{ value: "saved" }], commands: [] })); await act(() => result.current.runPreview({ blocks: [], records: [{ value: "saved" }], commands: [] }));
@@ -92,13 +92,15 @@ async function waitForChart(
const panel = document.querySelector<HTMLElement>(`[data-presentation-scope="${scope}"]`); const panel = document.querySelector<HTMLElement>(`[data-presentation-scope="${scope}"]`);
// A deliberate collapse defers rendering, rather than failing a valid command. // A deliberate collapse defers rendering, rather than failing a valid command.
if (panel?.dataset.investigationCollapsed === "true") return; if (panel?.dataset.investigationCollapsed === "true") return;
const mapHidden = Boolean(panel?.closest('[aria-hidden="true"]'));
const element = [ const element = [
...(panel?.querySelectorAll<HTMLElement>("[data-investigation-chart]") ?? []) ...(panel?.querySelectorAll<HTMLElement>("[data-investigation-chart]") ?? [])
].find( ].find(
(item) => item.dataset.investigationChart === chartId && !item.closest('[aria-hidden="true"]') (item) => item.dataset.investigationChart === chartId && (mapHidden || !item.closest('[aria-hidden="true"]'))
); );
if (element && element.getBoundingClientRect().height > 0) { if (element && (mapHidden || element.getBoundingClientRect().height > 0)) {
const viewport = panel?.querySelector<HTMLElement>("[data-investigation-content]"); // A focused workspace deliberately hides the map's inline chart copy.
const viewport = mapHidden ? null : panel?.querySelector<HTMLElement>("[data-investigation-content]");
if (viewport) { if (viewport) {
const plot = element.querySelector("svg[role=img]") ?? element; const plot = element.querySelector("svg[role=img]") ?? element;
const overflow = const overflow =
@@ -120,16 +122,25 @@ export function useInvestigationPresentation(options: Options) {
const valuesRef = useRef(options); const valuesRef = useRef(options);
valuesRef.current = options; valuesRef.current = options;
const storeRef = useRef(new PresentationViewHistory()); const storeRef = useRef(new PresentationViewHistory());
const displayScope = useRef(windowScope);
if (displayScope.current !== windowScope) {
displayScope.current = windowScope;
// The first render of a new task must not re-key the previous task's charts.
// Keep saved history; effects below still own cancellation and map cleanup.
storeRef.current.select(null);
storeRef.current.update(emptyPresentationView());
}
const [, refresh] = useState(0); const [, refresh] = useState(0);
const publish = useCallback(() => refresh((value) => value + 1), []); const publish = useCallback(() => refresh((value) => value + 1), []);
const [localPreview, setLocalPreview] = useState(false); const [localPreview, setLocalPreview] = useState(false);
const localPreviewRef = useRef(false); const localPreviewRef = useRef(false);
const [cameraPaused, setCameraPaused] = useState(false); const [cameraPaused, setCameraPaused] = useState(false);
const cameraPausedRef = useRef(false); const cameraPausedRef = useRef(false);
const [status, setStatus] = useState< const [connection, setConnection] = useState<{
"connecting" | "live" | "history" | "disconnected" | "error" scope: string;
>("disconnected"); status: "connecting" | "live" | "history" | "disconnected" | "error";
const [error, setError] = useState<string | null>(null); error: string | null;
}>({ scope: windowScope, status: "disconnected", error: null });
const [playbackSpeed, setPlaybackSpeed] = useState(1); const [playbackSpeed, setPlaybackSpeed] = useState(1);
const [activity, setActivity] = useState<InvestigationPresentationActivity[]>([]); const [activity, setActivity] = useState<InvestigationPresentationActivity[]>([]);
const activityIdRef = useRef(0); const activityIdRef = useRef(0);
@@ -289,18 +300,19 @@ export function useInvestigationPresentation(options: Options) {
update: apply, update: apply,
rendering: () => store.selectedId === null, rendering: () => store.selectedId === null,
cameraAllowed: () => !cameraPausedRef.current, cameraAllowed: () => !cameraPausedRef.current,
waitForChart: (chartId, nextSignal) => waitForChart: (chartId, nextSignal) => {
waitForChart( requestChartWindow(origin);
return waitForChart(
chartId, chartId,
nextSignal, nextSignal,
valuesRef.current.scope ?? "investigation", valuesRef.current.scope ?? "investigation",
() => store.selectedId === null () => store.selectedId === null
), );
},
frame frame
}) })
); );
signal.throwIfAborted(); signal.throwIfAborted();
if (command.action === "open_chart") requestChartWindow(origin);
if (historyId !== null) store.finish(historyId, "completed", undefined, actionSnapshot, pendingEntry); if (historyId !== null) store.finish(historyId, "completed", undefined, actionSnapshot, pendingEntry);
publish(); publish();
setActivity((current) => setActivity((current) =>
@@ -409,8 +421,9 @@ export function useInvestigationPresentation(options: Options) {
clear, clear,
stopPulse: () => scene.stopPulse(), stopPulse: () => scene.stopPulse(),
onStatus: (next, message) => { onStatus: (next, message) => {
setStatus(!valuesRef.current.enabled && next === "live" ? "history" : next); setConnection({ scope: windowScope,
setError(message ?? null); status: !valuesRef.current.enabled && next === "live" ? "history" : next,
error: message ?? null });
}, },
execute: async (command, signal, event) => { execute: async (command, signal, event) => {
await executeCommand(command, signal, "live", event); await executeCommand(command, signal, "live", event);
@@ -434,7 +447,8 @@ export function useInvestigationPresentation(options: Options) {
publish, publish,
scene, scene,
subscribe, subscribe,
taskId taskId,
windowScope
]); ]);
useEffect( useEffect(
() => () => { () => () => {
@@ -576,8 +590,8 @@ export function useInvestigationPresentation(options: Options) {
evidence: visible.evidence, evidence: visible.evidence,
highlightLayers: visible.highlightLayers, highlightLayers: visible.highlightLayers,
cameraPaused: reviewing ? false : cameraPaused, cameraPaused: reviewing ? false : cameraPaused,
status, status: connection.scope === windowScope ? connection.status : taskId ? "connecting" as const : "disconnected" as const,
error, error: connection.scope === windowScope ? connection.error : null,
activity, activity,
localPreview, localPreview,
hasHistory: taskEntries.length > 0, hasHistory: taskEntries.length > 0,
@@ -50,10 +50,12 @@ describe("workbench responsive layout", () => {
act(() => result.current.handleConditionExpandedChange(true)); act(() => result.current.handleConditionExpandedChange(true));
expect(result.current.conditionFeedExpanded).toBe(true); expect(result.current.conditionFeedExpanded).toBe(true);
expect(result.current.conditionFeedDocked).toBe(true);
expect(collapseAgentPanel).toHaveBeenCalledOnce(); expect(collapseAgentPanel).toHaveBeenCalledOnce();
act(() => result.current.handleConditionExpandedChange(false)); act(() => result.current.handleConditionExpandedChange(false));
expect(result.current.conditionFeedExpanded).toBe(false); expect(result.current.conditionFeedExpanded).toBe(false);
expect(result.current.conditionFeedDocked).toBe(false);
expect(expandAgentPanel).toHaveBeenCalledOnce(); expect(expandAgentPanel).toHaveBeenCalledOnce();
}); });
@@ -76,6 +78,10 @@ describe("workbench responsive layout", () => {
expect(result.current.mobileSheetSnap).toBe("half"); expect(result.current.mobileSheetSnap).toBe("half");
expect(onClearActiveTool).toHaveBeenCalledOnce(); expect(onClearActiveTool).toHaveBeenCalledOnce();
act(() => result.current.handleConditionExpandedChange(true));
expect(result.current.conditionFeedExpanded).toBe(true);
expect(result.current.conditionFeedDocked).toBe(false);
act(() => result.current.toggleConditionFeedForViewport()); act(() => result.current.toggleConditionFeedForViewport());
expect(result.current.mobileSheet).toBeNull(); expect(result.current.mobileSheet).toBeNull();
@@ -1,6 +1,7 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import type { MobileWorkbenchSheetSnap } from "../components/mobile-workbench-sheet"; import type { MobileWorkbenchSheetSnap } from "../components/mobile-workbench-sheet";
import { WORKBENCH_LAYOUT } from "../layout/workbench-layout"; import { WORKBENCH_LAYOUT } from "../layout/workbench-layout";
import { CONDITION_PANE_MIN_WIDTH, type ArtifactRequestedView } from "../workspace/workspace-model";
const CONDITION_FEED_EXIT_MS = 170; const CONDITION_FEED_EXIT_MS = 170;
const CONDITION_FEED_EXPANDED_MIN_WIDTH = 1440; const CONDITION_FEED_EXPANDED_MIN_WIDTH = 1440;
@@ -33,6 +34,8 @@ export function useWorkbenchResponsiveLayout({
const [conditionFeedVisible, setConditionFeedVisible] = useState(false); const [conditionFeedVisible, setConditionFeedVisible] = useState(false);
const [conditionFeedMounted, setConditionFeedMounted] = useState(false); const [conditionFeedMounted, setConditionFeedMounted] = useState(false);
const [conditionFeedExpanded, setConditionFeedExpanded] = useState(false); const [conditionFeedExpanded, setConditionFeedExpanded] = useState(false);
const [conditionFeedDocked, setConditionFeedDocked] = useState(false);
const [conditionView, setConditionView] = useState<ArtifactRequestedView>("map_split");
const [mobileSheet, setMobileSheet] = useState<WorkbenchMobileSheet>(null); const [mobileSheet, setMobileSheet] = useState<WorkbenchMobileSheet>(null);
const [mobileSheetSnap, setMobileSheetSnap] = useState<MobileWorkbenchSheetSnap>("half"); const [mobileSheetSnap, setMobileSheetSnap] = useState<MobileWorkbenchSheetSnap>("half");
const [agentCollapsedForCondition, setAgentCollapsedForCondition] = useState(false); const [agentCollapsedForCondition, setAgentCollapsedForCondition] = useState(false);
@@ -87,7 +90,11 @@ export function useWorkbenchResponsiveLayout({
function openAgentPanelForViewport() { function openAgentPanelForViewport() {
if (isLargeScreen) { if (isLargeScreen) {
if (conditionFeedExpanded && viewportWidth < CONDITION_FEED_EXPANDED_MIN_WIDTH) { if (conditionFeedDocked && viewportWidth - agentPanelWidth < CONDITION_PANE_MIN_WIDTH) {
setConditionFeedDocked(false);
setConditionFeedExpanded(false);
}
if (!conditionFeedDocked && conditionFeedExpanded && viewportWidth < CONDITION_FEED_EXPANDED_MIN_WIDTH) {
setConditionFeedExpanded(false); setConditionFeedExpanded(false);
setAgentCollapsedForCondition(false); setAgentCollapsedForCondition(false);
} }
@@ -100,10 +107,11 @@ export function useWorkbenchResponsiveLayout({
} }
function handleConditionExpandedChange(nextExpanded: boolean) { function handleConditionExpandedChange(nextExpanded: boolean) {
if (nextExpanded && isLargeScreen && viewportWidth < CONDITION_FEED_EXPANDED_MIN_WIDTH) { if (isLargeScreen) {
setAgentCollapsedForCondition(agentPanelOpen); setConditionFeedDocked(nextExpanded);
collapseAgentPanel(); if (nextExpanded) setConditionView("map_split");
} else if (!nextExpanded && agentCollapsedForCondition) { }
if (!nextExpanded && agentCollapsedForCondition) {
setAgentCollapsedForCondition(false); setAgentCollapsedForCondition(false);
expandAgentPanel(); expandAgentPanel();
} }
@@ -111,22 +119,22 @@ export function useWorkbenchResponsiveLayout({
} }
useEffect(() => { useEffect(() => {
if (!isLargeScreen || shouldShowConditionFeed || !conditionFeedExpanded) { if (isLargeScreen && conditionFeedDocked && shouldShowConditionFeed && agentPanelOpen
return; && viewportWidth - agentPanelWidth < CONDITION_PANE_MIN_WIDTH) {
setAgentCollapsedForCondition(true);
collapseAgentPanel();
} }
}, [agentPanelOpen, agentPanelWidth, collapseAgentPanel, conditionFeedDocked, isLargeScreen, shouldShowConditionFeed, viewportWidth]);
useEffect(() => {
if (!isLargeScreen || shouldShowConditionFeed || !conditionFeedExpanded) return;
setConditionFeedExpanded(false); setConditionFeedExpanded(false);
setConditionFeedDocked(false);
if (agentCollapsedForCondition) { if (agentCollapsedForCondition) {
setAgentCollapsedForCondition(false); setAgentCollapsedForCondition(false);
expandAgentPanel(); expandAgentPanel();
} }
}, [ }, [agentCollapsedForCondition, conditionFeedExpanded, expandAgentPanel, isLargeScreen, shouldShowConditionFeed]);
agentCollapsedForCondition,
conditionFeedExpanded,
expandAgentPanel,
isLargeScreen,
shouldShowConditionFeed
]);
function toggleConditionFeedForViewport() { function toggleConditionFeedForViewport() {
onClearActiveTool(); onClearActiveTool();
@@ -161,14 +169,16 @@ export function useWorkbenchResponsiveLayout({
} }
const leftPanelOpen = isLargeScreen && agentPanelOpen; const leftPanelOpen = isLargeScreen && agentPanelOpen;
const rightPanelOpen = isLargeScreen && (devPanelOpen || shouldShowConditionFeed); const rightPanelOpen = isLargeScreen && (devPanelOpen || (shouldShowConditionFeed && !conditionFeedDocked));
const rightPanelExpanded = const rightPanelExpanded =
isLargeScreen && shouldShowConditionFeed && conditionFeedExpanded && !devPanelOpen; isLargeScreen && shouldShowConditionFeed && !conditionFeedDocked && conditionFeedExpanded && !devPanelOpen;
return { return {
agentPanelWidth, agentPanelWidth,
closeMobileSheet, closeMobileSheet,
conditionFeedExpanded, conditionFeedExpanded,
conditionFeedDocked,
conditionView,
conditionFeedMounted, conditionFeedMounted,
handleConditionExpandedChange, handleConditionExpandedChange,
isLargeScreen, isLargeScreen,
@@ -181,6 +191,7 @@ export function useWorkbenchResponsiveLayout({
rightPanelExpanded, rightPanelExpanded,
rightPanelOpen, rightPanelOpen,
setAgentPanelWidth, setAgentPanelWidth,
setConditionView,
setMobileSheetSnap, setMobileSheetSnap,
shouldShowConditionFeed, shouldShowConditionFeed,
toggleConditionFeedForViewport, toggleConditionFeedForViewport,
+70 -12
View File
@@ -44,6 +44,11 @@ import { InvestigationPresentationPanel } from "./components/investigation-prese
import { MobileWorkbenchSheet } from "./components/mobile-workbench-sheet"; import { MobileWorkbenchSheet } from "./components/mobile-workbench-sheet";
import { FeaturePopover } from "./components/feature-popover"; import { FeaturePopover } from "./components/feature-popover";
import { ScheduledConditionFeed } from "./components/scheduled-condition-feed"; import { ScheduledConditionFeed } from "./components/scheduled-condition-feed";
import { ScheduledConditionWorkspace } from "./components/scheduled-condition-workspace";
import { CONDITION_MAP_SPLIT_MIN_WIDTH } from "./workspace/workspace-model";
import { ARTIFACT_MAP_SPLIT_MIN_WIDTH, ARTIFACT_PANE_MIN_WIDTH } from "./workspace/workspace-model";
import { ChartWorkspaceProvider } from "./workspace/chart-workspace-provider";
import { useChartWorkspace } from "./workspace/chart-workspace-context";
import type { InvestigationDiscussion } from "./api/investigation-report"; import type { InvestigationDiscussion } from "./api/investigation-report";
import { fetchOperationalTaskRuns, type TaskExecutionHistoryTarget } from "./api/operational-task-client"; import { fetchOperationalTaskRuns, type TaskExecutionHistoryTarget } from "./api/operational-task-client";
import { WorkbenchAgentPanels } from "./components/workbench-agent-panels"; import { WorkbenchAgentPanels } from "./components/workbench-agent-panels";
@@ -136,7 +141,7 @@ type MapWorkbenchPageProps = {
projectSelection?: WorkbenchProjectSelection; projectSelection?: WorkbenchProjectSelection;
}; };
export function MapWorkbenchPage(props: MapWorkbenchPageProps) { export function MapWorkbenchPage(props: MapWorkbenchPageProps) {
return <ReadingWorkspaceProvider><MapWorkbenchContent {...props} /></ReadingWorkspaceProvider>; return <ReadingWorkspaceProvider><ChartWorkspaceProvider><MapWorkbenchContent {...props} /></ChartWorkspaceProvider></ReadingWorkspaceProvider>;
} }
function MapWorkbenchContent({ function MapWorkbenchContent({
user = WORKBENCH_USER, user = WORKBENCH_USER,
@@ -145,6 +150,7 @@ function MapWorkbenchContent({
projectSelection projectSelection
}: MapWorkbenchPageProps) { }: MapWorkbenchPageProps) {
const readingWorkspace = useReadingWorkspace(); const readingWorkspace = useReadingWorkspace();
const chartWorkspace = useChartWorkspace()!;
const hasMapboxToken = Boolean(env.TJWATER_MAPBOX_ACCESS_TOKEN); const hasMapboxToken = Boolean(env.TJWATER_MAPBOX_ACCESS_TOKEN);
const hasTiandituToken = Boolean(env.TJWATER_TIANDITU_TOKEN); const hasTiandituToken = Boolean(env.TJWATER_TIANDITU_TOKEN);
const hasOnlineBasemap = hasMapboxToken || hasTiandituToken; const hasOnlineBasemap = hasMapboxToken || hasTiandituToken;
@@ -269,8 +275,10 @@ function MapWorkbenchContent({
agentPanelWidth, agentPanelWidth,
closeMobileSheet, closeMobileSheet,
conditionFeedExpanded, conditionFeedExpanded,
conditionFeedDocked,
conditionView,
conditionFeedMounted, conditionFeedMounted,
handleConditionExpandedChange, handleConditionExpandedChange: updateConditionExpanded,
isLargeScreen, isLargeScreen,
leftPanelOpen, leftPanelOpen,
mobileSheet, mobileSheet,
@@ -281,6 +289,7 @@ function MapWorkbenchContent({
rightPanelExpanded, rightPanelExpanded,
rightPanelOpen, rightPanelOpen,
setAgentPanelWidth, setAgentPanelWidth,
setConditionView,
setMobileSheetSnap, setMobileSheetSnap,
shouldShowConditionFeed, shouldShowConditionFeed,
toggleConditionFeedForViewport, toggleConditionFeedForViewport,
@@ -295,6 +304,20 @@ function MapWorkbenchContent({
}); });
const currentAgentWidth = leftPanelOpen ? agentPanelWidth : WORKBENCH_LAYOUT.collapsedAgentWidth; const currentAgentWidth = leftPanelOpen ? agentPanelWidth : WORKBENCH_LAYOUT.collapsedAgentWidth;
const businessWorkspaceWidth = Math.max(0, viewportWidth - currentAgentWidth); const businessWorkspaceWidth = Math.max(0, viewportWidth - currentAgentWidth);
const chartCollapsedAgent = useRef(false);
useEffect(() => {
if (isLargeScreen && chartWorkspace.activeId && leftPanelOpen && businessWorkspaceWidth < ARTIFACT_PANE_MIN_WIDTH) {
chartCollapsedAgent.current = true;
collapseAgentPanel();
} else if (!chartWorkspace.activeId && chartCollapsedAgent.current) {
chartCollapsedAgent.current = false;
expandAgentPanel();
}
}, [businessWorkspaceWidth, chartWorkspace.activeId, collapseAgentPanel, expandAgentPanel, isLargeScreen, leftPanelOpen]);
const handleConditionExpandedChange = useCallback((expanded: boolean) => {
if (expanded) chartWorkspace.deactivate();
updateConditionExpanded(expanded);
}, [chartWorkspace, updateConditionExpanded]);
const artifactWorkspace = useArtifactWorkspace(businessWorkspaceWidth); const artifactWorkspace = useArtifactWorkspace(businessWorkspaceWidth);
const artifactActive = artifactWorkspace.activeArtifact !== null; const artifactActive = artifactWorkspace.activeArtifact !== null;
const activeSpatialOverlay = artifactWorkspace.activeArtifact?.spatialOverlay ?? null; const activeSpatialOverlay = artifactWorkspace.activeArtifact?.spatialOverlay ?? null;
@@ -356,6 +379,7 @@ function MapWorkbenchContent({
}, [activeArtifactHasSpatialView, artifactWorkspace.activeArtifact?.id]); }, [activeArtifactHasSpatialView, artifactWorkspace.activeArtifact?.id]);
function openAgentWorkspaceForViewport() { function openAgentWorkspaceForViewport() {
if (!isLargeScreen || (chartWorkspace.activeId && viewportWidth - agentPanelWidth < ARTIFACT_PANE_MIN_WIDTH)) chartWorkspace.deactivate();
openAgentPanelForViewport(); openAgentPanelForViewport();
} }
@@ -417,10 +441,24 @@ function MapWorkbenchContent({
} }
function openConditionWorkspaceForViewport() { function openConditionWorkspaceForViewport() {
chartWorkspace.deactivate();
setSelectedConditionId(null);
setConditionFocusRequest(null);
openConditionFeedForViewport(); openConditionFeedForViewport();
} }
function toggleConditionWorkspaceForViewport() { function toggleConditionWorkspaceForViewport() {
if (chartWorkspace.activeId) {
chartWorkspace.deactivate();
if (!shouldShowConditionFeed) openConditionWorkspaceForViewport();
else if (!isLargeScreen) openConditionFeedForViewport();
handleConditionExpandedChange(true);
return;
}
if (isLargeScreen ? !shouldShowConditionFeed : mobileSheet !== "condition") {
setSelectedConditionId(null);
setConditionFocusRequest(null);
}
toggleConditionFeedForViewport(); toggleConditionFeedForViewport();
} }
@@ -517,8 +555,15 @@ function MapWorkbenchContent({
: { ...padding, bottom: Math.max(padding.bottom, 420) }); : { ...padding, bottom: Math.max(padding.bottom, 420) });
} }
}); });
function handleLocateInvestigationTargets(targets: InvestigationMapTarget[]) { function showMapForLocation() {
if (readingWorkspace?.active) readingWorkspace.setView(businessWorkspaceWidth >= 960 ? "map_split" : "map_only"); if (readingWorkspace?.active) readingWorkspace.setView(businessWorkspaceWidth >= 960 ? "map_split" : "map_only");
else if (chartWorkspace.activeId) chartWorkspace.setView(isLargeScreen && businessWorkspaceWidth >= ARTIFACT_MAP_SPLIT_MIN_WIDTH ? "map_split" : "map_only");
else if (isLargeScreen && conditionFeedDocked) {
setConditionView(businessWorkspaceWidth >= CONDITION_MAP_SPLIT_MIN_WIDTH ? "map_split" : "map_only");
}
}
function handleLocateInvestigationTargets(targets: InvestigationMapTarget[]) {
showMapForLocation();
return presentation.locateTargets(targets).then(() => true).catch((error) => { return presentation.locateTargets(targets).then(() => true).catch((error) => {
showMapNotice({ tone: "warning", title: "关联要素暂不可定位", message: error instanceof Error ? error.message : "地图当前不可用" }); showMapNotice({ tone: "warning", title: "关联要素暂不可定位", message: error instanceof Error ? error.message : "地图当前不可用" });
return false; return false;
@@ -838,6 +883,7 @@ function MapWorkbenchContent({
function handleOpenLatestAnalysis() { function handleOpenLatestAnalysis() {
if (!latestAnalysisArtifact || !latestAnalysisAvailable) return; if (!latestAnalysisArtifact || !latestAnalysisAvailable) return;
chartWorkspace.deactivate();
artifactWorkspace.openArtifact(latestAnalysisArtifact); artifactWorkspace.openArtifact(latestAnalysisArtifact);
} }
@@ -1285,7 +1331,7 @@ function MapWorkbenchContent({
} : undefined, } : undefined,
onSubmitPrompt: agent.submitPrompt, onSubmitPrompt: agent.submitPrompt,
onLocateAnswerFeatures: async (target) => { onLocateAnswerFeatures: async (target) => {
if (readingWorkspace?.active) readingWorkspace.setView(businessWorkspaceWidth >= 960 ? "map_split" : "map_only"); showMapForLocation();
return chatPresentation.executeCommand({ action: "locate_features", layer: target.layer, feature_ids: target.feature_ids }, new AbortController().signal, "chat"); return chatPresentation.executeCommand({ action: "locate_features", layer: target.layer, feature_ids: target.feature_ids }, new AbortController().signal, "chat");
}, },
onStopPrompt: agent.sessionPurpose === "task_execution" ? undefined : agent.stopPrompt, onStopPrompt: agent.sessionPurpose === "task_execution" ? undefined : agent.stopPrompt,
@@ -1294,8 +1340,10 @@ function MapWorkbenchContent({
onRejectQuestion: agent.sessionPurpose === "task_execution" ? undefined : agent.rejectQuestion onRejectQuestion: agent.sessionPurpose === "task_execution" ? undefined : agent.rejectQuestion
}; };
const conditionFeedSuspended = devPanelOpen || peripheralSamplePanelOpen || Boolean(readingWorkspace?.active); const conditionFeedSuspended = devPanelOpen || peripheralSamplePanelOpen || Boolean(readingWorkspace?.active) || Boolean(chartWorkspace.activeId);
const mobileSheetSuspended = Boolean(readingWorkspace?.active) || (mobileSheet === "condition" && peripheralSamplePanelOpen); const conditionDockTarget = useRef<HTMLDivElement>(null);
const conditionDockActive = isLargeScreen && conditionFeedDocked && shouldShowConditionFeed && !conditionFeedSuspended;
const mobileSheetSuspended = Boolean(chartWorkspace.activeId) || Boolean(readingWorkspace?.active) || (mobileSheet === "condition" && peripheralSamplePanelOpen);
return ( return (
<main <main
@@ -1369,6 +1417,7 @@ function MapWorkbenchContent({
onClose={() => setAnalysisResultsPanelOpen(false)} onClose={() => setAnalysisResultsPanelOpen(false)}
getAccessToken={getAccessToken} getAccessToken={getAccessToken}
onOpenArtifact={(artifact) => { onOpenArtifact={(artifact) => {
chartWorkspace.deactivate();
artifactWorkspace.openArtifact(artifact); artifactWorkspace.openArtifact(artifact);
setAnalysisResultsPanelOpen(false); setAnalysisResultsPanelOpen(false);
}} }}
@@ -1400,10 +1449,18 @@ function MapWorkbenchContent({
viewportWidth={viewportWidth} viewportWidth={viewportWidth}
conditionExpanded={rightPanelExpanded} conditionExpanded={rightPanelExpanded}
onCollapsePanel={agent.collapsePanel} onCollapsePanel={agent.collapsePanel}
onExpandPanel={agent.expandPanel} onExpandPanel={openAgentWorkspaceForViewport}
onWidthCommit={setAgentPanelWidth} onWidthCommit={setAgentPanelWidth}
> >
<WorkbenchMainFrame <WorkbenchMainFrame
chartDock={{ window: chartWorkspace, splitAvailable: isLargeScreen && businessWorkspaceWidth >= ARTIFACT_MAP_SPLIT_MIN_WIDTH, reserveAgentRail: !leftPanelOpen }}
conditionDock={{
active: conditionDockActive,
splitAvailable: businessWorkspaceWidth >= CONDITION_MAP_SPLIT_MIN_WIDTH,
target: conditionDockTarget,
view: conditionView,
onSetView: setConditionView
}}
activeArtifact={artifactWorkspace.activeArtifact} activeArtifact={artifactWorkspace.activeArtifact}
pendingArtifact={artifactWorkspace.pendingArtifact} pendingArtifact={artifactWorkspace.pendingArtifact}
surfaceMode={artifactWorkspace.surfaceMode} surfaceMode={artifactWorkspace.surfaceMode}
@@ -1523,9 +1580,10 @@ function MapWorkbenchContent({
</WorkbenchAgentPanels> </WorkbenchAgentPanels>
{conditionFeedMounted ? ( {conditionFeedMounted ? (
<div className="pointer-events-none absolute bottom-[calc(var(--workbench-timeline-height)+1.25rem)] right-16 top-24 z-50 hidden lg:block 2xl:[--workbench-condition-width:var(--workbench-condition-width-wide)]" style={conditionFeedSuspended ? { display: "none" } : undefined}> <ScheduledConditionWorkspace docked={conditionDockActive} dockTarget={conditionDockTarget} hidden={conditionFeedSuspended}>
<ScheduledConditionFeed <ScheduledConditionFeed
presentation="desktop-floating" presentation={conditionDockActive ? "workspace" : "desktop-floating"}
reserveAgentRail={!leftPanelOpen && (conditionView === "focus" || businessWorkspaceWidth < CONDITION_MAP_SPLIT_MIN_WIDTH)}
conditions={scheduledConditions} conditions={scheduledConditions}
dataSource={runtimeDataSource} dataSource={runtimeDataSource}
workOrderDataSource={workOrderDataSource} workOrderDataSource={workOrderDataSource}
@@ -1558,7 +1616,7 @@ function MapWorkbenchContent({
onReportViewed={operationalTasks.markReportRead} onReportViewed={operationalTasks.markReportRead}
onRefresh={workbenchSync.refresh} onRefresh={workbenchSync.refresh}
/> />
</div> </ScheduledConditionWorkspace>
) : null} ) : null}
{devPanelEnabled && devPanelOpen ? ( {devPanelEnabled && devPanelOpen ? (
@@ -1638,7 +1696,7 @@ function MapWorkbenchContent({
type="button" type="button"
aria-label="打开 Agent 面板" aria-label="打开 Agent 面板"
title="打开 Agent 面板" title="打开 Agent 面板"
onClick={openAgentPanelForViewport} onClick={openAgentWorkspaceForViewport}
className="acrylic-control grid h-11 w-11 shrink-0 place-items-center rounded-xl border text-violet-700" className="acrylic-control grid h-11 w-11 shrink-0 place-items-center rounded-xl border text-violet-700"
> >
<AgentPersona className="pointer-events-none h-10 w-10" state={agent.personaState} /> <AgentPersona className="pointer-events-none h-10 w-10" state={agent.personaState} />
@@ -1654,7 +1712,7 @@ function MapWorkbenchContent({
type="button" type="button"
aria-label="打开工况任务" aria-label="打开工况任务"
title="打开工况任务" title="打开工况任务"
onClick={toggleConditionFeedForViewport} onClick={toggleConditionWorkspaceForViewport}
className="acrylic-control grid h-11 w-11 shrink-0 place-items-center rounded-xl border text-blue-700" className="acrylic-control grid h-11 w-11 shrink-0 place-items-center rounded-xl border text-blue-700"
> >
<CalendarClock size={20} aria-hidden="true" /> <CalendarClock size={20} aria-hidden="true" />
@@ -21,6 +21,32 @@ const legacyComparison = (id: string, metric = "压力", unit = "m", date = "202
}; };
describe("investigation comparison groups", () => { describe("investigation comparison groups", () => {
it("groups all four bound devices even when titles differ and one device has no observations", () => {
const ids = ["486033", "542017", "541061", "524529"];
const charts = ids.map((id, index) => {
const command = comparison(id, "流量", "m3/h");
command.chart.title = `不同的标题 ${index}`;
command.chart.scada = { role: "comparison", metric: "flow", unit: "m3/h",
window_start: "2026-07-16T05:00:00+08:00", window_end: "2026-07-16T08:00:00+08:00" };
command.chart.series.forEach((series, offset) => {
series.device_id = id;
series.day_offset = offset;
series.name = offset ? "历史" : "当前";
if (id === "524529") { series.data = [null, null]; series.sample_times = [null, null]; }
});
return command;
});
const groups = groupInvestigationCharts(charts);
expect(groups).toHaveLength(1);
expect(groups[0].items.map((item) => item.label)).toEqual(ids);
expect(groups[0].id).toBe(groupInvestigationCharts([charts[3]])[0].id);
expect(groups[0].items[3].command).toBe(charts[3]);
charts[3].chart.scada!.unit = "m³/h";
charts[3].chart.scada!.window_start = "2026-07-15T21:00:00Z";
charts[3].chart.scada!.window_end = "2026-07-16T00:00:00Z";
expect(groupInvestigationCharts(charts)).toHaveLength(1);
});
it("groups pressure objects and pipe flow objects separately without changing data or evidence", () => { it("groups pressure objects and pipe flow objects separately without changing data or evidence", () => {
const charts = [comparison("170486"), comparison("175618"), comparison("542017", "管流", "m³/h"), comparison("486033", "管流", "m³/h")]; const charts = [comparison("170486"), comparison("175618"), comparison("542017", "管流", "m³/h"), comparison("486033", "管流", "m³/h")];
const groups = groupInvestigationCharts(charts); const groups = groupInvestigationCharts(charts);
@@ -44,10 +44,19 @@ export function groupInvestigationCharts(charts: InvestigationChart[]): Investig
const groups = new Map<string, InvestigationChartGroup>(); const groups = new Map<string, InvestigationChartGroup>();
for (const command of charts) { for (const command of charts) {
const { chart } = command; const { chart } = command;
const scada = chart.scada;
const boundDevices = new Set(chart.series.map((series) => series.device_id));
const typed = scada?.role === "comparison" && boundDevices.size === 1 &&
!boundDevices.has(undefined) && chart.series.every((series) => series.day_offset !== undefined);
const match = /^(?:(压力|流量)测点\s+|测点\s+)?([A-Za-z0-9][A-Za-z0-9_.-]*)\s+(.+)$/.exec(chart.title); const match = /^(?:(压力|流量)测点\s+|测点\s+)?([A-Za-z0-9][A-Za-z0-9_.-]*)\s+(.+)$/.exec(chart.title);
const object = match ? { id: match[2], title: `${match[1] ?? ""}${match[3]}` } : null; const object = typed ? {
const comparable = object && chart.series.some((series) => series.type === "scatter") && matchesObjectSeries(command, object.id); id: chart.series[0].device_id!,
const id = comparable ? JSON.stringify([ title: `${scada.metric === "pressure" ? "压力" : "流量"}当前曲线与前七天同期对比(${scada.unit})`
} : match ? { id: match[2], title: `${match[1] ?? ""}${match[3]}` } : null;
const comparable = object && (typed || chart.series.some((series) => series.type === "scatter") && matchesObjectSeries(command, object.id));
const id = typed ? JSON.stringify(["scada-comparison", scada.metric, scada.unit.replace("³", "3").replace(/\s/g, "").toLowerCase(),
Date.parse(scada.window_start), Date.parse(scada.window_end), scada.value_field ?? "monitored_value", chart.x_data
]) : comparable ? JSON.stringify([
object.title, chart.chart_type, chart.x_axis_name, chart.y_axis_name, chart.x_data, object.title, chart.chart_type, chart.x_axis_name, chart.y_axis_name, chart.x_data,
chart.series.filter((series) => series.type !== "scatter").map((series) => [ chart.series.filter((series) => series.type !== "scatter").map((series) => [
series.name.slice(object.id.length).trim(), series.sample_times ?? null series.name.slice(object.id.length).trim(), series.sample_times ?? null
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import { investigationDiagramSchema } from "../api/investigation-report";
import { styleInvestigationDiagram } from "./investigation-diagram-style";
describe("investigation diagrams as process references", () => {
it("reads a legacy running node as a neutral reference without suggesting live execution", () => {
const diagram = investigationDiagramSchema.parse({ title: "流程参考", mermaid: "flowchart TD\nA[核查]",
node_refs: [{ node_id: "A", label: "核查", status: "running" }] });
const styled = styleInvestigationDiagram(diagram);
expect(styled).toContain("class A tjReference;");
expect(diagram.node_refs[0].status).toBe("reference");
expect(styled).not.toContain("class A tjRunning;");
expect(styled).not.toContain("class A tjRecordedRunning;");
});
it("distinguishes a recorded finding from task completion and preserves failed paths", () => {
const diagram = investigationDiagramSchema.parse({ title: "调查脉络", mermaid: "flowchart TD\nA[原尝试] --> B[替代路线]",
node_refs: [{ node_id: "A", label: "原尝试", status: "failed", detail: "接口超时" },
{ node_id: "B", label: "替代路线", status: "recorded" }] });
const styled = styleInvestigationDiagram(diagram);
expect(styled).toContain("class A tjFailed;");
expect(styled).toContain("class B tjRecorded;");
expect(styled.startsWith(diagram.mermaid)).toBe(true);
expect(diagram.node_refs[0].detail).toBe("接口超时");
});
});
@@ -70,54 +70,79 @@ describe("investigation SVG post-processing", () => {
}); });
describe("investigation diagram presentation", () => { describe("investigation diagram presentation", () => {
it("applies recorded states to bare class-attached declarations and ignores partial IDs", () => { it("styles explicit reference annotations and ignores partial node ids", () => {
const styled = styleInvestigationDiagram({ title: "核查", mermaid: "flowchart TD\nQUERY:::tjAction --> REVIEW:::tjHuman", const styled = styleInvestigationDiagram({ title: "核查", mermaid: "flowchart TD\nQUERY:::tjAction --> REVIEW:::tjHuman",
node_refs: [{ node_id: "QUERY", label: "核查", status: "running", evidence_refs: [], action_refs: [] }, node_refs: [{ node_id: "QUERY", label: "核查", status: "reference", evidence_refs: [], action_refs: [] },
{ node_id: "REVIEW", label: "复核", status: "waiting_human", evidence_refs: [], action_refs: [] }, { node_id: "REVIEW", label: "复核", status: "needs_input", evidence_refs: [], action_refs: [] },
{ node_id: "QUER", label: "无效引用", status: "completed", evidence_refs: [], action_refs: [] }] }, true); { node_id: "QUER", label: "无效引用", status: "recorded", evidence_refs: [], action_refs: [] }] });
expect(styled).toContain("class QUERY tjRunning;"); expect(styled).toContain("class QUERY tjReference;");
expect(styled).toContain("class REVIEW tjWaitingHuman;"); expect(styled).toContain("class REVIEW tjNeedsInput;");
expect(styled).not.toContain("class QUER "); expect(styled).not.toContain("class QUER ");
}); });
it("retains source relationships and only styles declared business references", () => { it("keeps relationships and evidence neutral until a result is explicitly annotated", () => {
const source = 'flowchart TD\nA["核查"] --> B;\nB -->|资料不足| C["记录缺口"]'; const source = 'flowchart TD\nA["核查"] --> B;\nB -->|资料不足| C["记录缺口"]';
const styled = styleInvestigationDiagram({ const styled = styleInvestigationDiagram({ title: "调查脉络", mermaid: source, node_refs: [
title: "调查脉络",
mermaid: source,
node_refs: [
{ node_id: "B", label: "判断", evidence_refs: ["e1"], action_refs: [] }, { node_id: "B", label: "判断", evidence_refs: ["e1"], action_refs: [] },
{ node_id: "missing", label: "历史引用", evidence_refs: ["e2"], action_refs: [] } { node_id: "missing", label: "历史引用", evidence_refs: ["e2"], action_refs: [] }
] ] });
});
expect(styled.startsWith(source)).toBe(true); expect(styled.startsWith(source)).toBe(true);
expect(styled).toContain("class B tjUnknown;"); expect(styled).toContain("class B tjReference;");
expect(styled).not.toContain("class missing "); expect(styled).not.toContain("class missing ");
expect(styled).not.toContain("class B tjCompleted;"); expect(styled).not.toContain("class B tjRecorded;");
expect(styled).not.toContain("class B tjRunning;");
}); });
it("uses blue only for an explicitly running current diagram, and neutralizes historical running classes", () => { it("neutralizes old running classes even when the legacy source supplied them", () => {
const diagram = { title: "当前核查", mermaid: "flowchart TD\nA[查询]:::tjAgent --> B[判断]:::tjDecision", const styled = styleInvestigationDiagram({ title: "旧图参考", mermaid: "flowchart TD\nA[查询]:::tjRunning",
node_refs: [{ node_id: "A", label: "查询", status: "running" as const, evidence_refs: ["e1"], action_refs: [] }] }; node_refs: [] });
expect(styleInvestigationDiagram(diagram, true)).toContain("class A tjRunning;"); expect(styled).toContain("classDef tjRunning fill:#FFFFFF");
expect(styleInvestigationDiagram(diagram, true)).not.toContain("class A tjEvidence;"); expect(styled).not.toContain("#4263C7");
const historical = styleInvestigationDiagram(diagram, false);
expect(historical).not.toContain("class A tjRunning;");
expect(historical).toContain("class A tjRecordedRunning;");
expect(historical).not.toContain("#4263C7");
}); });
it.each([ it.each([
["pending", "tjPending"], ["running", "tjRunning"], ["reference", "tjReference"], ["recorded", "tjRecorded"], ["needs_input", "tjNeedsInput"],
["completed", "tjCompleted"], ["waiting", "tjWaiting"], ["failed", "tjFailed"], ["not_taken", "tjNotTaken"]
["waiting_human", "tjWaitingHuman"], ["failed", "tjFailed"], ] as const)("displays the saved %s annotation without inferring other node results", (status, className) => {
["skipped", "tjSkipped"], ["cancelled", "tjCancelled"]
] as const)("uses the explicit %s state even when evidence or actions are linked", (status, className) => {
const source = "flowchart LR\nA[核查] --> B[下一步]"; const source = "flowchart LR\nA[核查] --> B[下一步]";
const styled = styleInvestigationDiagram({ title: "核查", mermaid: source, const styled = styleInvestigationDiagram({ title: "核查", mermaid: source,
node_refs: [{ node_id: "A", label: "核查", status, evidence_refs: ["e1"], action_refs: ["a1"] }] }, true); node_refs: [{ node_id: "A", label: "核查", status, evidence_refs: ["e1"], action_refs: ["a1"] }] });
expect(styled.startsWith(source)).toBe(true); expect(styled.startsWith(source)).toBe(true);
expect(styled).toContain(`class A ${className};`); expect(styled).toContain(`class A ${className};`);
expect(styled).not.toContain("class A tjEvidence;"); expect(styled).not.toContain("class A tjEvidence;");
expect(styled).not.toContain("class A tjAction;"); expect(styled).not.toContain("class A tjAction;");
expect(styled).not.toContain("class B tjCompleted;"); expect(styled).not.toContain("class B tjRecorded;");
});
});
describe("investigation diagram render reuse", () => {
it("shares an in-flight layout and rebinds SVG ids for each mounted copy", async () => {
const renderSvg = vi.fn(async (id: string) => ({ svg:
`<svg xmlns="http://www.w3.org/2000/svg" id="${id}"><defs><marker id="${id}-arrow"/></defs><path marker-end="url(#${id}-arrow)"/></svg>` }));
vi.spyOn(mermaid, "getMermaid").mockReturnValue({ initialize: vi.fn(), render: renderSvg });
const first = investigationDiagramPlugins.mermaid.getMermaid({ theme: "base" }).render("first-render", "flowchart TD\nA[核查]");
const second = investigationDiagramPlugins.mermaid.getMermaid({ theme: "base" }).render("second-render", "flowchart TD\nA[核查]");
const [original, reused] = await Promise.all([first, second]);
expect(renderSvg).toHaveBeenCalledTimes(1);
expect(original.svg).toContain('id="first-render"');
expect(reused.svg).toContain('id="second-render"');
expect(reused.svg).toContain("url(#second-render-arrow)");
expect(reused.svg).not.toContain("first-render");
await investigationDiagramPlugins.mermaid.getMermaid({ theme: "dark" }).render("dark-render", "flowchart TD\nA[核查]");
expect(renderSvg).toHaveBeenCalledTimes(2);
const configured = investigationDiagramPlugins.mermaid.getMermaid({ theme: "base" });
configured.initialize({ theme: "forest" });
await configured.render("configured-render", "flowchart TD\nA[核查]");
expect(renderSvg).toHaveBeenCalledTimes(3);
});
it("retries failed rendering and bounds retained layouts", async () => {
const renderSvg = vi.fn().mockRejectedValueOnce(new Error("render failed")).mockResolvedValue({
svg: '<svg xmlns="http://www.w3.org/2000/svg"/>'
});
vi.spyOn(mermaid, "getMermaid").mockReturnValue({ initialize: vi.fn(), render: renderSvg });
const renderer = investigationDiagramPlugins.mermaid.getMermaid();
await expect(renderer.render("first", "flowchart TD\nA[核查]")).rejects.toThrow("render failed");
await renderer.render("retry", "flowchart TD\nA[核查]");
expect(renderSvg).toHaveBeenCalledTimes(2);
for (let index = 0; index < 32; index++) await renderer.render(`next-${index}`, `flowchart TD\nN${index}[步骤]`);
await renderer.render("after-eviction", "flowchart TD\nA[核查]");
expect(renderSvg).toHaveBeenCalledTimes(35);
}); });
}); });
@@ -1,5 +1,6 @@
import { mermaid, type MermaidConfig } from "@streamdown/mermaid"; import { mermaid, type MermaidConfig } from "@streamdown/mermaid";
import type { InvestigationDiagram } from "../api/investigation-report"; import type { InvestigationDiagram } from "../api/investigation-report";
import { normalizeInvestigationNodeAnnotation } from "../api/investigation-node-state";
export const INVESTIGATION_DIAGRAM_FONT = export const INVESTIGATION_DIAGRAM_FONT =
'"Noto Sans SC Variable", "PingFang SC", "Microsoft YaHei", sans-serif'; '"Noto Sans SC Variable", "PingFang SC", "Microsoft YaHei", sans-serif';
@@ -51,15 +52,41 @@ export const investigationDiagramConfig: MermaidConfig = {
` `
}; };
type DiagramResult = { svg: string };
type CachedDiagram = { id: string; result: Promise<DiagramResult> };
const diagramCaches = new WeakMap<object, Map<string, CachedDiagram>>();
/** Keep group captions beside crossing links, without moving nodes or changing edges. */ /** Keep group captions beside crossing links, without moving nodes or changing edges. */
export const investigationDiagramPlugins = { export const investigationDiagramPlugins = {
mermaid: { mermaid: {
...mermaid, ...mermaid,
getMermaid(config?: MermaidConfig) { getMermaid(config?: MermaidConfig) {
const renderer = mermaid.getMermaid(config); const renderer = mermaid.getMermaid(config);
let effectiveConfig = config;
const cache = diagramCaches.get(renderer) ?? new Map<string, CachedDiagram>();
diagramCaches.set(renderer, cache);
return { return {
initialize: (nextConfig: MermaidConfig) => renderer.initialize(nextConfig), initialize: (nextConfig: MermaidConfig) => { effectiveConfig = nextConfig; renderer.initialize(nextConfig); },
async render(id: string, source: string) { async render(id: string, source: string) {
const key = JSON.stringify([effectiveConfig, source]);
const cached = cache.get(key);
if (cached) {
cache.delete(key);
cache.set(key, cached);
const result = await cached.result;
// SVG markers and CSS must belong to this mounted instance.
return { ...result, svg: result.svg.replaceAll(cached.id, id) };
}
const result = renderSvg(id, source, effectiveConfig);
const entry = { id, result };
cache.set(key, entry);
if (cache.size > 32) cache.delete(cache.keys().next().value!);
try { return await result; }
catch (error) { if (cache.get(key) === entry) cache.delete(key); throw error; }
}
};
async function renderSvg(id: string, source: string, renderConfig?: MermaidConfig) {
// Streamdown's two-argument renderer uses Mermaid's temporary #d{id} // Streamdown's two-argument renderer uses Mermaid's temporary #d{id}
// under body. It must remain measurable, but never enter page flow. // under body. It must remain measurable, but never enter page flow.
// Scope the rule to this render, including fullscreen and error paths. // Scope the rule to this render, including fullscreen and error paths.
@@ -91,7 +118,7 @@ export const investigationDiagramPlugins = {
if (!Number.isFinite(x) || !Number.isFinite(y)) return; if (!Number.isFinite(x) || !Number.isFinite(y)) return;
caption.setAttribute( caption.setAttribute(
"transform", "transform",
`translate(${x + 18}, ${y + (config?.flowchart?.subGraphTitleMargin?.top ?? 12)})` `translate(${x + 18}, ${y + (renderConfig?.flowchart?.subGraphTitleMargin?.top ?? 12)})`
); );
// Mermaid paints crossing edges after clusters; keep captions above those edges. // Mermaid paints crossing edges after clusters; keep captions above those edges.
const clusters = cluster.parentElement; const clusters = cluster.parentElement;
@@ -104,30 +131,26 @@ export const investigationDiagramPlugins = {
return result; return result;
} }
} }
};
} }
} }
}; };
export const investigationDiagramStates = { export const investigationDiagramStates = {
pending: { className: "tjPending", label: "尚未开始", fill: "#F6F8FC", stroke: "#A5B5CC", color: "#475976", width: 1.5, dash: "0" }, reference: { className: "tjReference", label: "参考步骤", fill: "#FFFFFF", stroke: "#CCD6E5", color: "#536784", width: 1.4, dash: "0" },
running: { className: "tjRunning", label: "正在执行", fill: "#E8F0FF", stroke: "#4263C7", color: "#284574", width: 2.5, dash: "0" }, recorded: { className: "tjRecorded", label: "已有结果", fill: "#EDF7F4", stroke: "#6B9E8B", color: "#2D5E4E", width: 1.8, dash: "0" },
completed: { className: "tjCompleted", label: "已完成", fill: "#EDF7F4", stroke: "#6B9E8B", color: "#2D5E4E", width: 1.8, dash: "0" }, needs_input: { className: "tjNeedsInput", label: "待补充条件", fill: "#FFFBEA", stroke: "#C8AC60", color: "#78531B", width: 1.8, dash: "6 3" },
waiting: { className: "tjWaiting", label: "等待依赖 / 外部结果", fill: "#FFFBEA", stroke: "#C8AC60", color: "#78531B", width: 1.8, dash: "6 3" }, failed: { className: "tjFailed", label: "尝试失败", fill: "#FEF2F2", stroke: "#D96C75", color: "#922C3E", width: 2, dash: "0" },
waiting_human: { className: "tjWaitingHuman", label: "等待人工处理", fill: "#FFF6E8", stroke: "#C4A168", color: "#735018", width: 2, dash: "0" }, not_taken: { className: "tjNotTaken", label: "未采用路线", fill: "#F6F8FC", stroke: "#A5B5CC", color: "#64748B", width: 1.5, dash: "8 4" }
failed: { className: "tjFailed", label: "执行失败", fill: "#FEF2F2", stroke: "#D96C75", color: "#922C3E", width: 2, dash: "0" },
skipped: { className: "tjSkipped", label: "已跳过", fill: "#F6F8FC", stroke: "#A5B5CC", color: "#64748B", width: 1.5, dash: "8 4" },
cancelled: { className: "tjCancelled", label: "已取消", fill: "#F1F5F9", stroke: "#94A3B8", color: "#64748B", width: 1.5, dash: "2 3" },
recorded_running: { className: "tjRecordedRunning", label: "记录时执行中", fill: "#F6F8FC", stroke: "#A5B5CC", color: "#475976", width: 1.5, dash: "6 3" },
unknown: { className: "tjUnknown", label: "未标注状态", fill: "#FFFFFF", stroke: "#CCD6E5", color: "#536784", width: 1.4, dash: "0" }
} as const; } as const;
export function investigationNodeState( const legacyClasses = {
node: InvestigationDiagram["node_refs"][number], tjPending: "reference", tjRunning: "reference", tjRecordedRunning: "reference", tjUnknown: "reference",
running = false tjCompleted: "recorded", tjWaiting: "needs_input", tjWaitingHuman: "needs_input",
): keyof typeof investigationDiagramStates { tjSkipped: "not_taken", tjCancelled: "not_taken"
if (node.status === "running" && !running) return "recorded_running"; } as const;
return node.status ?? "unknown";
export function investigationNodeState(node: InvestigationDiagram["node_refs"][number]): keyof typeof investigationDiagramStates {
return normalizeInvestigationNodeAnnotation(node.status);
} }
function nodeStyle(state: typeof investigationDiagramStates[keyof typeof investigationDiagramStates]) { function nodeStyle(state: typeof investigationDiagramStates[keyof typeof investigationDiagramStates]) {
@@ -138,12 +161,12 @@ export const investigationDiagramNodeId = (node: Element | null | undefined) =>
node?.getAttribute("data-id") ?? node?.id.match(/(?:^|-)flowchart-(.+)-\d+$/)?.[1]; node?.getAttribute("data-id") ?? node?.id.match(/(?:^|-)flowchart-(.+)-\d+$/)?.[1];
/** Update state-only changes in place, preserving the reader's pan and zoom. */ /** Update state-only changes in place, preserving the reader's pan and zoom. */
export function paintInvestigationDiagramStates(root: Element, diagram: InvestigationDiagram, running: boolean) { export function paintInvestigationDiagramStates(root: Element, diagram: InvestigationDiagram) {
const refs = new Map(diagram.node_refs.map((node) => [node.node_id, node])); const refs = new Map(diagram.node_refs.map((node) => [node.node_id, node]));
const classes = Object.values(investigationDiagramStates).map((state) => state.className); const classes = [...Object.values(investigationDiagramStates).map((state) => state.className), ...Object.keys(legacyClasses)];
root.querySelectorAll<SVGGElement>("svg g.node").forEach((node) => { root.querySelectorAll<SVGGElement>("svg g.node").forEach((node) => {
const ref = refs.get(investigationDiagramNodeId(node) ?? ""); const ref = refs.get(investigationDiagramNodeId(node) ?? "");
const state = investigationDiagramStates[ref ? investigationNodeState(ref, running) : "unknown"]; const state = investigationDiagramStates[ref ? investigationNodeState(ref) : "reference"];
node.classList.remove(...classes); node.classList.remove(...classes);
node.classList.add(state.className); node.classList.add(state.className);
node.setAttribute("aria-label", `${ref?.label ?? node.textContent?.trim() ?? "节点"}:${state.label}`); node.setAttribute("aria-label", `${ref?.label ?? node.textContent?.trim() ?? "节点"}:${state.label}`);
@@ -162,23 +185,22 @@ export function paintInvestigationDiagramStates(root: Element, diagram: Investig
}); });
} }
/** Color explicit recorded states; relationships and evidence never imply completion. */ /** Color saved reference annotations without deriving state from an execution run. */
export function styleInvestigationDiagram(diagram: InvestigationDiagram, running = false) { export function styleInvestigationDiagram(diagram: InvestigationDiagram) {
const assignments = diagram.node_refs.flatMap((node) => { const assignments = diagram.node_refs.flatMap((node) => {
const escaped = node.node_id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const escaped = node.node_id.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const inSource = new RegExp(`(?:^|[^A-Za-z0-9_-])${escaped}(?=\\s*(?:[\\[({@;]|:::|--|==|-\\.|$))`, "m").test( const inSource = new RegExp(`(?:^|[^A-Za-z0-9_-])${escaped}(?=\\s*(?:[\\[({@;]|:::|--|==|-\\.|$))`, "m").test(
diagram.mermaid diagram.mermaid
); );
if (!inSource) return []; if (!inSource) return [];
const state = investigationDiagramStates[investigationNodeState(node, running)]; const state = investigationDiagramStates[investigationNodeState(node)];
return [`class ${node.node_id} ${state.className};`, `style ${node.node_id} ${nodeStyle(state)};`]; return [`class ${node.node_id} ${state.className};`, `style ${node.node_id} ${nodeStyle(state)};`];
}); });
// Keep role/reference classes neutral. Their presence conveys association, // Keep role/reference classes neutral. Their presence conveys association,
// while only node_refs.status supplies an execution fact. // and only explicit node annotations describe saved findings.
const roles = ["default", "tjAgent", "tjHuman", "tjDecision", "tjEvidence", "tjAction"] const roles = ["default", "tjAgent", "tjHuman", "tjDecision", "tjEvidence", "tjAction"]
.map((name) => `classDef ${name} ${nodeStyle(investigationDiagramStates.unknown)};`); .map((name) => `classDef ${name} ${nodeStyle(investigationDiagramStates.reference)};`);
const states = Object.entries(investigationDiagramStates).map(([key, state]) => const states = Object.values(investigationDiagramStates).map((state) => `classDef ${state.className} ${nodeStyle(state)};`);
`classDef ${state.className} ${nodeStyle(key === "running" && !running ? investigationDiagramStates.recorded_running : state)};` const legacy = Object.entries(legacyClasses).map(([name, annotation]) => `classDef ${name} ${nodeStyle(investigationDiagramStates[annotation])};`);
); return [diagram.mermaid, ...roles, ...states, ...legacy, ...assignments].join("\n");
return [diagram.mermaid, ...roles, ...states, ...assignments].join("\n");
} }
@@ -0,0 +1,5 @@
import { createContext, useContext } from "react";
import type { FloatingWindowDock } from "@/shared/ui/floating-window";
export const ChartWorkspaceContext = createContext<FloatingWindowDock | null>(null);
export const useChartWorkspace = () => useContext(ChartWorkspaceContext);
@@ -0,0 +1,17 @@
import { useCallback, useMemo, useRef, useState, type ReactNode } from "react";
import type { FloatingWindowDock } from "@/shared/ui/floating-window";
import { ChartWorkspaceContext } from "./chart-workspace-context";
export function ChartWorkspaceProvider({ children }: { children: ReactNode }) {
const target = useRef<HTMLDivElement>(null);
const [state, setState] = useState<{ activeId: string | null; view: FloatingWindowDock["view"] }>({ activeId: null, view: "map_split" });
const activate = useCallback((id: string) => {
setState((current) => current.activeId === id ? current : { activeId: id, view: "map_split" });
}, []);
const deactivate = useCallback((id?: string) => {
setState((current) => id && current.activeId !== id ? current : { ...current, activeId: null });
}, []);
const setView = useCallback((view: FloatingWindowDock["view"]) => setState((current) => ({ ...current, view })), []);
const value = useMemo(() => ({ ...state, target, activate, deactivate, setView }), [state, activate, deactivate, setView]);
return <ChartWorkspaceContext.Provider value={value}>{children}</ChartWorkspaceContext.Provider>;
}
@@ -9,6 +9,7 @@ export function WorkbenchContentSplit({
split, split,
showMap, showMap,
minPaneWidth, minPaneWidth,
minDocumentWidth = minPaneWidth,
onMapSizeChange onMapSizeChange
}: { }: {
map: ReactNode; map: ReactNode;
@@ -16,6 +17,7 @@ export function WorkbenchContentSplit({
split: boolean; split: boolean;
showMap: boolean; showMap: boolean;
minPaneWidth: number; minPaneWidth: number;
minDocumentWidth?: number;
onMapSizeChange: (percentage: number) => void; onMapSizeChange: (percentage: number) => void;
}) { }) {
const group = useGroupRef(); const group = useGroupRef();
@@ -24,7 +26,7 @@ export function WorkbenchContentSplit({
group.current?.setLayout( group.current?.setLayout(
split ? splitLayout.current : showMap ? { map: 100, document: 0 } : { map: 0, document: 100 } split ? splitLayout.current : showMap ? { map: 100, document: 0 } : { map: 0, document: 100 }
); );
}, [group, split, showMap, minPaneWidth]); }, [group, split, showMap, minPaneWidth, minDocumentWidth]);
return ( return (
<ResizablePanelGroup <ResizablePanelGroup
@@ -56,7 +58,7 @@ export function WorkbenchContentSplit({
<ResizablePanel <ResizablePanel
id="document" id="document"
defaultSize={showMap ? (split ? "50%" : "0%") : "100%"} defaultSize={showMap ? (split ? "50%" : "0%") : "100%"}
minSize={split ? minPaneWidth : showMap ? 0 : "100%"} minSize={split ? minDocumentWidth : showMap ? 0 : "100%"}
maxSize={!split && showMap ? 0 : "100%"} maxSize={!split && showMap ? 0 : "100%"}
className="relative h-full min-h-0 min-w-0" className="relative h-full min-h-0 min-w-0"
> >
@@ -1,7 +1,7 @@
import { useReadingWorkspace, type ReadingDocument } from "@/shared/ui/reading-workspace-context"; import { useReadingWorkspace, type ReadingDocument } from "@/shared/ui/reading-workspace-context";
import { ArrowLeft, Focus, Map as MapIcon, X } from "lucide-react"; import { ArrowLeft, Focus, Map as MapIcon, X } from "lucide-react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { useEffect, useRef, useState, type ReactNode } from "react"; import { useEffect, useRef, useState, type ReactNode, type RefObject } from "react";
import { cn } from "@/shared/ui/cn"; import { cn } from "@/shared/ui/cn";
import { Button } from "@/shared/ui/button"; import { Button } from "@/shared/ui/button";
import { Dialog, DialogContent, DialogTitle } from "@/shared/ui/dialog"; import { Dialog, DialogContent, DialogTitle } from "@/shared/ui/dialog";
@@ -10,7 +10,8 @@ import { OPERATIONAL_TIMELINE_LAYOUT } from "../operational-timeline/operational
import { AnalysisArtifactWorkspace } from "./analysis-document-view"; import { AnalysisArtifactWorkspace } from "./analysis-document-view";
import { ArtifactPeekBar } from "./artifact-peek-bar"; import { ArtifactPeekBar } from "./artifact-peek-bar";
import { WorkbenchContentSplit } from "./workbench-content-split"; import { WorkbenchContentSplit } from "./workbench-content-split";
import { ARTIFACT_PANE_MIN_WIDTH } from "./workspace-model"; import type { FloatingWindowDock } from "@/shared/ui/floating-window";
import { ARTIFACT_PANE_MIN_WIDTH, CONDITION_PANE_MIN_WIDTH } from "./workspace-model";
import { import {
ARTIFACT_VIEW_CONTROL_BUTTON_CLASS_NAME, ARTIFACT_VIEW_CONTROL_BUTTON_CLASS_NAME,
ARTIFACT_VIEW_CONTROL_SHELL_CLASS_NAME ARTIFACT_VIEW_CONTROL_SHELL_CLASS_NAME
@@ -32,6 +33,14 @@ type WorkbenchMainFrameProps = {
surfaceMode: WorkbenchSurfaceMode; surfaceMode: WorkbenchSurfaceMode;
mapSplitAvailable: boolean; mapSplitAvailable: boolean;
readingSplitAvailable?: boolean; readingSplitAvailable?: boolean;
chartDock?: { window: FloatingWindowDock; splitAvailable: boolean; reserveAgentRail: boolean };
conditionDock?: {
active: boolean;
splitAvailable: boolean;
target: RefObject<HTMLDivElement | null>;
view: ArtifactRequestedView;
onSetView: (view: ArtifactRequestedView) => void;
};
onOpenPendingArtifact: () => void; onOpenPendingArtifact: () => void;
onDestroyPendingArtifact: () => void; onDestroyPendingArtifact: () => void;
onSetArtifactView: (view: ArtifactRequestedView) => void; onSetArtifactView: (view: ArtifactRequestedView) => void;
@@ -50,6 +59,8 @@ export function WorkbenchMainFrame({
surfaceMode: artifactSurfaceMode, surfaceMode: artifactSurfaceMode,
mapSplitAvailable, mapSplitAvailable,
readingSplitAvailable = false, readingSplitAvailable = false,
chartDock,
conditionDock,
onOpenPendingArtifact, onOpenPendingArtifact,
onDestroyPendingArtifact, onDestroyPendingArtifact,
onSetArtifactView, onSetArtifactView,
@@ -59,19 +70,30 @@ export function WorkbenchMainFrame({
const reading = useReadingWorkspace(); const reading = useReadingWorkspace();
const lastReading = useRef<ReadingDocument | null>(null); const lastReading = useRef<ReadingDocument | null>(null);
useEffect(() => { if (reading?.active) lastReading.current = reading.active; }, [reading?.active]); useEffect(() => { if (reading?.active) lastReading.current = reading.active; }, [reading?.active]);
const chartActive = Boolean(chartDock?.window.activeId && !reading?.active);
const dock = reading?.active ? null : chartActive && chartDock
? { ...chartDock.window, splitAvailable: chartDock.splitAvailable, onSetView: chartDock.window.setView }
: conditionDock?.active ? conditionDock : null;
const dockActive = Boolean(dock);
const surfaceMode = reading?.active const surfaceMode = reading?.active
? reading.view === "map_split" && !readingSplitAvailable ? reading.view === "map_split" && !readingSplitAvailable
? "focus" ? "focus"
: reading.view : reading.view
: dock
? dock.view === "map_split" && !dock.splitAvailable ? "focus" : dock.view
: artifactSurfaceMode; : artifactSurfaceMode;
const prefersReducedMotion = useReducedMotion(); const prefersReducedMotion = useReducedMotion();
const showMap = surfaceMode !== "focus"; const showMap = surfaceMode !== "focus";
const showArtifact = Boolean(!reading?.active && activeArtifact && surfaceMode !== "map_only"); const showArtifact = Boolean(!reading?.active && !dockActive && activeArtifact && surfaceMode !== "map_only");
const showArtifactViewControl = Boolean(activeArtifact && !reading?.active); const showArtifactViewControl = Boolean((activeArtifact || dockActive) && !reading?.active);
const mapOnly = surfaceMode === "map_only"; const mapOnly = surfaceMode === "map_only";
const mapSplit = surfaceMode === "map_split"; const mapSplit = surfaceMode === "map_split";
const [mapPercentage, setMapPercentage] = useState(50); const [mapPercentage, setMapPercentage] = useState(50);
const viewControlLabel = mapOnly const splitAvailable = dock?.splitAvailable ?? mapSplitAvailable;
const viewControlLabel = dockActive
? mapOnly ? chartActive ? "返回图表管理" : "返回工况任务"
: mapSplit ? chartActive ? "专注图表" : "专注工况" : splitAvailable ? "地图对照" : "显示地图"
: mapOnly
? "返回分析成果" ? "返回分析成果"
: mapSplit : mapSplit
? "专注分析" ? "专注分析"
@@ -94,7 +116,7 @@ export function WorkbenchMainFrame({
<Dialog open={Boolean(reading?.active && surfaceMode === "focus")} <Dialog open={Boolean(reading?.active && surfaceMode === "focus")}
onOpenChange={(open) => { if (!open) reading?.close(); }}> onOpenChange={(open) => { if (!open) reading?.close(); }}>
<div <div
className="workbench-main-frame pointer-events-none absolute inset-0 min-h-0" className={cn("workbench-main-frame pointer-events-none absolute inset-0 min-h-0", chartActive && "max-h-dvh")}
data-testid="workbench-main-frame" data-testid="workbench-main-frame"
data-timeline-mode={timelineMode} data-timeline-mode={timelineMode}
> >
@@ -107,6 +129,7 @@ export function WorkbenchMainFrame({
split={mapSplit} split={mapSplit}
showMap={showMap} showMap={showMap}
minPaneWidth={reading?.active ? 360 : ARTIFACT_PANE_MIN_WIDTH} minPaneWidth={reading?.active ? 360 : ARTIFACT_PANE_MIN_WIDTH}
minDocumentWidth={dockActive && !chartActive ? CONDITION_PANE_MIN_WIDTH : undefined}
onMapSizeChange={setMapPercentage} onMapSizeChange={setMapPercentage}
map={ map={
<section <section
@@ -124,6 +147,15 @@ export function WorkbenchMainFrame({
} }
document={ document={
<> <>
<div
ref={conditionDock?.target}
id="condition-workspace"
className={cn("absolute inset-x-0 bottom-0 top-14 min-h-0 min-w-0", (!dockActive || chartActive || mapOnly) && "hidden")}
/>
<div ref={chartDock?.window.target} id="chart-workspace"
className={cn("absolute inset-x-0 bottom-0 top-14 min-h-0 min-w-0",
chartActive && surfaceMode === "focus" && chartDock?.reserveAgentRail && "lg:pl-[84px]",
(!chartActive || mapOnly) && "hidden")} />
<AnimatePresence initial={false} mode="popLayout"> <AnimatePresence initial={false} mode="popLayout">
{activeArtifact ? ( {activeArtifact ? (
<motion.section <motion.section
@@ -179,7 +211,7 @@ export function WorkbenchMainFrame({
</Button> </Button>
) : null} ) : null}
{pendingArtifact && !reading?.active ? ( {pendingArtifact && !reading?.active && !dockActive ? (
<ArtifactPeekBar <ArtifactPeekBar
artifact={pendingArtifact} artifact={pendingArtifact}
surfaceMode={surfaceMode} surfaceMode={surfaceMode}
@@ -205,9 +237,9 @@ export function WorkbenchMainFrame({
type="button" type="button"
aria-label={viewControlLabel} aria-label={viewControlLabel}
onClick={() => onClick={() =>
onSetArtifactView( (dock?.onSetView ?? onSetArtifactView)(
surfaceMode === "focus" surfaceMode === "focus"
? mapSplitAvailable ? splitAvailable
? "map_split" ? "map_split"
: "map_only" : "map_only"
: "focus" : "focus"
@@ -243,12 +275,12 @@ export function WorkbenchMainFrame({
</div> </div>
<motion.div <motion.div
className="pointer-events-auto absolute left-3 z-20 mx-auto min-h-0" className={cn("pointer-events-auto absolute left-3 z-20 mx-auto min-h-0", dockActive && !showMap && "hidden")}
initial={false} initial={false}
animate={{ animate={{
bottom: timelineBottom, bottom: timelineBottom,
maxWidth: OPERATIONAL_TIMELINE_LAYOUT[timelineMode].maxWidth, maxWidth: OPERATIONAL_TIMELINE_LAYOUT[timelineMode].maxWidth,
right: 12 right: dockActive && mapSplit ? `calc(${100 - mapPercentage}% + 12px)` : 12
}} }}
transition={timelineTransition} transition={timelineTransition}
> >
@@ -2,6 +2,8 @@ import type { FeatureCollection, Geometry } from "geojson";
export const ARTIFACT_PANE_MIN_WIDTH = 600; export const ARTIFACT_PANE_MIN_WIDTH = 600;
export const ARTIFACT_MAP_SPLIT_MIN_WIDTH = ARTIFACT_PANE_MIN_WIDTH * 2 + 1; export const ARTIFACT_MAP_SPLIT_MIN_WIDTH = ARTIFACT_PANE_MIN_WIDTH * 2 + 1;
export const CONDITION_PANE_MIN_WIDTH = 880;
export const CONDITION_MAP_SPLIT_MIN_WIDTH = ARTIFACT_PANE_MIN_WIDTH + CONDITION_PANE_MIN_WIDTH + 1;
export type ArtifactType = "diagnosis" | "simulation" | "metric_analysis"; export type ArtifactType = "diagnosis" | "simulation" | "metric_analysis";
export type ArtifactLifecycle = "draft" | "reviewed" | "published" | "archived"; export type ArtifactLifecycle = "draft" | "reviewed" | "published" | "archived";
+61
View File
@@ -0,0 +1,61 @@
import { act, cleanup, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { DeferredRender } from "./deferred-render";
let sequence = 0;
const frames = new Map<number, FrameRequestCallback>();
const tick = () => act(() => {
const callbacks = [...frames.values()];
frames.clear();
callbacks.forEach((callback) => callback(0));
});
beforeEach(() => {
vi.stubGlobal("IntersectionObserver", undefined);
vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => { frames.set(++sequence, callback); return sequence; });
vi.stubGlobal("cancelAnimationFrame", (id: number) => frames.delete(id));
});
afterEach(() => { cleanup(); frames.clear(); vi.unstubAllGlobals(); });
it("paints loading placeholders before mounting visible drawings one at a time", () => {
render(<><DeferredRender label="正在加载甲图"><p>甲图已就绪</p></DeferredRender>
<DeferredRender label="正在加载乙图"><p>乙图已就绪</p></DeferredRender></>);
expect(screen.getByRole("status", { name: "正在加载甲图" })).toHaveAttribute("aria-busy", "true");
tick();
expect(screen.queryByText("甲图已就绪")).toBeNull();
tick();
expect(screen.getByText("甲图已就绪")).toBeInTheDocument();
expect(screen.queryByText("乙图已就绪")).toBeNull();
tick(); tick();
expect(screen.getByText("乙图已就绪")).toBeInTheDocument();
expect(screen.queryByRole("status")).toBeNull();
});
it("cancels queued drawings when the task is removed", () => {
const Drawing = vi.fn(() => <p>已过期图表</p>);
const { unmount } = render(<DeferredRender label="加载中"><Drawing /></DeferredRender>);
tick();
unmount();
expect(frames.size).toBe(0);
tick(); tick();
expect(Drawing).not.toHaveBeenCalled();
expect(frames.size).toBe(0);
});
it("defers offscreen content until its own viewport intersection", () => {
let intersect!: IntersectionObserverCallback;
const disconnect = vi.fn();
vi.stubGlobal("IntersectionObserver", class {
constructor(callback: IntersectionObserverCallback) { intersect = callback; }
observe() {}
disconnect = disconnect;
});
render(<DeferredRender label="等待显示"><p>可见图表</p></DeferredRender>);
expect(frames.size).toBe(0);
act(() => intersect([{ isIntersecting: false }] as IntersectionObserverEntry[], {} as IntersectionObserver));
expect(frames.size).toBe(0);
act(() => intersect([{ isIntersecting: true }] as IntersectionObserverEntry[], {} as IntersectionObserver));
tick(); tick();
expect(screen.getByText("可见图表")).toBeInTheDocument();
expect(disconnect).toHaveBeenCalled();
});
+60
View File
@@ -0,0 +1,60 @@
import { useEffect, useRef, useState, type ReactNode } from "react";
import { cn } from "./cn";
const pending: Array<() => void> = [];
let frame = 0;
function schedule() {
if (frame || !pending.length) return;
// Let the task heading and placeholder paint before mounting an expensive plot.
frame = requestAnimationFrame(() => {
frame = requestAnimationFrame(() => {
frame = 0;
pending.shift()?.();
schedule();
});
});
}
function enqueue(render: () => void) {
pending.push(render);
schedule();
return () => {
const index = pending.indexOf(render);
if (index !== -1) pending.splice(index, 1);
if (!pending.length) { cancelAnimationFrame(frame); frame = 0; }
};
}
export function LoadingSkeleton({ label, className }: { label: string; className?: string }) {
return <div role="status" aria-label={label} aria-busy="true"
className={cn("space-y-3 rounded-lg border border-border bg-card p-4", className)}>
<span className="sr-only">{label}</span>
<div aria-hidden className="space-y-3 motion-safe:animate-pulse">
<div className="h-3 w-2/5 rounded bg-muted" />
<div className="h-32 rounded bg-muted/60" />
<div className="flex gap-3"><div className="h-2 w-1/4 rounded bg-muted" /><div className="h-2 w-1/3 rounded bg-muted" /></div>
</div>
</div>;
}
/** Mount visible drawings one at a time; cancel queued work when their task leaves. */
export function DeferredRender({ children, label, className }: {
children: ReactNode;
label: string;
className?: string;
}) {
const host = useRef<HTMLDivElement>(null);
const [ready, setReady] = useState(false);
useEffect(() => {
let cancel: (() => void) | undefined;
const load = () => { cancel ??= enqueue(() => setReady(true)); };
if (typeof IntersectionObserver === "undefined") { load(); return () => cancel?.(); }
const observer = new IntersectionObserver((entries) => {
if (entries.some((entry) => entry.isIntersecting)) { load(); observer.disconnect(); }
}, { rootMargin: "200px" });
if (host.current) observer.observe(host.current);
return () => { observer.disconnect(); cancel?.(); };
}, []);
return <div ref={host} className={className}>{ready ? children : <LoadingSkeleton label={label} />}</div>;
}
+60
View File
@@ -1,6 +1,8 @@
import { cleanup, fireEvent, render, screen } from "@testing-library/react"; import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, expect, it } from "vitest"; import { afterEach, expect, it } from "vitest";
import { FloatingWindow } from "./floating-window"; import { FloatingWindow } from "./floating-window";
import { floatingWindowEntries, floatingWindowOrder } from "./floating-window-layer";
import { useCallback, useRef, useState } from "react";
afterEach(cleanup); afterEach(cleanup);
@@ -35,3 +37,61 @@ it("retains manual opening, Escape dismissal and focus return", () => {
fireEvent.click(trigger); fireEvent.click(trigger);
expect(screen.getByRole("dialog", { name: "压力分析" })).toBeVisible(); expect(screen.getByRole("dialog", { name: "压力分析" })).toBeVisible();
}); });
function DockFixture({ multiple = false }: { multiple?: boolean }) {
const target = useRef<HTMLDivElement>(null);
const [activeId, setActiveId] = useState<string | null>(null);
const activate = useCallback((id: string) => setActiveId(id), []);
const deactivate = useCallback((id?: string) => setActiveId((current) => !id || current === id ? null : current), []);
return <>
<div ref={target} data-testid="workspace-slot" />
<button onClick={() => deactivate()}>切换工作区</button>
<FloatingWindow title="停靠分析" dock={{ target, activeId, activate, deactivate, view: "map_split", setView: () => undefined }}>
{() => <input aria-label="分析备注" />}
</FloatingWindow>
{multiple ? <FloatingWindow title="停靠对比" dock={{ target, activeId, activate, deactivate, view: "map_split", setView: () => undefined }}>
{() => <p>第二个来源</p>}
</FloatingWindow> : null}
</>;
}
it("preserves the live document when a docked window is hidden and located again", () => {
render(<DockFixture />);
const trigger = screen.getByRole("button", { name: "放大查看 停靠分析" });
fireEvent.click(trigger);
const dialog = screen.getByRole("dialog", { name: "停靠分析" });
expect(screen.getByTestId("workspace-slot")).toContainElement(dialog);
expect(dialog).toHaveAttribute("data-window-presentation", "docked");
expect(floatingWindowEntries()).toEqual([]);
expect(floatingWindowOrder()).toEqual([]);
const editor = screen.getByLabelText("分析备注");
fireEvent.change(editor, { target: { value: "保留核查说明" } });
fireEvent.click(screen.getByRole("button", { name: "切换工作区" }));
expect(dialog).not.toBeVisible();
fireEvent.click(trigger);
expect(screen.getByLabelText("分析备注")).toBe(editor);
expect(editor).toHaveValue("保留核查说明");
expect(dialog).toBeVisible();
expect(floatingWindowEntries()).toEqual([]);
expect(floatingWindowOrder()).toEqual([]);
fireEvent.keyDown(dialog, { key: "Escape" });
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
});
it("hides inactive docking hosts so another source can occupy the same workspace", () => {
render(<DockFixture multiple />);
fireEvent.click(screen.getByRole("button", { name: "放大查看 停靠分析" }));
const first = screen.getByRole("dialog", { name: "停靠分析" });
const editor = screen.getByLabelText("分析备注");
fireEvent.change(editor, { target: { value: "保留第一个来源" } });
fireEvent.click(screen.getByRole("button", { name: "放大查看 停靠对比" }));
const second = screen.getByRole("dialog", { name: "停靠对比" });
expect(first.parentElement).not.toBeVisible();
expect(first.parentElement).toHaveAttribute("hidden");
expect(second.parentElement).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: "放大查看 停靠分析" }));
expect(first.parentElement).toBeVisible();
expect(second.parentElement).not.toBeVisible();
expect(screen.getByLabelText("分析备注")).toBe(editor);
expect(editor).toHaveValue("保留第一个来源");
});
+63 -22
View File
@@ -1,4 +1,4 @@
import { useEffect, useId, useLayoutEffect, useRef, useState, useSyncExternalStore, type ReactNode } from "react"; import { useEffect, useId, useLayoutEffect, useRef, useState, useSyncExternalStore, type ReactNode, type RefObject } from "react";
import { createPortal } from "react-dom"; import { createPortal } from "react-dom";
import { Maximize2, Minimize2, X } from "lucide-react"; import { Maximize2, Minimize2, X } from "lucide-react";
import { Button } from "./button"; import { Button } from "./button";
@@ -8,6 +8,14 @@ import { useFloatingWindowDrag } from "./use-floating-window-drag";
import { useFloatingWindowResize, type ResizeEdge } from "./use-floating-window-resize"; import { useFloatingWindowResize, type ResizeEdge } from "./use-floating-window-resize";
type Bounds = { x: number; y: number; width: number; height: number }; type Bounds = { x: number; y: number; width: number; height: number };
export type FloatingWindowDock = {
target: RefObject<HTMLDivElement | null>;
activeId: string | null;
view: "map_split" | "focus" | "map_only";
activate: (id: string) => void;
deactivate: (id?: string) => void;
setView: (view: FloatingWindowDock["view"]) => void;
};
const resizeHandles: Record<ResizeEdge, React.CSSProperties> = { const resizeHandles: Record<ResizeEdge, React.CSSProperties> = {
top: { top: 0, left: 18, right: 18, height: 8, cursor: "ns-resize" }, top: { top: 0, left: 18, right: 18, height: 8, cursor: "ns-resize" },
right: { right: 0, top: 18, bottom: 18, width: 8, cursor: "ew-resize" }, right: { right: 0, top: 18, bottom: 18, width: 8, cursor: "ew-resize" },
@@ -28,7 +36,7 @@ function fitWindow(bounds: Bounds): Bounds {
y: Math.max(top, Math.min(bounds.y, window.innerHeight - height - 8)) }; y: Math.max(top, Math.min(bounds.y, window.innerHeight - height - 8)) };
} }
export function FloatingWindow({ title, navigationTitle, triggerLabel, fillContent = false, openRequestKey, triggerContent, initialSize = { width: 800, height: 560 }, children }: { export function FloatingWindow({ title, navigationTitle, triggerLabel, fillContent = false, openRequestKey, triggerContent, initialSize = { width: 800, height: 560 }, dock, children }: {
title: string; title: string;
navigationTitle?: string; navigationTitle?: string;
triggerLabel?: string; triggerLabel?: string;
@@ -37,6 +45,8 @@ export function FloatingWindow({ title, navigationTitle, triggerLabel, fillConte
fillContent?: boolean; fillContent?: boolean;
/** A new display request opens the window without taking keyboard focus. */ /** A new display request opens the window without taking keyboard focus. */
openRequestKey?: string; openRequestKey?: string;
/** An optional layout host; individual windows remain floating by default. */
dock?: FloatingWindowDock | null;
children: (size: { width: number; height: number }) => ReactNode; children: (size: { width: number; height: number }) => ReactNode;
}) { }) {
const id = useId(); const id = useId();
@@ -55,11 +65,23 @@ export function FloatingWindow({ title, navigationTitle, triggerLabel, fillConte
const trigger = useRef<HTMLButtonElement>(null); const trigger = useRef<HTMLButtonElement>(null);
const heading = useRef<HTMLDivElement>(null); const heading = useRef<HTMLDivElement>(null);
const focusOnOpen = useRef(false); const focusOnOpen = useRef(false);
const raise = () => raiseFloatingWindow(id); const [dockHost] = useState(() => {
const element = document.createElement("div");
element.className = "h-full min-h-0 min-w-0";
return element;
});
const docked = Boolean(dock);
const focusWindow = () => {
dock?.activate(id);
if (!docked) raiseFloatingWindow(id);
requestAnimationFrame(() => heading.current?.focus({ preventScroll: true }));
};
const raise = () => { if (!docked) raiseFloatingWindow(id); };
const close = () => { const close = () => {
setManuallyOpen(false); setManuallyOpen(false);
setRequest({ key: openRequestKey, dismissed: true }); setRequest({ key: openRequestKey, dismissed: true });
removeFloatingWindow(id); removeFloatingWindow(id);
dock?.deactivate(id);
if (heading.current?.closest('[data-floating-window]')?.contains(document.activeElement)) if (heading.current?.closest('[data-floating-window]')?.contains(document.activeElement))
trigger.current?.focus({ preventScroll: true }); trigger.current?.focus({ preventScroll: true });
}; };
@@ -67,14 +89,33 @@ export function FloatingWindow({ title, navigationTitle, triggerLabel, fillConte
const closeRef = useRef(close); const closeRef = useRef(close);
closeRef.current = close; closeRef.current = close;
useLayoutEffect(() => { useLayoutEffect(() => {
if (open) registerFloatingWindow({ id, title: navigationTitle ?? title, if (open && !docked) registerFloatingWindow({ id, title: navigationTitle ?? title,
focus: () => { raiseFloatingWindow(id); heading.current?.focus({ preventScroll: true }); }, focus: focusWindow,
close: () => closeRef.current() }); close: () => closeRef.current() });
}, [id, open, title, navigationTitle]); });
const activateDock = dock?.activate;
const deactivateDock = dock?.deactivate;
const dockTarget = dock?.target;
useLayoutEffect(() => {
dockHost.hidden = Boolean(dock && dock.activeId !== id);
}, [dock, dockHost, id]);
useLayoutEffect(() => {
if (!open || !dockTarget) return;
dockTarget.current?.append(dockHost);
activateDock?.(id);
return () => { dockHost.remove(); deactivateDock?.(id); };
}, [id, open, dockHost, dockTarget, activateDock, deactivateDock]);
useLayoutEffect(() => {
if (open && focusOnOpen.current && (!dock || dock.activeId === id)) {
heading.current?.focus({ preventScroll: true });
focusOnOpen.current = false;
}
}, [open, dock, id]);
useEffect(() => () => removeFloatingWindow(id), [id]); useEffect(() => () => removeFloatingWindow(id), [id]);
useLayoutEffect(() => { useLayoutEffect(() => {
if (!open) return; if (!open || docked) return;
const others = floatingWindowOrder().filter((windowId) => windowId !== id); const others = floatingWindowOrder().filter((windowId) => windowId !== id);
const headingHeight = Array.from(floatingWindowHost().querySelectorAll<HTMLElement>(".floating-window-heading")) const headingHeight = Array.from(floatingWindowHost().querySelectorAll<HTMLElement>(".floating-window-heading"))
.reduce((height, element) => Math.max(height, element.offsetHeight), 48); .reduce((height, element) => Math.max(height, element.offsetHeight), 48);
@@ -89,8 +130,6 @@ export function FloatingWindow({ title, navigationTitle, triggerLabel, fillConte
setBounds(fitWindow({ x: (window.innerWidth - initialSizeRef.current.width) / 2 + slot * 24, y, setBounds(fitWindow({ x: (window.innerWidth - initialSizeRef.current.width) / 2 + slot * 24, y,
width: initialSizeRef.current.width, height: Math.min(initialSizeRef.current.height, window.innerHeight - y - 8) })); width: initialSizeRef.current.width, height: Math.min(initialSizeRef.current.height, window.innerHeight - y - 8) }));
raiseFloatingWindow(id); raiseFloatingWindow(id);
if (focusOnOpen.current) heading.current?.focus({ preventScroll: true });
focusOnOpen.current = false;
const resize = () => { const resize = () => {
setViewport({ width: window.innerWidth, height: window.innerHeight }); setViewport({ width: window.innerWidth, height: window.innerHeight });
setBounds((current) => { setBounds((current) => {
@@ -104,16 +143,16 @@ export function FloatingWindow({ title, navigationTitle, triggerLabel, fillConte
window.removeEventListener("resize", resize); window.removeEventListener("resize", resize);
removeFloatingWindow(id); removeFloatingWindow(id);
}; };
}, [id, open]); }, [id, open, docked]);
const current = maximized const current = maximized
? { x: 8, y: floatingWindowTopInset(), width: viewport.width - 16, height: viewport.height - floatingWindowTopInset() - 8 } ? { x: 8, y: floatingWindowTopInset(), width: viewport.width - 16, height: viewport.height - floatingWindowTopInset() - 8 }
: bounds; : bounds;
const startDrag = useFloatingWindowDrag({ enabled: open && !maximized, position: current, const startDrag = useFloatingWindowDrag({ enabled: open && !maximized && !docked, position: current,
width: current.width, height: current.height, width: current.width, height: current.height,
onCommit: (position) => setBounds((previous) => fitWindow({ ...previous, ...position })) }); onCommit: (position) => setBounds((previous) => fitWindow({ ...previous, ...position })) });
const startResize = useFloatingWindowResize({ enabled: open && !maximized, bounds: current, onCommit: (next) => setBounds(fitWindow(next)) }); const startResize = useFloatingWindowResize({ enabled: open && !maximized && !docked, bounds: current, onCommit: (next) => setBounds(fitWindow(next)) });
return <> return <>
<Button ref={trigger} type="button" variant="ghost" size={triggerContent ? "sm" : "icon-sm"} className="shrink-0" <Button ref={trigger} type="button" variant="ghost" size={triggerContent ? "sm" : "icon-sm"} className="shrink-0"
@@ -124,24 +163,26 @@ export function FloatingWindow({ title, navigationTitle, triggerLabel, fillConte
setMaximized(false); setMaximized(false);
focusOnOpen.current = true; focusOnOpen.current = true;
setManuallyOpen(true); setManuallyOpen(true);
} else heading.current?.focus({ preventScroll: true }); } else focusWindow();
raise(); raise();
}}><Maximize2 size={15} aria-hidden />{triggerContent}</Button> }}><Maximize2 size={15} aria-hidden />{triggerContent}</Button>
{open ? createPortal( {open ? createPortal(
<div style={{ position: "absolute", left: 0, top: 0, width: current.width, height: current.height, <div style={docked ? { position: "relative", width: "100%", height: "100%" } : { position: "absolute", left: 0, top: 0, width: current.width, height: current.height,
transform: `translate(${current.x}px, ${current.y}px)`, zIndex: order.indexOf(id) + 1 }} transform: `translate(${current.x}px, ${current.y}px)`, zIndex: order.indexOf(id) + 1 }}
className="workbench-shadcn-surface pointer-events-auto flex flex-col overflow-hidden rounded-xl border border-border bg-background text-foreground shadow-lg" className={`workbench-shadcn-surface pointer-events-auto flex flex-col overflow-hidden border border-border bg-background text-foreground ${docked ? "pb-28 lg:pb-14" : "rounded-xl shadow-lg"}`}
role="dialog" aria-modal="false" aria-labelledby={titleId} data-floating-window="" data-floating-window-id={id} role="dialog" aria-modal="false" aria-labelledby={titleId} data-floating-window="" data-floating-window-id={id}
data-window-presentation={docked ? "docked" : "floating"}
hidden={Boolean(dock && dock.activeId !== id)}
onPointerDownCapture={raise} onFocusCapture={raise} onPointerDownCapture={raise} onFocusCapture={raise}
onKeyDown={(event: React.KeyboardEvent) => { onKeyDown={(event: React.KeyboardEvent) => {
if (event.key === "Escape" && !event.defaultPrevented) { event.stopPropagation(); close(); } if (event.key === "Escape" && !event.defaultPrevented) { event.stopPropagation(); close(); }
}}> }}>
<div ref={heading} tabIndex={0} <div ref={heading} tabIndex={0}
onPointerDown={startDrag} onPointerDown={startDrag}
className="floating-window-heading flex min-h-12 shrink-0 cursor-move touch-none select-none items-center justify-between gap-3 border-b border-border px-3 py-2 focus-visible:outline-2 focus-visible:outline-ring" className={`floating-window-heading flex min-h-12 shrink-0 ${docked ? "" : "cursor-move touch-none"} select-none items-center justify-between gap-3 border-b border-border px-3 py-2 focus-visible:outline-2 focus-visible:outline-ring`}
aria-label="窗口标题栏,可用方向键移动,Shift 加方向键调整大小" aria-label={docked ? `${title}标题栏` : "窗口标题栏,可用方向键移动,Shift 加方向键调整大小"}
onKeyDown={(event) => { onKeyDown={(event) => {
if (event.target !== event.currentTarget || maximized || !["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) return; if (docked || event.target !== event.currentTarget || maximized || !["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) return;
event.preventDefault(); event.preventDefault();
const dx = event.key === "ArrowLeft" ? -16 : event.key === "ArrowRight" ? 16 : 0; const dx = event.key === "ArrowLeft" ? -16 : event.key === "ArrowRight" ? 16 : 0;
const dy = event.key === "ArrowUp" ? -16 : event.key === "ArrowDown" ? 16 : 0; const dy = event.key === "ArrowUp" ? -16 : event.key === "ArrowDown" ? 16 : 0;
@@ -151,10 +192,10 @@ export function FloatingWindow({ title, navigationTitle, triggerLabel, fillConte
}}> }}>
<h2 id={titleId} className="min-w-0 break-words text-sm font-semibold leading-5">{title}</h2> <h2 id={titleId} className="min-w-0 break-words text-sm font-semibold leading-5">{title}</h2>
<div className="flex shrink-0 items-center gap-1"> <div className="flex shrink-0 items-center gap-1">
<Button type="button" variant="ghost" size="icon-sm" aria-label={maximized ? "还原窗口" : "最大化窗口"} {!docked ? <Button type="button" variant="ghost" size="icon-sm" aria-label={maximized ? "还原窗口" : "最大化窗口"}
title={maximized ? "还原窗口" : "最大化窗口"} onClick={() => setMaximized(!maximized)}> title={maximized ? "还原窗口" : "最大化窗口"} onClick={() => setMaximized(!maximized)}>
{maximized ? <Minimize2 size={15} aria-hidden /> : <Maximize2 size={15} aria-hidden />} {maximized ? <Minimize2 size={15} aria-hidden /> : <Maximize2 size={15} aria-hidden />}
</Button> </Button> : null}
<Button type="button" variant="ghost" size="icon-sm" aria-label="关闭窗口" title="关闭窗口" onClick={close}> <Button type="button" variant="ghost" size="icon-sm" aria-label="关闭窗口" title="关闭窗口" onClick={close}>
<X size={16} aria-hidden /> <X size={16} aria-hidden />
</Button> </Button>
@@ -165,13 +206,13 @@ export function FloatingWindow({ title, navigationTitle, triggerLabel, fillConte
{children({ width: current.width - 26, height: current.height - 76 })} {children({ width: current.width - 26, height: current.height - 76 })}
</div> </div>
</div> </div>
{!maximized ? (Object.entries(resizeHandles) as Array<[ResizeEdge, React.CSSProperties]>).map(([edge, style]) => ( {!maximized && !docked ? (Object.entries(resizeHandles) as Array<[ResizeEdge, React.CSSProperties]>).map(([edge, style]) => (
<div key={edge} aria-hidden data-window-resize-handle={edge} <div key={edge} aria-hidden data-window-resize-handle={edge}
className={`absolute z-10 touch-none ${edge === "bottomRight" ? "floating-window-resize" : ""}`} className={`absolute z-10 touch-none ${edge === "bottomRight" ? "floating-window-resize" : ""}`}
style={style} onPointerDown={(event) => startResize(event, edge)}> style={style} onPointerDown={(event) => startResize(event, edge)}>
{edge === "bottomRight" ? <span className="pointer-events-none absolute bottom-1 right-1 size-2 border-b-2 border-r-2 border-muted-foreground/60" /> : null} {edge === "bottomRight" ? <span className="pointer-events-none absolute bottom-1 right-1 size-2 border-b-2 border-r-2 border-muted-foreground/60" /> : null}
</div> </div>
)) : null} )) : null}
</div>, floatingWindowHost()) : null} </div>, docked ? dockHost : floatingWindowHost()) : null}
</>; </>;
} }
@@ -168,7 +168,7 @@ test("调查报告展示 SVG 脉络、处置进展和报告版本,缺数正常
expect(second).not.toBeNull(); expect(second).not.toBeNull();
return [first!, second!].map((box) => ({ x: Math.round(box.x), y: Math.round(box.y), width: Math.round(box.width), height: Math.round(box.height) })); return [first!, second!].map((box) => ({ x: Math.round(box.x), y: Math.round(box.y), width: Math.round(box.width), height: Math.round(box.height) }));
}; };
await expect(panel).toHaveCSS("width", "880px"); await expect(panel).toHaveAttribute("data-presentation", "workspace");
const scheduledColumns = await captureColumns(); const scheduledColumns = await captureColumns();
await testInfo.attach("scheduled-tab-alignment", { body: await panel.screenshot({ path: testInfo.outputPath("scheduled-tab-alignment.png") }), contentType: "image/png" }); await testInfo.attach("scheduled-tab-alignment", { body: await panel.screenshot({ path: testInfo.outputPath("scheduled-tab-alignment.png") }), contentType: "image/png" });
await panel.getByRole("button", { name: /预约任务/ }).click(); await panel.getByRole("button", { name: /预约任务/ }).click();
@@ -378,7 +378,7 @@ test("调查报告展示 SVG 脉络、处置进展和报告版本,缺数正常
await expect(panel.getByRole("button", { name: "确认并创建预约工单" })).toHaveCount(0); await expect(panel.getByRole("button", { name: "确认并创建预约工单" })).toHaveCount(0);
await page.getByRole("button", { name: "折叠 Agent 面板", exact: true }).click(); await page.getByRole("button", { name: "折叠 Agent 面板", exact: true }).click();
await expect(page.getByRole("button", { name: /展开 Agent 助手面板/ })).toBeVisible(); await expect(page.getByRole("button", { name: /展开 Agent 助手面板/ })).toBeVisible();
await expect(panel).toHaveCSS("width", "880px"); await expect(panel).toHaveAttribute("data-presentation", "workspace");
await panel.getByRole("heading", { name: "当前结果", exact: true }).scrollIntoViewIfNeeded(); await panel.getByRole("heading", { name: "当前结果", exact: true }).scrollIntoViewIfNeeded();
await testInfo.attach("insufficient-report-desktop", { body: await panel.screenshot({ await testInfo.attach("insufficient-report-desktop", { body: await panel.screenshot({
path: testInfo.outputPath("insufficient-report-desktop.png") }), contentType: "image/png" }); path: testInfo.outputPath("insufficient-report-desktop.png") }), contentType: "image/png" });
@@ -401,6 +401,7 @@ test("调查报告展示 SVG 脉络、处置进展和报告版本,缺数正常
const mobileExpand = mobilePanel.getByRole("button", { name: "展开工况任务" }); const mobileExpand = mobilePanel.getByRole("button", { name: "展开工况任务" });
if (await mobileExpand.isVisible()) await mobileExpand.click(); if (await mobileExpand.isVisible()) await mobileExpand.click();
await mobilePanel.getByRole("button", { name: /调查任务/ }).click(); await mobilePanel.getByRole("button", { name: /调查任务/ }).click();
await mobilePanel.getByText("水质投诉动态调查", { exact: true }).first().click();
await mobilePanel.getByLabel("调查脉络", { exact: true }).scrollIntoViewIfNeeded(); await mobilePanel.getByLabel("调查脉络", { exact: true }).scrollIntoViewIfNeeded();
await expect(mobilePanel.getByLabel("调查脉络", { exact: true }).locator("svg[id]")).toHaveCount(1); await expect(mobilePanel.getByLabel("调查脉络", { exact: true }).locator("svg[id]")).toHaveCount(1);
const mobileDiagram = mobilePanel.getByLabel("调查脉络", { exact: true }); const mobileDiagram = mobilePanel.getByLabel("调查脉络", { exact: true });
@@ -0,0 +1,118 @@
import { expect, test } from "@playwright/test";
import { investigationFixture, mockInvestigationPresentation, selectInvestigation, showInvestigationMap, showInvestigationTasks } from "./support/mock-investigation-presentation";
import { responsesFixture } from "./support/responses-fixture";
test.use({ reducedMotion: "reduce" });
const chart = (id: string) => ({ action: "open_chart", chart_id: id, evidence_refs: ["synthetic:pressure"],
chart: { title: `停靠监测 ${id}`, chart_type: "line", x_data: ["07:45", "08:00"], series: [{ name: "压力(m)", data: [32, 28] }] } });
test("chart manager occupies the right workspace and preserves charts when switching to tasks", async ({ page }, testInfo) => {
await page.setViewportSize({ width: 1920, height: 1000 });
const task = investigationFixture(1, "右侧图表工作区验收");
const mock = await mockInvestigationPresentation(page, [task]);
await selectInvestigation(page, task.title);
await page.getByRole("button", { name: /展开 Agent 助手面板/ }).click();
const presentation = page.getByLabel("调查实时展示", { exact: true });
await expect(presentation).toContainText("实时跟随");
await mock.emit(task, chart("P1"));
const manager = page.getByRole("dialog", { name: "图表管理", exact: true });
await expect(manager).toBeVisible();
await expect(manager).toHaveAttribute("data-window-presentation", "docked");
await expect(page.getByRole("button", { name: /窗口管理,当前/ })).toHaveCount(0);
await expect(manager.getByRole("button", { name: /最大化窗口|还原窗口/ })).toHaveCount(0);
await expect(manager.locator("[data-window-resize-handle]")).toHaveCount(0);
await expect(page.getByRole("region", { name: "工况任务", exact: true })).toBeHidden();
const box = (await manager.boundingBox())!;
const map = (await page.locator("#workspace-map").boundingBox())!;
expect(box.y).toBe(56);
expect(box.x).toBeGreaterThanOrEqual(map.x + map.width);
expect(Math.round(box.x + box.width)).toBe(1920);
await expect(manager.getByRole("img", { name: "停靠监测 P1", exact: true })).toBeVisible();
const separator = page.getByRole("separator", { name: "调整地图与报告宽度" });
await separator.focus();
await page.keyboard.press("End");
await expect.poll(async () => Math.round((await manager.boundingBox())!.width)).toBe(600);
await page.screenshot({ path: testInfo.outputPath("chart-workspace-minimum.png") });
const instance = await manager.locator(".echarts-for-react").getAttribute("_echarts_instance_");
await page.getByRole("button", { name: "工况任务", exact: true }).click();
await expect(manager).toBeHidden();
await expect(page.getByRole("region", { name: "工况任务", exact: true })).toBeVisible();
await showInvestigationMap(page);
await presentation.getByRole("button", { name: "打开图表管理", exact: true }).press("Enter");
await expect(manager).toBeVisible();
await expect(manager.getByLabel("图表管理标题栏", { exact: true })).toBeFocused();
await expect(manager.locator(".echarts-for-react")).toHaveAttribute("_echarts_instance_", instance!);
for (const width of [1200, 1024, 390, 320]) {
await page.setViewportSize({ width, height: 800 });
await expect(page.locator("#main-workspace")).toHaveAttribute("data-layout-mode", "focus");
const bounds = (await manager.boundingBox())!;
expect(bounds.x + bounds.width).toBeLessThanOrEqual(width);
expect(await manager.evaluate((node) => node.scrollWidth - node.clientWidth)).toBeLessThanOrEqual(1);
await page.screenshot({ path: testInfo.outputPath(`chart-workspace-${width}.png`) });
}
await page.setViewportSize({ width: 1920, height: 1000 });
await manager.getByRole("button", { name: "关闭窗口", exact: true }).click();
await expect(manager).toHaveCount(0);
await expect(page.locator("#workspace-map")).toBeVisible();
await showInvestigationTasks(page);
await expect(page.getByRole("region", { name: "工况任务", exact: true })).toBeVisible();
expect(mock.mutations).toEqual([]);
});
test("multiple chart sources share the visible dock without resetting their charts", async ({ page }) => {
await page.setViewportSize({ width: 1920, height: 1000 });
const task = investigationFixture(1, "多来源停靠验收");
const mock = await mockInvestigationPresentation(page, [task]);
await selectInvestigation(page, task.title);
await mock.emit(task, chart("P1"));
const first = page.getByRole("dialog", { name: "图表管理", exact: true }).filter({ hasText: task.title });
await expect(first).toBeVisible();
await expect(first.locator(".echarts-for-react svg")).toBeVisible();
const instance = await first.locator(".echarts-for-react").getAttribute("_echarts_instance_");
await page.getByRole("button", { name: "切换地图 Dev Panel" }).click();
const tools = page.getByTestId("investigation-dev-tools");
await tools.getByLabel("调查展示 JSONL", { exact: true }).fill(JSON.stringify({ record_type: "presentation", command: chart("preview") }));
await expect(tools.getByRole("combobox", { name: "JSONL 测试案例", exact: true })).toBeEnabled();
await tools.getByRole("button", { name: "执行本地预览", exact: true }).click();
await expect(tools.getByRole("status")).toContainText("本地预览完成");
await page.getByRole("button", { name: "切换地图 Dev Panel" }).click();
await page.getByLabel("本地预览展示", { exact: true }).getByRole("button", { name: "打开图表管理", exact: true }).press("Enter");
const second = page.getByRole("dialog", { name: "图表管理", exact: true }).filter({ hasText: "本地预览展示" });
await expect(second).toBeVisible();
expect((await second.boundingBox())!.y).toBe(56);
await expect(first).toBeHidden();
await page.getByLabel("调查实时展示", { exact: true }).getByRole("button", { name: "打开图表管理", exact: true }).press("Enter");
await expect(first).toBeVisible();
expect((await first.boundingBox())!.y).toBe(56);
await expect(second).toBeHidden();
await expect(first.locator(".echarts-for-react")).toHaveAttribute("_echarts_instance_", instance!);
await expect(page.getByRole("button", { name: /窗口管理,当前/ })).toHaveCount(0);
});
test("Agent map location reveals the map while the chart workspace is focused", async ({ page }) => {
await page.setViewportSize({ width: 1200, height: 900 });
const task = investigationFixture(1, "图表专注地图定位验收");
const mock = await mockInvestigationPresentation(page, [task]);
const block = { version: "answer-ui@1", block_id: "dock-location", fallback_text: "合成地图定位", spec: {
root: "location", elements: { location: { type: "MapLocation", props: { label: "定位合成监测点", layer: "junctions", feature_ids: ["P1"], source: "浏览器验收" }, children: [] } }
} };
await page.route("**/api/v1/responses", (route) => route.request().method() === "OPTIONS" ? route.fallback() : route.fulfill({
headers: { "Access-Control-Allow-Origin": "*", "Content-Type": "text/event-stream" }, body: responsesFixture([
{ type: "start", messageId: "dock-location-answer" }, { type: "data-answer_ui", id: block.block_id, data: block },
{ type: "data-final_answer", data: { content: "合成地图定位", ui_block_ids: [block.block_id] } }, { type: "finish", finishReason: "stop" }
])
}));
await selectInvestigation(page, task.title);
await mock.emit(task, chart("P1"));
await expect(page.getByRole("dialog", { name: "图表管理", exact: true })).toBeVisible();
await page.getByRole("button", { name: /展开 Agent 助手面板/ }).click();
const agent = page.getByRole("complementary", { name: "Agent 命令面板" });
await agent.locator(".agent-panel-prompt-textarea").fill("定位合成监测点");
await agent.getByRole("button", { name: "发送 Agent 指令", exact: true }).click();
await expect(page.locator("#workspace-map")).toBeHidden();
await agent.getByRole("button", { name: "定位合成监测点", exact: true }).click();
await expect(page.locator("#workspace-map")).toBeVisible();
await expect(page.locator("#main-workspace")).toHaveAttribute("data-layout-mode", "map_only");
await expect(page.getByRole("button", { name: "返回图表管理", exact: true })).toBeVisible();
});
@@ -77,6 +77,7 @@ async function resolvedColor(element: Locator, token: string, property: string)
} }
async function setup(page: Page, count: number) { async function setup(page: Page, count: number) {
await page.setViewportSize({ width: 1920, height: 1000 });
await page.route("**/@fs/**/noto-sans-sc-*.woff2", (route) => route.fulfill({ await page.route("**/@fs/**/noto-sans-sc-*.woff2", (route) => route.fulfill({
path: resolve("node_modules/@fontsource-variable/noto-sans-sc/files", basename(new URL(route.request().url()).pathname)), contentType: "font/woff2" path: resolve("node_modules/@fontsource-variable/noto-sans-sc/files", basename(new URL(route.request().url()).pathname)), contentType: "font/woff2"
})); }));
@@ -301,10 +302,8 @@ test("scrolling layouts adapt charts and retain empty places without turning int
} }
expect(dimensions.one.width).toBeGreaterThan(dimensions.two.width); expect(dimensions.one.width).toBeGreaterThan(dimensions.two.width);
expect(dimensions.one.height).toBeGreaterThan(dimensions.four.height); expect(dimensions.one.height).toBeGreaterThan(dimensions.four.height);
const heading = manager.getByLabel("窗口标题栏,可用方向键移动,Shift 加方向键调整大小", { exact: true }); await page.setViewportSize({ width: 1920, height: 480 });
await heading.focus(); await expect.poll(async () => (await manager.boundingBox())!.height).toBe(424);
for (let index = 0; index < 20; index++) await page.keyboard.press("Shift+ArrowUp");
expect((await manager.boundingBox())!.height).toBeLessThanOrEqual(441);
await manager.getByRole("combobox", { name: "快速定位图表", exact: true }).click(); await manager.getByRole("combobox", { name: "快速定位图表", exact: true }).click();
await page.getByRole("option").filter({ hasText: "合成监测 P3" }).click(); await page.getByRole("option").filter({ hasText: "合成监测 P3" }).click();
await expect(card(manager, "P3")).toBeFocused(); await expect(card(manager, "P3")).toBeFocused();
@@ -369,7 +368,7 @@ test("default keyboard dragging swaps fixed slots and narrow scrolling grids ret
await expect.poll(() => manager.locator("[data-chart-manager-scroll]").evaluate((node) => node.scrollTop)).toBeLessThanOrEqual(2); await expect.poll(() => manager.locator("[data-chart-manager-scroll]").evaluate((node) => node.scrollTop)).toBeLessThanOrEqual(2);
} }
await page.setViewportSize({ width: 1440, height: 900 }); await page.setViewportSize({ width: 1440, height: 900 });
await manager.getByRole("button", { name: "最大化窗口", exact: true }).click(); await page.getByRole("button", { name: "专注图表", exact: true }).click();
await expect(manager.locator("[data-chart-layout]")).toHaveAttribute("data-chart-layout", "four"); await expect(manager.locator("[data-chart-layout]")).toHaveAttribute("data-chart-layout", "four");
await expect(slots(manager)).toHaveCount(6); await expect(slots(manager)).toHaveCount(6);
await manager.getByRole("combobox", { name: "快速定位图表", exact: true }).click(); await manager.getByRole("combobox", { name: "快速定位图表", exact: true }).click();
@@ -1,6 +1,6 @@
import { expect, test } from "@playwright/test"; import { expect, test } from "@playwright/test";
import { basename, resolve } from "node:path"; import { basename, resolve } from "node:path";
import { investigationFixture, mockInvestigationPresentation, selectInvestigation } from "./support/mock-investigation-presentation"; import { investigationFixture, mockInvestigationPresentation, selectInvestigation, showInvestigationMap, showInvestigationTasks } from "./support/mock-investigation-presentation";
const chart = (id: string, value = 28) => ({ action: "open_chart", chart_id: id, evidence_refs: ["synthetic:pressure"], const chart = (id: string, value = 28) => ({ action: "open_chart", chart_id: id, evidence_refs: ["synthetic:pressure"],
chart: { title: `合成监测 ${id}`, chart_type: "line", x_data: ["07:45", "08:00"], series: [{ name: "压力(m)", data: [32, value] }] } }); chart: { title: `合成监测 ${id}`, chart_type: "line", x_data: ["07:45", "08:00"], series: [{ name: "压力(m)", data: [32, value] }] } });
@@ -17,10 +17,12 @@ test("one manager receives live charts and keeps independent enlarged children",
const task = investigationFixture(1, "多图统一窗口验收"); const task = investigationFixture(1, "多图统一窗口验收");
const mock = await mockInvestigationPresentation(page, [task]); const mock = await mockInvestigationPresentation(page, [task]);
await selectInvestigation(page, task.title); await selectInvestigation(page, task.title);
await expect(page.getByLabel("调查实时展示", { exact: true })).toContainText("实时跟随");
await mock.emit(task, chart("P1")); await mock.emit(task, chart("P1"));
const manager = page.getByRole("dialog", { name: "图表管理", exact: true }); const manager = page.getByRole("dialog", { name: "图表管理", exact: true });
await expect(manager).toBeVisible(); await expect(manager).toBeVisible();
await mock.emit(task, chart("P2")); await mock.emit(task, chart("P2"));
await manager.locator("[data-managed-chart]").filter({ hasText: "合成监测 P2" }).scrollIntoViewIfNeeded();
await expect(manager.getByRole("img", { name: "合成监测 P2", exact: true })).toBeVisible(); await expect(manager.getByRole("img", { name: "合成监测 P2", exact: true })).toBeVisible();
await expect(page.locator("[data-floating-window]")).toHaveCount(1); await expect(page.locator("[data-floating-window]")).toHaveCount(1);
await expect(manager).toContainText("2 张图表"); await expect(manager).toContainText("2 张图表");
@@ -45,7 +47,7 @@ test("one manager receives live charts and keeps independent enlarged children",
expect((await first.boundingBox())!.width).toBe(1424); expect((await first.boundingBox())!.width).toBe(1424);
await first.getByRole("button", { name: "关闭窗口", exact: true }).click(); await first.getByRole("button", { name: "关闭窗口", exact: true }).click();
await manager.locator(".floating-window-heading").focus(); await manager.locator(".floating-window-heading").focus();
await manager.getByRole("button", { name: "最大化窗口", exact: true }).click(); await page.getByRole("button", { name: "专注图表", exact: true }).click();
await page.evaluate(() => document.fonts.ready); await page.evaluate(() => document.fonts.ready);
await testInfo.attach("chart-manager-desktop", { body: await manager.screenshot({ path: testInfo.outputPath("chart-manager-desktop.png") }), contentType: "image/png" }); await testInfo.attach("chart-manager-desktop", { body: await manager.screenshot({ path: testInfo.outputPath("chart-manager-desktop.png") }), contentType: "image/png" });
for (const width of [375, 320]) { for (const width of [375, 320]) {
@@ -61,6 +63,7 @@ test("one manager receives live charts and keeps independent enlarged children",
const panel = page.getByLabel("调查实时展示", { exact: true }); const panel = page.getByLabel("调查实时展示", { exact: true });
await expect(panel.locator('[data-investigation-chart="P3"]')).toHaveCount(1); await expect(panel.locator('[data-investigation-chart="P3"]')).toHaveCount(1);
await expect(page.locator("[data-floating-window]")).toHaveCount(0); await expect(page.locator("[data-floating-window]")).toHaveCount(0);
if (page.viewportSize()!.width >= 1024) await showInvestigationMap(page);
await panel.getByRole("button", { name: "打开图表管理", exact: true }).click(); await panel.getByRole("button", { name: "打开图表管理", exact: true }).click();
await expect(manager).toContainText("3 张图表"); await expect(manager).toContainText("3 张图表");
expect(mock.mutations).toEqual([]); expect(mock.mutations).toEqual([]);
@@ -87,21 +90,27 @@ test("opening, switching, refreshing and reconnecting tasks restores charts sile
await expect(panel.locator('[data-investigation-chart="P1"]')).toHaveCount(1); await expect(panel.locator('[data-investigation-chart="P1"]')).toHaveCount(1);
await expect(page.locator("[data-floating-window]")).toHaveCount(0); await expect(page.locator("[data-floating-window]")).toHaveCount(0);
// Create a live request before returning to the same task later. // Create a live request before returning to the same task later.
await expect(panel).toContainText("实时跟随");
await mock.emit(running, chart("P1", 23)); await mock.emit(running, chart("P1", 23));
await expect(manager).toBeVisible(); await expect(manager).toBeVisible();
await manager.getByRole("button", { name: "关闭窗口", exact: true }).click(); await manager.getByRole("button", { name: "关闭窗口", exact: true }).click();
const tasks = page.getByRole("region", { name: "工况任务", exact: true }); const tasks = page.getByRole("region", { name: "工况任务", exact: true });
await showInvestigationTasks(page);
await tasks.getByText(completed.title, { exact: true }).first().click(); await tasks.getByText(completed.title, { exact: true }).first().click();
await expect(panel.locator('[data-investigation-chart="P2"]')).toHaveCount(1); await expect(panel.locator('[data-investigation-chart="P2"]')).toHaveCount(1);
await showInvestigationMap(page);
await expect(panel.getByRole("img", { name: "合成监测 报告", exact: true })).toBeVisible(); await expect(panel.getByRole("img", { name: "合成监测 报告", exact: true })).toBeVisible();
await expect(page.locator("[data-floating-window]")).toHaveCount(0); await expect(page.locator("[data-floating-window]")).toHaveCount(0);
await showInvestigationMap(page);
await panel.getByRole("button", { name: "打开图表管理", exact: true }).click(); await panel.getByRole("button", { name: "打开图表管理", exact: true }).click();
await expect(manager).toContainText("2 张图表"); await expect(manager).toContainText("2 张图表");
await expect(manager.getByRole("img", { name: "合成监测 报告", exact: true })).toBeVisible(); await expect(manager.getByRole("img", { name: "合成监测 报告", exact: true })).toBeVisible();
await manager.getByRole("button", { name: "关闭窗口", exact: true }).click(); await manager.getByRole("button", { name: "关闭窗口", exact: true }).click();
await showInvestigationTasks(page);
await tasks.getByText(running.title, { exact: true }).first().click(); await tasks.getByText(running.title, { exact: true }).first().click();
await expect(panel.locator('[data-investigation-chart="P1"]')).toHaveCount(1); await expect(panel.locator('[data-investigation-chart="P1"]')).toHaveCount(1);
await expect(page.locator("[data-floating-window]")).toHaveCount(0); await expect(page.locator("[data-floating-window]")).toHaveCount(0);
await showInvestigationMap(page);
await panel.getByRole("button", { name: "打开图表管理", exact: true }).click(); await panel.getByRole("button", { name: "打开图表管理", exact: true }).click();
await expect(manager).toBeVisible(); await expect(manager).toBeVisible();
await page.reload({ waitUntil: "domcontentloaded" }); await page.reload({ waitUntil: "domcontentloaded" });
+40 -10
View File
@@ -1,6 +1,25 @@
import { expect, test } from "@playwright/test"; import { expect, test, type Locator, type Page } from "@playwright/test";
import { mockInvestigationPresentation } from "./support/mock-investigation-presentation"; import { mockInvestigationPresentation } from "./support/mock-investigation-presentation";
async function selectSecondObject(page: Page, surface: Locator) {
const select = surface.getByRole("combobox", { name: "选择图表对象", exact: true });
let label: string;
if (await select.isVisible()) {
await select.click();
const option = page.getByRole("option").nth(1);
label = (await option.innerText()).trim();
await option.click();
} else {
const button = surface.getByRole("button", { name: /^切换对象 / }).nth(1);
label = (await button.getAttribute("aria-label"))!.replace("切换对象 ", "");
await button.click();
}
return async () => {
if (await select.isVisible()) await expect(select).toContainText(label);
else await expect(surface.getByRole("button", { name: `切换对象 ${label}`, exact: true })).toHaveAttribute("aria-pressed", "true");
};
}
test.use({ reducedMotion: "reduce", viewport: { width: 1600, height: 1000 } }); test.use({ reducedMotion: "reduce", viewport: { width: 1600, height: 1000 } });
for (const target of ["manager", "child"] as const) { for (const target of ["manager", "child"] as const) {
test(`resizing ${target} reflows charts at their actual dimensions without stretching text`, async ({ page }, testInfo) => { test(`resizing ${target} reflows charts at their actual dimensions without stretching text`, async ({ page }, testInfo) => {
@@ -13,6 +32,7 @@ for (const target of ["manager", "child"] as const) {
await page.getByRole("option", { name: "复杂图表:多测点与长时序", exact: true }).click(); await page.getByRole("option", { name: "复杂图表:多测点与长时序", exact: true }).click();
await tools.getByRole("button", { name: "执行本地预览", exact: true }).click(); await tools.getByRole("button", { name: "执行本地预览", exact: true }).click();
await expect(tools.getByRole("status")).toContainText("本地预览完成", { timeout: 20_000 }); await expect(tools.getByRole("status")).toContainText("本地预览完成", { timeout: 20_000 });
await page.getByRole("button", { name: "切换地图 Dev Panel" }).click();
const panel = page.getByLabel("本地预览展示", { exact: true }); const panel = page.getByLabel("本地预览展示", { exact: true });
await panel.getByRole("button", { name: "打开图表管理", exact: true }).click(); await panel.getByRole("button", { name: "打开图表管理", exact: true }).click();
const manager = page.getByRole("dialog", { name: "图表管理", exact: true }); const manager = page.getByRole("dialog", { name: "图表管理", exact: true });
@@ -27,7 +47,8 @@ for (const target of ["manager", "child"] as const) {
size: getComputedStyle(node).fontSize, height: node.getBoundingClientRect().height size: getComputedStyle(node).fontSize, height: node.getBoundingClientRect().height
})); }));
const before = (await popup.boundingBox())!; const before = (await popup.boundingBox())!;
const handle = (await popup.locator(".floating-window-resize").boundingBox())!; const resizeControl = target === "manager" ? page.getByRole("separator", { name: "调整地图与报告宽度" }) : popup.locator(".floating-window-resize");
const handle = (await resizeControl.boundingBox())!;
const session = await page.context().newCDPSession(page); const session = await page.context().newCDPSession(page);
await session.send("Emulation.setCPUThrottlingRate", { rate: 4 }); await session.send("Emulation.setCPUThrottlingRate", { rate: 4 });
await session.send("Performance.enable"); await session.send("Performance.enable");
@@ -41,9 +62,12 @@ for (const target of ["manager", "child"] as const) {
}); });
const first = await session.send("Performance.getMetrics"); const first = await session.send("Performance.getMetrics");
const started = Date.now(); const started = Date.now();
await page.mouse.move(handle.x + handle.width - 3, handle.y + handle.height - 3); const pointer = target === "manager"
? { x: handle.x + handle.width / 2, y: handle.y + handle.height / 2, dx: -128, dy: 0 }
: { x: handle.x + handle.width - 3, y: handle.y + handle.height - 3, dx: 128, dy: 64 };
await page.mouse.move(pointer.x, pointer.y);
await page.mouse.down(); await page.mouse.down();
await page.mouse.move(handle.x + handle.width - 3 + 128, handle.y + handle.height - 3 + 64, { steps: 32 }); await page.mouse.move(pointer.x + pointer.dx, pointer.y + pointer.dy, { steps: 32 });
// While the pointer is still held, layout and the chart drawing must adapt together. // While the pointer is still held, layout and the chart drawing must adapt together.
await expect.poll(() => popup.locator(".echarts-for-react").first().evaluate((node) => Math.abs(node.clientWidth - Number(node.querySelector("svg")?.getAttribute("width"))))).toBeLessThan(1); await expect.poll(() => popup.locator(".echarts-for-react").first().evaluate((node) => Math.abs(node.clientWidth - Number(node.querySelector("svg")?.getAttribute("width"))))).toBeLessThan(1);
await expect.poll(() => popup.locator(".echarts-for-react").first().evaluate((node) => Math.abs(node.clientHeight - Number(node.querySelector("svg")?.getAttribute("height"))))).toBeLessThan(1); await expect.poll(() => popup.locator(".echarts-for-react").first().evaluate((node) => Math.abs(node.clientHeight - Number(node.querySelector("svg")?.getAttribute("height"))))).toBeLessThan(1);
@@ -65,7 +89,7 @@ for (const target of ["manager", "child"] as const) {
console.info("Chart resize profile", JSON.stringify(summary)); console.info("Chart resize profile", JSON.stringify(summary));
await testInfo.attach("resize-profile", { body: JSON.stringify(summary, null, 2), contentType: "application/json" }); await testInfo.attach("resize-profile", { body: JSON.stringify(summary, null, 2), contentType: "application/json" });
expect(Math.round(preview.width - before.width)).toBe(128); expect(Math.round(preview.width - before.width)).toBe(128);
expect(Math.round(preview.height - before.height)).toBe(64); expect(Math.round(preview.height - before.height)).toBe(target === "manager" ? 0 : 64);
expect(during).toBeGreaterThan(0); expect(during).toBeGreaterThan(0);
// Bound the expensive work on the same 4x CPU fixture used to reproduce the lag. // Bound the expensive work on the same 4x CPU fixture used to reproduce the lag.
expect(summary.elapsedMs).toBeLessThan(12_000); expect(summary.elapsedMs).toBeLessThan(12_000);
@@ -89,13 +113,13 @@ for (const target of ["manager", "child"] as const) {
await testInfo.attach("resize-layout", { body: JSON.stringify(layout, null, 2), contentType: "application/json" }); await testInfo.attach("resize-layout", { body: JSON.stringify(layout, null, 2), contentType: "application/json" });
await session.send("Emulation.setCPUThrottlingRate", { rate: 1 }); await session.send("Emulation.setCPUThrottlingRate", { rate: 1 });
const chartSurface = target === "manager" ? manager.getByRole("group", { name: "合成全天压力对比", exact: true }) : popup; const chartSurface = target === "manager" ? manager.getByRole("group", { name: "合成全天压力对比", exact: true }) : popup;
const selectedObject = chartSurface.getByRole("button", { name: /^切换对象 / }).nth(1); const expectSelectedObject = await selectSecondObject(page, chartSurface);
await selectedObject.click();
const hiddenSeries = chartSurface.getByLabel("显示的数据序列").getByRole("button").last(); const hiddenSeries = chartSurface.getByLabel("显示的数据序列").getByRole("button").last();
await hiddenSeries.click(); await hiddenSeries.click();
await expect(selectedObject).toHaveAttribute("aria-pressed", "true"); await expectSelectedObject();
await expect(hiddenSeries).toHaveAttribute("aria-pressed", "false"); await expect(hiddenSeries).toHaveAttribute("aria-pressed", "false");
const selectedInstance = await chartSurface.locator(".echarts-for-react").first().getAttribute("_echarts_instance_"); const selectedInstance = await chartSurface.locator(".echarts-for-react").first().getAttribute("_echarts_instance_");
if (target === "child") {
const beforeCancel = (await popup.boundingBox())!; const beforeCancel = (await popup.boundingBox())!;
const cancelHandle = popup.locator(".floating-window-resize"); const cancelHandle = popup.locator(".floating-window-resize");
const cancelBox = (await cancelHandle.boundingBox())!; const cancelBox = (await cancelHandle.boundingBox())!;
@@ -112,7 +136,7 @@ for (const target of ["manager", "child"] as const) {
await page.mouse.up(); await page.mouse.up();
await expect.poll(() => popup.boundingBox()).toEqual(beforeCancel); await expect.poll(() => popup.boundingBox()).toEqual(beforeCancel);
await expect(popup.locator("[data-floating-window-document]")).toHaveCSS("transform", "none"); await expect(popup.locator("[data-floating-window-document]")).toHaveCSS("transform", "none");
await expect(selectedObject).toHaveAttribute("aria-pressed", "true"); await expectSelectedObject();
await expect(hiddenSeries).toHaveAttribute("aria-pressed", "false"); await expect(hiddenSeries).toHaveAttribute("aria-pressed", "false");
const boundaryBox = (await cancelHandle.boundingBox())!; const boundaryBox = (await cancelHandle.boundingBox())!;
await page.mouse.move(boundaryBox.x + boundaryBox.width - 3, boundaryBox.y + boundaryBox.height - 3); await page.mouse.move(boundaryBox.x + boundaryBox.width - 3, boundaryBox.y + boundaryBox.height - 3);
@@ -122,7 +146,13 @@ for (const target of ["manager", "child"] as const) {
const final = (await popup.boundingBox())!; const final = (await popup.boundingBox())!;
expect(Math.round(final.x + final.width)).toBe(1592); expect(Math.round(final.x + final.width)).toBe(1592);
expect(Math.round(final.y + final.height)).toBe(992); expect(Math.round(final.y + final.height)).toBe(992);
await expect(selectedObject).toHaveAttribute("aria-pressed", "true"); } else {
await expect(popup.locator("[data-window-resize-handle]")).toHaveCount(0);
await resizeControl.focus();
await page.keyboard.press("ArrowRight");
await page.keyboard.press("ArrowLeft");
}
await expectSelectedObject();
await expect(hiddenSeries).toHaveAttribute("aria-pressed", "false"); await expect(hiddenSeries).toHaveAttribute("aria-pressed", "false");
await expect(chartSurface.locator(".echarts-for-react").first()).toHaveAttribute("_echarts_instance_", selectedInstance!); await expect(chartSurface.locator(".echarts-for-react").first()).toHaveAttribute("_echarts_instance_", selectedInstance!);
await expect.poll(() => chartSurface.locator(".echarts-for-react").first().evaluate((node) => Math.abs(node.clientWidth - Number(node.querySelector("svg")?.getAttribute("width"))))).toBeLessThan(1); await expect.poll(() => chartSurface.locator(".echarts-for-react").first().evaluate((node) => Math.abs(node.clientWidth - Number(node.querySelector("svg")?.getAttribute("width"))))).toBeLessThan(1);
@@ -35,7 +35,7 @@ test("调查 SVG 兼容 HTML 换行并保留节点交互与错误兜底", async
}; };
const root = createRoot(document.getElementById("diagrams")); const root = createRoot(document.getElementById("diagrams"));
const render = () => root.render(React.createElement(React.Fragment, null, const render = () => root.render(React.createElement(React.Fragment, null,
React.createElement(InvestigationDiagramView, { diagram, running: true, React.createElement(InvestigationDiagramView, { diagram,
renderDetails: () => React.createElement("p", null, "已保存的 SCADA 引用依据") }), renderDetails: () => React.createElement("p", null, "已保存的 SCADA 引用依据") }),
React.createElement(InvestigationDiagramView, { diagram: { title: "错误兜底检查", mermaid: "flowchart TD\nA[未闭合", node_refs: [] }, React.createElement(InvestigationDiagramView, { diagram: { title: "错误兜底检查", mermaid: "flowchart TD\nA[未闭合", node_refs: [] },
renderDetails: () => null }) renderDetails: () => null })
@@ -47,7 +47,7 @@ test("调查 SVG 兼容 HTML 换行并保留节点交互与错误兜底", async
await expect(graph.locator("svg .node")).toHaveCount(3); await expect(graph.locator("svg .node")).toHaveCount(3);
await expect(graph.locator("svg foreignObject br")).toHaveCount(2); await expect(graph.locator("svg foreignObject br")).toHaveCount(2);
await expect(graph.locator("svg .cluster-label")).toContainText("证据核对"); await expect(graph.locator("svg .cluster-label")).toContainText("证据核对");
await expect(graph.locator("svg .tjRunning")).toHaveCount(1); await expect(graph.locator("svg .tjReference")).toHaveCount(3);
await expect(graph).not.toContainText("This page contains the following errors"); await expect(graph).not.toContainText("This page contains the following errors");
await graph.locator(".node").filter({ hasText: "读取SCADA" }).click(); await graph.locator(".node").filter({ hasText: "读取SCADA" }).click();
await expect(graph.getByLabel("节点详情 上游监测")).toContainText("已保存的 SCADA 引用依据"); await expect(graph.getByLabel("节点详情 上游监测")).toContainText("已保存的 SCADA 引用依据");
@@ -81,10 +81,17 @@ test("调查 SVG 兼容 HTML 换行并保留节点交互与错误兜底", async
await graph.getByRole("button", { name: "放大查看", exact: true }).click(); await graph.getByRole("button", { name: "放大查看", exact: true }).click();
await expect(detail.locator("svg .node")).toHaveCount(3); await expect(detail.locator("svg .node")).toHaveCount(3);
expect(await page.evaluate(() => (window as unknown as { diagramRenderCount: number }).diagramRenderCount)).toBe(1); expect(await page.evaluate(() => (window as unknown as { diagramRenderCount: number }).diagramRenderCount)).toBe(1);
await detail.evaluate(async (element) => {
await Promise.allSettled(element.getAnimations()
.filter((animation) => Number.isFinite(Number(animation.effect?.getComputedTiming().endTime)))
.map((animation) => animation.finished));
});
const narrowBox = (await detail.boundingBox())!; const narrowBox = (await detail.boundingBox())!;
expect(narrowBox.width).toBeLessThanOrEqual(343); const viewport = page.viewportSize()!;
expect(narrowBox.height).toBeLessThanOrEqual(688); expect(narrowBox.x).toBeGreaterThanOrEqual(0);
expect(narrowBox.x).toBeGreaterThanOrEqual(15); expect(narrowBox.y).toBeGreaterThanOrEqual(0);
expect(narrowBox.x + narrowBox.width).toBeLessThanOrEqual(viewport.width);
expect(narrowBox.y + narrowBox.height).toBeLessThanOrEqual(viewport.height);
await detail.screenshot({ path: testInfo.outputPath("diagram-expanded-narrow.png") }); await detail.screenshot({ path: testInfo.outputPath("diagram-expanded-narrow.png") });
await page.evaluate(() => (window as unknown as { updateDiagram: () => void }).updateDiagram()); await page.evaluate(() => (window as unknown as { updateDiagram: () => void }).updateDiagram());
await expect(detail.locator("svg .node")).toHaveCount(4); await expect(detail.locator("svg .node")).toHaveCount(4);
@@ -2,7 +2,7 @@ import { expect, test } from "@playwright/test";
import { mockAgentApi } from "./support/mock-agent-api"; import { mockAgentApi } from "./support/mock-agent-api";
for (const width of [1440, 375, 320]) { for (const width of [1440, 375, 320]) {
test(`investigation diagram displays recorded node states at ${width}px`, async ({ page }, testInfo) => { test(`investigation diagram displays saved reference annotations at ${width}px`, async ({ page }, testInfo) => {
await page.setViewportSize({ width, height: 900 }); await page.setViewportSize({ width, height: 900 });
await page.emulateMedia({ reducedMotion: "reduce" }); await page.emulateMedia({ reducedMotion: "reduce" });
await mockAgentApi(page); await mockAgentApi(page);
@@ -18,84 +18,57 @@ for (const width of [1440, 375, 320]) {
const clientModule = await import(clientUrl); const clientModule = await import(clientUrl);
const { createRoot } = clientModule.default ?? clientModule; const { createRoot } = clientModule.default ?? clientModule;
const { InvestigationDiagramView } = await import("/src/features/workbench/components/investigation-diagram-view.tsx"); const { InvestigationDiagramView } = await import("/src/features/workbench/components/investigation-diagram-view.tsx");
const diagram = { const { investigationDiagramSchema } = await import("/src/features/workbench/api/investigation-report.ts");
title: "调查节点状态", const diagram = investigationDiagramSchema.parse({
mermaid: 'flowchart TD\nP[待启动核查] --> R[核对监测]:::tjAction\nR --> C[核查完成]:::tjHuman\nR --> W[等待系统结果]\nR --> H[等待人工复核]\nC --> F:::tjHuman\nC --> S[未选用分支]\nW --> X[取消分支]\nH --> U:::tjAction\nstyle R fill:#FFF6E8,stroke:#C4A168;', title: "调查流程参考",
mermaid: "flowchart TD\nREF[核查方向] --> RESULT[监测结果]\nREF --> NEED[资料缺口]\nRESULT --> FAIL[首次尝试失败]\nRESULT --> OTHER[未采用分支]\nNEED --> OLD[旧执行中标记]:::tjRunning\nNEED --> UNSET[无标记步骤]",
node_refs: [ node_refs: [
{ node_id: "P", label: "待启动核查", status: "pending", evidence_refs: [], action_refs: [] }, { node_id: "REF", label: "核查方向", status: "reference" },
{ node_id: "R", label: "核对监测", status: "running", evidence_refs: ["e1"], action_refs: ["50000000-0000-4000-8000-000000000001"] }, { node_id: "RESULT", label: "监测结果", status: "recorded" },
{ node_id: "C", label: "核查完成", status: "completed", evidence_refs: [], action_refs: [] }, { node_id: "NEED", label: "资料缺口", status: "needs_input" },
{ node_id: "W", label: "等待系统结果", status: "waiting", evidence_refs: [], action_refs: [] }, { node_id: "FAIL", label: "首次尝试失败", status: "failed", detail: "此前计算超时,保留原尝试。" },
{ node_id: "H", label: "等待人工复核", status: "waiting_human", evidence_refs: [], action_refs: [] }, { node_id: "OTHER", label: "未采用分支", status: "not_taken" },
{ node_id: "F", label: "查询失败", status: "failed", evidence_refs: [], action_refs: [] }, { node_id: "OLD", label: "旧执行中标记", status: "running" },
{ node_id: "S", label: "未选用分支", status: "skipped", evidence_refs: [], action_refs: [] }, { node_id: "UNSET", label: "无标记步骤" }
{ node_id: "X", label: "取消分支", status: "cancelled", evidence_refs: [], action_refs: [] },
{ node_id: "U", label: "状态未记录", evidence_refs: ["e2"], action_refs: [] }
] ]
}; });
const root = createRoot(document.getElementById("state-reader")); const root = createRoot(document.getElementById("state-reader"));
const render = (running: boolean) => root.render(React.createElement(InvestigationDiagramView, { const render = () => root.render(React.createElement(InvestigationDiagramView, {
diagram: { ...diagram, node_refs: [...diagram.node_refs] }, running, diagram: { ...diagram, node_refs: [...diagram.node_refs] },
renderDetails: () => React.createElement("p", null, "状态来自节点快照,关联证据不代表步骤已经完成。") renderDetails: () => React.createElement("p", null, "图中标记来自最近整理,实际任务状态在任务记录中查看。")
})); }));
Object.assign(window, { setDiagramState: (running: boolean, status = "running") => { Object.assign(window, { updateReferenceAnnotation: () => { diagram.node_refs[0].status = "recorded"; render(); } });
diagram.node_refs[1].status = status; render();
render(running);
} });
render(true);
}); });
const diagram = page.getByRole("region", { name: "调查脉络", exact: true }); const diagram = page.getByRole("region", { name: "调查脉络", exact: true });
const node = (className: string) => diagram.locator(`svg g.node.${className}`); await expect(diagram.locator("svg g.node")).toHaveCount(7);
const shape = (className: string) => node(className).locator("rect,polygon,circle,ellipse,path").first(); await expect(diagram.locator("svg g.node.tjReference")).toHaveCount(3);
await expect(diagram.locator("svg g.node")).toHaveCount(9); for (const [className, fill] of [["tjRecorded", "rgb(237, 247, 244)"], ["tjNeedsInput", "rgb(255, 251, 234)"],
for (const [className, fill, stroke] of [ ["tjFailed", "rgb(254, 242, 242)"], ["tjNotTaken", "rgb(246, 248, 252)"]]) {
["tjPending", "rgb(246, 248, 252)", "rgb(165, 181, 204)"], await expect(diagram.locator(`svg g.node.${className}`)).toHaveCount(1);
["tjRunning", "rgb(232, 240, 255)", "rgb(66, 99, 199)"], await expect(diagram.locator(`svg g.node.${className}`).locator("rect,polygon").first()).toHaveCSS("fill", fill);
["tjCompleted", "rgb(237, 247, 244)", "rgb(107, 158, 139)"],
["tjWaiting", "rgb(255, 251, 234)", "rgb(200, 172, 96)"],
["tjWaitingHuman", "rgb(255, 246, 232)", "rgb(196, 161, 104)"],
["tjFailed", "rgb(254, 242, 242)", "rgb(217, 108, 117)"],
["tjSkipped", "rgb(246, 248, 252)", "rgb(165, 181, 204)"],
["tjCancelled", "rgb(241, 245, 249)", "rgb(148, 163, 184)"],
["tjUnknown", "rgb(255, 255, 255)", "rgb(204, 214, 229)"]
]) {
await expect(node(className)).toHaveCount(1);
await expect(shape(className)).toHaveCSS("fill", fill);
await expect(shape(className)).toHaveCSS("stroke", stroke);
} }
const legend = diagram.getByLabel("图示状态说明"); await expect(diagram.locator("svg g.node.tjRunning,svg g.node.tjRecordedRunning")).toHaveCount(0);
await expect(legend).toContainText("等待依赖 / 外部结果"); await expect(diagram).toContainText("不实时同步执行状态");
await expect(legend).toContainText("等待人工处理"); await expect(diagram.getByLabel("图示状态说明")).toContainText("已有结果");
await expect(legend).toContainText("未标注状态"); await diagram.getByRole("button", { name: /^首次尝试失败 ·/ }).click();
expect(await shape("tjSkipped").evaluate((element) => getComputedStyle(element).strokeDasharray)).not.toBe("none"); await expect(diagram.getByLabel("节点详情 首次尝试失败")).toContainText("此前计算超时");
await diagram.getByRole("button", { name: /^核对监测 · 正在执行/ }).click();
await expect(diagram.getByLabel("节点详情 核对监测")).toContainText("正在执行");
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(width); expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(width);
await diagram.screenshot({ path: testInfo.outputPath(`node-states-${width}.png`) }); await diagram.screenshot({ path: testInfo.outputPath(`reference-states-${width}.png`) });
await diagram.getByRole("button", { name: "放大查看", exact: true }).click(); await diagram.getByRole("button", { name: "放大查看", exact: true }).click();
const reader = page.getByRole("dialog", { name: "调查节点状态", exact: true }); const reader = page.getByRole("dialog", { name: "调查流程参考", exact: true });
await expect(reader.locator("svg g.node.tjRunning > rect")).toHaveCSS("fill", "rgb(232, 240, 255)"); await expect(reader.locator("svg g.node")).toHaveCount(7);
const bounds = (await reader.boundingBox())!;
expect(bounds.width).toBeLessThan(width);
expect(bounds.height).toBeLessThan(900);
await reader.getByRole("button", { name: "Zoom in", exact: true }).click(); await reader.getByRole("button", { name: "Zoom in", exact: true }).click();
const application = reader.getByRole("application"); const application = reader.getByRole("application");
const transform = await application.evaluate((element) => { const transform = await application.evaluate((element) => {
element.setAttribute("data-state-test-instance", "retained"); element.setAttribute("data-reference-instance", "retained");
return (element as HTMLElement).style.transform; return (element as HTMLElement).style.transform;
}); });
await page.evaluate(() => (window as unknown as { setDiagramState: (running: boolean) => void }).setDiagramState(false)); await page.evaluate(() => (window as unknown as { updateReferenceAnnotation: () => void }).updateReferenceAnnotation());
const archived = reader.locator("svg g.node.tjRecordedRunning > rect"); await expect(reader.locator("svg g.node.tjRecorded")).toHaveCount(2);
await expect(archived).toHaveCSS("fill", "rgb(246, 248, 252)"); await expect(reader.locator("svg g.node.tjFailed")).toHaveCount(1);
await expect(reader.getByLabel("图示状态说明")).toContainText("记录时执行中"); await expect(application).toHaveAttribute("data-reference-instance", "retained");
await expect(reader.locator("svg g.node.tjCompleted > rect")).toHaveCSS("fill", "rgb(237, 247, 244)");
await expect(reader.locator("svg g.node")).toHaveCount(9);
await expect(application).toHaveAttribute("data-state-test-instance", "retained");
expect(await application.evaluate((element) => (element as HTMLElement).style.transform)).toBe(transform); expect(await application.evaluate((element) => (element as HTMLElement).style.transform)).toBe(transform);
await page.evaluate(() => (window as unknown as { setDiagramState: (running: boolean, status: string) => void }).setDiagramState(true, "completed")); await expect(reader).not.toContainText("正在执行");
await expect(reader.locator("svg g.node.tjCompleted")).toHaveCount(2);
await expect(reader.locator("svg g.node.tjRunning")).toHaveCount(0);
await expect(reader.getByLabel("节点详情 核对监测")).toContainText("已完成");
}); });
} }
@@ -0,0 +1,92 @@
import { expect, test } from "@playwright/test";
import { mockAgentApi } from "./support/mock-agent-api";
for (const width of [1440, 375]) {
test(`retains failed investigation paths through updates and new rounds at ${width}px`, async ({ page }, testInfo) => {
await page.setViewportSize({ width, height: 1000 });
await page.emulateMedia({ reducedMotion: "reduce" });
await mockAgentApi(page);
await page.goto("/", { waitUntil: "domcontentloaded" });
await page.setContent('<html lang="zh-CN"><head><link rel="stylesheet" href="/src/styles.css"></head><body><main id="reader" class="workbench-shadcn-surface bg-background text-foreground" style="max-width:900px;margin:auto;padding:12px"></main></body></html>');
await page.evaluate(async () => {
const entry = await (await fetch("/src/main.tsx")).text();
const reactUrl = entry.match(/from "([^"\n]*\/react\.js[^"\n]*)"/)?.[1];
const clientUrl = entry.match(/from "([^"\n]*\/react-dom_client\.js[^"\n]*)"/)?.[1];
if (!reactUrl || !clientUrl) throw new Error("Vite React module paths unavailable");
const reactModule = await import(reactUrl);
const React = reactModule.default ?? reactModule;
const clientModule = await import(clientUrl);
const { createRoot } = clientModule.default ?? clientModule;
const { InvestigationTaskReport } = await import("/src/features/workbench/components/investigation-task-report.tsx");
const { investigationDiagramSchema } = await import("/src/features/workbench/api/investigation-report.ts");
const now = "2026-11-10T01:00:00Z";
const initial = investigationDiagramSchema.parse({
title: "SCADA 累计调查脉络", source_mermaid: null,
mermaid: 'flowchart TD\nread["读取全量 SCADA"]\nlocate_1["第一次定位(失败)"]\nread --> locate_1',
node_refs: [
{ node_id: "read", label: "读取全量 SCADA", status: "recorded" },
{ node_id: "locate_1", label: "第一次定位", status: "failed", detail: "计算超时,已保留本次失败记录。" }
], edges: [{ source: "read", target: "locate_1" }]
});
const report = { revision: 1, execution_generation: 1, published_at: now, source_session_id: "session-1", report: {
title: "SCADA 调查", current_conclusion: "首次定位超时,继续核查。", conclusion_boundary: "现有资料",
stage: "final", outcome: "concluded", data_gaps: [], evidence_refs: [], recommendations: [], pending_items: [],
diagram: initial
} };
let task = { task_id: "cumulative-graph", title: "SCADA 数据问题调查", summary: "保留失败路径后继续调查",
execution_generation: 1, status: "running", lifecycle_status: "open", latest_report: report,
latest_plan: null, actions: [], evidence: [], questions: [],
active_run: { run_id: "run-1", status: "running" },
latest_progress: { revision: 1, run_id: "run-1", execution_generation: 1, published_at: now,
progress: { summary: "首次定位失败", diagram: initial } }
};
const root = createRoot(document.getElementById("reader"));
const render = () => root.render(React.createElement(InvestigationTaskReport, {
task, onContinue: () => undefined, renderAction: () => null, renderEvidence: () => null,
onLoadReports: async () => ({ items: [report], next_offset: null })
}));
Object.assign(window, { advanceInvestigationGraph: () => {
const diagram = investigationDiagramSchema.parse({ ...initial,
mermaid: initial.mermaid + '\nlocate_2["调整窗口重试"]\nlocate_1 -->|"重试"| locate_2',
node_refs: [...initial.node_refs, { node_id: "locate_2", label: "调整窗口重试", status: "recorded" }],
edges: [...initial.edges!, { source: "locate_1", target: "locate_2", label: "重试" }]
});
task = { ...task, execution_generation: 2, active_run: { run_id: "run-2", status: "running" },
latest_progress: { ...task.latest_progress, execution_generation: 2, run_id: "run-2", revision: 1,
progress: { summary: "重试成功,原失败记录保留", diagram } }
};
render();
}, startNextGraphRound: () => { task = { ...task, execution_generation: 3 }; render(); },
stopGraphRun: () => {
Object.assign(task, { active_run: null, status: "completed", lifecycle_status: "completed" });
render();
} });
render();
});
const graph = page.getByRole("region", { name: "调查脉络", exact: true });
await expect(graph.locator("svg g.node")).toHaveCount(2);
await expect(graph.locator("svg g.node.tjFailed")).toHaveCount(1);
await graph.getByRole("button", { name: /^第一次定位 ·/ }).click();
await expect(graph.getByLabel("节点详情 第一次定位")).toContainText("计算超时");
await page.evaluate(() => (window as unknown as { advanceInvestigationGraph: () => void }).advanceInvestigationGraph());
await expect(graph.locator("svg g.node")).toHaveCount(3);
await expect(graph.locator("svg g.node.tjFailed")).toHaveCount(1);
await expect(graph.locator("svg g.node.tjRecorded")).toHaveCount(2);
await expect(graph.locator("svg g.node").filter({ hasText: "第一次定位(失败)" })).toHaveCount(1);
await expect(graph.getByLabel("节点详情 第一次定位")).toContainText("计算超时");
await page.evaluate(() => (window as unknown as { startNextGraphRound: () => void }).startNextGraphRound());
await expect(graph.locator("svg g.node")).toHaveCount(3);
await expect(graph.locator("svg g.node.tjFailed > rect")).toHaveCSS("fill", "rgb(254, 242, 242)");
await page.evaluate(() => (window as unknown as { stopGraphRun: () => void }).stopGraphRun());
await expect(graph.locator("svg g.node.tjRecorded")).toHaveCount(2);
await expect(graph.locator("svg g.node.tjFailed")).toHaveCount(1);
await expect(graph).toContainText("不实时同步执行状态");
await graph.screenshot({ path: testInfo.outputPath(`cumulative-failed-path-${width}.png`) });
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(width);
await page.getByRole("button", { name: "展开报告版本", exact: true }).click();
await page.getByRole("dialog", { name: "报告版本", exact: true }).getByRole("button", { name: /第 1 轮 · 报告第 1 版/ }).click();
await expect(graph.locator("svg g.node")).toHaveCount(2);
await page.getByRole("button", { name: "返回实时内容", exact: true }).click();
await expect(graph.locator("svg g.node")).toHaveCount(3);
});
}
@@ -20,13 +20,19 @@ test("调查图加载与尺寸变化保持阅读位置,刷新后仍可缩放
const renderer = investigationDiagramPlugins.mermaid.getMermaid.bind(investigationDiagramPlugins.mermaid); const renderer = investigationDiagramPlugins.mermaid.getMermaid.bind(investigationDiagramPlugins.mermaid);
let release: (() => void) | undefined; let release: (() => void) | undefined;
let renderPending = false; let renderPending = false;
let holdRender = true;
let completedRenders = 0;
investigationDiagramPlugins.mermaid.getMermaid = (config: unknown) => { investigationDiagramPlugins.mermaid.getMermaid = (config: unknown) => {
const instance = renderer(config); const instance = renderer(config);
return { ...instance, async render(id: string, source: string) { return { ...instance, async render(id: string, source: string) {
if (holdRender) {
renderPending = true; renderPending = true;
await new Promise<void>((resolve) => { release = resolve; }); await new Promise<void>((resolve) => { release = resolve; });
renderPending = false; renderPending = false;
return instance.render(id, source); }
const result = await instance.render(id, source);
completedRenders++;
return result;
} }; } };
}; };
const root = createRoot(document.getElementById("reader")); const root = createRoot(document.getElementById("reader"));
@@ -45,6 +51,8 @@ test("调查图加载与尺寸变化保持阅读位置,刷新后仍可缩放
)); ));
Object.assign(window, { investigationFixture: { Object.assign(window, { investigationFixture: {
release: () => release?.(), pending: () => renderPending, release: () => release?.(), pending: () => renderPending,
hold: (value: boolean) => { holdRender = value; },
completed: () => completedRenders,
update: (next: string) => { source = next; render(); } update: (next: string) => { source = next; render(); }
}, documentHeights }); }, documentHeights });
render(); render();
@@ -82,6 +90,22 @@ test("调查图加载与尺寸变化保持阅读位置,刷新后仍可缩放
await diagram.getByRole("button", { name: "Zoom in", exact: true }).click(); await diagram.getByRole("button", { name: "Zoom in", exact: true }).click();
await expect(diagram.locator('[role="application"]')).toHaveCSS("transform", "matrix(1.1, 0, 0, 1.1, 0, 0)"); await expect(diagram.locator('[role="application"]')).toHaveCSS("transform", "matrix(1.1, 0, 0, 1.1, 0, 0)");
await diagram.getByRole("button", { name: "Reset zoom and pan", exact: true }).click(); await diagram.getByRole("button", { name: "Reset zoom and pan", exact: true }).click();
// A pending layout must not overwrite a newer source restored from cache.
await page.evaluate(() => {
const api = (window as unknown as { investigationFixture: { update: (source: string) => void } }).investigationFixture;
api.update("flowchart LR\nA[读取工单] --> B[核对监测] --> C[迟到的排版]");
});
await expect.poll(() => fixture("pending")).toBe(true);
await page.evaluate(() => {
const api = (window as unknown as { investigationFixture: { hold: (value: boolean) => void; update: (source: string) => void } }).investigationFixture;
api.hold(false);
api.update("flowchart LR\nA[读取工单] --> B[核对监测]");
});
await expect.poll(() => page.evaluate(() => (window as unknown as { investigationFixture: { completed: () => number } }).investigationFixture.completed())).toBe(3);
await fixture("release");
await expect.poll(() => page.evaluate(() => (window as unknown as { investigationFixture: { completed: () => number } }).investigationFixture.completed())).toBe(4);
await page.evaluate(() => new Promise<void>((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))));
await expect(diagram.locator("svg .node")).toHaveCount(2);
const checkCollapse = async (keyboard: boolean) => { const checkCollapse = async (keyboard: boolean) => {
const before = await page.locator("#reading-anchor").evaluate((element) => element.getBoundingClientRect().top); const before = await page.locator("#reading-anchor").evaluate((element) => element.getBoundingClientRect().top);
await diagram.getByRole("button", { name: "放大查看", exact: true }).click(); await diagram.getByRole("button", { name: "放大查看", exact: true }).click();
@@ -0,0 +1,81 @@
import { expect, test } from "@playwright/test";
import { investigationFixture, mockInvestigationPresentation, selectInvestigation, type SavedPresentationEvent } from "./support/mock-investigation-presentation";
const first = investigationFixture(71, "切换性能调查甲");
const second = investigationFixture(72, "切换性能调查乙");
const events: SavedPresentationEvent[] = [first, second].flatMap((task, taskIndex) =>
Array.from({ length: 4 }, (_, index) => ({
task_id: task.task_id, run_id: task.active_run!.run_id, execution_generation: 1,
event_seq: 11 + taskIndex * 4 + index, occurred_at: "2026-11-10T00:00:00Z",
command: { action: "open_chart", chart_id: `${taskIndex}-${index}`, evidence_refs: ["synthetic:reading"],
chart: { title: `${taskIndex ? "乙" : "甲"}任务图表${index}`, chart_type: "line",
x_data: ["07:30", "07:45", "08:00"], series: [{ name: taskIndex ? "乙任务序列" : "甲任务序列", data: [30, 29, 25] }] } },
})));
test("shows the selected report and skeleton while history waits, without rebuilding the previous task's charts", async ({ page }, testInfo) => {
await mockInvestigationPresentation(page, [first, second], [...events]);
await selectInvestigation(page, first.title);
const panel = page.locator('[data-presentation-scope="investigation"]');
await expect(panel.getByRole("img", { name: "甲任务图表0", exact: true })).toBeVisible();
await page.evaluate(async () => {
const source = await (await fetch("/src/features/agent/answer-ui/responsive-chart.tsx")).text();
const url = source.match(/from "([^"\n]*echarts-for-react[^"\n]*)"/)?.[1];
if (!url) throw new Error("Vite chart module unavailable");
const { default: Chart } = await import(url);
const calls: string[] = [];
Object.assign(window, { taskSwitchChartInitializations: calls });
let prototype = Chart.prototype;
while (prototype && !Object.hasOwn(prototype, "initEchartsInstance")) prototype = Object.getPrototypeOf(prototype);
const original = prototype.initEchartsInstance;
prototype.initEchartsInstance = function (...args: unknown[]) {
calls.push(this.props.option.series[0].name);
return original.apply(this, args);
};
});
let release!: () => void;
const waiting = new Promise<void>((resolve) => { release = resolve; });
await page.route(`**/operational-tasks/${second.task_id}/presentation-events**`, async (route) => {
await waiting;
await route.fallback();
});
await page.getByRole("region", { name: "工况任务", exact: true }).getByText(second.title, { exact: true }).first().click();
await expect(page.locator('article[aria-label="调查任务报告"] h2')).toHaveText(second.title);
await expect(panel.getByRole("status", { name: "正在加载调查展示", exact: true })).toBeVisible();
await expect(panel.getByRole("img", { name: "甲任务图表0", exact: true })).toHaveCount(0);
expect(await page.evaluate(() => (window as unknown as { taskSwitchChartInitializations: string[] })
.taskSwitchChartInitializations.filter((name) => name === "甲任务序列"))).toEqual([]);
await panel.screenshot({ path: testInfo.outputPath("task-switch-loading-desktop.png") });
release();
await expect(panel.getByRole("img", { name: "乙任务图表0", exact: true })).toBeVisible();
await expect(panel.getByRole("status", { name: "正在加载调查展示", exact: true })).toHaveCount(0);
await expect(page.getByRole("dialog", { name: "图表管理", exact: true })).toHaveCount(0);
expect(await page.evaluate(() => (window as unknown as { taskSwitchChartInitializations: string[] })
.taskSwitchChartInitializations.filter((name) => name === "甲任务序列"))).toEqual([]);
});
test("keeps loading feedback readable on a narrow viewport and discards a late task response", async ({ page }, testInfo) => {
await page.setViewportSize({ width: 375, height: 800 });
await mockInvestigationPresentation(page, [first, second], [...events]);
await selectInvestigation(page, first.title);
let release!: () => void;
const waiting = new Promise<void>((resolve) => { release = resolve; });
await page.route(`**/operational-tasks/${second.task_id}/presentation-events**`, async (route) => {
await waiting;
await route.fallback();
});
// The map task selector remains available independently of the report reader.
const taskPanel = page.getByRole("region", { name: "工况任务", exact: true }).filter({ visible: true });
await taskPanel.getByRole("button", { name: "收起工况任务", exact: true }).click();
await taskPanel.getByText(second.title, { exact: true }).first().click();
await expect(page.locator('article[aria-label="调查任务报告"] h2').filter({ visible: true })).toHaveText(second.title);
const loading = page.getByRole("status", { name: "正在加载调查展示", exact: true });
await expect(loading).toBeVisible();
await taskPanel.getByRole("button", { name: "关闭工况任务", exact: true }).click();
await expect(loading).toBeVisible();
await page.screenshot({ path: testInfo.outputPath("task-switch-loading-mobile.png") });
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(375);
await selectInvestigation(page, first.title);
release();
await expect(page.locator('article[aria-label="调查任务报告"] h2').filter({ visible: true })).toHaveText(first.title);
await expect(page.getByRole("img", { name: "乙任务图表0", exact: true })).toHaveCount(0);
});
+6 -2
View File
@@ -192,13 +192,17 @@ for (const width of [1440, 375]) {
await expect(tools.getByRole("combobox", { name: "JSONL 测试案例", exact: true })).toBeEnabled({ timeout: 15_000 }); await expect(tools.getByRole("combobox", { name: "JSONL 测试案例", exact: true })).toBeEnabled({ timeout: 15_000 });
await tools.getByRole("button", { name: "执行本地预览", exact: true }).click(); await tools.getByRole("button", { name: "执行本地预览", exact: true }).click();
await expect(tools.getByRole("status")).toContainText("本地预览完成"); await expect(tools.getByRole("status")).toContainText("本地预览完成");
await page.getByRole("button", { name: "切换地图 Dev Panel", exact: true }).click();
await page.getByLabel("本地预览展示", { exact: true }).getByRole("button", { name: "打开图表管理", exact: true }).click(); await page.getByLabel("本地预览展示", { exact: true }).getByRole("button", { name: "打开图表管理", exact: true }).click();
await expect(page.getByRole("dialog", { name: "图表管理", exact: true })).toBeVisible(); const manager = page.getByRole("dialog", { name: "图表管理", exact: true });
await expect(manager).toBeVisible();
await expect(header.getByRole("button", { name: /窗口管理,当前/ })).toHaveCount(0);
await manager.getByRole("button", { name: "放大查看 交互验证压力趋势", exact: true }).click();
await page.setViewportSize({ width, height: 900 }); await page.setViewportSize({ width, height: 900 });
const navigator = header.getByRole("button", { name: /窗口管理,当前/ }); const navigator = header.getByRole("button", { name: /窗口管理,当前/ });
await navigator.click(); await navigator.click();
const windowMenu = page.getByRole("menu", { name: "已打开的窗口", exact: true }); const windowMenu = page.getByRole("menu", { name: "已打开的窗口", exact: true });
const currentWindow = windowMenu.getByRole("menuitem", { name: /定位窗口 .*图表管理/ }); const currentWindow = windowMenu.getByRole("menuitem", { name: "定位窗口 交互验证压力趋势", exact: true });
await expect(currentWindow).toHaveAttribute("aria-current", "true"); await expect(currentWindow).toHaveAttribute("aria-current", "true");
await expectPreservedOnHover(page, currentWindow, true); await expectPreservedOnHover(page, currentWindow, true);
await expect(currentWindow).toHaveCSS("background-color", await themeColor(currentWindow, "--action-selection-soft", "background-color")); await expect(currentWindow).toHaveCSS("background-color", await themeColor(currentWindow, "--action-selection-soft", "background-color"));
@@ -1,8 +1,12 @@
import { expect, test } from "@playwright/test"; import { expect, test } from "@playwright/test";
import { mockFlatWorkOrder } from "./support/mock-hierarchical-work-order"; import { mockFlatWorkOrder } from "./support/mock-hierarchical-work-order";
import { mockWorkbenchContext } from "./support/mock-workbench-context";
test.describe("mobile workbench sheet", () => { test.describe("mobile workbench sheet", () => {
test.use({ viewport: { width: 390, height: 844 } }); test.use({ viewport: { width: 390, height: 844 } });
test.beforeEach(async ({ page }) => {
await mockWorkbenchContext(page);
});
test("keeps the bottom launcher controls at one height", async ({ page }) => { test("keeps the bottom launcher controls at one height", async ({ page }) => {
await page.goto("/", { waitUntil: "domcontentloaded" }); await page.goto("/", { waitUntil: "domcontentloaded" });
@@ -0,0 +1,54 @@
import { expect, test } from "@playwright/test";
import { basename, resolve } from "node:path";
import { investigationFixture, mockInvestigationPresentation, selectInvestigation } from "./support/mock-investigation-presentation";
const ids = ["486033", "542017", "541061", "524529"];
const times = Array.from({ length: 13 }, (_, index) => `${String(5 + Math.floor(index / 4)).padStart(2, "0")}:${String(index % 4 * 15).padStart(2, "0")}`);
const series = (id: string, day: number, missing = false) => ({
name: `${id} ${day ? `07-${String(16 - day).padStart(2, "0")}` : "当日"}`,
device_id: id, day_offset: day, type: day ? "scatter" : "line",
data: times.map((_, index) => missing || day > 0 && index < 10 ? null : 200 + index * 10),
sample_times: times.map((time, index) => missing || day > 0 && index < 10 ? null : `2026-07-${String(16 - day).padStart(2, "0")}T${time}:00+08:00`)
});
test("keeps four SCADA comparison objects and explains verified missing history", async ({ page }, testInfo) => {
test.setTimeout(60_000);
await page.route("**/@fs/**/noto-sans-sc-*.woff2", (route) => route.fulfill({
path: resolve("node_modules/@fontsource-variable/noto-sans-sc/files", basename(new URL(route.request().url()).pathname)), contentType: "font/woff2"
}));
const task = investigationFixture(1, "SCADA展示覆盖核查");
const mock = await mockInvestigationPresentation(page, [task]);
await selectInvestigation(page, task.title);
const context = { metric: "flow", unit: "m3/h", window_start: "2026-07-16T05:00:00+08:00", window_end: "2026-07-16T08:00:00+08:00" };
await mock.emit(task, { action: "open_chart", chart_id: "flow-current", evidence_refs: ["synthetic:flow"], chart: {
title: "流量当前三小时趋势", chart_type: "line", x_data: times,
scada: { ...context, role: "current" }, series: ids.map((id) => series(id, 0))
} });
for (const id of ids) {
await mock.emit(task, { action: "open_chart", chart_id: `flow-${id}`, evidence_refs: ["synthetic:flow"], chart: {
title: `${id} 流量同期对比`, chart_type: "time_comparison", x_data: times,
scada: { ...context, role: "comparison", gaps: id === "524529" ? Array.from({ length: 7 }, (_, day) => ({
device_id: id, day_offset: day + 1, missing_count: 3, reason: day < 3 ? "no_readings" : "outside_frozen_window"
})) : [] },
series: Array.from({ length: 8 }, (_, day) => series(id, day, id === "524529" && day > 0))
} });
await expect(page.locator(`[data-presentation-scope="investigation"] [data-investigation-chart="flow-${id}"]`)).toHaveCount(1);
}
await page.getByRole("dialog", { name: "图表管理", exact: true }).getByRole("button", { name: "关闭窗口", exact: true }).click();
const panel = page.getByLabel("调查实时展示", { exact: true });
await panel.getByRole("button", { name: /放大查看 流量当前曲线与前七天同期对比/ }).click();
const dialog = page.getByRole("dialog", { name: /流量当前曲线与前七天同期对比/ });
const objects = dialog.getByLabel("选择图表对象");
await expect(objects.getByRole("button")).toHaveCount(4);
await expect(objects).toContainText("4 个");
await objects.getByRole("button", { name: "切换对象 524529", exact: true }).click();
await expect(dialog.getByLabel("监测数据缺口")).toContainText("历史缺测 21 点");
await expect(dialog.getByLabel("监测数据缺口")).toContainText("部分数据不在冻结范围内");
await expect(dialog.getByRole("img", { name: "524529 流量同期对比", exact: true })).toBeVisible();
expect(await dialog.evaluate((element) => element.scrollWidth - element.clientWidth)).toBeLessThanOrEqual(1);
await page.evaluate(() => document.fonts.ready);
await testInfo.attach("scada-four-objects-missing-history", {
body: await dialog.screenshot({ path: testInfo.outputPath("scada-four-objects.png") }), contentType: "image/png"
});
expect(mock.mutations).toEqual([]);
});
@@ -72,7 +72,7 @@ test("keeps the open scheduled report when the rolling history refreshes", async
await expect(rows.filter({ hasText: reportTitle ?? "" })).toHaveCount(0); await expect(rows.filter({ hasText: reportTitle ?? "" })).toHaveCount(0);
}); });
test("scheduled conditions keep acrylic blur outside transformed ancestors", async ({ page }) => { test("collapsed conditions use acrylic and expand into the analysis workspace", async ({ page }) => {
await page.goto("/", { waitUntil: "domcontentloaded" }); await page.goto("/", { waitUntil: "domcontentloaded" });
await openConditionFeed(page); await openConditionFeed(page);
@@ -84,15 +84,14 @@ test("scheduled conditions keep acrylic blur outside transformed ancestors", asy
const timeline = panel.getByTestId("scheduled-condition-timeline"); const timeline = panel.getByTestId("scheduled-condition-timeline");
const detailViewport = panel.locator(".scheduled-feed-detail-viewport"); const detailViewport = panel.locator(".scheduled-feed-detail-viewport");
const detailScroll = panel.getByTestId("scheduled-condition-detail-scroll"); const detailScroll = panel.getByTestId("scheduled-condition-detail-scroll");
const collapsedPanelBox = await panel.boundingBox();
const collapsedTimelineBox = await timeline.boundingBox(); const collapsedTimelineBox = await timeline.boundingBox();
expect(collapsedPanelBox).not.toBeNull();
expect(collapsedTimelineBox).not.toBeNull(); expect(collapsedTimelineBox).not.toBeNull();
await panel.getByRole("button", { name: "展开工况任务" }).click(); await panel.getByRole("button", { name: "展开工况任务" }).click();
await expectAcrylicComposition(panel); await expect(panel).toHaveAttribute("data-presentation", "workspace");
await expect(panel).toHaveCSS("width", "880px"); await expect(panel).toHaveCSS("backdrop-filter", "none");
await timeline.locator("button[data-condition-id]").first().click();
const expandedPanelBox = await panel.boundingBox(); const expandedPanelBox = await panel.boundingBox();
const expandedTimelineBox = await timeline.boundingBox(); const expandedTimelineBox = await timeline.boundingBox();
const expandedDetailViewportBox = await detailViewport.boundingBox(); const expandedDetailViewportBox = await detailViewport.boundingBox();
@@ -101,15 +100,9 @@ test("scheduled conditions keep acrylic blur outside transformed ancestors", asy
expect(expandedTimelineBox).not.toBeNull(); expect(expandedTimelineBox).not.toBeNull();
expect(expandedDetailViewportBox).not.toBeNull(); expect(expandedDetailViewportBox).not.toBeNull();
expect(expandedDetailScrollBox).not.toBeNull(); expect(expandedDetailScrollBox).not.toBeNull();
expect(Math.round(expandedPanelBox!.x + expandedPanelBox!.width)).toBe(
Math.round(collapsedPanelBox!.x + collapsedPanelBox!.width)
);
expect(Math.round(expandedTimelineBox!.width)).toBe( expect(Math.round(expandedTimelineBox!.width)).toBe(
Math.round(collapsedTimelineBox!.width) Math.round(collapsedTimelineBox!.width)
); );
expect(Math.round(expandedTimelineBox!.x + expandedTimelineBox!.width)).toBe(
Math.round(collapsedTimelineBox!.x + collapsedTimelineBox!.width)
);
expect(expandedTimelineBox!.y + expandedTimelineBox!.height).toBeLessThanOrEqual( expect(expandedTimelineBox!.y + expandedTimelineBox!.height).toBeLessThanOrEqual(
expandedPanelBox!.y + expandedPanelBox!.height - 12 expandedPanelBox!.y + expandedPanelBox!.height - 12
); );
@@ -124,6 +117,7 @@ test("scheduled conditions keep acrylic blur outside transformed ancestors", asy
); );
await expect(detailViewport).toHaveCSS("border-radius", "12px"); await expect(detailViewport).toHaveCSS("border-radius", "12px");
const timelineScroll = timeline.locator(".scheduled-feed-scroll.flex-1"); const timelineScroll = timeline.locator(".scheduled-feed-scroll.flex-1");
await page.mouse.move(0, 0);
expect(await readScrollbarPresentation(detailScroll)).toEqual( expect(await readScrollbarPresentation(detailScroll)).toEqual(
await readScrollbarPresentation(timelineScroll) await readScrollbarPresentation(timelineScroll)
); );
@@ -165,8 +159,8 @@ test("narrow desktop keeps Agent and expanded conditions from overlapping", asyn
await panel.getByRole("button", { name: "展开工况任务" }).focus(); await panel.getByRole("button", { name: "展开工况任务" }).focus();
await page.keyboard.press("Enter"); await page.keyboard.press("Enter");
await expect(page.locator('aside[aria-label="Agent 折叠栏"]')).toBeVisible(); await expect(page.locator('aside[aria-label="Agent 折叠栏"]')).toBeVisible();
await expect.poll(async () => (await panel.boundingBox())?.width ?? 0).toBeGreaterThan(800); await expect(panel).toHaveAttribute("data-presentation", "workspace");
await expect.poll(async () => (await panel.boundingBox())?.width ?? Infinity).toBeLessThanOrEqual(880); await expect(panel).toHaveCSS("width", "1024px");
const expandedConditionBox = await panel.boundingBox(); const expandedConditionBox = await panel.boundingBox();
const collapsedAgentBox = await page const collapsedAgentBox = await page
@@ -175,8 +169,9 @@ test("narrow desktop keeps Agent and expanded conditions from overlapping", asyn
expect(expandedConditionBox).not.toBeNull(); expect(expandedConditionBox).not.toBeNull();
expect(collapsedAgentBox).not.toBeNull(); expect(collapsedAgentBox).not.toBeNull();
expect( expect(
expandedConditionBox!.x - (collapsedAgentBox!.x + collapsedAgentBox!.width) (await panel.getByRole("heading", { name: "工况任务", exact: true }).boundingBox())!.x
).toBeGreaterThanOrEqual(24); - (collapsedAgentBox!.x + collapsedAgentBox!.width)
).toBeGreaterThanOrEqual(0);
await panel.getByRole("button", { name: "收起工况任务" }).click(); await panel.getByRole("button", { name: "收起工况任务" }).click();
await expect(agentPanel).toBeVisible(); await expect(agentPanel).toBeVisible();
@@ -188,7 +183,8 @@ test("switching conditions keeps the detail viewport fully expanded", async ({ p
const panel = page.getByRole("region", { name: "工况任务", exact: true }); const panel = page.getByRole("region", { name: "工况任务", exact: true });
await panel.getByRole("button", { name: "展开工况任务" }).click(); await panel.getByRole("button", { name: "展开工况任务" }).click();
await expect(panel).toHaveCSS("width", "880px"); await expect(panel).toHaveAttribute("data-presentation", "workspace");
await panel.getByTestId("scheduled-condition-timeline").getByRole("button", { name: /SCADA 数据诊断/ }).first().click();
const detailScroll = panel.getByTestId("scheduled-condition-detail-scroll"); const detailScroll = panel.getByTestId("scheduled-condition-detail-scroll");
const baselineHeight = await detailScroll.evaluate( const baselineHeight = await detailScroll.evaluate(
@@ -0,0 +1,125 @@
import { expect, test } from "@playwright/test";
import { mockWorkbenchContext } from "./support/mock-workbench-context";
import { createAnalysisRuntimeSnapshot, MOCK_SPATIAL_ANALYSIS } from "./support/mock-analysis-runtime";
test.beforeEach(async ({ page }) => {
await page.emulateMedia({ reducedMotion: "reduce" });
await mockWorkbenchContext(page, createAnalysisRuntimeSnapshot(MOCK_SPATIAL_ANALYSIS));
});
test("docks the live task panel into analysis, enforces both minimum widths and restores the analysis", async ({ page }) => {
await page.setViewportSize({ width: 1920, height: 1000 });
const errors: string[] = [];
page.on("pageerror", (error) => errors.push(error.message));
await page.goto("/", { waitUntil: "domcontentloaded" });
await page.getByRole("button", { name: "打开最新后端分析成果" }).click();
await expect(page.locator("#artifact-workspace")).toBeVisible();
await page.getByRole("button", { name: "工况任务", exact: true }).click();
const panel = page.getByRole("region", { name: "工况任务", exact: true });
await expect(panel.getByRole("button", { name: /停靠工况任务/ })).toHaveCount(0);
await expect(panel.locator("[data-condition-dock-toggle]")).toHaveCount(1);
await expect(panel.getByRole("button", { name: "展开工况任务" }).locator(".lucide-maximize2")).toBeVisible();
await expect(panel.locator('button[data-condition-id][aria-pressed="true"]')).toHaveCount(0);
await panel.getByRole("button", { name: "展开工况任务" }).click();
await expect(panel).toHaveAttribute("data-presentation", "workspace");
await expect(panel.getByRole("button", { name: "收起工况任务" }).locator(".lucide-minimize2")).toBeVisible();
await expect(panel.getByText("请选择工况任务", { exact: true })).toBeVisible();
const rows = panel.getByTestId("scheduled-condition-timeline").locator("button[aria-pressed]");
await rows.nth(1).click();
const selectedId = await rows.nth(1).getAttribute("data-condition-id");
await panel.evaluate((element) => Object.assign(window, { originalDockPanel: element }));
await expect(page.locator("#condition-workspace").getByRole("region", { name: "工况任务", exact: true })).toBeVisible();
await expect(page.locator("#artifact-workspace")).toBeHidden();
await expect(panel).toHaveAttribute("data-presentation", "workspace");
await expect(panel.locator(`[data-condition-id="${selectedId}"]`)).toHaveAttribute("aria-pressed", "true");
await expect(panel).toHaveCSS("backdrop-filter", "none");
const separator = page.getByRole("separator", { name: "调整地图与报告宽度" });
await expect(separator).toBeVisible();
await separator.focus();
await page.keyboard.press("Home");
await expect.poll(async () => Math.round((await page.locator("#workspace-map").boundingBox())!.width)).toBe(600);
await page.keyboard.press("End");
await expect.poll(async () => Math.round((await panel.boundingBox())!.width)).toBe(880);
const bounds = await panel.boundingBox();
expect(bounds!.y).toBe(56);
expect(Math.round(bounds!.height)).toBe(944);
const detail = panel.getByTestId("scheduled-condition-detail-scroll");
expect(await detail.evaluate((element) => element.scrollWidth - element.clientWidth)).toBeLessThanOrEqual(1);
const timeline = page.getByRole("region", { name: "运行时间轴", exact: true });
const timelineBox = (await timeline.boundingBox())!;
expect(timelineBox.x + timelineBox.width).toBeLessThanOrEqual(bounds!.x);
await page.screenshot({ path: "test-results/condition-dock-minimum-width.png" });
await page.setViewportSize({ width: 1480, height: 900 });
await expect(page.locator("#main-workspace")).toHaveAttribute("data-layout-mode", "focus");
await expect(panel).toHaveCSS("width", "1480px");
await page.setViewportSize({ width: 1481, height: 900 });
await expect(separator).toBeVisible();
await expect.poll(async () => Math.round((await page.locator("#workspace-map").boundingBox())!.width)).toBe(600);
await expect(panel).toHaveCSS("width", "880px");
await panel.getByRole("button", { name: "收起工况任务" }).click();
await expect(panel).toHaveAttribute("data-presentation", "desktop-floating");
await expect(page.locator("#artifact-workspace")).toBeVisible();
expect(await panel.evaluate((element) => element === (window as unknown as { originalDockPanel: Element }).originalDockPanel)).toBe(true);
await expect(panel.locator(`[data-condition-id="${selectedId}"]`)).toHaveAttribute("aria-pressed", "false");
await panel.getByRole("button", { name: "展开工况任务" }).click();
await expect(panel.locator(`[data-condition-id="${selectedId}"]`)).toHaveAttribute("aria-pressed", "true");
expect(errors).toEqual([]);
});
test("opens and reopens without selecting a task, and selecting a row docks its detail", async ({ page }) => {
await page.setViewportSize({ width: 1920, height: 1000 });
await page.goto("/", { waitUntil: "domcontentloaded" });
const toggle = page.getByRole("button", { name: "工况任务", exact: true });
const panel = page.getByRole("region", { name: "工况任务", exact: true });
await toggle.click();
await expect(panel.locator('button[data-condition-id][aria-pressed="true"]')).toHaveCount(0);
await panel.getByTestId("scheduled-condition-timeline").locator("button[data-condition-id]").nth(1).click();
await expect(panel).toHaveAttribute("data-presentation", "workspace");
await expect(panel.locator('button[data-condition-id][aria-pressed="true"]')).toHaveCount(1);
await expect(panel.getByTestId("scheduled-condition-detail-scroll")).toBeVisible();
await toggle.click();
await expect(panel).toBeHidden();
await toggle.click();
await expect(panel.locator('button[data-condition-id][aria-pressed="true"]')).toHaveCount(0);
await panel.getByRole("button", { name: "展开工况任务" }).click();
await expect(panel.getByText("请选择工况任务", { exact: true })).toBeVisible();
await page.screenshot({ path: "test-results/condition-dock-no-selection.png" });
});
test("uses focus mode when space is limited and adapts through Agent and mobile layouts", async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 });
await page.goto("/", { waitUntil: "domcontentloaded" });
await page.getByRole("button", { name: /展开 Agent 助手面板/ }).click();
await page.getByRole("button", { name: "工况任务", exact: true }).click();
const panel = page.getByRole("region", { name: "工况任务", exact: true });
await panel.getByRole("button", { name: "展开工况任务", exact: true }).click();
await expect(page.locator("#main-workspace")).toHaveAttribute("data-layout-mode", "focus");
await expect.poll(async () => (await panel.boundingBox())!.width).toBeGreaterThanOrEqual(880);
await page.setViewportSize({ width: 1024, height: 768 });
await expect(page.getByRole("complementary", { name: "Agent 命令面板" })).toBeHidden();
await expect(panel).toHaveCSS("width", "1024px");
await expect(page.getByRole("separator", { name: "调整地图与报告宽度" })).toBeHidden();
await page.getByRole("button", { name: "显示地图", exact: true }).click();
await expect(panel).toBeHidden();
await expect(page.locator("#workspace-map")).toBeVisible();
await page.getByRole("button", { name: "返回工况任务" }).click();
await expect(panel).toBeVisible();
const rail = (await page.getByRole("complementary", { name: "Agent 折叠栏" }).boundingBox())!;
const title = (await panel.getByRole("heading", { name: "工况任务", exact: true }).boundingBox())!;
expect(title.x).toBeGreaterThanOrEqual(rail.x + rail.width);
await page.screenshot({ path: "test-results/condition-dock-narrow-desktop.png" });
await page.setViewportSize({ width: 390, height: 844 });
await expect(panel).toBeHidden();
await page.getByRole("button", { name: "打开工况任务", exact: true }).click();
await expect(panel).toHaveAttribute("data-presentation", "mobile-sheet");
await expect(panel.locator('button[data-condition-id][aria-pressed="true"]')).toHaveCount(0);
await panel.getByTestId("scheduled-condition-timeline").locator("button[data-condition-id]").first().click();
await expect(panel.getByTestId("scheduled-condition-detail-scroll")).toBeVisible();
await expect(panel.getByRole("button", { name: "收起工况任务" })).toBeVisible();
await expect(panel.getByRole("button", { name: /停靠工况任务/ })).toHaveCount(0);
await page.setViewportSize({ width: 1920, height: 1000 });
await expect(panel).toHaveAttribute("data-presentation", "workspace");
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBe(1920);
});
@@ -144,3 +144,15 @@ export async function selectInvestigation(page: Page, title: string) {
} }
await task.click(); await task.click();
} }
export async function showInvestigationMap(page: Page) {
const showMap = page.getByRole("button", { name: "显示地图", exact: true });
if (await showMap.isVisible()) await showMap.click();
}
export async function showInvestigationTasks(page: Page) {
if (await page.getByRole("region", { name: "工况任务", exact: true }).isVisible()) return;
const returnToTasks = page.getByRole("button", { name: "返回工况任务", exact: true });
if (await returnToTasks.isVisible()) await returnToTasks.click();
else await page.getByRole("button", { name: /^(?:打开)?工况任务$/ }).click();
}
+13 -9
View File
@@ -4,7 +4,7 @@ import { mockInvestigationPresentation } from "./support/mock-investigation-pres
test.use({ reducedMotion: "reduce" }); test.use({ reducedMotion: "reduce" });
for (const width of [1440, 375, 320]) { for (const width of [1440, 375, 320]) {
test(`header locates managed, chart and table windows without changing their state at ${width}px`, async ({ page }, testInfo) => { test(`header lists only floating chart and table windows and preserves the docked manager at ${width}px`, async ({ page }, testInfo) => {
test.setTimeout(60_000); test.setTimeout(60_000);
await page.setViewportSize({ width: 1440, height: 900 }); await page.setViewportSize({ width: 1440, height: 900 });
await page.route("**/@fs/**/noto-sans-sc-*.woff2", (route) => route.fulfill({ await page.route("**/@fs/**/noto-sans-sc-*.woff2", (route) => route.fulfill({
@@ -28,11 +28,12 @@ for (const width of [1440, 375, 320]) {
await expect(tools.getByRole("combobox", { name: "JSONL 测试案例", exact: true })).toBeEnabled({ timeout: 15_000 }); await expect(tools.getByRole("combobox", { name: "JSONL 测试案例", exact: true })).toBeEnabled({ timeout: 15_000 });
await tools.getByRole("button", { name: "执行本地预览", exact: true }).click(); await tools.getByRole("button", { name: "执行本地预览", exact: true }).click();
await expect(tools.getByRole("status")).toContainText("本地预览完成"); await expect(tools.getByRole("status")).toContainText("本地预览完成");
await page.getByRole("button", { name: "切换地图 Dev Panel" }).click();
const panel = page.getByLabel("本地预览展示", { exact: true }); const panel = page.getByLabel("本地预览展示", { exact: true });
await panel.getByRole("button", { name: "放大查看表格 窗口定位核查表", exact: true }).click(); await panel.getByRole("button", { name: "放大查看表格 窗口定位核查表", exact: true }).click();
const table = page.getByRole("dialog", { name: "窗口定位核查表 · 表格", exact: true }); const table = page.getByRole("dialog", { name: "窗口定位核查表 · 表格", exact: true });
await expect(table).toBeVisible(); await expect(table).toBeVisible();
await panel.getByRole("button", { name: "打开图表管理", exact: true }).click(); await panel.getByRole("button", { name: "打开图表管理", exact: true }).press("Enter");
const manager = page.getByRole("dialog", { name: "图表管理", exact: true }); const manager = page.getByRole("dialog", { name: "图表管理", exact: true });
await manager.getByRole("button", { name: "放大查看 窗口定位压力趋势", exact: true }).click(); await manager.getByRole("button", { name: "放大查看 窗口定位压力趋势", exact: true }).click();
const child = page.getByRole("dialog", { name: "窗口定位压力趋势", exact: true }); const child = page.getByRole("dialog", { name: "窗口定位压力趋势", exact: true });
@@ -42,7 +43,7 @@ for (const width of [1440, 375, 320]) {
await table.locator(".floating-window-heading").focus(); await table.locator(".floating-window-heading").focus();
await search.fill("P2"); await search.fill("P2");
await page.setViewportSize({ width, height: 900 }); await page.setViewportSize({ width, height: 900 });
await expect(navigator).toHaveAttribute("aria-label", "窗口管理,当前 3 个窗口"); await expect(navigator).toHaveAttribute("aria-label", "窗口管理,当前 2 个窗口");
if (width === 1440) { if (width === 1440) {
const alignment = await navigator.evaluate((node) => { const alignment = await navigator.evaluate((node) => {
const label = node.children[1].getBoundingClientRect(); const label = node.children[1].getBoundingClientRect();
@@ -55,19 +56,21 @@ for (const width of [1440, 375, 320]) {
const tableBounds = await table.boundingBox(); const tableBounds = await table.boundingBox();
await navigator.click(); await navigator.click();
const menu = page.getByRole("menu", { name: "已打开的窗口", exact: true }); const menu = page.getByRole("menu", { name: "已打开的窗口", exact: true });
await expect(menu.getByRole("menuitem")).toHaveCount(4); await expect(menu.getByRole("menuitem")).toHaveCount(3);
await expect(menu.getByRole("menuitem", { name: /图表管理/ })).toHaveCount(0);
await menu.getByRole("menuitem", { name: "定位窗口 窗口定位核查表 · 表格", exact: true }).click(); await menu.getByRole("menuitem", { name: "定位窗口 窗口定位核查表 · 表格", exact: true }).click();
await expect(table.locator(".floating-window-heading")).toBeFocused(); await expect(table.locator(".floating-window-heading")).toBeFocused();
await expect(navigator).toHaveAttribute("aria-expanded", "false"); await expect(navigator).toHaveAttribute("aria-expanded", "false");
expect(await table.boundingBox()).toEqual(tableBounds); expect(await table.boundingBox()).toEqual(tableBounds);
await expect(search).toHaveValue("P2"); await expect(search).toHaveValue("P2");
const managerBounds = await manager.boundingBox(); const childBounds = await child.boundingBox();
await navigator.focus(); await navigator.focus();
await page.keyboard.press("Enter"); await page.keyboard.press("Enter");
await menu.getByRole("menuitem", { name: /定位窗口 .*图表管理/ }).focus(); await menu.getByRole("menuitem", { name: "定位窗口 窗口定位压力趋势", exact: true }).focus();
await page.keyboard.press("Enter"); await page.keyboard.press("Enter");
await expect(manager.locator(".floating-window-heading")).toBeFocused(); await expect(child.locator(".floating-window-heading")).toBeFocused();
expect(await manager.boundingBox()).toEqual(managerBounds); expect(await child.boundingBox()).toEqual(childBounds);
await expect(child.getByRole("tab", { name: "数据", exact: true })).toHaveAttribute("aria-selected", "true");
await navigator.click(); await navigator.click();
await header.getByRole("button", { name: "打开用户菜单", exact: true }).click(); await header.getByRole("button", { name: "打开用户菜单", exact: true }).click();
await expect(menu).toHaveCount(0); await expect(menu).toHaveCount(0);
@@ -85,7 +88,8 @@ for (const width of [1440, 375, 320]) {
await page.evaluate(() => document.fonts.ready); await page.evaluate(() => document.fonts.ready);
await testInfo.attach(`window-menu-${width}`, { body: await page.screenshot({ path: testInfo.outputPath(`window-menu-${width}.png`) }), contentType: "image/png" }); await testInfo.attach(`window-menu-${width}`, { body: await page.screenshot({ path: testInfo.outputPath(`window-menu-${width}.png`) }), contentType: "image/png" });
await menu.getByRole("menuitem", { name: "关闭全部窗口", exact: true }).click(); await menu.getByRole("menuitem", { name: "关闭全部窗口", exact: true }).click();
await expect(page.locator("[data-floating-window]")).toHaveCount(0); await expect(page.locator('[data-window-presentation="floating"]')).toHaveCount(0);
await expect(manager).toBeVisible();
await expect(navigator).toHaveCount(0); await expect(navigator).toHaveCount(0);
await expect(header.getByRole("button", { name: "打开用户菜单", exact: true })).toBeFocused(); await expect(header.getByRole("button", { name: "打开用户菜单", exact: true })).toBeFocused();
expect(mock.mutations).toEqual([]); expect(mock.mutations).toEqual([]);