第三波前两批:六个「看着成功其实没干活」的平台漏洞堵上,记录页能回放,管理页与画布收尾

起因是一次探索运行:Copilot 改节点时把工具绑定整份抹掉,agent 没有工具只能写「假设调用」,
校验节点的自动修复编出 total_count=0 让 schema 通过,协作成员把工具调用标记当文字输出了四轮,
轮数用完后节点把原话当成功结果交出去——运行标成已完成,数据库一次都没查。

平台可信度(先写失败测试)
- Copilot 修改节点改为合并:没写的字段保留,null 才删除;协作成员按名字合并。前后端同一套规则,
  工具集合变小时自查报警、改图回执列出变化
- 新校验规则:提示词点名了某个工具而节点没有绑定它,判错误,Copilot 自查会交回去修
- 校验修复只许改格式:冒出原文没有的值就判修复无效;修复这次模型调用计入用量
- 识别模型把工具调用写成文字的情况(DSML、<tool_call> 等标记):纠正一次,仍然如此就判失败并说明原因
- 协作团队用完轮数不再按成功交付:默认失败,可选降档,点出一次都没派到的成员
- 审批恢复后,同一节点里已经执行过的工具调用复用结果,不再重复执行

后端
- 查询时限交给数据库执行(Oracle call_timeout、PG statement_timeout、MySQL max_execution_time、
  SQLite progress handler),可按数据源配置;超时报错与实际耗时一致
- 等审批的运行可以真正取消;会话列表带最后一轮状态;测连接结果持久化;探查结构可只看不存;
  自定义工具可草稿试跑、写坏的参数定义保存时拒绝;MCP 服务改动后作废旧工具缓存;
  检索命中带贡献分解;重建索引在后台跑并报进度;报错统一收进 core/errors

前端
- 公共层:管理页共用件、失败说明(lib/explain)、健康状态进公共库;目录按表各自加载并有超时,
  一张表卡住不再拖垮整站;上传显示真实字节进度;离线横幅只播报不变的句子
- 画布:卡片只说游标所在的那一次执行;等审批时可放弃运行;团队收尾判定与未完成说清楚;
  回放用量取那一刻的值
- 编排页:Copilot 合并语义与工具变化回执;「用完轮数时」选项;正式运行期间锁住所有改图入口
- 回答流 / 问数据:新失败类型说人话并给下一步;画布与右栏互相定位;数据源范围、回收站、重新核对
- 记录页:「航迹」页签复用画布时间轴,可拖动回放、列出关键时刻;列表行带执行 / 等人 / 失败缩略条
- 外壳:统一的离开前确认(data router),导航、⌘K、快捷键、后退都会先问

验证(沙箱):tsc 干净,pytest 838 passed(两遍),14 个检查脚本中 13 个全绿;
check-ui 余 1 项旧断言(按旧日期格式找运行行),3c 更新。
This commit is contained in:
ThearchyHelios
2026-09-27 10:16:32 +08:00
parent e10c4f23fc
commit 587bf7e27c
134 changed files with 20140 additions and 2709 deletions
+99 -34
View File
@@ -12,9 +12,12 @@ import type { Approval, Provider, Skill, ToolInfo, Workflow } from '../types'
*/
export type BackendState = 'checking' | 'ok' | 'down'
/** catalog 里的一张表 */
export type CatalogKey = 'providers' | 'tools' | 'skills' | 'collections' | 'workflows' | 'approvals'
/** 启动清单里的一行:catalog.refresh 的一个真实请求 */
export interface CatalogCheck {
key: 'providers' | 'tools' | 'skills' | 'collections' | 'workflows' | 'approvals'
key: CatalogKey
label: string
state: 'pending' | 'ok' | 'error'
ms?: number
@@ -22,25 +25,45 @@ export interface CatalogCheck {
error?: string
}
const CHECK_LABELS: Record<CatalogCheck['key'], string> = {
/** 各张表的中文名。启动清单、「正在读取工作流」这类空态用 */
export const CATALOG_LABELS: Record<CatalogKey, string> = {
providers: '模型接入', tools: '工具', skills: 'Skill',
collections: '知识库', workflows: '工作流', approvals: '待审批',
}
const CATALOG_KEYS = Object.keys(CATALOG_LABELS) as CatalogKey[]
/**
* refresh 里每个请求最多等多久。一个接口卡住(MCP 服务不应答时的 /tools)不能
* 让它那张表永远停在「加载中」;到点掐断、记成出错,别的表不受影响
*/
export const CATALOG_TIMEOUT_MS = 15_000
/** 心跳间隔:连着时复用 4 秒一次的待审批轮询,不另起请求 */
const HEARTBEAT_MS = 4000
/** 断开后的重试退避 */
const BACKOFF_MS = [4000, 8000, 16000]
/** 全局参照数据:属性面板的各种下拉都从这里取,只加载一次。 */
interface CatalogState {
export interface CatalogState {
providers: Provider[]
tools: ToolInfo[]
skills: Skill[]
collections: { collection: string; documents: number; chunks: number }[]
workflows: Workflow[]
approvals: Approval[]
/**
* 启动后的第一次 refresh 已经落定(每个请求都回来了或超时了)。只从 false 变 true,
* 之后的刷新不会把它打回去——所以它不能回答「这张表是真的空还是没取到」,那个
* 看 loadedAt / catalogListState
*/
loaded: boolean
/** 每张表最近一次成功取回的时刻(ms)。没有这一项 = 从没取到过,空列表不能当「没有」 */
loadedAt: Partial<Record<CatalogKey, number>>
/**
* 重拉全部六张表,谁先回来先填谁:一张表卡住不拖累别的表。每个请求最多等
* CATALOG_TIMEOUT_MS,超时记成那一项出错
*/
refresh: () => Promise<void>
refreshApprovals: () => Promise<void>
@@ -71,6 +94,9 @@ let probing: Promise<boolean> | null = null
let retryTimer: ReturnType<typeof setTimeout> | undefined
let heartbeatOwner: symbol | null = null
let markUpRef: (latencyMs?: number) => void = () => {}
/** 第几次 refresh。两次 refresh 交叠时,晚发的那次的结果不能被早发、晚到的覆盖 */
let refreshEpoch = 0
const appliedGen: Partial<Record<CatalogKey, number>> = {}
export const useCatalog = create<CatalogState>((set, get) => {
let backoffStep = 0
@@ -112,6 +138,7 @@ export const useCatalog = create<CatalogState>((set, get) => {
workflows: [],
approvals: [],
loaded: false,
loadedAt: {},
backend: 'checking',
latencyMs: null,
@@ -122,41 +149,50 @@ export const useCatalog = create<CatalogState>((set, get) => {
reconnects: 0,
refresh: async () => {
const keys = Object.keys(CHECK_LABELS) as CatalogCheck['key'][]
set({ checks: keys.map((key) => ({ key, label: CHECK_LABELS[key], state: 'pending' })) })
const update = (key: CatalogCheck['key'], patch: Partial<CatalogCheck>) =>
const gen = ++refreshEpoch
const keys = CATALOG_KEYS
set({ checks: keys.map((key) => ({ key, label: CATALOG_LABELS[key], state: 'pending' })) })
// 清单只归最新一次 refresh 写:交叠时早发的那次别把新清单的行改回去
const update = (key: CatalogKey, patch: Partial<CatalogCheck>) => {
if (gen !== refreshEpoch) return
set((s) => ({ checks: s.checks.map((c) => (c.key === key ? { ...c, ...patch } : c)) }))
}
const opts = { timeoutMs: CATALOG_TIMEOUT_MS }
const fetchers: Record<CatalogKey, () => Promise<unknown[]>> = {
providers: () => api.providers.list(opts),
tools: () => api.tools.list(opts),
skills: () => api.skills.list(opts),
collections: () => api.kb.collections(opts),
workflows: () => api.workflows.list(opts),
approvals: () => api.approvals.list('pending', opts),
}
let networkFailures = 0
let lastError = ''
// 单项失败不该让整个面板空掉,各自兜底;但要记下是不是"够不着",
// 六个全是网络失败就是后端断了,不是"什么都没有"
const track = <T>(key: CatalogCheck['key'], p: Promise<T>): Promise<T | []> => {
// 各张表回来一张填一张:以前是 Promise.all 全到齐才一起写,/tools 卡着不回,
// 工作流也跟着一直是空的,编排页就说「还没有工作流」。单项失败各自兜底,
// 列表保持原样(不清成 []);但要记下是不是"够不着",六个全是网络失败就是
// 后端断了,不是"什么都没有"
const track = async (key: CatalogKey) => {
const t0 = performance.now()
return p.then(
(v) => { update(key, { state: 'ok', ms: Math.round(performance.now() - t0) }); return v },
(e: unknown) => {
const err = e instanceof ApiError ? e : null
if (err?.kind === 'network') networkFailures++
lastError = err?.message ?? String((e as any)?.message ?? e)
update(key, {
state: 'error', ms: Math.round(performance.now() - t0),
status: err?.status || undefined, error: lastError,
})
return []
},
)
try {
const rows = await fetchers[key]()
update(key, { state: 'ok', ms: Math.round(performance.now() - t0) })
if ((appliedGen[key] ?? 0) > gen) return
appliedGen[key] = gen
set((s) => ({ [key]: rows, loadedAt: { ...s.loadedAt, [key]: Date.now() } }) as Partial<CatalogState>)
} catch (e) {
const err = e instanceof ApiError ? e : null
if (err?.kind === 'network') networkFailures++
update(key, {
state: 'error', ms: Math.round(performance.now() - t0),
status: err?.status || undefined,
error: err?.message ?? String((e as any)?.message ?? e),
})
}
}
const t0 = performance.now()
const [providers, tools, skills, collections, workflows, approvals] = await Promise.all([
track('providers', api.providers.list()),
track('tools', api.tools.list()),
track('skills', api.skills.list()),
track('collections', api.kb.collections()),
track('workflows', api.workflows.list()),
track('approvals', api.approvals.list()),
])
set({ providers, tools, skills, collections, workflows, approvals, loaded: true })
await Promise.all(keys.map(track))
if (!get().loaded) set({ loaded: true })
if (networkFailures === keys.length) {
// 第一个失败的请求已经通过 onConnectivity 起了一次探活;这里并进同一次,
// 不另记一笔——两笔会让第一次断开就跳到退避的第二档(8 秒而不是 4 秒)
@@ -176,8 +212,14 @@ export const useCatalog = create<CatalogState>((set, get) => {
}
const t0 = performance.now()
try {
const approvals = await api.approvals.list()
set({ approvals, latencyMs: Math.round(performance.now() - t0), lastOkAt: Date.now() })
const gen = refreshEpoch
const approvals = await api.approvals.list('pending', { timeoutMs: CATALOG_TIMEOUT_MS })
// 这一拍在路上时又发起了 refresh、而且那次已经填过了:以那次为准
if ((appliedGen.approvals ?? 0) > gen) return
set((s) => ({
approvals, latencyMs: Math.round(performance.now() - t0), lastOkAt: Date.now(),
loadedAt: { ...s.loadedAt, approvals: Date.now() },
}))
} catch (e) {
// 后端回了错误码说明它还活着,列表保持原样;够不着才去确认是否断开
if (e instanceof ApiError && e.kind === 'network' && get().backend !== 'down') await get().checkBackend()
@@ -251,6 +293,29 @@ export function useOnReconnect(cb: () => void): void {
}), [])
}
/**
* 某张表眼下能不能当真:
* - ok:至少成功取回过一次。之后的刷新失败了,手上的也还是真数据;
* - offline:从没取到过,后端也断着;
* - loading:从没取到过,请求还在路上(或还没发);
* - error:从没取到过,最近一次请求出错或超时了。
* 后三种时列表是空的,但那不是「没有」。
*/
export type CatalogListState = 'ok' | 'loading' | 'error' | 'offline'
export function catalogListState(
s: Pick<CatalogState, 'loadedAt' | 'backend' | 'checks'>, key: CatalogKey,
): CatalogListState {
if (s.loadedAt[key] != null) return 'ok'
if (s.backend === 'down') return 'offline'
return s.checks.find((c) => c.key === key)?.state === 'error' ? 'error' : 'loading'
}
/** 同 catalogListState,订阅版。页面判断「空」之前先看它是不是 ok */
export function useCatalogListState(key: CatalogKey): CatalogListState {
return useCatalog((s) => catalogListState(s, key))
}
/** 这条运行有没有待处理的审批。区分「等待审批」和「已挂起 · 可续跑」要用它 */
export function hasPendingApproval(approvals: Approval[], runId: string | null | undefined): boolean {
if (!runId) return false
+286 -80
View File
@@ -2,7 +2,8 @@ import { create } from 'zustand'
import { ApiError, api, streamCopilot, streamRun } from '../api/client'
import type { CopilotOp, RunFinal } from '../run/decode'
import { decodeRun } from '../run/decode'
import { humanizeError } from '../lib/errors'
import { errorMessage, humanizeError, isNetworkError } from '../lib/errors'
import { explainRunError } from '../lib/explain'
import { parseServerTime } from '../lib/format'
import { useCatalog } from './catalog'
import { useConversations } from './conversations'
@@ -45,6 +46,11 @@ export type Phase =
| 'error'
| 'cancelled' // 用户点了停止。不是出错:不画红,也不给「接着跑」
| 'suspended' // 服务重启打断了,断点还在,可以接着跑
/**
* 核对撞上后端出错、超时:不知道它现在是在跑、跑完了还是失败了。只给「重新核对」——
* 给「重试」会在旧运行可能还活着的时候另起一次
*/
| 'unknown'
/** 占着这个会话的相位:这时再问一句、或者删掉这个会话,都会撞上正在跑的东西 */
const BUSY_PHASES: ReadonlySet<Phase> = new Set(['planning', 'building', 'running'])
@@ -56,10 +62,23 @@ export interface Failure {
hint?: string
detail?: string
/**
* 翻成人话之前的那句原话。流里的报错块会自己再翻一遍,交给它的得是原话:
* 把翻好的「操作超时:查询超时…」再翻一遍,标题和原因就成了两遍「操作超时」
* 翻成人话之前的那句原话。运行的失败把它交给流里的报错块按 lib/explain 再讲一遍;
* 别的交拆好的 title / reason——把翻好的「操作超时:查询超时…」再翻一遍,标题和
* 原因就成了两遍「操作超时」
*/
source?: string
/** 原样接着跑也过不去(缺输入、人驳回、没绑工具…),不给「接着跑」。见 lib/explain */
continuable?: false
/** 流程本身没问题,是发起那一下没到后端:原图再发起一次就行,不必让 Copilot 重新搭 */
rerun?: true
/** 限定的数据源都不在了(删了、停用了)。带着原范围重试只会再被拒一次 */
scopeGone?: true
}
/** 限定这一问只查哪些数据源。名字跟着存:库删了之后,这一轮查的是谁还得说得出来 */
export interface ScopeSource {
id: string
name: string
}
/**
@@ -80,12 +99,11 @@ export interface Attempt {
}
/**
* 刷新之后还得在的可信度信息。
* 刷新之后还得在的可信度信息,存在 conversation_turns.meta。
*
* conversation_turns 没有专门放它的列:出具档位、运行类别、「这一条没查库」
* 以前都只活在内存里,刷新就没了——而历史会话恰恰是事后复盘、转发结论时最常看
* 的地方。后端补上 meta 列之前,它挂在 review 这个 JSON 字段的 meta 键下:
* 后端对 review 只读 note,多一个键不影响任何逻辑。读的时候两处都认。
* 出具档位、运行类别、「这一条没查库」以前都只活在内存里,刷新就没了——而历史
* 会话恰恰是事后复盘、转发结论时最常看的地方。老轮次把它挂在 review.meta 下,
* 后端读出来时已经统一放进 meta,这里只认 meta。
*/
export interface TurnMeta {
v: 1
@@ -103,6 +121,18 @@ export interface TurnMeta {
ms?: number
/** 查了几次库 */
queries?: number
/**
* 答案没取全。不记下来的话,刷新之后只能靠「恰好 2000 字」去猜:多个成果键拼起来的
* 答案比 2000 长,猜不中,「刷新后会自动补全」的承诺就落空了
*/
clipped?: 'partial' | 'lost'
/** 这一问限定了只查哪些数据源 */
scope?: ScopeSource[]
/**
* 这份 meta 写下的时刻(本机时钟)。断在建图阶段的轮次按它和 created_at 里晚的那个算
* 有多久没动静:后端按 updated_at 算,而重试一轮昨天的问题时 created_at 是昨天的
*/
at?: number
}
export interface ChatTurn {
@@ -174,6 +204,8 @@ export interface ChatTurn {
* 复核完才摆出来,这里给的是「它没卡住」的证据,不是提前看答案的口子
*/
writing?: { chars: number; thought: string } | null
/** 这一问只查这几个数据源。重试、重新问都沿用它 */
scope?: ScopeSource[]
}
export type LoadState = 'loading' | 'ready' | 'error'
@@ -190,12 +222,21 @@ interface ChatState {
*/
loadState: Record<string, LoadState>
loadError: Record<string, unknown>
/**
* 每个会话限定查哪些数据源,空数组 = 不限。键 '' 是还没建出会话的首屏:开口那一下
* 建出会话后由调用方带过去。按会话记:换一个会话问别的库,回来还是原来的范围
*/
scopes: Record<string, ScopeSource[]>
setScope: (key: string, scope: ScopeSource[]) => void
turnsOf: (conversationId: string | null) => ChatTurn[]
/** force:已经取回来过也再取一次(重连后、点重试时) */
load: (conversationId: string, opts?: { force?: boolean }) => Promise<void>
/** 发出去了返回 true。会话还在加载或加载失败、或者正忙时不发 */
ask: (conversationId: string, question: string) => boolean
/**
* 发出去了返回 true。会话还在加载或加载失败、或者正忙时不发。
* scope 不给就用这个会话眼下的范围
*/
ask: (conversationId: string, question: string, opts?: { scope?: ScopeSource[] }) => boolean
/** 只停这个会话自己正在跑的那一轮 */
stop: (conversationId: string) => void
/** 审批完成后重新接上运行 */
@@ -209,11 +250,17 @@ interface ChatState {
/**
* 用户主动重试这一轮:上一次折叠留档,新的一次接在同一轮里。
* maxSteps:把图里 agent 的步数上限调到这个值,原图重跑(「放宽步数重跑」);
* rerun:原图原样重跑(取消了、中断了的那种,不需要改)
* rerun:原图原样重跑(取消了、中断了的那种,不需要改);
* scope:换一个数据源范围重来(限定的库不在了),不给就沿用这一轮的
*/
retryTurn: (conversationId: string, turnId: string, opts?: { maxSteps?: number; rerun?: boolean }) => void
retryTurn: (
conversationId: string, turnId: string,
opts?: { maxSteps?: number; rerun?: boolean; scope?: ScopeSource[] },
) => void
/** 向后端核对一轮历史:真实状态、完整答案、档位。只做一次 */
hydrate: (conversationId: string, turnId: string) => Promise<void>
/** 上次核对撞上后端出错(unknown)的轮次,再核对一次 */
recheck: (conversationId: string, turnId: string) => Promise<void>
/** 会话被删了,把内存里那一桶也丢掉 */
forget: (conversationId: string) => void
}
@@ -233,6 +280,7 @@ const PHASE_TEXT: Record<Phase, string> = {
error: '失败',
cancelled: '已取消',
suspended: '服务重启,这一轮中断了',
unknown: '没核对上这一轮现在的状态',
}
const EMPTY: ChatTurn[] = []
@@ -249,6 +297,24 @@ const REVIEW_TIMEOUT_MS = 25_000
*/
const LEGACY_CLIP = 2000
/**
* 是不是恰好切在 LEGACY_CLIP。后端按码点切,JS 的 length 数的是 UTF-16:答案里
* 有一个 emoji 就多出一个,按 length 比就认不出来了
*/
function atClip(s: string): boolean {
if (s.length < LEGACY_CLIP || s.length > LEGACY_CLIP * 2) return false
let n = 0
for (const _ of s) n++
return n === LEGACY_CLIP
}
/**
* 还停在 running 的轮次、又没有运行:断在建图阶段了。建图跟着页面那条流走,页面一关
* 就停;这么久还没动静就当它断了(和后端 conversations.BUILD_STALE 一致)。「动静」
* 按最后一次落库算,见 TurnMeta.at
*/
const BUILD_STALE_MS = 15 * 60_000
/** 留档的旧答案存多少。它是用来对照的,不是用来读全文的——全文在运行记录里 */
const ATTEMPT_ANSWER_CAP = 4000
@@ -312,7 +378,7 @@ function answerText(output: Record<string, any> | null | undefined): string {
/** 事件里那份 output 看起来是不是被切过:老后端不带 output_truncated,只能看长度 */
function looksClipped(output: Record<string, any> | null | undefined): boolean {
if (!output) return false
return Object.values(output).some((v) => typeof v === 'string' && v.length === LEGACY_CLIP)
return Object.values(output).some((v) => typeof v === 'string' && atClip(v))
}
/** 出具信息存进 meta 前瘦一下身:无法回指的数字可能有上百个,横幅只列得下一行 */
@@ -328,13 +394,10 @@ function countQueries(events: RunEvent[]): number {
}
export function metaOf(t: ConversationTurn): TurnMeta | null {
const own = (t as any).meta
if (own && typeof own === 'object') return own as TurnMeta
const bridged = (t.review as any)?.meta
return bridged && typeof bridged === 'object' ? (bridged as TurnMeta) : null
return t.meta && typeof t.meta === 'object' ? (t.meta as TurnMeta) : null
}
/** review 字段里真正的复核结论。只挂了 meta、没有 verdict 的不算复核过 */
/** review 字段里真正的复核结论。只挂了 meta、没有 verdict 的不算复核过(老轮次的 meta 在里面,剥掉) */
function reviewOf(t: ConversationTurn): ReviewResult | null {
const r = t.review as any
if (!r || typeof r !== 'object' || !r.verdict) return null
@@ -355,29 +418,60 @@ function buildMeta(t: ChatTurn): TurnMeta {
attempts: t.attempts?.length ? t.attempts : undefined,
ms: t.endedAt ? t.endedAt - t.startedAt : t.meta?.ms,
queries: t.events.length ? countQueries(t.events) : t.meta?.queries,
clipped: t.clipped,
scope: t.scope?.length ? t.scope : undefined,
at: Date.now(),
}
}
/** 写回 review 字段的那份:复核原样 + meta */
function packReview(t: ChatTurn): Record<string, any> {
return { ...(t.reviewRaw ?? {}), meta: buildMeta(t) }
}
/** 一行错误文案 → 结构化。后端的 detail 按约定已是人话,humanizeError 只做拆句和去类名 */
/**
* 一行错误文案 → 结构化。后端的 detail 按约定已是人话,humanizeError 只做拆句和去类名。
* 运行本身的失败不走这里,走 runFailure
*/
function failureOf(e: unknown, extra?: { hint?: string; detail?: string }): Failure {
const h = humanizeError(e)
// 原话留一份(后端的 detail)。连不上后端时原话是「Failed to fetch」,没有留的价值
const source = h.kind === 'network' ? undefined
: typeof e === 'string' ? e
: e instanceof ApiError ? e.message
: undefined
return {
title: h.title,
reason: h.reason,
hint: extra?.hint || h.action,
// 通用的「稍等几秒会自动重试」在这一页不成立:没有谁会替这一轮重发,得人来点
hint: extra?.hint || (h.kind === 'network' ? '后端连上之后点「重试这一轮」。' : h.action),
detail: extra?.detail || (h.raw && h.raw !== h.title ? h.raw : undefined),
// 连不上后端时原话是「Failed to fetch」,再翻一遍不会再判成网络问题,不能交出去
...(typeof e === 'string' && h.kind !== 'network' ? { source: e } : {}),
...(source ? { source } : {}),
}
}
/**
* 运行失败的说明:和记录页、画布右栏读同一份 lib/explain,同一次失败三处说法一致。
* 它还说得出「原样接着跑有没有用」:缺输入、人驳回、工具没绑,接着跑只会再失败一次。
* 原话跟着留:流里的报错块拿它按同一份 lib/explain 再讲一遍,才给得出「去模型接入」
* 这类直达入口
*/
function runFailure(error: string | null | undefined, detail?: string | null): Failure {
const x = explainRunError(error, detail)
return {
title: x.title,
reason: x.reason,
hint: x.action,
detail: x.raw && x.raw !== x.title ? x.raw : undefined,
...(x.continuable ? {} : { continuable: false as const }),
...(error ? { source: error } : {}),
}
}
const lineOf = (f: Failure) => (f.reason ? `${f.title}:${f.reason}` : f.title)
/** 运行记录被删了:没有断点可续,也补不回完整答案 */
const GONE: Failure = {
title: '上次没有跑完',
reason: '对应的运行记录已经删掉了,没有断点可以接着跑。',
hint: '点「重试这一轮」重新来一次。',
}
const SUSPENDED: Failure = {
title: PHASE_TEXT.suspended,
reason: '断点还在,前面查过的表、跑过的步骤都保留着。',
@@ -412,11 +506,21 @@ function findTurn(conversationId: string, turnId: string): ChatTurn | undefined
return useChat.getState().byConversation[conversationId]?.find((t) => t.id === turnId)
}
/** 带上 meta 一起写:review 字段是整块替换的,只写一半另一半就没了 */
/**
* 在回收站里的会话只能翻看。从这里发起的运行左栏找不到、没人看着,却照样计费;
* 跑着的时候又不能彻底删除。按钮已经按这个关掉了,这里再守一道
*/
const inTrash = (conversationId: string) =>
useConversations.getState().trash.some((c) => c.id === conversationId)
/**
* 连同 meta 和复核一起写。两者在后端都是整块替换。review 写 {} 而不是 null:null 等于
* 「这次不改」,重试之后上一次的复核就留在库里,刷新后挂到新答案头上
*/
function persist(conversationId: string, turnId: string, body: Record<string, any> = {}) {
const turn = findTurn(conversationId, turnId)
if (!turn) return Promise.resolve()
return saver(conversationId, turnId)({ ...body, review: packReview(turn) })
return saver(conversationId, turnId)({ ...body, meta: buildMeta(turn), review: turn.reviewRaw ?? {} })
}
/**
@@ -467,7 +571,9 @@ function restoreTurn(t: ConversationTurn): ChatTurn {
// 老数据没有 meta:停止写的是 status=error + 「已取消」
const outcome = meta?.outcome ?? (t.status === 'error' && t.error === '已取消' ? 'cancelled' : undefined)
const answer = t.answer ?? ''
const failure = meta?.failure ?? (t.error && t.error !== '已取消' ? failureOf(t.error) : null)
// 老数据没有 meta.failure,error 列里是原始异常:有运行的按运行失败解释
const failure = meta?.failure
?? (t.error && t.error !== '已取消' ? (runId ? runFailure(t.error) : failureOf(t.error)) : null)
let phase: Phase
let status: string
@@ -531,9 +637,13 @@ function restoreTurn(t: ConversationTurn): ChatTurn {
reviewRaw: review,
rawOutput: review?.original ? { answer: review.original } : null,
attempts: meta?.attempts,
// 旧版本切在 2000 字、运行也删了:补不回来,但至少别装作完整
clipped: !runId && graphful && answer.length === LEGACY_CLIP && !review?.answer ? 'lost' : undefined,
// 上次记下没取全的:运行还在就等 hydrate 补,运行没了就补不回来了。
// 老数据没记过,只能看是不是恰好切在 2000 字——运行也删了的,至少别装作完整
clipped: meta?.clipped === 'partial' ? (runId ? 'partial' : 'lost')
: meta?.clipped === 'lost' ? 'lost'
: !runId && graphful && atClip(answer) && !review?.answer ? 'lost' : undefined,
meta,
scope: meta?.scope,
}
}
@@ -543,9 +653,9 @@ function needsEagerHydrate(t: ChatTurn): boolean {
if (t.phase === 'checking' || t.phase === 'suspended') return true
// 「接着跑」给不给取决于运行现在的状态;老数据没存过
if (t.phase === 'error' && !t.runStatus) return true
// 旧版本被切在 2000 字的答案:运行还在就把完整版补回来
// 答案没取全:运行还在就把完整版补回来
return t.phase === 'done' && !t.review?.answer
&& typeof t.output?.answer === 'string' && t.output.answer.length === LEGACY_CLIP
&& (t.clipped === 'partial' || (typeof t.output?.answer === 'string' && atClip(t.output.answer)))
}
@@ -553,6 +663,9 @@ export const useChat = create<ChatState>((set, get) => ({
byConversation: {},
loadState: {},
loadError: {},
scopes: {},
setScope: (key, scope) => set((s) => ({ scopes: { ...s.scopes, [key]: scope } })),
turnsOf: (conversationId) =>
(conversationId && get().byConversation[conversationId]) || EMPTY,
@@ -581,15 +694,28 @@ export const useChat = create<ChatState>((set, get) => ({
// 完整的事件和进行中的流。库里多出来的补在前面
const known = new Set(mem.map((t) => t.serverId).filter(Boolean))
const extra = restored.filter((t) => !known.has(t.serverId))
// 数据源范围接着上一问的:回来追问的多半还是那个库。输入框旁写着范围,不是暗中沿用
const lastScope = restored[restored.length - 1]?.scope
return {
byConversation: { ...s.byConversation, [conversationId]: mem.length ? [...extra, ...mem] : restored },
loadState: { ...s.loadState, [conversationId]: 'ready' },
loadError: { ...s.loadError, [conversationId]: undefined },
...(lastScope && !(conversationId in s.scopes) ? { scopes: { ...s.scopes, [conversationId]: lastScope } } : {}),
}
})
for (const t of restored) {
// 内存里已有的那几轮没有并进来,下面对它们的 hydrate / persist 按 id 找不到,自然跳过
const now = Date.now()
detail.turns.forEach((row, i) => {
const t = restored[i]
if (needsEagerHydrate(t)) void get().hydrate(conversationId, t.id)
}
// 断在建图阶段、早就没动静的:库里那行一直是 running,每次进来都当它还在跑,
// Copilot 的上下文也把它当成没答完的一轮漏掉。认定断了就写回去。
// 动静按最后一次落库算:重试昨天那一轮时 created_at 是昨天,而它正在别的页面里建图
const at = Math.max(parseServerTime(row.created_at ?? null)?.getTime() ?? 0, t.meta?.at ?? 0)
if (row.status === 'running' && !t.run && t.phase === 'error' && at && now - at > BUILD_STALE_MS) {
void persist(conversationId, t.id, { status: 'error', error: lineOf(t.failure ?? GONE) })
}
})
} catch (e) {
set((s) => ({
loadState: { ...s.loadState, [conversationId]: 'error' },
@@ -618,14 +744,15 @@ export const useChat = create<ChatState>((set, get) => ({
}
},
ask: (conversationId, question) => {
ask: (conversationId, question, opts) => {
const state = get().loadState[conversationId]
// 历史还没回来就提问,新的一轮会把"这个会话"变成只有它一轮;加载失败时
// 页面上什么都没有,更像是空会话——两种情况都先别让它发
if (state === 'loading' || state === 'error') return false
if (isBusy(get().byConversation[conversationId])) return false
if (isBusy(get().byConversation[conversationId]) || inTrash(conversationId)) return false
const id = newId()
const scope = opts?.scope ?? get().scopes[conversationId] ?? []
set((s) => ({
byConversation: {
...s.byConversation,
@@ -635,7 +762,7 @@ export const useChat = create<ChatState>((set, get) => ({
id, serverId: null, question, phase: 'planning', status: PHASE_TEXT.planning,
thinking: '', ops: [], events: [], graph: null, explanation: '',
run: null, output: null, error: '', startedAt: Date.now(),
lastSeq: 0, cancel: null, attempt: 0,
lastSeq: 0, cancel: null, attempt: 0, scope: scope.length ? scope : undefined,
},
],
},
@@ -656,7 +783,7 @@ export const useChat = create<ChatState>((set, get) => ({
.catch(() => null)
serverIds.set(id, started)
plan(flow, { question, instruction: question, attempt: 0 })
plan(flow, { question, instruction: question, attempt: 0, scope })
return true
},
@@ -682,7 +809,7 @@ export const useChat = create<ChatState>((set, get) => ({
runNow: (conversationId, turnId) => {
const turn = findTurn(conversationId, turnId)
if (!turn?.graph || isBusy(get().byConversation[conversationId])) return
if (!turn?.graph || isBusy(get().byConversation[conversationId]) || inTrash(conversationId)) return
const flow = flowOf(conversationId, turnId)
flow.patch(() => ({
phase: 'running', status: PHASE_TEXT.running, pendingRun: false,
@@ -699,7 +826,7 @@ export const useChat = create<ChatState>((set, get) => ({
//
// 接上之后 run.finished 照常触发 settle,复核层自动覆盖这一次
const turn = findTurn(conversationId, turnId)
if (!turn?.run || isBusy(get().byConversation[conversationId])) return false
if (!turn?.run || isBusy(get().byConversation[conversationId]) || inTrash(conversationId)) return false
try {
await api.runs.continue(turn.run.id)
} catch (e) {
@@ -716,13 +843,19 @@ export const useChat = create<ChatState>((set, get) => ({
retryTurn: (conversationId, turnId, opts) => {
const turns = get().byConversation[conversationId]
const turn = turns?.find((t) => t.id === turnId)
if (!turn || isBusy(turns)) return
if (!turn || isBusy(turns) || inTrash(conversationId)) return
turn.cancel?.()
// 服务重启挂起的旧运行没人会再去续它:不取消的话,它在记录里一直是「已挂起 · 可续跑」。
// 停在审批上的不算——重试不会从那里发起
if (turn.run?.id && turn.phase !== 'waiting' && (turn.phase === 'suspended' || turn.runStatus === 'interrupted')) {
void api.runs.cancel(turn.run.id).catch(() => undefined)
}
const flow = flowOf(conversationId, turnId)
const base = turn.graph && (turn.graph.nodes?.length ?? 0) > 0 ? turn.graph : null
const record = attemptOf(turn)
const reason = record.detail ? `${record.summary}(${record.detail.slice(0, 300)})` : record.summary
const direct = !!base && !!(opts?.maxSteps || opts?.rerun)
const scope = opts?.scope ?? turn.scope
// 上一次原样留档,这一次从头记:旧的事件、答案、复核留在这里只会让人分不清
// 哪段是最终那次
@@ -735,7 +868,7 @@ export const useChat = create<ChatState>((set, get) => ({
rawOutput: null, failure: null, error: '', lastSeq: 0, final: undefined,
runStatus: undefined, clipped: undefined, pendingRun: false, steps: undefined,
hydrated: 'done', startedAt: Date.now(), endedAt: undefined, attempt: 0, cancel: null,
noQuery: false, thinking: '', writing: null,
noQuery: false, thinking: '', writing: null, scope: scope?.length ? scope : undefined,
}))
void flow.persist({ status: 'running', error: '', answer: '' })
@@ -746,7 +879,7 @@ export const useChat = create<ChatState>((set, get) => ({
return
}
plan(flow, {
question: turn.question, attempt: 0, baseGraph: base,
question: turn.question, attempt: 0, baseGraph: base, scope,
instruction: base
? `这张流程上一次没有给出可用的结果:${reason}。\n\n`
+ `请针对这个原因改它(比如调大最大步数、改正工具参数、换个查询方式),`
@@ -764,29 +897,51 @@ export const useChat = create<ChatState>((set, get) => ({
const stale = () => (epochs.get(turnId) ?? 0) !== epoch
const patch = patcher(set, conversationId, turnId)
patch(() => ({ hydrated: 'pending' }))
/**
* 查到了库里那行还不知道的结局:内存里改,库里也改。只改内存的话那行永远是
* running——每次进来都要再核对一遍,Copilot 的上下文把它当没答完的一轮漏掉,
* 运行一删它就只能退成「上次没有跑完」,连「已取消」都说不出来了
*/
const conclude = (fields: Partial<ChatTurn>, error: string) => {
patch(() => fields)
void persist(conversationId, turnId, { status: 'error', error })
}
let run: Run
try {
run = await api.runs.get(runId)
} catch (e) {
if (stale()) return
const cur = findTurn(conversationId, turnId)
if (stale() || !cur) return
if (e instanceof ApiError && e.status === 404) {
// 运行被删了:没有断点可续,也补不回完整答案
patch((t) => ({
hydrated: 'done',
runStatus: 'gone',
...(t.phase === 'checking' ? {
phase: 'error' as Phase, status: PHASE_TEXT.error, error: '上次没有跑完',
failure: {
title: '上次没有跑完',
reason: '对应的运行记录已经删掉了,没有断点可以接着跑。',
hint: '点「重试这一轮」重新来一次。',
},
} : {}),
clipped: t.phase === 'done' && !t.review?.answer
&& String(t.output?.answer ?? '').length === LEGACY_CLIP ? 'lost' : t.clipped,
if (cur.phase === 'checking') {
conclude({
hydrated: 'done', runStatus: 'gone', phase: 'error', status: PHASE_TEXT.error,
error: GONE.title, failure: GONE,
}, GONE.title)
return
}
// 没取全的答案,运行又删了:补不回来,但得说出来,也记下来
const lost = cur.phase === 'done' && !cur.review?.answer
&& (cur.clipped === 'partial' || atClip(String(cur.output?.answer ?? '')))
patch((t) => ({ hydrated: 'done', runStatus: 'gone', clipped: lost ? 'lost' : t.clipped }))
if (lost) void persist(conversationId, turnId)
} else if (cur.phase === 'checking') {
// 后端出错、超时:不知道它现在怎样,但不能一直停在「正在核对」转圈——那之后
// 再也没有人来核对(重连只在断开过之后才触发)。说清楚,给「重新核对」
const said = errorMessage(e)
const raw = humanizeError(e).raw
const failure: Failure = {
title: PHASE_TEXT.unknown,
reason: `去后端查这一轮的运行时出错了(${said})。它可能还在跑,也可能已经结束。`,
hint: '稍后点「重新核对」;后端断开又连上时会自动再核对一次。',
// 原话已经在括号里的,技术细节不再重复一遍
detail: raw && !said.includes(raw) ? raw : undefined,
}
patch(() => ({
hydrated: undefined, phase: 'unknown', status: PHASE_TEXT.unknown, failure, error: lineOf(failure),
}))
} else {
patch(() => ({ hydrated: undefined })) // 网断了之类:下次再试
patch(() => ({ hydrated: undefined })) // 已经有个结局摆着,下次再补
}
return
}
@@ -800,41 +955,54 @@ export const useChat = create<ChatState>((set, get) => ({
if (run.status === 'running' || run.status === 'queued') {
if (unsettled) {
const flow = flowOf(conversationId, turnId)
flow.patch(() => ({ phase: 'running', status: PHASE_TEXT.running, failure: null, error: '', endedAt: undefined }))
// 计时不从提问那天算:中断过的接着上次停下的地方走,停在半路的从运行开始算
const spent = cur.endedAt ? Math.max(0, cur.endedAt - cur.startedAt) : null
const startedAt = spent != null ? Date.now() - spent
: parseServerTime(run.started_at ?? null)?.getTime() ?? cur.startedAt
flow.patch(() => ({
phase: 'running', status: PHASE_TEXT.running, failure: null, error: '', startedAt, endedAt: undefined,
}))
watch(flow, run.id, cur.lastSeq, cur.question)
}
return
}
if (run.status === 'interrupted') {
if (pending) {
// 还在等人:库里那行保持 running 就是对的,它确实没结束
patch(() => ({ phase: 'waiting', status: PHASE_TEXT.waiting, failure: null, error: '' }))
void useCatalog.getState().refreshApprovals()
} else if (cur.phase !== 'done') {
patch(() => ({ phase: 'suspended', status: PHASE_TEXT.suspended, failure: SUSPENDED, error: '' }))
} else if (cur.phase !== 'done' && cur.phase !== 'suspended') {
conclude({ phase: 'suspended', status: PHASE_TEXT.suspended, failure: SUSPENDED, error: '' }, PHASE_TEXT.suspended)
}
return
}
if (run.status === 'cancelled' && cur.phase !== 'done') {
patch(() => ({ phase: 'cancelled', status: PHASE_TEXT.cancelled, failure: null, error: '' }))
if (run.status === 'cancelled') {
if (cur.phase !== 'done' && cur.phase !== 'cancelled') {
conclude({ phase: 'cancelled', status: PHASE_TEXT.cancelled, failure: null, error: '' }, '已取消')
}
return
}
if (run.status === 'failed' && cur.phase !== 'done') {
const failure = cur.phase === 'error' && cur.failure ? cur.failure : failureOf(run.error || '运行失败')
patch(() => ({ phase: 'error', status: PHASE_TEXT.error, failure, error: lineOf(failure) }))
if (run.status === 'failed') {
if (cur.phase === 'error' && cur.failure) return
if (cur.phase !== 'done') {
const failure = runFailure(run.error || '')
conclude({ phase: 'error', status: PHASE_TEXT.error, failure, error: lineOf(failure) }, lineOf(failure))
}
return
}
if (run.status !== 'succeeded') return
if (unsettled) {
// 跑完了,但交付没赶上(复核期间关了页面、服务重启):把这一轮补完,
// 走一遍和实时一样的复核与落库
// 走一遍和实时一样的复核与落库。相位停在「正在核对」而不是「运行中」:运行
// 早就结束了,按实时算的计时会从提问那天一路数到现在(「72:00:01」)
const flow = flowOf(conversationId, turnId)
flow.patch(() => ({ phase: 'running', status: '正在核对结果…', failure: null, error: '' }))
flow.patch(() => ({ phase: 'checking', status: '正在核对结果…', failure: null, error: '' }))
// 耗时按运行真正结束的时刻算:补交付可能发生在几天之后
const endedAt = parseServerTime(run.finished_at ?? null)?.getTime()
void settle(flow, run.id, cur.question, run.output ?? null, { run, endedAt })
return
}
// 已经交付过的:答案被旧版本切过就换成完整的,顺手把档位补回来
// 已经交付过的:答案没取全就换成完整的,顺手把档位补回来
const full = answerText(run.output)
const stored = String(cur.output?.answer ?? '')
const repaired = !cur.review?.answer && stored.length >= 200
@@ -848,6 +1016,15 @@ export const useChat = create<ChatState>((set, get) => ({
}
},
recheck: (conversationId, turnId) => {
const turn = findTurn(conversationId, turnId)
if (!turn || turn.phase !== 'unknown') return Promise.resolve()
patcher(set, conversationId, turnId)(() => ({
phase: 'checking', status: PHASE_TEXT.checking, failure: null, error: '', hydrated: undefined,
}))
return get().hydrate(conversationId, turnId)
},
reattach: async (conversationId, turnId) => {
const turn = findTurn(conversationId, turnId)
if (!turn?.run) return
@@ -1005,6 +1182,8 @@ interface PlanArgs {
/** 重试时把上一次那张图交回去,让它改而不是重建。null = 从零建 */
baseGraph?: GraphSpec | null
attempt: number
/** 这一问限定只查的数据源。空或不给 = 不限 */
scope?: ScopeSource[]
}
/**
@@ -1015,8 +1194,8 @@ interface PlanArgs {
* 本来就是在手动做这件事。
*/
function plan(flow: Flow, args: PlanArgs) {
const { question, instruction, baseGraph, attempt } = args
const { patch, save } = flow
const { question, instruction, baseGraph, attempt, scope } = args
const { patch } = flow
/** 这一轮建出来的图。retry 要把它交回去,所以得在闭包里留一份 */
let built: GraphSpec | null = baseGraph ?? null
@@ -1049,6 +1228,7 @@ function plan(flow: Flow, args: PlanArgs) {
question,
attempt: attempt + 1,
baseGraph: base,
scope,
instruction: base
? `这张流程上一次运行没有成功:${reason}。\n\n`
+ `请针对这个原因改它(比如调大最大步数、改正工具参数、换个查询方式),`
@@ -1069,7 +1249,10 @@ function plan(flow: Flow, args: PlanArgs) {
}
const cancelCopilot = streamCopilot(
{ instruction, base_graph: baseGraph ?? null, intent: 'answer', conversation_id: flow.conversationId },
{
instruction, base_graph: baseGraph ?? null, intent: 'answer', conversation_id: flow.conversationId,
...(scope?.length ? { datasource_ids: scope.map((d) => d.id) } : {}),
},
(op) => {
// 停止之后缓冲里还没派发完的操作:一条 final 就能把这一轮又跑起来
if (!flow.alive()) return
@@ -1120,7 +1303,8 @@ function plan(flow: Flow, args: PlanArgs) {
case 'final': {
const graph = op.graph as GraphSpec
built = graph // 要重试的话,交回去的就是它
void save({ graph, explanation: op.explanation ?? '' })
// 连 meta 一起写:它的 at 是「建图还有动静」的凭据,后端这时也会刷新 updated_at
void flow.persist({ graph, explanation: op.explanation ?? '' })
// 没过校验的图不能拿去跑:引擎会照实抛出它自己的措辞("图是空的,
// 先拖一个节点进来"),而用户根本不在画布上,这句话对他毫无意义。
@@ -1174,6 +1358,19 @@ function plan(flow: Flow, args: PlanArgs) {
if (!error || !flow.alive()) return
const turn = findTurn(flow.conversationId, flow.turnId)
if (!turn || !BUSY_PHASES.has(turn.phase) || turn.run) return
// 限定的库一个都不在了:后端在开流之前就 400。流的结束回调只拿得到那句 detail,
// 按它认;认出来了,补救得是「不限数据源重试」,带着原范围重试只会再被拒一次
if (scope?.length && error.startsWith('限定的数据源')) {
const at = error.indexOf(':')
fail({
title: at > 0 ? error.slice(0, at) : error,
reason: at > 0 ? `${error.slice(at + 1).split('。')[0]}。` : undefined,
hint: '点「不限数据源重试」;想还只查它,先到「数据」页确认它还在、而且是启用的。',
detail: error,
scopeGone: true,
})
return
}
fail(failureOf(error))
},
)
@@ -1194,10 +1391,18 @@ async function launch(
return
}
patch(() => ({ run, runStatus: run.status }))
void flow.save({ run_id: run.id })
// meta 里的 runId 优先于 run_id 列(重试建图失败时那一列清不掉),所以得一起改:
// 只写列的话,重试出来的这次运行在库里一直挂着 runId=null,跑着的时候刷新或者
// 另开一页,它就成了「断在建图阶段」,放久了还会被当成断了写回 error。
// 「跑一下」发起时库里那行还是 done,一并改成 running
void flow.persist({ run_id: run.id, status: 'running' })
watch(flow, run.id, 0, question, retry)
} catch (e) {
const failure = failureOf(e)
// 发起那一下没到后端:流程是好的,原样再发起就行。通用的「稍等几秒会自动重试」
// 在这里不成立——这一页没有谁会替它重发
const failure: Failure = isNetworkError(e)
? { ...failureOf(e, { hint: '后端连上之后点「重跑这一轮」,搭好的流程不用重来。' }), rerun: true }
: failureOf(e)
patch(() => ({
phase: 'error', status: PHASE_TEXT.error, error: lineOf(failure), failure,
cancel: null, endedAt: Date.now(),
@@ -1359,7 +1564,7 @@ function watch(
case 'run.failed': {
ended = true
batch.now()
const failure = failureOf(String(d.error ?? '运行失败'), { detail: d.detail ? String(d.detail) : undefined })
const failure = runFailure(d.error ? String(d.error) : '', d.detail ? String(d.detail) : undefined)
patch(() => ({
phase: 'error', status: PHASE_TEXT.error, error: lineOf(failure), failure,
cancel: null, endedAt: Date.now(), runStatus: 'failed', final: { status: 'failed' },
@@ -1482,7 +1687,8 @@ async function settle(
reviewRaw: result,
cancel: null,
endedAt: opts.endedAt ?? Date.now(),
clipped,
// 复核改写时读的是库里那份完整成果,改写出来的答案不缺尾巴
clipped: rewritten ? undefined : clipped,
// 到这一步才把成果摆出来:复核说明和结论同时出现,而不是结论先读完
output,
// 改写是有损的,原件得留着——界面上可以展开对照。它跟着 review 一起
+61 -19
View File
@@ -1,5 +1,6 @@
import { create } from 'zustand'
import { api } from '../api/client'
import { parseServerTime } from '../lib/format'
import type { Conversation } from '../types'
/**
@@ -27,8 +28,24 @@ export const lastVisited = (): string | null => {
}
}
/**
* 列表接口带上已归档的(回收站)。client 的 list 还不认 include_archived 参数(已提给 3c),
* kind 原样拼进查询串,先借它带上
*/
const WITH_TRASH = 'chat&include_archived=true' as 'chat'
/** 按最后活跃时间排:恢复出来的会话回到它原本该在的位置 */
const activeAt = (c: Conversation) => parseServerTime(c.last_active_at ?? c.created_at ?? '')?.getTime() ?? 0
interface ConversationState {
list: Conversation[]
/**
* 回收站:删掉(归档)的会话。删除先归档,是因为误删一个聊了七轮的对话没有别的
* 找回途径;撤销只有几秒,回收站一直在
*/
trash: Conversation[]
/** 左栏在看回收站。放在 store 里:问数据页的「恢复」要能把左栏切回列表 */
showTrash: boolean
currentId: string | null
loading: boolean
/** 列表取失败了。和「一个对话都没有」要分开说 */
@@ -40,23 +57,31 @@ interface ConversationState {
/** 由 URL 回流调用,把「在看哪个」记下来。不要在别处直接调它 */
select: (id: string | null) => void
rename: (id: string, title: string) => Promise<void>
/** 删掉,返回接下来该去哪个(列表空了就是 null),由调用方导航 */
remove: (id: string) => Promise<string | null>
setShowTrash: (show: boolean) => void
/**
* 从列表里拿掉(归档),返回接下来该去哪个。撤销就是 restore。
* 从列表里拿掉、放进回收站(归档),返回接下来该去哪个。撤销就是 restore。
*
* 用归档而不是「先藏起来、过几秒再真删」:延迟删除在关掉标签页、切走页面时
* 要么没删成、要么撤销不了。归档是一次就落库的状态,撤不撤都不会丢
*/
archive: (id: string) => Promise<string | null>
/** 撤销归档,放回原来的位置 */
restore: (item: Conversation, index: number) => Promise<void>
/** 从回收站拿回来。index 是撤销时的原位置;不给就按最后活跃时间插回去 */
restore: (item: Conversation, index?: number) => Promise<void>
/** 真删(DELETE)。只从回收站里发起,调用方负责先确认 */
purge: (id: string) => Promise<void>
/**
* 回收站里的这些真删(不给就是全部),返回没删掉的个数。正在跑的由调用方挑出去:
* 删掉会话只会关掉这一头的事件流,后端的运行照样跑、照样计费
*/
emptyTrash: (ids?: string[]) => Promise<number>
/** 有人在这个会话里说话了,把它顶到列表最前并刷新副标题 */
touch: (id: string, lastQuestion?: string) => void
}
export const useConversations = create<ConversationState>((set, get) => ({
list: [],
trash: [],
showTrash: false,
currentId: null, // 由 URL 填,见 ChatPage 的同步 effect
loading: false,
error: null,
@@ -66,7 +91,13 @@ export const useConversations = create<ConversationState>((set, get) => ({
// 两边都能定就会互相覆盖:深链接进来,列表一加载完又被拽回上次那个
set({ loading: true })
try {
set({ list: await api.conversations.list('chat'), loading: false, error: null })
const rows = await api.conversations.list(WITH_TRASH)
set({
list: rows.filter((c) => !c.archived),
trash: rows.filter((c) => c.archived),
loading: false,
error: null,
})
} catch (e) {
set({ loading: false, error: e })
}
@@ -102,23 +133,18 @@ export const useConversations = create<ConversationState>((set, get) => ({
}
},
remove: async (id) => {
await api.conversations.remove(id)
const list = get().list.filter((c) => c.id !== id)
set({ list })
// 删的不是当前这个就原地不动;删的是当前这个才需要换地方
return get().currentId === id ? (list[0]?.id ?? null) : get().currentId
},
setShowTrash: (show) => set({ showTrash: show }),
archive: async (id) => {
const before = get().list
const { list: before, trash } = get()
const item = before.find((c) => c.id === id)
const list = before.filter((c) => c.id !== id)
// 先从列表里拿掉再发请求:删除该是即时的,失败了再放回去
set({ list })
set({ list, trash: item ? [{ ...item, archived: true }, ...trash] : trash })
try {
await api.conversations.update(id, { archived: true })
} catch (e) {
set({ list: before })
set({ list: before, trash })
throw e
}
return get().currentId === id ? (list[0]?.id ?? null) : get().currentId
@@ -127,13 +153,29 @@ export const useConversations = create<ConversationState>((set, get) => ({
restore: async (item, index) => {
await api.conversations.update(item.id, { archived: false })
set((s) => {
if (s.list.some((c) => c.id === item.id)) return s
const trash = s.trash.filter((c) => c.id !== item.id)
if (s.list.some((c) => c.id === item.id)) return { trash }
const list = [...s.list]
list.splice(Math.min(index, list.length), 0, { ...item, archived: false })
return { list }
const later = list.findIndex((c) => activeAt(c) < activeAt(item))
const at = index ?? (later < 0 ? list.length : later)
list.splice(Math.min(at, list.length), 0, { ...item, archived: false })
return { list, trash }
})
},
purge: async (id) => {
await api.conversations.remove(id)
set((s) => ({ trash: s.trash.filter((c) => c.id !== id), list: s.list.filter((c) => c.id !== id) }))
},
emptyTrash: async (only) => {
const ids = get().trash.map((c) => c.id).filter((id) => !only || only.includes(id))
const results = await Promise.allSettled(ids.map((id) => api.conversations.remove(id)))
const gone = new Set(ids.filter((_, i) => results[i].status === 'fulfilled'))
set((s) => ({ trash: s.trash.filter((c) => !gone.has(c.id)) }))
return ids.length - gone.size
},
touch: (id, lastQuestion) => {
set((s) => {
const hit = s.list.find((c) => c.id === id)
+141 -27
View File
@@ -4,6 +4,7 @@ import {
type Connection, type Edge, type EdgeChange, type Node, type NodeChange,
} from '@xyflow/react'
import { api, streamCopilot, streamRun } from '../api/client'
import { describeToolChange, mergeNodeConfig, shrunkTools, toolChangesOf } from '../canvas/copilotMerge'
import { NODE_DEFS, sourceHandles } from '../canvas/nodeDefs'
import { toast } from '../components/ui'
import { humanizeError } from '../lib/errors'
@@ -16,7 +17,7 @@ import {
type NodeState, type RunPhase, type Trace,
} from '../run/trace'
import type {
ConversationTurn, GraphEdge, GraphSpec, NodeRuntime, NodeType, Run, RunEvent, ValidationIssue,
ConversationTurn, GraphEdge, GraphSpec, NodeRuntime, NodeType, Run, RunEvent, ToolChange, ValidationIssue,
VarIssue, Variable, Workflow,
} from '../types'
@@ -114,9 +115,24 @@ export interface CopilotTurn {
round?: number
repaired?: number
message?: string
/** 自查时发现的工具被删(tools_dropped)。不挡运行,但要在这一步说出来 */
warnings?: string[]
}
/** 这一轮开始前打的撤销点。还在栈顶时「撤销这次」直接撤它 */
checkpoint?: number
/** 提交的时刻(毫秒)。助手流的头部据此走实时计时,不用等 3 秒一次的心跳 */
startedAt?: number
/**
* 这一轮改了哪些节点、成员的工具绑定。画布上看不出来(节点还在),跑起来才发现查不了库,
* 所以回执要明说。取后端 final.tool_changes;老后端不给时前端自己比对前后两张图
*/
toolChanges?: ToolChange[]
/**
* 工具集合变小、而这一轮的指令没让删的提醒(check.warnings 和 final.issues 里
* code === 'tools_dropped' 的,去重)。单独放:和「成果字段可能为空」这类普通校验提示
* 混在一起,最要紧的这句就淹没了
*/
toolWarnings?: CopilotIssue[]
}
export interface CopilotIssue {
@@ -125,8 +141,34 @@ export interface CopilotIssue {
node_id?: string | null
code?: string
type?: string
field?: string | null
}
/**
* 画布此刻为什么改不了:
* - copilot:助手正在改它,这时候的手动编辑会被它的最终结果悄悄覆盖;
* - formal:正式运行在跑已发布的不可变版本,此刻改图既改不了它,还会让事件对到
* 已经被删掉的节点上。画布那边(FlowCanvas)按同一个条件写 data-readonly
*/
export type EditLock = 'copilot' | 'formal' | null
const formalRunning = (s: Pick<StudioState, 'runPhase' | 'trace' | 'run'>): boolean =>
isActivePhase(s.runPhase) && (s.trace.runClass ?? s.run?.run_class) === 'formal'
export function editLockOf(s: Pick<StudioState, 'copilot' | 'runPhase' | 'trace' | 'run'>): EditLock {
if (s.copilot.active) return 'copilot'
return formalRunning(s) ? 'formal' : null
}
/** 改图入口被拦下时说的话。检查器、节点库、快捷键都用这一份 */
export const EDIT_LOCK_TEXT: Record<Exclude<EditLock, null>, string> = {
copilot: '助手正在改这张工作流:等它做完,或者先停下',
formal: '正式运行进行中,画布只读:它跑的是已发布的不可变版本,结束后再改',
}
/** 组件里订阅锁:只在锁的原因变了时重渲染 */
export const useEditLock = (): EditLock => useStudio(editLockOf)
/** 两张图差在哪。只看节点的名字和配置,挪位置不算改动 */
export interface GraphDiff {
added: string[]
@@ -138,6 +180,17 @@ export interface GraphDiff {
total: number
}
/** 自查的 warnings 和 final.issues 里是同样的几条:按节点、字段、文字去重 */
function dedupeIssues(list: CopilotIssue[]): CopilotIssue[] {
const seen = new Set<string>()
return list.filter((i) => {
const key = `${i.node_id ?? ''}|${i.field ?? ''}|${i.message}`
if (seen.has(key)) return false
seen.add(key)
return true
})
}
// 只留最近几轮。画布只反映最后一次生成的结果,更早的轮次是参考而不是现状,
// 无上限地攒着只会把内存和滚动条都撑坏。
const COPILOT_TURN_LIMIT = 10
@@ -458,6 +511,10 @@ interface StudioState {
lastOp: string
explanation: string
error: string
/** 出错时「怎么办」(后端 error 操作的 hint)。Composer 的错误条和问数据页一样摊开它 */
errorHint: string
/** 出错时的原始报错(后端 error 操作的 detail),折叠在技术细节里 */
errorDetail: string
model: string
// 从提交到第一个操作之间有 5~30 秒,得让用户看见这段在发生什么
phase: 'connecting' | 'planning' | 'building' | 'wiring' | 'finalizing' | 'repairing' | ''
@@ -505,7 +562,11 @@ interface StudioState {
startRun: (input: Record<string, any>) => Promise<Run | null>
startFormalRun: (input: Record<string, any>) => Promise<Run | null>
runCopilot: (instruction: string, useBase: boolean, model?: string | null) => void
/**
* 开始一轮助手改图。返回开没开始:正式运行期间画布只读,会被拦下(并提示为什么),
* 输入框据此决定要不要清掉用户刚写的那句
*/
runCopilot: (instruction: string, useBase: boolean, model?: string | null) => boolean
/** 停掉这一轮,画布退回这一轮之前(半成品进 future,⇧⌘Z 能找回来) */
stopCopilot: () => void
retryCopilot: () => void
@@ -831,8 +892,8 @@ function commit(
return entry
}
/** 画布锁着:助手正在改这张图,这时候的手动编辑会被它的最终结果悄悄覆盖 */
const locked = (get: () => StudioState) => get().copilot.active
/** 画布锁着:助手正在改,或者正式运行在跑(见 editLockOf) */
const locked = (get: () => StudioState) => editLockOf(get()) !== null
/** 撤销 / 重做之后:选中的节点没了就收起检查器,未保存标记按内容重算 */
function afterJump(set: SetFn, get: () => StudioState, nodes: FlowNode[], edges: Edge[]) {
@@ -977,7 +1038,7 @@ export const useStudio = create<StudioState>((set, get) => ({
copilotConversationId: null,
copilotMemory: { past: [], total: 0, turns: 0 },
copilotCursor: null,
copilot: { active: false, lastOp: '', explanation: '', error: '', model: '',
copilot: { active: false, lastOp: '', explanation: '', error: '', errorHint: '', errorDetail: '', model: '',
phase: '', thinking: '', elapsedMs: 0, lastInstruction: '', lastUseBase: false },
copilotNew: [],
copilotTurns: [],
@@ -1014,7 +1075,8 @@ export const useStudio = create<StudioState>((set, get) => ({
copilotTurns: [],
copilotNew: [],
copilotCursor: null,
copilot: { ...get().copilot, active: false, phase: '', thinking: '', lastOp: '', error: '' },
copilot: { ...get().copilot, active: false, phase: '', thinking: '', lastOp: '', error: '',
errorHint: '', errorDetail: '' },
cancelCopilot: null,
// 先清空再去解析:留着上一张图的会话 id,这中间的任何一条指令
// 都会带着别的图的上下文发出去
@@ -1415,6 +1477,11 @@ export const useStudio = create<StudioState>((set, get) => ({
},
runCopilot: (instruction, useBase, model) => {
// 正式运行跑的是已发布的版本,画布此刻只读:助手改完的图落不下来,不如先说清楚
if (formalRunning(get())) {
toast.warn(EDIT_LOCK_TEXT.formal, { key: 'studio:readonly' })
return false
}
// 上一轮还在跑:先按停止收掉,免得两条流一起往画布上写
if (get().copilot.active) get().stopCopilot()
glideSeq++
@@ -1432,6 +1499,8 @@ export const useStudio = create<StudioState>((set, get) => ({
const anchored = new Set<string>()
/** 前端认不出来、没放上画布的节点类型。后端 final.issues 没说到的,收尾时补上,不能安静地少一步 */
const dropped: string[] = []
/** 自查时报出来的工具被删(check.warnings)。收尾时和 final 里同样的那几条合并去重 */
const toolDrops: CopilotIssue[] = []
const withDropped = (raw: unknown): CopilotIssue[] => {
const issues: CopilotIssue[] = Array.isArray(raw) ? [...raw] : []
for (const type of dropped) {
@@ -1444,7 +1513,7 @@ export const useStudio = create<StudioState>((set, get) => ({
set({
copilot: {
active: true, lastOp: '', explanation: '', error: '', model: model ?? '',
active: true, lastOp: '', explanation: '', error: '', errorHint: '', errorDetail: '', model: model ?? '',
phase: 'connecting', thinking: '', elapsedMs: 0,
lastInstruction: instruction, lastUseBase: useBase,
},
@@ -1456,7 +1525,7 @@ export const useStudio = create<StudioState>((set, get) => ({
copilotTurns: [
...state.copilotTurns.slice(-(COPILOT_TURN_LIMIT - 1)),
{ id: turnId, instruction, ops: [], phase: 'running', explanation: '', error: '',
useBase, checkpoint: checkpoint.id },
useBase, checkpoint: checkpoint.id, startedAt: Date.now() },
],
})
@@ -1488,7 +1557,7 @@ export const useStudio = create<StudioState>((set, get) => ({
if (activeTurn?.id === turnId) activeTurn = null
set({
copilot: { ...get().copilot, active: false, lastOp: '', phase: '', thinking: '',
elapsedMs: 0, ...patch },
elapsedMs: 0, errorHint: '', errorDetail: '', ...patch },
cancelCopilot: null, copilotCursor: null,
})
}
@@ -1541,8 +1610,17 @@ export const useStudio = create<StudioState>((set, get) => ({
(op) => {
if (finished) return
const s = get()
// 卡片上的「少了一步」读的是记下来的 final:这里认不出来而后端没提的,一并记进去
record(op.op === 'final' && dropped.length ? { ...op, issues: withDropped(op.issues) } : op)
if (op.op === 'final') {
// 卡片上的「少了一步」、回执里的工具绑定变化读的都是记下来的 final:这里认不出来
// 而后端没提的类型,老后端不给的 tool_changes(前端自己比对),一并补齐了再记
op = {
...op,
issues: withDropped(op.issues),
tool_changes: Array.isArray(op.tool_changes) ? op.tool_changes
: toolChangesOf(before.nodes, op.graph ? toFlow(op.graph).nodes : []),
}
}
record(op)
switch (op.op) {
case 'model':
// 后端首帧告知实际用的模型,浮条上直接显示,不用猜
@@ -1573,16 +1651,21 @@ export const useStudio = create<StudioState>((set, get) => ({
break
case 'check': {
// 服务端自查:用运行时同一套规则过一遍,有问题交回模型改
// 现在是一句话;以后后端会改成 {node_id, message}(能定位到节点),两种都接住。
// 以前是一句话,后端改成 {node_id, message, field?} 之后能定位到节点,两种都接住。
// 带节点的前面补上节点名,「再修一次」拼指令时模型才知道说的是哪个
const issues = (op.issues ?? []).map((x: any) => {
const lineOf = (x: any): string => {
if (typeof x === 'string') return x
const message = String(x?.message ?? JSON.stringify(x))
const label = x?.node_id ? s.nodes.find((n) => n.id === x.node_id)?.data.label : ''
return label && !message.includes(`「${label}」`) ? `「${label}」:${message}` : message
})
}
const issues = (op.issues ?? []).map(lineOf)
// 工具被删不挡运行,但自查这一步就要说出来(tools_dropped)
const warnings: any[] = Array.isArray(op.warnings) ? op.warnings : []
for (const w of warnings) if (w && typeof w === 'object') toolDrops.push(w)
settle({ check: { status: op.status, issues, round: op.round, repaired: op.repaired,
message: op.message } })
message: op.message,
...(warnings.length ? { warnings: warnings.map(lineOf) } : {}) } })
set({ copilot: { ...s.copilot,
phase: op.status === 'repairing' ? 'repairing' : s.copilot.phase,
lastOp: op.status === 'repairing'
@@ -1634,21 +1717,27 @@ export const useStudio = create<StudioState>((set, get) => ({
})
break
}
case 'update_node':
if (!s.nodes.some((x) => x.id === op.id)) break
case 'update_node': {
const target = s.nodes.find((x) => x.id === op.id)
if (!target) break
// 按字段合并,和后端 merge_node_config 同一套规则:没写的保留、写 null 删键、
// 协作成员按 name 合并。整体替换的话,模型只改一句提示词,工具就跟着没了——
// 流到一半断掉时,重做栈里的半成品就是那个没有工具的样子
const patch = op.config && typeof op.config === 'object' && !Array.isArray(op.config) ? op.config : null
set({
nodes: s.nodes.map((x) =>
x.id === op.id
? { ...x, data: { ...x.data,
...(op.label != null ? { label: op.label } : {}),
...(op.config != null ? { config: op.config } : {}) } }
...(patch ? { config: mergeNodeConfig(x.data.nodeType, x.data.config ?? {}, patch) } : {}) } }
: x),
copilotNew: s.copilotNew.includes(op.id) ? s.copilotNew : [...s.copilotNew, op.id],
copilotCursor: op.id,
copilot: { ...s.copilot, lastOp: `修改节点:${op.label || op.id}` },
copilot: { ...s.copilot, lastOp: `修改节点:${op.label || target.data.label || op.id}` },
dirty: true,
})
break
}
case 'remove_node':
set({
nodes: s.nodes.filter((x) => x.id !== op.id),
@@ -1709,7 +1798,10 @@ export const useStudio = create<StudioState>((set, get) => ({
}
})
const diff = diffGraphs(before, { nodes, edges: next.edges })
const issues = withDropped(op.issues)
// 上面记录时已经补齐:认不出的类型并进了 issues,老后端缺的 tool_changes 由前端比对
const issues: CopilotIssue[] = op.issues
const toolChanges: ToolChange[] = op.tool_changes
const toolWarnings = dedupeIssues([...toolDrops, ...issues.filter((i) => i.code === 'tools_dropped')])
const explanation = op.explanation ?? get().copilot.explanation
const outcome = diff.total ? 'applied' : 'unchanged'
if (!diff.total) {
@@ -1740,7 +1832,7 @@ export const useStudio = create<StudioState>((set, get) => ({
})
// 落定之后再取景:取景时节点还在半路的话,镜头对着的是它们出发的地方
if (moving) glide(set, get, targets, () => { if (refit) set({ fitRequest: get().fitRequest + 1 }) })
settle({ phase: 'done', outcome, diff, issues, explanation })
settle({ phase: 'done', outcome, diff, issues, explanation, toolChanges, toolWarnings })
finish({ explanation, error: '' })
recordCanvasTurn(get().copilotConversationId, instruction, {
graph: op.graph, explanation: explanation ?? '', status: 'done',
@@ -1754,12 +1846,25 @@ export const useStudio = create<StudioState>((set, get) => ({
const turn = get().copilotTurns.find((t) => t.id === turnId)
const missing = issues.filter((i) => i.code === 'unknown_node_type').length
const left = turn?.check?.status === 'failed' ? turn.check.issues.length : 0
// 工具绑定变了画布上看不出来,回执里逐条写明前后。变少了用 warn 色:指令里
// 没让删的(后端 tools_dropped)常驻到人看过为止——没工具的 agent 照样能跑,
// 只是跑出来的是模型「假设」查过库的答案
const shrunk = shrunkTools(toolChanges)
const unasked = shrunk.length > 0 && toolWarnings.length > 0
const head = left ? `已放到画布,但还有 ${left} 处问题要你处理`
: missing ? `已应用 ${diff.total} 处改动,但有 ${missing} 步没放上`
: `已应用 ${diff.total} 处改动`
const lines = shrunk.length
? [unasked ? '工具绑定变少了,这一轮没让删,确认一下是不是改漏了:' : '工具绑定变少了:',
...shrunk.map(describeToolChange)]
: []
toast(
left ? `已放到画布,但还有 ${left} 处问题要你处理`
: missing ? `已应用 ${diff.total} 处改动,但有 ${missing} 步没放上`
: `已应用 ${diff.total} 处改动`,
left || missing ? 'warn' : 'ok',
{ key: `copilot:${turnId}`, duration: 8000,
[toolChanges.length && !shrunk.length ? `${head} · 工具绑定变了 ${toolChanges.length} 处` : head,
...lines].join('\n'),
left || missing || shrunk.length ? 'warn' : 'ok',
{ key: `copilot:${turnId}`, duration: 8000, sticky: unasked,
...(toolChanges.length > shrunk.length
? { detail: toolChanges.map(describeToolChange).join('\n') } : {}),
action: { label: '撤销', onClick: () => { get().undoCopilotTurn(turnId) } } },
)
}
@@ -1771,7 +1876,10 @@ export const useStudio = create<StudioState>((set, get) => ({
const message = op.message ?? '生成失败'
const outcome = revert()
settle({ phase: 'error', error: message, outcome })
finish({ explanation: '', error: message })
// 「怎么办」和原始报错一起留下:Composer 的错误条和问数据页一样摊开它们
finish({ explanation: '', error: message,
errorHint: typeof op.hint === 'string' ? op.hint : '',
errorDetail: typeof op.detail === 'string' ? op.detail : '' })
recordCanvasTurn(get().copilotConversationId, instruction, { status: 'error', error: message }, set)
break
}
@@ -1808,6 +1916,7 @@ export const useStudio = create<StudioState>((set, get) => ({
},
}
set({ cancelCopilot: stop })
return true
},
stopCopilot: () => {
@@ -1879,6 +1988,11 @@ export const useStudio = create<StudioState>((set, get) => ({
const s = get()
const turn = s.copilotTurns.find((t) => t.id === turnId)
const top = s.past[s.past.length - 1]
// 正式运行期间 undo 会被锁拦下、画布不动:不能照样把这一轮标成「已撤回」
if (formalRunning(s)) {
toast.warn(EDIT_LOCK_TEXT.formal, { key: 'studio:readonly' })
return false
}
if (!turn?.checkpoint || !top || top.id !== turn.checkpoint || s.copilot.active) {
toast.warn(`这一轮之后画布又改过了,不能单独撤掉它。用 ${formatShortcut('Mod+Z')} 逐步撤回,或者在版本历史里找回`)
return false