mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-25 15:22:33 +00:00
第三波前两批:六个「看着成功其实没干活」的平台漏洞堵上,记录页能回放,管理页与画布收尾
起因是一次探索运行: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:
@@ -36,6 +36,8 @@ export const NETWORK_ERROR: Omit<HumanError, 'raw'> = {
|
||||
/** Python 异常类名前缀:「KeyError: 'x'」「sqlalchemy.exc.OperationalError: …」 */
|
||||
const PY_EXC_RE = /^(?:[a-z_][\w.]*\.)?([A-Z]\w*(?:Error|Exception|Exit|Timeout))\s*:\s*/
|
||||
|
||||
const CJK_RE = /[一-鿿]/
|
||||
|
||||
/**
|
||||
* network=false 用在「后端已经回了话」的文本上:那里面提到 fetch failed、
|
||||
* ECONNREFUSED,说的是后端够不着的下游(模型、数据库、MCP),不是我们连不上后端。
|
||||
@@ -65,7 +67,9 @@ function fromText(text: string, { network = true }: { network?: boolean } = {}):
|
||||
raw,
|
||||
}
|
||||
}
|
||||
if (/timed? ?out|timeout|超时/i.test(raw) && raw.length < 200) {
|
||||
// 只接英文原文(「ReadTimeout: timed out」)。带中文的已经是后端写好的人话,
|
||||
// 标题、原因、怎么办都在句子里:再套一个「操作超时」,标题和原因就说了两遍
|
||||
if (!CJK_RE.test(raw) && /timed? ?out|timeout/i.test(raw) && raw.length < 200) {
|
||||
return { title: '操作超时', reason: raw.replace(PY_EXC_RE, ''), action: '稍后重试;反复超时就调大超时或检查下游服务。', raw }
|
||||
}
|
||||
// 类名前缀去掉,剩下的才是给人看的;类名留在 raw 里
|
||||
|
||||
@@ -0,0 +1,301 @@
|
||||
/**
|
||||
* 失败运行的「为什么 + 怎么办」。
|
||||
*
|
||||
* 新后端的 run.error 已经是人话(后端 app/core/errors.py),但库里大量老运行留的是原始
|
||||
* 异常:「NodeError: AnthropicModelNotFoundError: Error code: 404 - {…}」「_make_
|
||||
* query_tool.<locals>._run() got an unexpected keyword argument」。排错的人要的是
|
||||
* 哪个节点、为什么、下一步点哪里,所以这里按库里真实出现过的失败归类,并说清
|
||||
* 「接着跑」有没有用——输入缺了、人驳回了,原样接着跑只会再失败一次,那就不给
|
||||
* 这个按钮。
|
||||
*
|
||||
* 归类之外的一律交给 lib/errors 的 humanizeError(去掉异常类名、拆标题和原因)。
|
||||
*
|
||||
* 记录页的失败横幅、列表行,助手流的报错行、失败的步骤,问数据页的失败轮次都读
|
||||
* 这一份:同一次失败在三处说法不一,人就不知道该信哪句、该点哪个按钮。
|
||||
*/
|
||||
|
||||
import { humanizeError } from './errors'
|
||||
|
||||
export type FixKind = 'settings' | 'canvas' | 'rerun' | 'tools'
|
||||
|
||||
export interface RunErrorExplain {
|
||||
title: string
|
||||
reason?: string
|
||||
action?: string
|
||||
/** 原样接着跑有没有可能过 */
|
||||
continuable: boolean
|
||||
/** 除了接着跑,最该去的地方 */
|
||||
fix?: FixKind
|
||||
/** fix 为 rerun 时缺的是哪一项输入:补上它就能重新发起 */
|
||||
missingInput?: string
|
||||
/** 原文,放进「技术细节」 */
|
||||
raw: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 状态码只在明说是 HTTP 的地方才算数:「Error code: 401」「HTTP 502」「(429)」。
|
||||
* 裸的三位数会误伤「查询结果超过 500 行上限」这种业务报错
|
||||
*/
|
||||
const http = (code: string) =>
|
||||
String.raw`(?:Error code|status(?: code)?|HTTP(?:/[\d.]+)?)\s*[:=]?\s*${code}\b|[((]${code}[))]`
|
||||
const AUTH = new RegExp(`${http('40[13]')}|authentication|unauthori[sz]ed|invalid[_ ]api[_ ]key|鉴权`, 'i')
|
||||
const RATE = new RegExp(`${http('429')}|rate.?limit|quota|额度|太频繁`, 'i')
|
||||
const MISSING_MODEL = new RegExp(`model ?not ?found|not_found_error|模型不存在|(?:${http('404')}).*model`, 'i')
|
||||
const SERVER = new RegExp(
|
||||
`${http(String.raw`5\d\d`)}|对方服务出错|Internal Server Error|Bad Gateway|Service Unavailable|Gateway Time-?out|overloaded`, 'i')
|
||||
|
||||
/** 「NodeError: AnthropicModelNotFoundError: …」这种套了几层的类名前缀全剥掉 */
|
||||
const CLASS_PREFIX = /^\s*(?:[a-z_][\w.]*\.)?[A-Z]\w*(?:Error|Exception|Exit|Timeout)\s*:\s*/
|
||||
|
||||
export function stripClassPrefix(text: string): string {
|
||||
let s = text
|
||||
for (let i = 0; i < 4 && CLASS_PREFIX.test(s); i++) s = s.replace(CLASS_PREFIX, '')
|
||||
return s.trim()
|
||||
}
|
||||
|
||||
export function explainRunError(error: string | null | undefined, detail?: string | null): RunErrorExplain {
|
||||
const raw = [error, detail && detail !== error ? detail : null].filter(Boolean).join('\n\n')
|
||||
const text = String(error ?? '').trim()
|
||||
const plain = stripClassPrefix(text)
|
||||
|
||||
if (!text) {
|
||||
return { title: '运行失败,但没有留下原因', action: '打开「原始事件」看最后几条记录。', continuable: true, raw }
|
||||
}
|
||||
// 下面四类是「图本身有缺口」:模型没真调工具、团队轮数用完、校验修复想凑数、
|
||||
// 提示词点名的工具没绑定。原样接着跑是同一份配置,只会再来一遍,所以都不给
|
||||
// 「接着跑」,指到画布上去改
|
||||
if (/没有真正调用工具|工具调用的原始标记|tool_markup_leak/.test(text)) {
|
||||
return {
|
||||
title: '模型没有真正调用工具',
|
||||
reason: '它把工具调用当成文字写了出来,这一步一次都没查到数据。常见原因是节点没有绑定工具,或者模型、服务不支持工具调用。',
|
||||
action: '到画布里确认这个节点绑定了要用的工具;绑定了还这样,就换一个支持工具调用的模型。改完再运行。',
|
||||
continuable: false,
|
||||
fix: 'canvas',
|
||||
raw,
|
||||
}
|
||||
}
|
||||
const exhausted = plain.match(/用完\s*(\d+)\s*轮(?:仍|还)?未完成[::]?\s*(.*)/s)
|
||||
if (exhausted || /team_exhausted/.test(text)) {
|
||||
return {
|
||||
title: exhausted ? `协作团队用完 ${exhausted[1]} 轮仍未完成` : '协作团队用完了轮数仍未完成',
|
||||
reason: exhausted?.[2]?.trim() || '调度者一直没有判定完成,成员的原话不能当作结论交出去。',
|
||||
action: '到画布里看看成员有没有绑定要用的工具,再调大这个团队的最多轮数;也可以把「用完轮数时」改成降档交付。',
|
||||
continuable: false,
|
||||
fix: 'canvas',
|
||||
raw,
|
||||
}
|
||||
}
|
||||
if (/原文没有的值|修复.*编造/.test(text)) {
|
||||
const values = plain.match(/原文没有的值[::]\s*([^\n。]+)/)?.[1]?.trim()
|
||||
return {
|
||||
title: '校验修复被拒绝:修复结果里出现了原文没有的值',
|
||||
reason: `上游产出里没有这些数据${values ? `(${values})` : ''},修复不许凑数,这次校验判为失败。`,
|
||||
action: '先看上游节点为什么没拿到数据(常见是没有绑定查询工具),改好后重新运行。',
|
||||
continuable: false,
|
||||
fix: 'canvas',
|
||||
raw,
|
||||
}
|
||||
}
|
||||
// 节点和协作成员两种说法:「…但节点没有绑定它」「成员「X」的…但没有给这个成员绑定它」
|
||||
const unbound = plain.match(/提示词要求用\s*「?([^」,,\s]+?)」?\s*[,,]?\s*但(?:节点)?没有(?:给这个成员)?绑定/)
|
||||
if (unbound) {
|
||||
const member = plain.match(/成员「([^」]+)」的提示词/)?.[1]
|
||||
return {
|
||||
title: member
|
||||
? `成员「${member}」的提示词要求用「${unbound[1]}」,但没有给它绑定`
|
||||
: `提示词要求用「${unbound[1]}」,但节点没有绑定它`,
|
||||
reason: '运行时模型拿不到这个工具,只能编一个结果出来。',
|
||||
action: '到画布里给这个节点绑定该工具,或者改掉提示词里的要求。',
|
||||
continuable: false,
|
||||
fix: 'canvas',
|
||||
raw,
|
||||
}
|
||||
}
|
||||
if (/人工驳回/.test(text)) {
|
||||
return {
|
||||
title: '人工审批驳回,运行终止',
|
||||
reason: plain.replace(/^人工驳回[::]?\s*/, '') || undefined,
|
||||
action: '这是审批人的决定,不是故障。需要的话改好内容后重新发起一次运行。',
|
||||
continuable: false,
|
||||
raw,
|
||||
}
|
||||
}
|
||||
const missing = plain.match(/缺少必填输入[::]\s*([^\s,。,]+)/)
|
||||
if (missing) {
|
||||
return {
|
||||
title: `缺少必填输入「${missing[1]}」`,
|
||||
reason: '发起这次运行时没有填这一项,输入节点直接拦下了。',
|
||||
action: '接着跑还是同一份输入,会再失败一次。补上这一项重新运行,其余输入照旧。',
|
||||
continuable: false,
|
||||
fix: 'rerun',
|
||||
missingInput: missing[1],
|
||||
raw,
|
||||
}
|
||||
}
|
||||
if (AUTH.test(text)) {
|
||||
return {
|
||||
title: '模型鉴权没通过',
|
||||
reason: /invalid_model/i.test(text)
|
||||
? 'key 没有这个模型的权限,或者模型名写错了(401)。'
|
||||
: 'key 无效、过期,或者没有这个模型的权限。',
|
||||
action: '去 设置 → 模型接入 检查 key 和模型名,改好后「接着跑」,前面跑完的节点不会重跑。',
|
||||
continuable: true,
|
||||
fix: 'settings',
|
||||
raw,
|
||||
}
|
||||
}
|
||||
if (MISSING_MODEL.test(text)) {
|
||||
const model = text.match(/model:\s*([\w.:/-]+)/)?.[1]
|
||||
return {
|
||||
title: model ? `模型「${model}」不存在` : '模型不存在',
|
||||
reason: '供应商那边没有这个模型名(404),可能拼错了或已经下线。',
|
||||
action: '在 设置 → 模型接入 换一个可用的模型,或者到画布里改这个节点的模型,再接着跑。',
|
||||
continuable: true,
|
||||
fix: 'settings',
|
||||
raw,
|
||||
}
|
||||
}
|
||||
if (RATE.test(text)) {
|
||||
return {
|
||||
title: '请求太频繁,或额度用完了',
|
||||
reason: '模型供应商限了流(429)。',
|
||||
action: '等一会儿直接接着跑;额度用完就去供应商那边充值或换一个模型。',
|
||||
continuable: true,
|
||||
raw,
|
||||
}
|
||||
}
|
||||
if (/timed? ?out|timeout|超时/i.test(text)) {
|
||||
return {
|
||||
title: '等待超时',
|
||||
reason: '下游服务没在限定时间内响应,多半是暂时的。',
|
||||
action: '直接接着跑;反复超时就到画布里调大这个节点的超时。',
|
||||
continuable: true,
|
||||
raw,
|
||||
}
|
||||
}
|
||||
if (/连不上|Connection ?(?:Error|refused)|ECONNREFUSED/i.test(text)) {
|
||||
return {
|
||||
title: '连不上对方服务',
|
||||
reason: '网络不通,或者数据库、MCP、模型接口没有启动。',
|
||||
action: '确认对方服务起着、地址能通,再接着跑;前面跑完的节点不会重跑。',
|
||||
continuable: true,
|
||||
raw,
|
||||
}
|
||||
}
|
||||
if (SERVER.test(text)) {
|
||||
return {
|
||||
title: '对方服务出错了',
|
||||
reason: '模型或工具那一端返回了服务器错误(5xx),多半是暂时的。',
|
||||
action: '等一会儿直接接着跑。',
|
||||
continuable: true,
|
||||
raw,
|
||||
}
|
||||
}
|
||||
if (/不允许出现 Set|\{\{\s*[\w.]+\s*\}\}.*表达式/.test(text)) {
|
||||
// 后端 expressions 已经把 {{ x }} 当 x 读了:这类老失败原图接着跑就能过,
|
||||
// 不该再让人去改表达式
|
||||
return {
|
||||
title: '条件表达式用了旧写法',
|
||||
reason: '当时的版本不认 {{ x }} 这种写法;现在已经自动兼容。',
|
||||
action: '不用改图,直接接着跑。',
|
||||
continuable: true,
|
||||
raw,
|
||||
}
|
||||
}
|
||||
if (/表达式语法错误|invalid syntax/.test(text)) {
|
||||
return {
|
||||
title: '条件表达式写错了',
|
||||
reason: plain.split(':').slice(1).join(':') || undefined,
|
||||
action: '到画布里改这个节点的条件,改完从画布接着跑。这里接着跑用的还是当时那条写错的条件,会再失败一次。',
|
||||
continuable: false,
|
||||
fix: 'canvas',
|
||||
raw,
|
||||
}
|
||||
}
|
||||
if (/unexpected keyword argument|参数对不上/.test(text)) {
|
||||
const arg = text.match(/argument '(\w+)'|名为「(\w+)」/)
|
||||
return {
|
||||
title: '工具参数对不上',
|
||||
reason: `工具不接受${arg ? `名为「${arg[1] ?? arg[2]}」的` : '传进去的'}参数,多半是旧版本工具的问题。`,
|
||||
action: '先直接接着跑试试;还不行就到画布里检查这个节点的工具配置。',
|
||||
continuable: true,
|
||||
fix: 'canvas',
|
||||
raw,
|
||||
}
|
||||
}
|
||||
if (/找不到工具|tool .*not found/i.test(text)) {
|
||||
const name = text.match(/找不到工具\s*'?"?([\w.-]+)/)
|
||||
return {
|
||||
title: `找不到工具${name ? `「${name[1]}」` : ''}`,
|
||||
reason: '它可能被删了、改了名,或者所在的 MCP 服务没连上。',
|
||||
action: '去工具库确认它还在,或者在画布里给这个节点换一个工具。',
|
||||
continuable: true,
|
||||
fix: 'tools',
|
||||
raw,
|
||||
}
|
||||
}
|
||||
if (/至少要配|没有配置|未配置|必须配置/.test(text)) {
|
||||
return {
|
||||
title: '节点配置不完整',
|
||||
reason: plain,
|
||||
action: '到画布里把这个节点配好。接着跑用的还是当时的配置,会再失败一次;画布里改完配置可以直接接着跑。',
|
||||
continuable: false,
|
||||
fix: 'canvas',
|
||||
raw,
|
||||
}
|
||||
}
|
||||
if (/Can receive only one value per step|InvalidUpdateError/.test(text)) {
|
||||
const key = text.match(/At key '(\w+)'/)?.[1]
|
||||
return {
|
||||
title: `同一拍里有两个节点同时写了${key ? `变量「${key}」` : '同一个变量'}`,
|
||||
reason: '并行的分支在同一步里各自往它写了一个值,执行图不知道该留哪个。',
|
||||
action: '到画布里检查这几条并行分支的汇合:让它们写不同的变量,或者先汇合再写。改了连线要重新运行。',
|
||||
continuable: false,
|
||||
fix: 'canvas',
|
||||
raw,
|
||||
}
|
||||
}
|
||||
if (/unsupported operand|can only concatenate|not supported between/.test(text)) {
|
||||
return {
|
||||
title: '数据类型对不上',
|
||||
reason: stripClassPrefix(plain) || undefined,
|
||||
action: '多半是代码或表达式把两种类型拼在了一起(比如布尔值加字符串)。到画布里检查这个节点;原样接着跑还会再报同样的错。',
|
||||
continuable: false,
|
||||
fix: 'canvas',
|
||||
raw,
|
||||
}
|
||||
}
|
||||
if (/结构化输出失败/.test(text)) {
|
||||
return {
|
||||
title: '结构化输出失败',
|
||||
reason: `模型没能按规定的字段结构回答${/Unsupported function/i.test(text) ? ':这个模型不支持这种输出结构' : ''}。`,
|
||||
action: '到画布里简化这个节点的输出结构(少几层嵌套、少几个字段),或者换一个支持结构化输出的模型。',
|
||||
continuable: false,
|
||||
fix: 'canvas',
|
||||
raw,
|
||||
}
|
||||
}
|
||||
if (/exceeds 64-bit|OverflowError|too large to convert/i.test(text)) {
|
||||
return {
|
||||
title: '数字太大,超出了整数的范围',
|
||||
reason: '某个节点产出的整数在写库或传给下游时溢出了(64 位)。',
|
||||
action: '常见于把 ID、时间戳当数字来算。到画布里检查产出这个数的节点,改成字符串后重新运行。',
|
||||
continuable: false,
|
||||
fix: 'canvas',
|
||||
raw,
|
||||
}
|
||||
}
|
||||
if (/服务重启/.test(text)) {
|
||||
return {
|
||||
title: '服务重启打断了这次运行',
|
||||
reason: plain,
|
||||
action: '断点还在,接着跑即可;前面跑完的节点不会重跑。',
|
||||
continuable: true,
|
||||
raw,
|
||||
}
|
||||
}
|
||||
// 兜底:句中还夹着的异常类名(「结构化输出失败:ValueError: …」)也去掉
|
||||
const h = humanizeError(plain)
|
||||
const scrub = (v?: string) => v?.replace(/\b[A-Z][A-Za-z]*(?:Error|Exception)\s*:\s*/g, '')
|
||||
return { title: scrub(h.title) ?? h.title, reason: scrub(h.reason), action: h.action, continuable: true, raw: raw || h.raw || text }
|
||||
}
|
||||
@@ -170,6 +170,18 @@ export function formatRelative(v: string | number | Date | null | undefined, now
|
||||
return formatTime(d, now)
|
||||
}
|
||||
|
||||
/** 文件大小:「820 B」「12.4 KB」「3.1 MB」「1.2 GB」 */
|
||||
export function formatBytes(n: number | null | undefined): string {
|
||||
if (!isNum(n) || n < 0) return NONE
|
||||
if (n < 1024) return `${Math.round(n)} B`
|
||||
if (n < 1024 ** 2) return `${(n / 1024).toFixed(1)} KB`
|
||||
if (n < 1024 ** 3) return `${(n / 1024 ** 2).toFixed(1)} MB`
|
||||
return `${(n / 1024 ** 3).toFixed(1)} GB`
|
||||
}
|
||||
|
||||
/** 去掉名字后面括号里的补充说明:「OpenAI 兼容(DeepSeek、通义…)」→「OpenAI 兼容」 */
|
||||
export const shortLabel = (label?: string | null): string => (label ?? '').replace(/[((].*$/, '').trim()
|
||||
|
||||
/** 短 id:「#66a5a6」。完整 id 放 title,点击复制由调用方决定 */
|
||||
export function shortId(id: string | null | undefined, len = 6): string {
|
||||
if (!id) return NONE
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
import { useSyncExternalStore } from 'react'
|
||||
import { toast } from '../components/ui'
|
||||
import type { ServerHealth } from '../types'
|
||||
import { humanizeError } from './errors'
|
||||
import { parseServerTime } from './format'
|
||||
|
||||
/**
|
||||
* 连没连上:统一、持久的状态。
|
||||
*
|
||||
* 一次「测连接」的结果按 `种类:id` 存:模型接入 provider:<id>、数据源
|
||||
* datasource:<id>、MCP mcp:<id>。
|
||||
*
|
||||
* 以前测完只弹 4 秒 toast,结果存在组件 state 里,切个标签就没了;卡片上的圆点
|
||||
* 又各说各的(模型卡的绿点其实是「启用」)。管理页最核心的问题是「现在能不能
|
||||
* 用」,答案得留在对象上,并注明是什么时候测的。
|
||||
*
|
||||
* 模块级而不是组件 state:切标签、换页都还在。再写一份到 localStorage,刷新
|
||||
* 也还在——只是这台浏览器的缓存,所以一律带上「几分钟前测的」。后端也记着上次
|
||||
* 的结果时(列表接口里的 last_check_*),用 healthFromServer 取出来当初值,
|
||||
* useHealth 取两边较新的那份。
|
||||
*/
|
||||
export interface HealthRecord {
|
||||
ok: boolean
|
||||
/** 往返毫秒 */
|
||||
ms?: number | null
|
||||
/** 测的时刻(ms)。0 = 知道结果、不知道是什么时候测的 */
|
||||
at: number
|
||||
error?: string
|
||||
hint?: string
|
||||
detail?: string
|
||||
/** 成功时的补充:用的哪个模型、回了什么 */
|
||||
note?: string
|
||||
}
|
||||
|
||||
const HEALTH_KEY = 'agentlab.health'
|
||||
|
||||
/**
|
||||
* 后端记着的上次结果(列表接口里平铺的 last_check_* 四个字段)→ HealthRecord。
|
||||
* 没测过、或者连接配置改过之后后端给的全是 null,这里返回 undefined。
|
||||
* 测的时刻解析不出来时 at 为 0:知道结果,不写「几分钟前测」
|
||||
*/
|
||||
export function healthFromServer(o: ServerHealth | null | undefined): HealthRecord | undefined {
|
||||
if (!o || typeof o.last_check_ok !== 'boolean') return undefined
|
||||
return {
|
||||
ok: o.last_check_ok,
|
||||
ms: o.last_latency_ms ?? null,
|
||||
at: parseServerTime(o.last_checked_at)?.getTime() ?? 0,
|
||||
...(o.last_error ? { error: o.last_error } : {}),
|
||||
}
|
||||
}
|
||||
|
||||
function readHealth(): Record<string, HealthRecord> {
|
||||
try {
|
||||
const raw = JSON.parse(localStorage.getItem(HEALTH_KEY) ?? '{}')
|
||||
return raw && typeof raw === 'object' ? raw : {}
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
let healthSnap: { records: Record<string, HealthRecord>; checking: Record<string, number> } = {
|
||||
records: readHealth(), checking: {},
|
||||
}
|
||||
const healthListeners = new Set<() => void>()
|
||||
const subscribeHealth = (l: () => void) => {
|
||||
healthListeners.add(l)
|
||||
return () => { healthListeners.delete(l) }
|
||||
}
|
||||
function emitHealth(next: Partial<typeof healthSnap>, persist = false) {
|
||||
healthSnap = { ...healthSnap, ...next }
|
||||
if (persist) {
|
||||
try { localStorage.setItem(HEALTH_KEY, JSON.stringify(healthSnap.records)) } catch { /* 隐私模式:只是刷新后不记得 */ }
|
||||
}
|
||||
healthListeners.forEach((l) => l())
|
||||
}
|
||||
|
||||
/**
|
||||
* 某个对象最近一次的测连接结果,以及是不是正在测。
|
||||
*
|
||||
* server 是后端记着的那份(healthFromServer 的结果):换了台浏览器、清了缓存也
|
||||
* 还在。两份都有时取测得晚的那份——本机刚测过的比后端上次记的新。
|
||||
*/
|
||||
export function useHealth(key: string, server?: HealthRecord | null): { record?: HealthRecord; checkingSince?: number } {
|
||||
const snap = useSyncExternalStore(subscribeHealth, () => healthSnap, () => healthSnap)
|
||||
const local = snap.records[key]
|
||||
const record = !server ? local : !local ? server : server.at > local.at ? server : local
|
||||
return { record, checkingSince: snap.checking[key] }
|
||||
}
|
||||
|
||||
export function setHealth(key: string, record: HealthRecord) {
|
||||
emitHealth({ records: { ...healthSnap.records, [key]: record } }, true)
|
||||
}
|
||||
|
||||
export function forgetHealth(key: string) {
|
||||
const { [key]: _gone, ...rest } = healthSnap.records
|
||||
emitHealth({ records: rest }, true)
|
||||
}
|
||||
|
||||
/**
|
||||
* 测一次并记下结果。run 返回后端的 {ok, error, hint, detail};ms 和 note 由调用方
|
||||
* 从各自的字段里取(latency_ms / elapsed_ms)。
|
||||
*
|
||||
* 后端本身够不着时不记:那说的是「我们连不上后端」,不是这个库或模型坏了,
|
||||
* 记成它的失败就是冤枉它。只弹 toast。
|
||||
*/
|
||||
export async function checkHealth(
|
||||
key: string,
|
||||
run: () => Promise<Omit<HealthRecord, 'at'>>,
|
||||
): Promise<HealthRecord | null> {
|
||||
if (healthSnap.checking[key]) return null
|
||||
emitHealth({ checking: { ...healthSnap.checking, [key]: Date.now() } })
|
||||
let record: HealthRecord | null = null
|
||||
try {
|
||||
record = { ...(await run()), at: Date.now() }
|
||||
} catch (e) {
|
||||
const h = humanizeError(e)
|
||||
if (h.kind === 'network') {
|
||||
toast.error(e)
|
||||
} else {
|
||||
record = {
|
||||
ok: false, at: Date.now(),
|
||||
error: h.reason ? `${h.title}:${h.reason}` : h.title, hint: h.action, detail: h.raw,
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
const { [key]: _done, ...checking } = healthSnap.checking
|
||||
emitHealth({
|
||||
checking,
|
||||
...(record ? { records: { ...healthSnap.records, [key]: record } } : {}),
|
||||
}, !!record)
|
||||
}
|
||||
return record
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
/**
|
||||
* 离开前确认:页面有没保存的改动时登记一道守卫,站内的每一次换页都先经过它——
|
||||
* 左侧导航、页面里的链接、⌘K、⌥ 数字、浏览器前进后退、代码里的 navigate()——
|
||||
* 关页和刷新也会让浏览器问一句。
|
||||
*
|
||||
* 以前设置页自己在捕获阶段拦 <a> 的点击:⌘K 和快捷键直接调 navigate(),浏览器
|
||||
* 后退也不走 <a>,改到一半的表单照样丢。路由换成 data router 之后,react-router 的
|
||||
* useBlocker 拦得住所有换页;但一个 router 同时只认一个 blocker,所以由外壳挂唯一
|
||||
* 那一个(useLeaveBlocker),页面只往这里登记,别自己调 useBlocker。
|
||||
*
|
||||
* useLeaveGuard(dirty > 0, () => confirmDialog({ title: `有 ${dirty} 项设置还没保存`, … }))
|
||||
*/
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { NavigationType, parsePath, useBlocker } from 'react-router-dom'
|
||||
import type { BlockerFunction, NavigateOptions, Path } from 'react-router-dom'
|
||||
|
||||
export interface LeaveGuard {
|
||||
/**
|
||||
* 这一次换页要不要拦。next 为 null 表示去向还没定(canLeave() 不带目标时)。
|
||||
* 默认:路径变了就拦;只改 ?query 或 #hash 不算,同一页里换个筛选不会丢表单
|
||||
*/
|
||||
blocks?: (next: Path | null, current: Path) => boolean
|
||||
/** 拦下之后怎么问:true 放行,false 留下。抛错按留下算 */
|
||||
confirm: (next: Path | null) => Promise<boolean>
|
||||
/** 关页、刷新时要不要让浏览器问一句,默认要。浏览器只给通用文案,写不了自己的话 */
|
||||
unload?: boolean
|
||||
}
|
||||
|
||||
const guards = new Set<LeaveGuard>()
|
||||
|
||||
const pathChanged = (next: Path | null, current: Path) => next == null || next.pathname !== current.pathname
|
||||
|
||||
function blocking(next: Path | null, current: Path): LeaveGuard[] {
|
||||
return [...guards].filter((g) => {
|
||||
try {
|
||||
return (g.blocks ?? pathChanged)(next, current)
|
||||
} catch {
|
||||
return true
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const onBeforeUnload = (e: BeforeUnloadEvent) => {
|
||||
e.preventDefault()
|
||||
e.returnValue = ''
|
||||
}
|
||||
let unloadOn = false
|
||||
|
||||
/** 只在有守卫时挂 beforeunload:常驻的监听会让浏览器的往返缓存失效 */
|
||||
function syncUnload() {
|
||||
const want = [...guards].some((g) => g.unload !== false)
|
||||
if (want === unloadOn || typeof window === 'undefined') return
|
||||
unloadOn = want
|
||||
if (want) window.addEventListener('beforeunload', onBeforeUnload)
|
||||
else window.removeEventListener('beforeunload', onBeforeUnload)
|
||||
}
|
||||
|
||||
/** 登记一道守卫,返回撤销函数。组件里用 useLeaveGuard,它管登记和撤销的时机 */
|
||||
export function registerLeaveGuard(guard: LeaveGuard): () => void {
|
||||
guards.add(guard)
|
||||
syncUnload()
|
||||
return () => {
|
||||
guards.delete(guard)
|
||||
syncUnload()
|
||||
}
|
||||
}
|
||||
|
||||
/** 一道一道地问:同时弹两个确认框,人不知道先答哪个。有一道说留下就留下 */
|
||||
async function ask(list: LeaveGuard[], next: Path | null): Promise<boolean> {
|
||||
for (const g of list) {
|
||||
let ok = false
|
||||
try {
|
||||
ok = await g.confirm(next)
|
||||
} catch {
|
||||
ok = false
|
||||
}
|
||||
if (!ok) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
const here = (): Path => ({ pathname: location.pathname, search: location.search, hash: location.hash })
|
||||
|
||||
/**
|
||||
* 有没保存的改动时拦住离开。active 为 false 时什么都不登记。
|
||||
* confirm、blocks 每次渲染取最新的,不必包 useCallback。
|
||||
*/
|
||||
export function useLeaveGuard(
|
||||
active: boolean,
|
||||
confirm: (next: Path | null) => Promise<boolean>,
|
||||
opts?: Pick<LeaveGuard, 'blocks' | 'unload'>,
|
||||
): void {
|
||||
const latest = useRef({ confirm, blocks: opts?.blocks })
|
||||
latest.current = { confirm, blocks: opts?.blocks }
|
||||
const unload = opts?.unload
|
||||
useEffect(() => {
|
||||
if (!active) return
|
||||
return registerLeaveGuard({
|
||||
confirm: (next) => latest.current.confirm(next),
|
||||
blocks: (next, current) => (latest.current.blocks ?? pathChanged)(next, current),
|
||||
unload,
|
||||
})
|
||||
}, [active, unload])
|
||||
}
|
||||
|
||||
/**
|
||||
* 先问、再做。「新对话」「新建工作流」要先建出东西、建完才跳:等到跳的时候才问,
|
||||
* 人点了「留下」,东西已经建出来了。所以先问一遍;问过之后的那次跳转带上
|
||||
* leavePass(),不再问第二遍。没有拦着的守卫就直接是 true。
|
||||
* to 省略表示去向还没定:只要有守卫在就问。
|
||||
*/
|
||||
export function canLeave(to?: string): Promise<boolean> {
|
||||
const next = to == null ? null : { pathname: '/', search: '', hash: '', ...parsePath(to) }
|
||||
const list = blocking(next, here())
|
||||
return list.length ? ask(list, next) : Promise.resolve(true)
|
||||
}
|
||||
|
||||
const PASS = '__leaveConfirmed'
|
||||
|
||||
/** 给 canLeave() 问过的那一次跳转放行:navigate(to, leavePass(opts)) */
|
||||
export function leavePass<T extends NavigateOptions>(opts?: T): T {
|
||||
const state = opts?.state && typeof opts.state === 'object' ? opts.state : {}
|
||||
return { ...opts, state: { ...state, [PASS]: true } } as T
|
||||
}
|
||||
|
||||
/** 拦下时那几道守卫:问的时候就问它们,不再重新挑(后退时地址已经变过一次了) */
|
||||
let held: LeaveGuard[] = []
|
||||
|
||||
const shouldBlock: BlockerFunction = ({ currentLocation, nextLocation, historyAction }) => {
|
||||
// 后退前进不认通行证:它存在历史记录的 state 里,退回那一条时还在
|
||||
if (historyAction !== NavigationType.Pop && (nextLocation.state as Record<string, unknown> | null)?.[PASS]) return false
|
||||
held = blocking(nextLocation, currentLocation)
|
||||
return held.length > 0
|
||||
}
|
||||
|
||||
/**
|
||||
* 外壳挂一次(App 里)。一个 router 同时只认一个 blocker:页面别自己调 useBlocker,
|
||||
* 用 useLeaveGuard 登记。
|
||||
*/
|
||||
export function useLeaveBlocker(): void {
|
||||
const blocker = useBlocker(shouldBlock)
|
||||
const latest = useRef(blocker)
|
||||
latest.current = blocker
|
||||
// 正在问的是哪一次:StrictMode 下 effect 会跑两遍,同一次别问两回
|
||||
const asking = useRef<string | null>(null)
|
||||
useEffect(() => {
|
||||
if (blocker.state !== 'blocked') {
|
||||
asking.current = null
|
||||
return
|
||||
}
|
||||
const key = blocker.location.key
|
||||
if (asking.current === key) return
|
||||
asking.current = key
|
||||
void ask(held, blocker.location).then((ok) => {
|
||||
const b = latest.current
|
||||
// 问的时候人又点了别处(比如又按了后退),这一问就作废,归新的那次
|
||||
if (b.state !== 'blocked' || b.location.key !== key) return
|
||||
if (ok) b.proceed()
|
||||
else b.reset()
|
||||
})
|
||||
}, [blocker])
|
||||
}
|
||||
|
||||
// 开发期挂到 window 上,好让 check-shell 登记一道测试守卫,看各条换页的路都拦得住。
|
||||
// 生产构建里去掉
|
||||
if (import.meta.env.DEV && typeof window !== 'undefined') {
|
||||
;(window as any).__leave = { register: registerLeaveGuard, count: () => guards.size }
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { Workflow } from '../types'
|
||||
|
||||
/**
|
||||
* 图里引用了这些名字(工具名、模型 id)的工作流。按 JSON 里的整串值匹配,不做子串:
|
||||
* 删一个叫 db_query 的工具,不该把只用了 db_query__shop 的工作流也算进来。
|
||||
* 删除、停用之前先说清会波及谁。
|
||||
*/
|
||||
export function workflowsMentioning(workflows: Workflow[], tokens: string[]): Workflow[] {
|
||||
const needles = tokens.filter(Boolean).map((t) => JSON.stringify(t))
|
||||
if (!needles.length) return []
|
||||
return workflows.filter((w) => {
|
||||
const text = JSON.stringify(w.graph ?? {})
|
||||
return needles.some((n) => text.includes(n))
|
||||
})
|
||||
}
|
||||
|
||||
/** 「3 个工作流(「周报」「巡检」 等)」 */
|
||||
export function workflowList(list: Workflow[], max = 3): string {
|
||||
const names = list.slice(0, max).map((w) => `「${w.name}」`).join('')
|
||||
return `${list.length} 个工作流(${names}${list.length > max ? ' 等' : ''})`
|
||||
}
|
||||
Reference in New Issue
Block a user