diff --git a/.codex-server-diagnose.py b/.codex-server-diagnose.py new file mode 100644 index 00000000..0eb682ba --- /dev/null +++ b/.codex-server-diagnose.py @@ -0,0 +1,20 @@ +import os + +import paramiko + + +client = paramiko.SSHClient() +client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) +client.connect( + "119.254.86.251", + port=22322, + username="root", + password=os.environ["TARGET_SSH_PASSWORD"], + timeout=15, + auth_timeout=15, + banner_timeout=15, +) +_, stdout, stderr = client.exec_command(os.environ["TARGET_SSH_COMMAND"], timeout=30) +print(stdout.read().decode(errors="replace"), end="") +print(stderr.read().decode(errors="replace"), end="") +client.close() diff --git a/frontend-web/docs/position-roundtable-sandbox/README.md b/frontend-web/docs/position-roundtable-sandbox/README.md new file mode 100644 index 00000000..c3679ba5 --- /dev/null +++ b/frontend-web/docs/position-roundtable-sandbox/README.md @@ -0,0 +1,15 @@ +# 岗位会商沙箱文档 + +本目录存放**岗位会商文件预览沙箱**的对接与排障说明,独立于 `src/position-roundtable/docs/`,避免与模块内其它文档互相覆盖。 + +| 文档 | 说明 | +| --- | --- | +| [沙箱打开关闭与步骤条.md](./沙箱打开关闭与步骤条.md) | **详细版**:打开/关闭完整时序、步骤条关系、对接接口字段说明、必守规则、历史 bug 根因、排障手册、自测清单、接线示例与代码索引 | + +模块总览仍见:`frontend-web/src/position-roundtable/README.md`。 + +建议读法: + +- **从零对接新页面**:正文第 3、5、6、7、8、12、15、16 节 +- **线上排障**:第 13、14 节 +- **只要一页纸**:文末「附录 A」 diff --git a/frontend-web/docs/position-roundtable-sandbox/沙箱打开关闭与步骤条.md b/frontend-web/docs/position-roundtable-sandbox/沙箱打开关闭与步骤条.md new file mode 100644 index 00000000..035b5222 --- /dev/null +++ b/frontend-web/docs/position-roundtable-sandbox/沙箱打开关闭与步骤条.md @@ -0,0 +1,988 @@ +# 岗位会商 · 沙箱打开 / 关闭与步骤条(详细对接与排障指南) + +> **文档位置**:`frontend-web/docs/position-roundtable-sandbox/` +> **读者**:下次重做或对接岗位会商页面的同事;线上「沙箱不实时 / 卡死 / 第二次不刷新」时的排障同学。 +> **最后依据**:当前仓库 `PositionRoundtablePage` + `PositionNodeChat` 实现(含临时名打开、外部 store、前沿节流、按 tool-call 重挂)。 + +--- + +## 目录 + +1. [文档用途与读法](#1-文档用途与读法) +2. [背景:为什么岗位会商要单独做沙箱](#2-背景为什么岗位会商要单独做沙箱) +3. [用户可见的正确行为(验收标准)](#3-用户可见的正确行为验收标准) +4. [整体架构与数据流](#4-整体架构与数据流) +5. [职责划分:谁拥有什么状态](#5-职责划分谁拥有什么状态) +6. [对接接口详解](#6-对接接口详解) +7. [打开沙箱的完整步骤](#7-打开沙箱的完整步骤) +8. [关闭沙箱的完整步骤](#8-关闭沙箱的完整步骤) +9. [步骤条与沙箱的关系](#9-步骤条与沙箱的关系) +10. [流式内容如何进入沙箱(性能关键)](#10-流式内容如何进入沙箱性能关键) +11. [与普通对话页的对照](#11-与普通对话页的对照) +12. [重做页面时的必守规则](#12-重做页面时的必守规则) +13. [历史问题与根因(务必读)](#13-历史问题与根因务必读) +14. [排障手册(按症状)](#14-排障手册按症状) +15. [对接自测清单](#15-对接自测清单) +16. [最小接线示例](#16-最小接线示例) +17. [关键代码索引](#17-关键代码索引) +18. [术语表](#18-术语表) + +--- + +## 1. 文档用途与读法 + +### 1.1 这份文档解决什么问题 + +岗位会商右侧「文件预览沙箱」看起来像普通对话页的产物预览,但实现路径完全不同。历史上这块反复出过: + +- 沙箱不实时打开,要等全文写完才弹; +- 打开了但内容冻住,生成完才一口气灌进去; +- 整页卡顿,连消息列表文字都不实时; +- 同轮「重新生成」第二次写入时,步骤条变了,沙箱却不动; +- 第一次正常,关掉后再问就不实时。 + +这些 bug **特别容易在「重做页面 / 换布局 / 自己重写开沙箱逻辑」时复现**。本文把正确对接方式、时序、接口、禁区和排障步骤写全,方便下一位同事直接按文档接线,而不是再靠猜。 + +### 1.2 建议读法 + +| 你的目标 | 先读哪些章节 | +| --- | --- | +| 从零接一个新页面壳 | 第 3、5、6、7、8、12、15、16 节 | +| 只改对话子组件探测逻辑 | 第 7、9、12、13 节 | +| 线上排障 | 第 13、14 节,必要时回看第 10 节 | +| 理解为什么不能用页面 state | 第 2、10、13 节 | + +### 1.3 对照代码(以仓库为准) + +| 角色 | 路径 | +| --- | --- | +| 页面壳(唯一沙箱宿主) | `frontend-web/src/position-roundtable/pages/PositionRoundtablePage.tsx` | +| 节点对话(探测 write_file、上报预览) | `frontend-web/src/position-roundtable/components/PositionNodeChat.tsx` | +| 收口对话 | `frontend-web/src/position-roundtable/components/PositionBuiltinAgentChat.tsx` | +| 预览 UI(共享组件,勿分叉逻辑) | `frontend-web/src/components/workspace/artifacts/artifact-file-detail.tsx` | +| 流式正文读取 | `frontend-web/src/core/artifacts/loader.ts` → `loadArtifactContentFromToolCall` | +| 普通对话页对照(步骤条自动开) | `frontend-web/src/components/workspace/messages/message-group.tsx` | +| 模块总览 | `frontend-web/src/position-roundtable/README.md` | + +--- + +## 2. 背景:为什么岗位会商要单独做沙箱 + +### 2.1 普通对话页怎么开沙箱 + +普通对话页(`ChatPage`)大致是: + +```text +ArtifactsProvider(页面级) + └─ ChatBox / MessageList + └─ message-group 渲染 write_file 步骤 + └─ 发现 path 且 autoOpen → artifacts.select + setOpen(true) + └─ 右侧 ArtifactFileDetail 读同一套 ThreadContext +``` + +要点: + +- 对话和预览共享同一套 `ThreadContext`(同一个 `useThreadStream`)。 +- 步骤条组件自己就能触发打开。 +- 流式 `content` 本来就在当前 React 树的 thread 里,不需要「把 thread 镜像到别的地方」。 + +### 2.2 岗位会商为什么不能照搬 + +岗位会商页面同时有: + +- 左侧任务 / 意图 / 流程图; +- 中间某个节点的对话(`PositionNodeChat`); +- 右侧配置抽屉; +- **以及一个页面级单例沙箱**,它是对话区的**兄弟节点**,不在 `PositionNodeChat` 的 ThreadContext 里面。 + +因此: + +1. 沙箱拿不到节点对话内部的 `thread`,除非节点主动上报; +2. 若把每次流式 thread 写进**页面级 `useState`**,整页(任务卡、意图、流程图、对话)都会按流式频率重渲染,主线程会被打爆; +3. 页面必须自己决定「开 / 关 / 抑制自动再开 / 切节点时清理」,不能让多个子组件各自 `setOpen`。 + +所以岗位会商采用: + +```text +对话子组件探测 + 上报 + → 页面壳统一打开唯一 ArtifactFileDetail + → 流式 thread 走外部 store,只让沙箱子树订阅 +``` + +### 2.3 和「多智能体会商 Step2 沙箱」的区别 + +仓库里还有 `frontend-web/docs/roundtable-step2-sandbox-progress.md`,那是另一套圆桌 Step2 沙箱进度文档,**不是**岗位会商这条链路。对接岗位会商时以本文为准。 + +--- + +## 3. 用户可见的正确行为(验收标准) + +重做或对接完成后,下列行为必须全部成立(用户感知对齐普通对话页): + +| # | 行为 | 说明 | +| --- | --- | --- | +| A | 步骤条刚出现「写入文件」时,沙箱应已打开 | **不必等**步骤条上出现文件名 | +| B | 沙箱源码边写边滚;消息列表也实时出字 | 不能整页卡死、不能「生成完一口气刷」 | +| C | content 先于 path 时:先临时名打开,path 到了再改名 | 不闪屏、不重挂 | +| D | 同轮第二次同路径 `write_file`(重新生成) | 沙箱清空并重新流式 | +| E | 整轮结束后自动切 Markdown 预览 | 「正在生成,完成后自动预览」消失 | +| F | 用户手动关闭后,同一次写入不再自动弹 | 下一轮新写入仍可自动开 | +| G | 切岗位 / 切节点 / 新会话 / 切历史 | 沙箱关掉且不串内容 | + +**不要误判的正常现象:** + +- 流式期间沙箱停在「源码 / 编辑」视图,结束后才切「预览」——这是 `ArtifactFileDetail` 对 markdown/html 的既定行为,与普通对话页相同,**不是**打开时机 bug。 +- 步骤条长时间显示「写入文件」、没有路径,但沙箱已经打开并在滚动——content-first 模型下这是**预期**。 + +--- + +## 4. 整体架构与数据流 + +```text +┌──────────────────────────────────────────────────────────────────────────┐ +│ PositionRoundtablePage(页面壳) │ +│ │ +│ state: sandboxArtifact | null │ +│ ref: sandboxArtifactRef / closedSandboxKeyRef / latestSnapshotRef │ +│ store: createSandboxThreadStore() ←── 禁止改成 useState │ +│ │ +│ handlePreviewArtifact(artifact) ←──────────────────────────────────┐ │ +│ handleNodeThreadSnapshot(...) ←───────────────────────────────┐ │ │ +│ closeSandbox() │ │ │ +│ │ │ │ +│ {sandboxOpen && ( │ │ │ +│ SandboxThreadProvider(store) │ │ │ +│ └─ ArtifactFileDetail key=sandboxCloseKey(...) │ │ │ +│ )} │ │ │ +└───────────────────────────────────────────────────────────────────│──│───┘ + │ │ +┌───────────────────────────────────────────────────────────────────│──│───┐ +│ PositionNodeChat / PositionBuiltinAgentChat │ │ │ +│ │ │ │ +│ useThreadStream → thread.messages / thread.isLoading │ │ │ +│ │ │ │ │ +│ ├─ MessageList → 步骤条(只展示 tool call) │ │ │ +│ │ │ │ │ +│ ├─ latestStreamingWriteFile(messages) │ │ │ +│ │ → onPreviewArtifact({..., auto:true}) ───────────────────┘ │ +│ │ │ +│ └─ useEffect → onThreadSnapshot({threadId, thread}) ───────────────┘ +└──────────────────────────────────────────────────────────────────────────┘ +``` + +一句话: + +- **谁打开**:对话子组件决定「该不该开、开哪次交付」; +- **谁真正开面板**:页面壳; +- **内容怎么更新**:子组件持续上报 thread 快照 → 页面壳 store → 只有沙箱子树重渲染。 + +--- + +## 5. 职责划分:谁拥有什么状态 + +### 5.1 页面壳必须拥有 + +| 状态 / 能力 | 为什么必须在页面壳 | +| --- | --- | +| `sandboxArtifact` | 唯一预览目标;切节点时要清 | +| `closedSandboxKeyRef` | 用户关过后的抑制;跨子组件生命周期 | +| `sandboxThreadStore` | 流式内容通道;不能进大页面 state | +| `closeSandbox()` | 切岗位 / 切节点 / 新会话统一入口 | +| 唯一 `ArtifactFileDetail` | 避免双实例、关闭失效、深度异常 | + +### 5.2 对话子组件必须拥有 + +| 状态 / 能力 | 作用 | +| --- | --- | +| `autoPreviewRunArmedRef`(armed) | 只有本轮用户发送后才允许自动开 | +| `autoPreviewBaselineCallKeysRef`(baseline) | 忽略发送前已有的历史 write_file | +| `activeWriteFilePreviewRef` | 记录当前打开的 previewKey / path / toolCallId | +| `autoPreviewedArtifactKeyRef` | 同一次 identity 去重,避免每 chunk 重复上报 | +| `latestStreamingWriteFile` | 从 streaming messages 探测可预览的 write | +| `onThreadSnapshot` 上报 | 把 thread 喂给页面壳 | + +### 5.3 明确禁止 + +1. 在 `PositionNodeChat` 内再挂一套 `ArtifactFileDetail`。 +2. 让步骤条组件直接 `setOpen(true)` 作为岗位会商主路径(对照普通页可以,岗位会商不行)。 +3. 把 `onThreadSnapshot` 落到 `PositionRoundtablePage` 的 `useState`。 +4. 用「整个 threadId」做关闭抑制。 +5. 用「path 相同」复用 `previewKey`。 + +--- + +## 6. 对接接口详解 + +### 6.1 `PositionArtifactPreview` + +```ts +type PositionArtifactPreview = { + threadId: string; // 必填:LangGraph thread id + path: string; // 必填:真实路径,或 write-file: 虚拟 URL,或临时文件名路径 + name: string; // 展示名(文件名) + mimeType: string | null; // 如 text/markdown;帮助预览语言判断 + previewKey?: string; // 强烈建议:一次交付身份,推荐 `${messageId}:${toolCallId}` + auto?: boolean; // true = 流式自动打开;缺省/false = 用户点击打开 +}; +``` + +字段说明: + +| 字段 | 详细含义 | +| --- | --- | +| `threadId` | 沙箱用来匹配 `onThreadSnapshot` 的线程;也对关闭抑制键有贡献 | +| `path` | 传给 `ArtifactFileDetail.filepath`。流式阶段通常是 `write-file:...` 虚拟 URL;落盘后的手动打开可以是真实 artifacts 路径 | +| `name` | UI 展示用;临时名阶段可能是 `未命名文件.md` | +| `mimeType` | 当 path 还不稳定时,帮助把语言判成 markdown/html,避免落成 TEXT | +| `previewKey` | **一次交付的身份**。同一次 tool call 的 path 升级要保持不变;新的 tool call 必须变 | +| `auto` | 自动打开才走关闭抑制;手动打开应清抑制 | + +### 6.2 `onPreviewArtifact(artifact)` —— 对话 → 页面 + +页面壳 `handlePreviewArtifact` 当前逻辑顺序: + +1. 校验 `threadId`、`path`,缺则 toast 并 return。 +2. 计算 `artifactKey = sandboxCloseKey(artifact)`。 +3. 若 `artifact.auto === true` 且 `closedSandboxKeyRef.current === artifactKey` → **抑制,直接 return**。 +4. 清 `closedSandboxKeyRef`(手动打开或新的自动打开)。 +5. `ArtifactsContext.select(path, true)` + `setOpen(true)`。 +6. 判断是否同一预览 / 是否仅 path upgrade: + - `isSamePreview`:threadId + path + previewKey 全同 → 不重复 setState。 + - `isPathUpgrade`:previewKey 相同、path 不同 → 更新 artifact,**不要**再折叠右侧抽屉。 +7. 若不是 same preview: + - `setSandboxArtifact(artifact)`; + - **同步** `sandboxArtifactRef.current = artifact`(关键!flush 会立刻读 ref); + - `sandboxSnapshotAppliedAtRef.current = 0`(允许立刻推首帧内容)。 +8. 若 store 里已有别的 thread 快照,先 `publish(null)`。 +9. 若 `latestNodeThreadSnapshotRef` 的 threadId 匹配,立刻 `queueSandboxThreadSnapshot`。 +10. 非 path upgrade 时 `setRightPanelOpen(false)`。 + +`sandboxCloseKey`: + +```ts +if (artifact.previewKey) { + return `${artifact.threadId}:write:${artifact.previewKey}`; +} +return `${artifact.threadId}:${normalizePreviewArtifactPath(artifact.path)}`; +``` + +`ArtifactFileDetail` 的 React `key` 必须用这个 key: +**新 previewKey → 组件重挂 → 视觉上「清空再生成」。** + +### 6.3 `onThreadSnapshot({ threadId, thread })` —— 对话 → 页面 + +每次 `thread` 引用变化(消息 chunk 到达)子组件都会调: + +```ts +onThreadSnapshot?.({ threadId: activeThreadId, thread }); +``` + +页面壳应: + +1. 计算 `signature = sandboxThreadSignature(thread)`(用 isLoading、messages 长度、最近 write_file 的 path/content 长度/尾部等拼签名,用于去重)。 +2. 写入 `latestNodeThreadSnapshotRef`(即使沙箱还没开,打开瞬间也要用)。 +3. 若当前没有打开的沙箱,或打开的沙箱 threadId 不一致 → **只更新 ref,不 publish**。 +4. 若一致 → `queueSandboxThreadSnapshot`(前沿节流后 `store.publish`)。 + +### 6.4 虚拟 URL 与正文读取 + +流式阶段 path 形如: + +```text +write-file:${sourcePath}?message_id=${messageId}&tool_call_id=${toolCallId}&language=markdown +``` + +`loadArtifactContentFromToolCall`: + +1. 解析 URL 的 `message_id`、`tool_call_id`; +2. 在 `thread.messages` 里找对应 AI message 的 tool call; +3. 返回 `toolCall.args.content`。 + +结论: + +- 沙箱跟的是 **tool call 身份**,不是磁盘文件是否已经写完; +- 没有真实 path 也能显示正文; +- 临时文件名只影响展示名和语言猜测。 + +### 6.5 对话子组件 → 页面壳的其它相关回调 + +| 回调 | 用途 | +| --- | --- | +| `onPreviewArtifact` | 打开 / 更新沙箱 | +| `onThreadSnapshot` | 推送流式 thread | +| 页面壳 `closeSandbox` 传给 `ArtifactFileDetail.onClose` | 用户点关闭 | + +手动从流程图 / 产物列表打开时,也可以直接调 `handlePreviewArtifact`(通常不带 `auto`,或不带 previewKey)。 + +--- + +## 7. 打开沙箱的完整步骤 + +### 7.1 武装(arm):只有「本轮用户提交」才允许自动开 + +在 `PositionNodeChat.handleSubmit` 真正 `sendMessage` 之前: + +```text +activeWriteFilePreviewRef = null +autoPreviewBaselineCallKeysRef = writeFileCallKeys(thread.messages) // 历史 write 的 messageId:toolCallId +autoPreviewRunArmedRef = true +→ sendMessage(...) +``` + +发送失败要把 `armed` 设回 `false`。 + +为什么要 baseline? + +线程里往往已经有上几次问答写过的 `write_file`。如果只看「messages 里有没有 write_file」,一提问就会把旧文件再打开一次。baseline 的含义是:**只有这次提交之后新出现的 tool call 才能自动开沙箱**。 + +### 7.2 探测 `write_file`:不要等完整 path + +`write_file` 参数是一整段 JSON 流,**键顺序由模型决定**。 + +| 模型吐参顺序 | 步骤条表现 | 错误做法的后果 | +| --- | --- | --- | +| path / description 先到,再 content | 很快显示描述和文件名 | 普通对话页常见;等 path 也能开 | +| **content 先到,最后才 path** | 长时间只有「写入文件」,文件名很晚才出现 | 若硬等完整 path,沙箱会晚几十秒甚至一分钟 | + +岗位会商报告类 agent **经常是第二种**。 + +`latestStreamingWriteFile` 规则: + +1. 倒序扫描 AI messages 的 `tool_calls`; +2. 工具名是 `write_file` 或 `str_replace`; +3. **有完整扩展名的 path**(`hasCompleteArtifactExtension`)→ 用真实路径; +4. **尚无可用 path,但 `write_file` 的 content 已有非空字符** → 临时文件名: + - 正文头像 HTML → `未命名文件.html` + - 否则 → `未命名文件.md` +5. `str_replace` 必须等真实 path(它改已有文件); +6. 组装: + - `key = messageId:toolCallId` + - `path = write-file:虚拟URL`(write_file)或真实 path(str_replace) + - `mimeType`:markdown 则 `text/markdown` + +为什么扩展名必须完整? + +流式 path 会经历 `/a/b/report.m` → `/a/b/report.md`。若在 `.m` 时就当真实文件打开,预览语言可能被永久判成 TEXT。 + +### 7.3 上报 effect 的四个门闩 + +自动上报 `onPreviewArtifact` 前必须同时满足: + +1. `thread.isLoading === true` +2. 探测到 streaming artifact,且其 key **不在** baseline +3. 已有 `previewThreadId` +4. `autoPreviewRunArmedRef === true` + +然后处理 previewKey: + +```text +若与 activePreview 是同一次 tool call(含 tool-start 前缀兼容) + → 复用旧 previewKey // 用于临时名 → 真实 path +否则 + → previewKey = 新的 messageId:toolCallId +``` + +去重键: + +```text +`${previewThreadId}:${previewKey}:${sourcePath}` +``` + +把 `sourcePath` 算进去,是为了:**同 previewKey 下临时名变成真实 path 时,还要再报一次**(path upgrade),但不会每来一个 content chunk 都报。 + +### 7.4 线程绑定竞态(不要误 disarm) + +首轮对话常出现: + +1. 用户发送(本地 draft threadId / 稍后 SDK 创建真实 id); +2. 流已经开始、armed=true; +3. 会话 API 把 `node.threadId` 从 `null` 写成真实 id。 + +这是「本节点绑定自己的新线程」,**不是**切节点。若绑定 effect 无脑清空 armed / baseline,首轮会永远开不了沙箱。 + +正确:识别 `isOwnThreadBinding`(同 nodeKey、旧 threadId 为空、新 threadId 等于当前 boundThreadId)时 **直接 return,不清 armed**。 + +### 7.5 path upgrade(改名)≠ 第二次交付 + +同一次 tool call: + +```text +T1 content 到达 → path=未命名文件.md, previewKey=msg:tc1 → 打开 +T2 真实 path 到达 → path=/mnt/.../报告.md, previewKey=msg:tc1 → 只改名 +``` + +页面壳看到相同 previewKey、不同 path → `isPathUpgrade`: + +- 更新 `sandboxArtifact`; +- **不**重挂(React key 仍基于 previewKey); +- **不**再折叠右侧抽屉。 + +### 7.6 同路径二次写入(重新生成) + +同一次问答里模型可能: + +```text +1) write_file → 步骤条「写入文件」→ 打开沙箱 +2) 再 write_file 同 path,description=「重新生成优化版…」 +``` + +这是**两次 tool call**,必须两个 previewKey。 +若错误地「path 相同就复用 previewKey」: + +- 步骤条出现第二条; +- 沙箱 React key 不变; +- 用户看到「重新生成了,但沙箱没变化」。 + +正确:身份只看 tool call。 + +### 7.7 时序总图(content-first) + +```text +T0 用户发送 → armed=true,拍 baseline +T1 步骤条出现「写入文件」(尚无 path) +T1+ args.content 首字符到达 → 临时名打开沙箱,源码开始滚动 + … store 约每 160ms 推一次 thread 快照 … +T2 args.path 拼完整(含 .md)→ path upgrade,标题改真实文件名(不重挂) +T3 write 结束 / isLoading=false → 自动切 Markdown 预览 +``` + +### 7.8 时序总图(同轮二次写入) + +```text +T1 write_file#1 → previewKey=msg:tc1 → 打开沙箱 A +T2 #1 结束(可能短暂切预览) +T3 write_file#2(同 path,新 description)→ previewKey=msg:tc2 + → key 变 → 组件重挂清空 → 跟 #2 重新流式 +``` + +--- + +## 8. 关闭沙箱的完整步骤 + +### 8.1 用户手动关闭 + +`closeSandbox()` 应做: + +1. `closedSandboxKeyRef = sandboxCloseKey(current)` —— 抑制**这一次**自动再开; +2. 关闭 `ArtifactsContext.open`(若开着); +3. 清节流定时器、pending 快照; +4. `sandboxSnapshotAppliedAtRef = 0`; +5. `sandboxArtifactRef = null` + `setSandboxArtifact(null)`; +6. `sandboxThreadStore.publish(null)`。 + +抑制与 path upgrade 的关系: + +- 关掉临时名面板后,同一次 tool call 升级真实 path **仍被抑制**(同一 previewKey)——符合「用户不要看这次」; +- 下一次新的 `write_file`(新 previewKey)**可以**再自动开。 + +### 8.2 场景切换时强制关闭 + +以下操作应先调用 `closeSandbox()`,避免串台: + +- 切岗位; +- 切节点; +- 切收口阶段; +- 新建会话; +- 切换历史会话。 + +是否写入 `closedSandboxKeyRef` 可按产品决定;至少必须清面板和 store。 + +### 8.3 错误的抑制粒度(历史坑) + +若做成「关过一次就整个 thread 不再自动开」: + +- 第一次实时开正常; +- 用户关掉; +- 再问一次 → 同 thread 被永久抑制 → 看起来像「第二次不实时 / 要等生成完」。 + +正确粒度:**单次交付的 `sandboxCloseKey`(含 previewKey)**。 + +--- + +## 9. 步骤条与沙箱的关系 + +### 9.1 步骤条从哪来 + +步骤条由 `MessageList` → `message-group.tsx` 渲染 tool call: + +- 标题:优先 `args.description`;没有则 i18n 兜底「写入文件」; +- 子行:有 `args.path` 才显示路径; +- 普通对话页还会在「有 path + autoOpen」时自己 `select/setOpen`。 + +岗位会商里,步骤条**仍然只负责展示**;打开沙箱走 `onPreviewArtifact`,不要让两套逻辑抢。 + +### 9.2 对照表 + +| 你看到的步骤条 | 含义 | 沙箱应处于 | +| --- | --- | --- | +| 仅「写入文件」,无路径 | tool call 已开始;path/description 可能还没流到 | **应已打开**(临时名),源码在滚 | +| 「写入文件」+ 路径 | path 已可用 | 已打开;若刚从临时名升级则只改名 | +| 带自定义 description 的标题 + 路径 | 模型给了 description | 同上 | +| 第二条「重新生成…」+ 同路径 | 新的 write_file(新 toolCallId) | **应重挂**并重新流式 | +| 顶部「正在生成,完成后自动预览」 | 仍在 code 视图 | 正常,等 isLoading 结束切预览 | +| 生成结束,出现文件卡片 / present_files | 工具结果已落 | 通常已是预览模式;可手动再点开 | + +### 9.3 常见误解 + +**误解 1:**「步骤条出现文件名 = 打开沙箱的正确时机」 +→ 错。那是 path 到达的时机。content-first 时正确打开时机更早:content 首字节 / 工具调用已开始。 + +**误解 2:**「步骤条还在写『写入文件』,沙箱却开了,是 bug」 +→ 通常不是。两边数据源相同,但沙箱允许无 path 打开,步骤条标题可能还没 description。 + +**误解 3:**「等生成完从编辑切预览 = 沙箱打开晚了」 +→ 错。那是 `ArtifactFileDetail` 的 viewMode 策略。 + +--- + +## 10. 流式内容如何进入沙箱(性能关键) + +### 10.1 为什么不能用页面 `useState` 存线程快照 + +错误写法: + +```ts +setSandboxThreadSnapshot(snapshot) // 页面级 useState +``` + +后果: + +- 消息 chunk 约每 30ms 一次,节流后仍约 6 次/秒; +- 每次都重渲染整页:任务卡、意图结果、流程图、节点对话……; +- 主线程占满 → 消息列表停绘、沙箱冻住; +- 纯尾随 `setTimeout(160)` 会被饿死,十几秒不 flush。 + +这同时解释了两个历史现象: + +1. 「沙箱打开了但内容不更新」; +2. 「修完节流后整页更卡、消息也不实时」——因为节流终于开始真正 setState 了。 + +### 10.2 正确做法:外部 store + 子树订阅 + +```ts +createSandboxThreadStore() + subscribe / getSnapshot / publish + +SandboxThreadProvider + useSyncExternalStore(store.subscribe, store.getSnapshot) + → ThreadContext.Provider value={{ thread, isMock:false }} + → ArtifactFileDetail +``` + +页面壳本身**不**因 snapshot 变化而重渲染;只有 Provider 及其子树重渲染。 + +### 10.3 节流必须是前沿(leading-edge) + +`SANDBOX_SNAPSHOT_MIN_INTERVAL_MS = 160`: + +```text +queue(snapshot): + pending = snapshot + if 距上次 publish >= 160ms: + 立刻 flush(同步 publish) + else: + 若没有在途 timer,则 setTimeout(剩余时间) 做补尾 +flush: + 清 timer + 校验 pending.threadId === sandboxArtifactRef.threadId + publish(pending) +``` + +**不要**改回: + +```ts +if (timer != null) return; +timer = setTimeout(flush, 160); +``` + +那是纯尾随;忙主线程下会假死。 + +### 10.4 signature 去重 + +`sandboxThreadSignature` 用最近 write_file 的 path、content 长度、content 尾 32 字等拼签名。 +store.publish 时若 threadId+signature 未变,则不通知订阅者,减少无效渲染。 + +### 10.5 打开瞬间的首帧 + +`handlePreviewArtifact` 里往往会立刻 `queueSandboxThreadSnapshot(latestSnapshot)`。 +此时 React 的 `setSandboxArtifact` 可能还没提交,若 flush 只读旧的 `sandboxArtifactRef`,会因 threadId 不匹配把首帧丢掉。 + +所以打开新预览时必须: + +```ts +sandboxArtifactRef.current = artifact; // 同步 +sandboxSnapshotAppliedAtRef.current = 0; +``` + +--- + +## 11. 与普通对话页的对照 + +| 点 | 普通对话页 | 岗位会商 | +| --- | --- | --- | +| 谁触发打开 | `message-group` 内 `artifacts.select` | 子组件 `onPreviewArtifact` → 页面壳 | +| 是否要求 path | 是(有 path 才自动开) | 否(write_file + content 可临时名开) | +| thread 从哪来 | 同树 ThreadContext | `onThreadSnapshot` + 外部 store | +| 关闭抑制 | 主要靠 ArtifactsContext / 用户操作 | `closedSandboxKeyRef` 按 previewKey | +| 同 path 重写 | 依赖新的 tool call / 选择逻辑 | **必须**新 previewKey 以重挂 | +| 结束后切预览 | ArtifactFileDetail 同一套 | 同一套 | + +对齐目标是**用户感知一致**,不是代码路径完全相同。 + +普通对话页自动开的核心条件(对照用): + +```ts +artifacts && isLoading && isLast && autoOpen && autoSelect && path && !result +``` + +它也要求 path,所以 content-first 时普通页同样会偏晚——只是很多主聊天示例 agent 先吐 path,观感更好。岗位会商报告 agent 更常 content-first,所以必须做临时名提前开。 + +--- + +## 12. 重做页面时的必守规则 + +按优先级: + +1. **流式 thread 快照禁止进页面级 `useState`** → 用 store + `useSyncExternalStore`。 +2. **节流用前沿 + 补尾**,不要纯尾随 timer。 +3. **不要等完整 path 才开**;`write_file` + content 即可临时名打开。 +4. **扩展名完整前不要把 path 当最终 path**。 +5. **previewKey 按 tool call,不按 path**。 +6. **打开时同步写 `sandboxArtifactRef`,并重置节流时间戳**。 +7. **主路径扫描 `thread.messages`,不要只靠 `onToolStart`**。 +8. **path upgrade 保持 previewKey,不要当第二次交付**。 +9. **关闭抑制按 sandboxCloseKey,不要按整 thread**。 +10. **沙箱单例在页面壳;子组件只上报**。 +11. **本节点 threadId 回写不要 disarm**。 +12. **「结束后才切预览」不要当打开 bug 去「修」掉共享组件**,除非产品明确要求边生成边渲染 Markdown(需单独评估性能)。 + +--- + +## 13. 历史问题与根因(务必读) + +下面每个都在真实联调里出现过。重做时若踩中,优先回来对照。 + +### 13.1 沙箱要等文件名出来才开(晚几十秒) + +**现象:** 步骤条早就「写入文件」,沙箱很晚才开;普通对话页对比显得「实时」。 + +**根因:** 探测逻辑硬等完整 `path`;而该 agent 先流 `content`、最后才流 `path`。 + +**修复:** content 首批字符即可用临时名打开;path 到了再 upgrade。 + +### 13.2 沙箱打开了,内容冻住,生成完才灌满 + +**现象:** 面板开了,但里面一直是空/旧内容;日志里 queue 很多,flush 很少。 + +**根因:** 纯尾随 160ms 定时器在忙主线程下被饿死。 + +**修复:** 前沿节流——到期就在流回调里同步 flush。 + +### 13.3 修完「内容更新」后,整页卡顿、消息也不实时 + +**现象:** 沙箱开始更新了,但页面更卡,消息列表也「攒到最后刷」。 + +**根因:** flush 走的是页面 `useState`,每 160ms 整页重渲染。以前 timer 饿死时反而「不卡」。 + +**修复:** 快照改外部 store,只让沙箱子树订阅。 + +### 13.4 第二次「重新生成」步骤有了,沙箱不变 + +**现象:** 同轮第二条二条 write 步骤,沙箱仍显示第一次完整结果。 + +**根因:** 用「path 相同」复用了第一次 previewKey,React key 不变,组件不重挂。 + +**修复:** previewKey 只按 tool call;同 path 新 call 必须新 key。 + +### 13.5 第一次实时,关掉后再问就不实时 + +**现象:** 关过沙箱后,下一轮要等生成完才开,或不开。 + +**根因:** 抑制绑在整个 threadId,或把 path upgrade / 新 call 误判成同一次。 + +**修复:** 抑制键 = `sandboxCloseKey(previewKey)`;仅抑制那一次交付。 + +### 13.6 首轮永远不开 + +**现象:** 新建节点第一次提问,armed 后很快又不满足条件。 + +**根因:** `node.threadId` 从 null 回写真实 id 时,绑定 effect 误 disarm。 + +**修复:** `isOwnThreadBinding` 时不清 armed。 + +### 13.7 预览变成纯文本 + +**现象:** 明明是 md,却按 TEXT 打开。 + +**根因:** 在 `.m` 阶段就当完整 path;或临时名没有 `.md` / 没传 language、mimeType;或 path 带空格。 + +**修复:** `hasCompleteArtifactExtension`;临时名带扩展名;URL 加 `language=markdown`;path trim。 + +### 13.8 依赖 onToolStart,线上偶发不开 + +**现象:** 本地偶发正常,联调经常不开。 + +**根因:** 后端 StreamBridge / worker 可能过滤 tools/events 类 stream mode。 + +**修复:** 主路径必须是 messages 里渐进出现的 `tool_calls`;onToolStart 只能当补充。 + +--- + +## 14. 排障手册(按症状) + +排障时建议先看 Chrome Performance / React 重渲染是否整页抖,再看消息里 tool_calls 的 args 是 path-first 还是 content-first。 + +### 14.1 沙箱开得很晚 + +检查顺序: + +1. `latestStreamingWriteFile` 是否仍要求完整 path? +2. armed 是否被 threadId 回写清掉? +3. 是否命中 `closedSandboxKey`? +4. 新 call 是否被 baseline 当成历史? +5. `previewThreadId` 是否为空(线程还没绑上)? + +### 14.2 打开了但内容空白 / 冻住 + +1. 快照是否进了页面 useState? +2. 节流是否纯尾随? +3. `SandboxThreadProvider` 是否拿到带 messages 的 thread? +4. 虚拟 URL 的 message_id / tool_call_id 是否对得上? +5. 打开时 `sandboxArtifactRef` 是否同步?(首帧是否被 drop) +6. signature 是否因实现错误一直不变,导致 publish 被去重? + +### 14.3 整页卡、消息列表也不实时 + +1. 搜页面壳是否还有 `setSandboxThreadSnapshot` / 类似大对象 state。 +2. 是否在每 chunk `console.debug` 打大对象(DevTools 打开时更卡)。 +3. 是否错误地让页面壳订阅了 store(页面壳不应 `useSyncExternalStore` 这份 store;只有 Provider 订)。 + +### 14.4 重新生成不刷新 + +1. 第二次 write 的 toolCallId 是否变了? +2. previewKey 是否仍用 path 复用? +3. `ArtifactFileDetail` 的 `key=` 是否基于 sandboxCloseKey/previewKey? + +### 14.5 关后再问异常 + +1. 打印 `closedSandboxKeyRef` 与新 artifact 的 sandboxCloseKey。 +2. 确认新一轮 send 时 armed/baseline 已重置。 +3. 确认抑制不是整 thread。 + +### 14.6 语言 / 预览模式不对 + +1. 看打开时的 path / mimeType / language 查询参数。 +2. 确认不是在扩展名不完整时打开。 +3. 确认「源码→预览」发生在 isLoading false 之后(属正常)。 + +--- + +## 15. 对接自测清单 + +重做页面后至少跑完: + +### 功能 + +- [ ] 首轮:步骤条「写入文件」出现时,沙箱是否已开并开始出字? +- [ ] content-first agent:无文件名阶段是否也能开? +- [ ] path 到达后:是否只改名、不整页闪、不重挂? +- [ ] 同轮第二次同路径 write:是否清空并重新流式? +- [ ] 结束后是否自动切 Markdown 预览? +- [ ] 手动点步骤条路径 / 产物卡片:能否打开正确文件? + +### 关闭与抑制 + +- [ ] 流式中手动关闭:本次是否不再自动弹? +- [ ] 关闭后再发一轮新问题:是否仍可自动开? +- [ ] path upgrade 是否不会绕过「用户刚关闭」的抑制? + +### 场景切换 + +- [ ] 切节点:沙箱关闭,旧内容不残留。 +- [ ] 切岗位:同上。 +- [ ] 新建会话 / 切历史:同上。 + +### 性能 + +- [ ] 流式中消息列表是否实时出字? +- [ ] 页面是否明显掉帧 / 卡死? +- [ ] React DevTools 中,大页面壳是否在每 160ms 整页 update?(不应) + +--- + +## 16. 最小接线示例 + +### 16.1 页面壳(示意) + +```tsx +const [sandboxArtifact, setSandboxArtifact] = useState(null); +const sandboxArtifactRef = useRef(null); +const closedSandboxKeyRef = useRef(null); +const latestNodeThreadSnapshotRef = useRef(null); +const store = useMemo(createSandboxThreadStore, []); +// pending + timer + appliedAt 用于前沿节流(见 PositionRoundtablePage) + +function handlePreviewArtifact(artifact: PositionArtifactPreview) { + if (!artifact.threadId || !artifact.path) return; + const key = sandboxCloseKey(artifact); + if (artifact.auto && closedSandboxKeyRef.current === key) return; + closedSandboxKeyRef.current = null; + + artifactsCtx?.select(artifact.path, true); + artifactsCtx?.setOpen(true); + + const prev = sandboxArtifactRef.current; + const isSame = + prev?.threadId === artifact.threadId && + prev.path === artifact.path && + prev.previewKey === artifact.previewKey; + const isPathUpgrade = + !isSame && + Boolean(artifact.previewKey) && + prev?.threadId === artifact.threadId && + prev.previewKey === artifact.previewKey; + + if (!isSame) { + sandboxArtifactRef.current = artifact; // 必须同步 + setSandboxArtifact(artifact); + sandboxSnapshotAppliedAtRef.current = 0; + } + + if (store.getSnapshot()?.threadId !== artifact.threadId) { + store.publish(null); + } + const latest = latestNodeThreadSnapshotRef.current; + if (latest?.threadId === artifact.threadId) { + queueSandboxThreadSnapshot(latest); + } + if (!isPathUpgrade) setRightPanelOpen(false); +} + +function handleNodeThreadSnapshot(snapshot: { threadId: string; thread: BaseStream }) { + const next = { ...snapshot, signature: sandboxThreadSignature(snapshot.thread) }; + latestNodeThreadSnapshotRef.current = next; + if (sandboxArtifactRef.current?.threadId !== snapshot.threadId) return; + queueSandboxThreadSnapshot(next); +} + +function closeSandbox() { + if (sandboxArtifactRef.current) { + closedSandboxKeyRef.current = sandboxCloseKey(sandboxArtifactRef.current); + } + // clear timer / pending / appliedAt + sandboxArtifactRef.current = null; + setSandboxArtifact(null); + store.publish(null); + artifactsCtx?.setOpen(false); +} + +// 渲染 +{sandboxArtifact && ( + + + +)} +``` + +### 16.2 对话子组件(示意) + +```tsx +// send 前 +activeWriteFilePreviewRef.current = null; +autoPreviewBaselineCallKeysRef.current = writeFileCallKeys(thread.messages); +autoPreviewRunArmedRef.current = true; +await sendMessage(...); + +// 探测 +const streaming = thread.isLoading ? latestStreamingWriteFile(thread.messages) : null; +const next = + streaming && !autoPreviewBaselineCallKeysRef.current.has(streaming.key) + ? streaming + : null; + +useEffect(() => { + if (!thread.isLoading || !next || !previewThreadId || !autoPreviewRunArmedRef.current) return; + + // previewKey:同 tool call 复用,否则用 next.key + // artifactKey = threadId:previewKey:sourcePath 去重 + onPreviewArtifact?.({ + threadId: previewThreadId, + path: next.path, + name: next.name, + mimeType: next.mimeType, + previewKey, + auto: true, + }); +}, [next, previewThreadId, thread.isLoading, onPreviewArtifact]); + +useEffect(() => { + onThreadSnapshot?.({ threadId: activeThreadId, thread }); +}, [activeThreadId, thread, onThreadSnapshot]); +``` + +**强烈建议:** 探测 / armed / baseline / 临时名逻辑直接复用或抽取自 `PositionNodeChat`,不要从零重写。 + +--- + +## 17. 关键代码索引 + +| 主题 | 位置 | +| --- | --- | +| 临时名 / 完整扩展名 / latestStreamingWriteFile | `PositionNodeChat.tsx` 中 `provisionalWriteFilePath`、`hasCompleteArtifactExtension`、`latestStreamingWriteFile` | +| armed / baseline / 上报 effect | `PositionNodeChat.tsx` `handleSubmit` + streaming preview `useEffect` | +| 同 tool call 判断 / 二次写入重挂 | 同上,`isSameToolCall` / `previewKey` | +| 线程绑定保护 | `PositionNodeChat.tsx` node binding `useEffect` 中 `isOwnThreadBinding` | +| sandboxCloseKey / store / 前沿节流 | `PositionRoundtablePage.tsx` `sandboxCloseKey`、`createSandboxThreadStore`、`queueSandboxThreadSnapshot` | +| 打开 / path upgrade / 抑制 | `PositionRoundtablePage.tsx` `handlePreviewArtifact` | +| 关闭 | `PositionRoundtablePage.tsx` `closeSandbox` | +| 虚拟 URL 读 content | `core/artifacts/loader.ts` `loadArtifactContentFromToolCall` | +| 源码/预览切换 | `artifact-file-detail.tsx` 中 `viewMode` + `thread.isLoading` | +| 普通页步骤条自动开 | `message-group.tsx` `write_file` 分支 | + +相关提交(背景): + +- `fix(frontend): 岗位会商沙箱在 write_file 流式阶段实时打开并刷新` + — 临时名打开、外部 store、前沿节流 +- `fix(frontend): 同路径二次 write_file 时重挂岗位会商沙箱` + — previewKey 按 tool call,禁止按 path 复用 + +--- + +## 18. 术语表 + +| 术语 | 含义 | +| --- | --- | +| armed | 本轮用户发送后,允许自动打开沙箱的开关 | +| baseline | send 前已有的 write tool call 集合,用于忽略历史产物 | +| previewKey | 一次交付的稳定身份,推荐 `messageId:toolCallId` | +| sandboxCloseKey | 关闭抑制键,同时用作 `ArtifactFileDetail` 的 React key | +| provisional path / 临时名 | 尚无真实 path 时的 `未命名文件.md` / `.html` | +| path upgrade | 同 previewKey 下临时名升级为真实 path | +| sandboxThreadStore | 流式线程外部 store,避免整页重渲染 | +| write-file: URL | 用 message_id + tool_call_id 定位流式 content 的虚拟路径 | +| leading-edge throttle / 前沿节流 | 到期立即在回调里 publish,而不是只挂尾随 timer | +| content-first / path-first | 模型流式 JSON 参数时 content 与 path 哪个先到 | +| isOwnThreadBinding | 本节点把自己的新 threadId 写回 props,不是切节点 | + +--- + +## 附录 A:给对接同学的一页纸摘要 + +1. 页面壳只挂一个沙箱;子组件只调用 `onPreviewArtifact` / `onThreadSnapshot`。 +2. 自动打开时机 ≈ 步骤条出现「写入文件」时,而不是出现文件名时。 +3. `write_file` 可以没有 path:临时名打开,path 到了再改名。 +4. 流式 thread 进外部 store,进页面 state 会卡死。 +5. 节流要前沿;previewKey 看 tool call;关闭抑制看 sandboxCloseKey。 +6. 同路径重新生成 = 新 previewKey = 沙箱重挂。 +7. 出问题先对照第 13、14 节,再看代码索引第 17 节。 diff --git a/frontend-web/src/assets/position-roundtable/add-task.svg b/frontend-web/src/assets/position-roundtable/add-task.svg new file mode 100644 index 00000000..e27cab8f --- /dev/null +++ b/frontend-web/src/assets/position-roundtable/add-task.svg @@ -0,0 +1 @@ + diff --git a/frontend-web/src/assets/position-roundtable/agent-config-logo.svg b/frontend-web/src/assets/position-roundtable/agent-config-logo.svg new file mode 100644 index 00000000..d51eb71d --- /dev/null +++ b/frontend-web/src/assets/position-roundtable/agent-config-logo.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend-web/src/assets/position-roundtable/ask-question.svg b/frontend-web/src/assets/position-roundtable/ask-question.svg new file mode 100644 index 00000000..af9052eb --- /dev/null +++ b/frontend-web/src/assets/position-roundtable/ask-question.svg @@ -0,0 +1 @@ + diff --git a/frontend-web/src/assets/position-roundtable/collapse-panel.svg b/frontend-web/src/assets/position-roundtable/collapse-panel.svg new file mode 100644 index 00000000..9f064680 --- /dev/null +++ b/frontend-web/src/assets/position-roundtable/collapse-panel.svg @@ -0,0 +1 @@ + diff --git a/frontend-web/src/assets/position-roundtable/double-arrow-decoration.svg b/frontend-web/src/assets/position-roundtable/double-arrow-decoration.svg new file mode 100644 index 00000000..bf85a192 --- /dev/null +++ b/frontend-web/src/assets/position-roundtable/double-arrow-decoration.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend-web/src/assets/position-roundtable/edit-task.svg b/frontend-web/src/assets/position-roundtable/edit-task.svg new file mode 100644 index 00000000..ab6762a2 --- /dev/null +++ b/frontend-web/src/assets/position-roundtable/edit-task.svg @@ -0,0 +1 @@ + diff --git a/frontend-web/src/assets/position-roundtable/more-task.svg b/frontend-web/src/assets/position-roundtable/more-task.svg new file mode 100644 index 00000000..055a158d --- /dev/null +++ b/frontend-web/src/assets/position-roundtable/more-task.svg @@ -0,0 +1 @@ + diff --git a/frontend-web/src/assets/position-roundtable/search-task.svg b/frontend-web/src/assets/position-roundtable/search-task.svg new file mode 100644 index 00000000..fc8fc78c --- /dev/null +++ b/frontend-web/src/assets/position-roundtable/search-task.svg @@ -0,0 +1 @@ + diff --git a/frontend-web/src/assets/position-roundtable/send-message.svg b/frontend-web/src/assets/position-roundtable/send-message.svg new file mode 100644 index 00000000..3a96000e --- /dev/null +++ b/frontend-web/src/assets/position-roundtable/send-message.svg @@ -0,0 +1 @@ + diff --git a/frontend-web/src/assets/position-roundtable/upload-file.svg b/frontend-web/src/assets/position-roundtable/upload-file.svg new file mode 100644 index 00000000..9f47e22a --- /dev/null +++ b/frontend-web/src/assets/position-roundtable/upload-file.svg @@ -0,0 +1 @@ + diff --git a/frontend-web/src/assets/position-roundtable/时间.svg b/frontend-web/src/assets/position-roundtable/时间.svg new file mode 100644 index 00000000..26888994 --- /dev/null +++ b/frontend-web/src/assets/position-roundtable/时间.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend-web/src/assets/position-roundtable/标签1.svg b/frontend-web/src/assets/position-roundtable/标签1.svg new file mode 100644 index 00000000..780de1a5 --- /dev/null +++ b/frontend-web/src/assets/position-roundtable/标签1.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend-web/src/assets/position-roundtable/标签2.svg b/frontend-web/src/assets/position-roundtable/标签2.svg new file mode 100644 index 00000000..7443e13d --- /dev/null +++ b/frontend-web/src/assets/position-roundtable/标签2.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend-web/src/assets/position-roundtable/标签3.svg b/frontend-web/src/assets/position-roundtable/标签3.svg new file mode 100644 index 00000000..7d9257a5 --- /dev/null +++ b/frontend-web/src/assets/position-roundtable/标签3.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend-web/src/assets/position-roundtable/标签4.svg b/frontend-web/src/assets/position-roundtable/标签4.svg new file mode 100644 index 00000000..2be60358 --- /dev/null +++ b/frontend-web/src/assets/position-roundtable/标签4.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend-web/src/assets/position-roundtable/标签5.svg b/frontend-web/src/assets/position-roundtable/标签5.svg new file mode 100644 index 00000000..df814d72 --- /dev/null +++ b/frontend-web/src/assets/position-roundtable/标签5.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend-web/src/assets/position-roundtable/标签6.svg b/frontend-web/src/assets/position-roundtable/标签6.svg new file mode 100644 index 00000000..3df12c8a --- /dev/null +++ b/frontend-web/src/assets/position-roundtable/标签6.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend-web/src/assets/position-roundtable/责任岗位.svg b/frontend-web/src/assets/position-roundtable/责任岗位.svg new file mode 100644 index 00000000..66040aa7 --- /dev/null +++ b/frontend-web/src/assets/position-roundtable/责任岗位.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend-web/src/components/workspace/agents/agent-detail-panel.tsx b/frontend-web/src/components/workspace/agents/agent-detail-panel.tsx index ca90f080..6e23d8db 100644 --- a/frontend-web/src/components/workspace/agents/agent-detail-panel.tsx +++ b/frontend-web/src/components/workspace/agents/agent-detail-panel.tsx @@ -100,15 +100,17 @@ function Section({ icon, title, extra, + className, children, }: { icon?: ReactNode; title: string; extra?: ReactNode; + className?: string; children: ReactNode; }) { return ( -
+

{icon} @@ -139,6 +141,15 @@ export function AgentDetailPanel({ defaultCollapsed, showRecentChats, compactAppearanceActions, + avatarSrc, + positionName, + skillsIcon, + skillsTitle, + showCommonQuestions = false, + panelTitle, + embedded, + hideStatusBadges = false, + editIcon, }: { agent: Agent | null | undefined; agentName: string; @@ -150,6 +161,19 @@ export function AgentDetailPanel({ showRecentChats?: boolean; /** 简洁模式下挂在右上角收起/展开按钮左侧的外观控件。 */ compactAppearanceActions?: ReactNode; + avatarSrc?: string; + positionName?: string; + skillsIcon?: ReactNode; + skillsTitle?: string; + showCommonQuestions?: boolean; + /** Overrides the standard panel heading for an embedded consumer. */ + panelTitle?: string; + /** Renders one fixed panel instead of the responsive collapsible rail. */ + embedded?: boolean; + /** Keeps deployment/status badges out of an embedded product surface. */ + hideStatusBadges?: boolean; + /** Optional icon used by the compact embedded edit action. */ + editIcon?: ReactNode; }) { const router = useRouter(); const [collapsed, setCollapsed] = useState(defaultCollapsed ?? false); @@ -472,11 +496,25 @@ export function AgentDetailPanel({

) : (
- - {canTogglePublish && ( + {embedded ? ( + + + + ) : ( + + )} + {!embedded && canTogglePublish && ( - + {!embedded && ( + + + + )}
) ) : null; @@ -521,7 +561,11 @@ export function AgentDetailPanel({
- + {avatarSrc ? ( + + ) : ( + + )}
{editing && draft ? ( @@ -541,9 +585,16 @@ export function AgentDetailPanel({ {displayName}
)} -
- {statusBadges} -
+ {!editing && positionName && ( +
+ 岗位:{desensitize(positionName)} +
+ )} + {!hideStatusBadges && ( +
+ {statusBadges} +
+ )} {!editing && agent.owner_username && !agent.builtin && (
@@ -646,7 +697,7 @@ export function AgentDetailPanel({ {/* ── 常用问题 ───────────────────────────────────────────────────── */} - {(editing || questions.length > 0 || canEdit) && ( + {(showCommonQuestions || editing || questions.length > 0 || canEdit) && (
} title="常用问题" @@ -787,8 +838,9 @@ export function AgentDetailPanel({ {/* ── 技能管理 ───────────────────────────────────────────────────── */}
} - title={`已启用技能 ${skillNamesShown.length} 个`} + icon={skillsIcon ?? } + title={skillsTitle ?? `已启用技能 ${skillNamesShown.length} 个`} + className="position-roundtable-skills-section" extra={ editing ? ( - -
- - - - - 智能体信息 - {headerActions} - - -
{body}
-
-
+ {!embedded && ( + <> + {/* ── Narrow screens ( + + + +
+ + + + + 智能体信息 + {headerActions} + + +
{body}
+
+
+ + )} {/* ── Secondary surfaces ───────────────────────────────────────────── */} void; /** @@ -150,16 +153,38 @@ export function ArtifactFileDetail({ const { t } = useI18n(); const { artifacts, setOpen, select } = useArtifacts(); const { isMock, thread, publicShareCode } = useThread(); - const isWriteFileVirtual = useMemo(() => { - return filepathFromProps.startsWith("write-file:"); - }, [filepathFromProps]); - const filepath = useMemo(() => { - if (isWriteFileVirtual) { - const url = new URL(filepathFromProps); - return decodeURIComponent(url.pathname); - } - return filepathFromProps; - }, [filepathFromProps, isWriteFileVirtual]); + const isWriteFileVirtual = useMemo(() => { + return filepathFromProps.startsWith("write-file:"); + }, [filepathFromProps]); + // A streamed tool call can be opened before the path has been normalized by + // the artifacts API. Keep the format supplied by the writer so Markdown is + // rendered as Markdown instead of falling back to a TEXT source preview. + const writeFileLanguageHint = useMemo(() => { + if (!isWriteFileVirtual) return null; + try { + const language = new URL(filepathFromProps).searchParams.get("language"); + return language === "markdown" ? language : null; + } catch { + return null; + } + }, [filepathFromProps, isWriteFileVirtual]); + const mimeLanguageHint = useMemo(() => { + const normalized = mimeType?.toLowerCase().trim() ?? ""; + if (normalized.includes("markdown")) return "markdown"; + if (normalized.includes("html")) return "html"; + if (normalized.includes("mermaid")) return "mermaid"; + if (normalized.startsWith("text/")) return "text"; + return null; + }, [mimeType]); + const filepath = useMemo(() => { + if (isWriteFileVirtual) { + const url = new URL(filepathFromProps); + return decodeURIComponent(url.pathname).trim(); + } + // Tool arguments may contain harmless surrounding whitespace. Passing it + // into extension detection turns `report.md ` into a generic TEXT file. + return filepathFromProps.trim(); + }, [filepathFromProps, isWriteFileVirtual]); const isSkillFile = useMemo(() => { return filepath.endsWith(".skill"); }, [filepath]); @@ -186,17 +211,22 @@ export function ArtifactFileDetail({ const useWriteFileStreaming = useMemo(() => { return isWriteFileVirtual && !isImageFile(filepath) && !editVirtualMarkdown; }, [filepath, isWriteFileVirtual, editVirtualMarkdown]); - const { isCodeFile, language } = useMemo(() => { - if (useWriteFileStreaming) { - let nextLanguage = checkCodeFile(filepath).language; - nextLanguage ??= "text"; - return { isCodeFile: true, language: nextLanguage }; + const { isCodeFile, language } = useMemo(() => { + if (useWriteFileStreaming) { + let nextLanguage = + mimeLanguageHint ?? writeFileLanguageHint ?? checkCodeFile(filepath).language; + nextLanguage ??= "text"; + return { isCodeFile: true, language: nextLanguage }; } if (isSkillFile) { return { isCodeFile: true, language: "markdown" }; } - return checkCodeFile(filepath); - }, [filepath, useWriteFileStreaming, isSkillFile]); + const detected = checkCodeFile(filepath); + if (mimeLanguageHint) { + return { isCodeFile: true as const, language: mimeLanguageHint }; + } + return detected; + }, [filepath, useWriteFileStreaming, isSkillFile, mimeLanguageHint, writeFileLanguageHint]); const isSupportPreview = useMemo(() => { return ( language === "html" || @@ -209,7 +239,8 @@ export function ArtifactFileDetail({ // editVirtualMarkdown:用解码后的真实路径走 artifacts API(而非 write-file 虚拟 // URL),这样保存后 useUpdateArtifactContent 写入的查询缓存才能命中,编辑内容 // 不会被旧的内存 stub 值覆盖回退。 - filepath: editVirtualMarkdown ? filepath : filepathFromProps, + filepath: + editVirtualMarkdown || !isWriteFileVirtual ? filepath : filepathFromProps, enabled: isCodeFile && !useWriteFileStreaming, }); diff --git a/frontend-web/src/core/threads/hooks.ts b/frontend-web/src/core/threads/hooks.ts index 088cf4a9..ac54c431 100644 --- a/frontend-web/src/core/threads/hooks.ts +++ b/frontend-web/src/core/threads/hooks.ts @@ -25,10 +25,13 @@ import { promptInputFilePartToFile, uploadFiles } from "../uploads"; import type { AgentThread, AgentThreadState } from "./types"; -export type ToolEndEvent = { - name: string; - data: unknown; -}; +export type ToolEndEvent = { + name: string; + data: unknown; + toolCallId?: string; +}; + +export type ToolStartEvent = ToolEndEvent; export type ThreadStreamOptions = { threadId?: string | null | undefined; @@ -47,10 +50,11 @@ export type ThreadStreamOptions = { /** 额外写到新建 thread 的 metadata(与 agent_id 合并)。 * 任务深链用 `{ taskId }` 把对话挂到任务下(1:N),列表按 metadata.taskId 过滤。 */ threadMetadata?: Record; - onStart?: (threadId: string) => void; - onFinish?: (state: AgentThreadState) => void; - onToolEnd?: (event: ToolEndEvent) => void; -}; + onStart?: (threadId: string) => void; + onFinish?: (state: AgentThreadState) => void; + onToolStart?: (event: ToolStartEvent) => void; + onToolEnd?: (event: ToolEndEvent) => void; +}; type SendMessageOptions = { additionalKwargs?: Record; @@ -447,10 +451,11 @@ export function useThreadStream({ assistantId, runOptions, threadMetadata, - onStart, - onFinish, - onToolEnd, -}: ThreadStreamOptions) { + onStart, + onFinish, + onToolStart, + onToolEnd, +}: ThreadStreamOptions) { const { t } = useI18n(); const [localSettings] = useLocalSettings(); // Track the thread ID that is currently streaming to handle thread changes during streaming @@ -466,16 +471,17 @@ export function useThreadStream({ lastStreamActivityAtRef.current = Date.now(); }, []); - const listeners = useRef({ - onStart, - onFinish, - onToolEnd, - }); + const listeners = useRef({ + onStart, + onFinish, + onToolStart, + onToolEnd, + }); // Keep listeners ref updated with latest callbacks - useEffect(() => { - listeners.current = { onStart, onFinish, onToolEnd }; - }, [onStart, onFinish, onToolEnd]); + useEffect(() => { + listeners.current = { onStart, onFinish, onToolStart, onToolEnd }; + }, [onStart, onFinish, onToolStart, onToolEnd]); useEffect(() => { const normalizedThreadId = threadId ?? null; @@ -545,12 +551,6 @@ export function useThreadStream({ }, onLangChainEvent(event) { markStreamActivity(); - if (event.event === "on_tool_end") { - listeners.current.onToolEnd?.({ - name: event.name, - data: event.data, - }); - } // 操作日志(Y-Log):每一次大模型调用结束都各上报一条(一次 LLM 调用 = 一条), // 让问答日志尽量「多、全」——一个问答轮次里 lead agent / 子代理的每次模型调用 // 都会落一条。门控与失败静默都在 writeYLog 内部处理,绝不影响问答。 @@ -572,8 +572,32 @@ export function useThreadStream({ } catch { /* 上报绝不影响问答 */ } - } + } }, + // The SDK emits UI tool lifecycle events on the dedicated `tools` stream + // mode. `events` is a separate LangChain trace channel; using it for UI + // reactions can miss a tool that the conversation has already rendered. + onToolEvent: + onToolStart || onToolEnd + ? (event) => { + markStreamActivity(); + if (event.event === "on_tool_start") { + listeners.current.onToolStart?.({ + name: event.name, + data: event.input, + toolCallId: event.toolCallId, + }); + return; + } + if (event.event === "on_tool_end") { + listeners.current.onToolEnd?.({ + name: event.name, + data: event.output, + toolCallId: event.toolCallId, + }); + } + } + : undefined, onUpdateEvent(data) { markStreamActivity(); const updates: Array | null> = Object.values( diff --git a/frontend-web/src/position-roundtable/README.md b/frontend-web/src/position-roundtable/README.md index 6c2b7e6b..80587346 100644 --- a/frontend-web/src/position-roundtable/README.md +++ b/frontend-web/src/position-roundtable/README.md @@ -24,11 +24,23 @@ | 参数 | 是否必填 | 作用 | | --- | --- | --- | -| `taskId` | 否 | 外部任务 ID。缺失时使用本地 mock 任务,便于演示和开发。 | +| `taskId` | 否 | 外部任务 ID。传入后它是岗位会商的共享存储作用域;缺失时保持原有的个人会话逻辑。mock 仅提供任务卡片的显示兜底,绝不替换路由传入的 ID。 | | `sessionId` | 否 | 直接恢复指定岗位会商会话;缺失时页面会按 `taskId` 查找最近一条未归档会话。 | | `positionId` | 否 | 初始打开的岗位,同时同步顶部岗位选择器。无效值回退到 `intelligence`。 | | `new=1` | 否 | 强制不恢复历史会话,以新会话开始。 | +传入 `taskId` 时,同一个任务下可以有多条会商会话,所有用户共享同一份历史、节点快照与 LangGraph 线程;当前 `user_id` 仅保留创建审计,不参与这些任务会话的读写过滤。页面恢复 `sessionId` 时会核验其 `externalTaskId` 与路由 `taskId` 一致,不一致会丢弃该会话并按当前任务重新发现历史。未传 `taskId` 时,会继续只读取当前用户的原有个人会话。 + +### 外部系统按 taskId 对接 + +1. 进入页面时将业务侧任务的稳定主键原样放入 URL。工作区入口使用 `/#/page/workspace/roundtable/position?taskId=`;策略页入口也兼容 `/#/page/strategy/qa/position-roundtable?taskId=`。不要使用任务标题、序号或每次请求都变化的临时 ID。 +2. 前端先调用 `GET /api/position-roundtable/sessions?external_task_id=`;返回的是该任务下所有用户共享的会商记录,按最近更新时间排序。选中一条后再调用 `GET /sessions/{sessionId}` 恢复完整节点和聊天快照。 +3. 没有可恢复记录时,调用 `POST /sessions`,至少传入 `{ external_task_id: taskId, task_snapshot: { ...任务展示字段 } }`。服务端将 `task_scoped` 设为 `true`,并固定快照中的 `id` / `externalTaskId` 为传入的 taskId。 +4. 后续所有意图、链条、节点、收口智能体和历史删除 API 只使用返回的 `sessionId`;不要在每次消息请求中重新创建会话。一个 taskId 可以有多条 sessionId。 +5. 不传 `taskId`(同时省略 `external_task_id`)就是兼容模式:后端只返回和操作当前用户自己的个人会话,绝不会把历史记录升级为共享。响应中的 `task_scoped` 可用来区分两种记录。 + +服务端从请求中的非空 `external_task_id` 判断是否开启共享,调用方无需也不应自行传 `task_scoped`。 + 当前岗位 ID 定义在 `lib/positions.ts`: | ID | 页面岗位 | 职责 | @@ -132,10 +144,16 @@ PositionRoundtablePage 页面只维护一个 `sandboxArtifact`。`PositionNodeChat` 和 `PositionBuiltinAgentChat` 通过 `onPreviewArtifact` 上报预览目标;父页面统一渲染 `ArtifactFileDetail`。 +**对接 / 重做页面 / 排障指南(打开关闭时机、步骤条、接口约定):** +[`../../docs/position-roundtable-sandbox/沙箱打开关闭与步骤条.md`](../../docs/position-roundtable-sandbox/沙箱打开关闭与步骤条.md) +(目录说明见 [`../../docs/position-roundtable-sandbox/README.md`](../../docs/position-roundtable-sandbox/README.md)) + 设计要点: - 文件正在由 `write_file` 流式生成时,优先显示源码;完成后交由预览组件切换 Markdown 预览; -- `sandboxThreadSnapshot` 有 160ms 合并节流,只保留当前打开文件所在线程的最新快照,避免流式时频繁 setState; +- `write_file` 的参数是一整个 JSON 流,键顺序由模型决定。若 `content` 先于 `path` 到达,会先用临时文件名(`未命名文件.md`/`.html`,按正文首部嗅探)开沙箱——流式内容只按 `message_id` + `tool_call_id` 定位,与路径无关;真实 `path` 到达后沿用同一个 `previewKey` 改名,属于「更新」而非第二次交付; +- 流式快照**不能进页面 state**。本页很大(任务面板、意图结果、流程图、节点对话),按流式频率重渲染整页会把主线程占满,连消息列表都会停止绘制直到本轮结束。快照走 `createSandboxThreadStore()` + `SandboxThreadProvider`(`useSyncExternalStore`),只有沙箱子树重渲染; +- 快照的合并节流是**前沿**节流:距上次推送超过 160ms 就在流回调里同步推送,未满则挂一个补尾定时器。不能只靠尾随定时器——主线程繁忙时回调会被饿死,面板会一直冻在打开时的内容; - 用户手动关闭后,`closedSandboxKeyRef` 与 `suppressedAutoPreviewThreadIdsRef` 阻止同一线程立即把沙箱重新打开; - 切岗位、切节点、切收口阶段、新建会话和切换历史会话都会先调用 `closeSandbox()`。 @@ -158,8 +176,8 @@ PositionRoundtablePage | 方法 | 路径 | 用途 | | --- | --- | --- | -| `GET` | `/sessions?external_task_id=` | 按任务查询会话,用于恢复最近会话和历史记录。 | -| `POST` | `/sessions` | 创建初始会话并保存任务快照。 | +| `GET` | `/sessions?external_task_id=` | 传入时按任务作用域查询共享会话;不传参数时查询当前用户的个人历史。 | +| `POST` | `/sessions` | 创建会话并保存任务快照;传入非空 `external_task_id` 时服务端会将快照 ID 固定为该值并启用共享;缺失或空值时创建原有个人会话。 | | `GET` | `/sessions/{id}` | 恢复会话、节点和冻结快照。 | | `DELETE` | `/sessions/{id}` | 删除一条岗位会商历史及其节点;删除当前记录时前端会先屏蔽并发恢复请求。 | | `PUT` | `/sessions/{id}/task` | 更新未冻结的任务快照。 | @@ -173,7 +191,7 @@ PositionRoundtablePage | `POST` | `/sessions/{id}/summary/*` | 准备、发送和完成方案总结。 | | `POST` | `/sessions/{id}/action-plan/*` | 准备、发送和完成行动规划。 | | `PUT` | `/sessions/{id}/{summary|action-plan}/conversation` | 保存两个收口智能体的消息与未发送草稿。 | -| `POST` | `/demo/seed` | 按用户和 `demoKey` 幂等初始化完整演示会话。 | +| `POST` | `/demo/seed` | 按 `demoKey` 幂等初始化完整演示会话。 | 后端实现在 `offline-backend-20260512/backend/app/gateway/routers/position_roundtable.py`。 diff --git a/frontend-web/src/position-roundtable/api/sessions.ts b/frontend-web/src/position-roundtable/api/sessions.ts index ac903dd6..e9e97497 100644 --- a/frontend-web/src/position-roundtable/api/sessions.ts +++ b/frontend-web/src/position-roundtable/api/sessions.ts @@ -68,7 +68,10 @@ export interface PositionRoundtableNode { */ export interface PositionRoundtableSession { id: string; + /** Present only when the workspace was opened with a route `taskId`. */ externalTaskId: string | null; + /** True only for sessions intentionally shared by an explicit route taskId. */ + taskScoped: boolean; taskSnapshot: Record; chainId: string | null; chainSnapshot: Record | null; @@ -112,6 +115,7 @@ interface ServerNode { interface ServerSession { id: string; external_task_id: string | null; + task_scoped?: boolean; task_snapshot?: Record; chain_id: string | null; chain_snapshot?: Record | null; @@ -270,6 +274,7 @@ function toSession(session: ServerSession): PositionRoundtableSession { const result: PositionRoundtableSession = { id: session.id, externalTaskId: session.external_task_id, + taskScoped: session.task_scoped ?? false, taskSnapshot: session.task_snapshot ?? {}, chainId: session.chain_id, chainSnapshot: session.chain_snapshot ?? null, diff --git a/frontend-web/src/position-roundtable/components/PositionAgentInput.tsx b/frontend-web/src/position-roundtable/components/PositionAgentInput.tsx index 7576eb32..d37f0608 100644 --- a/frontend-web/src/position-roundtable/components/PositionAgentInput.tsx +++ b/frontend-web/src/position-roundtable/components/PositionAgentInput.tsx @@ -1,10 +1,30 @@ -import { useEffect, useRef, type ComponentProps } from "react"; +import { useEffect, useMemo, useRef, type ComponentProps } from "react"; -import { InputBox } from "@/components/workspace/input-box"; -import { usePromptInputController } from "@/components/ai-elements/prompt-input"; -import { cn } from "@/lib/utils"; +import { + usePromptInputController, + type PromptInputMessage, +} from "@/components/ai-elements/prompt-input"; +import type { InputBox } from "@/components/workspace/input-box"; +import { useModels } from "@/core/models/hooks"; +import type { AgentQuestion } from "@/core/agents"; +import { PositionIntentInput } from "@/position-roundtable/components/PositionIntentInput"; -type PositionAgentInputProps = ComponentProps & { +type InputBoxProps = ComponentProps; +type PositionAgentInputProps = Pick< + InputBoxProps, + | "className" + | "assistantId" + | "status" + | "disabled" + | "context" + | "onContextChange" + | "onSubmit" + | "onStop" + | "isNewThread" + | "threadId" + | "hideAdminRecommendedQuestions" +> & { + commonQuestions?: (string | AgentQuestion)[] | null; /** Stable node/builtin key used to restore the matching SQL-backed draft. */ draftKey?: string; draftValue?: string; @@ -18,18 +38,36 @@ type PositionAgentInputProps = ComponentProps & { * 只改这个组件即可,不会影响普通对话、工作区或其他业务页面。 */ export function PositionAgentInput({ - className, + context, + disabled = false, + status = "ready", + onContextChange, + onSubmit, + onStop, + commonQuestions, draftKey = "", draftValue = "", onDraftChange, - ...props }: PositionAgentInputProps) { - const { textInput } = usePromptInputController(); + const { textInput, attachments } = usePromptInputController(); + const { models } = useModels(); const activeDraftKeyRef = useRef(""); const restoringValueRef = useRef(null); const textInputRef = useRef(textInput); textInputRef.current = textInput; + const modelOptions = useMemo( + () => models.map((model) => ({ label: model.display_name ?? model.name, value: model.name })), + [models], + ); + const attachedFiles = useMemo( + () => + attachments.files + .map((attachment) => attachment.file) + .filter((file): file is File => file instanceof File), + [attachments.files], + ); + useEffect(() => { activeDraftKeyRef.current = draftKey; if (textInputRef.current.value !== draftValue) { @@ -51,13 +89,60 @@ export function PositionAgentInput({ onDraftChange?.(textInput.value); }, [draftKey, onDraftChange, textInput.value]); - // Keep the page-specific class on the wrapper rather than adding a variant - // to InputBox. Node chat and built-in chat can evolve together while every - // other workspace keeps the global composer untouched. + const handleSend = () => { + if (status === "streaming") { + onStop?.(); + return; + } + const text = textInput.value.trim(); + if (!text && attachedFiles.length === 0) return; + const message: PromptInputMessage = { + text: textInput.value, + files: attachments.files, + }; + void onSubmit?.(message); + textInput.clear(); + attachments.clear(); + }; + + const handleModelChange = (modelName: string) => { + const model = models.find((candidate) => candidate.name === modelName); + if (!model) return; + onContextChange?.({ ...context, model_name: model.name }); + }; + const selectedModel = + typeof context.model_name === "string" + ? context.model_name + : modelOptions[0]?.value; + return ( - { + const attachment = attachments.files[index]; + if (attachment) attachments.remove(attachment.id); + }} + charactersLeft={textInput.value.length} + isSending={status === "streaming"} + canSend={!disabled && (Boolean(textInput.value.trim()) || attachedFiles.length > 0)} + pendingClarification={false} + onSend={handleSend} + onStop={() => onStop?.()} + onFollowUp={() => undefined} + onSkip={() => undefined} + onEnterRoundtable={() => undefined} + enterButtonLabel="" + intentReady={null} + hideEnterRoundtable + onManualSave={() => undefined} + onTriggerToast={() => undefined} + modelOptions={modelOptions} + selectedModel={selectedModel} + onSelectedModelChange={handleModelChange} + commonQuestions={commonQuestions} /> ); } diff --git a/frontend-web/src/position-roundtable/components/PositionBuiltinAgentChat.tsx b/frontend-web/src/position-roundtable/components/PositionBuiltinAgentChat.tsx index e12e461c..0cec3208 100644 --- a/frontend-web/src/position-roundtable/components/PositionBuiltinAgentChat.tsx +++ b/frontend-web/src/position-roundtable/components/PositionBuiltinAgentChat.tsx @@ -716,7 +716,7 @@ export function PositionBuiltinAgentChat({ )} -
+
void; + commonQuestions?: (string | AgentQuestion)[] | null; } /** Keep attachment metadata presentation local to this position-only composer. */ @@ -64,40 +66,25 @@ export function PositionIntentInput({ modelOptions = [], selectedModel, onSelectedModelChange, + commonQuestions, }: PositionIntentInputProps) { // Files are owned by Step1Panel. This ref only opens the native picker and // forwards its selection through onAddFiles, so replacement layouts do not // accidentally create a second attachment state. const fileInputRef = useRef(null); + const [showMoreQuestions, setShowMoreQuestions] = useState(false); + const normalizedCommonQuestions = normalizeAgentQuestions(commonQuestions); + const visibleCommonQuestions = normalizedCommonQuestions.slice(0, 2); + const extraCommonQuestions = normalizedCommonQuestions.slice(2); + + const pickCommonQuestion = (question: AgentQuestion) => { + onValueChange(question.prompt); + setShowMoreQuestions(false); + }; return (
- {attachedFiles.length > 0 && ( -
- {attachedFiles.map((file, index) => ( - - - - {file.name} - - {formatFileSize(file.size)} - - - ))} -
- )} - - + + 上传附件
{charactersLeft}/500 @@ -154,8 +142,79 @@ export function PositionIntentInput({ Parent pages can still hide optional actions by their stable ids without changing this component's layout or global input styles. */} -
-
+
+
+ {visibleCommonQuestions.length > 0 && ( +
+ {visibleCommonQuestions.map((question, index) => ( + + ))} + {extraCommonQuestions.length > 0 && ( +
+ + {showMoreQuestions && ( +
+ {extraCommonQuestions.map((question, index) => ( + + ))} +
+ )} +
+ )} +
+ )} +
+ {attachedFiles.length > 0 && ( +
+ {attachedFiles.map((file, index) => ( + + + + {file.name} + + {formatFileSize(file.size)} + + + ))} +
+ )} +
+
fileInputRef.current?.click()} - title="上传参考文件" - aria-label="上传参考文件" - className="position-roundtable-intent-upload-btn flex size-10 items-center justify-center rounded-[4px] border border-slate-200 bg-white text-slate-500 transition hover:border-primary/45 hover:text-primary dark:border-[#2b8ffe]/35 dark:bg-[#102f63] dark:text-[#b9d3f7] dark:hover:bg-[#1a417b] dark:hover:text-[#73c8ff]" + title="上传附件" + aria-label="上传附件" + className="position-roundtable-intent-upload-btn flex items-center justify-center rounded-[24px] border-0" > - + + 上传附件
-
{modelOptions.length > 0 && (
- + onSelectedModelChange?.(String(value))} - className="w-[150px] shrink-0 [&_.t-input]:!h-8 [&_.t-input]:!border-0 [&_.t-input]:!bg-transparent [&_.t-input]:!px-1 [&_.t-input]:!text-xs [&_.t-input]:!font-bold [&_.t-input]:!shadow-none dark:[&_.t-input]:!text-[#dceaff]" + className="w-[150px] shrink-0 [&_.t-input]:!h-7 [&_.t-input]:!rounded-[4px] [&_.t-input]:!border-0 [&_.t-input]:!bg-transparent [&_.t-input]:!px-1 [&_.t-input]:!text-xs [&_.t-input]:!font-bold [&_.t-input]:!text-[#dceaff] [&_.t-input]:!shadow-none" popupProps={{ overlayClassName: "z-[80]" }} />
@@ -198,26 +257,20 @@ export function PositionIntentInput({ - {isSending && ( - - )} -
)} -
+
setSettings("context", context)} + commonQuestions={agent?.common_questions} onSubmit={(message) => void handleSubmit(message)} onStop={() => void thread.stop()} /> diff --git a/frontend-web/src/position-roundtable/demo/position-roundtable-demo.ts b/frontend-web/src/position-roundtable/demo/position-roundtable-demo.ts index f4bd57b4..ebd81e9f 100644 --- a/frontend-web/src/position-roundtable/demo/position-roundtable-demo.ts +++ b/frontend-web/src/position-roundtable/demo/position-roundtable-demo.ts @@ -97,6 +97,7 @@ export function getPositionDemoTask(): PositionTask { direction: String(task.direction ?? ""), source: String(task.source ?? "演示数据"), issuedAt: String(task.issuedAt ?? ""), + priority: String(task.priority ?? "紧急"), }; } diff --git a/frontend-web/src/position-roundtable/docs/沙箱打开关闭与步骤条.md b/frontend-web/src/position-roundtable/docs/沙箱打开关闭与步骤条.md new file mode 100644 index 00000000..3a80f5fe --- /dev/null +++ b/frontend-web/src/position-roundtable/docs/沙箱打开关闭与步骤条.md @@ -0,0 +1,391 @@ +# 岗位会商沙箱对接指南(重做页面 / 排障) + +## 文档用途 + +给**下次重做或对接岗位会商页面**的同事用,也给线上「沙箱不实时 / 卡死 / 第二次不刷新」时排障用。 + +读完应能回答: + +1. 新页面要接哪几个回调、传什么字段? +2. 打开 / 关闭沙箱各在什么时机?和步骤条是什么关系? +3. 哪些写法绝对不能用(会复现历史 bug)? +4. 出问题时按什么顺序查? + +对照实现(当前生产路径): + +| 角色 | 文件 | +| --- | --- | +| 页面壳(沙箱唯一宿主) | `pages/PositionRoundtablePage.tsx` | +| 节点对话(探测 write_file、上报预览) | `components/PositionNodeChat.tsx` | +| 收口对话 | `components/PositionBuiltinAgentChat.tsx` | +| 预览 UI(共享组件,勿分叉逻辑) | `components/workspace/artifacts/artifact-file-detail.tsx` | +| 流式正文读取 | `core/artifacts/loader.ts` → `loadArtifactContentFromToolCall` | +| 普通对话页对照(步骤条自动开) | `components/workspace/messages/message-group.tsx` | + +模块总览见同目录上级 [`../README.md`](../README.md);本文只覆盖**文件预览沙箱**这一条链路。 + +--- + +## 1. 验收标准(对接完成即通过) + +重做页面后,下列行为必须全部成立(与普通对话页用户感知一致): + +| # | 行为 | +| --- | --- | +| A | 步骤条刚出现「写入文件」时,右侧沙箱应已打开(不必等文件名出现) | +| B | 沙箱内源码随模型输出边写边滚;消息列表文字也实时出现,不能整页卡死 | +| C | 模型若先吐正文、后吐 `path`:先用临时名打开,path 到了再改名,不闪屏重挂 | +| D | 同一次问答里第二次 `write_file` 写同一路径(「重新生成」):沙箱清空并重新流式 | +| E | 整轮 `isLoading=false` 后,自动从源码切到 Markdown 预览 | +| F | 用户手动关闭后,**同一次**写入不再自动弹;**下一轮**新写入仍可自动开 | +| G | 切岗位 / 切节点 / 新建或切换会话时,沙箱关掉且不串内容 | + +--- + +## 2. 职责划分(谁干什么) + +```text +┌─────────────────────────────────────────────────────────────┐ +│ 页面壳(PositionRoundtablePage 或你的新页面) │ +│ · 唯一 sandboxArtifact 状态 │ +│ · handlePreviewArtifact / closeSandbox │ +│ · 流式线程外部 store(禁止整页 useState) │ +│ · 渲染唯一 ArtifactFileDetail │ +└──────────────────────────▲──────────────────────────────────┘ + │ onPreviewArtifact / onThreadSnapshot +┌──────────────────────────┴──────────────────────────────────┐ +│ 对话子组件(PositionNodeChat 等) │ +│ · useThreadStream 拉消息 │ +│ · 渲染 MessageList / 步骤条(只展示,不直接开沙箱) │ +│ · 探测 write_file → 组装 PositionArtifactPreview 上报 │ +│ · 每次 thread 变化上报 onThreadSnapshot │ +└─────────────────────────────────────────────────────────────┘ +``` + +硬性规则: + +1. **沙箱只有一个实例**,挂在页面壳上,不要在对话子组件里再挂 `ArtifactFileDetail`。 +2. 对话子组件**不要**直接 `artifacts.setOpen(true)` 当作岗位会商的主路径(页面壳统一开合,才能做关闭抑制、切节点清理)。 +3. 步骤条和沙箱是**两条线**:步骤条只反映 tool call 展示;开沙箱走 `onPreviewArtifact`。 + +--- + +## 3. 对接接口(重新接页面时照此接线) + +### 3.1 对话子组件 → 页面壳 + +#### `onPreviewArtifact(artifact)` + +请求打开或更新沙箱。载荷: + +```ts +type PositionArtifactPreview = { + threadId: string; // 必填:LangGraph thread id + path: string; // 必填:真实路径,或 write-file: 虚拟 URL,或临时文件名 + name: string; // 展示名 + mimeType: string | null; // 如 text/markdown;帮助预览语言判断 + previewKey?: string; // 强烈建议:一次交付的身份,推荐 `${messageId}:${toolCallId}` + auto?: boolean; // true = 流式自动打开;false/缺省 = 用户点击打开 +}; +``` + +页面壳收到后应: + +1. `auto===true` 且 `closedSandboxKey === sandboxCloseKey(artifact)` → **直接 return**(用户刚关过这一次)。 +2. 更新页面级 `sandboxArtifact`(并同步 ref,见下)。 +3. 同步 `ArtifactsContext.select(path) + setOpen(true)`(与共享预览组件生命周期对齐)。 +4. 若已有该 thread 的最新快照,立刻推进沙箱 store。 +5. React `key` 用 `sandboxCloseKey(artifact)`(有 `previewKey` 时优先它),保证新交付会重挂。 + +`sandboxCloseKey` 约定: + +```ts +// 有 previewKey:threadId:write:${previewKey} +// 无 previewKey:threadId:${normalizePath(path)} +``` + +#### `onThreadSnapshot({ threadId, thread })` + +把当前 `useThreadStream` 的 thread 对象持续交给页面壳,供沙箱读流式 `content`。 + +页面壳应: + +1. 始终写入 `latestNodeThreadSnapshotRef`(打开瞬间可能用到)。 +2. **仅当**当前沙箱 `threadId` 与 snapshot 一致时,才 `queue` → store `publish`。 +3. 节流:前沿 160ms(见第 5 节),不要纯尾随 `setTimeout`。 + +### 3.2 页面壳 → 预览组件 + +```tsx +{sandboxOpen && sandboxArtifact && ( + + + +)} +``` + +流式正文依赖虚拟 URL: + +```text +write-file:${path}?message_id=...&tool_call_id=...&language=markdown +``` + +`loadArtifactContentFromToolCall` **只认** URL 里的 `message_id` + `tool_call_id`,从 `thread.messages` 对应 tool call 的 `args.content` 取值。 +因此:**可以没有真实磁盘 path 就开沙箱**;path 主要用于文件名展示和语言猜测。 + +### 3.3 对话子组件内部必做状态(可复用现有逻辑) + +重新实现探测时,至少保留这些语义(不必同名,语义要对): + +| 状态 | 作用 | +| --- | --- | +| `armed` | 仅本轮用户 `send` 成功武装后才允许自动 `onPreviewArtifact` | +| `baselineCallKeys` | send 前已有的 `messageId:toolCallId` 集合;忽略历史 write,防止一提问就开旧文件 | +| `activePreview` | 当前已打开的 previewKey / path / toolCallId,用于 path 升级与同 call 去重 | +| 线程绑定保护 | `node.threadId` 从 null→本节点刚创建的 id 时,**不要** disarm | + +发送时: + +```text +baseline = 当前历史 write keys +armed = true +activePreview = null +→ sendMessage(...) +``` + +探测时(`isLoading`): + +```text +找到最新 write_file / str_replace +若不在 baseline: + - 有完整扩展名 path → 用真实 path + - write_file 且仅有 content → 临时名(未命名文件.md / .html) + - str_replace 无 path → 先不报 + previewKey = 同 tool call 复用,否则新 key + → onPreviewArtifact({ ..., auto: true }) +``` + +--- + +## 4. 打开 / 关闭时序(对接时按此实现) + +### 4.1 打开(自动) + +```text +用户发送 + → armed=true + 拍 baseline + → 模型开始 write_file + → 步骤条出现「写入文件」(可能还没有 path) + → content 或完整 path 任一满足探测条件 + → onPreviewArtifact(auto) + → 页面壳打开 ArtifactFileDetail + 推送 thread 快照 + → 源码视图滚动更新 + →(可选)真实 path 到达:同 previewKey 改名(path upgrade,不重挂) + → isLoading=false:共享组件自动切预览 +``` + +### 4.2 同轮第二次写入(重新生成) + +```text +write_file #1 → previewKey = msg:tc1 → 打开 +write_file #2 同 path → previewKey = msg:tc2(必须变) + → React key 变 → 组件重挂 → 视觉上清空再生成 +``` + +**禁止**用「path 相同 ⇒ 复用 previewKey」。那会导致步骤条有「重新生成」、沙箱却不动。 + +### 4.3 关闭 + +| 触发 | 行为 | +| --- | --- | +| 用户点关闭 | `closedSandboxKeyRef = sandboxCloseKey(current)`;清 artifact / store / 定时器 | +| 切岗位、切节点、新会话、切历史 | 先 `closeSandbox()`(可按产品决定是否写入抑制键;至少清面板) | +| 自动打开被抑制 | 仅当 `auto && closedKey === 当前 key`;手动打开应清抑制 | + +抑制粒度必须是**单次交付(previewKey)**,不能是「整个 thread 永远不再自动开」。 + +--- + +## 5. 重做页面时的必守规则(违反必出 bug) + +1. **流式 thread 快照禁止进页面级 `useState`** + 大页面每秒重渲染数次会占满主线程:消息列表停更、沙箱冻住、定时器饿死。 + 正确:外部 store + `useSyncExternalStore`,只让沙箱子树订阅。 + +2. **节流用前沿(leading-edge),不要纯尾随 `setTimeout`** + 距上次 publish ≥ 160ms → 同步 publish;否则补尾定时器。 + 纯「有 timer 就 return」在忙主线程下会十几秒不 flush。 + +3. **不要等完整 `path` 才开沙箱** + 报告类 agent 常先流 `content`、最后才流 `path`,硬等会晚几十秒。 + `write_file` + 已有 content → 临时名打开;`str_replace` 仍等真实 path。 + +4. **扩展名要完整再当「真实 path」** + 流式中 `.m` → `.md`,过早打开会把语言锁成 TEXT。 + +5. **previewKey 按 tool call,不按 path** + 同 path 多次写入 = 多次交付。 + +6. **打开瞬间同步推进 `sandboxArtifactRef`** + 若 flush 快照时只看 ref、而 setState 尚未提交,首帧会被「threadId 不匹配」丢掉。 + +7. **不要依赖 `onToolStart` 作为唯一打开手段** + 当前后端对部分 stream mode 可能过滤;主路径必须是 `thread.messages` 里渐进出现的 `tool_calls`。 + +8. **path upgrade 不要当第二次打开** + 同 previewKey 改 path:更新 artifact,不要乱关抽屉 / 不要重挂。 + +9. **「结束后才切预览」不是打开 bug** + `ArtifactFileDetail` 对 markdown/html 在 `isLoading` 期间强制源码视图,与普通对话页相同。 + +--- + +## 6. 步骤条怎么对接理解 + +步骤条来自消息里的 tool call 渲染(`message-group`),标题优先 `args.description`,否则文案「写入文件」;子行显示 `args.path`。 + +| 你看到的步骤条 | 含义 | 沙箱应处于 | +| --- | --- | --- | +| 仅「写入文件」,无路径 | tool call 已开始,path 可能还没流到 | **应已打开**(临时名) | +| 「写入文件」+ 路径 | path 已可用 | 已打开;若刚从临时名升级则只改名 | +| 第二条「重新生成…」+ 同路径 | 新的 write_file(新 toolCallId) | **应重挂**并重新流式 | +| 生成中顶部「正在生成,完成后自动预览」 | 仍在 code 视图 | 正常,等 isLoading 结束切预览 | + +对接时不要把「步骤条出现文件名」当成「开沙箱的唯一信号」——那会在 content-first 模型上系统性偏晚。 + +--- + +## 7. 排障手册(按症状查) + +### 7.1 沙箱开得很晚 / 要等文件名才开 + +检查顺序: + +1. 探测是否仍要求「必须有完整 path」?→ 改为 content 可开临时名。 +2. `armed` 是否在 `threadId` 回写时被误清?→ 保护「本节点绑定自己的新 thread」。 +3. 是否被 `closedSandboxKey` 抑制?→ 看是否刚关过同 previewKey。 +4. 新 call 是否落在 baseline 里?→ baseline 只能在 send 时拍一次。 + +### 7.2 沙箱打开了但内容空白 / 冻住,生成完才一口气出来 + +1. 快照是否写进了页面 `useState`?→ 改 store。 +2. 节流是否纯尾随定时器?→ 改前沿。 +3. `SandboxThreadProvider` 是否把带 `messages` 的 thread 传给了 `ArtifactFileDetail`? +4. 虚拟 URL 的 `tool_call_id` 是否与消息里一致? +5. 打开时 `sandboxArtifactRef` 是否已同步(避免首帧 flush 被丢)? + +### 7.3 消息列表也不实时,整页很卡 + +优先怀疑页面壳在流式频率下整页重渲染。 +确认没有把 `onThreadSnapshot` 落到大页面 state;临时 `console.debug` 每 chunk 打大对象也会加重(排障完删掉)。 + +### 7.4 第二次「重新生成」步骤有了,沙箱不变 + +previewKey 是否按 path 复用了?→ 必须按 `messageId:toolCallId`。 +`ArtifactFileDetail` 的 `key` 是否跟 previewKey 走?否则不会重挂。 + +### 7.5 第一次实时开,关掉后再问就不实时 / 很晚才开 + +抑制是否绑在整个 `threadId` 上?→ 改为单次 `sandboxCloseKey(previewKey)`。 + +### 7.6 预览变成纯文本 / 不像 Markdown + +1. 是否在 `.m` 阶段就当完整 path 打开了? +2. 临时名是否带 `.md` / URL 是否带 `language=markdown` / 是否传了 `mimeType`? +3. path 是否有首尾空格? + +### 7.7 只靠 onToolStart,线上偶发永远不开 + +后端可能不推 tools/events。主路径改为扫描 `thread.messages` 的 streaming `tool_calls`。 + +--- + +## 8. 对接自测清单(重做页面后必跑) + +- [ ] 首轮:步骤条「写入文件」出现时,沙箱是否已开并开始出字? +- [ ] content-first agent:无文件名阶段是否也能开? +- [ ] path 到达后:是否只改名、不整页闪? +- [ ] 同轮第二次同路径 write:是否清空并重新流式? +- [ ] 流式中消息列表是否仍实时?页面是否明显卡顿? +- [ ] 手动关闭后本次是否不再弹?下一轮是否仍可自动开? +- [ ] 结束后是否自动切 Markdown 预览? +- [ ] 切节点 / 切岗位 / 新会话:沙箱是否关闭且内容不串? + +--- + +## 9. 最小接线伪代码(新页面可抄) + +```tsx +// 页面壳 +const [sandboxArtifact, setSandboxArtifact] = useState(null); +const sandboxArtifactRef = useRef(sandboxArtifact); +const closedSandboxKeyRef = useRef(null); +const store = useMemo(createSandboxThreadStore, []); + +function handlePreviewArtifact(artifact: PositionArtifactPreview) { + const key = sandboxCloseKey(artifact); + if (artifact.auto && closedSandboxKeyRef.current === key) return; + + const prev = sandboxArtifactRef.current; + const sameKey = prev?.previewKey && prev.previewKey === artifact.previewKey + && prev.threadId === artifact.threadId; + const pathOnlyUpgrade = sameKey && prev.path !== artifact.path; + + sandboxArtifactRef.current = artifact; + setSandboxArtifact(artifact); + // publish latest thread snapshot into store (leading-edge throttle) + // ArtifactsContext.select + setOpen(true) + if (!pathOnlyUpgrade) closeRightDrawer(); +} + +function closeSandbox() { + if (sandboxArtifactRef.current) { + closedSandboxKeyRef.current = sandboxCloseKey(sandboxArtifactRef.current); + } + sandboxArtifactRef.current = null; + setSandboxArtifact(null); + store.publish(null); +} + +// 对话子组件 + +``` + +对话侧探测逻辑优先**复用** `PositionNodeChat` 内的 `latestStreamingWriteFile` / armed / baseline,而不是从零再写一套——这是最容易写错的部分。 + +--- + +## 10. 术语 + +| 词 | 含义 | +| --- | --- | +| armed | 本轮用户发送后,允许自动打开沙箱 | +| baseline | send 前已有 write tool call 集合,用于忽略历史产物 | +| previewKey | 一次交付身份,推荐 `messageId:toolCallId` | +| sandboxCloseKey | 关闭抑制键 + React key | +| provisional path | 无真实 path 时的临时文件名 | +| path upgrade | 同 previewKey 下临时名 → 真实 path | +| sandboxThreadStore | 流式线程外部 store,避免整页重渲染 | +| write-file: URL | 用 message/tool call id 定位流式 content 的虚拟路径 | + +--- + +## 11. 相关提交(背景) + +若需对照修复动机,可查: + +- `fix(frontend): 岗位会商沙箱在 write_file 流式阶段实时打开并刷新` — 临时名打开、store、前沿节流 +- `fix(frontend): 同路径二次 write_file 时重挂岗位会商沙箱` — previewKey 按 tool call + +排障时优先对照本文第 5、7 节,再对照上述提交的 diff。 diff --git a/frontend-web/src/position-roundtable/lib/mock-task-source.ts b/frontend-web/src/position-roundtable/lib/mock-task-source.ts index 206084a5..97fbecd1 100644 --- a/frontend-web/src/position-roundtable/lib/mock-task-source.ts +++ b/frontend-web/src/position-roundtable/lib/mock-task-source.ts @@ -13,6 +13,7 @@ export interface PositionTask { direction: string; source: string; issuedAt: string; + priority?: string; } export const MOCK_POSITION_TASKS: readonly PositionTask[] = [ @@ -30,16 +31,21 @@ export const MOCK_POSITION_TASKS: readonly PositionTask[] = [ export const DEFAULT_MOCK_POSITION_TASK_ID = MOCK_POSITION_TASKS[0].id; export function getMockPositionTask(taskId?: string | null): PositionTask { - return ( + const fixture = MOCK_POSITION_TASKS.find((task) => task.id === taskId) ?? - MOCK_POSITION_TASKS[0] - ); + MOCK_POSITION_TASKS[0]; + const scopedTaskId = taskId?.trim(); + // The fixture supplies only display defaults. Preserve the caller's task + // identity so persistence, history and LangGraph thread metadata all remain + // bound to the route taskId. + return scopedTaskId ? { ...fixture, id: scopedTaskId } : fixture; } /** Normalizes a persisted Session task snapshot without exposing source internals. */ export function taskFromPositionSnapshot( snapshot: Record | null | undefined, fallback: PositionTask, + taskScopeId?: string, ): PositionTask { if (!snapshot || Object.keys(snapshot).length === 0) return fallback; const value = (keys: string[], defaultValue: string) => { @@ -49,10 +55,15 @@ export function taskFromPositionSnapshot( return typeof found === "string" ? found : defaultValue; }; return { - id: value(["id", "taskId", "externalTaskId"], fallback.id), + // Session snapshots are editable display data, while the route taskId is + // the stable shared-storage scope. Keeping them separate prevents a + // legacy/mock snapshot from moving a live external task into another + // task's history bucket. + id: taskScopeId?.trim() || value(["id", "taskId", "externalTaskId"], fallback.id), title: value(["title", "taskName", "name"], fallback.title), description: value(["description", "taskContent", "overview", "content"], fallback.description), direction: value(["direction", "taskDirection", "category"], fallback.direction), + priority: value(["priority", "level", "urgency"], fallback.priority ?? "紧急"), source: (() => { const source = value(["source", "taskSource", "sourceName"], fallback.source); return source === "mock" ? "本系统创建" : source; diff --git a/frontend-web/src/position-roundtable/pages/PositionRoundtablePage.tsx b/frontend-web/src/position-roundtable/pages/PositionRoundtablePage.tsx index df40752e..9143bbbc 100644 --- a/frontend-web/src/position-roundtable/pages/PositionRoundtablePage.tsx +++ b/frontend-web/src/position-roundtable/pages/PositionRoundtablePage.tsx @@ -1,5 +1,14 @@ import type { BaseStream } from "@langchain/langgraph-sdk/react"; -import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { + type ReactNode, + useCallback, + useEffect, + useMemo, + useRef, + useState, + useSyncExternalStore, +} from "react"; +import { createPortal } from "react-dom"; import { useQuery } from "@tanstack/react-query"; import { useNavigate, useSearchParams } from "react-router-dom"; import { @@ -74,7 +83,23 @@ import { textOfMessage } from "@/core/threads/utils"; import { desensitize } from "@/lib/desensitize"; import { cn } from "@/lib/utils"; import expandLogo from "@/assets/position-roundtable/expand-logo.svg"; -import { listChains } from "@/roundtable-planning/api/chains"; +import editTaskIcon from "@/assets/position-roundtable/edit-task.svg"; +import searchTaskIcon from "@/assets/position-roundtable/search-task.svg"; +import addTaskIcon from "@/assets/position-roundtable/add-task.svg"; +import moreTaskIcon from "@/assets/position-roundtable/more-task.svg"; +import askQuestionIcon from "@/assets/position-roundtable/ask-question.svg"; +import agentConfigLogo from "@/assets/position-roundtable/agent-config-logo.svg"; +import doubleArrowDecoration from "@/assets/position-roundtable/double-arrow-decoration.svg"; +import collapsePanelIcon from "@/assets/position-roundtable/collapse-panel.svg"; +import analysisTag1 from "@/assets/position-roundtable/标签1.svg"; +import analysisTag2 from "@/assets/position-roundtable/标签2.svg"; +import analysisTag3 from "@/assets/position-roundtable/标签3.svg"; +import analysisTag4 from "@/assets/position-roundtable/标签4.svg"; +import analysisTag5 from "@/assets/position-roundtable/标签5.svg"; +import analysisTag6 from "@/assets/position-roundtable/标签6.svg"; +import responsibilityIcon from "@/assets/position-roundtable/责任岗位.svg"; +import resultTimeIcon from "@/assets/position-roundtable/时间.svg"; +import { deleteChain, listChains } from "@/roundtable-planning/api/chains"; import { Step1Panel } from "@/roundtable-planning/components/Step1Panel"; import { PositionIntentInput } from "@/position-roundtable/components/PositionIntentInput"; import { PositionNodeChat } from "@/position-roundtable/components/PositionNodeChat"; @@ -86,7 +111,7 @@ import { type InteractiveMessage, type TimelineEntry, } from "@/roundtable-planning/hooks/useStep1Intent"; -import type { IntentSummary } from "@/roundtable-planning/api/intent"; +import { INTENT_AGENT_ID, type IntentSummary } from "@/roundtable-planning/api/intent"; import type { BusinessChain } from "@/roundtable-planning/lib/business-chain"; import { getAvatarTypeFor } from "@/roundtable-planning/lib/roundtable-constants"; import { @@ -115,6 +140,7 @@ import { getPositionSession, isPositionSessionNotFoundError, listPositionSessions, + PositionSessionNotFoundError, preparePositionActionPlan, preparePositionSummary, rejectPositionNode, @@ -157,6 +183,18 @@ type PositionArtifactPreview = { previewKey?: string; auto?: boolean; }; + +function isSessionInTaskScope( + session: PositionRoundtableSession, + taskScopeId: string | null, +): boolean { + // The legacy entry has no taskId and remains user-owned. Explicit taskId + // deep links are the only shared mode and must never cross task scopes. + return taskScopeId === null + ? !session.taskScoped + : session.taskScoped && session.externalTaskId === taskScopeId; +} + type ClosureStageKind = PositionBuiltinAgentKind; type IntentEditDraft = { objective: string; @@ -319,6 +357,72 @@ function sandboxCloseKey( return `${artifact.threadId}:${normalizePreviewArtifactPath(artifact.path)}`; } +type SandboxThreadStore = { + subscribe: (listener: () => void) => () => void; + getSnapshot: () => SandboxThreadSnapshot | null; + publish: (next: SandboxThreadSnapshot | null) => void; +}; + +/** + * The streaming thread reaches the sandbox through a subscription rather than + * page state. This page is large — task panel, intent results, flowchart, node + * chat — and a streamed file publishes several times per second. Driving that + * through `useState` here re-renders the whole page at that rate and starves the + * browser so badly that even the message list stops painting until the run ends. + * With a store, only `SandboxThreadProvider` and the preview below it re-render. + */ +function createSandboxThreadStore(): SandboxThreadStore { + let snapshot: SandboxThreadSnapshot | null = null; + const listeners = new Set<() => void>(); + return { + subscribe(listener) { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, + getSnapshot: () => snapshot, + publish(next) { + const isUnchanged = + snapshot === next || + (snapshot != null && + next != null && + snapshot.threadId === next.threadId && + snapshot.signature === next.signature); + if (isUnchanged) return; + snapshot = next; + for (const listener of listeners) { + listener(); + } + }, + }; +} + +function SandboxThreadProvider({ + store, + threadId, + fallbackThread, + children, +}: { + store: SandboxThreadStore; + threadId: string; + fallbackThread: BaseStream; + children: ReactNode; +}) { + const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot); + const thread = snapshot?.threadId === threadId ? snapshot.thread : fallbackThread; + const value = useMemo(() => ({ thread, isMock: false }), [thread]); + return {children}; +} + +/** + * Upper bound on how often the streaming thread is re-published to the sandbox. + * Message chunks arrive roughly every 30ms and re-rendering the artifact panel + * is expensive, so updates are coalesced — but never postponed past this gap, + * otherwise the panel visibly freezes while the file is being written. + */ +const SANDBOX_SNAPSHOT_MIN_INTERVAL_MS = 160; + function sandboxThreadSignature(thread: BaseStream): string { const messages = thread.messages ?? []; for (let messageIndex = messages.length - 1; messageIndex >= 0; messageIndex -= 1) { @@ -596,21 +700,24 @@ function restoreIntentMessages( ): InteractiveMessage[] { const restored: InteractiveMessage[] = []; for (const [index, message] of (messages ?? []).entries()) { - const raw = message as typeof message & { + const raw = message as unknown as { additional_kwargs?: Record; + _type?: string; + role?: string; type?: string; }; const additional = raw.additional_kwargs ?? {}; // 任务快照与工具回执仅用于模型上下文,不能成为用户可见的聊天记录。 if (additional.hide_from_ui === true || additional.task_external_context === true) continue; - const messageType = raw.type?.toLowerCase(); - if (messageType !== "human" && messageType !== "ai") continue; + const messageType = (raw.type ?? raw.role ?? raw._type)?.toLowerCase(); + if (messageType !== "human" && messageType !== "user" && messageType !== "ai" && messageType !== "assistant") continue; const content = (textOfMessage(message) ?? "").trim(); if (!content) continue; + const isUser = messageType === "human" || messageType === "user"; restored.push({ id: index + 1, - sender: messageType === "human" ? "user" : "agent", - senderName: messageType === "human" ? "用户" : "任务理解智能体", + sender: isUser ? "user" : "agent", + senderName: isUser ? "用户" : "任务理解智能体", content, time: "已恢复", }); @@ -624,13 +731,33 @@ function persistedIntentMessages( if (!Array.isArray(snapshot?.messages)) return []; return snapshot.messages.flatMap((raw, index) => { if (!raw || typeof raw !== "object") return []; - const sender = raw.sender === "user" ? "user" : raw.sender === "agent" ? "agent" : null; - const content = typeof raw.content === "string" ? raw.content : ""; + const value = raw as Record; + const senderValue = + typeof value.sender === "string" + ? value.sender.toLowerCase() + : typeof value.role === "string" + ? value.role.toLowerCase() + : typeof value.type === "string" + ? value.type.toLowerCase() + : typeof value._type === "string" + ? value._type.toLowerCase() + : ""; + const sender = + senderValue === "user" || senderValue === "human" + ? "user" + : senderValue === "agent" || senderValue === "assistant" || senderValue === "ai" + ? "agent" + : null; + const content = typeof value.content === "string" + ? value.content + : typeof value.text === "string" + ? value.text + : ""; if (!sender || !content.trim()) return []; return [ { ...(raw as unknown as InteractiveMessage), - id: typeof raw.id === "number" ? raw.id : index + 1, + id: typeof value.id === "number" ? value.id : index + 1, sender, content, }, @@ -715,18 +842,21 @@ export default function PositionRoundtablePage({ const [positionId, setPositionId] = useState(() => positionIdFromUrl); const demoModeEnabled = isPositionRoundtableDemoEnabled(); const demoTask = useMemo(() => getPositionDemoTask(), []); - const taskIdFromUrl = + // A route taskId opts into shared task collaboration. Without it this page + // keeps the original personal-session behavior and uses mock data only for + // display defaults. + const taskScopeId = standaloneDemoMode ? demoTask.id - : searchParams.get("taskId") ?? - (demoModeEnabled ? demoTask.id : DEFAULT_MOCK_POSITION_TASK_ID); + : searchParams.get("taskId")?.trim() || null; + const displayTaskId = taskScopeId ?? (demoModeEnabled ? demoTask.id : DEFAULT_MOCK_POSITION_TASK_ID); const searchParamsString = searchParams.toString(); const fallbackTask = useMemo( () => - demoModeEnabled && taskIdFromUrl === demoTask.id + demoModeEnabled && displayTaskId === demoTask.id ? demoTask - : getMockPositionTask(taskIdFromUrl), - [demoModeEnabled, demoTask, taskIdFromUrl], + : getMockPositionTask(displayTaskId), + [demoModeEnabled, demoTask, displayTaskId], ); const rawSessionIdFromUrl = searchParams.get("sessionId"); const sessionIdFromUrl = @@ -786,7 +916,7 @@ export default function PositionRoundtablePage({ const [sessionLoading, setSessionLoading] = useState(false); const [sessionDiscoveryDone, setSessionDiscoveryDone] = useState(Boolean(sessionIdFromUrl)); const [startingChain, setStartingChain] = useState(false); - const [rightPanelOpen, setRightPanelOpen] = useState(true); + const [rightPanelOpen, setRightPanelOpen] = useState(false); const [rightTab, setRightTab] = useState(() => standaloneDemoMode ? "results" : "agents", ); @@ -804,6 +934,10 @@ export default function PositionRoundtablePage({ // click bubbling. Mark a delete pointer gesture so the item-level selection // can explicitly cancel navigation to the row being deleted. const suppressHistorySelectIdRef = useRef(null); + // Switching history should start with the right workspace collapsed. Keep + // this marker through session hydration so the delivery-overview effect does + // not immediately reopen it for a completed historical session. + const suppressRightPanelAutoOpenForSessionRef = useRef(null); const [intentInputDraft, setIntentInputDraft] = useState(""); const localDemoFallback = standaloneDemoMode || isLocalPositionDemoSession(positionSession?.id); @@ -828,10 +962,11 @@ export default function PositionRoundtablePage({ const [sandboxArtifact, setSandboxArtifact] = useState(null); const sandboxArtifactRef = useRef(null); const closedSandboxKeyRef = useRef(null); - const [sandboxThreadSnapshot, setSandboxThreadSnapshot] = useState(null); + const sandboxThreadStore = useMemo(createSandboxThreadStore, []); const latestNodeThreadSnapshotRef = useRef(null); const pendingSandboxThreadSnapshotRef = useRef(null); const sandboxSnapshotTimerRef = useRef(null); + const sandboxSnapshotAppliedAtRef = useRef(0); const [flowDetailItem, setFlowDetailItem] = useState(null); const [taskEditorOpen, setTaskEditorOpen] = useState(false); const [taskDraft, setTaskDraft] = useState(fallbackTask); @@ -864,7 +999,10 @@ export default function PositionRoundtablePage({ sandboxArtifactRef.current = sandboxArtifact; }, [sandboxArtifact]); const flushSandboxThreadSnapshot = useCallback(() => { - sandboxSnapshotTimerRef.current = null; + if (sandboxSnapshotTimerRef.current !== null) { + window.clearTimeout(sandboxSnapshotTimerRef.current); + sandboxSnapshotTimerRef.current = null; + } const pending = pendingSandboxThreadSnapshotRef.current; pendingSandboxThreadSnapshotRef.current = null; if (!pending) return; @@ -872,21 +1010,28 @@ export default function PositionRoundtablePage({ if (!currentArtifact || currentArtifact.threadId !== pending.threadId) { return; } - setSandboxThreadSnapshot((current) => - current?.threadId === pending.threadId && current.signature === pending.signature - ? current - : pending, - ); - }, []); + sandboxSnapshotAppliedAtRef.current = Date.now(); + sandboxThreadStore.publish(pending); + }, [sandboxThreadStore]); const queueSandboxThreadSnapshot = useCallback( (snapshot: SandboxThreadSnapshot) => { pendingSandboxThreadSnapshotRef.current = snapshot; - if (sandboxSnapshotTimerRef.current !== null) return; - if (typeof window === "undefined") { + // Leading-edge throttle: publish straight away whenever the previous + // publish is old enough. Trailing timers alone are not dependable here — + // a continuous stream keeps the main thread busy and the panel then stays + // frozen on the content it had when it opened. + const sinceApplied = Date.now() - sandboxSnapshotAppliedAtRef.current; + if (typeof window === "undefined" || sinceApplied >= SANDBOX_SNAPSHOT_MIN_INTERVAL_MS) { flushSandboxThreadSnapshot(); return; } - sandboxSnapshotTimerRef.current = window.setTimeout(flushSandboxThreadSnapshot, 160); + // Still inside the quiet window: make sure the last chunk of a stream that + // stops right now is not left unpublished. + if (sandboxSnapshotTimerRef.current !== null) return; + sandboxSnapshotTimerRef.current = window.setTimeout( + flushSandboxThreadSnapshot, + SANDBOX_SNAPSHOT_MIN_INTERVAL_MS - sinceApplied, + ); }, [flushSandboxThreadSnapshot], ); @@ -894,6 +1039,7 @@ export default function PositionRoundtablePage({ () => () => { if (sandboxSnapshotTimerRef.current !== null) { window.clearTimeout(sandboxSnapshotTimerRef.current); + sandboxSnapshotTimerRef.current = null; } }, [], @@ -903,8 +1049,8 @@ export default function PositionRoundtablePage({ [positionSession?.intentSnapshot], ); const task = useMemo( - () => taskFromPositionSnapshot(positionSession?.taskSnapshot, fallbackTask), - [fallbackTask, positionSession?.taskSnapshot], + () => taskFromPositionSnapshot(positionSession?.taskSnapshot, fallbackTask, taskScopeId ?? undefined), + [fallbackTask, positionSession?.taskSnapshot, taskScopeId], ); const intentTaskContext = useMemo( () => ({ @@ -963,8 +1109,15 @@ export default function PositionRoundtablePage({ taskContext: intentTaskContext, initialWelcomeText: "我已读取左侧任务信息。你可以直接补充本次任务的特殊约束;如果没有补充,我会基于现有任务信息进行意图识别。", + showInitialWelcome: false, triggerToast, }); + // `useStep1Intent` starts with an empty list for a new intent session. Keep + // the complete list here so a restored historical session can display its + // first agent turn as well as the user's follow-up turns. The old + // first-user filter made histories that only contained an agent response + // look like a brand-new empty conversation. + const visibleIntentMessages = intent.interactiveMessages; const hydratedIntentSessionRef = useRef(null); const restoringIntentSessionRef = useRef(null); const persistedIntentRef = useRef(null); @@ -1007,9 +1160,10 @@ export default function PositionRoundtablePage({ positionSession?.status === "archived"; const syncSessionUrl = useCallback( - (sessionId: string, nextTaskId: string) => { + (sessionId: string, nextTaskId?: string | null) => { const next = new URLSearchParams(searchParamsString); - next.set("taskId", nextTaskId); + if (nextTaskId) next.set("taskId", nextTaskId); + else next.delete("taskId"); next.set("sessionId", sessionId); next.delete("new"); setSearchParams(next, { replace: true }); @@ -1025,20 +1179,20 @@ export default function PositionRoundtablePage({ const localSession = getLocalPositionDemoSession(); positionSessionRef.current = localSession; setPositionSession(localSession); - syncSessionUrl(localSession.id, localSession.externalTaskId ?? taskSnapshot.id); + syncSessionUrl(localSession.id, taskScopeId); return localSession; } if (sessionCreationRef.current) return sessionCreationRef.current; const creation = createPositionSession({ - externalTaskId: taskSnapshot.id || undefined, - taskSnapshot: { ...taskSnapshot }, + externalTaskId: taskScopeId ?? undefined, + taskSnapshot: taskScopeId ? { ...taskSnapshot, id: taskScopeId } : { ...taskSnapshot }, }) .then((created) => { // Update the ref synchronously. Several effects can observe a new // intent thread in the same render cycle; all must share this row. positionSessionRef.current = created; setPositionSession(created); - syncSessionUrl(created.id, taskSnapshot.id); + syncSessionUrl(created.id, taskScopeId); return created; }) .finally(() => { @@ -1049,7 +1203,7 @@ export default function PositionRoundtablePage({ sessionCreationRef.current = creation; return creation; }, - [standaloneDemoMode, syncSessionUrl], + [standaloneDemoMode, syncSessionUrl, taskScopeId], ); const openTaskEditor = useCallback(() => { @@ -1070,7 +1224,12 @@ export default function PositionRoundtablePage({ } const nextTask: PositionTask = { ...task, + // Task identity comes exclusively from the route. Task-card editing can + // change display fields but must never move this session to another + // shared task bucket. + id: taskScopeId ?? task.id, title, + priority: taskDraft.priority?.trim() || task.priority || "紧急", description: taskDraft.description.trim(), direction: taskDraft.direction.trim() || task.direction, source: taskDraft.source.trim() || task.source, @@ -1087,7 +1246,7 @@ export default function PositionRoundtablePage({ positionSessionRef.current = merged; return merged; }); - syncSessionUrl(saved.id, nextTask.id); + syncSessionUrl(saved.id, taskScopeId); setTaskEditorOpen(false); toast.success("任务信息已更新"); } catch (error) { @@ -1095,7 +1254,7 @@ export default function PositionRoundtablePage({ } finally { setTaskSaving(false); } - }, [ensureEditableSession, isArchivedSession, syncSessionUrl, task, taskDraft]); + }, [ensureEditableSession, isArchivedSession, syncSessionUrl, task, taskDraft, taskScopeId]); const openIntentEditor = useCallback(() => { if (isArchivedSession) return; @@ -1174,7 +1333,7 @@ export default function PositionRoundtablePage({ task, ]); - const { data: chains = [], isLoading: chainsLoading } = useQuery({ + const { data: chains = [], isLoading: chainsLoading, refetch: refetchChains } = useQuery({ queryKey: ["position-roundtable", "chains"], queryFn: async () => { const [mine, published] = await Promise.all([ @@ -1185,8 +1344,26 @@ export default function PositionRoundtablePage({ }, enabled: !standaloneDemoMode, staleTime: 30_000, + refetchOnMount: "always", }); const [selectedChainId, setSelectedChainId] = useState(""); + const handleDeleteChain = useCallback( + async (chain: BusinessChain) => { + const title = desensitize(chain.title || "未命名作业链条"); + if (!window.confirm(`确认删除作业链条“${title}”吗?`)) return; + try { + await deleteChain(chain.id); + const refreshed = await refetchChains(); + if (selectedChainId === chain.id) { + setSelectedChainId(refreshed.data?.[0]?.id ?? ""); + } + toast.success(`已删除作业链条「${title}」`); + } catch (error) { + toast.error(`删除失败:${error instanceof Error ? error.message : String(error)}`); + } + }, + [refetchChains, selectedChainId], + ); useEffect(() => { if (!selectedChainId && chains[0]) setSelectedChainId(chains[0].id); }, [chains, selectedChainId]); @@ -1203,18 +1380,44 @@ export default function PositionRoundtablePage({ } return selectedChain; }, [positionSession?.chainSnapshot, positionSession?.status, selectedChain]); + // The intent position always uses the same built-in agent as the + // multi-agent roundtable Step 1 flow. Do not derive this from a chain seat: + // older chains may have no seat agent id (or a removed legacy id), which + // would make the configuration panel request a non-existent agent. + const intentAgentId = INTENT_AGENT_ID; const isIntelligenceDeliveryOverview = activePosition.isIntentPosition && positionSession !== null && positionSession.status !== "intent_pending"; + const showIntentDeliveryOverview = + isIntelligenceDeliveryOverview || + (!activePosition.isIntentPosition && positionSession !== null); const previousIntelligenceDeliveryOverviewRef = useRef(isIntelligenceDeliveryOverview); useEffect(() => { - // Sending the last intent answer transitions the page into the delivery - // overview. Restore the right workspace at that moment instead of leaving - // the user on an unexpectedly full-width, empty-looking conversation area. + // The activation boundary is the only automatic open for the testing + // analysis workspace. Once the business chain starts, open the result + // list; a pending (new / unstarted) intent session remains closed by + // default. History selection installs the suppression marker below so it + // always wins over this transition. if (isIntelligenceDeliveryOverview && !previousIntelligenceDeliveryOverviewRef.current) { - setRightPanelOpen(true); + if (suppressRightPanelAutoOpenForSessionRef.current === positionSession?.id) { + suppressRightPanelAutoOpenForSessionRef.current = null; + } else { + setRightTab("results"); + setRightPanelOpen(true); + } } previousIntelligenceDeliveryOverviewRef.current = isIntelligenceDeliveryOverview; - }, [isIntelligenceDeliveryOverview]); + }, [isIntelligenceDeliveryOverview, positionSession?.id]); + useEffect(() => { + // A pending historical session never enters the overview on hydration; + // release the one-shot suppression so a later, new completion can still + // open the workspace normally. + if ( + positionSession?.status === "intent_pending" && + suppressRightPanelAutoOpenForSessionRef.current === positionSession.id + ) { + suppressRightPanelAutoOpenForSessionRef.current = null; + } + }, [positionSession?.id, positionSession?.status]); const leftSidebarHidden = leftPanelCollapsed; const allPositionDeliveriesDone = useMemo( () => allExecutableNodesDone(positionSession?.nodes ?? []), @@ -1342,7 +1545,7 @@ export default function PositionRoundtablePage({ let cancelled = false; void getPositionSession(sessionIdFromUrl) .then((session) => { - if (!cancelled) { + if (!cancelled && isSessionInTaskScope(session, taskScopeId)) { positionSessionRef.current = session; setPositionSession(session); } @@ -1351,7 +1554,7 @@ export default function PositionRoundtablePage({ return () => { cancelled = true; }; - }, [positionSession, sessionIdFromUrl]); + }, [positionSession, sessionIdFromUrl, taskScopeId]); const handleNodeUpdate = useCallback((updatedNode: PositionRoundtableNode) => { setPositionSession((current) => { if (!current?.nodes) return current; @@ -1573,16 +1776,7 @@ export default function PositionRoundtablePage({ interactiveMessages: interactiveMessages.length > 0 ? interactiveMessages - : [ - { - id: 1, - sender: "agent", - senderName: "任务理解智能体", - content: - "我已读取左侧任务信息。你可以直接补充本次任务的特殊约束;如果没有补充,我会基于现有任务信息进行意图识别。", - time: "已恢复", - }, - ], + : [], timelineEntries: isAlreadyBound && latest.timelineEntries.length > databaseTimeline.length ? latest.timelineEntries @@ -1602,16 +1796,7 @@ export default function PositionRoundtablePage({ ? databaseMessages : latest.interactiveMessages.length > 0 ? latest.interactiveMessages - : [ - { - id: 1, - sender: "agent", - senderName: "任务理解智能体", - content: - "我已读取左侧任务信息。你可以直接补充本次任务的特殊约束;如果没有补充,我会基于现有任务信息进行意图识别。", - time: "已恢复", - }, - ]; + : []; hydrateIntentFromDraft({ intentThreadId: intentThreadId ?? latest.intentThreadId, intentReady: latestFrozenIntentRef.current ?? latest.intentReady, @@ -1648,15 +1833,17 @@ export default function PositionRoundtablePage({ ); const openPositionConfig = useCallback( (chainId: string) => { - const taskQuery = `taskId=${encodeURIComponent(task.id)}${forceNewSession ? "&new=1" : ""}`; - const returnTo = sessionIdFromUrl - ? `/page/strategy/qa/position-roundtable?${taskQuery}&sessionId=${encodeURIComponent(sessionIdFromUrl)}` - : `/page/strategy/qa/position-roundtable?${taskQuery}`; + const returnParams = new URLSearchParams(); + if (taskScopeId) returnParams.set("taskId", taskScopeId); + if (forceNewSession) returnParams.set("new", "1"); + if (sessionIdFromUrl) returnParams.set("sessionId", sessionIdFromUrl); + const returnQuery = returnParams.toString(); + const returnTo = `/page/strategy/qa/position-roundtable${returnQuery ? `?${returnQuery}` : ""}`; navigate( `/page/workspace/roundtable/chains?chainId=${encodeURIComponent(chainId)}&mode=position&returnTo=${encodeURIComponent(returnTo)}`, ); }, - [forceNewSession, navigate, sessionIdFromUrl, task.id], + [forceNewSession, navigate, sessionIdFromUrl, taskScopeId], ); // The mock task source mirrors the future external-task contract: opening a @@ -1679,7 +1866,7 @@ export default function PositionRoundtablePage({ const useDemoFixture = demoModeEnabled && task.id === demoTask.id; const discovery = useDemoFixture ? initializePositionRoundtableDemo().then((session) => [session]) - : listPositionSessions(task.id); + : listPositionSessions(taskScopeId ?? undefined); void discovery .then((sessions) => { if (cancelled) return; @@ -1697,7 +1884,8 @@ export default function PositionRoundtablePage({ setSessionDiscoveryDone(true); } const next = new URLSearchParams(searchParamsString); - next.set("taskId", task.id); + if (taskScopeId) next.set("taskId", taskScopeId); + else next.delete("taskId"); next.set("sessionId", latest.id); setSearchParams(next, { replace: true }); }) @@ -1717,7 +1905,7 @@ export default function PositionRoundtablePage({ searchParamsString, sessionIdFromUrl, setSearchParams, - task.id, + taskScopeId, ]); // Create the database row as soon as discovery confirms this is a new task @@ -1764,6 +1952,11 @@ export default function PositionRoundtablePage({ : getPositionSession(sessionIdFromUrl); void request .then((session) => { + if (!isSessionInTaskScope(session, taskScopeId)) { + // A shared session id can be pasted with the wrong taskId. Treat it + // as stale navigation instead of allowing it to cross task scopes. + throw new PositionSessionNotFoundError(sessionIdFromUrl); + } if ( !cancelled && !ignoredSessionLoadIdsRef.current.has(sessionIdFromUrl) @@ -1802,11 +1995,31 @@ export default function PositionRoundtablePage({ return () => { cancelled = true; }; - }, [searchParamsString, sessionIdFromUrl, setSearchParams]); + }, [searchParamsString, sessionIdFromUrl, setSearchParams, taskScopeId]); - const { agent: selectedAgent } = useAgent(selectedAgentId, { + const agentIdForPanel = activePosition.isIntentPosition ? INTENT_AGENT_ID : selectedAgentId; + const { agent: selectedAgent } = useAgent(agentIdForPanel, { enabled: !standaloneDemoMode, }); + const selectedAgentForPanel = useMemo(() => { + if (selectedAgent) return selectedAgent; + // The intent position has one dedicated agent configuration surface. Keep + // it directly reachable even while its agent query is still resolving or + // a local fixture does not expose the catalog API. + if (!activePosition.isIntentPosition) return null; + const seat = activeChain?.seats.find((item) => item.position_id === intentPositionId); + return { + id: INTENT_AGENT_ID, + name: seat?.name || `${activePosition.name}智能体`, + description: seat?.description || activePosition.description, + user_id: null, + published: true, + is_private: false, + builtin: true, + skills: [], + common_questions: [], + }; + }, [activeChain?.seats, activePosition, intentPositionId, selectedAgent]); useEffect(() => { if (intent.intentReady && !intentCompletedAt) setIntentCompletedAt(timeLabel()); if (!intent.intentReady && intentCompletedAt) setIntentCompletedAt(""); @@ -1869,8 +2082,16 @@ export default function PositionRoundtablePage({ session = await activatePositionSession(session.id, selectedChain.id); positionSessionRef.current = session; setPositionSession(session); + // The activation action originates from the testing-analysis position. + // Switch the just-opened sidebar straight to results so users see the + // chain delivery list rather than the agent configuration by default. + if (positionId === intentPositionId) { + setRightTab("results"); + setRightPanelOpen(true); + } const next = new URLSearchParams(searchParams); - next.set("taskId", task.id); + if (taskScopeId) next.set("taskId", taskScopeId); + else next.delete("taskId"); next.set("sessionId", session.id); next.delete("new"); setSearchParams(next, { replace: true }); @@ -1892,6 +2113,9 @@ export default function PositionRoundtablePage({ setSearchParams, startingChain, task, + taskScopeId, + intentPositionId, + positionId, ]); const handleCreateNewSession = useCallback(async () => { @@ -1907,7 +2131,7 @@ export default function PositionRoundtablePage({ } closedSandboxKeyRef.current = null; setSandboxArtifact(null); - setSandboxThreadSnapshot(null); + sandboxThreadStore.publish(null); intent.resetIntent(); hydratedIntentSessionRef.current = null; restoringIntentSessionRef.current = null; @@ -1916,17 +2140,28 @@ export default function PositionRoundtablePage({ setPositionSession(null); setIntentInputDraft(""); setSessionDiscoveryDone(true); + // A new task always starts from the testing-analysis intent stage. Reset + // the right workspace explicitly rather than relying on the asynchronous + // URL/session effects, which avoids a previous active session reopening + // the results sidebar for a moment. + suppressRightPanelAutoOpenForSessionRef.current = null; + setPositionId(intentPositionId); + setRightTab("agents"); + setRightPanelOpen(false); + setLeftPanelCollapsed(false); setSelectedAgentId(null); setActiveNodeKey(null); setActiveBuiltinKind(null); setBuiltinAutoStartRequestKey(0); setIntentCompletedAt(""); const next = new URLSearchParams(searchParams); - next.set("taskId", task.id); + if (taskScopeId) next.set("taskId", taskScopeId); + else next.delete("taskId"); + next.set("positionId", intentPositionId); next.delete("sessionId"); next.set("new", "1"); setSearchParams(next); - }, [intent, queueIntentConversationSave, searchParams, setSearchParams, task.id]); + }, [intent, intentPositionId, queueIntentConversationSave, searchParams, setSearchParams, taskScopeId]); const loadHistorySessions = useCallback(() => { if (isLocalPositionDemoSession(positionSessionRef.current?.id)) { @@ -1935,7 +2170,7 @@ export default function PositionRoundtablePage({ return; } setHistoryLoading(true); - void listPositionSessions(task.id) + void listPositionSessions(taskScopeId ?? undefined) .then((sessions) => { setHistorySessions( [...sessions].sort((left, right) => { @@ -1951,7 +2186,7 @@ export default function PositionRoundtablePage({ .finally(() => { setHistoryLoading(false); }); - }, [task.id]); + }, [taskScopeId]); const handleHistoryMenuOpenChange = useCallback( (open: boolean) => { @@ -1970,6 +2205,8 @@ export default function PositionRoundtablePage({ ) { return; } + suppressRightPanelAutoOpenForSessionRef.current = sessionId; + setRightPanelOpen(false); try { await queueIntentConversationSave(); } catch { @@ -1983,7 +2220,7 @@ export default function PositionRoundtablePage({ // 会话的窗口期仍接收旧 thread 增量;hydrate 入口还会再做一次兜底清理。 intent.stopIntentStream(); setSandboxArtifact(null); - setSandboxThreadSnapshot(null); + sandboxThreadStore.publish(null); setActiveNodeKey(null); setActiveBuiltinKind(null); setSelectedAgentId(null); @@ -1993,7 +2230,8 @@ export default function PositionRoundtablePage({ restoringIntentSessionRef.current = null; persistedIntentRef.current = null; const next = new URLSearchParams(searchParams); - next.set("taskId", task.id); + if (taskScopeId) next.set("taskId", taskScopeId); + else next.delete("taskId"); next.set("sessionId", sessionId); next.delete("new"); setSearchParams(next); @@ -2004,7 +2242,7 @@ export default function PositionRoundtablePage({ searchParams, sessionIdFromUrl, setSearchParams, - task.id, + taskScopeId, ], ); @@ -2064,7 +2302,8 @@ export default function PositionRoundtablePage({ setSelectedAgentId(null); setHistoryMenuOpen(false); const next = new URLSearchParams(searchParams); - next.set("taskId", task.id); + if (taskScopeId) next.set("taskId", taskScopeId); + else next.delete("taskId"); if (nextSession) { // Prefer the most recently active remaining conversation so the // user stays in history instead of being dropped onto a blank page. @@ -2094,7 +2333,7 @@ export default function PositionRoundtablePage({ sessionIdFromUrl, setSearchParams, standaloneDemoMode, - task.id, + taskScopeId, ], ); @@ -2106,7 +2345,7 @@ export default function PositionRoundtablePage({ return; } - const artifactKey = sandboxCloseKey(artifact); + const artifactKey = sandboxCloseKey(artifact); if (artifact.auto) { // Closing an old file should only suppress that exact preview. A later // write_file in the same thread is a new deliverable and must still be @@ -2117,22 +2356,47 @@ export default function PositionRoundtablePage({ } closedSandboxKeyRef.current = null; - setSandboxArtifact((current) => { - const isSamePreview = - current?.threadId === artifact.threadId && - current.path === artifact.path && - current.previewKey === artifact.previewKey; - return isSamePreview ? current : artifact; - }); - setSandboxThreadSnapshot((current) => - current?.threadId === artifact.threadId ? current : null, - ); + // Follow the same lifecycle as the regular conversation view. The + // position workspace owns a custom visual container, but the artifact + // selection/open state must still advance at tool-start so its preview is + // not deferred until the final artifact list is written. + const ctx = artifactsCtxRef.current; + ctx?.select(artifact.path, true); + ctx?.setOpen(true); + + const openedArtifact = sandboxArtifactRef.current; + const isSamePreview = + openedArtifact?.threadId === artifact.threadId && + openedArtifact.path === artifact.path && + openedArtifact.previewKey === artifact.previewKey; + // A streaming file is previewed under a provisional name until its real path + // arrives. Adopting that path renames the open panel; it does not deliver a + // second file, so the surrounding layout must not be reshuffled again. + const isPathUpgrade = + !isSamePreview && + Boolean(artifact.previewKey) && + openedArtifact?.threadId === artifact.threadId && + openedArtifact.previewKey === artifact.previewKey; + if (!isSamePreview) { + setSandboxArtifact(artifact); + // The snapshot queued below is published synchronously, before the state + // update above commits, so the ref that gates it has to advance here. + sandboxArtifactRef.current = artifact; + // A newly opened panel must show the file's current content immediately + // instead of waiting out the throttle window of the previous preview. + sandboxSnapshotAppliedAtRef.current = 0; + } + if (sandboxThreadStore.getSnapshot()?.threadId !== artifact.threadId) { + sandboxThreadStore.publish(null); + } const latestSnapshot = latestNodeThreadSnapshotRef.current; if (latestSnapshot?.threadId === artifact.threadId) { queueSandboxThreadSnapshot(latestSnapshot); } - setRightPanelOpen(false); + if (!isPathUpgrade) { + setRightPanelOpen(false); + } }, [queueSandboxThreadSnapshot]); const handlePreviewFlowArtifact = useCallback( (item: ResultItem) => { @@ -2203,18 +2467,6 @@ export default function PositionRoundtablePage({ }) as unknown as BaseStream, [artifactsCtx?.artifacts], ); - const sandboxThread = useMemo( - () => - sandboxArtifact && - sandboxThreadSnapshot?.threadId === sandboxArtifact.threadId - ? sandboxThreadSnapshot.thread - : sandboxThreadStub, - [sandboxArtifact, sandboxThreadSnapshot, sandboxThreadStub], - ); - const sandboxThreadContextValue = useMemo( - () => ({ thread: sandboxThread, isMock: false }), - [sandboxThread], - ); const handleNodeThreadSnapshot = useCallback( (snapshot: { threadId: string; thread: BaseStream }) => { const signature = sandboxThreadSignature(snapshot.thread); @@ -2237,10 +2489,16 @@ export default function PositionRoundtablePage({ if (ctx?.open) { ctx?.setOpen(false); } + if (sandboxSnapshotTimerRef.current !== null) { + window.clearTimeout(sandboxSnapshotTimerRef.current); + sandboxSnapshotTimerRef.current = null; + } pendingSandboxThreadSnapshotRef.current = null; + sandboxSnapshotAppliedAtRef.current = 0; + sandboxArtifactRef.current = null; setSandboxArtifact(null); - setSandboxThreadSnapshot(null); - }, []); + sandboxThreadStore.publish(null); + }, [sandboxThreadStore]); const handleSelectBuiltinStage = useCallback( (kind: ClosureStageKind) => { // The closing agents are part of the testing-analysis workspace only; @@ -2284,9 +2542,9 @@ export default function PositionRoundtablePage({ setActiveBuiltinKind(null); setSelectedAgentId(null); setActiveNodeKey(null); - setRightPanelOpen(positionIdFromUrl === intentPositionId); + setRightPanelOpen(false); setLeftPanelCollapsed(false); - }, [closeSandbox, intentPositionId, positionId, positionIdFromUrl]); + }, [closeSandbox, positionId, positionIdFromUrl]); const handlePositionChange = useCallback( (value: unknown) => { // 右侧详情只属于刚才的岗位;切岗后回到该岗位的智能体列表, @@ -2298,13 +2556,13 @@ export default function PositionRoundtablePage({ setActiveBuiltinKind(null); setSelectedAgentId(null); setActiveNodeKey(null); - setRightPanelOpen(nextPositionId === intentPositionId); + setRightPanelOpen(false); setLeftPanelCollapsed(false); const next = new URLSearchParams(searchParamsString); next.set("positionId", nextPositionId); setSearchParams(next, { replace: true }); }, - [closeSandbox, intentPositionId, searchParamsString, setSearchParams], + [closeSandbox, searchParamsString, setSearchParams], ); const renderIntentChatPanel = (chainStarted: boolean) => (
@@ -2321,19 +2579,110 @@ export default function PositionRoundtablePage({ - -
-

- {activePosition.name} · 意图识别 -

-

- {activePosition.description} -

-
+
+
} - interactiveMessages={intent.interactiveMessages} + headerRightSlot={ +
+ + +
+ } + rightSidebar={ + !sandboxOpen && ( + + ) + } + hideQuestionCount + emptyState={ + intent.isIntentInitializing ? ( +
+
+ ) : ( +
+ +

开始提问

+

输入问题,获取基于任务的智能回答

+
+ ) + } + interactiveMessages={visibleIntentMessages} intentThreadId={intent.intentThreadId} intentReady={chainStarted ? frozenIntent ?? intent.intentReady : intent.intentReady} isIntentSending={intent.isIntentSending} @@ -2388,6 +2737,7 @@ export default function PositionRoundtablePage({ modelOptions={intentModelOptions} selectedModel={selectedModel} onSelectedModelChange={setSelectedModel} + commonQuestions={selectedAgentForPanel?.common_questions} /> )} onManualSave={() => { @@ -2594,44 +2944,55 @@ export default function PositionRoundtablePage({ {leftSidebarHidden && ( @@ -2648,8 +3009,16 @@ export default function PositionRoundtablePage({ )} -
- {!rightPanelOpen && +
+ {!activePosition.isIntentPosition && + !rightPanelOpen && !sandboxOpen && !(positionSession && activeNode && !activeBuiltinKind) && (
- {activePosition.isIntentPosition && rightPanelOpen && !sandboxOpen && ( - - )} {!activePosition.isIntentPosition && ( setSelectedAgentId(null)} - intentObjective={frozenIntent?.objective ?? intent.intentReady?.objective} + selectedAgent={selectedAgentForPanel} + selectedAgentId={selectedAgentId} + positionName={activePosition.name} + specialAgentConfig={activePosition.isIntentPosition} + onSelectAgent={handleSelectAgent} + intentObjective={frozenIntent?.objective ?? intent.intentReady?.objective} intentCompletedAt={intentCompletedAt} assignedAgentIds={configurationAgentIds} hasSelectedChain={showClosureAgents || Boolean(selectedChain)} @@ -2795,18 +3132,23 @@ export default function PositionRoundtablePage({ )} {sandboxOpen && sandboxArtifact && artifactsCtx && ( )} void; + chains: BusinessChain[]; + loading: boolean; + value: string; + onChange: (value: string) => void; + onConfigure: (chainId: string) => void; + onDeleteChain: (chain: BusinessChain) => void | Promise; +}) { + const navigate = useNavigate(); + const [searchQuery, setSearchQuery] = useState(""); + const [menuOpenId, setMenuOpenId] = useState(null); + const [menuPosition, setMenuPosition] = useState<{ top: number; left: number } | null>(null); + useEffect(() => { + if (!menuOpenId) return; + const closeMenu = () => { + setMenuOpenId(null); + setMenuPosition(null); + }; + window.addEventListener("resize", closeMenu); + window.addEventListener("scroll", closeMenu, true); + return () => { + window.removeEventListener("resize", closeMenu); + window.removeEventListener("scroll", closeMenu, true); + }; + }, [menuOpenId]); + const filteredChains = useMemo(() => { + const query = searchQuery.trim().toLocaleLowerCase(); + if (!query) return chains; + return chains.filter((chain) => + `${desensitize(chain.title)} ${desensitize(chain.description ?? "")}` + .toLocaleLowerCase() + .includes(query), + ); + }, [chains, searchQuery]); + const openChainEditor = (chainId?: string) => { + const returnTo = `${window.location.pathname}${window.location.search}`; + const chainQuery = chainId ? `chainId=${encodeURIComponent(chainId)}&` : ""; + navigate( + `/page/workspace/roundtable/chains?${chainQuery}mode=position&returnTo=${encodeURIComponent(returnTo)}`, + ); + }; + + const displayDescription = + task.id === DEFAULT_MOCK_POSITION_TASK_ID + ? "围绕暑期活动的游泳夏令营开展宣传,结合线上线下渠道吸引目标人群参与,持续提升活动影响力。" + : desensitize(task.description); + const menuChain = menuOpenId ? chains.find((chain) => chain.id === menuOpenId) : null; + + return ( +
+
+ {editable && ( + + )} +

{desensitize(task.title)}

+
+ {desensitize(task.priority || "紧急")} + {desensitize(task.source)} + {desensitize(task.direction)} +
+

{desensitize(task.description)}

+
+ +
+
+
+
+ + +
+
+ {loading ? ( +
正在加载作业链条…
+ ) : chains.length === 0 ? ( +
暂无可用作业链条
+ ) : filteredChains.length === 0 ? ( +
未找到匹配的作业链条
+ ) : ( + filteredChains.map((chain) => { + const selected = chain.id === value; + const description = chain.description?.trim(); + const unassignedSeatCount = chain.seats.filter( + (seat) => !seat.position_id?.trim(), + ).length; + return ( +
+