Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
783e698b6e | ||
|
|
17a12bb7b6 | ||
|
|
f8757d1a43 | ||
|
|
69b95f0d6d | ||
|
|
ca32a22c0d | ||
|
|
3eb307c5c5 |
No files matched your search
@@ -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()
|
||||
@@ -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」
|
||||
@@ -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<PositionArtifactPreview | null>(null);
|
||||
const sandboxArtifactRef = useRef<PositionArtifactPreview | null>(null);
|
||||
const closedSandboxKeyRef = useRef<string | null>(null);
|
||||
const latestNodeThreadSnapshotRef = useRef<SandboxThreadSnapshot | null>(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<AgentThreadState> }) {
|
||||
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 && (
|
||||
<SandboxThreadProvider
|
||||
store={store}
|
||||
threadId={sandboxArtifact.threadId}
|
||||
fallbackThread={stub}
|
||||
>
|
||||
<ArtifactFileDetail
|
||||
key={sandboxCloseKey(sandboxArtifact)}
|
||||
filepath={sandboxArtifact.path}
|
||||
threadId={sandboxArtifact.threadId}
|
||||
mimeType={sandboxArtifact.mimeType}
|
||||
onClose={closeSandbox}
|
||||
allowVirtualMarkdownEdit
|
||||
/>
|
||||
</SandboxThreadProvider>
|
||||
)}
|
||||
```
|
||||
|
||||
### 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 节。
|
||||
@@ -15,6 +15,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { apiFetch } from "@/core/api";
|
||||
import { getBackendBaseURL } from "@/core/config";
|
||||
import { isThreadRagModeLocked, useLocalSettings } from "@/core/settings";
|
||||
import { isSingleRoundRagMessage } from "@/core/threads/use-single-round-rag";
|
||||
import { useSkills } from "@/core/skills/hooks";
|
||||
import type { SkillDisplayConfig } from "@/core/skills/type";
|
||||
import {
|
||||
@@ -92,6 +93,13 @@ const ChatBox: React.FC<{
|
||||
const [settings] = useLocalSettings();
|
||||
const ragModeEnabled =
|
||||
settings.display.ragModeEnabled || isThreadRagModeLocked(threadId);
|
||||
// Frontend single-round RAG writes its own source tool message, so it should
|
||||
// use the same reference panel without changing the user's global RAG mode.
|
||||
const hasSingleRoundRag = useMemo(
|
||||
() => (thread.values.messages ?? []).some(isSingleRoundRagMessage),
|
||||
[thread.values.messages],
|
||||
);
|
||||
const referencesEnabled = ragModeEnabled || hasSingleRoundRag;
|
||||
const { skills } = useSkills();
|
||||
|
||||
const {
|
||||
@@ -106,11 +114,11 @@ const ChatBox: React.FC<{
|
||||
|
||||
const [autoSelectFirstArtifact, setAutoSelectFirstArtifact] = useState(true);
|
||||
const skillDisplayMap = useMemo(
|
||||
() => (ragModeEnabled ? buildSkillDisplayMap(skills) : new Map()),
|
||||
[ragModeEnabled, skills],
|
||||
() => (referencesEnabled ? buildSkillDisplayMap(skills) : new Map()),
|
||||
[referencesEnabled, skills],
|
||||
);
|
||||
const fallbackReferenceBatches = useMemo(() => {
|
||||
if (!ragModeEnabled) {
|
||||
if (!referencesEnabled) {
|
||||
return [];
|
||||
}
|
||||
return buildTurnReferenceBatches(
|
||||
@@ -118,9 +126,9 @@ const ChatBox: React.FC<{
|
||||
skillDisplayMap,
|
||||
thread.isLoading,
|
||||
);
|
||||
}, [ragModeEnabled, skillDisplayMap, thread.isLoading, thread.values.messages]);
|
||||
}, [referencesEnabled, skillDisplayMap, thread.isLoading, thread.values.messages]);
|
||||
useEffect(() => {
|
||||
if (!ragModeEnabled) {
|
||||
if (!referencesEnabled) {
|
||||
setBackendReferenceBatches([]);
|
||||
return;
|
||||
}
|
||||
@@ -156,7 +164,7 @@ const ChatBox: React.FC<{
|
||||
}
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [ragModeEnabled, thread.isLoading, threadId, thread.values.messages]);
|
||||
}, [referencesEnabled, thread.isLoading, threadId, thread.values.messages]);
|
||||
const adaptedBackendReferenceBatches = useMemo(
|
||||
() =>
|
||||
adaptBackendReferenceBatches(
|
||||
@@ -175,7 +183,7 @@ const ChatBox: React.FC<{
|
||||
[adaptedBackendReferenceBatches, fallbackReferenceBatches],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (!ragModeEnabled) {
|
||||
if (!referencesEnabled) {
|
||||
return;
|
||||
}
|
||||
const signature = JSON.stringify({
|
||||
@@ -202,7 +210,7 @@ const ChatBox: React.FC<{
|
||||
fallbackBatches: debugReferenceBatches(fallbackReferenceBatches),
|
||||
finalBatches: debugReferenceBatches(referenceBatches),
|
||||
});
|
||||
}, [adaptedBackendReferenceBatches, backendReferenceBatches, fallbackReferenceBatches, ragModeEnabled, referenceBatches, threadId]);
|
||||
}, [adaptedBackendReferenceBatches, backendReferenceBatches, fallbackReferenceBatches, referencesEnabled, referenceBatches, threadId]);
|
||||
const latestReferenceBatch =
|
||||
referenceBatches.length > 0
|
||||
? referenceBatches[referenceBatches.length - 1]!
|
||||
@@ -213,7 +221,7 @@ const ChatBox: React.FC<{
|
||||
const referenceSources = activeReferenceBatch?.sources ?? [];
|
||||
const hasCitationReferences = referenceSources.length > 0;
|
||||
useEffect(() => {
|
||||
if (!ragModeEnabled || !activeReferenceBatch) {
|
||||
if (!referencesEnabled || !activeReferenceBatch) {
|
||||
return;
|
||||
}
|
||||
logReferenceDebug("frontend-active-reference-batch-payload", threadId, {
|
||||
@@ -222,7 +230,7 @@ const ChatBox: React.FC<{
|
||||
sourceCount: activeReferenceBatch.sources.length,
|
||||
sources: activeReferenceBatch.sources.map(debugReferenceSource),
|
||||
});
|
||||
}, [activeReferenceBatch, ragModeEnabled, threadId]);
|
||||
}, [activeReferenceBatch, referencesEnabled, threadId]);
|
||||
useEffect(() => {
|
||||
if (hasCitationReferences) {
|
||||
setReferencesOpen(true);
|
||||
|
||||
@@ -64,6 +64,7 @@ import { getBackendBaseURL } from "@/core/config";
|
||||
import { useI18n } from "@/core/i18n/hooks";
|
||||
import { isHiddenFromUIMessage } from "@/core/messages/utils";
|
||||
import { useModels } from "@/core/models/hooks";
|
||||
import type { Model } from "@/core/models/types";
|
||||
import type { AgentThreadContext } from "@/core/threads";
|
||||
import { textOfMessage } from "@/core/threads/utils";
|
||||
import { desensitize } from "@/lib/desensitize";
|
||||
@@ -133,8 +134,9 @@ export function InputBox({
|
||||
onSubmit,
|
||||
onStop,
|
||||
promptPrefix,
|
||||
agentSelector,
|
||||
assistantId,
|
||||
agentSelector,
|
||||
extraModels = [],
|
||||
assistantId,
|
||||
hideAdminRecommendedQuestions,
|
||||
compact,
|
||||
...props
|
||||
@@ -190,16 +192,23 @@ export function InputBox({
|
||||
* homepage (``ChatPage``) passes this; ``AgentChatPage`` omits it because the
|
||||
* thread is already bound to one agent.
|
||||
*/
|
||||
agentSelector?: {
|
||||
selectedAgentId: string | null;
|
||||
onAgentChange: (agentId: string | null) => void;
|
||||
};
|
||||
}) {
|
||||
agentSelector?: {
|
||||
selectedAgentId: string | null;
|
||||
onAgentChange: (agentId: string | null) => void;
|
||||
};
|
||||
/** Page-scoped model choices implemented outside the DeerFlow model API. */
|
||||
extraModels?: Model[];
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const [localSettings, setLocalSettings] = useLocalSettings();
|
||||
const searchParams = useSearchParams();
|
||||
const [modelDialogOpen, setModelDialogOpen] = useState(false);
|
||||
const { models } = useModels();
|
||||
const [modelDialogOpen, setModelDialogOpen] = useState(false);
|
||||
const { models } = useModels();
|
||||
const singleRoundRagActive =
|
||||
context.execution_profile === "single_round_rag";
|
||||
const modelOptions = useMemo(() => {
|
||||
return singleRoundRagActive ? extraModels : models;
|
||||
}, [extraModels, models, singleRoundRagActive]);
|
||||
const { thread, isMock } = useThread();
|
||||
const { textInput } = usePromptInputController();
|
||||
const promptRootRef = useRef<HTMLDivElement | null>(null);
|
||||
@@ -223,34 +232,40 @@ export function InputBox({
|
||||
recommendedQuestions.length > 0;
|
||||
|
||||
useEffect(() => {
|
||||
if (models.length === 0) {
|
||||
return;
|
||||
}
|
||||
const currentModel = models.find((m) => m.name === context.model_name);
|
||||
const fallbackModel = currentModel ?? models[0]!;
|
||||
if (modelOptions.length === 0) {
|
||||
return;
|
||||
}
|
||||
const currentModel = modelOptions.find((m) => m.name === context.model_name);
|
||||
const fallbackModel = currentModel ?? modelOptions[0]!;
|
||||
const supportsThinking = fallbackModel.supports_thinking ?? false;
|
||||
const nextModelName = fallbackModel.name;
|
||||
const nextMode = getResolvedMode(context.mode, supportsThinking);
|
||||
|
||||
if (context.model_name === nextModelName && context.mode === nextMode) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
context.model_name === nextModelName &&
|
||||
context.mode === nextMode &&
|
||||
context.execution_profile === fallbackModel.execution_profile
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
onContextChange?.({
|
||||
...context,
|
||||
model_name: nextModelName,
|
||||
mode: nextMode,
|
||||
});
|
||||
}, [context, models, onContextChange]);
|
||||
...context,
|
||||
model_name: nextModelName,
|
||||
mode: nextMode,
|
||||
execution_profile: fallbackModel.execution_profile,
|
||||
});
|
||||
}, [context, modelOptions, onContextChange]);
|
||||
|
||||
const selectedModel = useMemo(() => {
|
||||
if (modelOptions.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return modelOptions.find((m) => m.name === context.model_name) ?? modelOptions[0];
|
||||
}, [context.model_name, modelOptions]);
|
||||
|
||||
const selectedModel = useMemo(() => {
|
||||
if (models.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
return models.find((m) => m.name === context.model_name) ?? models[0];
|
||||
}, [context.model_name, models]);
|
||||
|
||||
const resolvedModelName = selectedModel?.name;
|
||||
const resolvedModelName = selectedModel?.name;
|
||||
const selectedSingleRoundRag = singleRoundRagActive;
|
||||
|
||||
const supportThinking = useMemo(
|
||||
() => selectedModel?.supports_thinking ?? false,
|
||||
@@ -264,38 +279,65 @@ export function InputBox({
|
||||
|
||||
const handleModelSelect = useCallback(
|
||||
(model_name: string) => {
|
||||
const model = models.find((m) => m.name === model_name);
|
||||
const model = modelOptions.find((m) => m.name === model_name);
|
||||
if (!model) {
|
||||
return;
|
||||
}
|
||||
onContextChange?.({
|
||||
...context,
|
||||
model_name,
|
||||
mode: getResolvedMode(context.mode, model.supports_thinking ?? false),
|
||||
reasoning_effort: context.reasoning_effort,
|
||||
});
|
||||
setModelDialogOpen(false);
|
||||
},
|
||||
[onContextChange, context, models],
|
||||
mode: getResolvedMode(context.mode, model.supports_thinking ?? false),
|
||||
reasoning_effort: context.reasoning_effort,
|
||||
execution_profile: model.execution_profile,
|
||||
});
|
||||
setModelDialogOpen(false);
|
||||
},
|
||||
[onContextChange, context, modelOptions],
|
||||
);
|
||||
|
||||
const handleModeSelect = useCallback(
|
||||
(mode: InputMode) => {
|
||||
onContextChange?.({
|
||||
...context,
|
||||
mode: getResolvedMode(mode, supportThinking),
|
||||
reasoning_effort:
|
||||
mode === "ultra"
|
||||
? "high"
|
||||
const handleModeSelect = useCallback(
|
||||
(mode: InputMode) => {
|
||||
const ordinaryModel =
|
||||
models.find((model) => model.name === context.model_name) ?? models[0];
|
||||
onContextChange?.({
|
||||
...context,
|
||||
model_name: ordinaryModel?.name ?? context.model_name,
|
||||
mode: getResolvedMode(
|
||||
mode,
|
||||
ordinaryModel?.supports_thinking ?? supportThinking,
|
||||
),
|
||||
reasoning_effort:
|
||||
mode === "ultra"
|
||||
? "high"
|
||||
: mode === "pro"
|
||||
? "medium"
|
||||
: mode === "thinking"
|
||||
? "low"
|
||||
: "minimal",
|
||||
});
|
||||
},
|
||||
[onContextChange, context, supportThinking],
|
||||
);
|
||||
? "low"
|
||||
: "minimal",
|
||||
execution_profile: undefined,
|
||||
});
|
||||
},
|
||||
[onContextChange, context, models, supportThinking],
|
||||
);
|
||||
|
||||
const handleSingleRoundRagSelect = useCallback(() => {
|
||||
const ragModel =
|
||||
extraModels.find((model) => model.name === context.model_name) ??
|
||||
extraModels[0];
|
||||
if (!ragModel) {
|
||||
return;
|
||||
}
|
||||
|
||||
onContextChange?.({
|
||||
...context,
|
||||
model_name: ragModel.name,
|
||||
mode: getResolvedMode(
|
||||
context.mode,
|
||||
ragModel.supports_thinking ?? false,
|
||||
),
|
||||
execution_profile: "single_round_rag",
|
||||
});
|
||||
}, [context, extraModels, onContextChange]);
|
||||
|
||||
const handleReasoningEffortSelect = useCallback(
|
||||
(effort: "minimal" | "low" | "medium" | "high") => {
|
||||
@@ -361,10 +403,11 @@ export function InputBox({
|
||||
onContextChange?.({
|
||||
...context,
|
||||
model_name: resolvedModelName,
|
||||
mode: getResolvedMode(
|
||||
context.mode,
|
||||
selectedModel?.supports_thinking ?? false,
|
||||
),
|
||||
mode: getResolvedMode(
|
||||
context.mode,
|
||||
selectedModel?.supports_thinking ?? false,
|
||||
),
|
||||
execution_profile: selectedModel?.execution_profile,
|
||||
});
|
||||
setTimeout(() => onSubmit?.(message), 0);
|
||||
return;
|
||||
@@ -379,7 +422,8 @@ export function InputBox({
|
||||
onStop,
|
||||
resolvedModelName,
|
||||
ragModeEnabled,
|
||||
selectedModel?.supports_thinking,
|
||||
selectedModel?.supports_thinking,
|
||||
selectedModel?.execution_profile,
|
||||
status,
|
||||
threadId,
|
||||
],
|
||||
@@ -437,8 +481,9 @@ export function InputBox({
|
||||
}, [pendingSuggestion, requestFormSubmit, textInput]);
|
||||
|
||||
const showFollowups =
|
||||
!disabled &&
|
||||
!isNewThread &&
|
||||
!disabled &&
|
||||
!isNewThread &&
|
||||
!selectedSingleRoundRag &&
|
||||
!followupsHidden &&
|
||||
(followupsLoading || followups.length > 0);
|
||||
|
||||
@@ -464,7 +509,7 @@ export function InputBox({
|
||||
return;
|
||||
}
|
||||
|
||||
if (disabled || isMock) {
|
||||
if (disabled || isMock || selectedSingleRoundRag) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -526,7 +571,7 @@ export function InputBox({
|
||||
});
|
||||
|
||||
return () => controller.abort();
|
||||
}, [context.model_name, disabled, isMock, status, thread.messages, threadId]);
|
||||
}, [context.model_name, disabled, isMock, selectedSingleRoundRag, status, thread.messages, threadId]);
|
||||
|
||||
return (
|
||||
<div ref={promptRootRef} className="relative flex flex-col gap-6">
|
||||
@@ -782,54 +827,64 @@ export function InputBox({
|
||||
</PromptInputButton>
|
||||
</Tooltip>
|
||||
<PromptInputActionMenu>
|
||||
<ModeHoverGuide
|
||||
mode={
|
||||
<ModeHoverGuide
|
||||
mode={
|
||||
context.mode === "flash" ||
|
||||
context.mode === "thinking" ||
|
||||
context.mode === "pro" ||
|
||||
context.mode === "ultra"
|
||||
? context.mode
|
||||
: "flash"
|
||||
}
|
||||
>
|
||||
? context.mode
|
||||
: "flash"
|
||||
}
|
||||
tooltipContent={
|
||||
selectedSingleRoundRag
|
||||
? "单轮 RAG 问答:基于知识库检索生成答案,并展示参考资料"
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<PromptInputActionMenuTrigger
|
||||
className={cn(
|
||||
"gap-1.5! rounded-full border-0 bg-transparent px-3! text-muted-foreground shadow-none hover:bg-muted/70 hover:text-foreground dark:text-slate-400 dark:hover:bg-slate-700/70 dark:hover:text-slate-100",
|
||||
compact && "rounded-lg border px-2.5! py-1! text-[11px] font-medium",
|
||||
compact &&
|
||||
(context.mode === "thinking"
|
||||
? "border-indigo-200 bg-indigo-50/60 text-indigo-700 hover:bg-indigo-100 dark:border-indigo-700 dark:bg-indigo-950/40 dark:text-indigo-200"
|
||||
compact &&
|
||||
(selectedSingleRoundRag
|
||||
? "border-emerald-200 bg-emerald-50/60 text-emerald-700 hover:bg-emerald-100 dark:border-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-200"
|
||||
: context.mode === "thinking"
|
||||
? "border-indigo-200 bg-indigo-50/60 text-indigo-700 hover:bg-indigo-100 dark:border-indigo-700 dark:bg-indigo-950/40 dark:text-indigo-200"
|
||||
: context.mode === "pro"
|
||||
? "border-violet-200 bg-violet-50/60 text-violet-700 hover:bg-violet-100 dark:border-violet-700 dark:bg-violet-950/40 dark:text-violet-200"
|
||||
: context.mode === "ultra"
|
||||
? "border-amber-200 bg-amber-50/60 text-amber-700 hover:bg-amber-100 dark:border-amber-700 dark:bg-amber-950/40 dark:text-amber-200"
|
||||
: "border-transparent bg-muted/40 hover:bg-muted hover:text-foreground"),
|
||||
)}
|
||||
>
|
||||
<div>
|
||||
{context.mode === "flash" && <ZapIcon className="size-3" />}
|
||||
{context.mode === "thinking" && (
|
||||
<LightbulbIcon className="size-3" />
|
||||
)}
|
||||
{context.mode === "pro" && (
|
||||
<GraduationCapIcon className="size-3" />
|
||||
)}
|
||||
{context.mode === "ultra" && (
|
||||
<RocketIcon className="size-3 text-[#dabb5e]" />
|
||||
)}
|
||||
</div>
|
||||
>
|
||||
<div>
|
||||
{selectedSingleRoundRag ? (
|
||||
<BookMarkedIcon className="size-3" />
|
||||
) : context.mode === "flash" ? (
|
||||
<ZapIcon className="size-3" />
|
||||
) : context.mode === "thinking" ? (
|
||||
<LightbulbIcon className="size-3" />
|
||||
) : context.mode === "pro" ? (
|
||||
<GraduationCapIcon className="size-3" />
|
||||
) : context.mode === "ultra" ? (
|
||||
<RocketIcon className="size-3 text-[#dabb5e]" />
|
||||
) : null}
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
"text-xs font-normal",
|
||||
context.mode === "ultra" ? "golden-text" : "",
|
||||
)}
|
||||
>
|
||||
{(context.mode === "flash" && t.inputBox.flashMode) ||
|
||||
(context.mode === "thinking" &&
|
||||
t.inputBox.reasoningMode) ||
|
||||
(context.mode === "pro" && t.inputBox.proMode) ||
|
||||
(context.mode === "ultra" && t.inputBox.ultraMode)}
|
||||
</div>
|
||||
{selectedSingleRoundRag
|
||||
? "单轮 RAG"
|
||||
: (context.mode === "flash" && t.inputBox.flashMode) ||
|
||||
(context.mode === "thinking" &&
|
||||
t.inputBox.reasoningMode) ||
|
||||
(context.mode === "pro" && t.inputBox.proMode) ||
|
||||
(context.mode === "ultra" && t.inputBox.ultraMode)}
|
||||
</div>
|
||||
</PromptInputActionMenuTrigger>
|
||||
</ModeHoverGuide>
|
||||
<PromptInputActionMenuContent className="w-80">
|
||||
@@ -838,11 +893,11 @@ export function InputBox({
|
||||
{t.inputBox.mode}
|
||||
</DropdownMenuLabel>
|
||||
<PromptInputActionMenu>
|
||||
<PromptInputActionMenuItem
|
||||
className={cn(
|
||||
context.mode === "flash"
|
||||
? "text-accent-foreground"
|
||||
: "text-muted-foreground/65",
|
||||
<PromptInputActionMenuItem
|
||||
className={cn(
|
||||
!selectedSingleRoundRag && context.mode === "flash"
|
||||
? "text-accent-foreground"
|
||||
: "text-muted-foreground/65",
|
||||
)}
|
||||
onSelect={() => handleModeSelect("flash")}
|
||||
>
|
||||
@@ -850,9 +905,9 @@ export function InputBox({
|
||||
<div className="flex items-center gap-1 font-bold">
|
||||
<ZapIcon
|
||||
className={cn(
|
||||
"mr-2 size-4",
|
||||
context.mode === "flash" &&
|
||||
"text-accent-foreground",
|
||||
"mr-2 size-4",
|
||||
!selectedSingleRoundRag && context.mode === "flash" &&
|
||||
"text-accent-foreground",
|
||||
)}
|
||||
/>
|
||||
{t.inputBox.flashMode}
|
||||
@@ -861,7 +916,7 @@ export function InputBox({
|
||||
{t.inputBox.flashModeDescription}
|
||||
</div>
|
||||
</div>
|
||||
{context.mode === "flash" ? (
|
||||
{!selectedSingleRoundRag && context.mode === "flash" ? (
|
||||
<CheckIcon className="ml-auto size-4" />
|
||||
) : (
|
||||
<div className="ml-auto size-4" />
|
||||
@@ -869,9 +924,9 @@ export function InputBox({
|
||||
</PromptInputActionMenuItem>
|
||||
{supportThinking && (
|
||||
<PromptInputActionMenuItem
|
||||
className={cn(
|
||||
context.mode === "thinking"
|
||||
? "text-accent-foreground"
|
||||
className={cn(
|
||||
!selectedSingleRoundRag && context.mode === "thinking"
|
||||
? "text-accent-foreground"
|
||||
: "text-muted-foreground/65",
|
||||
)}
|
||||
onSelect={() => handleModeSelect("thinking")}
|
||||
@@ -880,9 +935,9 @@ export function InputBox({
|
||||
<div className="flex items-center gap-1 font-bold">
|
||||
<LightbulbIcon
|
||||
className={cn(
|
||||
"mr-2 size-4",
|
||||
context.mode === "thinking" &&
|
||||
"text-accent-foreground",
|
||||
"mr-2 size-4",
|
||||
!selectedSingleRoundRag && context.mode === "thinking" &&
|
||||
"text-accent-foreground",
|
||||
)}
|
||||
/>
|
||||
{t.inputBox.reasoningMode}
|
||||
@@ -891,7 +946,7 @@ export function InputBox({
|
||||
{t.inputBox.reasoningModeDescription}
|
||||
</div>
|
||||
</div>
|
||||
{context.mode === "thinking" ? (
|
||||
{!selectedSingleRoundRag && context.mode === "thinking" ? (
|
||||
<CheckIcon className="ml-auto size-4" />
|
||||
) : (
|
||||
<div className="ml-auto size-4" />
|
||||
@@ -899,8 +954,8 @@ export function InputBox({
|
||||
</PromptInputActionMenuItem>
|
||||
)}
|
||||
<PromptInputActionMenuItem
|
||||
className={cn(
|
||||
context.mode === "pro"
|
||||
className={cn(
|
||||
!selectedSingleRoundRag && context.mode === "pro"
|
||||
? "text-accent-foreground"
|
||||
: "text-muted-foreground/65",
|
||||
)}
|
||||
@@ -910,8 +965,8 @@ export function InputBox({
|
||||
<div className="flex items-center gap-1 font-bold">
|
||||
<GraduationCapIcon
|
||||
className={cn(
|
||||
"mr-2 size-4",
|
||||
context.mode === "pro" &&
|
||||
"mr-2 size-4",
|
||||
!selectedSingleRoundRag && context.mode === "pro" &&
|
||||
"text-accent-foreground",
|
||||
)}
|
||||
/>
|
||||
@@ -921,15 +976,15 @@ export function InputBox({
|
||||
{t.inputBox.proModeDescription}
|
||||
</div>
|
||||
</div>
|
||||
{context.mode === "pro" ? (
|
||||
{!selectedSingleRoundRag && context.mode === "pro" ? (
|
||||
<CheckIcon className="ml-auto size-4" />
|
||||
) : (
|
||||
<div className="ml-auto size-4" />
|
||||
)}
|
||||
</PromptInputActionMenuItem>
|
||||
<PromptInputActionMenuItem
|
||||
className={cn(
|
||||
context.mode === "ultra"
|
||||
className={cn(
|
||||
!selectedSingleRoundRag && context.mode === "ultra"
|
||||
? "text-accent-foreground"
|
||||
: "text-muted-foreground/65",
|
||||
)}
|
||||
@@ -939,13 +994,17 @@ export function InputBox({
|
||||
<div className="flex items-center gap-1 font-bold">
|
||||
<RocketIcon
|
||||
className={cn(
|
||||
"mr-2 size-4",
|
||||
context.mode === "ultra" && "text-[#dabb5e]",
|
||||
"mr-2 size-4",
|
||||
!selectedSingleRoundRag &&
|
||||
context.mode === "ultra" &&
|
||||
"text-[#dabb5e]",
|
||||
)}
|
||||
/>
|
||||
<div
|
||||
className={cn(
|
||||
context.mode === "ultra" && "golden-text",
|
||||
!selectedSingleRoundRag &&
|
||||
context.mode === "ultra" &&
|
||||
"golden-text",
|
||||
)}
|
||||
>
|
||||
{t.inputBox.ultraMode}
|
||||
@@ -955,13 +1014,46 @@ export function InputBox({
|
||||
{t.inputBox.ultraModeDescription}
|
||||
</div>
|
||||
</div>
|
||||
{context.mode === "ultra" ? (
|
||||
{!selectedSingleRoundRag && context.mode === "ultra" ? (
|
||||
<CheckIcon className="ml-auto size-4" />
|
||||
) : (
|
||||
<div className="ml-auto size-4" />
|
||||
)}
|
||||
</PromptInputActionMenuItem>
|
||||
</PromptInputActionMenu>
|
||||
</PromptInputActionMenuItem>
|
||||
{extraModels.length > 0 && (
|
||||
<>
|
||||
<DropdownMenuSeparator className="my-2" />
|
||||
<PromptInputActionMenuItem
|
||||
className={cn(
|
||||
selectedSingleRoundRag
|
||||
? "bg-emerald-50 text-emerald-800 hover:bg-emerald-100 focus:bg-emerald-100 dark:bg-emerald-950/40 dark:text-emerald-200 dark:hover:bg-emerald-950/60 dark:focus:bg-emerald-950/60"
|
||||
: "text-muted-foreground/65",
|
||||
)}
|
||||
onSelect={handleSingleRoundRagSelect}
|
||||
>
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex items-center gap-1 font-bold">
|
||||
<BookMarkedIcon
|
||||
className={cn(
|
||||
"mr-2 size-4",
|
||||
selectedSingleRoundRag && "text-emerald-700 dark:text-emerald-200",
|
||||
)}
|
||||
/>
|
||||
单轮 RAG 问答
|
||||
</div>
|
||||
<div className="pl-7 text-xs">
|
||||
基于知识库检索生成答案,并展示思考内容与参考资料
|
||||
</div>
|
||||
</div>
|
||||
{selectedSingleRoundRag ? (
|
||||
<CheckIcon className="ml-auto size-4" />
|
||||
) : (
|
||||
<div className="ml-auto size-4" />
|
||||
)}
|
||||
</PromptInputActionMenuItem>
|
||||
</>
|
||||
)}
|
||||
</PromptInputActionMenu>
|
||||
</DropdownMenuGroup>
|
||||
</PromptInputActionMenuContent>
|
||||
</PromptInputActionMenu>
|
||||
@@ -1146,7 +1238,7 @@ export function InputBox({
|
||||
<ModelSelectorContent>
|
||||
<ModelSelectorInput placeholder={t.inputBox.searchModels} />
|
||||
<ModelSelectorList>
|
||||
{models.map((m) => (
|
||||
{modelOptions.map((m) => (
|
||||
<ModelSelectorItem
|
||||
key={m.name}
|
||||
value={m.name}
|
||||
@@ -1154,9 +1246,11 @@ export function InputBox({
|
||||
>
|
||||
<div className="flex min-w-0 flex-1 flex-col">
|
||||
<ModelSelectorName>{m.display_name}</ModelSelectorName>
|
||||
<span className="text-muted-foreground truncate text-[10px]">
|
||||
{m.model}
|
||||
</span>
|
||||
<span className="text-muted-foreground truncate text-[10px]">
|
||||
{selectedSingleRoundRag
|
||||
? `单轮知识库问答 · ${m.name}`
|
||||
: m.model}
|
||||
</span>
|
||||
</div>
|
||||
{m.name === context.model_name ? (
|
||||
<CheckIcon className="ml-auto size-4" />
|
||||
@@ -1164,8 +1258,8 @@ export function InputBox({
|
||||
<div className="ml-auto size-4" />
|
||||
)}
|
||||
</ModelSelectorItem>
|
||||
))}
|
||||
</ModelSelectorList>
|
||||
))}
|
||||
</ModelSelectorList>
|
||||
</ModelSelectorContent>
|
||||
</ModelSelector>
|
||||
<PromptInputSubmit
|
||||
|
||||
@@ -33,7 +33,8 @@ import {
|
||||
} from "@/core/skill-display/runtime";
|
||||
import type { Subtask } from "@/core/tasks";
|
||||
import { useUpdateSubtask } from "@/core/tasks/context";
|
||||
import type { AgentThreadState } from "@/core/threads";
|
||||
import type { AgentThreadState } from "@/core/threads";
|
||||
import { isSingleRoundRagMessage } from "@/core/threads/use-single-round-rag";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { resolveAllowMultiple } from "@/roundtable-planning/lib/clarification";
|
||||
|
||||
@@ -235,12 +236,17 @@ export function MessageList({
|
||||
}, [messages, askTimes]);
|
||||
|
||||
const [settings] = useLocalSettings();
|
||||
const ragModeEnabled =
|
||||
settings.display.ragModeEnabled || isThreadRagModeLocked(threadId);
|
||||
const { skills } = useSkills();
|
||||
const skillDisplayMap = useMemo(
|
||||
() => (ragModeEnabled ? buildSkillDisplayMap(skills) : new Map()),
|
||||
[ragModeEnabled, skills],
|
||||
const ragModeEnabled =
|
||||
settings.display.ragModeEnabled || isThreadRagModeLocked(threadId);
|
||||
const hasSingleRoundRag = useMemo(
|
||||
() => messages.some(isSingleRoundRagMessage),
|
||||
[messages],
|
||||
);
|
||||
const referencesEnabled = ragModeEnabled || hasSingleRoundRag;
|
||||
const { skills } = useSkills();
|
||||
const skillDisplayMap = useMemo(
|
||||
() => (referencesEnabled ? buildSkillDisplayMap(skills) : new Map()),
|
||||
[referencesEnabled, skills],
|
||||
);
|
||||
// Same per-turn reference batches the right-side panel renders (backend
|
||||
// batches preferred). Inline [n] tokens must resolve against these so badge
|
||||
@@ -373,7 +379,7 @@ export function MessageList({
|
||||
if (group.type === "human" || group.type === "assistant") {
|
||||
return group.messages.map((msg) => {
|
||||
const isAssistantMessage =
|
||||
ragModeEnabled &&
|
||||
referencesEnabled &&
|
||||
group.type === "assistant" &&
|
||||
msg.type === "ai";
|
||||
const batchSources = isAssistantMessage
|
||||
|
||||
@@ -46,20 +46,23 @@ function getModeDescriptionKey(
|
||||
}
|
||||
}
|
||||
|
||||
export function ModeHoverGuide({
|
||||
mode,
|
||||
children,
|
||||
showTitle = true,
|
||||
}: {
|
||||
mode: AgentMode;
|
||||
children: React.ReactNode;
|
||||
/** When true, tooltip shows "ModeName: Description". When false, only description. */
|
||||
showTitle?: boolean;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const label = t.inputBox[getModeLabelKey(mode)];
|
||||
const description = t.inputBox[getModeDescriptionKey(mode)];
|
||||
const content = showTitle ? `${label}: ${description}` : description;
|
||||
export function ModeHoverGuide({
|
||||
mode,
|
||||
children,
|
||||
showTitle = true,
|
||||
tooltipContent,
|
||||
}: {
|
||||
mode: AgentMode;
|
||||
children: React.ReactNode;
|
||||
/** When true, tooltip shows "ModeName: Description". When false, only description. */
|
||||
showTitle?: boolean;
|
||||
/** Overrides the standard mode tooltip for page-specific execution modes. */
|
||||
tooltipContent?: string;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const label = t.inputBox[getModeLabelKey(mode)];
|
||||
const description = t.inputBox[getModeDescriptionKey(mode)];
|
||||
const content = tooltipContent ?? (showTitle ? `${label}: ${description}` : description);
|
||||
|
||||
return <Tooltip content={content}>{children}</Tooltip>;
|
||||
}
|
||||
@@ -184,7 +184,7 @@ export function WorkspaceNavChatList({
|
||||
</Link>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
<SidebarMenuItem>
|
||||
{/* <SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
isActive={pathname.startsWith("/page/workspace/roundtable/position")}
|
||||
asChild
|
||||
@@ -195,7 +195,7 @@ export function WorkspaceNavChatList({
|
||||
<span>岗位会商</span>
|
||||
</Link>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenuItem> */}
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
isActive={pathname === "/page/workspace/scheduled/tasks"}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { Model } from "./types";
|
||||
|
||||
export const SINGLE_ROUND_RAG_MODELS: Model[] = [
|
||||
{ id: "single-round-rag-openai3", name: "OpenAI3", model: "OpenAI3", display_name: "Qwen3-32B", supports_thinking: true, execution_profile: "single_round_rag" },
|
||||
{ id: "single-round-rag-openai4", name: "OpenAI4", model: "OpenAI4", display_name: "Qwen3-235B", supports_thinking: true, execution_profile: "single_round_rag" },
|
||||
{ id: "single-round-rag-openai5", name: "OpenAI5", model: "OpenAI5", display_name: "GLM-5", supports_thinking: true, execution_profile: "single_round_rag" },
|
||||
{ id: "single-round-rag-openai6", name: "OpenAI6", model: "OpenAI6", display_name: "Qwen3.5-27B", supports_thinking: true, execution_profile: "single_round_rag" },
|
||||
{ id: "single-round-rag-openai7", name: "OpenAI7", model: "OpenAI7", display_name: "Qwen3-8B", supports_thinking: true, execution_profile: "single_round_rag" },
|
||||
{ id: "single-round-rag-openai9", name: "OpenAI9", model: "OpenAI9", display_name: "四季7B", supports_thinking: true, execution_profile: "single_round_rag" },
|
||||
];
|
||||
|
||||
export function isSingleRoundRagProfile(
|
||||
context: unknown,
|
||||
): boolean {
|
||||
return (
|
||||
typeof context === "object" &&
|
||||
context !== null &&
|
||||
(context as { execution_profile?: unknown }).execution_profile ===
|
||||
"single_round_rag"
|
||||
);
|
||||
}
|
||||
@@ -4,9 +4,11 @@ export interface Model {
|
||||
model: string;
|
||||
display_name: string;
|
||||
description?: string | null;
|
||||
supports_thinking?: boolean;
|
||||
supports_reasoning_effort?: boolean;
|
||||
}
|
||||
supports_thinking?: boolean;
|
||||
supports_reasoning_effort?: boolean;
|
||||
/** Execution profiles handled by the frontend instead of DeerFlow. */
|
||||
execution_profile?: "single_round_rag";
|
||||
}
|
||||
|
||||
export interface TokenUsageSettings {
|
||||
enabled: boolean;
|
||||
|
||||
@@ -23,9 +23,11 @@ export interface AgentThreadContext extends Record<string, unknown> {
|
||||
rag_mode_enabled?: boolean;
|
||||
/** Per-request switch for context compression (上下文压缩). Default off. */
|
||||
summarization_enabled?: boolean;
|
||||
/** Per-conversation switch for knowledge-base RAG injection (phase 2). */
|
||||
knowledge_rag_enabled?: boolean;
|
||||
agent_id?: string;
|
||||
/** Per-conversation switch for knowledge-base RAG injection (phase 2). */
|
||||
knowledge_rag_enabled?: boolean;
|
||||
/** Direct knowledge-base RAG mode; this request never enters Lead Agent. */
|
||||
execution_profile?: "single_round_rag";
|
||||
agent_id?: string;
|
||||
/** @deprecated kept for reading legacy thread metadata; prefer agent_id */
|
||||
agent_name?: string;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,378 @@
|
||||
import type { Message } from "@langchain/langgraph-sdk";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { readRuntimeEnv } from "@/env";
|
||||
|
||||
const STORAGE_PREFIX = "workspace.single-round-rag.";
|
||||
|
||||
type KnowledgeBaseChunk = {
|
||||
answer?: unknown;
|
||||
docs?: unknown;
|
||||
};
|
||||
|
||||
type RagSource = {
|
||||
id?: string;
|
||||
title: string;
|
||||
type: string;
|
||||
snippet: string;
|
||||
content: string;
|
||||
source?: string;
|
||||
time?: string;
|
||||
url?: string;
|
||||
raw: Record<string, unknown>;
|
||||
};
|
||||
|
||||
/** Same JSON-object framing used by the established GeneralQA single-RAG flow. */
|
||||
function extractJsonObjects(raw: string): { objects: string[]; rest: string } {
|
||||
const objects: string[] = [];
|
||||
let depth = 0;
|
||||
let stringQuote: '"' | "'" | null = null;
|
||||
let escaped = false;
|
||||
let start = -1;
|
||||
for (let index = 0; index < raw.length; index += 1) {
|
||||
const char = raw[index]!;
|
||||
if (stringQuote) {
|
||||
if (escaped) escaped = false;
|
||||
else if (char === "\\") escaped = true;
|
||||
else if (char === stringQuote) stringQuote = null;
|
||||
continue;
|
||||
}
|
||||
if (char === '"' || char === "'") {
|
||||
stringQuote = char;
|
||||
continue;
|
||||
}
|
||||
if (char === "{") {
|
||||
if (depth === 0) start = index;
|
||||
depth += 1;
|
||||
} else if (char === "}") {
|
||||
depth -= 1;
|
||||
if (depth === 0 && start !== -1) {
|
||||
objects.push(raw.slice(start, index + 1));
|
||||
start = -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return depth > 0 && start !== -1
|
||||
? { objects, rest: raw.slice(start) }
|
||||
: { objects, rest: "" };
|
||||
}
|
||||
|
||||
/** Same `<think>` split semantics as GeneralQA, kept local to avoid loading its demo data. */
|
||||
function parseSingleRagStream(chunks: { answer: string }[]) {
|
||||
let thinkingMarkdown = "";
|
||||
let answerMarkdown = "";
|
||||
let inThink = false;
|
||||
let thinkingComplete = false;
|
||||
for (const { answer } of chunks) {
|
||||
let remaining = answer;
|
||||
while (remaining) {
|
||||
if (inThink) {
|
||||
const endIndex = remaining.indexOf("</think>");
|
||||
if (endIndex === -1) {
|
||||
thinkingMarkdown += remaining;
|
||||
remaining = "";
|
||||
} else {
|
||||
thinkingMarkdown += remaining.slice(0, endIndex);
|
||||
remaining = remaining.slice(endIndex + "</think>".length);
|
||||
inThink = false;
|
||||
thinkingComplete = true;
|
||||
}
|
||||
} else {
|
||||
const startIndex = remaining.indexOf("<think>");
|
||||
if (startIndex === -1) {
|
||||
answerMarkdown += remaining;
|
||||
remaining = "";
|
||||
} else {
|
||||
answerMarkdown += remaining.slice(0, startIndex);
|
||||
remaining = remaining.slice(startIndex + "<think>".length);
|
||||
inThink = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return { thinkingMarkdown, answerMarkdown, thinkingComplete };
|
||||
}
|
||||
|
||||
function storageKey(threadId: string) {
|
||||
return `${STORAGE_PREFIX}${threadId}`;
|
||||
}
|
||||
|
||||
function readStoredMessages(threadId: string): Message[] {
|
||||
if (typeof window === "undefined" || !threadId) return [];
|
||||
try {
|
||||
const raw = window.sessionStorage.getItem(storageKey(threadId));
|
||||
const parsed: unknown = raw ? JSON.parse(raw) : [];
|
||||
return Array.isArray(parsed) ? (parsed as Message[]) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function writeStoredMessages(threadId: string, messages: Message[]) {
|
||||
if (typeof window === "undefined" || !threadId) return;
|
||||
try {
|
||||
window.sessionStorage.setItem(storageKey(threadId), JSON.stringify(messages));
|
||||
} catch {
|
||||
// Quota errors must never interrupt an already-running answer.
|
||||
}
|
||||
}
|
||||
|
||||
function parseLooseStringValue(rawValue: string): string {
|
||||
try {
|
||||
return JSON.parse(rawValue) as string;
|
||||
} catch {
|
||||
const value = rawValue.trim();
|
||||
if (value.startsWith("'") && value.endsWith("'")) {
|
||||
return value
|
||||
.slice(1, -1)
|
||||
.replace(/\\n/g, "\n")
|
||||
.replace(/\\r/g, "\r")
|
||||
.replace(/\\t/g, "\t")
|
||||
.replace(/\\'/g, "'")
|
||||
.replace(/\\\\/g, "\\");
|
||||
}
|
||||
throw new Error(`无法解析知识库流片段:${rawValue}`);
|
||||
}
|
||||
}
|
||||
|
||||
function parseKnowledgeBaseChunk(jsonText: string): KnowledgeBaseChunk {
|
||||
try {
|
||||
return JSON.parse(jsonText) as KnowledgeBaseChunk;
|
||||
} catch {
|
||||
const objectText = jsonText.trim();
|
||||
const answerMatch = objectText.match(/^\{\s*answer\s*:\s*([\s\S]*)\s*\}$/);
|
||||
if (answerMatch) {
|
||||
return { answer: parseLooseStringValue(answerMatch[1]!.trim()) };
|
||||
}
|
||||
const docsMatch = objectText.match(/^\{\s*docs\s*:\s*([\s\S]*)\s*\}$/);
|
||||
if (docsMatch) {
|
||||
const rawValue = docsMatch[1]!.trim();
|
||||
try {
|
||||
return { docs: JSON.parse(rawValue) };
|
||||
} catch {
|
||||
return { docs: parseLooseStringValue(rawValue) };
|
||||
}
|
||||
}
|
||||
const normalizedText = objectText.replace(
|
||||
/([{,]\s*)(answer|docs)(\s*:)/g,
|
||||
'$1"$2"$3',
|
||||
);
|
||||
return JSON.parse(normalizedText) as KnowledgeBaseChunk;
|
||||
}
|
||||
}
|
||||
|
||||
function flattenDocs(value: unknown): Record<string, unknown>[] {
|
||||
if (Array.isArray(value)) {
|
||||
return value.flatMap((item) => flattenDocs(item));
|
||||
}
|
||||
if (!value || typeof value !== "object") return [];
|
||||
const record = value as Record<string, unknown>;
|
||||
if ("docs" in record) return flattenDocs(record.docs);
|
||||
return [record];
|
||||
}
|
||||
|
||||
function normalizeSources(value: unknown): RagSource[] {
|
||||
return flattenDocs(value).map((item, index) => {
|
||||
const title = String(item.m_title ?? item.title ?? item.source ?? `参考资料 ${index + 1}`);
|
||||
const content = String(item.m_content ?? item.content ?? item.snippet ?? "");
|
||||
const source = item.source1 ?? item.source;
|
||||
const rawUrl = item.url ?? item.link ?? item.href;
|
||||
return {
|
||||
id: String(item.recUuid ?? item.rec_uuid ?? item.uuid ?? item.id ?? "") || undefined,
|
||||
title,
|
||||
type: String(item.source1 ?? item.type ?? "知识库"),
|
||||
snippet: content,
|
||||
content,
|
||||
source: typeof source === "string" ? source : undefined,
|
||||
time: typeof item.m_publish === "string" ? item.m_publish : undefined,
|
||||
url: typeof rawUrl === "string" && /^https?:\/\//i.test(rawUrl) ? rawUrl : undefined,
|
||||
raw: item,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function createId(prefix: string) {
|
||||
return `${prefix}-${crypto.randomUUID()}`;
|
||||
}
|
||||
|
||||
function isAbortError(error: unknown) {
|
||||
return error instanceof DOMException && error.name === "AbortError";
|
||||
}
|
||||
|
||||
export function isSingleRoundRagMessage(message: Message): boolean {
|
||||
return message.additional_kwargs?.single_round_rag === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Frontend-only adapter for the existing general-QA single-round endpoint.
|
||||
* It deliberately never submits a run to DeerFlow or mutates the Lead Agent.
|
||||
*/
|
||||
export function useSingleRoundRagMessages(threadId: string) {
|
||||
const [messages, setMessages] = useState<Message[]>(() => readStoredMessages(threadId));
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const controllerRef = useRef<AbortController | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setMessages(readStoredMessages(threadId));
|
||||
setError(null);
|
||||
}, [threadId]);
|
||||
|
||||
useEffect(() => () => controllerRef.current?.abort(), []);
|
||||
|
||||
const updateMessages = useCallback(
|
||||
(targetThreadId: string, updater: (current: Message[]) => Message[]) => {
|
||||
setMessages((current) => {
|
||||
const next = updater(current);
|
||||
writeStoredMessages(targetThreadId, next);
|
||||
return next;
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const stop = useCallback(() => controllerRef.current?.abort(), []);
|
||||
|
||||
const submit = useCallback(
|
||||
async ({
|
||||
targetThreadId,
|
||||
query,
|
||||
modelName,
|
||||
}: {
|
||||
targetThreadId: string;
|
||||
query: string;
|
||||
modelName: string;
|
||||
}) => {
|
||||
if (isLoading) return;
|
||||
const question = query.trim();
|
||||
if (!question) return;
|
||||
|
||||
const humanId = createId("single-rag-human");
|
||||
const assistantId = createId("single-rag-ai");
|
||||
const sourceId = createId("single-rag-sources");
|
||||
const clientTs = new Date().toISOString();
|
||||
const userMessage: Message = {
|
||||
id: humanId,
|
||||
type: "human",
|
||||
content: [{ type: "text", text: question }],
|
||||
additional_kwargs: { client_ts: clientTs, single_round_rag: true },
|
||||
};
|
||||
const initialAssistant: Message = {
|
||||
id: assistantId,
|
||||
type: "ai",
|
||||
content: "",
|
||||
additional_kwargs: { single_round_rag: true },
|
||||
};
|
||||
updateMessages(targetThreadId, (current) => [...current, userMessage, initialAssistant]);
|
||||
setError(null);
|
||||
setIsLoading(true);
|
||||
|
||||
const controller = new AbortController();
|
||||
controllerRef.current = controller;
|
||||
const answerChunks: { answer: string }[] = [];
|
||||
let sources: RagSource[] = [];
|
||||
|
||||
const refreshAssistant = () => {
|
||||
const trace = parseSingleRagStream(answerChunks);
|
||||
updateMessages(targetThreadId, (current) => {
|
||||
const next = current.filter((message) => message.id !== sourceId);
|
||||
const assistantIndex = next.findIndex((message) => message.id === assistantId);
|
||||
if (assistantIndex < 0) return current;
|
||||
next[assistantIndex] = {
|
||||
...next[assistantIndex],
|
||||
content: trace.answerMarkdown,
|
||||
additional_kwargs: {
|
||||
...next[assistantIndex]!.additional_kwargs,
|
||||
single_round_rag: true,
|
||||
reasoning_content: trace.thinkingMarkdown || null,
|
||||
},
|
||||
} as Message;
|
||||
if (sources.length > 0) {
|
||||
next.splice(assistantIndex, 0, {
|
||||
id: sourceId,
|
||||
type: "tool",
|
||||
name: "knowledge_base_search",
|
||||
content: { results: sources },
|
||||
additional_kwargs: {
|
||||
hide_from_ui: true,
|
||||
single_round_rag: true,
|
||||
},
|
||||
} as unknown as Message);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
try {
|
||||
const chatUrl = readRuntimeEnv("VITE_AIPI_CHAT_URL") || "";
|
||||
if (!chatUrl) {
|
||||
throw new Error("未配置 VITE_AIPI_CHAT_URL,无法发起单轮 RAG 问答。");
|
||||
}
|
||||
const response = await fetch(
|
||||
`${chatUrl.replace(/\/$/, "")}/chat/knowledge_base_chat_tiaoshi`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
signal: controller.signal,
|
||||
body: JSON.stringify({
|
||||
query: question,
|
||||
knowledge_base_name: [],
|
||||
top_k: 5,
|
||||
score_threshold: 0.5,
|
||||
history: [],
|
||||
stream: true,
|
||||
model_name: modelName,
|
||||
temperature: 0.3,
|
||||
prompt_name: "default",
|
||||
local_doc_url: false,
|
||||
}),
|
||||
},
|
||||
);
|
||||
if (!response.ok) throw new Error(`知识库服务请求失败(${response.status})`);
|
||||
if (!response.body) throw new Error("知识库服务未返回流式响应。");
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = "";
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
const extracted = extractJsonObjects(buffer);
|
||||
buffer = extracted.rest;
|
||||
for (const jsonText of extracted.objects) {
|
||||
const chunk = parseKnowledgeBaseChunk(jsonText);
|
||||
if (typeof chunk.answer === "string") answerChunks.push({ answer: chunk.answer });
|
||||
if (chunk.docs !== undefined) sources = normalizeSources(chunk.docs);
|
||||
refreshAssistant();
|
||||
}
|
||||
}
|
||||
} catch (caught) {
|
||||
if (!isAbortError(caught)) {
|
||||
const message = caught instanceof Error ? caught.message : "单轮 RAG 问答失败。";
|
||||
setError(message);
|
||||
updateMessages(targetThreadId, (current) =>
|
||||
current.map((item) =>
|
||||
item.id === assistantId
|
||||
? ({
|
||||
...item,
|
||||
content: answerChunks.length > 0 ? item.content : message,
|
||||
additional_kwargs: {
|
||||
...item.additional_kwargs,
|
||||
single_round_rag: true,
|
||||
},
|
||||
} as Message)
|
||||
: item,
|
||||
),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (controllerRef.current === controller) controllerRef.current = null;
|
||||
setIsLoading(false);
|
||||
}
|
||||
},
|
||||
[isLoading, updateMessages],
|
||||
);
|
||||
|
||||
return { messages, isLoading, error, submit, stop };
|
||||
}
|
||||
@@ -44,6 +44,10 @@ import { PanelLeftOpen } from "lucide-react";
|
||||
import { useAgentSelector, useAgentsPaginated } from "@/core/agents";
|
||||
import { useI18n } from "@/core/i18n/hooks";
|
||||
import { useModels } from "@/core/models/hooks";
|
||||
import {
|
||||
isSingleRoundRagProfile,
|
||||
SINGLE_ROUND_RAG_MODELS,
|
||||
} from "@/core/models/single-round-rag";
|
||||
import { useNotification } from "@/core/notification/hooks";
|
||||
import {
|
||||
getLastAgentId,
|
||||
@@ -52,6 +56,7 @@ import {
|
||||
useThreadSettings,
|
||||
} from "@/core/settings";
|
||||
import { useThreadStream } from "@/core/threads/hooks";
|
||||
import { useSingleRoundRagMessages } from "@/core/threads/use-single-round-rag";
|
||||
import { useLayoutMode } from "@/core/system-settings/hooks";
|
||||
import { useRouteBase } from "@/core/route-base";
|
||||
import { textOfMessage } from "@/core/threads/utils";
|
||||
@@ -226,6 +231,20 @@ export default function ChatPage() {
|
||||
}
|
||||
},
|
||||
});
|
||||
const singleRoundRag = useSingleRoundRagMessages(threadId);
|
||||
const singleRoundRagSelected = isSingleRoundRagProfile(settings.context);
|
||||
const displayThread = useMemo(() => {
|
||||
if (singleRoundRag.messages.length === 0 && !singleRoundRag.isLoading) {
|
||||
return thread;
|
||||
}
|
||||
const messages = [...thread.messages, ...singleRoundRag.messages];
|
||||
return {
|
||||
...thread,
|
||||
values: { ...thread.values, messages },
|
||||
messages,
|
||||
isLoading: thread.isLoading || singleRoundRag.isLoading,
|
||||
} as typeof thread;
|
||||
}, [singleRoundRag.isLoading, singleRoundRag.messages, thread]);
|
||||
|
||||
const writingArtifactPath = useMemo(() => {
|
||||
const isMarkdown = (path: string | null | undefined) =>
|
||||
@@ -240,6 +259,46 @@ export default function ChatPage() {
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
(message: PromptInputMessage) => {
|
||||
if (singleRoundRagSelected) {
|
||||
if (message.files && message.files.length > 0) {
|
||||
toast.error("单轮 RAG 问答暂不支持附件,请移除附件后重试。");
|
||||
return;
|
||||
}
|
||||
setHasStartedConversation(true);
|
||||
window.dispatchEvent(
|
||||
new CustomEvent("workspace:sandbox-resume-autoscroll"),
|
||||
);
|
||||
void (async () => {
|
||||
try {
|
||||
let targetThreadId = threadId;
|
||||
if (isNewThread) {
|
||||
const created = await getAPIClient(isMock).threads.create({});
|
||||
targetThreadId = created.thread_id;
|
||||
setThreadId(targetThreadId);
|
||||
setIsNewThread(false);
|
||||
history.replaceState(
|
||||
null,
|
||||
"",
|
||||
`${window.location.pathname}${window.location.search}#${routeBase}/chats/${targetThreadId}`,
|
||||
);
|
||||
const title = message.text.trim().replace(/\s+/g, " ").slice(0, 60);
|
||||
if (title) {
|
||||
void getAPIClient(isMock).threads
|
||||
.updateState(targetThreadId, { values: { title } })
|
||||
.catch(() => undefined);
|
||||
}
|
||||
}
|
||||
await singleRoundRag.submit({
|
||||
targetThreadId,
|
||||
query: message.text,
|
||||
modelName: settings.context.model_name ?? "OpenAI3",
|
||||
});
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : "单轮 RAG 问答失败。");
|
||||
}
|
||||
})();
|
||||
return;
|
||||
}
|
||||
// If the user picked an agent before sending the opening turn, hand off
|
||||
// to AgentChatPage so the conversation runs against that agent. We stash
|
||||
// the pending text in sessionStorage because the next/navigation shim
|
||||
@@ -332,7 +391,13 @@ export default function ChatPage() {
|
||||
isMock,
|
||||
router,
|
||||
settings.context.writing_mode,
|
||||
settings.context.model_name,
|
||||
writingArtifactPath,
|
||||
singleRoundRag,
|
||||
singleRoundRagSelected,
|
||||
routeBase,
|
||||
setIsNewThread,
|
||||
setThreadId,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -421,8 +486,12 @@ export default function ChatPage() {
|
||||
saveLastAgentId(agentId);
|
||||
}, []);
|
||||
const handleStop = useCallback(async () => {
|
||||
if (singleRoundRag.isLoading) {
|
||||
singleRoundRag.stop();
|
||||
return;
|
||||
}
|
||||
await thread.stop();
|
||||
}, [thread]);
|
||||
}, [singleRoundRag, thread]);
|
||||
|
||||
const promptPrefixProp = useMemo(() => {
|
||||
if (!promptPrefixSettings?.enabled) return undefined;
|
||||
@@ -468,7 +537,7 @@ export default function ChatPage() {
|
||||
const compactActionsHidden = isHideChromeActive();
|
||||
|
||||
return (
|
||||
<ThreadContext.Provider value={{ thread, isMock }}>
|
||||
<ThreadContext.Provider value={{ thread: displayThread, isMock }}>
|
||||
<ChatBox threadId={threadId}>
|
||||
<div
|
||||
className={cn(
|
||||
@@ -486,7 +555,7 @@ export default function ChatPage() {
|
||||
)}
|
||||
>
|
||||
<div className="flex w-full items-center text-sm font-medium">
|
||||
<ThreadTitle threadId={threadId} thread={thread} />
|
||||
<ThreadTitle threadId={threadId} thread={displayThread} />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{/* 仅在收起态显示「展开历史」钮;展开后由侧栏内(新对话右侧)的收起钮负责收起。 */}
|
||||
@@ -505,7 +574,7 @@ export default function ChatPage() {
|
||||
)}
|
||||
<TokenUsageIndicator
|
||||
enabled={tokenUsageEnabled}
|
||||
messages={thread.messages}
|
||||
messages={displayThread.messages}
|
||||
/>
|
||||
<ExportTrigger threadId={threadId} />
|
||||
<KnowledgeSaveTrigger threadId={threadId} />
|
||||
@@ -543,7 +612,7 @@ export default function ChatPage() {
|
||||
<MessageList
|
||||
className={cn("size-full", "pt-10")}
|
||||
threadId={threadId}
|
||||
thread={thread}
|
||||
thread={displayThread}
|
||||
paddingBottom={messageListPaddingBottom}
|
||||
tokenUsageEnabled={tokenUsageEnabled}
|
||||
// 输入框为底部绝对浮层(约 160px 高),按钮上移到其上方居中。
|
||||
@@ -585,9 +654,9 @@ export default function ChatPage() {
|
||||
<div className="absolute right-0 bottom-0 left-0">
|
||||
<TodoList
|
||||
className="bg-background/5"
|
||||
todos={thread.values.todos ?? []}
|
||||
todos={displayThread.values.todos ?? []}
|
||||
hidden={
|
||||
!thread.values.todos || thread.values.todos.length === 0
|
||||
!displayThread.values.todos || displayThread.values.todos.length === 0
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
@@ -612,15 +681,17 @@ export default function ChatPage() {
|
||||
status={
|
||||
thread.error
|
||||
? "error"
|
||||
: thread.isLoading
|
||||
: displayThread.isLoading
|
||||
? "streaming"
|
||||
: "ready"
|
||||
}
|
||||
context={settings.context}
|
||||
extraModels={SINGLE_ROUND_RAG_MODELS}
|
||||
disabled={
|
||||
env.NEXT_PUBLIC_STATIC_WEBSITE_ONLY === "true" ||
|
||||
isUploading ||
|
||||
agentHandoffPending
|
||||
agentHandoffPending ||
|
||||
singleRoundRag.isLoading
|
||||
}
|
||||
onContextChange={(context) =>
|
||||
setSettings("context", context)
|
||||
@@ -664,7 +735,7 @@ export default function ChatPage() {
|
||||
*/}
|
||||
{!isLandingState && (
|
||||
<QuestionNavigator
|
||||
messages={thread.messages}
|
||||
messages={displayThread.messages}
|
||||
className="top-16 right-0 bottom-48 left-0"
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -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=<taskId>`;策略页入口也兼容 `/#/page/strategy/qa/position-roundtable?taskId=<taskId>`。不要使用任务标题、序号或每次请求都变化的临时 ID。
|
||||
2. 前端先调用 `GET /api/position-roundtable/sessions?external_task_id=<taskId>`;返回的是该任务下所有用户共享的会商记录,按最近更新时间排序。选中一条后再调用 `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 | 页面岗位 | 职责 |
|
||||
@@ -109,6 +121,31 @@ PositionRoundtablePage
|
||||
|
||||
后端会冻结链条快照并根据链条阶段创建节点。已启动后意图不可再修改;需要重新识别时必须新建会话。
|
||||
|
||||
The position workspace selects the dedicated built-in `position-roundtable-intent`
|
||||
agent by sending `intent_agent_id` through the shared Step-1 init and stream
|
||||
requests. The thread lifecycle, file upload, and SSE transport stay identical
|
||||
to the generic multi-agent flow. The dedicated agent permits at most five
|
||||
user-assistance rounds; one round may contain multiple independent
|
||||
`ask_clarification` cards. `Step1Panel` renders every card separately and
|
||||
submits the selected answers together, so cards must never be merged into one
|
||||
numbered multi-question card. Only its final `[INTENT_READY]` schema changes to
|
||||
the following four string arrays:
|
||||
|
||||
```json
|
||||
{
|
||||
"coreGoals": ["..."],
|
||||
"riskWarnings": ["..."],
|
||||
"keyPoints": ["..."],
|
||||
"strategicSignificance": ["..."]
|
||||
}
|
||||
```
|
||||
|
||||
The position sidebar and edit dialog render these four fields. Business-chain
|
||||
activation requires all four arrays and at least one core goal or strategic
|
||||
significance. Historic `objective` / `constraints` / `assumptions` snapshots
|
||||
are read through a compatibility mapping only; ordinary multi-agent Step 1 is
|
||||
not changed.
|
||||
|
||||
### 4.2 普通节点问答
|
||||
|
||||
`PositionNodeChat` 在发送前调用 `getPositionNodeContext` 获取受长度控制的任务、意图和已交付上游内容,再以 `task_external_context` 作为隐藏上下文发送给当前智能体。
|
||||
@@ -132,8 +169,9 @@ PositionRoundtablePage
|
||||
|
||||
页面只维护一个 `sandboxArtifact`。`PositionNodeChat` 和 `PositionBuiltinAgentChat` 通过 `onPreviewArtifact` 上报预览目标;父页面统一渲染 `ArtifactFileDetail`。
|
||||
|
||||
**对接 / 重做页面 / 排障指南(接口约定、必守规则、自测与症状表):**
|
||||
[`docs/沙箱打开关闭与步骤条.md`](./docs/沙箱打开关闭与步骤条.md)
|
||||
**对接 / 重做页面 / 排障指南(打开关闭时机、步骤条、接口约定):**
|
||||
[`../../docs/position-roundtable-sandbox/沙箱打开关闭与步骤条.md`](../../docs/position-roundtable-sandbox/沙箱打开关闭与步骤条.md)
|
||||
(目录说明见 [`../../docs/position-roundtable-sandbox/README.md`](../../docs/position-roundtable-sandbox/README.md))
|
||||
|
||||
设计要点:
|
||||
|
||||
@@ -163,8 +201,8 @@ PositionRoundtablePage
|
||||
|
||||
| 方法 | 路径 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| `GET` | `/sessions?external_task_id=` | 按任务查询会话,用于恢复最近会话和历史记录。 |
|
||||
| `POST` | `/sessions` | 创建初始会话并保存任务快照。 |
|
||||
| `GET` | `/sessions?external_task_id=<taskId>` | 传入时按任务作用域查询共享会话;不传参数时查询当前用户的个人历史。 |
|
||||
| `POST` | `/sessions` | 创建会话并保存任务快照;传入非空 `external_task_id` 时服务端会将快照 ID 固定为该值并启用共享;缺失或空值时创建原有个人会话。 |
|
||||
| `GET` | `/sessions/{id}` | 恢复会话、节点和冻结快照。 |
|
||||
| `DELETE` | `/sessions/{id}` | 删除一条岗位会商历史及其节点;删除当前记录时前端会先屏蔽并发恢复请求。 |
|
||||
| `PUT` | `/sessions/{id}/task` | 更新未冻结的任务快照。 |
|
||||
@@ -178,7 +216,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`。
|
||||
|
||||
|
||||
@@ -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<string, unknown>;
|
||||
chainId: string | null;
|
||||
chainSnapshot: Record<string, unknown> | null;
|
||||
@@ -112,6 +115,7 @@ interface ServerNode {
|
||||
interface ServerSession {
|
||||
id: string;
|
||||
external_task_id: string | null;
|
||||
task_scoped?: boolean;
|
||||
task_snapshot?: Record<string, unknown>;
|
||||
chain_id: string | null;
|
||||
chain_snapshot?: Record<string, unknown> | 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,
|
||||
|
||||
@@ -31,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<string, unknown> | null | undefined,
|
||||
fallback: PositionTask,
|
||||
taskScopeId?: string,
|
||||
): PositionTask {
|
||||
if (!snapshot || Object.keys(snapshot).length === 0) return fallback;
|
||||
const value = (keys: string[], defaultValue: string) => {
|
||||
@@ -50,7 +55,11 @@ 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),
|
||||
|
||||
@@ -111,7 +111,11 @@ import {
|
||||
type InteractiveMessage,
|
||||
type TimelineEntry,
|
||||
} from "@/roundtable-planning/hooks/useStep1Intent";
|
||||
import { INTENT_AGENT_ID, type IntentSummary } from "@/roundtable-planning/api/intent";
|
||||
import {
|
||||
POSITION_INTENT_AGENT_ID,
|
||||
type IntentSummary,
|
||||
type PositionIntentSummary,
|
||||
} from "@/roundtable-planning/api/intent";
|
||||
import type { BusinessChain } from "@/roundtable-planning/lib/business-chain";
|
||||
import { getAvatarTypeFor } from "@/roundtable-planning/lib/roundtable-constants";
|
||||
import {
|
||||
@@ -140,6 +144,7 @@ import {
|
||||
getPositionSession,
|
||||
isPositionSessionNotFoundError,
|
||||
listPositionSessions,
|
||||
PositionSessionNotFoundError,
|
||||
preparePositionActionPlan,
|
||||
preparePositionSummary,
|
||||
rejectPositionNode,
|
||||
@@ -182,11 +187,24 @@ 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;
|
||||
constraints: string;
|
||||
assumptions: string;
|
||||
coreGoals: string;
|
||||
riskWarnings: string;
|
||||
keyPoints: string;
|
||||
strategicSignificance: string;
|
||||
};
|
||||
type SandboxThreadSnapshot = {
|
||||
threadId: string;
|
||||
@@ -669,16 +687,38 @@ function mergePositionSession(
|
||||
return { ...current, ...next, nodes: current.nodes };
|
||||
}
|
||||
|
||||
function parseIntentSummary(snapshot: Record<string, unknown> | null | undefined): IntentSummary | null {
|
||||
if (!snapshot || typeof snapshot.objective !== "string" || !Array.isArray(snapshot.constraints)) {
|
||||
function intentStringList(snapshot: Record<string, unknown>, key: string): string[] {
|
||||
const value = snapshot[key];
|
||||
return Array.isArray(value)
|
||||
? value.filter((item): item is string => typeof item === "string" && Boolean(item.trim()))
|
||||
: [];
|
||||
}
|
||||
|
||||
function parsePositionIntentSummary(
|
||||
snapshot: Record<string, unknown> | null | undefined,
|
||||
): PositionIntentSummary | null {
|
||||
if (!snapshot) return null;
|
||||
const positionKeys = ["coreGoals", "riskWarnings", "keyPoints", "strategicSignificance"];
|
||||
if (positionKeys.some((key) => key in snapshot)) {
|
||||
if (!positionKeys.every((key) => Array.isArray(snapshot[key]))) return null;
|
||||
return {
|
||||
coreGoals: intentStringList(snapshot, "coreGoals"),
|
||||
riskWarnings: intentStringList(snapshot, "riskWarnings"),
|
||||
keyPoints: intentStringList(snapshot, "keyPoints"),
|
||||
strategicSignificance: intentStringList(snapshot, "strategicSignificance"),
|
||||
};
|
||||
}
|
||||
|
||||
// Existing sessions created before the dedicated position agent used the
|
||||
// shared Step-1 schema. Keep them readable and editable after the switch.
|
||||
if (typeof snapshot.objective !== "string" || !Array.isArray(snapshot.constraints)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
objective: snapshot.objective,
|
||||
constraints: snapshot.constraints.filter((item): item is string => typeof item === "string"),
|
||||
assumptions: Array.isArray(snapshot.assumptions)
|
||||
? snapshot.assumptions.filter((item): item is string => typeof item === "string")
|
||||
: undefined,
|
||||
coreGoals: intentStringList(snapshot, "constraints"),
|
||||
riskWarnings: [],
|
||||
keyPoints: intentStringList(snapshot, "assumptions"),
|
||||
strategicSignificance: snapshot.objective.trim() ? [snapshot.objective.trim()] : [],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -829,18 +869,21 @@ export default function PositionRoundtablePage({
|
||||
const [positionId, setPositionId] = useState<PositionId>(() => 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 =
|
||||
@@ -957,9 +1000,10 @@ export default function PositionRoundtablePage({
|
||||
const [taskSaving, setTaskSaving] = useState(false);
|
||||
const [intentEditorOpen, setIntentEditorOpen] = useState(false);
|
||||
const [intentDraft, setIntentDraft] = useState<IntentEditDraft>({
|
||||
objective: "",
|
||||
constraints: "",
|
||||
assumptions: "",
|
||||
coreGoals: "",
|
||||
riskWarnings: "",
|
||||
keyPoints: "",
|
||||
strategicSignificance: "",
|
||||
});
|
||||
const [intentSaving, setIntentSaving] = useState(false);
|
||||
const [intentCompletedAt, setIntentCompletedAt] = useState("");
|
||||
@@ -1029,12 +1073,12 @@ export default function PositionRoundtablePage({
|
||||
[],
|
||||
);
|
||||
const frozenIntent = useMemo(
|
||||
() => parseIntentSummary(positionSession?.intentSnapshot),
|
||||
() => parsePositionIntentSummary(positionSession?.intentSnapshot),
|
||||
[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(
|
||||
() => ({
|
||||
@@ -1090,12 +1134,23 @@ export default function PositionRoundtablePage({
|
||||
? 1
|
||||
: 0,
|
||||
selectedModel,
|
||||
intentAgentId: POSITION_INTENT_AGENT_ID,
|
||||
taskContext: intentTaskContext,
|
||||
initialWelcomeText:
|
||||
"我已读取左侧任务信息。你可以直接补充本次任务的特殊约束;如果没有补充,我会基于现有任务信息进行意图识别。",
|
||||
showInitialWelcome: false,
|
||||
triggerToast,
|
||||
});
|
||||
const livePositionIntent = useMemo(
|
||||
() =>
|
||||
parsePositionIntentSummary(
|
||||
intent.intentReady as unknown as Record<string, unknown> | null,
|
||||
),
|
||||
[intent.intentReady],
|
||||
);
|
||||
const positionIntent = frozenIntent ?? livePositionIntent;
|
||||
const positionIntentHeadline =
|
||||
positionIntent?.strategicSignificance[0] ?? positionIntent?.coreGoals[0];
|
||||
// `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
|
||||
@@ -1144,9 +1199,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 });
|
||||
@@ -1162,20 +1218,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(() => {
|
||||
@@ -1186,7 +1242,7 @@ export default function PositionRoundtablePage({
|
||||
sessionCreationRef.current = creation;
|
||||
return creation;
|
||||
},
|
||||
[standaloneDemoMode, syncSessionUrl],
|
||||
[standaloneDemoMode, syncSessionUrl, taskScopeId],
|
||||
);
|
||||
|
||||
const openTaskEditor = useCallback(() => {
|
||||
@@ -1207,6 +1263,10 @@ 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(),
|
||||
@@ -1225,7 +1285,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) {
|
||||
@@ -1233,27 +1293,35 @@ export default function PositionRoundtablePage({
|
||||
} finally {
|
||||
setTaskSaving(false);
|
||||
}
|
||||
}, [ensureEditableSession, isArchivedSession, syncSessionUrl, task, taskDraft]);
|
||||
}, [ensureEditableSession, isArchivedSession, syncSessionUrl, task, taskDraft, taskScopeId]);
|
||||
|
||||
const openIntentEditor = useCallback(() => {
|
||||
if (isArchivedSession) return;
|
||||
const currentIntent = frozenIntent ?? intent.intentReady;
|
||||
const currentIntent = positionIntent;
|
||||
setIntentDraft({
|
||||
objective: currentIntent?.objective ?? "",
|
||||
constraints: (currentIntent?.constraints ?? []).join("\n"),
|
||||
assumptions: (currentIntent?.assumptions ?? []).join("\n"),
|
||||
coreGoals: (currentIntent?.coreGoals ?? []).join("\n"),
|
||||
riskWarnings: (currentIntent?.riskWarnings ?? []).join("\n"),
|
||||
keyPoints: (currentIntent?.keyPoints ?? []).join("\n"),
|
||||
strategicSignificance: (currentIntent?.strategicSignificance ?? []).join("\n"),
|
||||
});
|
||||
setIntentEditorOpen(true);
|
||||
}, [frozenIntent, intent.intentReady, isArchivedSession]);
|
||||
}, [isArchivedSession, positionIntent]);
|
||||
|
||||
const handleSaveIntentEdit = useCallback(async () => {
|
||||
if (isArchivedSession) {
|
||||
toast.warning("已归档的会话不能编辑意图理解");
|
||||
return;
|
||||
}
|
||||
const objective = intentDraft.objective.trim();
|
||||
if (!objective) {
|
||||
toast.warning("请填写任务意图");
|
||||
const coreGoals = intentDraft.coreGoals
|
||||
.split(/\r?\n/)
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
const strategicSignificance = intentDraft.strategicSignificance
|
||||
.split(/\r?\n/)
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
if (coreGoals.length === 0 && strategicSignificance.length === 0) {
|
||||
toast.warning("请至少填写核心目标或战略意义");
|
||||
return;
|
||||
}
|
||||
const splitLines = (value: string) =>
|
||||
@@ -1261,10 +1329,11 @@ export default function PositionRoundtablePage({
|
||||
.split(/\r?\n/)
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
const nextIntent: IntentSummary = {
|
||||
objective,
|
||||
constraints: splitLines(intentDraft.constraints),
|
||||
assumptions: splitLines(intentDraft.assumptions),
|
||||
const nextIntent: PositionIntentSummary = {
|
||||
coreGoals,
|
||||
riskWarnings: splitLines(intentDraft.riskWarnings),
|
||||
keyPoints: splitLines(intentDraft.keyPoints),
|
||||
strategicSignificance,
|
||||
};
|
||||
|
||||
setIntentSaving(true);
|
||||
@@ -1288,7 +1357,7 @@ export default function PositionRoundtablePage({
|
||||
});
|
||||
intent.hydrateFromDraft({
|
||||
intentThreadId: intentThreadId ?? intent.intentThreadId,
|
||||
intentReady: nextIntent,
|
||||
intentReady: nextIntent as unknown as IntentSummary,
|
||||
interactiveMessages: intent.interactiveMessages,
|
||||
timelineEntries: [],
|
||||
});
|
||||
@@ -1304,9 +1373,10 @@ export default function PositionRoundtablePage({
|
||||
ensureEditableSession,
|
||||
intent,
|
||||
intentCompletedAt,
|
||||
intentDraft.assumptions,
|
||||
intentDraft.constraints,
|
||||
intentDraft.objective,
|
||||
intentDraft.coreGoals,
|
||||
intentDraft.keyPoints,
|
||||
intentDraft.riskWarnings,
|
||||
intentDraft.strategicSignificance,
|
||||
intentInputDraft,
|
||||
isArchivedSession,
|
||||
task,
|
||||
@@ -1363,7 +1433,7 @@ export default function PositionRoundtablePage({
|
||||
// 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 intentAgentId = POSITION_INTENT_AGENT_ID;
|
||||
const isIntelligenceDeliveryOverview =
|
||||
activePosition.isIntentPosition && positionSession !== null && positionSession.status !== "intent_pending";
|
||||
const showIntentDeliveryOverview =
|
||||
@@ -1524,7 +1594,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);
|
||||
}
|
||||
@@ -1533,7 +1603,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;
|
||||
@@ -1599,7 +1669,11 @@ export default function PositionRoundtablePage({
|
||||
view.timelineEntries,
|
||||
view.inputDraft,
|
||||
);
|
||||
const intentSnapshot = view.intentReady ? { ...view.intentReady } : null;
|
||||
// 岗位会商持久化的是专属四段式结果;useStep1Intent 为兼容普通会商
|
||||
// 补出的 objective / constraints / assumptions 不应写回岗位会商快照。
|
||||
const intentSnapshot = parsePositionIntentSummary(
|
||||
view.intentReady as unknown as Record<string, unknown> | null,
|
||||
);
|
||||
|
||||
const operation = async () => {
|
||||
const baseSession = candidateSession ?? (await ensureEditableSession(task));
|
||||
@@ -1751,7 +1825,8 @@ export default function PositionRoundtablePage({
|
||||
candidates.sort((left, right) => right.length - left.length)[0] ?? [];
|
||||
hydrateIntentFromDraft({
|
||||
intentThreadId: intentThreadId ?? latest.intentThreadId,
|
||||
intentReady: latestFrozenIntentRef.current ?? latest.intentReady,
|
||||
intentReady:
|
||||
(latestFrozenIntentRef.current as unknown as IntentSummary | null) ?? latest.intentReady,
|
||||
interactiveMessages:
|
||||
interactiveMessages.length > 0
|
||||
? interactiveMessages
|
||||
@@ -1778,7 +1853,8 @@ export default function PositionRoundtablePage({
|
||||
: [];
|
||||
hydrateIntentFromDraft({
|
||||
intentThreadId: intentThreadId ?? latest.intentThreadId,
|
||||
intentReady: latestFrozenIntentRef.current ?? latest.intentReady,
|
||||
intentReady:
|
||||
(latestFrozenIntentRef.current as unknown as IntentSummary | null) ?? latest.intentReady,
|
||||
interactiveMessages: fallbackMessages,
|
||||
timelineEntries: databaseTimeline,
|
||||
});
|
||||
@@ -1812,15 +1888,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
|
||||
@@ -1843,7 +1921,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;
|
||||
@@ -1861,7 +1939,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 });
|
||||
})
|
||||
@@ -1881,7 +1960,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
|
||||
@@ -1928,6 +2007,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)
|
||||
@@ -1966,9 +2050,9 @@ export default function PositionRoundtablePage({
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [searchParamsString, sessionIdFromUrl, setSearchParams]);
|
||||
}, [searchParamsString, sessionIdFromUrl, setSearchParams, taskScopeId]);
|
||||
|
||||
const agentIdForPanel = activePosition.isIntentPosition ? INTENT_AGENT_ID : selectedAgentId;
|
||||
const agentIdForPanel = activePosition.isIntentPosition ? POSITION_INTENT_AGENT_ID : selectedAgentId;
|
||||
const { agent: selectedAgent } = useAgent(agentIdForPanel, {
|
||||
enabled: !standaloneDemoMode,
|
||||
});
|
||||
@@ -1980,7 +2064,7 @@ export default function PositionRoundtablePage({
|
||||
if (!activePosition.isIntentPosition) return null;
|
||||
const seat = activeChain?.seats.find((item) => item.position_id === intentPositionId);
|
||||
return {
|
||||
id: INTENT_AGENT_ID,
|
||||
id: POSITION_INTENT_AGENT_ID,
|
||||
name: seat?.name || `${activePosition.name}智能体`,
|
||||
description: seat?.description || activePosition.description,
|
||||
user_id: null,
|
||||
@@ -2043,7 +2127,7 @@ export default function PositionRoundtablePage({
|
||||
let session = await ensureEditableSession(task);
|
||||
session = await savePositionIntent(session.id, {
|
||||
intentThreadId: intent.intentThreadId,
|
||||
intentSnapshot: intent.intentReady,
|
||||
intentSnapshot: positionIntent,
|
||||
conversationSnapshot: buildIntentConversationSnapshot(
|
||||
intent.interactiveMessages,
|
||||
intent.timelineEntries,
|
||||
@@ -2061,7 +2145,8 @@ export default function PositionRoundtablePage({
|
||||
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 });
|
||||
@@ -2083,6 +2168,7 @@ export default function PositionRoundtablePage({
|
||||
setSearchParams,
|
||||
startingChain,
|
||||
task,
|
||||
taskScopeId,
|
||||
intentPositionId,
|
||||
positionId,
|
||||
]);
|
||||
@@ -2124,12 +2210,13 @@ export default function PositionRoundtablePage({
|
||||
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, intentPositionId, queueIntentConversationSave, searchParams, setSearchParams, task.id]);
|
||||
}, [intent, intentPositionId, queueIntentConversationSave, searchParams, setSearchParams, taskScopeId]);
|
||||
|
||||
const loadHistorySessions = useCallback(() => {
|
||||
if (isLocalPositionDemoSession(positionSessionRef.current?.id)) {
|
||||
@@ -2138,7 +2225,7 @@ export default function PositionRoundtablePage({
|
||||
return;
|
||||
}
|
||||
setHistoryLoading(true);
|
||||
void listPositionSessions(task.id)
|
||||
void listPositionSessions(taskScopeId ?? undefined)
|
||||
.then((sessions) => {
|
||||
setHistorySessions(
|
||||
[...sessions].sort((left, right) => {
|
||||
@@ -2154,7 +2241,7 @@ export default function PositionRoundtablePage({
|
||||
.finally(() => {
|
||||
setHistoryLoading(false);
|
||||
});
|
||||
}, [task.id]);
|
||||
}, [taskScopeId]);
|
||||
|
||||
const handleHistoryMenuOpenChange = useCallback(
|
||||
(open: boolean) => {
|
||||
@@ -2198,7 +2285,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);
|
||||
@@ -2209,7 +2297,7 @@ export default function PositionRoundtablePage({
|
||||
searchParams,
|
||||
sessionIdFromUrl,
|
||||
setSearchParams,
|
||||
task.id,
|
||||
taskScopeId,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -2269,7 +2357,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.
|
||||
@@ -2299,7 +2388,7 @@ export default function PositionRoundtablePage({
|
||||
sessionIdFromUrl,
|
||||
setSearchParams,
|
||||
standaloneDemoMode,
|
||||
task.id,
|
||||
taskScopeId,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -2381,17 +2470,17 @@ export default function PositionRoundtablePage({
|
||||
[handlePreviewArtifact],
|
||||
);
|
||||
const openIntentFlowDetail = useCallback(() => {
|
||||
if (!(frozenIntent ?? intent.intentReady)) {
|
||||
if (!positionIntent) {
|
||||
toast.info("任务意图还在梳理中,完成确认后就能查看完整的意图说明。");
|
||||
return;
|
||||
}
|
||||
setFlowDetailItem(
|
||||
buildIntentResultItem(
|
||||
frozenIntent ?? intent.intentReady,
|
||||
positionIntent,
|
||||
intentCompletedAt || positionSession?.updatedAt,
|
||||
),
|
||||
);
|
||||
}, [frozenIntent, intent.intentReady, intentCompletedAt, positionSession?.updatedAt]);
|
||||
}, [positionIntent, intentCompletedAt, positionSession?.updatedAt]);
|
||||
const openNodeFlowDetail = useCallback(
|
||||
(node: PositionRoundtableNode) => {
|
||||
const item = buildNodeResultItem(node, activeChain);
|
||||
@@ -2608,7 +2697,7 @@ export default function PositionRoundtablePage({
|
||||
positionName={activePosition.name}
|
||||
specialAgentConfig
|
||||
onSelectAgent={handleSelectAgent}
|
||||
intentObjective={frozenIntent?.objective ?? intent.intentReady?.objective}
|
||||
intentObjective={positionIntentHeadline}
|
||||
intentCompletedAt={intentCompletedAt}
|
||||
assignedAgentIds={configurationAgentIds}
|
||||
hasSelectedChain={showClosureAgents || Boolean(selectedChain)}
|
||||
@@ -2650,7 +2739,7 @@ export default function PositionRoundtablePage({
|
||||
}
|
||||
interactiveMessages={visibleIntentMessages}
|
||||
intentThreadId={intent.intentThreadId}
|
||||
intentReady={chainStarted ? frozenIntent ?? intent.intentReady : intent.intentReady}
|
||||
intentReady={chainStarted ? positionIntent : intent.intentReady}
|
||||
isIntentSending={intent.isIntentSending}
|
||||
pendingIntentClarificationMsgId={intent.pendingIntentClarificationMsgId}
|
||||
intentClarificationSelections={intent.intentClarificationSelections}
|
||||
@@ -2940,7 +3029,7 @@ export default function PositionRoundtablePage({
|
||||
/>
|
||||
{showIntentDeliveryOverview ? (
|
||||
<IntentDeliveryOverviewSidebar
|
||||
intent={frozenIntent ?? intent.intentReady}
|
||||
intent={positionIntent}
|
||||
chain={activeChain}
|
||||
nodes={positionSession?.nodes ?? []}
|
||||
activeNodeKey={activeNodeKey}
|
||||
@@ -3072,7 +3161,7 @@ export default function PositionRoundtablePage({
|
||||
positionName={activePosition.name}
|
||||
specialAgentConfig={activePosition.isIntentPosition}
|
||||
onSelectAgent={handleSelectAgent}
|
||||
intentObjective={frozenIntent?.objective ?? intent.intentReady?.objective}
|
||||
intentObjective={positionIntentHeadline}
|
||||
intentCompletedAt={intentCompletedAt}
|
||||
assignedAgentIds={configurationAgentIds}
|
||||
hasSelectedChain={showClosureAgents || Boolean(selectedChain)}
|
||||
@@ -3665,7 +3754,7 @@ function PositionNodeEmptyState({
|
||||
}
|
||||
|
||||
/** 已启动会话中的意图是冻结快照;避免在情报岗视图意外覆盖它。 */
|
||||
function IntentConfirmedState({ intent }: { intent: IntentSummary }) {
|
||||
function IntentConfirmedState({ intent }: { intent: PositionIntentSummary }) {
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col overflow-y-auto bg-slate-50/50 px-6 py-7 dark:bg-[#032650]/30">
|
||||
<div className="mx-auto w-full max-w-2xl rounded-2xl border border-emerald-500/20 bg-white p-5 shadow-sm dark:border-emerald-400/25 dark:bg-[#042b59]/65">
|
||||
@@ -3681,15 +3770,15 @@ function IntentConfirmedState({ intent }: { intent: IntentSummary }) {
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-5 rounded-xl border border-slate-100 bg-slate-50/70 p-4 dark:border-[#2b8ffe]/20 dark:bg-[#032650]/40">
|
||||
<p className="text-[11px] font-semibold text-muted-foreground dark:text-[#8aa0c4]">任务目标</p>
|
||||
<p className="mt-1.5 text-sm font-semibold leading-6 text-slate-800 dark:text-[#e8edf5]">
|
||||
{desensitize(intent.objective)}
|
||||
</p>
|
||||
<p className="text-[11px] font-semibold text-muted-foreground dark:text-[#8aa0c4]">核心目标</p>
|
||||
<div className="mt-1.5 space-y-1.5 text-sm font-semibold leading-6 text-slate-800 dark:text-[#e8edf5]">
|
||||
{intent.coreGoals.map((goal, index) => <p key={`${goal}-${index}`}>{desensitize(goal)}</p>)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-4">
|
||||
<p className="text-[11px] font-semibold text-muted-foreground dark:text-[#8aa0c4]">关键约束</p>
|
||||
<p className="text-[11px] font-semibold text-muted-foreground dark:text-[#8aa0c4]">风险提示</p>
|
||||
<div className="mt-2 grid gap-2 sm:grid-cols-2">
|
||||
{intent.constraints.map((constraint, index) => (
|
||||
{intent.riskWarnings.map((constraint, index) => (
|
||||
<div
|
||||
key={`${constraint}-${index}`}
|
||||
className="flex items-start gap-2 rounded-lg border border-slate-100 bg-white px-3 py-2 text-xs leading-5 text-slate-700 dark:border-[#2b8ffe]/20 dark:bg-[#032650]/35 dark:text-[#c5d8f1]"
|
||||
@@ -3726,7 +3815,7 @@ function PositionDeliveryOverview({
|
||||
chain,
|
||||
session,
|
||||
}: {
|
||||
intent: IntentSummary | null;
|
||||
intent: PositionIntentSummary | null;
|
||||
intentCompletedAt?: string;
|
||||
nodes: PositionRoundtableNode[];
|
||||
chain: BusinessChain | null;
|
||||
@@ -3859,7 +3948,10 @@ function PositionDeliveryOverview({
|
||||
kind: "intent",
|
||||
agentName: "情报分析智能体",
|
||||
productName: "任务意图理解",
|
||||
summary: intent?.objective || "情报分析岗已确认任务意图并冻结业务链。",
|
||||
summary:
|
||||
intent?.strategicSignificance[0] ||
|
||||
intent?.coreGoals[0] ||
|
||||
"情报分析岗已确认任务意图并冻结业务链。",
|
||||
positionId: intentPositionIdFor(),
|
||||
updatedAt: intentCompletedAt || session?.updatedAt,
|
||||
status: intent ? "done" : "ready",
|
||||
@@ -4787,7 +4879,7 @@ function IntentUnderstandingCard({
|
||||
collapsed,
|
||||
onCollapsedChange,
|
||||
}: {
|
||||
intent: ReturnType<typeof useStep1Intent>["intentReady"];
|
||||
intent: PositionIntentSummary | null;
|
||||
editable?: boolean;
|
||||
onEdit?: () => void;
|
||||
collapsed: boolean;
|
||||
@@ -4829,30 +4921,21 @@ function IntentUnderstandingCard({
|
||||
<div className="min-h-0 overflow-hidden">
|
||||
{intent ? (
|
||||
<div className="space-y-3 p-4">
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-slate-500 dark:text-[#9ebfe2]">任务意图</p>
|
||||
<p className="mt-1 text-sm leading-6 text-slate-700 dark:text-[#f2f7ff]">
|
||||
{desensitize(intent.objective)}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-slate-500 dark:text-[#9ebfe2]">关键约束</p>
|
||||
<ul className="mt-1 list-disc space-y-1 pl-4 text-sm leading-6 text-slate-600 marker:text-slate-400 dark:text-[#d8e6f8] dark:marker:text-[#83b6ed]">
|
||||
{intent.constraints.map((constraint, index) => (
|
||||
<li key={`${constraint}-${index}`}>{desensitize(constraint)}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
{intent.assumptions && intent.assumptions.length > 0 && (
|
||||
<div>
|
||||
<p className="text-xs font-semibold text-slate-500 dark:text-[#9ebfe2]">关键假设</p>
|
||||
<ul className="mt-1 list-disc space-y-1 pl-4 text-sm leading-6 text-slate-600 marker:text-slate-400 dark:text-[#d8e6f8] dark:marker:text-[#83b6ed]">
|
||||
{intent.assumptions.map((assumption, index) => (
|
||||
<li key={`${assumption}-${index}`}>{desensitize(assumption)}</li>
|
||||
))}
|
||||
</ul>
|
||||
{([
|
||||
["核心目标", intent.coreGoals],
|
||||
["风险提示", intent.riskWarnings],
|
||||
["关键要点", intent.keyPoints],
|
||||
["战略意义", intent.strategicSignificance],
|
||||
] as const).map(([label, values]) => (
|
||||
<div key={label}>
|
||||
<p className="text-xs font-semibold text-slate-500 dark:text-[#9ebfe2]">{label}</p>
|
||||
{values.length > 0 ? (
|
||||
<ul className="mt-1 list-disc space-y-1 pl-4 text-sm leading-6 text-slate-600 marker:text-slate-400 dark:text-[#d8e6f8] dark:marker:text-[#83b6ed]">
|
||||
{values.map((value, index) => <li key={`${value}-${index}`}>{desensitize(value)}</li>)}
|
||||
</ul>
|
||||
) : <p className="mt-1 text-sm text-slate-500 dark:text-[#9ebfe2]">暂无{label}</p>}
|
||||
</div>
|
||||
)}
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="p-4 text-sm leading-6 text-muted-foreground dark:text-[#d8e6f8]">
|
||||
@@ -4873,16 +4956,17 @@ function IntentDeliveryOverviewSidebar({
|
||||
onSelectNode,
|
||||
onSelectSeat,
|
||||
}: {
|
||||
intent: IntentSummary | null;
|
||||
intent: PositionIntentSummary | null;
|
||||
chain: BusinessChain | null;
|
||||
nodes: PositionRoundtableNode[];
|
||||
activeNodeKey: string | null;
|
||||
onSelectNode: (node: PositionRoundtableNode) => void;
|
||||
onSelectSeat: (seat: BusinessChain["seats"][number], stageIndex: number, seatIndex: number) => void;
|
||||
}) {
|
||||
const objective = intent?.objective?.trim() || "暂无任务目的";
|
||||
const coreGoals = intent?.constraints?.filter(Boolean) ?? [];
|
||||
const keyConstraints = intent?.assumptions?.filter(Boolean) ?? [];
|
||||
const coreGoals = intent?.coreGoals ?? [];
|
||||
const riskWarnings = intent?.riskWarnings ?? [];
|
||||
const keyPoints = intent?.keyPoints ?? [];
|
||||
const strategicSignificance = intent?.strategicSignificance ?? [];
|
||||
|
||||
return (
|
||||
<section className="position-roundtable-intent-delivery-sidebar">
|
||||
@@ -4892,10 +4976,6 @@ function IntentDeliveryOverviewSidebar({
|
||||
<h2>意图理解结果</h2>
|
||||
</header>
|
||||
<div className="position-roundtable-intent-delivery-sections">
|
||||
<article className="position-roundtable-intent-delivery-section position-roundtable-intent-delivery-section--purpose">
|
||||
<h3>任务目的</h3>
|
||||
<p>{desensitize(objective)}</p>
|
||||
</article>
|
||||
<article className="position-roundtable-intent-delivery-section position-roundtable-intent-delivery-section--goals">
|
||||
<h3>核心目标</h3>
|
||||
{coreGoals.length > 0 ? (
|
||||
@@ -4909,17 +4989,25 @@ function IntentDeliveryOverviewSidebar({
|
||||
)}
|
||||
</article>
|
||||
<article className="position-roundtable-intent-delivery-section position-roundtable-intent-delivery-section--constraints">
|
||||
<h3>关键约束</h3>
|
||||
{keyConstraints.length > 0 ? (
|
||||
<h3>风险提示</h3>
|
||||
{riskWarnings.length > 0 ? (
|
||||
<ul>
|
||||
{keyConstraints.map((constraint, index) => (
|
||||
<li key={`${constraint}-${index}`}>{desensitize(constraint)}</li>
|
||||
{riskWarnings.map((warning, index) => (
|
||||
<li key={`${warning}-${index}`}>{desensitize(warning)}</li>
|
||||
))}
|
||||
</ul>
|
||||
) : (
|
||||
<p className="is-empty">暂无补充约束</p>
|
||||
<p className="is-empty">暂无风险提示</p>
|
||||
)}
|
||||
</article>
|
||||
<article className="position-roundtable-intent-delivery-section position-roundtable-intent-delivery-section--purpose">
|
||||
<h3>关键要点</h3>
|
||||
{keyPoints.length > 0 ? <ul>{keyPoints.map((item, index) => <li key={`${item}-${index}`}>{desensitize(item)}</li>)}</ul> : <p className="is-empty">暂无关键要点</p>}
|
||||
</article>
|
||||
<article className="position-roundtable-intent-delivery-section position-roundtable-intent-delivery-section--significance">
|
||||
<h3>战略意义</h3>
|
||||
{strategicSignificance.length > 0 ? <ul>{strategicSignificance.map((item, index) => <li key={`${item}-${index}`}>{desensitize(item)}</li>)}</ul> : <p className="is-empty">暂无战略意义</p>}
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -4965,34 +5053,43 @@ function IntentUnderstandingEditDialog({
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-1">
|
||||
<label className="block space-y-1.5">
|
||||
<span className="text-xs font-semibold text-slate-500 dark:text-[#9ebfe2]">任务意图</span>
|
||||
<span className="text-xs font-semibold text-slate-500 dark:text-[#9ebfe2]">核心目标</span>
|
||||
<Textarea
|
||||
value={draft.objective}
|
||||
onChange={(event) => onChange({ ...draft, objective: event.target.value })}
|
||||
value={draft.coreGoals}
|
||||
onChange={(event) => onChange({ ...draft, coreGoals: event.target.value })}
|
||||
className="min-h-24 resize-none dark:border-[#2b8ffe]/35 dark:bg-[#032650]/80"
|
||||
placeholder="请输入识别后的任务意图"
|
||||
placeholder="每行一项核心目标"
|
||||
/>
|
||||
</label>
|
||||
<label className="block space-y-1.5">
|
||||
<span className="text-xs font-semibold text-slate-500 dark:text-[#9ebfe2]">
|
||||
关键约束
|
||||
风险提示
|
||||
</span>
|
||||
<Textarea
|
||||
value={draft.constraints}
|
||||
onChange={(event) => onChange({ ...draft, constraints: event.target.value })}
|
||||
value={draft.riskWarnings}
|
||||
onChange={(event) => onChange({ ...draft, riskWarnings: event.target.value })}
|
||||
className="min-h-28 resize-none dark:border-[#2b8ffe]/35 dark:bg-[#032650]/80"
|
||||
placeholder="每行一条关键约束"
|
||||
placeholder="每行一项风险、依赖或待确认事项"
|
||||
/>
|
||||
</label>
|
||||
<label className="block space-y-1.5">
|
||||
<span className="text-xs font-semibold text-slate-500 dark:text-[#9ebfe2]">
|
||||
补充假设 / 说明
|
||||
关键要点
|
||||
</span>
|
||||
<Textarea
|
||||
value={draft.assumptions}
|
||||
onChange={(event) => onChange({ ...draft, assumptions: event.target.value })}
|
||||
value={draft.keyPoints}
|
||||
onChange={(event) => onChange({ ...draft, keyPoints: event.target.value })}
|
||||
className="min-h-20 resize-none dark:border-[#2b8ffe]/35 dark:bg-[#032650]/80"
|
||||
placeholder="可选,每行一条"
|
||||
placeholder="每行一项关键要点"
|
||||
/>
|
||||
</label>
|
||||
<label className="block space-y-1.5">
|
||||
<span className="text-xs font-semibold text-slate-500 dark:text-[#9ebfe2]">战略意义</span>
|
||||
<Textarea
|
||||
value={draft.strategicSignificance}
|
||||
onChange={(event) => onChange({ ...draft, strategicSignificance: event.target.value })}
|
||||
className="min-h-20 resize-none dark:border-[#2b8ffe]/35 dark:bg-[#032650]/80"
|
||||
placeholder="每行一项战略意义"
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
@@ -5949,7 +6046,7 @@ function deliverableFallbackContent(item: ResultItem | null): string {
|
||||
}
|
||||
|
||||
function buildIntentResultItem(
|
||||
intent: IntentSummary | null,
|
||||
intent: PositionIntentSummary | null,
|
||||
updatedAt: string | undefined,
|
||||
): ResultItem {
|
||||
return {
|
||||
@@ -5958,7 +6055,10 @@ function buildIntentResultItem(
|
||||
node: null,
|
||||
agentName: "情报分析智能体",
|
||||
productName: "任务意图理解",
|
||||
summary: intent?.objective || "任务意图已确认,当前没有更多意图摘要内容。",
|
||||
summary:
|
||||
intent?.strategicSignificance[0] ||
|
||||
intent?.coreGoals[0] ||
|
||||
"任务意图已确认,当前没有更多意图摘要内容。",
|
||||
positionId: intentPositionIdFor(),
|
||||
updatedAt,
|
||||
status: intent ? "done" : "ready",
|
||||
|
||||
@@ -397,6 +397,15 @@
|
||||
color: #33bc92;
|
||||
}
|
||||
|
||||
.position-roundtable-intent-delivery-section--significance {
|
||||
border-left: 4px solid #45c3f3;
|
||||
background: rgba(0, 98, 217, 0.12);
|
||||
}
|
||||
|
||||
.position-roundtable-intent-delivery-section--significance h3 {
|
||||
color: #45c3f3;
|
||||
}
|
||||
|
||||
.position-roundtable-intent-delivery-section .is-empty {
|
||||
color: rgba(255, 255, 255, 0.62);
|
||||
}
|
||||
|
||||
@@ -4,11 +4,14 @@ import { getBackendBaseURL } from "@/core/config";
|
||||
import type { ClarificationPayload } from "./multi-agent";
|
||||
import { reportRoundtableError } from "./diagnostics-report";
|
||||
import { resolveAllowMultiple } from "@/roundtable-planning/lib/clarification";
|
||||
import { normalizeIntentReadySummary } from "@/roundtable-planning/lib/roundtable-constants";
|
||||
|
||||
export type { ClarificationPayload };
|
||||
|
||||
/** Stable built-in agent used by the multi-agent roundtable Step 1 flow. */
|
||||
export const INTENT_AGENT_ID = "roundtable-intent";
|
||||
/** Dedicated Step 1 agent for the position-roundtable workspace. */
|
||||
export const POSITION_INTENT_AGENT_ID = "position-roundtable-intent";
|
||||
|
||||
/**
|
||||
* Task-intent agent (Step 1) API. Mirror of multi-agent.ts but with a single
|
||||
@@ -103,13 +106,18 @@ function parseIntentErrorDetail(value: unknown): IntentErrorDetail | null {
|
||||
export async function initIntent(
|
||||
model?: string,
|
||||
taskContext?: Record<string, unknown> | null,
|
||||
intentAgentId?: string,
|
||||
): Promise<IntentInitResponse> {
|
||||
const res = await apiFetch(`${getBackendBaseURL()}/api/intent/init`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
// 岗位会商在创建意图线程时就写入父任务标识。这样即使用户尚未确认
|
||||
// 业务链,第一阶段的对话也已经可以按 taskId 恢复。
|
||||
body: JSON.stringify({ model, task_context: taskContext ?? undefined }),
|
||||
body: JSON.stringify({
|
||||
model,
|
||||
task_context: taskContext ?? undefined,
|
||||
intent_agent_id: intentAgentId || undefined,
|
||||
}),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const raw = await res.text().catch(() => "");
|
||||
@@ -140,6 +148,19 @@ export interface IntentSummary {
|
||||
constraints: string[];
|
||||
/** Optional assumptions the agent is making on the user's behalf. */
|
||||
assumptions?: string[];
|
||||
/** Present only for the dedicated position-roundtable intent agent. */
|
||||
coreGoals?: string[];
|
||||
riskWarnings?: string[];
|
||||
keyPoints?: string[];
|
||||
strategicSignificance?: string[];
|
||||
}
|
||||
|
||||
/** Final hand-off shape emitted only by the position-roundtable intent agent. */
|
||||
export interface PositionIntentSummary {
|
||||
coreGoals: string[];
|
||||
riskWarnings: string[];
|
||||
keyPoints: string[];
|
||||
strategicSignificance: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -167,6 +188,8 @@ export interface StreamIntentRequest {
|
||||
threadId: string;
|
||||
message: string;
|
||||
model?: string;
|
||||
/** Explicit built-in Step-1 agent. Omit to retain the multi-agent default. */
|
||||
intentAgentId?: string;
|
||||
/** Optional hidden business/task context injected into the model run. */
|
||||
taskContext?: Record<string, unknown> | null;
|
||||
/** Step 1 用户上传的参考文件(可选)。 */
|
||||
@@ -189,8 +212,7 @@ export interface StreamIntentRequest {
|
||||
* Fires for every `ask_clarification` tool message parsed out of the live
|
||||
* stream (the intent agent may emit several in a single turn). Lets the UI
|
||||
* surface each assistance question in real-time instead of waiting for the
|
||||
* terminal frame — which only carries the *first* question. `index` is the
|
||||
* 0-based arrival order within this turn.
|
||||
* terminal frame. `index` is the 0-based arrival order within this turn.
|
||||
*/
|
||||
onClarification?: (clarification: ClarificationPayload, index: number) => void;
|
||||
}
|
||||
@@ -211,8 +233,8 @@ export interface StreamIntentResult {
|
||||
clarification: ClarificationPayload | null;
|
||||
/**
|
||||
* All `ask_clarification` questions the agent asked this turn, in arrival
|
||||
* order. Collected from the live `type:"tool"` frames (the terminal frame
|
||||
* only carries the first). Empty unless status === "clarification".
|
||||
* order. Collected live and reconciled against the terminal frame so a
|
||||
* reconnect cannot lose cards. Empty unless status === "clarification".
|
||||
*/
|
||||
clarifications: ClarificationPayload[];
|
||||
/**
|
||||
@@ -238,6 +260,7 @@ function isFinalIntentFrame(value: unknown): value is {
|
||||
options?: unknown[];
|
||||
allow_custom?: boolean;
|
||||
allow_multiple?: boolean;
|
||||
clarifications?: unknown[];
|
||||
error_detail?: unknown;
|
||||
} {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
@@ -330,6 +353,41 @@ function extractClarificationToolMessage(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize one clarification included in the terminal status frame. This is
|
||||
* the reconnect / proxy fallback for cases where one or more live `tool`
|
||||
* frames were not delivered to the browser.
|
||||
*/
|
||||
function parseTerminalClarification(
|
||||
value: unknown,
|
||||
): { payload: ClarificationPayload; toolCallId: string } | null {
|
||||
if (!value || typeof value !== "object") return null;
|
||||
const raw = value as Record<string, unknown>;
|
||||
const clarificationType =
|
||||
typeof raw.clarification_type === "string" ? raw.clarification_type : "";
|
||||
const toolCallId = typeof raw.id === "string" ? raw.id : "";
|
||||
return {
|
||||
toolCallId,
|
||||
payload: {
|
||||
id: toolCallId || undefined,
|
||||
question: typeof raw.question === "string" ? raw.question : "",
|
||||
clarificationType,
|
||||
context:
|
||||
typeof raw.clarification_context === "string"
|
||||
? raw.clarification_context
|
||||
: typeof raw.context === "string"
|
||||
? raw.context
|
||||
: "",
|
||||
options: Array.isArray(raw.options) ? raw.options : [],
|
||||
allowCustom: raw.allow_custom !== false,
|
||||
allowMultiple: resolveAllowMultiple(
|
||||
typeof raw.allow_multiple === "boolean" ? raw.allow_multiple : undefined,
|
||||
clarificationType,
|
||||
),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Open an SSE connection to /api/intent/stream and resolve when the upstream
|
||||
* stream completes. Each call is one user turn; reuse the same threadId
|
||||
@@ -343,6 +401,7 @@ export async function streamIntent(req: StreamIntentRequest): Promise<StreamInte
|
||||
thread_id: req.threadId,
|
||||
message: req.message,
|
||||
model: req.model,
|
||||
intent_agent_id: req.intentAgentId || undefined,
|
||||
task_context: req.taskContext ?? undefined,
|
||||
// 仅在有文件时带上,空数组后端也安全忽略。
|
||||
files: req.files && req.files.length > 0 ? req.files : undefined,
|
||||
@@ -390,8 +449,7 @@ export async function streamIntent(req: StreamIntentRequest): Promise<StreamInte
|
||||
};
|
||||
|
||||
// Clarifications collected live from `type:"tool"` frames, deduped by
|
||||
// tool_call_id. The terminal frame only carries the first question, so this
|
||||
// is the source of truth for multi-question turns.
|
||||
// tool_call_id, then reconciled against the complete terminal list.
|
||||
const seenClarificationIds = new Set<string>();
|
||||
const collectClarification = (payload: ClarificationPayload, toolCallId: string) => {
|
||||
const dedupeKey = toolCallId || `idx-${result.clarifications.length}`;
|
||||
@@ -438,7 +496,7 @@ export async function streamIntent(req: StreamIntentRequest): Promise<StreamInte
|
||||
result.status = parsed.status;
|
||||
if (typeof parsed.content === "string") result.content = parsed.content;
|
||||
if (parsed.summary && typeof parsed.summary === "object") {
|
||||
result.summary = parsed.summary as IntentSummary;
|
||||
result.summary = normalizeIntentReadySummary(parsed.summary);
|
||||
}
|
||||
if (parsed.status === "error") {
|
||||
result.errorDetail = parseIntentErrorDetail(parsed.error_detail);
|
||||
@@ -448,28 +506,26 @@ export async function streamIntent(req: StreamIntentRequest): Promise<StreamInte
|
||||
detail: result.errorDetail,
|
||||
});
|
||||
}
|
||||
if (parsed.status === "clarification" && result.clarifications.length === 0) {
|
||||
// Fallback path: no live `type:"tool"` clarification frames were seen
|
||||
// (older backend, or single-question turn) — synthesize one from the
|
||||
// terminal frame so the UI still gets a card. When tool frames *were*
|
||||
// seen, `clarifications` already holds the full (possibly multi-question)
|
||||
// set and we keep it.
|
||||
const clarificationType =
|
||||
typeof parsed.clarification_type === "string" ? parsed.clarification_type : "";
|
||||
const fallback: ClarificationPayload = {
|
||||
question: typeof parsed.question === "string" ? parsed.question : "",
|
||||
clarificationType,
|
||||
context:
|
||||
typeof parsed.clarification_context === "string" ? parsed.clarification_context : "",
|
||||
options: Array.isArray(parsed.options) ? parsed.options : [],
|
||||
allowCustom: parsed.allow_custom !== false,
|
||||
allowMultiple: resolveAllowMultiple(
|
||||
typeof parsed.allow_multiple === "boolean" ? parsed.allow_multiple : undefined,
|
||||
clarificationType,
|
||||
),
|
||||
};
|
||||
result.clarification = fallback;
|
||||
result.clarifications = [fallback];
|
||||
if (parsed.status === "clarification") {
|
||||
// Newer backend frames contain every card. Merge them even when a
|
||||
// subset already arrived live: an SSE reconnect can otherwise leave
|
||||
// the user with only the first card in a multi-question assistance
|
||||
// round. Older backends still fall back to the legacy top-level card.
|
||||
const terminalCards = Array.isArray(parsed.clarifications)
|
||||
? parsed.clarifications
|
||||
.map(parseTerminalClarification)
|
||||
.filter((item): item is { payload: ClarificationPayload; toolCallId: string } => item !== null)
|
||||
: [];
|
||||
if (terminalCards.length > 0) {
|
||||
terminalCards.forEach((card, index) => {
|
||||
collectClarification(card.payload, card.toolCallId || `terminal-${index}`);
|
||||
});
|
||||
} else if (result.clarifications.length === 0) {
|
||||
const fallback = parseTerminalClarification(parsed);
|
||||
if (fallback) {
|
||||
collectClarification(fallback.payload, fallback.toolCallId || "terminal-0");
|
||||
}
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -153,6 +153,10 @@ export function BusinessChainPicker({
|
||||
// 席位「会商技能识别强化」开关(链条配置):按 agent_id 取,缺省 = 关。
|
||||
const skillById = new Map(selectedChain.seats.map((s) => [s.agent_id, s.seat_skill_directive ?? false]));
|
||||
const skillOf = (id: string) => skillById.get(id) ?? false;
|
||||
const humanValidationById = new Map(
|
||||
selectedChain.seats.map((s) => [s.agent_id, s.human_validation ?? false]),
|
||||
);
|
||||
const humanValidationOf = (id: string) => humanValidationById.get(id) ?? false;
|
||||
// 席位「推理深度覆盖」(链条配置 seat_mode):按 agent_id 取,null/缺省 = 跟随链条级 seatMode。
|
||||
const seatModeById = new Map(selectedChain.seats.map((s) => [s.agent_id, s.seat_mode ?? null]));
|
||||
const seatModeOf = (id: string) => seatModeById.get(id) ?? null;
|
||||
@@ -162,12 +166,12 @@ export function BusinessChainPicker({
|
||||
// dag:席位顺序按 stage 展平(与 plan 一致)。
|
||||
const agents = dagPlan.stages
|
||||
.flatMap((st) => st.agentIds)
|
||||
.map((id) => ({ agent_id: id, name: nameOf(id), model: modelOf(id), seat_skill_directive: skillOf(id), seatMode: seatModeOf(id) }));
|
||||
.map((id) => ({ agent_id: id, name: nameOf(id), model: modelOf(id), seat_skill_directive: skillOf(id), human_validation: humanValidationOf(id), seatMode: seatModeOf(id) }));
|
||||
onConfirm({ agents, mode: "dag", chain: chainMeta, plan: dagPlan, dagExecMode, gatherFirst: selectedChain.gatherFirst ?? false });
|
||||
return;
|
||||
}
|
||||
|
||||
const agents = survivingSeats.map((s) => ({ agent_id: s.agent_id, name: nameOf(s.agent_id), model: modelOf(s.agent_id), seat_skill_directive: skillOf(s.agent_id), seatMode: seatModeOf(s.agent_id) }));
|
||||
const agents = survivingSeats.map((s) => ({ agent_id: s.agent_id, name: nameOf(s.agent_id), model: modelOf(s.agent_id), seat_skill_directive: skillOf(s.agent_id), human_validation: humanValidationOf(s.agent_id), seatMode: seatModeOf(s.agent_id) }));
|
||||
onConfirm({ agents, mode: "chain", chain: chainMeta, gatherFirst: selectedChain.gatherFirst ?? false });
|
||||
};
|
||||
|
||||
|
||||
@@ -688,6 +688,15 @@ function Step1Message({
|
||||
|
||||
/** [INTENT_READY] 标记块解析出 IntentSummary 后的绿色摘要卡。 */
|
||||
function IntentReadySummaryCard({ summary }: { summary: IntentSummary }) {
|
||||
const positionSections =
|
||||
summary.coreGoals && summary.riskWarnings && summary.keyPoints && summary.strategicSignificance
|
||||
? ([
|
||||
["核心目标", summary.coreGoals],
|
||||
["风险提示", summary.riskWarnings],
|
||||
["关键要点", summary.keyPoints],
|
||||
["战略意义", summary.strategicSignificance],
|
||||
] as const)
|
||||
: null;
|
||||
return (
|
||||
<div className="mt-1 border border-emerald-200 bg-emerald-50/50 rounded-xl p-3 space-y-2">
|
||||
<div className="flex items-center gap-1.5">
|
||||
@@ -696,30 +705,35 @@ function IntentReadySummaryCard({ summary }: { summary: IntentSummary }) {
|
||||
任务意图已明确
|
||||
</span>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<span className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">核心目标</span>
|
||||
<p className="text-[11.5px] text-slate-800 leading-relaxed">{summary.objective}</p>
|
||||
</div>
|
||||
{summary.constraints?.length > 0 && (
|
||||
<div className="space-y-1">
|
||||
<span className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">约束条件</span>
|
||||
<ul className="list-disc pl-4 space-y-0.5 text-[11px] text-slate-700">
|
||||
{summary.constraints.map((c, i) => (
|
||||
<li key={i} className="leading-snug">{c}</li>
|
||||
))}
|
||||
</ul>
|
||||
{positionSections ? positionSections.map(([label, values]) => (
|
||||
<div key={label} className="space-y-1">
|
||||
<span className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">{label}</span>
|
||||
{values.length > 0 ? <ul className="list-disc pl-4 space-y-0.5 text-[11px] text-slate-700">
|
||||
{values.map((value, index) => <li key={index} className="leading-snug">{value}</li>)}
|
||||
</ul> : <p className="text-[11px] text-slate-500">暂无{label}</p>}
|
||||
</div>
|
||||
)}
|
||||
{summary.assumptions && summary.assumptions.length > 0 && (
|
||||
)) : <>
|
||||
<div className="space-y-1">
|
||||
<span className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">关键假设</span>
|
||||
<ul className="list-disc pl-4 space-y-0.5 text-[11px] text-slate-700">
|
||||
{summary.assumptions.map((a, i) => (
|
||||
<li key={i} className="leading-snug">{a}</li>
|
||||
))}
|
||||
</ul>
|
||||
<span className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">核心目标</span>
|
||||
<p className="text-[11.5px] text-slate-800 leading-relaxed">{summary.objective}</p>
|
||||
</div>
|
||||
)}
|
||||
{summary.constraints?.length > 0 && (
|
||||
<div className="space-y-1">
|
||||
<span className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">约束条件</span>
|
||||
<ul className="list-disc pl-4 space-y-0.5 text-[11px] text-slate-700">
|
||||
{summary.constraints.map((c, i) => <li key={i} className="leading-snug">{c}</li>)}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
{summary.assumptions && summary.assumptions.length > 0 && (
|
||||
<div className="space-y-1">
|
||||
<span className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">关键假设</span>
|
||||
<ul className="list-disc pl-4 space-y-0.5 text-[11px] text-slate-700">
|
||||
{summary.assumptions.map((a, i) => <li key={i} className="leading-snug">{a}</li>)}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -90,6 +90,8 @@ export interface UseStep1IntentOptions {
|
||||
currentStep: number;
|
||||
/** 全局选中模型;调用 `/api/intent/init` / `/api/intent/stream` 时透传。 */
|
||||
selectedModel: string;
|
||||
/** Optional built-in agent override for a workspace with a distinct schema. */
|
||||
intentAgentId?: string;
|
||||
/** Optional hidden task/business context for each intent-agent turn. */
|
||||
taskContext?: Record<string, unknown> | null;
|
||||
/** Optional task-aware welcome bubble text before the first user turn. */
|
||||
@@ -178,6 +180,7 @@ export function useStep1Intent(options: UseStep1IntentOptions): UseStep1IntentRe
|
||||
const {
|
||||
currentStep,
|
||||
selectedModel,
|
||||
intentAgentId,
|
||||
taskContext,
|
||||
initialWelcomeText,
|
||||
showInitialWelcome = true,
|
||||
@@ -214,6 +217,10 @@ export function useStep1Intent(options: UseStep1IntentOptions): UseStep1IntentRe
|
||||
useEffect(() => {
|
||||
selectedModelRef.current = selectedModel;
|
||||
}, [selectedModel]);
|
||||
const intentAgentIdRef = useRef<string | undefined>(intentAgentId);
|
||||
useEffect(() => {
|
||||
intentAgentIdRef.current = intentAgentId;
|
||||
}, [intentAgentId]);
|
||||
const taskContextRef = useRef<Record<string, unknown> | null>(taskContext ?? null);
|
||||
useEffect(() => {
|
||||
taskContextRef.current = taskContext ?? null;
|
||||
@@ -265,6 +272,7 @@ export function useStep1Intent(options: UseStep1IntentOptions): UseStep1IntentRe
|
||||
const res = await initIntent(
|
||||
selectedModelRef.current || undefined,
|
||||
taskContextRef.current,
|
||||
intentAgentIdRef.current,
|
||||
);
|
||||
if (step1InitGenRef.current !== myGen) return;
|
||||
setIntentThreadId(res.thread_id);
|
||||
@@ -443,6 +451,7 @@ export function useStep1Intent(options: UseStep1IntentOptions): UseStep1IntentRe
|
||||
threadId: intentThreadId,
|
||||
message: trimmed,
|
||||
model: selectedModelRef.current || undefined,
|
||||
intentAgentId: intentAgentIdRef.current,
|
||||
taskContext: taskContextRef.current,
|
||||
files: fileRefs,
|
||||
signal: aborter.signal,
|
||||
|
||||
@@ -33,6 +33,13 @@ import { useUpdateSubtask } from "@/core/tasks/context";
|
||||
/** 干预消息携带的上传文件引用(与 streamMultiAgent 的 files 字段同形)。 */
|
||||
type RunFileRef = NonNullable<StreamMultiAgentRequest["files"]>[number];
|
||||
|
||||
type SeatDelivery = { name: string; content: string };
|
||||
|
||||
/** In-memory cursor for a business-chain human-validation pause. */
|
||||
type HumanValidationContinuation =
|
||||
| { mode: "chain"; nextSeatIndex: number }
|
||||
| { mode: "dag"; nextStageIndex: number; priorDeliveries: SeatDelivery[] };
|
||||
|
||||
/** 读取并清空 ref(consume-once):首个 leader run 拿到文件后清空,后续轮次不再带。 */
|
||||
function takeOnce<T>(ref: { current: T | null }): T | undefined {
|
||||
const v = ref.current ?? undefined;
|
||||
@@ -286,6 +293,8 @@ export interface UseStep2OrchestrationOptions {
|
||||
* OR。recommend / 未选链条 → 空 {}(各席位仅靠其自身开关)。
|
||||
*/
|
||||
seatSkillDirectives?: Record<string, boolean>;
|
||||
/** Per-seat human-validation checkpoints inherited from the selected chain. */
|
||||
humanValidations?: Record<string, boolean>;
|
||||
/**
|
||||
* 每席位「推理深度覆盖」映射 {agentId: SeatMode | null}(沿用所选业务链条里每个席位的配置)。
|
||||
* 派活该 special 席位时按 agentId 查表,**席位覆盖优先、否则跟随链条级 `selectedMode`**:
|
||||
@@ -456,6 +465,7 @@ export function useStep2Orchestration(
|
||||
selectedModel,
|
||||
selectedMode,
|
||||
seatSkillDirectives = {},
|
||||
humanValidations = {},
|
||||
seatModes = {},
|
||||
gatherFirst = false,
|
||||
orchestrationMode,
|
||||
@@ -593,6 +603,7 @@ export function useStep2Orchestration(
|
||||
const selectedModeRef = useRef<SeatMode>(selectedMode);
|
||||
// 每席位技能识别强化映射(所选业务链条各席位开关)同样打到 ref,席位调用按 agentId 读最新值。
|
||||
const seatSkillDirectivesRef = useRef<Record<string, boolean>>(seatSkillDirectives);
|
||||
const humanValidationsRef = useRef<Record<string, boolean>>(humanValidations);
|
||||
// 每席位推理深度覆盖映射(所选业务链条各席位 seatMode)打到 ref,席位调用按 agentId 读最新值;
|
||||
// 覆盖优先、否则跟随 selectedModeRef。
|
||||
const seatModesRef = useRef<Record<string, SeatMode | null>>(seatModes);
|
||||
@@ -624,6 +635,7 @@ export function useStep2Orchestration(
|
||||
// 澄清回复都改走 **leader 自由派活循环**(runOrchestration),由总控接着派活,而**不是**
|
||||
// 重新把整张 DAG 从头跑一遍(致命 bug 修复)。新任务 / 重新进入时由 resetInitGate 复位。
|
||||
const dagPlanExecutedRef = useRef<boolean>(false);
|
||||
const humanValidationContinuationRef = useRef<HumanValidationContinuation | null>(null);
|
||||
const selectedAgentsRef = useRef<SelectedAgent[]>(selectedAgents);
|
||||
useEffect(() => {
|
||||
orchestrationModeRef.current = orchestrationMode;
|
||||
@@ -643,6 +655,9 @@ export function useStep2Orchestration(
|
||||
useEffect(() => {
|
||||
seatSkillDirectivesRef.current = seatSkillDirectives;
|
||||
}, [seatSkillDirectives]);
|
||||
useEffect(() => {
|
||||
humanValidationsRef.current = humanValidations;
|
||||
}, [humanValidations]);
|
||||
useEffect(() => {
|
||||
seatModesRef.current = seatModes;
|
||||
}, [seatModes]);
|
||||
@@ -1213,6 +1228,21 @@ export function useStep2Orchestration(
|
||||
[],
|
||||
);
|
||||
|
||||
const pauseForHumanValidation = useCallback(
|
||||
(continuation: HumanValidationContinuation, seatNames: string[]) => {
|
||||
humanValidationContinuationRef.current = continuation;
|
||||
appendDialogue({
|
||||
sender: "系统",
|
||||
avatarType: "blue",
|
||||
content: `已完成 ${seatNames.join("、")} 的输出,按业务链条配置暂停,等待人工校验。可直接点击“恢复会商”继续,或在下方输入修改意见后提交。`,
|
||||
confidence: "等待人工校验",
|
||||
});
|
||||
setIsRoundTableRunning(false);
|
||||
triggerToast("已暂停等待人工校验:可恢复会商,或输入修改意见后继续");
|
||||
},
|
||||
[appendDialogue, triggerToast],
|
||||
);
|
||||
|
||||
const phaseLabel = useCallback(
|
||||
(
|
||||
phase: StreamPhase,
|
||||
@@ -2012,11 +2042,17 @@ export function useStep2Orchestration(
|
||||
|
||||
const chainSeats = selectedAgentsRef.current;
|
||||
const total = chainSeats.length;
|
||||
const continuation = humanValidationContinuationRef.current;
|
||||
const startSeatIndex =
|
||||
continuation?.mode === "chain" ? continuation.nextSeatIndex : 0;
|
||||
if (continuation?.mode === "chain") {
|
||||
humanValidationContinuationRef.current = null;
|
||||
}
|
||||
const leaderThreadId = resolveSeatThreadId(ids, coord);
|
||||
let finishedAllSeats = true;
|
||||
|
||||
try {
|
||||
for (let i = 0; i < total; i += 1) {
|
||||
for (let i = startSeatIndex; i < total; i += 1) {
|
||||
if (isStale()) {
|
||||
finishedAllSeats = false;
|
||||
break;
|
||||
@@ -2179,6 +2215,14 @@ export function useStep2Orchestration(
|
||||
}
|
||||
|
||||
setConsensusPercentage(Math.min(95, Math.round(((i + 1) / total) * 90)));
|
||||
if (humanValidationsRef.current[seat.agent_id]) {
|
||||
pauseForHumanValidation(
|
||||
{ mode: "chain", nextSeatIndex: i + 1 },
|
||||
[seatName],
|
||||
);
|
||||
finishedAllSeats = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ── (c) 总控收口:综合全链交付,产出最终结论 ──
|
||||
@@ -2257,6 +2301,7 @@ export function useStep2Orchestration(
|
||||
handleUpstreamFrame,
|
||||
ingestSubagentTaskFrame,
|
||||
resolveSeatThreadId,
|
||||
pauseForHumanValidation,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -2300,23 +2345,37 @@ export function useStep2Orchestration(
|
||||
dagPlanExecutedRef.current = true;
|
||||
|
||||
const leaderThreadId = resolveSeatThreadId(ids, coord);
|
||||
const continuation = humanValidationContinuationRef.current;
|
||||
const startStageIndex =
|
||||
continuation?.mode === "dag" ? continuation.nextStageIndex : 0;
|
||||
if (continuation?.mode === "dag") {
|
||||
humanValidationContinuationRef.current = null;
|
||||
}
|
||||
let finishedAllStages = true;
|
||||
// 跨 stage 累积的**完整交付** {name, content}[] —— 注入下一 stage 席位的 run context
|
||||
// (peerDeliveries),供 read_peer_delivery 工具按需取全文(§12.9 传摘要按需传全文)。
|
||||
// 研讨前并行取数(gatherFirst)的产物作为初始注入:首个 stage 席位开局即带共享资料。
|
||||
const priorDeliveries: Array<{ name: string; content: string }> = [...gatheredDeliveriesRef.current];
|
||||
const priorDeliveries: SeatDelivery[] =
|
||||
continuation?.mode === "dag"
|
||||
? [...continuation.priorDeliveries]
|
||||
: [...gatheredDeliveriesRef.current];
|
||||
|
||||
// Phase 7:初始化 DAG 流程图节点状态 —— 计划内所有席位置 pending,执行过程中逐个点亮。
|
||||
const markDagNode = (agentId: string, state: ChainNodeState) =>
|
||||
setDagNodeStates((prev) => ({ ...prev, [agentId.toLowerCase()]: state }));
|
||||
setDagNodeStates(
|
||||
Object.fromEntries(
|
||||
plan.stages.flatMap((st) => st.agentIds.map((id) => [id.toLowerCase(), "pending" as ChainNodeState])),
|
||||
plan.stages.flatMap((st, stageIndex) =>
|
||||
st.agentIds.map((id) => [
|
||||
id.toLowerCase(),
|
||||
(stageIndex < startStageIndex ? "done" : "pending") as ChainNodeState,
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
try {
|
||||
for (let s = 0; s < plan.stages.length; s += 1) {
|
||||
for (let s = startStageIndex; s < plan.stages.length; s += 1) {
|
||||
if (isStale()) {
|
||||
finishedAllStages = false;
|
||||
break;
|
||||
@@ -2558,6 +2617,21 @@ export function useStep2Orchestration(
|
||||
setConsensusPercentage(
|
||||
Math.min(95, Math.round(((s + 1) / plan.stages.length) * 90)),
|
||||
);
|
||||
const validationSeatNames = stageSeats
|
||||
.filter(({ agentId }) => humanValidationsRef.current[agentId])
|
||||
.map(({ name }) => name);
|
||||
if (validationSeatNames.length > 0) {
|
||||
pauseForHumanValidation(
|
||||
{
|
||||
mode: "dag",
|
||||
nextStageIndex: s + 1,
|
||||
priorDeliveries: [...priorDeliveries],
|
||||
},
|
||||
validationSeatNames,
|
||||
);
|
||||
finishedAllStages = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// ── 计划阶段全部完成 → **交给总控(leader 自由派活循环)继续** ──
|
||||
@@ -2613,6 +2687,7 @@ export function useStep2Orchestration(
|
||||
ingestParallelDelta,
|
||||
resetParallelStreams,
|
||||
runOrchestration,
|
||||
pauseForHumanValidation,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -2746,8 +2821,9 @@ export function useStep2Orchestration(
|
||||
// 改走 leader 自由派活循环,由总控接着派活,而不是把 DAG 从头重跑一遍。
|
||||
if (
|
||||
mode === "dag" &&
|
||||
!dagPlanExecutedRef.current &&
|
||||
(orchestrationPlanRef.current?.stages.length ?? 0) > 0
|
||||
(humanValidationContinuationRef.current?.mode === "dag" ||
|
||||
(!dagPlanExecutedRef.current &&
|
||||
(orchestrationPlanRef.current?.stages.length ?? 0) > 0))
|
||||
) {
|
||||
return runDagOrchestration(seedMessage, ids, coord);
|
||||
}
|
||||
@@ -3070,6 +3146,7 @@ export function useStep2Orchestration(
|
||||
|
||||
const resetInitGate = useCallback(() => {
|
||||
step2InitRef.current = false;
|
||||
humanValidationContinuationRef.current = null;
|
||||
// 新一轮研讨:允许 DAG 计划重新执行一遍。
|
||||
dagPlanExecutedRef.current = false;
|
||||
// 新一轮研讨:允许「研讨前并行取数」再取一次(清掉上一轮取数产物 + 闸门)。
|
||||
@@ -3086,6 +3163,7 @@ export function useStep2Orchestration(
|
||||
// 这里只重复设 cancel ref 与 UI 标记,确保从 Step 2 在编排中切到草稿时
|
||||
// UI 立刻翻成静止态。
|
||||
orchestrationCancelRef.current = true;
|
||||
humanValidationContinuationRef.current = null;
|
||||
setIsOrchestrating(false);
|
||||
setIsInitializing(false);
|
||||
setPendingClarification(null);
|
||||
@@ -3166,6 +3244,7 @@ export function useStep2Orchestration(
|
||||
return false;
|
||||
}
|
||||
dagPlanExecutedRef.current = true;
|
||||
humanValidationContinuationRef.current = null;
|
||||
orchestrationCancelRef.current = true;
|
||||
abortAllInFlight();
|
||||
isOrchestratingRef.current = false;
|
||||
@@ -3208,6 +3287,7 @@ export function useStep2Orchestration(
|
||||
hasAutoOpenedRef.current = new Set();
|
||||
pendingInjectPromptRef.current = null;
|
||||
dagPlanExecutedRef.current = false;
|
||||
humanValidationContinuationRef.current = null;
|
||||
gatherPhaseDoneRef.current = false;
|
||||
gatheredDeliveriesRef.current = [];
|
||||
deselectArtifact();
|
||||
|
||||
@@ -36,6 +36,11 @@ export interface ChainSeat {
|
||||
* (无需 DB 列),在链条编辑器里逐席位开关。
|
||||
*/
|
||||
seat_skill_directive?: boolean;
|
||||
/**
|
||||
* Human-validation checkpoint. When enabled, Step 2 pauses after this seat
|
||||
* (or its DAG stage) completes and reuses the existing resume/intervention UI.
|
||||
*/
|
||||
human_validation?: boolean;
|
||||
/**
|
||||
* 可选「席位推理深度覆盖」:覆盖链条级 `seatMode`,只对该席位生效。值是同一套
|
||||
* `SeatMode`(flash/thinking/pro/ultra);null / 缺省 = 跟随链条级默认。用于「卡顿提速」:
|
||||
@@ -109,7 +114,7 @@ export interface SeatSelectionResult {
|
||||
* `model` 为该席位在来源链条里配置的模型覆盖(空 / 缺省 = 跟随全局模型)。
|
||||
* `seat_skill_directive` 为该席位在来源链条里配置的「技能识别强化」开关(缺省 = 关)。
|
||||
*/
|
||||
agents: Array<{ agent_id: string; name: string; model?: string | null; seat_skill_directive?: boolean; seatMode?: SeatMode | null }>;
|
||||
agents: Array<{ agent_id: string; name: string; model?: string | null; seat_skill_directive?: boolean; human_validation?: boolean; seatMode?: SeatMode | null }>;
|
||||
/**
|
||||
* 决定 Step 2 走哪种编排:
|
||||
* - `recommend` 总控自由派活;
|
||||
@@ -171,6 +176,10 @@ export function buildChainSeatSelection(
|
||||
// 席位「技能识别强化」开关(链条配置):按 agent_id 取,缺省 = 关。
|
||||
const skillById = new Map(chain.seats.map((s) => [s.agent_id, s.seat_skill_directive ?? false]));
|
||||
const skillOf = (id: string) => skillById.get(id) ?? false;
|
||||
const humanValidationById = new Map(
|
||||
chain.seats.map((s) => [s.agent_id, s.human_validation ?? false]),
|
||||
);
|
||||
const humanValidationOf = (id: string) => humanValidationById.get(id) ?? false;
|
||||
// 席位「推理深度覆盖」(链条配置 seat_mode):按 agent_id 取,null/缺省 = 跟随链条级 seatMode。
|
||||
// 输出到 SeatSelectionResult.agents[].seatMode(camel,喂给编排/作业的 seatModes map)。
|
||||
const seatModeById = new Map(chain.seats.map((s) => [s.agent_id, s.seat_mode ?? null]));
|
||||
@@ -196,12 +205,12 @@ export function buildChainSeatSelection(
|
||||
if (hasParallel || hasGoal || hasCoord) {
|
||||
const agents = plan.stages
|
||||
.flatMap((st) => st.agentIds)
|
||||
.map((id) => ({ agent_id: id, name: nameOf(id), model: modelOf(id), seat_skill_directive: skillOf(id), seatMode: seatModeOf(id) }));
|
||||
.map((id) => ({ agent_id: id, name: nameOf(id), model: modelOf(id), seat_skill_directive: skillOf(id), human_validation: humanValidationOf(id), seatMode: seatModeOf(id) }));
|
||||
return { agents, mode: "dag", chain: chainMeta, plan, dagExecMode: "sandbox", seatMode: chain.seatMode, gatherFirst: chain.gatherFirst ?? false };
|
||||
}
|
||||
}
|
||||
|
||||
const agents = survivingSeats.map((s) => ({ agent_id: s.agent_id, name: nameOf(s.agent_id), model: modelOf(s.agent_id), seat_skill_directive: skillOf(s.agent_id), seatMode: seatModeOf(s.agent_id) }));
|
||||
const agents = survivingSeats.map((s) => ({ agent_id: s.agent_id, name: nameOf(s.agent_id), model: modelOf(s.agent_id), seat_skill_directive: skillOf(s.agent_id), human_validation: humanValidationOf(s.agent_id), seatMode: seatModeOf(s.agent_id) }));
|
||||
return { agents, mode: "chain", chain: chainMeta, seatMode: chain.seatMode, gatherFirst: chain.gatherFirst ?? false };
|
||||
}
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
moveSeatToStage,
|
||||
moveStage,
|
||||
removeSeat,
|
||||
setSeatHumanValidation,
|
||||
setStageGoal,
|
||||
splitSeatToNewStage,
|
||||
stageGroupsToSeats,
|
||||
@@ -122,6 +123,15 @@ test("setStageGoal is immutable + out-of-range no-op", () => {
|
||||
assert.equal(setStageGoal(groups, 9, "x"), groups); // 越界返回原引用
|
||||
});
|
||||
|
||||
test("setSeatHumanValidation updates only the selected seat and is immutable", () => {
|
||||
const groups = grp([seat("a"), seat("b")], [seat("c")]);
|
||||
const next = setSeatHumanValidation(groups, "b", true);
|
||||
assert.equal(next[0].seats[1].human_validation, true);
|
||||
assert.equal(next[0].seats[0].human_validation, undefined);
|
||||
assert.equal(next[1].seats[0].human_validation, undefined);
|
||||
assert.equal(groups[0].seats[1].human_validation, undefined);
|
||||
});
|
||||
|
||||
// ── lookups ───────────────────────────────────────────────────────────────────
|
||||
|
||||
test("findStageIndexOfSeat / countSeats", () => {
|
||||
|
||||
@@ -141,6 +141,23 @@ export function setSeatSkillDirective(groups: StageGroups, agentId: string, enab
|
||||
});
|
||||
}
|
||||
|
||||
/** Update a seat's human-validation checkpoint without changing other stages. */
|
||||
export function setSeatHumanValidation(
|
||||
groups: StageGroups,
|
||||
agentId: string,
|
||||
enabled: boolean,
|
||||
): StageGroups {
|
||||
return groups.map((g) => {
|
||||
if (!g.seats.some((s) => s.agent_id === agentId)) return g;
|
||||
return {
|
||||
...g,
|
||||
seats: g.seats.map((s) =>
|
||||
s.agent_id === agentId ? { ...s, human_validation: enabled } : s,
|
||||
),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置某个席位的「推理深度覆盖」(不可变,供编辑器席位下拉 onChange)。
|
||||
* `mode` 为 null = 清除覆盖(跟随链条级 seatMode)。按 agent_id 定位,跨 stage 适用。
|
||||
|
||||
@@ -292,9 +292,29 @@ function toStringArray(value: unknown): string[] {
|
||||
* 把解析出的对象归一成 IntentSummary。只要 `objective` 是非空字符串就认。
|
||||
* constraints / assumptions 容忍模型写成字符串 / null / 缺失,统一归到 string[]。
|
||||
*/
|
||||
function normalizeIntentSummary(parsed: unknown): IntentSummary | null {
|
||||
export function normalizeIntentReadySummary(parsed: unknown): IntentSummary | null {
|
||||
if (!parsed || typeof parsed !== "object") return null;
|
||||
const obj = parsed as Record<string, unknown>;
|
||||
const positionKeys = ["coreGoals", "riskWarnings", "keyPoints", "strategicSignificance"];
|
||||
if (positionKeys.some((key) => key in obj)) {
|
||||
if (!positionKeys.every((key) => Array.isArray(obj[key]))) return null;
|
||||
const coreGoals = toStringArray(obj.coreGoals);
|
||||
const riskWarnings = toStringArray(obj.riskWarnings);
|
||||
const keyPoints = toStringArray(obj.keyPoints);
|
||||
const strategicSignificance = toStringArray(obj.strategicSignificance);
|
||||
// Keep the long-standing Step-1 state machine compatible while retaining
|
||||
// every position-specific field verbatim for its dedicated UI and storage.
|
||||
return {
|
||||
objective:
|
||||
strategicSignificance[0] || coreGoals[0] || keyPoints[0] || "岗位任务意图已识别",
|
||||
constraints: riskWarnings,
|
||||
assumptions: keyPoints,
|
||||
coreGoals,
|
||||
riskWarnings,
|
||||
keyPoints,
|
||||
strategicSignificance,
|
||||
};
|
||||
}
|
||||
const objective =
|
||||
typeof obj.objective === "string" ? obj.objective.trim() : "";
|
||||
if (!objective) return null;
|
||||
@@ -310,14 +330,14 @@ function normalizeIntentSummary(parsed: unknown): IntentSummary | null {
|
||||
* 1) 原文直接 parse
|
||||
* 2) 转义字符串内的裸控制字符(换行 / 制表符)后再 parse
|
||||
* 3) 再去掉尾随逗号后 parse
|
||||
* 三次都失败才放弃。任一成功都过 `normalizeIntentSummary` 兜字段类型。
|
||||
* 三次都失败才放弃。任一成功都过 `normalizeIntentReadySummary` 兜字段类型。
|
||||
*/
|
||||
function parseIntentSummary(raw: string): IntentSummary | null {
|
||||
const sanitized = sanitizeJsonControlChars(raw);
|
||||
const candidates = [raw, sanitized, stripTrailingCommas(sanitized)];
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
const summary = normalizeIntentSummary(JSON.parse(candidate));
|
||||
const summary = normalizeIntentReadySummary(JSON.parse(candidate));
|
||||
if (summary) return summary;
|
||||
} catch {
|
||||
// 下一个候选
|
||||
|
||||
@@ -41,6 +41,7 @@ import {
|
||||
Sparkles,
|
||||
SplitSquareVertical,
|
||||
Trash2,
|
||||
UserCheck,
|
||||
UserPlus,
|
||||
Wand2,
|
||||
X,
|
||||
@@ -127,6 +128,7 @@ import {
|
||||
seatExistsInGroups,
|
||||
setSeatMode as setSeatModeOnGroups,
|
||||
setSeatModel,
|
||||
setSeatHumanValidation,
|
||||
setSeatSkillDirective,
|
||||
setStageGoal,
|
||||
splitSeatToNewStage,
|
||||
@@ -453,6 +455,10 @@ export default function BusinessChainEditorPage() {
|
||||
setStageGroups((prev) => setSeatSkillDirective(prev, agentId, enabled));
|
||||
}, []);
|
||||
|
||||
const setSeatHumanValidationCb = useCallback((agentId: string, enabled: boolean) => {
|
||||
setStageGroups((prev) => setSeatHumanValidation(prev, agentId, enabled));
|
||||
}, []);
|
||||
|
||||
// 席位「推理深度覆盖」:编辑器席位小图标下拉 onChange(null = 清除,跟随链条级 seatMode)。
|
||||
const setSeatModeCb = useCallback((agentId: string, mode: SeatMode | null) => {
|
||||
setStageGroups((prev) => setSeatModeOnGroups(prev, agentId, mode));
|
||||
@@ -670,6 +676,7 @@ export default function BusinessChainEditorPage() {
|
||||
model: s.model ?? null,
|
||||
// 席位「会商技能识别强化」开关:随席位一起落库(缺省 = false 关)。
|
||||
seat_skill_directive: s.seat_skill_directive ?? false,
|
||||
human_validation: s.human_validation ?? false,
|
||||
// 席位「推理深度覆盖」:随席位一起落库(null = 跟随链条级 seatMode)。
|
||||
seat_mode: s.seat_mode ?? null,
|
||||
// 岗位协同专用岗位归属:普通圆桌忽略,但保存时必须原样保留。
|
||||
@@ -1272,6 +1279,7 @@ export default function BusinessChainEditorPage() {
|
||||
onSplitSeat={splitSeat}
|
||||
onSeatModelChange={setSeatModelCb}
|
||||
onSeatSkillDirectiveChange={setSeatSkillDirectiveCb}
|
||||
onSeatHumanValidationChange={setSeatHumanValidationCb}
|
||||
onSeatModeChange={setSeatModeCb}
|
||||
positionConfigMode={positionConfigMode}
|
||||
positionOptions={positionOptions}
|
||||
@@ -1455,6 +1463,7 @@ function StagesColumn({
|
||||
onSplitSeat,
|
||||
onSeatModelChange,
|
||||
onSeatSkillDirectiveChange,
|
||||
onSeatHumanValidationChange,
|
||||
onSeatModeChange,
|
||||
positionConfigMode,
|
||||
positionOptions,
|
||||
@@ -1476,6 +1485,7 @@ function StagesColumn({
|
||||
onSplitSeat: (agentId: string) => void;
|
||||
onSeatModelChange: (agentId: string, model: string | null) => void;
|
||||
onSeatSkillDirectiveChange: (agentId: string, enabled: boolean) => void;
|
||||
onSeatHumanValidationChange: (agentId: string, enabled: boolean) => void;
|
||||
onSeatModeChange: (agentId: string, mode: SeatMode | null) => void;
|
||||
/** 仅岗位协同入口启用;普通圆桌编辑器不显示岗位控件。 */
|
||||
positionConfigMode: boolean;
|
||||
@@ -1586,6 +1596,7 @@ function StagesColumn({
|
||||
onSplitSeat={onSplitSeat}
|
||||
onSeatModelChange={onSeatModelChange}
|
||||
onSeatSkillDirectiveChange={onSeatSkillDirectiveChange}
|
||||
onSeatHumanValidationChange={onSeatHumanValidationChange}
|
||||
onSeatModeChange={onSeatModeChange}
|
||||
positionConfigMode={positionConfigMode}
|
||||
positionOptions={positionOptions}
|
||||
@@ -1620,6 +1631,7 @@ function StageSection({
|
||||
onSplitSeat,
|
||||
onSeatModelChange,
|
||||
onSeatSkillDirectiveChange,
|
||||
onSeatHumanValidationChange,
|
||||
onSeatModeChange,
|
||||
positionConfigMode,
|
||||
positionOptions,
|
||||
@@ -1643,6 +1655,7 @@ function StageSection({
|
||||
onSplitSeat: (agentId: string) => void;
|
||||
onSeatModelChange: (agentId: string, model: string | null) => void;
|
||||
onSeatSkillDirectiveChange: (agentId: string, enabled: boolean) => void;
|
||||
onSeatHumanValidationChange: (agentId: string, enabled: boolean) => void;
|
||||
onSeatModeChange: (agentId: string, mode: SeatMode | null) => void;
|
||||
positionConfigMode: boolean;
|
||||
positionOptions: readonly PositionOption[];
|
||||
@@ -1809,6 +1822,7 @@ function StageSection({
|
||||
onSplit={() => onSplitSeat(seat.agent_id)}
|
||||
onModelChange={(model) => onSeatModelChange(seat.agent_id, model)}
|
||||
onSkillDirectiveChange={(enabled) => onSeatSkillDirectiveChange(seat.agent_id, enabled)}
|
||||
onHumanValidationChange={(enabled) => onSeatHumanValidationChange(seat.agent_id, enabled)}
|
||||
onSeatModeChange={(mode) => onSeatModeChange(seat.agent_id, mode)}
|
||||
showPositionConfig={positionConfigMode}
|
||||
positionOptions={positionOptions}
|
||||
@@ -1837,6 +1851,7 @@ function SeatStrip({
|
||||
onSplit,
|
||||
onModelChange,
|
||||
onSkillDirectiveChange,
|
||||
onHumanValidationChange,
|
||||
onSeatModeChange,
|
||||
showPositionConfig,
|
||||
positionOptions,
|
||||
@@ -1857,6 +1872,7 @@ function SeatStrip({
|
||||
onModelChange: (model: string | null) => void;
|
||||
/** 席位「会商技能识别强化」开关变更。 */
|
||||
onSkillDirectiveChange: (enabled: boolean) => void;
|
||||
onHumanValidationChange: (enabled: boolean) => void;
|
||||
/** 席位「推理深度覆盖」变更(null = 跟随链条级 seatMode)。 */
|
||||
onSeatModeChange: (mode: SeatMode | null) => void;
|
||||
/** 仅岗位协同入口展示的岗位配置。 */
|
||||
@@ -2058,6 +2074,38 @@ function SeatStrip({
|
||||
</div>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<button
|
||||
type="button"
|
||||
title="人工校验:该席位完成后暂停会商,等待用户恢复或输入修改意见"
|
||||
className={cn(
|
||||
"p-1 transition",
|
||||
R_CTRL,
|
||||
seat.human_validation
|
||||
? "bg-primary/10 text-primary"
|
||||
: "text-muted-foreground hover:bg-muted hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
<UserCheck className="size-3.5" />
|
||||
</button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-64 p-3">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="space-y-0.5">
|
||||
<p className="text-xs font-semibold text-foreground">人工校验</p>
|
||||
<p className="text-[11px] leading-relaxed text-muted-foreground">
|
||||
开启后,该席位所在的执行单元完成时会自动暂停。用户可直接点击“恢复会商”继续,或在下方输入修改意见后提交;不会新增校验卡片。
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={seat.human_validation ?? false}
|
||||
onCheckedChange={onHumanValidationChange}
|
||||
aria-label={`切换 ${seat.name || seat.agent_id} 的人工校验`}
|
||||
/>
|
||||
</div>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onDetail}
|
||||
|
||||
@@ -409,6 +409,10 @@ export default function RoundtablePlanningPage({
|
||||
// Step 2 每席位「技能识别强化」开关映射 {agentId: bool}:由所选业务链条里**每个席位**的同名
|
||||
// 配置决定(recommend 无链条 → 空 {})。透传给每个席位 run,与各席位智能体自身的开关取 OR。
|
||||
const [seatSkillDirectives, setSeatSkillDirectives] = useState<Record<string, boolean>>({});
|
||||
// Per-seat human-validation checkpoints from the selected business chain.
|
||||
// A checkpoint pauses Step 2 after the configured seat/stage completes and
|
||||
// reuses the existing resume button plus bottom intervention composer.
|
||||
const [humanValidations, setHumanValidations] = useState<Record<string, boolean>>({});
|
||||
// Step 2 每席位「推理深度覆盖」映射 {agentId: SeatMode|null}:由所选业务链条里**每个席位**单独配
|
||||
// 的推理深度决定(null/未配 → 跟随链条级 seatMode)。透传给席位 run(覆盖优先、否则跟随 seatMode)。
|
||||
// 「卡顿提速」用:把次要席位降到 flash 即可大幅缩短第二步耗时。
|
||||
@@ -573,6 +577,7 @@ export default function RoundtablePlanningPage({
|
||||
selectedModel,
|
||||
selectedMode: seatMode,
|
||||
seatSkillDirectives,
|
||||
humanValidations,
|
||||
seatModes,
|
||||
gatherFirst,
|
||||
orchestrationMode,
|
||||
@@ -1058,6 +1063,9 @@ export default function RoundtablePlanningPage({
|
||||
setSeatSkillDirectives(
|
||||
Object.fromEntries(result.agents.map((a) => [a.agent_id, a.seat_skill_directive ?? false])),
|
||||
);
|
||||
setHumanValidations(
|
||||
Object.fromEntries(result.agents.map((a) => [a.agent_id, a.human_validation ?? false])),
|
||||
);
|
||||
// 每席位推理深度覆盖:取所选业务链条里**每席位**单独配的 seatMode → {agentId: SeatMode|null}
|
||||
// 映射(recommend / 未配 → null,跟随链条级 seatMode)。
|
||||
setSeatModes(
|
||||
|
||||
@@ -123,6 +123,27 @@ cascade pragmas. The router is mounted canonically below
|
||||
schema-hidden compatibility prefix `/api/multi-agent/position-roundtable`.
|
||||
Clients may retry the compatibility route only for a framework/proxy-level
|
||||
`404 Not Found`; domain-level missing-session responses must remain real 404s.
|
||||
|
||||
Position roundtable selects the separately seeded built-in agent
|
||||
`position-roundtable-intent` by passing `intent_agent_id` to the shared
|
||||
`/api/intent/init` and `/api/intent/stream` endpoints. Its request lifecycle,
|
||||
files, and SSE protocol match `roundtable-intent`, but its cap is five
|
||||
**user-assistance rounds**. A single round may emit several independent
|
||||
`ask_clarification` tool calls; those calls are separate cards, not one card
|
||||
containing several numbered questions. Count that as one round by the
|
||||
tool-calling AI message, never by card count. Topic-only requests must request
|
||||
all material missing decisions as separate cards rather than being treated as a
|
||||
resolved intent; after the fifth set is answered it must emit completed final
|
||||
JSON without unresolved placeholders. The required arrays are
|
||||
`coreGoals`, `riskWarnings`, `keyPoints`, and `strategicSignificance`. Do not
|
||||
treat a fresh dedicated-agent `ask_clarification` as stale: it must win over
|
||||
a same-run premature `[INTENT_READY]` and leave the UI waiting for the user.
|
||||
Conversely, the prior turn’s historical clarification must not block the user
|
||||
reply from completing. Do not
|
||||
change `roundtable-intent`'s `{objective,constraints,assumptions}` contract for
|
||||
this feature. The position router accepts the new schema for activation and
|
||||
injects all four sections into downstream position-node and closing-agent
|
||||
context; legacy stored summaries are mapped read-only for compatibility.
|
||||
`/api/intent/init` must create the empty Step-1 thread through
|
||||
`multi_agent._create_thread_direct`, exactly like multi-agent initialization;
|
||||
do not restore the old HTTP loopback to `/api/threads`, because deployed
|
||||
@@ -436,6 +457,15 @@ Backs the zzJC / zzXD agent-chat left sidebar (「按类型聚合智能体 + 聊
|
||||
|
||||
### Position-collaboration foundation
|
||||
|
||||
### Roundtable business-chain human validation
|
||||
|
||||
The existing `/api/roundtable-chains` `seats` JSON also accepts the optional
|
||||
boolean `human_validation` field on each seat (`ChainSeatSchema`). It is a
|
||||
frontend Step 2 checkpoint, not a server-side approval task: after the marked
|
||||
seat completes (or, in a DAG, after its stage completes), the client pauses and
|
||||
uses the existing resume button or intervention composer to continue. No new
|
||||
database column, migration, or validation card is required.
|
||||
|
||||
The position-collaboration workspace is a separate frontend route and must not
|
||||
use the original roundtable coordinator or jobs. Its shared configuration
|
||||
integration point is the existing `/api/roundtable-chains` store: each `seats` JSON item
|
||||
@@ -1132,6 +1162,26 @@ the initial intent workspace plus the summary/action-plan closing agents. Do
|
||||
not delete a built-in id because historical chain nodes persist those ids;
|
||||
custom role ids may be added and removed.
|
||||
|
||||
### Position-roundtable task-scoped session history
|
||||
|
||||
`position_roundtable_sessions.external_task_id` is optional. When populated from the frontend route `taskId`, new rows set `task_scoped = true`: a task can have multiple sessions and all users opening that task see the same sessions, nodes and persisted conversation snapshots. When it is NULL/empty, keep the original `user_id`-scoped personal workspace behavior. `20260808_01` adds `task_scoped` with default `false` (so all historical records remain personal) plus the task/update-time index; it must not backfill or make `external_task_id` non-null.
|
||||
|
||||
### Roundtable artifact submission status
|
||||
|
||||
`roundtable_artifact_submissions` keeps task-level submission state for a
|
||||
generated deliverable and is deliberately separate from task details and any
|
||||
external task-system delivery. The API is
|
||||
`GET /api/roundtable/tasks/{taskId}/artifacts?submitted=true` and
|
||||
`PUT /api/roundtable/tasks/{taskId}/artifacts/submission`. All callers use the
|
||||
normal Gateway Bearer authentication; records are shared by task while
|
||||
`created_by`/`submitted_by`/`cancelled_by` are audit-only. The server derives a
|
||||
SHA-256 idempotency key from `taskId + sourceKey + path + revision`: submitting
|
||||
the same revision is an upsert, while cancellation only flips `submitted` and
|
||||
sets `cancelled_at` (it never deletes history). Store only the sandbox file
|
||||
reference (`threadId`, path, source/node/session fields, name/MIME and revision)
|
||||
and timestamps; do not persist Markdown content or call a formal delivery
|
||||
interface. Previews continue to read the DeerFlow artifact by `threadId + path`.
|
||||
|
||||
See `docs/` directory for detailed documentation:
|
||||
- [../README.md](../README.md) - Offline Docker wheelhouse preparation and startup workflow. The pinned versions in `../offline-runtime-requirements.txt` and `../start_backend.sh` must stay synchronized. `start_backend.sh` stays aligned with the deployment script and adds only the Redis wheel fallback line. The download target defaults to CPython 3.12 on Linux x86_64 and verifies dependency closure using wheelhouse only.
|
||||
- [CONFIGURATION.md](docs/CONFIGURATION.md) - Configuration options
|
||||
|
||||
@@ -123,7 +123,7 @@ FastAPI application providing REST endpoints for frontend integration:
|
||||
| `POST /api/skills/install` | Install skill from `.skill` archive |
|
||||
| `GET/POST /api/agents` | List visible agents or create a user-owned agent |
|
||||
| `GET/PUT/DELETE /api/agents/{id}` | Read, update, or delete an id-addressed agent |
|
||||
| `GET/POST/PUT/DELETE /api/roundtable-chains` | Manage user-owned roundtable business chains; each seat may optionally carry `position_id` for the separate position-collaboration workspace (the original roundtable ignores it) |
|
||||
| `GET/POST/PUT/DELETE /api/roundtable-chains` | Manage user-owned roundtable business chains; each seat may optionally carry `position_id` for the separate position-collaboration workspace, plus `human_validation` to mark a Step 2 client-side pause checkpoint after that seat/stage completes (the original roundtable has no extra validation card) |
|
||||
| `GET/PUT /api/business-mapping` | Read global business mappings. Updates to 3Q/6BF/7BF require an administrator; the 8BF public business-chain mapping is maintained exclusively by the trusted `lqq` account (derived from the authenticated email prefix). |
|
||||
| `GET/POST/PUT /api/position-roundtable/sessions` | Standalone position-collaboration sessions: freeze task/intent/chain snapshots, index one direct-agent node per seat, build upstream handoff context (including bounded UTF-8 excerpts of text artifacts), and make archived sessions read-only without invoking the original roundtable coordinator or jobs. Built-in summary/action-plan completion mirrors visible report text into a Markdown artifact when a model omits its final `write_file` call. `POST /sessions/{id}/nodes/{nodeKey}/reject` accepts an optional reason, marks the rejected delivery for rework, and invalidates affected downstream deliveries so they are regenerated in order. The same router is also mounted at `/api/multi-agent/position-roundtable/*` for intranet gateways that only forward the established multi-agent namespace; the compatibility mount is intentionally omitted from OpenAPI. |
|
||||
| `GET /api/memory` | Retrieve memory data |
|
||||
@@ -144,6 +144,8 @@ FastAPI application providing REST endpoints for frontend integration:
|
||||
|
||||
The separately deployed TaskCOP Vue app uses `POST /api/v1/auth/login/username` directly (its `username`, `userId`, or `yUserId` URL parameter identifies the user), so this compatibility flow does not depend on the retired Consumer login service. It calls the Gateway address configured as `b1ConsumerUrl` directly; it does not use a Vite `/api` reverse proxy. An empty TaskCOP store remains empty; task data is introduced through normal creation or the JSON import API. The Gateway CORS middleware always merges the local TaskCOP Vite origins `http://localhost:8080` and `http://127.0.0.1:8080`, including when `GATEWAY_CORS_ORIGINS` is set for another frontend. `scripts/env.sh` also includes them in its startup default. For a deployment, set `GATEWAY_CORS_ORIGINS` to the exact additional frontend origins that are allowed to call the Gateway.
|
||||
|
||||
Position-roundtable history supports two modes. A non-empty `external_task_id` from the frontend route's `taskId` creates a row with `task_scoped = true`, so all sessions, nodes and persisted conversation snapshots for that task are shared across users; `user_id` is then creator audit metadata only. When the field is absent or empty, the original per-user personal-session behavior remains unchanged. Alembic revision `20260808_01` adds `task_scoped` with the safe default `false` for historical rows plus the task/update-time index.
|
||||
|
||||
AI writing supports a sample-imitation mode: the frontend can upload or paste a sample article, the Gateway extracts text for document files, and the `ai_writing` graph runs a `sample_analyzer` node before normal intent/research/outline/draft stages. The resulting style profile is injected into outline and draft prompts with explicit guardrails against copying source sentences, facts, names, or data.
|
||||
|
||||
### Custom Agents
|
||||
@@ -479,6 +481,24 @@ checkpoint or sandbox-output volume is replaced. Apply Alembic revision
|
||||
|
||||
Its live intent conversation still uses the shared `/api/intent/init` and
|
||||
`/api/intent/stream` endpoints used by the original multi-agent roundtable.
|
||||
Position roundtable identifies itself with `intent_agent_id: "position-roundtable-intent"`;
|
||||
this is a separately seeded built-in agent, not an alias of `roundtable-intent`.
|
||||
It preserves the same thread, SSE streaming, and file-reading lifecycle as the
|
||||
generic Step-1 agent, but has its own **at-most-five user-assistance-round**
|
||||
brake. A round is one AI turn plus the user reply, not one tool call: the
|
||||
dedicated agent may emit several independent `ask_clarification` calls in the
|
||||
same turn, which the frontend renders as several separate selection cards and
|
||||
submits together. A topic-only request is not considered resolved: the agent
|
||||
asks for every independent missing decision (such as scope, decision use, or
|
||||
task constraints) as separate cards. For the dedicated agent, a fresh
|
||||
`ask_clarification` emitted in a stream is a strict user-input pause and wins over any same-run premature
|
||||
`[INTENT_READY]`; a historical clarification from the prior turn does not
|
||||
block the user answer from completing. Its final
|
||||
`[INTENT_READY]` JSON contains four string arrays: `coreGoals`, `riskWarnings`,
|
||||
`keyPoints`, and `strategicSignificance`; it must contain completed conclusions,
|
||||
not “待确认” or other unresolved placeholders. The multi-agent endpoint remains
|
||||
backwards compatible when this optional field is omitted and continues to emit
|
||||
`objective`, `constraints`, and `assumptions`.
|
||||
`/api/intent/init` creates its empty thread directly through the in-process
|
||||
thread store/checkpointer, matching multi-agent initialization and avoiding a
|
||||
deployment-sensitive `127.0.0.1:<gateway-port>` loopback. If initial checkpoint
|
||||
@@ -507,3 +527,23 @@ is required. It is the initial intent-identification workspace and owns the
|
||||
summary/action-plan closing agents. Built-in rows retain stable ids so
|
||||
historical chain nodes remain readable; they can be edited or disabled but not
|
||||
deleted. Custom roles may be freely added or removed.
|
||||
|
||||
## Roundtable artifact submission status
|
||||
|
||||
The task-scoped roundtable workbench exposes a lightweight submission-status
|
||||
API for generated deliverables:
|
||||
|
||||
- `GET /api/roundtable/tasks/{taskId}/artifacts?submitted=true` returns the
|
||||
submitted artifact references for a task (or `items: []`).
|
||||
- `PUT /api/roundtable/tasks/{taskId}/artifacts/submission` records
|
||||
`submitted: true` or cancels it with `submitted: false`.
|
||||
|
||||
Both routes use the normal Gateway `Authorization: Bearer <token>` middleware.
|
||||
The record is shared by `taskId`; the authenticated user is retained only in
|
||||
audit columns. Its server-owned idempotency key is
|
||||
`taskId + sourceKey + path + revision`. Repeating the same submitted payload
|
||||
returns the existing record; cancellation updates its state and timestamp
|
||||
without deleting the audit row. DeerFlow stores only the artifact reference
|
||||
(`threadId` + sandbox `path`, plus the optional session/node/name/MIME fields),
|
||||
never the Markdown body and never a task-system delivery. Continue to preview
|
||||
the file through the existing thread-artifact endpoint.
|
||||
@@ -65,8 +65,9 @@ from app.gateway.routers import (
|
||||
recommend,
|
||||
flow_extract,
|
||||
recommended_questions,
|
||||
roundtable_chains,
|
||||
roundtable_diagnostics,
|
||||
roundtable_chains,
|
||||
roundtable_artifact_submissions,
|
||||
roundtable_diagnostics,
|
||||
roundtable_draft_shares,
|
||||
roundtable_drafts,
|
||||
roundtable_jobs,
|
||||
@@ -1465,8 +1466,11 @@ This gateway provides custom endpoints for models, MCP configuration, skills, an
|
||||
# Roundtable-planning drafts + recommendation history at /api/roundtable-drafts
|
||||
app.include_router(roundtable_drafts.router)
|
||||
|
||||
# Task-scoped roundtable drafts (taskId 深链聊天记录,独立存、不分权) at /api/roundtable-task-drafts
|
||||
app.include_router(roundtable_task_drafts.router)
|
||||
# Task-scoped roundtable drafts (taskId 深链聊天记录,独立存、不分权) at /api/roundtable-task-drafts
|
||||
app.include_router(roundtable_task_drafts.router)
|
||||
|
||||
# Task-scoped artifact submission status; stores references only, never artifact content.
|
||||
app.include_router(roundtable_artifact_submissions.router)
|
||||
|
||||
# Step3 流程图结构化抽取 + 校验 (SSE) at /api/flow-extract
|
||||
app.include_router(flow_extract.router)
|
||||
|
||||
@@ -305,6 +305,11 @@ async def langgraph_runtime(app: FastAPI) -> AsyncGenerator[None, None]:
|
||||
|
||||
app.state.task_report_store = make_task_report_store(sf)
|
||||
|
||||
from deerflow.persistence.roundtable_artifact_submissions import make_roundtable_artifact_submission_store
|
||||
|
||||
# Task-scoped artifact submission status: shared by task; actor is audit-only.
|
||||
app.state.roundtable_artifact_submission_store = make_roundtable_artifact_submission_store(sf)
|
||||
|
||||
from deerflow.persistence.parallel_agent_tasks import make_parallel_agent_task_store
|
||||
|
||||
app.state.parallel_agent_task_store = make_parallel_agent_task_store(sf)
|
||||
|
||||
@@ -58,6 +58,10 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
INTENT_AGENT_ID = "roundtable-intent"
|
||||
# Position roundtable deliberately owns a separate intent agent. Its dialogue
|
||||
# lifecycle is shared with Step 1 above, but its final structured hand-off is
|
||||
# different and must not change the multi-agent roundtable contract.
|
||||
POSITION_INTENT_AGENT_ID = "position-roundtable-intent"
|
||||
RECOMMENDER_AGENT_ID = "roundtable-recommender"
|
||||
COORDINATOR_AGENT_ID = "roundtable-coordinator"
|
||||
# Step 3「结果绘制」用的方案可视化总结智能体:读各席位交付 + 共识,画自包含图表 HTML。
|
||||
@@ -92,6 +96,7 @@ _ASSETS_DIR = Path(__file__).parent / "_roundtable_seed_assets"
|
||||
# roundtable-dashboard 支撑 Step 3 大屏多页结构化数据(report-json + 问答/增量改)。
|
||||
_FUNCTIONAL_AGENT_IDS: tuple[str, ...] = (
|
||||
INTENT_AGENT_ID,
|
||||
POSITION_INTENT_AGENT_ID,
|
||||
RECOMMENDER_AGENT_ID,
|
||||
COORDINATOR_AGENT_ID,
|
||||
REPORT_AGENT_ID,
|
||||
@@ -109,14 +114,14 @@ def _ensure_one(agent_id: str) -> bool:
|
||||
"""Copy the verified SOUL.md + config.yaml for one functional agent into
|
||||
``.deer-flow/agents/<id>/`` if that directory is missing.
|
||||
|
||||
Returns True if the files were just created, False if the directory already
|
||||
existed (we never overwrite — respect any local edits) or the seed assets
|
||||
are missing.
|
||||
"""
|
||||
agent_dir = get_paths().agent_dir(agent_id)
|
||||
if agent_dir.exists():
|
||||
return False
|
||||
The position-roundtable intent agent is an implementation-owned compatibility
|
||||
contract: unlike user-managed agents, its schema must stay aligned with the
|
||||
position workspace. Its two seed files are therefore refreshed when they
|
||||
differ, so a previously seeded incorrect prompt is repaired after deployment.
|
||||
|
||||
Returns True if files were created or refreshed, False if no work was needed
|
||||
or the seed assets are missing.
|
||||
"""
|
||||
src_dir = _ASSETS_DIR / agent_id
|
||||
if not src_dir.is_dir():
|
||||
# Assets should always ship with the code; if they don't, surface a loud
|
||||
@@ -128,6 +133,25 @@ def _ensure_one(agent_id: str) -> bool:
|
||||
)
|
||||
return False
|
||||
|
||||
agent_dir = get_paths().agent_dir(agent_id)
|
||||
if agent_dir.exists():
|
||||
if agent_id != POSITION_INTENT_AGENT_ID:
|
||||
# Other built-in agents may have been tuned on a deployed machine;
|
||||
# preserve the long-standing no-overwrite behavior for them.
|
||||
return False
|
||||
|
||||
refreshed = False
|
||||
for fname in _SEED_FILES:
|
||||
src = src_dir / fname
|
||||
if not src.exists():
|
||||
continue
|
||||
target = agent_dir / fname
|
||||
source_bytes = src.read_bytes()
|
||||
if not target.exists() or target.read_bytes() != source_bytes:
|
||||
target.write_bytes(source_bytes)
|
||||
refreshed = True
|
||||
return refreshed
|
||||
|
||||
agent_dir.mkdir(parents=True, exist_ok=True)
|
||||
for fname in _SEED_FILES:
|
||||
src = src_dir / fname
|
||||
@@ -138,9 +162,9 @@ def _ensure_one(agent_id: str) -> bool:
|
||||
|
||||
|
||||
def ensure_roundtable_functional_agents() -> list[str]:
|
||||
"""Seed the three roundtable functional agents (``roundtable-intent`` /
|
||||
``roundtable-recommender`` / ``roundtable-coordinator``) if their on-disk
|
||||
directories are missing. Idempotent — fast no-op when all exist.
|
||||
"""Seed the built-in roundtable functional agents when their on-disk
|
||||
directories are missing, and refresh the implementation-owned position
|
||||
intent schema when it has changed. Idempotent after synchronization.
|
||||
|
||||
Called from the startup lifespan and from the entry of intent/init,
|
||||
intent/stream, recommend/stream, and multi_agent/init so the routes
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
# 岗位会商任务意图理解智能体
|
||||
|
||||
你是岗位多智能体会商 Step 1 的“意图理解专员”。你的唯一职责是把用户输入背后的任务意图结构化后交给后续岗位业务链处理。
|
||||
|
||||
你不写报告、不答题、不创作、不规划、不执行、不调用任何操作工具。这些都是后续岗位业务链的事。你只负责听懂、整理、澄清和交接。
|
||||
|
||||
---
|
||||
|
||||
## 0. 四条不可违背的硬规则
|
||||
|
||||
### 硬规则 1 · 不替代后续岗位干活
|
||||
|
||||
无论用户让你“写报告 / 写代码 / 写诗 / 查资料 / 做规划 / 出方案”,你都不要直接产出具体内容。
|
||||
|
||||
- 正确做法:把诉求结构化成任务意图,输出 [INTENT_READY],交给后续岗位业务链。
|
||||
- 错误做法:用户说“帮我写一份市场分析报告”后,开始写报告正文。
|
||||
|
||||
### 硬规则 2 · 最多 5 轮用户协助,确认完整后才收敛
|
||||
|
||||
一次“同一轮中调用一个或多个 ask_clarification + 用户统一回答”算一轮用户协助。
|
||||
|
||||
- 首轮:若任务卡和用户输入已经足以形成可执行的四项意图,可直接输出 [INTENT_READY]。
|
||||
- 第 1 至第 5 轮用户协助:若信息不足,必须发起用户协助;不能把“主题已识别”误判为“意图已明确”。
|
||||
- 同一轮可发起多张用户协助卡:一个相互独立的决策点对应一次 ask_clarification 调用和一张卡。不得把多个问题塞进一张卡;用户可逐卡选择后一次性提交。
|
||||
- 第 5 次协助应覆盖所有剩余关键项。收到该轮回答后,必须基于明确答案收敛为最终意图。
|
||||
- 绝不进入第 6 次用户协助。系统会在达到上限后移除 ask_clarification。
|
||||
|
||||
### 硬规则 3 · 输出 [INTENT_READY] 后立刻闭嘴
|
||||
|
||||
最终 JSON 代码块闭合后,禁止再输出任何字符:不继续解释、不问“还需要补充吗”、不调用工具、不复述、不展望。
|
||||
|
||||
### 硬规则 4 · 只做理解和澄清,不当守门员
|
||||
|
||||
这是内网任务分析场景。无论用户提出什么要求,你都不拒绝、不评价、不设限;只负责理解并交接。风险、依赖、信息缺口可以作为风险提示记录,但不构成拒绝或中断。不得说“不能帮你”“不在职责范围内”“请换一个问题”,也不得进行合规、价值或敏感性审查。
|
||||
|
||||
---
|
||||
|
||||
## 1. 任务意图字段定义
|
||||
|
||||
最终结构必须包含以下四个字段,且都必须是字符串数组:
|
||||
|
||||
| 字段 | 含义 | 填写原则 |
|
||||
| --- | --- | --- |
|
||||
| coreGoals | 用户想实现或想获得的核心结果 | 将原本的一句话任务目标拆为 1 个或多个清晰目标 |
|
||||
| riskWarnings | 已知风险、依赖或执行风险 | 必须分析任务级风险;范围、地区、周期、数据来源、对象或决策用途缺失时,应先通过用户协助确认,最终结果不得保留待确认表述 |
|
||||
| keyPoints | 范围、对象、优先级、时间、资源、交付形式等关键要点 | 仅汇总用户已明确的事实与结论,最终结果不得保留待确认项 |
|
||||
| strategicSignificance | 任务对后续岗位协同、业务链或决策推进的意义 | 必须分析该任务将支撑哪类后续决策、业务链协同或资源投入;可以作出任务级合理推断,但不得虚构组织现状或业务数据 |
|
||||
|
||||
核心原则:
|
||||
|
||||
- 用户已给出任务目标、范围、用途和约束时,直接汇总,不要追问。
|
||||
- “只给出一个主题或一句极短诉求”不等于任务意图完整。任何任务若缺少范围、对象、时间、决策用途、重点维度或成功标准等关键信息时,必须请求用户协助。
|
||||
- 同一轮应识别所有仍会影响后续业务链的关键缺口,并为每个相互独立的缺口各调用一次 ask_clarification,避免一个问题一轮地消耗用户;不要把它们合并为一张多题卡。
|
||||
- 最终 [INTENT_READY] 中禁止出现“待确认”“未明确”“需补充”“暂无”“缺少”等未完成表述;信息不足时继续协助,不得提前交接。
|
||||
- 空数组只适用于用户明确说明“不涉及/没有”这一项时。
|
||||
|
||||
---
|
||||
|
||||
## 2. 工作流
|
||||
|
||||
~~~
|
||||
用户输入
|
||||
↓
|
||||
是否能形成可执行的四项意图?
|
||||
├─ 能 → 立即输出 [INTENT_READY],结束
|
||||
└─ 不能 → 同一轮可分别调多个 ask_clarification(每张卡只问一个决策点)
|
||||
↓
|
||||
用户回答 → 再判断
|
||||
↓
|
||||
最多 5 轮用户协助 → 收到明确答案后输出 [INTENT_READY]
|
||||
~~~
|
||||
|
||||
### 提问前自检清单
|
||||
|
||||
任一项为“否”,就应发起用户协助;同轮把全部为“否”的独立决策点分别做成卡片:
|
||||
|
||||
1. 我是否不仅能写出核心目标,也能明确主要分析范围或决策用途?
|
||||
2. 我是否能基于任务给出至少一项任务级风险提示和战略意义?
|
||||
3. 用户是否已经在任务卡、当前消息或历史消息中给出这些关键信息?
|
||||
4. 这些缺口是否已经在本轮协助中一次性列出?
|
||||
5. 是否已达到第 5 次用户协助?若是,等待用户对最后一组问题的回答,不再发起第 6 次协助。
|
||||
|
||||
---
|
||||
|
||||
## 3. 唯一允许的工具:ask_clarification
|
||||
|
||||
除 ask_clarification 外,禁止调用任何工具、技能或操作。尤其禁止搜索、写文件、读写沙箱、展示文件、创建任务、编排智能体或生成交付物。
|
||||
|
||||
当任务只有主题、或缺少决定范围/用途/风险判断的关键信息时,必须调用它。每个协助问题只包含一个决策点;同一轮需要确认多个点时,连续调用多次工具,生成多张独立选择卡:
|
||||
|
||||
~~~
|
||||
ask_clarification(
|
||||
question="本次分析主要面向哪个范围?",
|
||||
clarification_type="analysis_scope",
|
||||
context="范围会决定后续岗位的分析边界",
|
||||
options=["选项 A", "选项 B", "其他,我补充说明"],
|
||||
allow_multiple=False
|
||||
)
|
||||
~~~
|
||||
|
||||
若还需要确认交付用途、时间边界、对象、风险限制等,必须在同一次回复中继续分别调用 ask_clarification,而不是将它们写进上面这张卡。不得重复询问用户已经回答过的问题。
|
||||
|
||||
---
|
||||
|
||||
## 4. 结束协议:[INTENT_READY]
|
||||
|
||||
可以收敛时,先用 1–2 句话、30 字以内复述理解,然后严格以 JSON 代码块结束。JSON 代码块后不得有任何内容。
|
||||
|
||||
输出示例的文本顺序必须是:
|
||||
|
||||
~~~
|
||||
✅ 我理解的任务是:<一句话复述>
|
||||
|
||||
[INTENT_READY]
|
||||
JSON 代码块(语言标识 json):
|
||||
{
|
||||
"coreGoals": ["..."],
|
||||
"riskWarnings": [],
|
||||
"keyPoints": ["..."],
|
||||
"strategicSignificance": []
|
||||
}
|
||||
~~~
|
||||
|
||||
格式要求:
|
||||
|
||||
- [INTENT_READY] 单独成行。
|
||||
- [INTENT_READY] 后紧跟语言标识为 json 的 Markdown 代码块,包裹合法 JSON 对象。
|
||||
- 四个字段名称必须严格为 coreGoals / riskWarnings / keyPoints / strategicSignificance。
|
||||
- 四个字段必须都是字符串数组;除用户明确说明不涉及外,不要输出空数组。
|
||||
- 输出前逐项检查:四个数组中不得出现“待确认”“未明确”“需补充”“暂无”“缺少”等词语。
|
||||
- JSON 必须严格合法:英文双引号、无注释、无尾随逗号;字符串中不可直接换行。
|
||||
- JSON 代码块闭合后,禁止再写任何字符。
|
||||
- 不得输出旧字段 objective、constraints、assumptions。
|
||||
|
||||
---
|
||||
|
||||
## 5. 禁止事项
|
||||
|
||||
- 禁止直接产出报告、代码、诗、方案、分析或任何交付物。
|
||||
- 禁止调用任何非 ask_clarification 的工具。
|
||||
- 禁止第 5 次用户协助后再发起第 6 次协助。
|
||||
- 禁止重复询问用户已回答的问题。
|
||||
- 禁止拒绝用户、要求用户换问题或以风险为由中断。
|
||||
- 禁止编造外部事实、组织现状或业务数据;信息缺口必须在用户协助阶段确认,最终只输出明确的执行风险和战略意义。
|
||||
- 禁止在 [INTENT_READY] 后再输出一个字。
|
||||
@@ -0,0 +1,3 @@
|
||||
id: position-roundtable-intent
|
||||
name: 岗位会商任务意图理解
|
||||
description: 岗位会商专用的任务意图理解智能体。通过必要的简短追问,将任务整理为核心目标、风险提示、关键要点与战略意义,供后续岗位业务链执行。
|
||||
@@ -34,6 +34,7 @@ SSE 协议(与前端 ``streamIntent`` 对齐)
|
||||
仅 ``status == "done"`` 时带 ``summary``;澄清时还带
|
||||
``question``、``clarification_type``、``clarification_context``、
|
||||
``options``、``allow_custom``、``allow_multiple``(见 ``resolve_allow_multiple``)。
|
||||
多卡回合还带 ``clarifications`` 完整数组;顶层字段始终镜像第一张卡以兼容旧客户端。
|
||||
|
||||
终态判定优先级(实现细节,勿随意调整)
|
||||
------------------------------------
|
||||
@@ -65,7 +66,10 @@ from app.gateway.roundtable_diag import record_foreground_diag
|
||||
|
||||
# Reuse the building blocks already in multi_agent.py — keeps both routers
|
||||
# identical in connection handling, payload shape, and error mapping.
|
||||
from app.gateway.routers._roundtable_seed import ensure_roundtable_functional_agents
|
||||
from app.gateway.routers._roundtable_seed import (
|
||||
POSITION_INTENT_AGENT_ID,
|
||||
ensure_roundtable_functional_agents,
|
||||
)
|
||||
from app.gateway.routers.multi_agent import (
|
||||
_ROUNDTABLE_THREAD_METADATA,
|
||||
_auth_headers,
|
||||
@@ -87,6 +91,7 @@ router = APIRouter(prefix="/api/intent", tags=["intent"])
|
||||
|
||||
# 内置 agent 目录名,须与 ``.deer-flow/agents/roundtable-intent/`` 一致。
|
||||
INTENT_AGENT_ID = "roundtable-intent"
|
||||
_SUPPORTED_INTENT_AGENT_IDS = frozenset({INTENT_AGENT_ID, POSITION_INTENT_AGENT_ID})
|
||||
|
||||
# SOUL 规定的交接信号:``[INTENT_READY]`` + markdown json 代码块。
|
||||
# group(1) 解析为 IntentSummary;解析失败则继续走澄清/asking 分支。
|
||||
@@ -96,7 +101,49 @@ _INTENT_READY_PATTERN = re.compile(
|
||||
)
|
||||
|
||||
|
||||
def _intent_thread_metadata(task_context: dict[str, Any] | None) -> dict[str, Any]:
|
||||
def _requested_intent_agent_id(payload: dict[str, Any]) -> str:
|
||||
"""Resolve the explicitly supported Step-1 agent without opening a route
|
||||
for arbitrary custom-agent execution.
|
||||
|
||||
Existing multi-agent callers omit the field and therefore keep using
|
||||
``roundtable-intent``. Position roundtable sends the dedicated ID so its
|
||||
prompt and final JSON schema remain isolated.
|
||||
"""
|
||||
requested = str(payload.get("intent_agent_id") or "").strip()
|
||||
if not requested:
|
||||
return INTENT_AGENT_ID
|
||||
if requested not in _SUPPORTED_INTENT_AGENT_IDS:
|
||||
raise HTTPException(status_code=400, detail="Unsupported intent agent")
|
||||
return requested
|
||||
|
||||
|
||||
def _clarification_blocks_ready(
|
||||
intent_agent_id: str,
|
||||
clarification_calls: Any,
|
||||
*,
|
||||
is_fresh: bool,
|
||||
) -> bool:
|
||||
"""Position intent must wait for a fresh clarification answer.
|
||||
|
||||
The generic Step-1 route intentionally preserves READY-first behavior for
|
||||
stale tool calls in historical snapshots. Position roundtable instead has
|
||||
a four-part hand-off whose missing context is requested interactively, so
|
||||
a newly dispatched clarification is a strict terminal pause. A historical
|
||||
tool call from the preceding user-assistance turn must not block the next
|
||||
user answer from reaching READY.
|
||||
"""
|
||||
return (
|
||||
intent_agent_id == POSITION_INTENT_AGENT_ID
|
||||
and bool(clarification_calls)
|
||||
and is_fresh
|
||||
)
|
||||
|
||||
|
||||
def _intent_thread_metadata(
|
||||
task_context: dict[str, Any] | None,
|
||||
*,
|
||||
intent_agent_id: str = INTENT_AGENT_ID,
|
||||
) -> dict[str, Any]:
|
||||
"""Build task-scoped metadata for a newly-created intent thread.
|
||||
|
||||
Normal roundtable Step 1 calls still use the original system-thread tag.
|
||||
@@ -122,6 +169,8 @@ def _intent_thread_metadata(task_context: dict[str, Any] | None) -> dict[str, An
|
||||
"position_roundtable_phase": "intent",
|
||||
}
|
||||
)
|
||||
if intent_agent_id == POSITION_INTENT_AGENT_ID:
|
||||
metadata["position_roundtable_intent_agent_id"] = intent_agent_id
|
||||
return metadata
|
||||
|
||||
|
||||
@@ -190,6 +239,32 @@ def _count_past_clarifications(messages: list[dict[str, Any]]) -> int:
|
||||
return count
|
||||
|
||||
|
||||
def _count_past_clarification_rounds(messages: list[dict[str, Any]]) -> int:
|
||||
"""Count completed assistance *rounds*, rather than question cards.
|
||||
|
||||
The generic roundtable agent retains its historic three-tool-call brake.
|
||||
Position roundtable deliberately lets one model turn emit several
|
||||
independent ``ask_clarification`` cards, so using the tool-call count
|
||||
there would accidentally spend all five user-assistance rounds at once.
|
||||
One AI message containing one or more clarification calls is one round.
|
||||
"""
|
||||
if not isinstance(messages, list):
|
||||
return 0
|
||||
rounds = 0
|
||||
for msg in messages:
|
||||
if not isinstance(msg, dict):
|
||||
continue
|
||||
if (msg.get("type") or "").lower() not in ("ai", "aimessage", "aimessagechunk"):
|
||||
continue
|
||||
if any(
|
||||
(tc.get("name") or "").lower() == "ask_clarification"
|
||||
for tc in msg.get("tool_calls") or []
|
||||
if isinstance(tc, dict)
|
||||
):
|
||||
rounds += 1
|
||||
return rounds
|
||||
|
||||
|
||||
async def _fetch_thread_messages(
|
||||
client: httpx.AsyncClient,
|
||||
base: str,
|
||||
@@ -225,8 +300,18 @@ async def _fetch_thread_messages(
|
||||
|
||||
|
||||
# 硬上限:超过这个轮数,无论模型怎么想,都强制移除 ask_clarification 工具。
|
||||
# 与 SOUL.md §0 「硬规则 2」对齐——"绝不存在第 4 轮"。
|
||||
# 通用会商沿用 3 次工具调用的历史保护;岗位会商按"一轮可多张卡"计数,
|
||||
# 允许最多 5 次用户协助。
|
||||
_MAX_CLARIFICATION_ROUNDS = 3
|
||||
_POSITION_MAX_CLARIFICATION_ROUNDS = 5
|
||||
|
||||
|
||||
def _max_clarification_rounds(intent_agent_id: str) -> int:
|
||||
return (
|
||||
_POSITION_MAX_CLARIFICATION_ROUNDS
|
||||
if intent_agent_id == POSITION_INTENT_AGENT_ID
|
||||
else _MAX_CLARIFICATION_ROUNDS
|
||||
)
|
||||
|
||||
|
||||
def _is_repeated_clarification(
|
||||
@@ -310,6 +395,7 @@ async def init_intent(request: Request, payload: dict = Body(...)) -> dict[str,
|
||||
# 调用前自检:内网部署 .deer-flow/ 被 gitignore,首次启动时本 agent 目录可能不存在,
|
||||
# 缺失则就地用嵌入模板补建,避免下一步 /stream 报 500。
|
||||
ensure_roundtable_functional_agents()
|
||||
intent_agent_id = _requested_intent_agent_id(payload)
|
||||
|
||||
# Keep Step-1 initialization aligned with multi-agent initialization:
|
||||
# create the empty thread in-process rather than looping back through
|
||||
@@ -321,7 +407,7 @@ async def init_intent(request: Request, payload: dict = Body(...)) -> dict[str,
|
||||
try:
|
||||
thread_id = await _create_thread_direct(
|
||||
request,
|
||||
metadata=_intent_thread_metadata(task_context),
|
||||
metadata=_intent_thread_metadata(task_context, intent_agent_id=intent_agent_id),
|
||||
)
|
||||
except HTTPException:
|
||||
# 上游已用结构化方式失败,原样传给前端不需要二次包装。
|
||||
@@ -341,7 +427,7 @@ async def init_intent(request: Request, payload: dict = Body(...)) -> dict[str,
|
||||
raise HTTPException(status_code=500, detail=diagnostic) from exc
|
||||
return {
|
||||
"status": "success",
|
||||
"agent_id": INTENT_AGENT_ID,
|
||||
"agent_id": intent_agent_id,
|
||||
"thread_id": thread_id,
|
||||
}
|
||||
|
||||
@@ -363,6 +449,7 @@ async def stream_intent(request: Request, payload: dict = Body(...)) -> Streamin
|
||||
}
|
||||
"""
|
||||
thread_id = str(payload.get("thread_id") or "").strip()
|
||||
intent_agent_id = _requested_intent_agent_id(payload)
|
||||
message = str(payload.get("message") or "").strip()
|
||||
# 不写死任何默认模型名:空串会让 lead_agent._resolve_model_name() 回退到
|
||||
# config.yaml 的 models[0],与 /api/ai-writing 等其它路由一致,内网部署只配
|
||||
@@ -386,21 +473,30 @@ async def stream_intent(request: Request, payload: dict = Body(...)) -> Streamin
|
||||
|
||||
base = _loopback_base(request)
|
||||
headers = _auth_headers(request)
|
||||
fallback_instruction = (
|
||||
"四个岗位会商字段都必须保留为字符串数组,依据已获得的用户确认形成明确结论,"
|
||||
"不得写待确认、未明确、需补充、暂无或缺少"
|
||||
if intent_agent_id == POSITION_INTENT_AGENT_ID
|
||||
else "缺的字段用 assumptions 兜底"
|
||||
)
|
||||
|
||||
async def stream_generator() -> AsyncIterator[str]:
|
||||
# ASGITransport:进程内直调本机 ASGI app,**不走 TCP / 不经过网络栈**,
|
||||
# 因此既无须 trust_env=False 防代理,也不存在 loopback 40s 超时这种坑。
|
||||
async with _make_loopback_client(request) as client:
|
||||
try:
|
||||
# —— 3 轮硬上限兜底 ——
|
||||
# 在发起 run 之前先读一次 thread state,数当前 ask_clarification 已发出次数:
|
||||
# past=0/1 → 正常,不动 message,不动工具白名单
|
||||
# past=2(本轮即将变成第 3 轮)→ 给消息加前缀,强提示"必须 INTENT_READY"
|
||||
# past≥3 → 直接把 ask_clarification 也加进 excluded_tools,工具物理消失
|
||||
# 这一步是个"刹车":SOUL 让模型自律,这里让系统兜底。
|
||||
past_clarifications = _count_past_clarifications(
|
||||
await _fetch_thread_messages(client, base, headers, thread_id)
|
||||
# —— 澄清轮次硬上限兜底 ——
|
||||
# 通用会商保持原来的 3 次 ask 工具调用上限;岗位会商允许一个
|
||||
# AI turn 同时产生多张独立协助卡,所以必须按 AI 消息(一次
|
||||
# "提问 + 用户回答")计轮,不能按卡片数计轮。
|
||||
past_messages = await _fetch_thread_messages(client, base, headers, thread_id)
|
||||
past_clarifications = _count_past_clarifications(past_messages)
|
||||
past_rounds = (
|
||||
_count_past_clarification_rounds(past_messages)
|
||||
if intent_agent_id == POSITION_INTENT_AGENT_ID
|
||||
else past_clarifications
|
||||
)
|
||||
max_rounds = _max_clarification_rounds(intent_agent_id)
|
||||
|
||||
# 1. ask_clarification 的工具白名单——超过硬上限就移除。
|
||||
base_excluded_tools = [
|
||||
@@ -420,13 +516,13 @@ async def stream_intent(request: Request, payload: dict = Body(...)) -> Streamin
|
||||
"task",
|
||||
"write_todos",
|
||||
]
|
||||
if past_clarifications >= _MAX_CLARIFICATION_ROUNDS:
|
||||
if past_rounds >= max_rounds:
|
||||
base_excluded_tools.append("ask_clarification")
|
||||
logger.info(
|
||||
"intent stream: past_clarifications=%d >= %d, force-disabling "
|
||||
"intent stream: past_rounds=%d >= %d, force-disabling "
|
||||
"ask_clarification to break the loop",
|
||||
past_clarifications,
|
||||
_MAX_CLARIFICATION_ROUNDS,
|
||||
past_rounds,
|
||||
max_rounds,
|
||||
)
|
||||
|
||||
# 带了上传文件时,解锁「读」类工具(read_file / ls / grep / view_image),
|
||||
@@ -440,22 +536,42 @@ async def stream_intent(request: Request, payload: dict = Body(...)) -> Streamin
|
||||
# 2. message 前缀——给模型一个明确的"本轮必须收敛"信号。
|
||||
# 仅文件、无文本时给一句兜底引导,让模型先读文件再澄清意图。
|
||||
effective_message = message or "我上传了文件,请先阅读文件内容,再据此理解并澄清我的任务意图。"
|
||||
if past_clarifications >= _MAX_CLARIFICATION_ROUNDS:
|
||||
if intent_agent_id == POSITION_INTENT_AGENT_ID and past_rounds < max_rounds:
|
||||
# The position flow needs an actionable four-part hand-off,
|
||||
# not merely a recognizable topic. One turn may ask several
|
||||
# independent decisions, each rendered as its own selection
|
||||
# card by the existing Step-1 UI.
|
||||
effective_message = (
|
||||
f"[系统强制] 已澄清 {past_clarifications} 轮,触发硬上限。"
|
||||
f"本轮请直接输出 [INTENT_READY],缺的字段用 assumptions 兜底,"
|
||||
"[岗位会商收敛检查] 仅识别出主题不等于意图已明确。"
|
||||
"若当前任务还无法判断分析范围、决策用途、关键风险或战略意义,"
|
||||
"请在同一次回复中为每个相互独立的关键缺口分别调用一次 "
|
||||
"ask_clarification;每个工具调用只能问一个决策点,不能把多项"
|
||||
"问题合并成一张卡片。用户会一次性回答这些卡片。"
|
||||
"如果四项意图已经足够明确,则直接输出最终结果。"
|
||||
"不要以风险提示和战略意义为空的 [INTENT_READY] 结束。"
|
||||
"本轮是第 %d/%d 轮用户协助;第 %d 轮若仍有缺口,必须把所有"
|
||||
"剩余关键缺口分别发成卡片,收到回答后立即收敛。\n\n"
|
||||
f"用户最新输入:{effective_message}"
|
||||
) % (past_rounds + 1, max_rounds, max_rounds)
|
||||
if past_rounds >= max_rounds:
|
||||
effective_message = (
|
||||
f"[系统强制] 已澄清 {past_rounds} 轮,触发硬上限。"
|
||||
f"本轮请直接输出 [INTENT_READY],{fallback_instruction},"
|
||||
f"绝对不要再调任何工具,也不要再询问任何问题。\n\n"
|
||||
f"用户最新输入:{message}"
|
||||
)
|
||||
elif past_clarifications >= _MAX_CLARIFICATION_ROUNDS - 1:
|
||||
elif (
|
||||
intent_agent_id != POSITION_INTENT_AGENT_ID
|
||||
and past_rounds >= max_rounds - 1
|
||||
):
|
||||
effective_message = (
|
||||
f"[系统提示] 已澄清 {past_clarifications} 轮,这是最后一轮。"
|
||||
f"本轮请直接输出 [INTENT_READY],未明确的字段用 assumptions 兜底。\n\n"
|
||||
f"[系统提示] 已澄清 {past_rounds} 轮,这是最后一轮。"
|
||||
f"本轮请直接输出 [INTENT_READY],{fallback_instruction}。\n\n"
|
||||
f"用户最新输入:{message}"
|
||||
)
|
||||
|
||||
body = _run_payload(
|
||||
agent_name=INTENT_AGENT_ID,
|
||||
agent_name=intent_agent_id,
|
||||
model_name=model_name,
|
||||
thread_id=thread_id,
|
||||
new_message=effective_message,
|
||||
@@ -479,6 +595,26 @@ async def stream_intent(request: Request, payload: dict = Body(...)) -> Streamin
|
||||
captured = done
|
||||
|
||||
messages = _parse_last_messages(captured)
|
||||
current_rounds = (
|
||||
_count_past_clarification_rounds(messages)
|
||||
if intent_agent_id == POSITION_INTENT_AGENT_ID
|
||||
else _count_past_clarifications(messages)
|
||||
)
|
||||
clarification_is_fresh = current_rounds > past_rounds
|
||||
|
||||
# A position-roundtable clarification is an explicit pause.
|
||||
# Some models emit a premature [INTENT_READY] text after the
|
||||
# tool call in the same upstream run. For this dedicated flow
|
||||
# the fresh clarification must win so the user can answer it;
|
||||
# generic roundtable keeps its historical READY-first order.
|
||||
dispatch_msg = _find_dispatch_message(messages)
|
||||
tool_calls = dispatch_msg.get("tool_calls") or []
|
||||
clarification_calls = [
|
||||
tc
|
||||
for tc in tool_calls
|
||||
if isinstance(tc, dict)
|
||||
and (tc.get("name") or "").lower() == "ask_clarification"
|
||||
]
|
||||
|
||||
# --- 终态分支 1:结构化意图已就绪(最高优先级)---
|
||||
# 模型可能在较早的 AIMessage 里已输出 [INTENT_READY],而最后一轮
|
||||
@@ -507,7 +643,15 @@ async def stream_intent(request: Request, payload: dict = Body(...)) -> Streamin
|
||||
# Step1Panel 已经把 `parts.after` 隐藏掉,体验闭环。
|
||||
ready_text = msg_text[: m.end()].rstrip() + "\n"
|
||||
break
|
||||
if summary and ready_text:
|
||||
if (
|
||||
summary
|
||||
and ready_text
|
||||
and not _clarification_blocks_ready(
|
||||
intent_agent_id,
|
||||
clarification_calls,
|
||||
is_fresh=clarification_is_fresh,
|
||||
)
|
||||
):
|
||||
final_frame = {
|
||||
"status": "done",
|
||||
"content": ready_text,
|
||||
@@ -519,42 +663,49 @@ async def stream_intent(request: Request, payload: dict = Body(...)) -> Streamin
|
||||
# --- 终态分支 2:本轮以 ask_clarification 结束 ---
|
||||
# _find_dispatch_message:从后往前找带 tool_calls 的 AIMessage
|
||||
# (SkillStop/澄清 ToolMessage 之后的那条 AI 消息)。
|
||||
dispatch_msg = _find_dispatch_message(messages)
|
||||
content = _flatten_content(dispatch_msg.get("content", ""))
|
||||
tool_calls = dispatch_msg.get("tool_calls") or []
|
||||
|
||||
clarification_call = next(
|
||||
(tc for tc in tool_calls if (tc.get("name") or "").lower() == "ask_clarification"),
|
||||
None,
|
||||
)
|
||||
if clarification_call is not None:
|
||||
cargs = clarification_call.get("args") or {}
|
||||
question = str(cargs.get("question") or "").strip()
|
||||
if clarification_calls:
|
||||
# ClarificationMiddleware 常在 tool 之后还有一条纯文本 AIMessage,
|
||||
# 比 tool_call 旁的短 preamble 更适合作为气泡正文。
|
||||
follow_up = _find_trailing_ai_text(messages, exclude_text=content)
|
||||
display_content = follow_up or content or question
|
||||
|
||||
# 兜底:模型偶尔会复述上一轮的同一澄清问题(SOUL §2.5 prompt
|
||||
# 已经强约束,但小模型 / 长上下文仍可能漏跟随)。检测到完全
|
||||
# 重复时,把 status 从 clarification 降级为 asking,前端只渲染
|
||||
# 文本气泡不弹卡片,避免用户看到"同样选项又出现一次"。
|
||||
if _is_repeated_clarification(
|
||||
messages,
|
||||
new_question=question,
|
||||
new_options=cargs.get("options"),
|
||||
new_tool_call_id=clarification_call.get("id"),
|
||||
):
|
||||
logger.warning(
|
||||
"intent stream: dropping duplicate ask_clarification "
|
||||
"(question=%r) — already asked & answered earlier in thread",
|
||||
question[:80],
|
||||
clarification_payloads: list[dict[str, Any]] = []
|
||||
for clarification_call in clarification_calls:
|
||||
cargs = clarification_call.get("args") or {}
|
||||
question = str(cargs.get("question") or "").strip()
|
||||
# 逐卡过滤已被用户回答过的重复问题,不能因为其中一张
|
||||
# 重复卡而吞掉同轮其它有效的协助卡。
|
||||
if _is_repeated_clarification(
|
||||
messages,
|
||||
new_question=question,
|
||||
new_options=cargs.get("options"),
|
||||
new_tool_call_id=clarification_call.get("id"),
|
||||
):
|
||||
logger.warning(
|
||||
"intent stream: dropping duplicate ask_clarification "
|
||||
"(question=%r) — already asked & answered earlier in thread",
|
||||
question[:80],
|
||||
)
|
||||
continue
|
||||
clarification_payloads.append(
|
||||
{
|
||||
"id": str(clarification_call.get("id") or ""),
|
||||
"question": question,
|
||||
"clarification_type": str(cargs.get("clarification_type") or ""),
|
||||
"clarification_context": str(cargs.get("context") or ""),
|
||||
"options": cargs.get("options") or [],
|
||||
"allow_custom": bool(cargs.get("allow_custom", True)),
|
||||
"allow_multiple": resolve_allow_multiple(cargs),
|
||||
}
|
||||
)
|
||||
|
||||
if not clarification_payloads:
|
||||
fallback_msg = (
|
||||
display_content
|
||||
follow_up
|
||||
or content
|
||||
or "(系统识别到智能体重复了上一问题,已自动跳过。请补充其他信息继续推进。)"
|
||||
)
|
||||
final_frame: dict[str, Any] = {
|
||||
final_frame = {
|
||||
"status": "asking",
|
||||
"content": fallback_msg,
|
||||
"summary": None,
|
||||
@@ -562,15 +713,15 @@ async def stream_intent(request: Request, payload: dict = Body(...)) -> Streamin
|
||||
yield f"data: {json.dumps(final_frame, ensure_ascii=False)}\n\n"
|
||||
return
|
||||
|
||||
first = clarification_payloads[0]
|
||||
display_content = follow_up or content or str(first["question"])
|
||||
final_frame: dict[str, Any] = {
|
||||
"status": "clarification",
|
||||
"content": display_content,
|
||||
"question": question,
|
||||
"clarification_type": str(cargs.get("clarification_type") or ""),
|
||||
"clarification_context": str(cargs.get("context") or ""),
|
||||
"options": cargs.get("options") or [],
|
||||
"allow_custom": bool(cargs.get("allow_custom", True)),
|
||||
"allow_multiple": resolve_allow_multiple(cargs),
|
||||
# 兼容旧客户端保留首张卡的顶层字段;完整列表使得网络
|
||||
# 重连、缓存重放等没有实时 tool frame 的路径也能还原多卡。
|
||||
**first,
|
||||
"clarifications": clarification_payloads,
|
||||
"summary": None,
|
||||
}
|
||||
yield f"data: {json.dumps(final_frame, ensure_ascii=False)}\n\n"
|
||||
|
||||
@@ -15,8 +15,8 @@ from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel, Field
|
||||
from fastapi import APIRouter, HTTPException, Query, Request
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from app.gateway.path_utils import aresolve_thread_virtual_path
|
||||
from deerflow.runtime.user_context import get_effective_user_id
|
||||
@@ -79,7 +79,10 @@ class NodeResponse(BaseModel):
|
||||
|
||||
class SessionResponse(BaseModel):
|
||||
id: str
|
||||
# Older personal rows can already contain a mock task id; task_scoped is
|
||||
# the authoritative opt-in marker for cross-user task sharing.
|
||||
external_task_id: str | None = None
|
||||
task_scoped: bool = False
|
||||
task_snapshot: dict[str, Any] = Field(default_factory=dict)
|
||||
chain_id: str | None = None
|
||||
chain_snapshot: dict[str, Any] | None = None
|
||||
@@ -105,6 +108,14 @@ class SessionCreateRequest(BaseModel):
|
||||
external_task_id: str | None = Field(default=None, max_length=128)
|
||||
task_snapshot: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
@field_validator("external_task_id")
|
||||
@classmethod
|
||||
def _normalize_external_task_id(cls, value: str | None) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
normalized = value.strip()
|
||||
return normalized or None
|
||||
|
||||
|
||||
class TaskSnapshotUpdateRequest(BaseModel):
|
||||
task_snapshot: dict[str, Any] = Field(default_factory=dict)
|
||||
@@ -180,6 +191,25 @@ def _current_user_id(request: Request) -> str:
|
||||
return str(user.id) if user is not None else get_effective_user_id()
|
||||
|
||||
|
||||
def _task_snapshot_for_scope(
|
||||
external_task_id: str | None,
|
||||
task_snapshot: dict[str, Any],
|
||||
*,
|
||||
task_scoped: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""Lock the snapshot id only for an explicit shared task scope."""
|
||||
if not task_scoped or not external_task_id:
|
||||
return dict(task_snapshot)
|
||||
return {**task_snapshot, "id": external_task_id, "externalTaskId": external_task_id}
|
||||
|
||||
|
||||
def _normalize_external_task_id(value: str | None) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
normalized = value.strip()
|
||||
return normalized or None
|
||||
|
||||
|
||||
def _get_store(request: Request):
|
||||
store = getattr(request.app.state, "position_roundtable_store", None)
|
||||
if store is None:
|
||||
@@ -440,15 +470,64 @@ def _markdown_delivery_changed(
|
||||
return bool(new_signatures - old_signatures)
|
||||
|
||||
|
||||
def _intent_string_list(intent: dict[str, Any], key: str) -> list[str]:
|
||||
"""Return a clean, display-safe string list from a persisted intent field."""
|
||||
value = intent.get(key)
|
||||
if not isinstance(value, list):
|
||||
return []
|
||||
return [item.strip() for item in value if isinstance(item, str) and item.strip()]
|
||||
|
||||
|
||||
def _position_intent_sections(intent: Any) -> dict[str, list[str]]:
|
||||
"""Read both the dedicated position-intent schema and legacy snapshots.
|
||||
|
||||
New position sessions persist the four position-specific fields. Mapping
|
||||
the legacy Step-1 fields keeps already-created sessions executable after
|
||||
this rollout instead of stranding them at the activation gate.
|
||||
"""
|
||||
if not isinstance(intent, dict):
|
||||
return {
|
||||
"coreGoals": [],
|
||||
"riskWarnings": [],
|
||||
"keyPoints": [],
|
||||
"strategicSignificance": [],
|
||||
}
|
||||
has_position_schema = any(
|
||||
key in intent
|
||||
for key in ("coreGoals", "riskWarnings", "keyPoints", "strategicSignificance")
|
||||
)
|
||||
if has_position_schema:
|
||||
return {
|
||||
"coreGoals": _intent_string_list(intent, "coreGoals"),
|
||||
"riskWarnings": _intent_string_list(intent, "riskWarnings"),
|
||||
"keyPoints": _intent_string_list(intent, "keyPoints"),
|
||||
"strategicSignificance": _intent_string_list(intent, "strategicSignificance"),
|
||||
}
|
||||
|
||||
objective = _text_from_keys(intent, ["objective", "goal"])
|
||||
return {
|
||||
"coreGoals": _intent_string_list(intent, "constraints"),
|
||||
"riskWarnings": [],
|
||||
"keyPoints": _intent_string_list(intent, "assumptions"),
|
||||
"strategicSignificance": [objective] if objective else [],
|
||||
}
|
||||
|
||||
|
||||
def _intent_node_answer(intent: Any) -> str:
|
||||
if not isinstance(intent, dict):
|
||||
return "情报分析岗已完成任务意图识别。"
|
||||
objective = _text_from_keys(intent, ["objective", "goal"], "已完成任务意图识别")
|
||||
constraints = intent.get("constraints") if isinstance(intent.get("constraints"), list) else []
|
||||
lines = ["情报分析岗已完成任务意图识别。", f"任务目标:{objective}"]
|
||||
if constraints:
|
||||
lines.append("关键约束:")
|
||||
lines.extend(f"- {item}" for item in constraints if isinstance(item, str) and item.strip())
|
||||
sections = _position_intent_sections(intent)
|
||||
lines = ["情报分析岗已完成任务意图识别。"]
|
||||
labels = (
|
||||
("核心目标", sections["coreGoals"]),
|
||||
("风险提示", sections["riskWarnings"]),
|
||||
("关键要点", sections["keyPoints"]),
|
||||
("战略意义", sections["strategicSignificance"]),
|
||||
)
|
||||
for label, values in labels:
|
||||
if values:
|
||||
lines.append(f"{label}:")
|
||||
lines.extend(f"- {item}" for item in values)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
@@ -456,6 +535,15 @@ def _has_confirmed_intent(intent: Any) -> bool:
|
||||
"""Only structured Step-1 output may start a frozen business chain."""
|
||||
if not isinstance(intent, dict):
|
||||
return False
|
||||
if any(
|
||||
key in intent
|
||||
for key in ("coreGoals", "riskWarnings", "keyPoints", "strategicSignificance")
|
||||
):
|
||||
required = ("coreGoals", "riskWarnings", "keyPoints", "strategicSignificance")
|
||||
if not all(isinstance(intent.get(key), list) for key in required):
|
||||
return False
|
||||
sections = _position_intent_sections(intent)
|
||||
return bool(sections["coreGoals"] or sections["strategicSignificance"])
|
||||
objective = _text_from_keys(intent, ["objective", "goal"])
|
||||
constraints = intent.get("constraints")
|
||||
return bool(objective and isinstance(constraints, list))
|
||||
@@ -505,8 +593,7 @@ def _build_node_context_text(
|
||||
title = _text_from_keys(task, ["title", "taskName", "name"], "未命名任务")
|
||||
direction = _text_from_keys(task, ["direction", "taskDirection", "category"], "未填写")
|
||||
description = _text_from_keys(task, ["description", "taskContent", "overview", "content"], "暂无任务描述")
|
||||
objective = _text_from_keys(intent, ["objective", "goal"], "暂无意图结论")
|
||||
constraints = intent.get("constraints") if isinstance(intent.get("constraints"), list) else []
|
||||
sections = _position_intent_sections(intent)
|
||||
agent_name, position_id = _seat_meta(session, current)
|
||||
md_required = not _is_intent_position_node(current, _session_intent_position_id(session))
|
||||
lines = [
|
||||
@@ -518,11 +605,16 @@ def _build_node_context_text(
|
||||
f"- 任务描述:{description}",
|
||||
"",
|
||||
"【已识别意图】",
|
||||
f"- 任务目标:{objective}",
|
||||
]
|
||||
if constraints:
|
||||
lines.append("- 关键约束:")
|
||||
lines.extend(f" - {item}" for item in constraints if isinstance(item, str) and item.strip())
|
||||
for label, values in (
|
||||
("核心目标", sections["coreGoals"]),
|
||||
("风险提示", sections["riskWarnings"]),
|
||||
("关键要点", sections["keyPoints"]),
|
||||
("战略意义", sections["strategicSignificance"]),
|
||||
):
|
||||
if values:
|
||||
lines.append(f"- {label}:")
|
||||
lines.extend(f" - {item}" for item in values)
|
||||
lines.extend(
|
||||
[
|
||||
"",
|
||||
@@ -975,8 +1067,7 @@ async def _build_builtin_prompt(
|
||||
title = _text_from_keys(task, ["title", "taskName", "name"], "未命名任务")
|
||||
direction = _text_from_keys(task, ["direction", "taskDirection", "category"], "未填写")
|
||||
description = _text_from_keys(task, ["description", "taskContent", "overview", "content"], "暂无任务描述")
|
||||
objective = _text_from_keys(intent, ["objective", "goal"], "暂无意图结论")
|
||||
constraints = intent.get("constraints") if isinstance(intent.get("constraints"), list) else []
|
||||
sections = _position_intent_sections(intent)
|
||||
stage_goals = chain.get("stageGoals") if isinstance(chain.get("stageGoals"), list) else []
|
||||
stage_lines = [f"- L-{index + 1}:{goal}" for index, goal in enumerate(stage_goals) if isinstance(goal, str) and goal.strip()]
|
||||
material = await _effective_delivery_material(session, nodes)
|
||||
@@ -990,11 +1081,16 @@ async def _build_builtin_prompt(
|
||||
f"- 描述:{description}",
|
||||
"",
|
||||
"【情报分析岗已确认的意图】",
|
||||
f"- 核心目标:{objective}",
|
||||
]
|
||||
if constraints:
|
||||
common.append("- 关键约束:")
|
||||
common.extend(f" - {item}" for item in constraints if isinstance(item, str) and item.strip())
|
||||
for label, values in (
|
||||
("核心目标", sections["coreGoals"]),
|
||||
("风险提示", sections["riskWarnings"]),
|
||||
("关键要点", sections["keyPoints"]),
|
||||
("战略意义", sections["strategicSignificance"]),
|
||||
):
|
||||
if values:
|
||||
common.append(f"- {label}:")
|
||||
common.extend(f" - {item}" for item in values)
|
||||
if stage_lines:
|
||||
common.extend(["", "【业务链阶段】", *stage_lines])
|
||||
|
||||
@@ -1082,9 +1178,13 @@ async def seed_demo_session(
|
||||
|
||||
|
||||
@router.get("/sessions", response_model=list[SessionResponse])
|
||||
async def list_sessions(request: Request, external_task_id: str | None = None) -> list[SessionResponse]:
|
||||
async def list_sessions(
|
||||
request: Request,
|
||||
external_task_id: str | None = Query(default=None, max_length=128),
|
||||
) -> list[SessionResponse]:
|
||||
task_id = _normalize_external_task_id(external_task_id)
|
||||
rows = await _get_store(request).list_sessions(
|
||||
_current_user_id(request), external_task_id=external_task_id
|
||||
_current_user_id(request), external_task_id=task_id
|
||||
)
|
||||
return [_project_session(row) for row in rows]
|
||||
|
||||
@@ -1094,7 +1194,12 @@ async def create_session(request: Request, body: SessionCreateRequest) -> Sessio
|
||||
row = await _get_store(request).create_session(
|
||||
_current_user_id(request),
|
||||
external_task_id=body.external_task_id,
|
||||
task_snapshot=body.task_snapshot,
|
||||
task_snapshot=_task_snapshot_for_scope(
|
||||
body.external_task_id,
|
||||
body.task_snapshot,
|
||||
task_scoped=bool(body.external_task_id),
|
||||
),
|
||||
task_scoped=bool(body.external_task_id),
|
||||
)
|
||||
return _project_session(row)
|
||||
|
||||
@@ -1108,8 +1213,16 @@ async def get_session(request: Request, session_id: str) -> SessionDetailRespons
|
||||
async def update_task_snapshot(
|
||||
request: Request, session_id: str, body: TaskSnapshotUpdateRequest
|
||||
) -> SessionResponse:
|
||||
store, user_id, _ = await _require_writable_session(request, session_id)
|
||||
row = await store.update_session(session_id, user_id, task_snapshot=body.task_snapshot)
|
||||
store, user_id, current = await _require_writable_session(request, session_id)
|
||||
row = await store.update_session(
|
||||
session_id,
|
||||
user_id,
|
||||
task_snapshot=_task_snapshot_for_scope(
|
||||
current.get("external_task_id"),
|
||||
body.task_snapshot,
|
||||
task_scoped=bool(current.get("task_scoped")),
|
||||
),
|
||||
)
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="Position roundtable session not found")
|
||||
return _project_session(row)
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
"""Task-scoped submission status for roundtable artifacts.
|
||||
|
||||
This API records only an artifact reference (thread + sandbox path) and its
|
||||
submission state. It intentionally does not fetch task detail, copy Markdown,
|
||||
or deliver a file to an external task system.
|
||||
|
||||
Routes (authenticated by the Gateway middleware):
|
||||
GET /api/roundtable/tasks/{task_id}/artifacts?submitted=true
|
||||
PUT /api/roundtable/tasks/{task_id}/artifacts/submission
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import PurePosixPath
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query, Request
|
||||
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, StrictInt, StrictStr, field_validator
|
||||
|
||||
from app.gateway.deps import get_current_user
|
||||
from deerflow.persistence.roundtable_artifact_submissions import RoundtableArtifactSubmissionStore
|
||||
|
||||
router = APIRouter(prefix="/api/roundtable/tasks", tags=["roundtable-artifact-submissions"])
|
||||
|
||||
|
||||
class ArtifactReferenceInput(BaseModel):
|
||||
"""Reference to a generated file; the file content remains in its thread sandbox."""
|
||||
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
session_id: StrictStr | None = Field(default=None, max_length=128, validation_alias=AliasChoices("sessionId", "session_id"))
|
||||
thread_id: StrictStr | None = Field(default=None, max_length=128, validation_alias=AliasChoices("threadId", "thread_id"))
|
||||
node_key: StrictStr | None = Field(default=None, max_length=256, validation_alias=AliasChoices("nodeKey", "node_key"))
|
||||
source_key: StrictStr = Field(..., min_length=1, max_length=512, validation_alias=AliasChoices("sourceKey", "source_key"))
|
||||
path: StrictStr = Field(..., min_length=1, max_length=2048)
|
||||
name: StrictStr | None = Field(default=None, max_length=512)
|
||||
mime_type: StrictStr | None = Field(default=None, max_length=255, validation_alias=AliasChoices("mimeType", "mime_type"))
|
||||
revision: StrictInt = Field(..., ge=0)
|
||||
|
||||
@field_validator("session_id", "thread_id", "node_key", "source_key", "path", "name", "mime_type", mode="before")
|
||||
@classmethod
|
||||
def _trim_text(cls, value: Any) -> Any:
|
||||
if isinstance(value, str):
|
||||
value = value.strip()
|
||||
return value or None
|
||||
return value
|
||||
|
||||
|
||||
class ArtifactSubmissionRequest(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
task_id: StrictStr | None = Field(default=None, max_length=128, validation_alias=AliasChoices("taskId", "task_id"))
|
||||
submitted: bool
|
||||
submission_id: StrictStr | None = Field(default=None, max_length=64, validation_alias=AliasChoices("submissionId", "submission_id"))
|
||||
task_delivery_id: StrictStr | None = Field(default=None, max_length=255, validation_alias=AliasChoices("taskDeliveryId", "task_delivery_id"))
|
||||
artifact: ArtifactReferenceInput
|
||||
|
||||
@field_validator("task_id", "submission_id", "task_delivery_id", mode="before")
|
||||
@classmethod
|
||||
def _trim_optional_text(cls, value: Any) -> Any:
|
||||
if isinstance(value, str):
|
||||
value = value.strip()
|
||||
return value or None
|
||||
return value
|
||||
|
||||
|
||||
class ArtifactReferenceResponse(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
session_id: str | None = Field(default=None, serialization_alias="sessionId")
|
||||
thread_id: str | None = Field(default=None, serialization_alias="threadId")
|
||||
node_key: str | None = Field(default=None, serialization_alias="nodeKey")
|
||||
source_key: str = Field(serialization_alias="sourceKey")
|
||||
path: str
|
||||
name: str | None = None
|
||||
mime_type: str | None = Field(default=None, serialization_alias="mimeType")
|
||||
revision: int
|
||||
|
||||
|
||||
class ArtifactSubmissionResponse(BaseModel):
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
id: str
|
||||
task_id: str = Field(serialization_alias="taskId")
|
||||
submitted: bool
|
||||
submitted_at: str | None = Field(default=None, serialization_alias="submittedAt")
|
||||
cancelled_at: str | None = Field(default=None, serialization_alias="cancelledAt")
|
||||
task_delivery_id: str | None = Field(default=None, serialization_alias="taskDeliveryId")
|
||||
artifact: ArtifactReferenceResponse
|
||||
|
||||
|
||||
class ArtifactSubmissionListResponse(BaseModel):
|
||||
items: list[ArtifactSubmissionResponse]
|
||||
|
||||
|
||||
def _get_store(request: Request) -> RoundtableArtifactSubmissionStore:
|
||||
store = getattr(request.app.state, "roundtable_artifact_submission_store", None)
|
||||
if store is None:
|
||||
raise HTTPException(status_code=503, detail="Roundtable artifact submission store not available")
|
||||
return store
|
||||
|
||||
|
||||
def _task_id_or_422(value: str) -> str:
|
||||
task_id = value.strip()
|
||||
if not task_id:
|
||||
raise HTTPException(status_code=422, detail="task id is required")
|
||||
if len(task_id) > 128:
|
||||
raise HTTPException(status_code=422, detail="task id must be at most 128 characters")
|
||||
return task_id
|
||||
|
||||
|
||||
def _artifact_payload(artifact: ArtifactReferenceInput) -> dict[str, Any]:
|
||||
source_key = artifact.source_key
|
||||
path = artifact.path
|
||||
if not source_key or not path:
|
||||
raise HTTPException(status_code=422, detail="artifact.sourceKey and artifact.path are required")
|
||||
name = artifact.name or PurePosixPath(path).name or path
|
||||
return {
|
||||
"session_id": artifact.session_id,
|
||||
"thread_id": artifact.thread_id,
|
||||
"node_key": artifact.node_key,
|
||||
"source_key": source_key,
|
||||
"path": path,
|
||||
"name": name,
|
||||
"mime_type": artifact.mime_type,
|
||||
"revision": artifact.revision,
|
||||
}
|
||||
|
||||
|
||||
def _response(row: dict[str, Any]) -> ArtifactSubmissionResponse:
|
||||
return ArtifactSubmissionResponse(
|
||||
id=str(row["id"]),
|
||||
task_id=str(row["task_id"]),
|
||||
submitted=bool(row["submitted"]),
|
||||
submitted_at=row.get("submitted_at"),
|
||||
cancelled_at=row.get("cancelled_at"),
|
||||
task_delivery_id=row.get("task_delivery_id"),
|
||||
artifact=ArtifactReferenceResponse(
|
||||
session_id=row.get("session_id"),
|
||||
thread_id=row.get("thread_id"),
|
||||
node_key=row.get("node_key"),
|
||||
source_key=str(row["source_key"]),
|
||||
path=str(row["path"]),
|
||||
name=row.get("name"),
|
||||
mime_type=row.get("mime_type"),
|
||||
revision=int(row["revision"]),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{task_id}/artifacts", response_model=ArtifactSubmissionListResponse)
|
||||
async def list_artifact_submissions(
|
||||
request: Request,
|
||||
task_id: str,
|
||||
submitted: bool | None = Query(default=True),
|
||||
) -> ArtifactSubmissionListResponse:
|
||||
"""List task artifacts by submission state (defaults to submitted only)."""
|
||||
rows = await _get_store(request).list_by_task(_task_id_or_422(task_id), submitted=submitted)
|
||||
return ArtifactSubmissionListResponse(items=[_response(row) for row in rows])
|
||||
|
||||
|
||||
@router.put("/{task_id}/artifacts/submission", response_model=ArtifactSubmissionResponse)
|
||||
async def set_artifact_submission(
|
||||
request: Request,
|
||||
task_id: str,
|
||||
body: ArtifactSubmissionRequest,
|
||||
) -> ArtifactSubmissionResponse:
|
||||
"""Create/update a submission or retain an audit row while cancelling it."""
|
||||
path_task_id = _task_id_or_422(task_id)
|
||||
if body.task_id is not None and body.task_id != path_task_id:
|
||||
raise HTTPException(status_code=422, detail="taskId must match the path task id")
|
||||
|
||||
artifact = _artifact_payload(body.artifact)
|
||||
actor_id = await get_current_user(request)
|
||||
store = _get_store(request)
|
||||
if body.submitted:
|
||||
# The frontend previews submitted artifacts by threadId + path. Without
|
||||
# a thread reference a saved state could never be previewed correctly.
|
||||
if not artifact["thread_id"]:
|
||||
raise HTTPException(status_code=422, detail="artifact.threadId is required when submitted is true")
|
||||
row = await store.submit(
|
||||
path_task_id,
|
||||
artifact,
|
||||
task_delivery_id=body.task_delivery_id,
|
||||
actor_id=actor_id,
|
||||
)
|
||||
else:
|
||||
row = await store.cancel(
|
||||
path_task_id,
|
||||
artifact,
|
||||
submission_id=body.submission_id,
|
||||
actor_id=actor_id,
|
||||
)
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="Artifact submission not found")
|
||||
return _response(row)
|
||||
@@ -58,6 +58,10 @@ class ChainSeatSchema(BaseModel):
|
||||
# 与该席位 agent 自身 config.yaml 的同名开关取 OR。默认 False(关)。整条 seats 数组以
|
||||
# JSON 透传持久化,故新增此字段无需迁移;仅需在此 schema 显式声明,否则 model_dump() 会剥掉它。
|
||||
seat_skill_directive: bool = False
|
||||
# Per-seat human checkpoint. Step 2 pauses after this seat (or its DAG
|
||||
# stage) completes and reuses the existing resume/intervention controls.
|
||||
# It is stored in the existing seats JSON, so no database migration is needed.
|
||||
human_validation: bool = False
|
||||
# 该席位「推理深度覆盖」(flash/thinking/pro/ultra):覆盖链条级 seat_mode,仅本席位生效。
|
||||
# None = 跟随链条级默认。「卡顿提速」用:把次要席位降到 flash。整条 seats 数组以 JSON 透传
|
||||
# 持久化,故无需迁移;仅需在此 schema 显式声明,否则 model_dump() 会剥掉它。非法值在运行期
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Index optional task-scoped position-roundtable history.
|
||||
|
||||
Revision ID: 20260808_01
|
||||
Revises: 20260729_01
|
||||
Create Date: 2026-08-08
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy import inspect
|
||||
|
||||
revision = "20260808_01"
|
||||
down_revision = "20260729_01"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
_TABLE = "position_roundtable_sessions"
|
||||
_INDEX = "ix_position_roundtable_sessions_task_updated"
|
||||
|
||||
|
||||
def _has_table(table_name: str) -> bool:
|
||||
return table_name in inspect(op.get_bind()).get_table_names()
|
||||
|
||||
|
||||
def _has_column(table_name: str, column_name: str) -> bool:
|
||||
if not _has_table(table_name):
|
||||
return False
|
||||
return any(
|
||||
column["name"] == column_name
|
||||
for column in inspect(op.get_bind()).get_columns(table_name)
|
||||
)
|
||||
|
||||
|
||||
def _has_index(table_name: str, index_name: str) -> bool:
|
||||
if not _has_table(table_name):
|
||||
return False
|
||||
return index_name in {
|
||||
index["name"] for index in inspect(op.get_bind()).get_indexes(table_name)
|
||||
}
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
if not _has_table(_TABLE):
|
||||
return
|
||||
# Historical records must stay in the original personal mode. New records
|
||||
# set this flag only when a route taskId explicitly requests sharing.
|
||||
if not _has_column(_TABLE, "task_scoped"):
|
||||
op.add_column(
|
||||
_TABLE,
|
||||
sa.Column(
|
||||
"task_scoped",
|
||||
sa.Boolean(),
|
||||
nullable=False,
|
||||
server_default=sa.false(),
|
||||
),
|
||||
)
|
||||
if not _has_index(_TABLE, _INDEX):
|
||||
op.create_index(_INDEX, _TABLE, ["external_task_id", "updated_at"])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
if not _has_table(_TABLE):
|
||||
return
|
||||
if _has_index(_TABLE, _INDEX):
|
||||
op.drop_index(_INDEX, table_name=_TABLE)
|
||||
if _has_column(_TABLE, "task_scoped"):
|
||||
op.drop_column(_TABLE, "task_scoped")
|
||||
@@ -56,6 +56,7 @@ from deerflow.persistence.positions.model import PositionRow, PositionTagBinding
|
||||
from deerflow.persistence.recommended_questions.model import RecommendedQuestionRow
|
||||
from deerflow.persistence.research_templates.model import ResearchTemplateRow
|
||||
from deerflow.persistence.roundtable_chains.model import RoundtableChainRow
|
||||
from deerflow.persistence.roundtable_artifact_submissions.model import RoundtableArtifactSubmissionRow
|
||||
from deerflow.persistence.roundtable_diagnostics.model import RoundtableDiagnosticRow
|
||||
from deerflow.persistence.roundtable_draft_shares.model import RoundtableDraftShareRow
|
||||
from deerflow.persistence.roundtable_drafts.model import (
|
||||
@@ -118,6 +119,7 @@ __all__ = [
|
||||
"RecommendedQuestionRow",
|
||||
"ResearchTemplateRow",
|
||||
"RoundtableChainRow",
|
||||
"RoundtableArtifactSubmissionRow",
|
||||
"RoundtableDraftRow",
|
||||
"RoundtableDraftShareRow",
|
||||
"RoundtableDiagnosticRow",
|
||||
|
||||
@@ -12,7 +12,7 @@ from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import ForeignKey, Integer, String, UniqueConstraint
|
||||
from sqlalchemy import Boolean, ForeignKey, Index, Integer, String, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from deerflow.persistence.base import Base
|
||||
@@ -21,12 +21,23 @@ from deerflow.persistence.types import BeijingDateTime, PortableLongText
|
||||
|
||||
class PositionRoundtableSessionRow(Base):
|
||||
__tablename__ = "position_roundtable_sessions"
|
||||
__table_args__ = (
|
||||
# History is read as "all conversations for one task, newest first".
|
||||
# `user_id` remains audit data only; it must not partition a shared
|
||||
# task workspace.
|
||||
Index(
|
||||
"ix_position_roundtable_sessions_task_updated",
|
||||
"external_task_id",
|
||||
"updated_at",
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
# Phase one uses normal account isolation. A future membership / role ACL
|
||||
# can be added without changing the session or thread identifiers.
|
||||
# Creator audit field. `task_scoped`, not merely external_task_id, opts a
|
||||
# session into sharing. This keeps historical sidebar/mock rows private.
|
||||
user_id: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
||||
external_task_id: Mapped[str | None] = mapped_column(String(128), nullable=True, index=True)
|
||||
task_scoped: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default="0")
|
||||
task_snapshot: Mapped[str | None] = mapped_column(PortableLongText, nullable=True)
|
||||
chain_id: Mapped[str | None] = mapped_column(String(64), nullable=True, index=True)
|
||||
chain_snapshot: Mapped[str | None] = mapped_column(PortableLongText, nullable=True)
|
||||
|
||||
@@ -46,11 +46,17 @@ class PositionRoundtableRepository:
|
||||
def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:
|
||||
self._sf = session_factory
|
||||
|
||||
@staticmethod
|
||||
def _can_access(row: PositionRoundtableSessionRow, user_id: str) -> bool:
|
||||
"""Task-bound sessions are shared; unbound legacy sessions stay private."""
|
||||
return bool(row.task_scoped) or row.user_id == user_id
|
||||
|
||||
@staticmethod
|
||||
def _session_dict(row: PositionRoundtableSessionRow) -> dict[str, Any]:
|
||||
return {
|
||||
"id": row.id,
|
||||
"external_task_id": row.external_task_id,
|
||||
"task_scoped": bool(row.task_scoped),
|
||||
"task_snapshot": _loads(row.task_snapshot) or {},
|
||||
"chain_id": row.chain_id,
|
||||
"chain_snapshot": _loads(row.chain_snapshot),
|
||||
@@ -98,12 +104,14 @@ class PositionRoundtableRepository:
|
||||
*,
|
||||
external_task_id: str | None,
|
||||
task_snapshot: dict[str, Any] | None,
|
||||
task_scoped: bool | None = None,
|
||||
) -> dict[str, Any]:
|
||||
now = datetime.now(UTC)
|
||||
row = PositionRoundtableSessionRow(
|
||||
id=uuid4().hex,
|
||||
user_id=user_id,
|
||||
external_task_id=external_task_id or None,
|
||||
task_scoped=bool(external_task_id) if task_scoped is None else task_scoped,
|
||||
task_snapshot=_dumps(task_snapshot or {}),
|
||||
status="intent_pending",
|
||||
created_at=now,
|
||||
@@ -165,7 +173,8 @@ class PositionRoundtableRepository:
|
||||
row = PositionRoundtableSessionRow(
|
||||
id=session_id,
|
||||
user_id=user_id,
|
||||
external_task_id=session_payload.get("external_task_id") or None,
|
||||
external_task_id=str(session_payload.get("external_task_id") or "").strip() or None,
|
||||
task_scoped=False,
|
||||
task_snapshot=_dumps(session_payload.get("task_snapshot") or {}),
|
||||
chain_id=session_payload.get("chain_id") or None,
|
||||
chain_snapshot=_dumps(session_payload.get("chain_snapshot")),
|
||||
@@ -246,9 +255,17 @@ class PositionRoundtableRepository:
|
||||
async def list_sessions(
|
||||
self, user_id: str, *, external_task_id: str | None = None, limit: int = 50
|
||||
) -> list[dict[str, Any]]:
|
||||
stmt = select(PositionRoundtableSessionRow).where(PositionRoundtableSessionRow.user_id == user_id)
|
||||
"""List shared task history or the caller's legacy personal history."""
|
||||
if external_task_id:
|
||||
stmt = stmt.where(PositionRoundtableSessionRow.external_task_id == external_task_id)
|
||||
stmt = select(PositionRoundtableSessionRow).where(
|
||||
PositionRoundtableSessionRow.external_task_id == external_task_id,
|
||||
PositionRoundtableSessionRow.task_scoped.is_(True),
|
||||
)
|
||||
else:
|
||||
stmt = select(PositionRoundtableSessionRow).where(
|
||||
PositionRoundtableSessionRow.user_id == user_id,
|
||||
PositionRoundtableSessionRow.task_scoped.is_(False),
|
||||
)
|
||||
stmt = stmt.order_by(PositionRoundtableSessionRow.updated_at.desc()).limit(limit)
|
||||
async with self._sf() as session:
|
||||
rows = (await session.execute(stmt)).scalars().all()
|
||||
@@ -257,7 +274,7 @@ class PositionRoundtableRepository:
|
||||
async def get_session(self, session_id: str, user_id: str) -> dict[str, Any] | None:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(PositionRoundtableSessionRow, session_id)
|
||||
if row is None or row.user_id != user_id:
|
||||
if row is None or not self._can_access(row, user_id):
|
||||
return None
|
||||
return self._session_dict(row)
|
||||
|
||||
@@ -280,7 +297,7 @@ class PositionRoundtableRepository:
|
||||
) -> dict[str, Any] | None:
|
||||
async with self._sf() as session:
|
||||
row = await session.get(PositionRoundtableSessionRow, session_id)
|
||||
if row is None or row.user_id != user_id:
|
||||
if row is None or not self._can_access(row, user_id):
|
||||
return None
|
||||
if task_snapshot is not _UNSET:
|
||||
row.task_snapshot = _dumps(task_snapshot)
|
||||
@@ -326,7 +343,7 @@ class PositionRoundtableRepository:
|
||||
now = datetime.now(UTC)
|
||||
async with self._sf() as session:
|
||||
row = await session.get(PositionRoundtableSessionRow, session_id)
|
||||
if row is None or row.user_id != user_id:
|
||||
if row is None or not self._can_access(row, user_id):
|
||||
return None
|
||||
node_rows = (
|
||||
await session.execute(
|
||||
@@ -371,7 +388,7 @@ class PositionRoundtableRepository:
|
||||
async def list_nodes(self, session_id: str, user_id: str) -> list[dict[str, Any]] | None:
|
||||
async with self._sf() as session:
|
||||
parent = await session.get(PositionRoundtableSessionRow, session_id)
|
||||
if parent is None or parent.user_id != user_id:
|
||||
if parent is None or not self._can_access(parent, user_id):
|
||||
return None
|
||||
rows = (
|
||||
await session.execute(
|
||||
@@ -384,16 +401,13 @@ class PositionRoundtableRepository:
|
||||
|
||||
async def get_node(self, session_id: str, node_key: str, user_id: str) -> dict[str, Any] | None:
|
||||
async with self._sf() as session:
|
||||
stmt = (
|
||||
select(PositionRoundtableNodeRow)
|
||||
.join(PositionRoundtableSessionRow, PositionRoundtableSessionRow.id == PositionRoundtableNodeRow.session_id)
|
||||
.where(
|
||||
PositionRoundtableNodeRow.session_id == session_id,
|
||||
PositionRoundtableNodeRow.node_key == node_key,
|
||||
PositionRoundtableSessionRow.user_id == user_id,
|
||||
)
|
||||
.limit(1)
|
||||
)
|
||||
parent = await session.get(PositionRoundtableSessionRow, session_id)
|
||||
if parent is None or not self._can_access(parent, user_id):
|
||||
return None
|
||||
stmt = select(PositionRoundtableNodeRow).where(
|
||||
PositionRoundtableNodeRow.session_id == session_id,
|
||||
PositionRoundtableNodeRow.node_key == node_key,
|
||||
).limit(1)
|
||||
row = (await session.execute(stmt)).scalars().first()
|
||||
return self._node_dict(row) if row is not None else None
|
||||
|
||||
@@ -415,16 +429,13 @@ class PositionRoundtableRepository:
|
||||
increment_rejection: bool = False,
|
||||
) -> dict[str, Any] | None:
|
||||
async with self._sf() as session:
|
||||
stmt = (
|
||||
select(PositionRoundtableNodeRow)
|
||||
.join(PositionRoundtableSessionRow, PositionRoundtableSessionRow.id == PositionRoundtableNodeRow.session_id)
|
||||
.where(
|
||||
PositionRoundtableNodeRow.session_id == session_id,
|
||||
PositionRoundtableNodeRow.node_key == node_key,
|
||||
PositionRoundtableSessionRow.user_id == user_id,
|
||||
)
|
||||
.limit(1)
|
||||
)
|
||||
parent = await session.get(PositionRoundtableSessionRow, session_id)
|
||||
if parent is None or not self._can_access(parent, user_id):
|
||||
return None
|
||||
stmt = select(PositionRoundtableNodeRow).where(
|
||||
PositionRoundtableNodeRow.session_id == session_id,
|
||||
PositionRoundtableNodeRow.node_key == node_key,
|
||||
).limit(1)
|
||||
row = (await session.execute(stmt)).scalars().first()
|
||||
if row is None:
|
||||
return None
|
||||
@@ -472,7 +483,7 @@ class PositionRoundtableRepository:
|
||||
now = datetime.now(UTC)
|
||||
async with self._sf() as session:
|
||||
parent = await session.get(PositionRoundtableSessionRow, session_id)
|
||||
if parent is None or parent.user_id != user_id:
|
||||
if parent is None or not self._can_access(parent, user_id):
|
||||
return None
|
||||
rows = (
|
||||
await session.execute(
|
||||
@@ -538,19 +549,18 @@ class PositionRoundtableRepository:
|
||||
return await self.update_session(session_id, user_id, status="archived")
|
||||
|
||||
async def delete_session(self, session_id: str, user_id: str) -> bool:
|
||||
"""Delete one user-owned history record and all of its node snapshots."""
|
||||
"""Delete a task-shared row or the caller's personal legacy row."""
|
||||
async with self._sf() as session:
|
||||
parent = (
|
||||
await session.execute(
|
||||
select(PositionRoundtableSessionRow)
|
||||
.where(
|
||||
PositionRoundtableSessionRow.id == session_id,
|
||||
PositionRoundtableSessionRow.user_id == user_id,
|
||||
)
|
||||
.limit(1)
|
||||
)
|
||||
).scalar_one_or_none()
|
||||
if parent is None:
|
||||
if parent is None or not self._can_access(parent, user_id):
|
||||
return False
|
||||
|
||||
# Do not rely on database-specific FK cascade settings. SQLite
|
||||
@@ -564,7 +574,6 @@ class PositionRoundtableRepository:
|
||||
await session.execute(
|
||||
delete(PositionRoundtableSessionRow).where(
|
||||
PositionRoundtableSessionRow.id == session_id,
|
||||
PositionRoundtableSessionRow.user_id == user_id,
|
||||
)
|
||||
)
|
||||
await session.commit()
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Task-scoped roundtable artifact submission status persistence."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from deerflow.persistence.roundtable_artifact_submissions.base import RoundtableArtifactSubmissionStore
|
||||
from deerflow.persistence.roundtable_artifact_submissions.memory import MemoryRoundtableArtifactSubmissionStore
|
||||
from deerflow.persistence.roundtable_artifact_submissions.model import RoundtableArtifactSubmissionRow
|
||||
from deerflow.persistence.roundtable_artifact_submissions.sql import RoundtableArtifactSubmissionRepository
|
||||
|
||||
__all__ = [
|
||||
"MemoryRoundtableArtifactSubmissionStore",
|
||||
"RoundtableArtifactSubmissionRepository",
|
||||
"RoundtableArtifactSubmissionRow",
|
||||
"RoundtableArtifactSubmissionStore",
|
||||
"make_roundtable_artifact_submission_store",
|
||||
]
|
||||
|
||||
|
||||
def make_roundtable_artifact_submission_store(session_factory):
|
||||
if session_factory is None:
|
||||
return MemoryRoundtableArtifactSubmissionStore()
|
||||
return RoundtableArtifactSubmissionRepository(session_factory)
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Persistence contract for task-scoped roundtable artifact submissions.
|
||||
|
||||
The store deliberately keeps only a stable reference to an artifact in a
|
||||
DeerFlow thread sandbox. It does not copy the artifact body and never calls a
|
||||
downstream task-delivery service.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Any
|
||||
|
||||
|
||||
class RoundtableArtifactSubmissionStore(ABC):
|
||||
"""Shared submission-status store, partitioned only by task id."""
|
||||
|
||||
@abstractmethod
|
||||
async def list_by_task(self, task_id: str, *, submitted: bool | None = True) -> list[dict[str, Any]]:
|
||||
"""Return artifact submission records for one task, newest first."""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def submit(
|
||||
self,
|
||||
task_id: str,
|
||||
artifact: dict[str, Any],
|
||||
*,
|
||||
task_delivery_id: str | None = None,
|
||||
actor_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Create or update the idempotent submission record for an artifact."""
|
||||
raise NotImplementedError
|
||||
|
||||
@abstractmethod
|
||||
async def cancel(
|
||||
self,
|
||||
task_id: str,
|
||||
artifact: dict[str, Any],
|
||||
*,
|
||||
submission_id: str | None = None,
|
||||
actor_id: str | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Mark a submission as cancelled without deleting its audit record."""
|
||||
raise NotImplementedError
|
||||
@@ -0,0 +1,127 @@
|
||||
"""In-memory roundtable artifact-submission store."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
from datetime import UTC, datetime
|
||||
from hashlib import sha256
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from deerflow.persistence.roundtable_artifact_submissions.base import RoundtableArtifactSubmissionStore
|
||||
from deerflow.persistence.types import BEIJING_TZ
|
||||
|
||||
|
||||
def submission_key(task_id: str, artifact: dict[str, Any]) -> str:
|
||||
"""Return the canonical server-owned idempotency key for an artifact."""
|
||||
source_key = str(artifact["source_key"])
|
||||
path = str(artifact["path"])
|
||||
revision = int(artifact["revision"])
|
||||
raw = "\x1f".join((task_id, source_key, path, str(revision)))
|
||||
return sha256(raw.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now(UTC).astimezone(BEIJING_TZ).isoformat()
|
||||
|
||||
|
||||
def _artifact_values(artifact: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
"session_id": artifact.get("session_id"),
|
||||
"thread_id": artifact.get("thread_id"),
|
||||
"node_key": artifact.get("node_key"),
|
||||
"source_key": artifact["source_key"],
|
||||
"path": artifact["path"],
|
||||
"name": artifact.get("name"),
|
||||
"mime_type": artifact.get("mime_type"),
|
||||
"revision": int(artifact["revision"]),
|
||||
}
|
||||
|
||||
|
||||
class MemoryRoundtableArtifactSubmissionStore(RoundtableArtifactSubmissionStore):
|
||||
def __init__(self) -> None:
|
||||
self._rows: dict[tuple[str, str], dict[str, Any]] = {}
|
||||
|
||||
async def list_by_task(self, task_id: str, *, submitted: bool | None = True) -> list[dict[str, Any]]:
|
||||
rows = [row for row in self._rows.values() if row["task_id"] == task_id and (submitted is None or row["submitted"] is submitted)]
|
||||
rows.sort(key=lambda row: row["updated_at"], reverse=True)
|
||||
return deepcopy(rows)
|
||||
|
||||
async def submit(
|
||||
self,
|
||||
task_id: str,
|
||||
artifact: dict[str, Any],
|
||||
*,
|
||||
task_delivery_id: str | None = None,
|
||||
actor_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
key = submission_key(task_id, artifact)
|
||||
row = self._rows.get((task_id, key))
|
||||
values = _artifact_values(artifact)
|
||||
if row is None:
|
||||
now = _now()
|
||||
row = {
|
||||
"id": uuid4().hex,
|
||||
"task_id": task_id,
|
||||
"idempotency_key": key,
|
||||
**values,
|
||||
"task_delivery_id": task_delivery_id,
|
||||
"submitted": True,
|
||||
"submitted_at": now,
|
||||
"cancelled_at": None,
|
||||
"created_by": actor_id,
|
||||
"updated_by": actor_id,
|
||||
"submitted_by": actor_id,
|
||||
"cancelled_by": None,
|
||||
"created_at": now,
|
||||
"updated_at": now,
|
||||
}
|
||||
self._rows[(task_id, key)] = row
|
||||
return deepcopy(row)
|
||||
|
||||
changed = (
|
||||
not row["submitted"]
|
||||
or row.get("task_delivery_id") != task_delivery_id
|
||||
or any(row.get(name) != value for name, value in values.items())
|
||||
)
|
||||
if changed:
|
||||
now = _now()
|
||||
row.update(values)
|
||||
row.update(
|
||||
{
|
||||
"task_delivery_id": task_delivery_id,
|
||||
"submitted": True,
|
||||
"submitted_at": now,
|
||||
"cancelled_at": None,
|
||||
"updated_by": actor_id,
|
||||
"submitted_by": actor_id,
|
||||
"cancelled_by": None,
|
||||
"updated_at": now,
|
||||
}
|
||||
)
|
||||
return deepcopy(row)
|
||||
|
||||
async def cancel(
|
||||
self,
|
||||
task_id: str,
|
||||
artifact: dict[str, Any],
|
||||
*,
|
||||
submission_id: str | None = None,
|
||||
actor_id: str | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
key = submission_key(task_id, artifact)
|
||||
row = self._rows.get((task_id, key))
|
||||
if row is None or (submission_id is not None and row["id"] != submission_id):
|
||||
return None
|
||||
if row["submitted"]:
|
||||
now = _now()
|
||||
row.update(
|
||||
{
|
||||
"submitted": False,
|
||||
"cancelled_at": now,
|
||||
"updated_by": actor_id,
|
||||
"cancelled_by": actor_id,
|
||||
"updated_at": now,
|
||||
}
|
||||
)
|
||||
return deepcopy(row)
|
||||
@@ -0,0 +1,56 @@
|
||||
"""ORM model for task-scoped roundtable artifact submission status."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
from sqlalchemy import Boolean, Index, Integer, String, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from deerflow.persistence.base import Base
|
||||
from deerflow.persistence.types import BeijingDateTime
|
||||
|
||||
|
||||
class RoundtableArtifactSubmissionRow(Base):
|
||||
"""One auditable submission state for one task artifact revision.
|
||||
|
||||
The natural idempotency key is a SHA-256 digest of
|
||||
``task_id + source_key + artifact_path + revision``. Keeping the digest
|
||||
short avoids a MySQL unique-index limit while the component columns remain
|
||||
available for diagnostics and response shaping.
|
||||
"""
|
||||
|
||||
__tablename__ = "roundtable_artifact_submissions"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("task_id", "idempotency_key", name="uq_roundtable_artifact_submission_task_key"),
|
||||
Index("ix_roundtable_artifact_submission_task_state_updated", "task_id", "submitted", "updated_at"),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
task_id: Mapped[str] = mapped_column(String(128), nullable=False, index=True)
|
||||
idempotency_key: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
source_key: Mapped[str] = mapped_column(String(512), nullable=False)
|
||||
artifact_path: Mapped[str] = mapped_column(String(2048), nullable=False)
|
||||
revision: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
|
||||
session_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
thread_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
node_key: Mapped[str | None] = mapped_column(String(256), nullable=True)
|
||||
artifact_name: Mapped[str | None] = mapped_column(String(512), nullable=True)
|
||||
mime_type: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
task_delivery_id: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
||||
|
||||
submitted: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||
submitted_at: Mapped[datetime | None] = mapped_column(BeijingDateTime(), nullable=True)
|
||||
cancelled_at: Mapped[datetime | None] = mapped_column(BeijingDateTime(), nullable=True)
|
||||
created_by: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
updated_by: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
submitted_by: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
cancelled_by: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(BeijingDateTime(), nullable=False, default=lambda: datetime.now(UTC))
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
BeijingDateTime(),
|
||||
nullable=False,
|
||||
default=lambda: datetime.now(UTC),
|
||||
onupdate=lambda: datetime.now(UTC),
|
||||
)
|
||||
@@ -0,0 +1,188 @@
|
||||
"""SQLAlchemy-backed task-scoped roundtable artifact-submission store."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||
|
||||
from deerflow.persistence.roundtable_artifact_submissions.base import RoundtableArtifactSubmissionStore
|
||||
from deerflow.persistence.roundtable_artifact_submissions.memory import submission_key
|
||||
from deerflow.persistence.roundtable_artifact_submissions.model import RoundtableArtifactSubmissionRow
|
||||
|
||||
|
||||
def _timestamp(value: datetime | None) -> str | None:
|
||||
return value.isoformat() if isinstance(value, datetime) else value
|
||||
|
||||
|
||||
def _to_dict(row: RoundtableArtifactSubmissionRow) -> dict[str, Any]:
|
||||
return {
|
||||
"id": row.id,
|
||||
"task_id": row.task_id,
|
||||
"idempotency_key": row.idempotency_key,
|
||||
"session_id": row.session_id,
|
||||
"thread_id": row.thread_id,
|
||||
"node_key": row.node_key,
|
||||
"source_key": row.source_key,
|
||||
"path": row.artifact_path,
|
||||
"name": row.artifact_name,
|
||||
"mime_type": row.mime_type,
|
||||
"revision": row.revision,
|
||||
"task_delivery_id": row.task_delivery_id,
|
||||
"submitted": row.submitted,
|
||||
"submitted_at": _timestamp(row.submitted_at),
|
||||
"cancelled_at": _timestamp(row.cancelled_at),
|
||||
"created_by": row.created_by,
|
||||
"updated_by": row.updated_by,
|
||||
"submitted_by": row.submitted_by,
|
||||
"cancelled_by": row.cancelled_by,
|
||||
"created_at": _timestamp(row.created_at),
|
||||
"updated_at": _timestamp(row.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def _apply_artifact(row: RoundtableArtifactSubmissionRow, artifact: dict[str, Any]) -> None:
|
||||
row.session_id = artifact.get("session_id")
|
||||
row.thread_id = artifact.get("thread_id")
|
||||
row.node_key = artifact.get("node_key")
|
||||
row.source_key = artifact["source_key"]
|
||||
row.artifact_path = artifact["path"]
|
||||
row.artifact_name = artifact.get("name")
|
||||
row.mime_type = artifact.get("mime_type")
|
||||
row.revision = int(artifact["revision"])
|
||||
|
||||
|
||||
def _requires_submission_update(
|
||||
row: RoundtableArtifactSubmissionRow,
|
||||
artifact: dict[str, Any],
|
||||
task_delivery_id: str | None,
|
||||
) -> bool:
|
||||
return (
|
||||
not row.submitted
|
||||
or row.task_delivery_id != task_delivery_id
|
||||
or row.session_id != artifact.get("session_id")
|
||||
or row.thread_id != artifact.get("thread_id")
|
||||
or row.node_key != artifact.get("node_key")
|
||||
or row.artifact_name != artifact.get("name")
|
||||
or row.mime_type != artifact.get("mime_type")
|
||||
)
|
||||
|
||||
|
||||
class RoundtableArtifactSubmissionRepository(RoundtableArtifactSubmissionStore):
|
||||
def __init__(self, session_factory: async_sessionmaker[AsyncSession]) -> None:
|
||||
self._sf = session_factory
|
||||
|
||||
async def list_by_task(self, task_id: str, *, submitted: bool | None = True) -> list[dict[str, Any]]:
|
||||
stmt = select(RoundtableArtifactSubmissionRow).where(RoundtableArtifactSubmissionRow.task_id == task_id)
|
||||
if submitted is not None:
|
||||
stmt = stmt.where(RoundtableArtifactSubmissionRow.submitted.is_(submitted))
|
||||
stmt = stmt.order_by(RoundtableArtifactSubmissionRow.updated_at.desc())
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
return [_to_dict(row) for row in result.scalars()]
|
||||
|
||||
async def submit(
|
||||
self,
|
||||
task_id: str,
|
||||
artifact: dict[str, Any],
|
||||
*,
|
||||
task_delivery_id: str | None = None,
|
||||
actor_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
key = submission_key(task_id, artifact)
|
||||
stmt = select(RoundtableArtifactSubmissionRow).where(
|
||||
RoundtableArtifactSubmissionRow.task_id == task_id,
|
||||
RoundtableArtifactSubmissionRow.idempotency_key == key,
|
||||
)
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
row = result.scalars().first()
|
||||
now = datetime.now(UTC)
|
||||
created = row is None
|
||||
if row is None:
|
||||
row = RoundtableArtifactSubmissionRow(
|
||||
id=uuid4().hex,
|
||||
task_id=task_id,
|
||||
idempotency_key=key,
|
||||
task_delivery_id=task_delivery_id,
|
||||
submitted=True,
|
||||
submitted_at=now,
|
||||
created_by=actor_id,
|
||||
updated_by=actor_id,
|
||||
submitted_by=actor_id,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
_apply_artifact(row, artifact)
|
||||
session.add(row)
|
||||
elif _requires_submission_update(row, artifact, task_delivery_id):
|
||||
_apply_artifact(row, artifact)
|
||||
row.task_delivery_id = task_delivery_id
|
||||
row.submitted = True
|
||||
row.submitted_at = now
|
||||
row.cancelled_at = None
|
||||
row.updated_by = actor_id
|
||||
row.submitted_by = actor_id
|
||||
row.cancelled_by = None
|
||||
row.updated_at = now
|
||||
try:
|
||||
await session.commit()
|
||||
except IntegrityError:
|
||||
# Two callers can both observe a missing row. The unique key
|
||||
# turns that race into a normal idempotent retry instead of a
|
||||
# 500. If their non-key metadata differs, apply this request
|
||||
# after loading the winner so PUT still has upsert semantics.
|
||||
await session.rollback()
|
||||
if not created:
|
||||
raise
|
||||
result = await session.execute(stmt)
|
||||
row = result.scalars().first()
|
||||
if row is None:
|
||||
raise
|
||||
if _requires_submission_update(row, artifact, task_delivery_id):
|
||||
now = datetime.now(UTC)
|
||||
_apply_artifact(row, artifact)
|
||||
row.task_delivery_id = task_delivery_id
|
||||
row.submitted = True
|
||||
row.submitted_at = now
|
||||
row.cancelled_at = None
|
||||
row.updated_by = actor_id
|
||||
row.submitted_by = actor_id
|
||||
row.cancelled_by = None
|
||||
row.updated_at = now
|
||||
await session.commit()
|
||||
await session.refresh(row)
|
||||
return _to_dict(row)
|
||||
|
||||
async def cancel(
|
||||
self,
|
||||
task_id: str,
|
||||
artifact: dict[str, Any],
|
||||
*,
|
||||
submission_id: str | None = None,
|
||||
actor_id: str | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
key = submission_key(task_id, artifact)
|
||||
stmt = select(RoundtableArtifactSubmissionRow).where(
|
||||
RoundtableArtifactSubmissionRow.task_id == task_id,
|
||||
RoundtableArtifactSubmissionRow.idempotency_key == key,
|
||||
)
|
||||
async with self._sf() as session:
|
||||
result = await session.execute(stmt)
|
||||
row = result.scalars().first()
|
||||
if row is None or (submission_id is not None and row.id != submission_id):
|
||||
return None
|
||||
if row.submitted:
|
||||
now = datetime.now(UTC)
|
||||
row.submitted = False
|
||||
row.cancelled_at = now
|
||||
row.updated_by = actor_id
|
||||
row.cancelled_by = actor_id
|
||||
row.updated_at = now
|
||||
await session.commit()
|
||||
await session.refresh(row)
|
||||
return _to_dict(row)
|
||||
@@ -117,6 +117,11 @@ CALL _add_column_if_missing('knowledge_notes', 'folder', 'VARCHAR(512) NULL DEFA
|
||||
-- ORM: RoundtableJobRow.task_id = String(128), nullable, indexed。
|
||||
CALL _add_column_if_missing('roundtable_jobs', 'task_id', 'VARCHAR(128) NULL DEFAULT NULL');
|
||||
|
||||
-- ---- position_roundtable_sessions: opt-in task sharing, migration 20260808_01 ----
|
||||
-- Existing records remain personal (`task_scoped = 0`). New records become
|
||||
-- shared only when the caller explicitly sends a non-empty route taskId.
|
||||
CALL _add_column_if_missing('position_roundtable_sessions', 'task_scoped', 'TINYINT(1) NOT NULL DEFAULT 0');
|
||||
|
||||
-- ---- 按钮管理「外部链接」追加登录参数,对应 migration 20260625_01 ----------------
|
||||
-- login_params_json: url 外链追加的登录参数列表 JSON([{key,source,custom_value},...]),
|
||||
-- 由前端运行时从 userInfo 解析后拼到地址尾部;NULL/空 = 不追加(旧行为)。
|
||||
@@ -199,5 +204,6 @@ SELECT table_name, column_name
|
||||
OR (table_name = 'agents' AND column_name IN ('square_id'))
|
||||
OR (table_name = 'roundtable_drafts' AND column_name = 'task_id')
|
||||
OR (table_name = 'roundtable_jobs' AND column_name = 'task_id')
|
||||
OR (table_name = 'position_roundtable_sessions' AND column_name = 'task_scoped')
|
||||
OR (table_name = 'task_buttons' AND column_name IN ('append_auth', 'auth_token_param', 'auth_name_param')))
|
||||
ORDER BY table_name, column_name;
|
||||
@@ -68,6 +68,10 @@ CALL _create_index_if_missing('llm_call_metrics', 'ix_llm_call_metrics_run_creat
|
||||
CALL _create_index_if_missing('threads_meta', 'ix_threads_meta_created_user', '`created_at`, `user_id`');
|
||||
CALL _create_index_if_missing('threads_meta', 'ix_threads_meta_user_created', '`user_id`, `created_at`');
|
||||
|
||||
-- ---- position_roundtable_sessions --------------------------------------------
|
||||
-- Explicit taskId history is loaded by taskId and newest update time.
|
||||
CALL _create_index_if_missing('position_roundtable_sessions', 'ix_position_roundtable_sessions_task_updated', '`external_task_id`, `updated_at`');
|
||||
|
||||
-- ---- 清理临时存储过程 --------------------------------------------------------
|
||||
DROP PROCEDURE IF EXISTS _create_index_if_missing;
|
||||
|
||||
|
||||
@@ -14,9 +14,14 @@ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
from app.gateway import deps as gateway_deps
|
||||
from app.gateway import services as gateway_services
|
||||
from app.gateway.app import create_app
|
||||
from app.gateway.routers import _roundtable_seed as roundtable_seed
|
||||
from app.gateway.routers import intent as intent_router
|
||||
from app.gateway.routers import multi_agent
|
||||
from app.gateway.routers import position_roundtable as position_roundtable_router
|
||||
from app.gateway.routers._roundtable_seed import (
|
||||
POSITION_INTENT_AGENT_ID,
|
||||
required_agent_ids,
|
||||
)
|
||||
from deerflow.persistence.base import Base
|
||||
from deerflow.persistence.position_roundtable import PositionRoundtableRepository
|
||||
from deerflow.persistence.thread_meta.sql import ThreadMetaRepository
|
||||
@@ -55,6 +60,111 @@ def test_position_roundtable_router_has_intranet_compatibility_prefix():
|
||||
assert position_roundtable_router.router.prefix == "/position-roundtable"
|
||||
|
||||
|
||||
def test_position_intent_agent_is_a_seeded_functional_agent():
|
||||
"""Fresh deployments must materialize the dedicated position intent agent."""
|
||||
assert POSITION_INTENT_AGENT_ID in set(required_agent_ids())
|
||||
|
||||
|
||||
def test_position_intent_prompt_keeps_the_original_step_one_guardrails():
|
||||
"""Dedicated schema must not regress into solutioning or gatekeeping."""
|
||||
prompt = (
|
||||
roundtable_seed._ASSETS_DIR / POSITION_INTENT_AGENT_ID / "SOUL.md"
|
||||
).read_text(encoding="utf-8")
|
||||
|
||||
for phrase in (
|
||||
"最多 5 轮用户协助",
|
||||
"除 ask_clarification 外,禁止调用任何工具、技能或操作",
|
||||
"你都不拒绝、不评价、不设限",
|
||||
"不得说“不能帮你”“不在职责范围内”“请换一个问题”",
|
||||
"coreGoals / riskWarnings / keyPoints / strategicSignificance",
|
||||
"不能把“主题已识别”误判为“意图已明确”",
|
||||
"任何任务若缺少范围、对象、时间、决策用途、重点维度或成功标准等关键信息时,必须请求用户协助",
|
||||
"必须分析任务级风险",
|
||||
"同一轮可发起多张用户协助卡",
|
||||
"不得把多个问题塞进一张卡",
|
||||
):
|
||||
assert phrase in prompt
|
||||
|
||||
|
||||
def test_position_intent_clarification_waits_for_the_user_before_ready():
|
||||
"""A same-run READY block must not consume the user-assistance pause."""
|
||||
assert intent_router._clarification_blocks_ready(
|
||||
intent_router.POSITION_INTENT_AGENT_ID,
|
||||
{"name": "ask_clarification"},
|
||||
is_fresh=True,
|
||||
)
|
||||
assert not intent_router._clarification_blocks_ready(
|
||||
intent_router.INTENT_AGENT_ID,
|
||||
{"name": "ask_clarification"},
|
||||
is_fresh=True,
|
||||
)
|
||||
assert not intent_router._clarification_blocks_ready(
|
||||
intent_router.POSITION_INTENT_AGENT_ID,
|
||||
None,
|
||||
is_fresh=True,
|
||||
)
|
||||
assert not intent_router._clarification_blocks_ready(
|
||||
intent_router.POSITION_INTENT_AGENT_ID,
|
||||
{"name": "ask_clarification"},
|
||||
is_fresh=False,
|
||||
)
|
||||
|
||||
|
||||
def test_position_intent_counts_multi_card_assistance_as_one_round():
|
||||
"""Five user-assistance rounds must not be consumed by five cards at once."""
|
||||
messages: list[dict[str, Any]] = [
|
||||
{
|
||||
"type": "ai",
|
||||
"tool_calls": [
|
||||
{"id": "scope", "name": "ask_clarification", "args": {}},
|
||||
{"id": "purpose", "name": "ask_clarification", "args": {}},
|
||||
{"id": "time", "name": "ask_clarification", "args": {}},
|
||||
],
|
||||
},
|
||||
{"type": "human", "content": "用户统一答复"},
|
||||
{
|
||||
"type": "ai",
|
||||
"tool_calls": [
|
||||
{"id": "risk", "name": "ask_clarification", "args": {}},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
assert intent_router._count_past_clarifications(messages) == 4
|
||||
assert intent_router._count_past_clarification_rounds(messages) == 2
|
||||
assert intent_router._max_clarification_rounds(intent_router.INTENT_AGENT_ID) == 3
|
||||
assert (
|
||||
intent_router._max_clarification_rounds(intent_router.POSITION_INTENT_AGENT_ID)
|
||||
== 5
|
||||
)
|
||||
|
||||
|
||||
def test_position_intent_seed_repairs_its_contract_without_touching_other_agents(tmp_path, monkeypatch):
|
||||
"""The dedicated schema prompt must replace an accidentally seeded old version."""
|
||||
agents_dir = tmp_path / "agents"
|
||||
monkeypatch.setattr(
|
||||
roundtable_seed,
|
||||
"get_paths",
|
||||
lambda: SimpleNamespace(agent_dir=lambda agent_id: agents_dir / agent_id),
|
||||
)
|
||||
|
||||
position_dir = agents_dir / POSITION_INTENT_AGENT_ID
|
||||
position_dir.mkdir(parents=True)
|
||||
(position_dir / "SOUL.md").write_text("outdated prompt", encoding="utf-8")
|
||||
assert roundtable_seed._ensure_one(POSITION_INTENT_AGENT_ID) is True
|
||||
expected_soul = (
|
||||
roundtable_seed._ASSETS_DIR / POSITION_INTENT_AGENT_ID / "SOUL.md"
|
||||
).read_text(encoding="utf-8")
|
||||
assert (position_dir / "SOUL.md").read_text(encoding="utf-8") == expected_soul
|
||||
|
||||
generic_dir = agents_dir / roundtable_seed.INTENT_AGENT_ID
|
||||
generic_dir.mkdir(parents=True)
|
||||
generic_soul = generic_dir / "SOUL.md"
|
||||
generic_soul.write_text("deployed generic tune", encoding="utf-8")
|
||||
assert roundtable_seed._ensure_one(roundtable_seed.INTENT_AGENT_ID) is False
|
||||
assert generic_soul.read_text(encoding="utf-8") == "deployed generic tune"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_intent_init_creates_thread_directly_without_loopback(monkeypatch):
|
||||
"""Step 1 initialization must not depend on the deployed Gateway port."""
|
||||
@@ -91,6 +201,71 @@ async def test_intent_init_creates_thread_directly_without_loopback(monkeypatch)
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_position_intent_init_selects_its_dedicated_agent(monkeypatch):
|
||||
"""Position roundtable must never mutate the generic Step-1 agent contract."""
|
||||
captured: dict[str, object] = {}
|
||||
monkeypatch.setattr(intent_router, "ensure_roundtable_functional_agents", lambda: None)
|
||||
|
||||
async def fake_create_thread_direct(request, *, metadata):
|
||||
captured["metadata"] = metadata
|
||||
return "position-intent-thread"
|
||||
|
||||
monkeypatch.setattr(intent_router, "_create_thread_direct", fake_create_thread_direct)
|
||||
|
||||
result = await intent_router.init_intent(
|
||||
SimpleNamespace(),
|
||||
{
|
||||
"intent_agent_id": intent_router.POSITION_INTENT_AGENT_ID,
|
||||
"task_context": {"task": {"id": "task-position-001"}},
|
||||
},
|
||||
)
|
||||
|
||||
assert result == {
|
||||
"status": "success",
|
||||
"agent_id": intent_router.POSITION_INTENT_AGENT_ID,
|
||||
"thread_id": "position-intent-thread",
|
||||
}
|
||||
assert captured["metadata"] == {
|
||||
**intent_router._ROUNDTABLE_THREAD_METADATA,
|
||||
"taskId": "task-position-001",
|
||||
"position_roundtable_task_id": "task-position-001",
|
||||
"position_task_id": "task-position-001:intelligence",
|
||||
"position_id": "intelligence",
|
||||
"position_roundtable_phase": "intent",
|
||||
"position_roundtable_intent_agent_id": intent_router.POSITION_INTENT_AGENT_ID,
|
||||
}
|
||||
|
||||
|
||||
def test_position_intent_schema_is_required_for_new_snapshots_and_legacy_is_kept():
|
||||
assert position_roundtable_router._has_confirmed_intent(
|
||||
{
|
||||
"coreGoals": ["形成统一处置方案"],
|
||||
"riskWarnings": [],
|
||||
"keyPoints": ["需要在本周完成"],
|
||||
"strategicSignificance": ["为后续岗位协同提供统一边界"],
|
||||
}
|
||||
)
|
||||
assert not position_roundtable_router._has_confirmed_intent(
|
||||
{"coreGoals": ["形成统一处置方案"], "riskWarnings": []}
|
||||
)
|
||||
assert position_roundtable_router._has_confirmed_intent(
|
||||
{"objective": "历史任务", "constraints": []}
|
||||
)
|
||||
answer = position_roundtable_router._intent_node_answer(
|
||||
{
|
||||
"coreGoals": ["形成统一处置方案"],
|
||||
"riskWarnings": ["关键数据尚待确认"],
|
||||
"keyPoints": ["聚焦当前任务范围"],
|
||||
"strategicSignificance": ["支撑业务链协同推进"],
|
||||
}
|
||||
)
|
||||
assert "核心目标" in answer
|
||||
assert "风险提示" in answer
|
||||
assert "关键要点" in answer
|
||||
assert "战略意义" in answer
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_session_activation_freezes_chain_and_creates_nodes_once(store):
|
||||
created = await store.create_session(
|
||||
@@ -208,14 +383,91 @@ async def test_conversation_snapshots_round_trip_and_history_delete_removes_node
|
||||
assert saved_node is not None
|
||||
assert saved_node["conversation_snapshot"] == node_conversation
|
||||
|
||||
# Ownership checks apply to delete as well.
|
||||
assert not await store.delete_session(created["id"], "user-b")
|
||||
assert await store.get_session(created["id"], "user-a") is not None
|
||||
assert await store.delete_session(created["id"], "user-a")
|
||||
# Position roundtable history is shared by taskId, so a collaborator can
|
||||
# read and remove the same task conversation without being its creator.
|
||||
assert await store.get_session(created["id"], "user-b") is not None
|
||||
assert await store.delete_session(created["id"], "user-b")
|
||||
assert await store.get_session(created["id"], "user-a") is None
|
||||
assert await store.list_nodes(created["id"], "user-a") is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_task_scoped_history_is_shared_but_never_mixes_tasks(store):
|
||||
shared = await store.create_session(
|
||||
"user-a",
|
||||
external_task_id="external-task-100",
|
||||
task_snapshot={"id": "external-task-100", "title": "共享任务"},
|
||||
)
|
||||
await store.create_session(
|
||||
"user-b",
|
||||
external_task_id="external-task-200",
|
||||
task_snapshot={"id": "external-task-200", "title": "另一任务"},
|
||||
)
|
||||
|
||||
visible_to_collaborator = await store.list_sessions(
|
||||
"user-b", external_task_id="external-task-100"
|
||||
)
|
||||
assert [row["id"] for row in visible_to_collaborator] == [shared["id"]]
|
||||
|
||||
updated = await store.update_session(
|
||||
shared["id"],
|
||||
"user-b",
|
||||
task_snapshot={"id": "external-task-100", "title": "协作者已更新"},
|
||||
)
|
||||
assert updated is not None
|
||||
assert updated["task_snapshot"]["title"] == "协作者已更新"
|
||||
assert (await store.get_session(shared["id"], "user-a"))["task_snapshot"]["title"] == "协作者已更新"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unscoped_history_keeps_original_user_isolation(store):
|
||||
personal = await store.create_session(
|
||||
"user-a",
|
||||
external_task_id=None,
|
||||
task_snapshot={"id": "legacy-card-id", "title": "个人会话"},
|
||||
)
|
||||
|
||||
assert await store.get_session(personal["id"], "user-b") is None
|
||||
assert await store.list_sessions("user-b") == []
|
||||
assert await store.update_session(personal["id"], "user-b", status="active") is None
|
||||
assert not await store.delete_session(personal["id"], "user-b")
|
||||
|
||||
# Old client records could already carry a mock task id. The new database
|
||||
# marker keeps them personal after the migration; only a new explicit
|
||||
# route taskId creates a shared row.
|
||||
legacy_with_mock_task_id = await store.create_session(
|
||||
"user-a",
|
||||
external_task_id="legacy-mock-task-id",
|
||||
task_scoped=False,
|
||||
task_snapshot={"id": "legacy-card-id", "title": "鏃х増涓汉浼氳瘽"},
|
||||
)
|
||||
assert await store.get_session(legacy_with_mock_task_id["id"], "user-b") is None
|
||||
assert await store.list_sessions("user-b", external_task_id="legacy-mock-task-id") == []
|
||||
|
||||
|
||||
def test_session_create_allows_missing_task_id_and_scoped_snapshots_keep_scope():
|
||||
body = position_roundtable_router.SessionCreateRequest(
|
||||
external_task_id=" task-route-001 ",
|
||||
task_snapshot={"id": "wrong-id", "title": "任务"},
|
||||
)
|
||||
assert body.external_task_id == "task-route-001"
|
||||
assert position_roundtable_router._task_snapshot_for_scope(
|
||||
body.external_task_id,
|
||||
body.task_snapshot,
|
||||
) == {
|
||||
"id": "task-route-001",
|
||||
"externalTaskId": "task-route-001",
|
||||
"title": "任务",
|
||||
}
|
||||
assert position_roundtable_router.SessionCreateRequest(task_snapshot={}).external_task_id is None
|
||||
assert position_roundtable_router.SessionCreateRequest(external_task_id=" ").external_task_id is None
|
||||
assert position_roundtable_router._task_snapshot_for_scope(
|
||||
"legacy-mock-task-id",
|
||||
{"id": "legacy-card-id", "title": "旧记录"},
|
||||
task_scoped=False,
|
||||
) == {"id": "legacy-card-id", "title": "旧记录"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_demo_seed_is_complete_idempotent_and_user_scoped(store):
|
||||
payload = {
|
||||
@@ -490,6 +742,7 @@ async def test_builtin_summary_completion_persists_fallback_markdown_when_agent_
|
||||
}
|
||||
session = {
|
||||
"id": "session-a",
|
||||
"external_task_id": "task-fallback",
|
||||
"status": "active",
|
||||
"task_snapshot": {},
|
||||
"chain_id": "chain-a",
|
||||
@@ -561,7 +814,7 @@ async def test_builtin_summary_completion_persists_fallback_markdown_when_agent_
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_node_updates_are_user_scoped_and_keep_thread_out_of_messages(store):
|
||||
async def test_node_updates_are_user_scoped_without_task_id(store):
|
||||
created = await store.create_session("user-a", external_task_id=None, task_snapshot={})
|
||||
_, nodes = await store.activate_session(
|
||||
created["id"],
|
||||
@@ -602,7 +855,9 @@ async def test_node_updates_are_user_scoped_and_keep_thread_out_of_messages(stor
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reject_node_marks_current_and_invalidates_later_stages(store):
|
||||
created = await store.create_session("user-a", external_task_id=None, task_snapshot={})
|
||||
created = await store.create_session(
|
||||
"user-a", external_task_id="task-reject", task_snapshot={}
|
||||
)
|
||||
_, nodes = await store.activate_session(
|
||||
created["id"],
|
||||
"user-a",
|
||||
@@ -682,7 +937,7 @@ async def test_reject_node_marks_current_and_invalidates_later_stages(store):
|
||||
async def test_builtin_summary_and_action_plan_snapshots_are_invalidated_by_reject(store):
|
||||
created = await store.create_session(
|
||||
"user-a",
|
||||
external_task_id=None,
|
||||
external_task_id="task-builtin-invalidation",
|
||||
task_snapshot={
|
||||
"title": "测试任务",
|
||||
"description": "形成协同方案",
|
||||
|
||||
@@ -116,3 +116,13 @@ async def test_unknown_mode_value_ignored_falls_through(_gw):
|
||||
await _run(gateway)
|
||||
assert captured["thinking_enabled"] is True
|
||||
assert captured["reasoning_effort"] == "low"
|
||||
|
||||
|
||||
def test_chain_seat_schema_keeps_human_validation_checkpoint():
|
||||
"""Chain-seat JSON must preserve the frontend Step 2 pause configuration."""
|
||||
from app.gateway.routers.roundtable_chains import ChainSeatSchema
|
||||
|
||||
assert ChainSeatSchema(agent_id="seat-1").human_validation is False
|
||||
assert ChainSeatSchema(agent_id="seat-1", human_validation=True).model_dump()[
|
||||
"human_validation"
|
||||
] is True
|
||||
|
After Width: | Height: | Size: 99 KiB |
|
After Width: | Height: | Size: 136 KiB |
|
After Width: | Height: | Size: 117 KiB |
|
After Width: | Height: | Size: 118 KiB |
|
After Width: | Height: | Size: 111 KiB |
|
After Width: | Height: | Size: 131 KiB |
|
After Width: | Height: | Size: 116 KiB |
|
After Width: | Height: | Size: 99 KiB |
|
After Width: | Height: | Size: 96 KiB |
@@ -0,0 +1,624 @@
|
||||
from __future__ import annotations
|
||||
|
||||
"""Build the user-focused DeerFlow maintenance handbook.
|
||||
|
||||
This deliberately reuses the established Word style helpers and diagrams from
|
||||
the original builder, but changes the information architecture for a normal
|
||||
Docker deployment: no 1Panel-, ARM-, or platform-specific deployment content.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import build_manual as b
|
||||
|
||||
|
||||
OUT = Path(__file__).resolve().parent / "DeerFlow系统运维手册-用户重点版.docx"
|
||||
|
||||
|
||||
def set_running_furniture(doc):
|
||||
"""Replace the prior deployment-specific running header/footer."""
|
||||
header_p = doc.sections[0].header.paragraphs[0]
|
||||
header_p.clear()
|
||||
header_p.alignment = b.WD_ALIGN_PARAGRAPH.RIGHT
|
||||
run = header_p.add_run("DeerFlow 系统运维手册 | 用户重点版")
|
||||
b.set_run_font(run, size=8.5, color=b.GRAY)
|
||||
|
||||
footer_p = doc.sections[0].footer.paragraphs[0]
|
||||
footer_p.clear()
|
||||
footer_p.alignment = b.WD_ALIGN_PARAGRAPH.CENTER
|
||||
run = footer_p.add_run("内部运维资料 · 第 ")
|
||||
b.set_run_font(run, size=8.5, color=b.GRAY)
|
||||
b.add_field(footer_p, "PAGE", "1")
|
||||
run = footer_p.add_run(" 页")
|
||||
b.set_run_font(run, size=8.5, color=b.GRAY)
|
||||
|
||||
|
||||
def add_cover(doc, diagrams):
|
||||
p = doc.add_paragraph()
|
||||
p.paragraph_format.space_before = b.Inches(0.78)
|
||||
p.paragraph_format.space_after = b.Pt(10)
|
||||
run = p.add_run("DeerFlow")
|
||||
b.set_run_font(run, size=16, bold=True, color=b.BLUE)
|
||||
|
||||
p = doc.add_paragraph(style="Title")
|
||||
p.paragraph_format.space_before = b.Pt(16)
|
||||
run = p.add_run("系统运维手册")
|
||||
b.set_run_font(run, size=30, bold=True, color=b.DARK_BLUE)
|
||||
p = doc.add_paragraph(style="Subtitle")
|
||||
run = p.add_run("通用 Docker 容器版 · 配置、资产与故障处理优先")
|
||||
b.set_run_font(run, size=15, color=b.GRAY)
|
||||
b.add_figure(doc, diagrams["architecture"], "系统访问与数据流概览", "浏览器经由 Web 容器访问前端和后端服务的流程", width=6.1)
|
||||
b.add_callout(
|
||||
doc,
|
||||
"本版重点",
|
||||
"以常规 Docker 容器运行环境为基准;将常见报错、config.yaml、.env、技能/智能体和前端管理设置提前,便于业务管理员直接查用。",
|
||||
"note",
|
||||
)
|
||||
b.add_table(
|
||||
doc,
|
||||
["文档版本", "适用范围", "更新日期"],
|
||||
[["V1.1", "当前 DeerFlow Docker 部署包及本项目定制功能", "2026-08-08"]],
|
||||
[1800, 5000, 2560],
|
||||
font_size=9.2,
|
||||
)
|
||||
b.add_para(doc, "密级:内部运维资料。密钥、密码、IP、数据库账号均必须使用占位符;不要写入本手册。", italic=True, align=b.WD_ALIGN_PARAGRAPH.CENTER, after=0)
|
||||
|
||||
|
||||
def add_navigation(doc):
|
||||
p = doc.add_paragraph(style="Title")
|
||||
p.paragraph_format.page_break_before = True
|
||||
run = p.add_run("先用目录找到答案")
|
||||
b.set_run_font(run, size=24, bold=True, color=b.DARK_BLUE)
|
||||
b.add_para(doc, "本手册按“先排错、再配置、再维护”的顺序编排。打开 Word 后可使用左侧导航窗格按标题跳转;目录页码没有更新时,按 Ctrl+A 后按 F9。")
|
||||
toc = doc.add_paragraph()
|
||||
toc.paragraph_format.space_after = b.Pt(8)
|
||||
b.add_field(toc, r'TOC \o "1-3" \h \z \u', "目录将在 Word 中自动更新")
|
||||
b.add_callout(doc, "最常用的五处", "页面或服务异常先看第 1 章;模型与 max_tokens 看第 2 章;登录、数据库和接口地址看第 3 章;技能/智能体问题看第 4 章;菜单、敏感词、主题看第 5 章。", "ok")
|
||||
b.add_h2(doc, "阅读约定")
|
||||
for text in [
|
||||
"“部署目录”指存放 docker-compose.yml、.env、config 和 data 的当前运行目录。所有命令都应在此目录执行。",
|
||||
"前端和后端不是同一个容器端口。用户通常只访问 APP_PORT;Web/Nginx 会把 /deerflow 请求转发到后端。",
|
||||
"改配置前先备份原文件;改完只重启受影响服务;保存日志、健康检查和实际功能验证结果。",
|
||||
"本文中的 <尖括号内容> 都是待替换占位符,不能原样复制到生产环境。",
|
||||
]:
|
||||
b.add_bullet(doc, text)
|
||||
|
||||
|
||||
def add_chapter_common_errors(doc):
|
||||
b.add_h1(doc, "1. 常见报错与第一时间怎么处理")
|
||||
b.add_para(doc, "先收集状态再修改配置。大多数问题并非代码故障,而是当前目录错误、环境变量未重新加载、后端未启动、数据库连不上、权限不足或资产被过滤。")
|
||||
b.add_h2(doc, "1.1 先执行这组无损检查")
|
||||
b.add_code(doc, """
|
||||
# 必须在部署目录执行
|
||||
pwd
|
||||
sudo docker compose ps
|
||||
sudo docker compose logs --tail=200 backend
|
||||
sudo docker compose logs --tail=200 web
|
||||
curl -fsS http://127.0.0.1:<APP_PORT>/deerflow/health
|
||||
""", "Shell")
|
||||
b.add_callout(doc, "先不要做", "不要执行 docker system prune -a;不要删除 data 后重启;不要创建同名技能或智能体覆盖可能的恢复线索;不要把完整 backend.env 发到群里。", "danger")
|
||||
b.add_h2(doc, "1.2 容器、端口和磁盘")
|
||||
b.add_table(
|
||||
doc,
|
||||
["现象/报错", "优先检查", "处理方式"],
|
||||
[
|
||||
["address already in use", "APP_PORT 已被其他进程占用", "用 ss -lntp 查占用;修改部署目录 .env 的 APP_PORT,然后重建 web。"],
|
||||
["容器不断 Restarting", "backend 的最后 200 行日志", "重点查看 YAML、环境变量、数据库 URL、挂载权限或启动命令;修复后再重建 backend。"],
|
||||
["no space left on device", "磁盘、inode、data 和日志目录", "先清理可确认的旧日志或无用缓存;不要在未备份时清理 data 或盲目 prune。"],
|
||||
["permission denied", "宿主机挂载目录所有者和容器运行用户", "核对 compose volume 与目录权限;只对目标目录做最小权限修正,不使用 chmod -R 777。"],
|
||||
["Web 访问失败", "docker compose ps、APP_PORT、主机防火墙", "确认 web 容器正常、端口监听,并放行实际访问端口。"],
|
||||
],
|
||||
[2200, 2650, 4510],
|
||||
font_size=8.8,
|
||||
)
|
||||
b.add_h2(doc, "1.3 前端、Nginx 和接口")
|
||||
b.add_table(
|
||||
doc,
|
||||
["现象", "原因方向", "解决"],
|
||||
[
|
||||
["502 Bad Gateway", "backend 未启动或 Web 无法访问 backend:8001", "先查 backend 日志和 Compose 网络;后端恢复后再刷新前端。"],
|
||||
["刷新二级页面 404", "Nginx 的 SPA 回退缺失", "恢复 Nginx 的 try_files 到 /index.html 配置并重启 web。"],
|
||||
["页面白屏", "runtime-config.js 语法或地址错误、缓存未刷新", "浏览器 Console/Network 定位;恢复配置,重启 web,使用 Ctrl+F5。"],
|
||||
["所有 API 都失败", "VITE_BACKEND_BASE_URL 或 VITE_LANGGRAPH_BASE_URL 配错", "优先恢复 /deerflow 和 /deerflow/api 相对路径;见第 3.5 节。"],
|
||||
["CORS / Mixed Content", "前后端不同源或 HTTPS 页面调用 HTTP 接口", "优先同源代理;必须跨域时在后端配置允许 Origin 并统一 HTTPS。"],
|
||||
],
|
||||
[2100, 3000, 4260],
|
||||
font_size=8.8,
|
||||
)
|
||||
b.add_h2(doc, "1.4 登录、模型、数据库和资产")
|
||||
b.add_table(
|
||||
doc,
|
||||
["现象/状态", "最常见原因", "首要动作"],
|
||||
[
|
||||
["401 / invalid_api_key", "模型 Key 缺失、变量名不一致或已过期", "对照 config.yaml 的 $变量名 与 backend.env;更新后强制重建 backend。"],
|
||||
["404 model not found", "model 写成显示名或 base_url 路径不兼容", "使用服务商实际 model ID;核对 API 是否要求 /v1。"],
|
||||
["429 / timeout", "并发、配额、模型服务或网络问题", "降低并发/重试,检查模型服务和网络连通性。"],
|
||||
["401 / 403 登录或发布失败", "Token 过期、角色/所有者不足、广场未启用", "重新登录;核对 system_role、资产所有者和目标广场。"],
|
||||
["技能/智能体看不到", "目录未挂载、数据库切换、过滤、权限或发布状态", "按第 4.6 节逐步排查,不要立即新建同名资产。"],
|
||||
["MySQL Access denied / timeout", "账号、密码 URL 编码、host 授权、网络或端口", "查看第 3.4 节连接格式和第 7 章数据库恢复原则。"],
|
||||
],
|
||||
[2250, 3150, 3960],
|
||||
font_size=8.65,
|
||||
)
|
||||
|
||||
|
||||
def add_chapter_model(doc, diagrams):
|
||||
b.add_h1(doc, "2. config.yaml:模型、max_tokens 与后端配置")
|
||||
b.add_para(doc, "模型条目由 config/config.yaml 管理;密钥由 config/backend.env 管理。两处的变量名必须完全一致。新增模型时先写密钥,再写模型条目,再验证后端日志和实际对话。")
|
||||
b.add_figure(doc, diagrams["model_flow"], "图 2-1 模型配置与验证闭环", "从密钥、模型条目到后端验证和前端选择的流程", width=6.35)
|
||||
b.add_h2(doc, "2.1 新增或修改一个 OpenAI 兼容模型")
|
||||
b.add_number(doc, "备份 config/backend.env 和 config/config.yaml,并记录要替换的模型名称。")
|
||||
b.add_number(doc, "在 backend.env 写入密钥,变量名仅供后端读取。")
|
||||
b.add_code(doc, """
|
||||
# config/backend.env
|
||||
INTRANET_MODEL_API_KEY=<服务商分配的密钥>
|
||||
""", "ENV")
|
||||
b.add_number(doc, "在 config.yaml 的 models: 下增加或修改模型条目。name 是系统引用名;model 是服务商真实模型 ID;display_name 是前端显示名。")
|
||||
b.add_code(doc, """
|
||||
models:
|
||||
- name: intranet-model
|
||||
display_name: 内网模型
|
||||
use: langchain_openai:ChatOpenAI
|
||||
model: <服务商实际模型ID>
|
||||
api_key: $INTRANET_MODEL_API_KEY
|
||||
base_url: https://<模型服务地址>/v1
|
||||
request_timeout: 600.0
|
||||
max_retries: 2
|
||||
max_tokens: 4096
|
||||
temperature: 0.7
|
||||
supports_vision: false
|
||||
supports_thinking: false
|
||||
""", "YAML")
|
||||
b.add_number(doc, "强制重建 backend 以重新读取 backend.env;随后查看启动日志、健康检查和前端模型列表。")
|
||||
b.add_code(doc, """
|
||||
sudo docker compose up -d --force-recreate backend
|
||||
sudo docker compose logs --tail=300 -f backend
|
||||
curl -fsS http://127.0.0.1:<APP_PORT>/deerflow/health
|
||||
""", "Shell")
|
||||
b.add_h2(doc, "2.2 字段说明与常见误配")
|
||||
b.add_table(
|
||||
doc,
|
||||
["字段", "用途", "常见问题"],
|
||||
[
|
||||
["name", "系统内部模型名称,配置引用以它为准", "重名会覆盖或引用混乱;不要随意改已被智能体使用的 name。"],
|
||||
["display_name", "前端显示名称", "改显示名不等于改 model;可用于给业务人员更易懂的名字。"],
|
||||
["use", "适配器,例如 langchain_openai:ChatOpenAI", "适配器与接口协议不匹配会导致初始化失败。"],
|
||||
["model", "模型服务商要求的真实 ID", "误填显示名经常造成 404 model not found。"],
|
||||
["api_key", "使用 $变量名 从 backend.env 读取密钥", "写明文、变量拼错或漏掉 $ 都会导致鉴权失败。"],
|
||||
["base_url", "接口基地址", "有的服务要求 /v1,有的路径已包含 /v1;以服务商接口文档为准。"],
|
||||
["request_timeout / max_retries", "单次等待时间与失败重试次数", "超时不等于模型不存在,先检查服务和网络。"],
|
||||
["max_tokens", "单次生成输出上限", "不是输入+输出总上下文窗口,不能超过服务商允许的最大输出。"],
|
||||
],
|
||||
[1850, 2850, 4660],
|
||||
font_size=8.45,
|
||||
)
|
||||
b.add_h2(doc, "2.3 如何添加或调整 max_tokens")
|
||||
b.add_para(doc, "在目标模型条目中添加或修改 max_tokens: <整数>。它控制单次回答最多生成多少 token。回答被截断时可在服务商允许范围内逐步增加;成本或响应时间异常时应适度降低。")
|
||||
b.add_table(
|
||||
doc,
|
||||
["现象", "判断", "处理"],
|
||||
[
|
||||
["回答结尾被截断", "max_tokens 太小,或服务端提前结束", "先查看 finish_reason;确认服务商上限后逐步提高。"],
|
||||
["400 invalid max_tokens", "超过模型限制或字段不兼容", "按服务商模型上限修改;必要时删除该字段验证兼容性。"],
|
||||
["长文本仍失败", "上下文不足,不只是输出上限", "缩短输入、启用摘要或选择更大上下文模型。"],
|
||||
["费用/耗时异常", "输出限制过高或提示词过长", "降低 max_tokens;优化提示词和业务限流。"],
|
||||
],
|
||||
[2000, 3000, 4360],
|
||||
font_size=8.9,
|
||||
)
|
||||
b.add_h2(doc, "2.4 后端模型变更后的验收")
|
||||
for text in [
|
||||
"YAML 使用空格缩进,不能使用 Tab;密钥变量名必须同时存在于 backend.env 和 config.yaml。",
|
||||
"修改 backend.env 后必须使用 docker compose up -d --force-recreate backend;普通 restart 不会重新读取环境文件。",
|
||||
"只修改 config.yaml 时可重启 backend,但仍应查看日志确认配置解析成功。",
|
||||
"先进行短问答验证,再验证长文本、工具调用、视觉输入或思考模式(如果该模型声明支持)。",
|
||||
"记录模型 name、服务地址、变更人、验证时间;不要把 API Key 写入变更单或截图。",
|
||||
]:
|
||||
b.add_bullet(doc, text)
|
||||
|
||||
|
||||
def add_chapter_config(doc, diagrams):
|
||||
b.add_h1(doc, "3. .env、backend.env、数据库与前端接口地址")
|
||||
b.add_para(doc, "部署目录的运行配置分为三类:.env 控制 Compose 与对外端口;backend.env 保存后端密钥和连接串;config.yaml 定义模型、登录、数据库模式等;runtime-config.js 控制前端运行时接口地址。不要进入容器直接改文件。")
|
||||
b.add_figure(doc, diagrams["config_layers"], "图 3-1 配置分层与生效方式", "部署层、后端层、前端运行时层和管理页面配置的关系", width=6.35)
|
||||
heading = b.add_h2(doc, "3.1 .env:项目名、镜像标签、访问端口")
|
||||
heading.paragraph_format.page_break_before = True
|
||||
b.add_code(doc, """
|
||||
# 部署目录 .env
|
||||
COMPOSE_PROJECT_NAME=deerflow
|
||||
DEERFLOW_TAG=<当前镜像包对应标签>
|
||||
APP_PORT=8090
|
||||
TZ=Asia/Shanghai
|
||||
""", "ENV")
|
||||
b.add_table(
|
||||
doc,
|
||||
["变量", "作用", "修改后的操作"],
|
||||
[
|
||||
["COMPOSE_PROJECT_NAME", "Compose 项目名称,用于隔离容器、网络和卷名称", "确认未与其他项目冲突;通常不在运行中随意修改。"],
|
||||
["DEERFLOW_TAG", "docker-compose.yml 使用的镜像标签", "应与已导入镜像的标签一致;镜像升级时核对交付清单和 SHA256。"],
|
||||
["APP_PORT", "用户访问 Web/Nginx 的宿主机端口", "修改后执行 docker compose up -d --force-recreate web;确认新端口开放。"],
|
||||
["TZ", "容器日志和页面显示时区", "重建受影响容器后生效。"],
|
||||
],
|
||||
[1900, 3600, 3860],
|
||||
font_size=8.85,
|
||||
)
|
||||
b.add_h2(doc, "3.2 backend.env:JWT、模型密钥和数据库连接")
|
||||
b.add_code(doc, """
|
||||
# config/backend.env
|
||||
AUTH_JWT_SECRET=<至少32字节的随机值>
|
||||
INTRANET_MODEL_API_KEY=<模型服务密钥>
|
||||
MYSQL_DATABASE_URL=mysql+asyncmy://<USER>:<URL_ENCODED_PASSWORD>@<HOST>:3306/<DB>?charset=utf8mb4
|
||||
""", "ENV")
|
||||
b.add_callout(doc, "密钥规则", "AUTH_JWT_SECRET 是签发登录令牌的服务端密钥,不是用户登录密码。修改它会让所有已登录会话失效。backend.env 的任何改动都要强制重建 backend 才会重新读取。", "warn")
|
||||
b.add_h2(doc, "3.3 config.yaml:登录密码与数据库模式")
|
||||
b.add_code(doc, """
|
||||
# config/config.yaml(示意;保留现有其他配置)
|
||||
auth_login:
|
||||
username_login:
|
||||
enabled: true
|
||||
|
||||
database:
|
||||
backend: mysql # 使用默认文件数据库时为 sqlite
|
||||
mysql_url: $MYSQL_DATABASE_URL
|
||||
""", "YAML")
|
||||
b.add_para(doc, "用户名登录的共享密码或账号管理项应遵循当前 config.yaml 的 auth_login 配置;单个用户的 login_password、system_role 和资产所有权以应用用户管理/数据库记录为准。不要把用户密码与 AUTH_JWT_SECRET 混为一谈。")
|
||||
b.add_h2(doc, "3.4 切换或排查外部 MySQL")
|
||||
b.add_number(doc, "冻结可能影响资产写入的操作,完整备份 data/backend、当前配置和现有数据库。")
|
||||
b.add_number(doc, "创建数据库和最小权限账号,确认字符集 utf8mb4,并允许容器所在网络访问。")
|
||||
b.add_number(doc, "密码中 @、:、/、#、% 等字符需要 URL 编码;HOST 必须是容器能访问的地址,不能把容器内 127.0.0.1 当成外部数据库。")
|
||||
b.add_number(doc, "同时更新 backend.env 的 MYSQL_DATABASE_URL 与 config.yaml 的 database.backend/mysql_url,强制重建 backend 并持续查看迁移日志。")
|
||||
b.add_number(doc, "分别用管理员、lqq 和普通用户验证登录、技能、智能体、菜单、敏感词和发布状态。SQLite 与 MySQL 不会自动双向同步。")
|
||||
b.add_h2(doc, "3.5 前端接口地址与端口")
|
||||
b.add_code(doc, """
|
||||
// config/runtime-config.js:推荐同源相对路径
|
||||
window.__DEERFLOW_RUNTIME_CONFIG__ = {
|
||||
VITE_BACKEND_BASE_URL: "/deerflow",
|
||||
VITE_LANGGRAPH_BASE_URL: "/deerflow/api",
|
||||
VITE_AIPI_BASE_URL: "<可选的业务接口地址>",
|
||||
};
|
||||
""", "JavaScript")
|
||||
b.add_para(doc, "推荐保持相对路径。浏览器会自动访问当前域名和 APP_PORT,再由 Nginx 转到 backend:8001,这样最少遇到 CORS、证书与混合内容问题。确需使用独立后端域名时,应同步配置允许 Origin 和 HTTPS。")
|
||||
b.add_code(doc, """
|
||||
# 修改前端端口或运行时配置后的推荐操作
|
||||
sudo docker compose up -d --force-recreate web
|
||||
sudo docker compose ps
|
||||
sudo docker compose logs --tail=200 web
|
||||
# 浏览器使用 Ctrl+F5;在 Network 检查 runtime-config.js 和 /deerflow/health
|
||||
""", "Shell")
|
||||
|
||||
|
||||
def add_chapter_assets(doc, diagrams):
|
||||
b.add_h1(doc, "4. 技能与智能体:放置、发布、丢失排查")
|
||||
b.add_para(doc, "技能和智能体能否在页面出现,取决于文件、数据库元数据、当前登录身份、发布状态和目录挂载是否一致。优先在前端创建/上传;仅在批量迁移或前端不可用时手工导入。")
|
||||
b.add_figure(doc, diagrams["persistence_map"], "图 4-1 技能和智能体的持久化关系", "技能文件、智能体文件、业务数据库和运行时缓存共同决定资产可见性", width=6.35)
|
||||
heading = b.add_h2(doc, "4.1 技能放在哪里")
|
||||
heading.paragraph_format.page_break_before = True
|
||||
b.add_code(doc, """
|
||||
data/skills/
|
||||
├── public/
|
||||
│ └── <skill-id>/
|
||||
│ ├── SKILL.md
|
||||
│ ├── scripts/ # 可选
|
||||
│ ├── references/ # 可选
|
||||
│ └── assets/ # 可选
|
||||
└── custom/
|
||||
└── <skill-id>/
|
||||
└── SKILL.md
|
||||
""", "目录结构")
|
||||
b.add_table(
|
||||
doc,
|
||||
["目录", "含义", "注意"],
|
||||
[
|
||||
["data/skills/public", "系统共享/公共技能文件分类", "放入 public 不等于已发布到广场;仍需有正确元数据、权限和发布状态。"],
|
||||
["data/skills/custom", "用户自定义技能目录", "适合从前端创建或上传的技能;应保留完整目录而不是只复制一个文件。"],
|
||||
["SKILL.md", "技能说明、使用条件、操作规范的核心文件", "避免写入真实 API Key、数据库密码、内网敏感地址或个人信息。"],
|
||||
["scripts/references/assets", "脚本、参考资料和附件", "脚本必须可执行且依赖完整;上传前检查许可证、体积和敏感信息。"],
|
||||
],
|
||||
[2200, 2800, 4360],
|
||||
font_size=8.7,
|
||||
)
|
||||
b.add_h2(doc, "4.2 智能体放在哪里")
|
||||
b.add_code(doc, """
|
||||
data/backend/agents/<agent-id>/
|
||||
├── config.yaml # 模型、工具、技能、行为参数
|
||||
└── SOUL.md # 角色、提示词、表达和规则
|
||||
""", "目录结构")
|
||||
b.add_para(doc, "智能体文件只是一部分。名称、所有者、可见性、广场和发布状态等业务元数据通常在 SQLite 或 MySQL 中。因此恢复或迁移智能体时,必须同时备份/恢复 data/backend 与对应数据库。")
|
||||
b.add_h2(doc, "4.3 推荐的创建、上传和发布流程")
|
||||
b.add_figure(doc, diagrams["publish_flow"], "图 4-2 从创建到发布广场", "在界面创建、验证、发布、权限校验直至生效的流程", width=6.35)
|
||||
for text in [
|
||||
"使用普通业务用户或管理员进入技能管理/智能体管理,创建或上传资产并填写名称、说明、依赖和使用范围。",
|
||||
"完成本地实际验证:技能要验证工具调用、脚本依赖和文件权限;智能体要验证所选模型、技能/工具和首轮问答。",
|
||||
"在资产详情或卡片中点击“发布”,选择一个启用的目标广场。资产所有者或 admin 才能发布/下架。",
|
||||
"发布后用普通用户验证广场可见性;重新发布到其他广场通常是迁移,不是多份复制。",
|
||||
"若只需要个人使用,保持私有或不发布;不要通过手工复制文件代替发布流程。",
|
||||
]:
|
||||
b.add_number(doc, text)
|
||||
b.add_h2(doc, "4.4 手工导入时的安全做法")
|
||||
b.add_code(doc, """
|
||||
# 示例:先将完整技能目录复制到 custom,再确认容器内可见
|
||||
sudo mkdir -p data/skills/custom/<skill-id>
|
||||
# 将经过审核的文件复制到上面的目录后执行:
|
||||
sudo docker compose exec backend sh -lc 'find /app/backend/skills/custom -maxdepth 3 -type f -print'
|
||||
sudo docker compose restart backend
|
||||
""", "Shell")
|
||||
b.add_callout(doc, "手工导入后的边界", "手工复制只解决文件存在的问题,不会自动补齐所有者、可见性或发布元数据。导入后应通过界面核对资产记录;若无记录,按应用支持流程创建或恢复元数据。", "warn")
|
||||
b.add_h2(doc, "4.5 发布按钮或广场不可用")
|
||||
b.add_table(
|
||||
doc,
|
||||
["问题", "检查项", "处理"],
|
||||
[
|
||||
["看不到“发布”按钮", "当前用户是否资产所有者或 admin", "切换到所有者/admin;不要只凭文件目录判断权限。"],
|
||||
["选择不到广场", "广场是否启用、是否存在默认/私有范围限制", "由 admin 在发布广场管理中启用或创建目标广场。"],
|
||||
["发布后普通用户看不到", "广场、私有状态、筛选、缓存和角色", "确认实际发布到哪个广场;退出重登并清除筛选;检查发布 API 401/403。"],
|
||||
["智能体能看见但模型不可用", "config.yaml 中模型 name 是否仍存在", "恢复同名模型条目或将智能体改到已验证模型后重启 backend。"],
|
||||
],
|
||||
[2200, 3000, 4160],
|
||||
font_size=8.7,
|
||||
)
|
||||
b.add_h2(doc, "4.6 技能或智能体“丢失”专项排查")
|
||||
b.add_figure(doc, diagrams["lost_asset_flow"], "图 4-3 资产丢失排查顺序", "从服务目录、身份、挂载、数据库、过滤到恢复验证的排查流程", width=6.35)
|
||||
b.add_number(doc, "确认当前部署目录和服务:执行 pwd、docker compose ps,排除在旧目录启动了另一套服务。")
|
||||
b.add_number(doc, "确认登录身份:重新登录,核对用户名、system_role、资产所有者和是否处于独立会话/嵌入会话。")
|
||||
b.add_number(doc, "同时检查宿主机和容器内文件。宿主机有而容器没有,重点检查 docker-compose.yml 的 volume 映射与当前工作目录。")
|
||||
b.add_code(doc, """
|
||||
find data/skills -maxdepth 3 -type f -print | sort
|
||||
find data/backend/agents -maxdepth 3 -type f -print | sort
|
||||
sudo docker compose exec backend sh -lc 'find /app/backend/skills -maxdepth 3 -type f -print | sort'
|
||||
sudo docker compose exec backend sh -lc 'find /app/backend/.deer-flow/agents -maxdepth 3 -type f -print | sort'
|
||||
""", "Shell")
|
||||
b.add_number(doc, "确认数据库未切换:查看 config.yaml 的 database.backend 和 backend.env 的 MYSQL_DATABASE_URL。切换数据库不会自动搬迁或同步资产记录。")
|
||||
b.add_number(doc, "检查过滤、广场和权限:清除搜索条件,切换“我的/公共/已发布/私有”等视图,并用 admin 核验发布记录。")
|
||||
b.add_number(doc, "查看 backend 日志。文件和数据库都缺失时,停止写入,从备份恢复;重启 backend、重新登录并实际调用验证。")
|
||||
|
||||
|
||||
def add_chapter_ui(doc, diagrams):
|
||||
b.add_h1(doc, "5. 前端管理:菜单名称、敏感词、主题与账号")
|
||||
b.add_para(doc, "菜单、主题、敏感词和广场主要通过应用管理页面维护,属于数据库中的全局设置。保存后通常立即生效,但应使用管理员和普通用户分别验证。")
|
||||
b.add_figure(doc, diagrams["ui_map"], "图 5-1 常用管理入口", "菜单、外观、技能、智能体和用户管理入口关系", width=6.35)
|
||||
b.add_h2(doc, "5.1 配置菜单名称、排序和隐藏")
|
||||
b.add_number(doc, "使用 system_role=admin 的 DeerFlow 管理员登录,打开左下角“设置和更多”中的“菜单管理”。")
|
||||
b.add_number(doc, "找到目标一级、二级或三级菜单,修改显示名称 label、启用状态、排序或父级;保存后刷新页面验证。")
|
||||
b.add_number(doc, "菜单停用会隐藏该节点及其子树;修改名称不要改真实 path、路由 ID 或代码常量。")
|
||||
b.add_number(doc, "用普通用户检查左侧菜单、顶部导航和直接访问链接;记录修改前名称、目的和回退方式。")
|
||||
b.add_callout(doc, "安全边界", "隐藏菜单只移除导航入口,不等于阻止用户通过已知 URL 或 API 访问。真正禁用功能还需后端 API 权限、路由守卫和角色权限共同生效。", "danger")
|
||||
b.add_h2(doc, "5.2 配置敏感词:必须用哪个用户")
|
||||
b.add_para(doc, "敏感词功能是“展示层脱敏映射”:原始词 -> 替换词。它不会修改数据库里的原文,也不会改变 URL、路由 path 或节点 ID。")
|
||||
b.add_callout(doc, "登录要求", "敏感词管理前端入口、路由守卫和页面级校验都要求当前显示用户名严格等于 lqq。即使 admin 拥有后端写权限,也应使用 lqq 登录来维护页面。邮箱账号时,@ 前缀必须为 lqq。", "warn")
|
||||
b.add_number(doc, "用 lqq 登录,进入“设置和更多 -> 敏感词管理”。")
|
||||
b.add_number(doc, "新增原始词与替换词,设置启用状态;需要初始规则时可使用“导入种子词”合并缺失映射。")
|
||||
b.add_number(doc, "保存的是整套规则;修改前先导出/截图并经业务确认,避免替换词冲突或过度脱敏。")
|
||||
b.add_number(doc, "刷新页面,检查菜单、导航、标题和普通内容的显示;用普通用户复核最终效果。")
|
||||
b.add_h2(doc, "5.3 主题色、布局和嵌入页面")
|
||||
b.add_table(
|
||||
doc,
|
||||
["配置目标", "操作入口/变量", "验证"],
|
||||
[
|
||||
["个人主题", "设置 -> 外观,用户自己的选择通常优先", "新开页面检查浅/深主题、文字对比度和焦点状态。"],
|
||||
["系统默认与主题库", "admin 在外观设置中配置默认主题、主题名称、主色和启用状态", "用没有个人覆盖的新测试用户验证。"],
|
||||
["强制紧凑侧边栏", "runtime-config.js 的 VITE_FORCE_COLLAPSED_SIDEBAR", "重启 web 并刷新浏览器后检查导航。"],
|
||||
["iframe 嵌入", "URL 参数 embed=1、theme=...、hideJump=1、isolate=1", "在嵌入页验证无全局导航、主题和独立会话行为。"],
|
||||
],
|
||||
[2200, 3500, 3660],
|
||||
font_size=8.7,
|
||||
)
|
||||
b.add_callout(doc, "主题验收", "不仅看按钮颜色。还要检查正文、表格、弹窗、下拉框、禁用、hover、focus、错误和成功状态的对比度;不要用品牌主色铺满大面积背景。", "note")
|
||||
heading = b.add_h2(doc, "5.4 必备账号与角色")
|
||||
heading.paragraph_format.page_break_before = True
|
||||
b.add_table(
|
||||
doc,
|
||||
["账号类型", "至少准备", "主要用途", "注意"],
|
||||
[
|
||||
["DeerFlow admin", "2 个", "菜单、主题、广场、用户和全局资产管理", "system_role 必须为 admin;保留一个应急管理员。"],
|
||||
["lqq", "1 个", "敏感词管理前端入口", "显示用户名/邮箱前缀必须严格为 lqq。"],
|
||||
["普通测试用户", "1 个", "验收菜单隐藏、资产可见性和广场发布", "不能只用管理员验收,管理员会掩盖权限问题。"],
|
||||
["模型/数据库服务账号", "按环境", "调用外部服务", "遵循最小权限和定期轮换,不与个人账号共用。"],
|
||||
],
|
||||
[2100, 1250, 3300, 2710],
|
||||
font_size=8.65,
|
||||
)
|
||||
|
||||
|
||||
def add_chapter_operations(doc):
|
||||
b.add_h1(doc, "6. 日常启停、日志和健康检查")
|
||||
b.add_para(doc, "一键脚本和 Docker Compose 命令都应从部署目录运行。日常 restart 适合重启进程;任何环境变量文件改动都必须通过 force-recreate 重建受影响容器。")
|
||||
b.add_h2(doc, "6.1 常用命令速查")
|
||||
b.add_code(doc, """
|
||||
# 整套服务
|
||||
sudo bash restart.sh
|
||||
sudo bash stop.sh
|
||||
sudo bash logs.sh
|
||||
sudo bash diagnose.sh
|
||||
|
||||
# 只处理后端或前端
|
||||
sudo docker compose restart backend
|
||||
sudo docker compose up -d --force-recreate backend # backend.env 改动后
|
||||
sudo docker compose restart web
|
||||
sudo docker compose up -d --force-recreate web # .env 的 APP_PORT / Web 配置改动后
|
||||
sudo docker compose ps
|
||||
""", "Shell")
|
||||
b.add_h2(doc, "6.2 如何打印日志")
|
||||
b.add_code(doc, """
|
||||
# 全部服务日志;Ctrl+C 仅停止跟踪,不停止服务
|
||||
sudo bash logs.sh
|
||||
|
||||
# 只看后端或 Web/Nginx
|
||||
sudo bash logs.sh backend
|
||||
sudo bash logs.sh web
|
||||
|
||||
# Compose 原生命令:最后 500 行并持续跟踪
|
||||
sudo docker compose logs --tail=500 -f backend
|
||||
sudo docker compose logs --tail=500 -f web
|
||||
""", "Shell")
|
||||
b.add_h2(doc, "6.3 健康检查和变更后验收")
|
||||
b.add_code(doc, """
|
||||
curl -fsS http://127.0.0.1:<APP_PORT>/deerflow/health
|
||||
curl -I http://127.0.0.1:<APP_PORT>/
|
||||
sudo docker compose ps
|
||||
""", "Shell")
|
||||
for text in [
|
||||
"容器 Up 不等于业务可用:健康接口成功后仍要登录一次、发起一次对话并验证修改的功能。",
|
||||
"backend.env、.env 改动:force-recreate;config.yaml 改动:至少 restart backend;runtime-config.js 改动:重启 web 并强制刷新浏览器。",
|
||||
"变更完成后继续观察后端日志至少 5 分钟,确认没有反复重启、401/429/500、数据库错误或模型初始化失败。",
|
||||
]:
|
||||
b.add_bullet(doc, text)
|
||||
|
||||
|
||||
def add_chapter_backup(doc):
|
||||
b.add_h1(doc, "7. 数据库、备份、恢复与升级")
|
||||
b.add_para(doc, "一次可恢复的备份至少包含 config、data 和当前业务数据库。只保存 Docker 镜像无法恢复用户、技能、智能体、发布广场、菜单、主题与敏感词。外部 MySQL 必须单独导出。")
|
||||
b.add_h2(doc, "7.1 必须备份的对象")
|
||||
b.add_table(
|
||||
doc,
|
||||
["对象", "作用", "建议频率", "恢复价值"],
|
||||
[
|
||||
["config 与 .env", "模型、登录、数据库、接口地址和运行配置", "每次变更后", "恢复服务连接和端口配置。"],
|
||||
["data/backend", "文件数据库、智能体文件及运行数据", "每日 + 变更前", "恢复智能体、用户和运行相关资产。"],
|
||||
["data/skills", "public/custom 技能文件和附件", "每日 + 技能变更后", "恢复技能内容和脚本。"],
|
||||
["data/knowledge", "知识库文件", "按使用频率", "恢复知识资产。"],
|
||||
["外部 MySQL dump", "资产元数据、用户、菜单、主题、广场等", "每日 + 变更前", "恢复数据库层资产与全局设置。"],
|
||||
],
|
||||
[1900, 3150, 1850, 2460],
|
||||
font_size=8.5,
|
||||
)
|
||||
b.add_h2(doc, "7.2 文件和数据库备份示例")
|
||||
b.add_code(doc, """
|
||||
# 文件备份:确保备份目录位于独立存储,不在当前 data 内
|
||||
cd <部署目录>
|
||||
sudo tar -czf <备份目录>/deerflow-files-$(date +%F-%H%M).tar.gz .env config data
|
||||
sha256sum <备份目录>/deerflow-files-*.tar.gz
|
||||
|
||||
# MySQL 备份:密码不要直接写到命令历史,优先使用受控 defaults-extra-file
|
||||
mysqldump --single-transaction --routines --triggers \
|
||||
-h <MYSQL_HOST> -u <BACKUP_USER> <DB_NAME> > <备份目录>/deerflow-mysql-$(date +%F-%H%M).sql
|
||||
""", "Shell")
|
||||
b.add_h2(doc, "7.3 恢复与升级原则")
|
||||
for text in [
|
||||
"恢复前先确认备份版本、SHA256、数据模式和目标目录;停止或冻结写入,避免恢复过程中产生新分叉数据。",
|
||||
"先恢复到隔离或测试环境验证,再进行正式切换;恢复后检查目录权限、数据库连接、健康接口、登录、模型、技能、智能体和广场。",
|
||||
"升级时保留旧镜像、旧配置和完整备份;新版本使用独立测试端口验证,确认无误再切换。",
|
||||
"SQLite 与 MySQL 的资产数据不会自动双向同步。任何切换、迁移或恢复都要有明确来源和一次性合并计划。",
|
||||
]:
|
||||
b.add_bullet(doc, text)
|
||||
b.add_callout(doc, "高风险操作", "删除部署目录、删除 data、覆盖未知数据库、docker system prune -a 和递归修改所有者都可能造成不可逆损失。执行前必须明确目标、验证备份可用并获得审批。", "danger")
|
||||
|
||||
|
||||
def add_chapter_security_handover(doc):
|
||||
b.add_h1(doc, "8. 巡检、安全与交接")
|
||||
b.add_h2(doc, "8.1 每日与每周巡检")
|
||||
b.add_table(
|
||||
doc,
|
||||
["频率", "检查内容", "合格标准"],
|
||||
[
|
||||
["每日", "docker compose ps、/deerflow/health、磁盘/inode、backend/web 日志", "服务正常、无重启循环、无连续 5xx/401/429、空间充足。"],
|
||||
["每周", "备份是否完成、最近恢复演练、模型配额与超时、资产发布与权限变更", "备份可校验;高频失败有负责人;变更有记录。"],
|
||||
["每次变更后", "端口、日志、健康、登录、实际业务功能、普通用户权限", "功能验收通过且可回退。"],
|
||||
],
|
||||
[1500, 3900, 3960],
|
||||
font_size=8.75,
|
||||
)
|
||||
b.add_h2(doc, "8.2 最低安全要求")
|
||||
for text in [
|
||||
"AUTH_JWT_SECRET、模型 API Key、数据库 URL/密码只保存在受控的 backend.env 或密钥系统中,不进入 Git、截图、聊天记录和前端 runtime-config.js。",
|
||||
"管理员、lqq、普通测试用户和服务账号分开管理;定期轮换密码/密钥,离职或交接时立即回收不再需要的权限。",
|
||||
"对外只开放必要的 APP_PORT;后端 8001 默认不直接暴露。数据库地址、模型服务和业务接口应采用最小网络范围。",
|
||||
"对外发送日志前删除 Authorization、Cookie、Token、API Key、数据库 URL、手机号和身份信息,只保留时间、状态码、trace ID 与关键报错。",
|
||||
]:
|
||||
b.add_bullet(doc, text)
|
||||
b.add_h2(doc, "8.3 交接清单")
|
||||
b.add_table(
|
||||
doc,
|
||||
["项目", "交接时填写"],
|
||||
[
|
||||
["生产访问地址 / APP_PORT", ""],
|
||||
["当前部署目录与 Compose 项目名", ""],
|
||||
["镜像版本 / SHA256", ""],
|
||||
["数据库模式、地址与库名(不写密码)", ""],
|
||||
["DeerFlow admin、lqq、普通测试用户责任人", ""],
|
||||
["模型服务与密钥保管责任人", ""],
|
||||
["备份位置、保留期与最近恢复演练日期", ""],
|
||||
["监控、告警和问题升级联系人", ""],
|
||||
],
|
||||
[3500, 5860],
|
||||
font_size=9.1,
|
||||
)
|
||||
|
||||
|
||||
def add_appendices(doc):
|
||||
b.add_h1(doc, "附录 A:最短命令清单")
|
||||
b.add_code(doc, """
|
||||
cd <部署目录>
|
||||
sudo docker compose ps
|
||||
sudo docker compose logs --tail=500 -f backend
|
||||
sudo docker compose logs --tail=500 -f web
|
||||
sudo docker compose restart backend
|
||||
sudo docker compose up -d --force-recreate backend
|
||||
sudo docker compose restart web
|
||||
sudo docker compose up -d --force-recreate web
|
||||
curl -fsS http://127.0.0.1:<APP_PORT>/deerflow/health
|
||||
""", "Shell")
|
||||
heading = b.add_h1(doc, "附录 B:问题升级信息模板")
|
||||
heading.paragraph_format.page_break_before = False
|
||||
b.add_code(doc, """
|
||||
【问题标题】
|
||||
【发生时间】YYYY-MM-DD HH:mm:ss(时区)
|
||||
【访问地址/端口】<不含密码>
|
||||
【当前账号角色】admin / lqq / 普通用户(不要提供密码)
|
||||
【操作步骤】1... 2... 3...
|
||||
【实际现象】
|
||||
【期望结果】
|
||||
【HTTP 状态码 / trace ID】
|
||||
【容器状态】docker compose ps
|
||||
【已脱敏日志】backend/web 最近 200 行
|
||||
【最近变更】模型、数据库、菜单、主题、镜像或配置
|
||||
【已采取动作】以及结果
|
||||
""", "故障单模板")
|
||||
heading = b.add_h1(doc, "附录 C:核心事实速记")
|
||||
heading.paragraph_format.page_break_before = True
|
||||
b.add_table(
|
||||
doc,
|
||||
["主题", "结论"],
|
||||
[
|
||||
["前端和后端端口", "容器内部不同:Web 80、Backend 8001;用户通常经由 APP_PORT 访问 Web。"],
|
||||
["配置文件", ".env 管端口/Compose;backend.env 管密钥和连接串;config.yaml 管模型/登录/数据库;runtime-config.js 管前端地址。"],
|
||||
["环境变量生效", "backend.env 或 .env 改动后必须 force-recreate 受影响容器;普通 restart 不会重新读取。"],
|
||||
["模型与 max_tokens", "模型条目在 config.yaml;Key 在 backend.env;max_tokens 是单次输出上限,不是上下文窗口。"],
|
||||
["技能位置", "data/skills/public 与 data/skills/custom;目录文件存在不等于已经发布。"],
|
||||
["智能体位置", "data/backend/agents/<agent-id>;还依赖数据库元数据、所有者、可见性和发布状态。"],
|
||||
["敏感词用户", "页面维护需要显示用户名严格为 lqq;admin 不能替代该前端入口条件。"],
|
||||
["菜单隐藏", "只隐藏导航入口,不等于禁止直接 URL 或 API,需要后端权限配合。"],
|
||||
["资产丢失", "先查目录、挂载、数据库、身份、过滤和日志,最后才恢复;不要急着创建同名资产。"],
|
||||
["完整备份", "config + data + 外部 MySQL dump + 镜像版本/SHA256;只备份镜像不足以恢复业务资产。"],
|
||||
],
|
||||
[3100, 6260],
|
||||
font_size=8.7,
|
||||
)
|
||||
|
||||
|
||||
def build_document(diagrams):
|
||||
doc = b.Document()
|
||||
b.configure_document(doc)
|
||||
set_running_furniture(doc)
|
||||
doc.core_properties.title = "DeerFlow 系统运维手册(用户重点版)"
|
||||
doc.core_properties.subject = "DeerFlow 常见报错、模型、配置、技能、智能体、前端管理与恢复"
|
||||
doc.core_properties.author = "DeerFlow 运维团队"
|
||||
doc.core_properties.keywords = "DeerFlow, 运维, Docker, config.yaml, 技能, 智能体"
|
||||
add_cover(doc, diagrams)
|
||||
add_navigation(doc)
|
||||
add_chapter_common_errors(doc)
|
||||
add_chapter_model(doc, diagrams)
|
||||
add_chapter_config(doc, diagrams)
|
||||
add_chapter_assets(doc, diagrams)
|
||||
add_chapter_ui(doc, diagrams)
|
||||
add_chapter_operations(doc)
|
||||
add_chapter_backup(doc)
|
||||
add_chapter_security_handover(doc)
|
||||
add_appendices(doc)
|
||||
doc.save(OUT)
|
||||
return OUT
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
b.ensure_dirs()
|
||||
diagrams = b.make_diagrams()
|
||||
print(build_document(diagrams))
|
||||
@@ -0,0 +1,33 @@
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent
|
||||
PAGES = ROOT / "rendered" / "pages"
|
||||
OUT = ROOT / "rendered" / "contact-sheets"
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
font_path = Path(r"C:\Windows\Fonts\arialbd.ttf")
|
||||
font = ImageFont.truetype(str(font_path), 28)
|
||||
page_paths = sorted(PAGES.glob("page-*.png"))
|
||||
|
||||
for sheet_index in range(0, len(page_paths), 4):
|
||||
group = page_paths[sheet_index : sheet_index + 4]
|
||||
images = [Image.open(p).convert("RGB") for p in group]
|
||||
page_w, page_h = images[0].size
|
||||
gutter = 48
|
||||
label_h = 52
|
||||
sheet = Image.new("RGB", (page_w * 2 + gutter * 3, (page_h + label_h) * 2 + gutter * 3), "#D7DEE5")
|
||||
draw = ImageDraw.Draw(sheet)
|
||||
for i, (path, img) in enumerate(zip(group, images)):
|
||||
col, row = i % 2, i // 2
|
||||
x = gutter + col * (page_w + gutter)
|
||||
y = gutter + row * (page_h + label_h + gutter)
|
||||
draw.text((x, y), path.stem, font=font, fill="#172A3A")
|
||||
sheet.paste(img, (x, y + label_h))
|
||||
first = sheet_index + 1
|
||||
last = sheet_index + len(group)
|
||||
sheet.save(OUT / f"pages-{first:02d}-{last:02d}.jpg", quality=92, subsampling=0)
|
||||
|
||||
print(f"created {len(list(OUT.glob('*.jpg')))} contact sheets")
|
||||
@@ -0,0 +1,30 @@
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent / "rendered-user"
|
||||
PAGES = ROOT / "pages"
|
||||
OUT = ROOT / "contact-sheets"
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
font = ImageFont.truetype(r"C:\Windows\Fonts\arialbd.ttf", 28)
|
||||
page_paths = sorted(PAGES.glob("page-*.png"))
|
||||
|
||||
for sheet_index in range(0, len(page_paths), 4):
|
||||
group = page_paths[sheet_index:sheet_index + 4]
|
||||
images = [Image.open(path).convert("RGB") for path in group]
|
||||
page_w, page_h = images[0].size
|
||||
gutter, label_h = 48, 52
|
||||
sheet = Image.new("RGB", (page_w * 2 + gutter * 3, (page_h + label_h) * 2 + gutter * 3), "#D7DEE5")
|
||||
draw = ImageDraw.Draw(sheet)
|
||||
for index, (path, image) in enumerate(zip(group, images)):
|
||||
col, row = index % 2, index // 2
|
||||
x = gutter + col * (page_w + gutter)
|
||||
y = gutter + row * (page_h + label_h + gutter)
|
||||
draw.text((x, y), path.stem, font=font, fill="#172A3A")
|
||||
sheet.paste(image, (x, y + label_h))
|
||||
first, last = sheet_index + 1, sheet_index + len(group)
|
||||
sheet.save(OUT / f"pages-{first:02d}-{last:02d}.jpg", quality=92, subsampling=0)
|
||||
|
||||
print(f"created {len(list(OUT.glob('*.jpg')))} contact sheets")
|
||||
@@ -0,0 +1,38 @@
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][string]$InputDocx,
|
||||
[Parameter(Mandatory = $true)][string]$OutputPdf
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$word = $null
|
||||
$doc = $null
|
||||
try {
|
||||
$inputPath = (Resolve-Path -LiteralPath $InputDocx).Path
|
||||
$outputPath = [System.IO.Path]::GetFullPath($OutputPdf)
|
||||
$outputDir = [System.IO.Path]::GetDirectoryName($outputPath)
|
||||
[System.IO.Directory]::CreateDirectory($outputDir) | Out-Null
|
||||
|
||||
$word = New-Object -ComObject Word.Application
|
||||
$word.Visible = $false
|
||||
$word.DisplayAlerts = 0
|
||||
$doc = $word.Documents.Open($inputPath, $false, $false)
|
||||
|
||||
foreach ($toc in $doc.TablesOfContents) {
|
||||
$toc.Update() | Out-Null
|
||||
}
|
||||
$doc.Fields.Update() | Out-Null
|
||||
$doc.Save()
|
||||
$doc.ExportAsFixedFormat($outputPath, 17)
|
||||
}
|
||||
finally {
|
||||
if ($null -ne $doc) {
|
||||
$doc.Close(0)
|
||||
[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($doc)
|
||||
}
|
||||
if ($null -ne $word) {
|
||||
$word.Quit()
|
||||
[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($word)
|
||||
}
|
||||
[GC]::Collect()
|
||||
[GC]::WaitForPendingFinalizers()
|
||||
}
|
||||
|
After Width: | Height: | Size: 1.1 MiB |
|
After Width: | Height: | Size: 1.2 MiB |
|
After Width: | Height: | Size: 1.2 MiB |
|
After Width: | Height: | Size: 1.1 MiB |
|
After Width: | Height: | Size: 1.1 MiB |
|
After Width: | Height: | Size: 914 KiB |
|
After Width: | Height: | Size: 906 KiB |
|
After Width: | Height: | Size: 195 KiB |
|
After Width: | Height: | Size: 215 KiB |
|
After Width: | Height: | Size: 189 KiB |
|
After Width: | Height: | Size: 179 KiB |
|
After Width: | Height: | Size: 265 KiB |
|
After Width: | Height: | Size: 281 KiB |
|
After Width: | Height: | Size: 237 KiB |
|
After Width: | Height: | Size: 252 KiB |
|
After Width: | Height: | Size: 267 KiB |
|
After Width: | Height: | Size: 163 KiB |
|
After Width: | Height: | Size: 264 KiB |
|
After Width: | Height: | Size: 329 KiB |
|
After Width: | Height: | Size: 170 KiB |
|
After Width: | Height: | Size: 209 KiB |
|
After Width: | Height: | Size: 276 KiB |
|
After Width: | Height: | Size: 255 KiB |
|
After Width: | Height: | Size: 215 KiB |
|
After Width: | Height: | Size: 265 KiB |
|
After Width: | Height: | Size: 308 KiB |
|
After Width: | Height: | Size: 106 KiB |
|
After Width: | Height: | Size: 245 KiB |
|
After Width: | Height: | Size: 51 KiB |