mirror of
https://github.com/ThearchyHelios/AgentLab.git
synced 2026-11-19 09:32:01 +00:00
界面与交互全面翻修(前两波):运行态有了 HUD 和时间轴,终态会收尾,全站令牌、组件、文案统一
来自 2026-09 的 UI/UX 审查(142 条)。本提交是前两波,第三波(记录页接入时间轴、跨页互链、check-ui 更新、全站扫尾)另行提交。 地基 - 设计令牌:全局规则和 .btn/.field/.chip 放进 CSS 层,Tailwind 工具类重新生效,选中态、开启态不再被吞掉;字号阶梯; 辅助文字在所有底色上 >= 4.5:1;状态色专用,节点类型色与之拉开色相;「跟随系统」真的跟随,首帧不闪深色;新字标与 favicon - 基础组件:confirmDialog / promptDialog 取代原生对话框;toast 出错不自动消失、可复制、读屏可播报;离线横幅与断线恢复; 九种剪影的状态徽标;唯一一份状态文案(lib/status)、格式化(lib/format)、术语(lib/terms)、报错人话(lib/errors) - 运行态内核:事件折成航迹(run/trace.ts),可投影到任意时刻;取消 / 失败 / 服务重启后统一收尾,不再永远转圈; run.status 随事件回写;token 事件不再堆进 events - 后端:协作成员逐个完成即发事件,调度者决策有事件;时长分执行 / 墙钟 / 等人;API 时间带时区; 中断的运行也发 stream.end;运行列表可筛选翻页;删除运行 / 工作流有保护;运行默认值接通;可测未保存的配置; 报错说清发生了什么、为什么、怎么办 功能 - 画布:状态四重编码、固定高度遥测槽、按缩放三档、运行胶囊与 HUD、航迹时间轴与回放、执行轨迹边、 等待闸门、跟随执行、正式运行只读、一次性时刻(开场点亮、回扫、阻断级联、出具印章) - 编辑:撤销重做、版本历史、问题面板可定位、三栏可收起、模板与表达式字段区分、变量血缘、快捷键、带搜索的选择器 - 回答流 / 问数据:贴底才跟随滚动、工件下钻、出具横幅列出缺口、答案可复制导出、按会话的忙闲、 答案不再在 2000 字处截断、重启后这一轮会收尾 - 记录页:待审批 / 运行中 / 失败页签、筛选翻页、实时接流、排错路径指到节点、封存凭证常驻 - 管理页:新的「数据」页、写操作失败都有反馈、弹窗里先测连接、统一持久的连接状态 - 外壳:导航改版、⌘K 命令面板、? 快捷键帮助、404、页面标题与 favicon 状态点、后台提醒 验证(沙箱):tsc 干净,pytest 579 passed,14 个检查脚本中 13 个全绿;check-ui 剩 1 项旧断言(按旧日期格式找运行行),第三波更新。
This commit is contained in:
@@ -0,0 +1,165 @@
|
||||
/**
|
||||
* 把各种报错翻成人话:发生了什么(title)、为什么(reason)、怎么办(action)。
|
||||
*
|
||||
* 项目一贯要求「错误要能照着做」,但最常见的「后端没起或正在重启」反而是最难懂
|
||||
* 的一句:fetch 抛出的 TypeError 原样透出成「Failed to fetch」,沙箱没回
|
||||
* exit_code 时拼出「exit undefined」,问数据页直接露出 pydantic 原文。
|
||||
*
|
||||
* 原文不丢:raw 放进「技术细节」折叠区,给运维复制用。
|
||||
*/
|
||||
|
||||
import { ApiError } from '../api/client'
|
||||
|
||||
export interface HumanError {
|
||||
/** 一句人话:发生了什么 */
|
||||
title: string
|
||||
/** 为什么(知道时才有) */
|
||||
reason?: string
|
||||
/** 怎么办(知道时才有) */
|
||||
action?: string
|
||||
/** 原始报错文本,放进「技术细节」 */
|
||||
raw?: string
|
||||
/** network:连不上;http:后端回了错误;client:前端自己的错;unknown:说不清 */
|
||||
kind: 'network' | 'http' | 'client' | 'unknown'
|
||||
status?: number
|
||||
}
|
||||
|
||||
const NETWORK_RE = /failed to fetch|networkerror|network request failed|load failed|err_connection|econnrefused|fetch failed/i
|
||||
|
||||
export const NETWORK_ERROR: Omit<HumanError, 'raw'> = {
|
||||
title: '连不上后端服务',
|
||||
reason: '后端可能没启动、正在重启,或者中间的代理断了。',
|
||||
action: '稍等几秒会自动重试;一直连不上就检查后端进程和 /api 代理。',
|
||||
kind: 'network',
|
||||
}
|
||||
|
||||
/** Python 异常类名前缀:「KeyError: 'x'」「sqlalchemy.exc.OperationalError: …」 */
|
||||
const PY_EXC_RE = /^(?:[a-z_][\w.]*\.)?([A-Z]\w*(?:Error|Exception|Exit|Timeout))\s*:\s*/
|
||||
|
||||
/**
|
||||
* network=false 用在「后端已经回了话」的文本上:那里面提到 fetch failed、
|
||||
* ECONNREFUSED,说的是后端够不着的下游(模型、数据库、MCP),不是我们连不上后端。
|
||||
*/
|
||||
function fromText(text: string, { network = true }: { network?: boolean } = {}): Omit<HumanError, 'kind'> & { kind?: HumanError['kind'] } {
|
||||
const raw = text.trim()
|
||||
if (!raw) return { title: '出错了,但没有给出原因', raw }
|
||||
if (network && NETWORK_RE.test(raw)) return { ...NETWORK_ERROR, raw }
|
||||
if (/exit (?:code )?undefined|exit_code.*none/i.test(raw)) {
|
||||
return { title: '请求没到沙箱', reason: '沙箱没有返回退出码,可能没启动或者中途被中断。', action: '看一眼设置里的沙箱状态,再重试。', raw }
|
||||
}
|
||||
// pydantic:「2 validation errors for GraphSpec\nnodes.1.type\n Input should be …」
|
||||
const pyd = raw.match(/(\d+) validation errors? for (\w+)/)
|
||||
if (pyd) {
|
||||
if (/nodes\.\d+\.type/.test(raw)) {
|
||||
return {
|
||||
title: '生成的工作流里有节点类型不认识',
|
||||
reason: `模型写了一个不存在的节点类型,${pyd[1]} 处没通过格式校验。`,
|
||||
action: '换个说法再试一次;反复出现就把技术细节发给维护者。',
|
||||
raw,
|
||||
}
|
||||
}
|
||||
return {
|
||||
title: '数据格式没通过校验',
|
||||
reason: `${pyd[2]} 有 ${pyd[1]} 处不符合要求。`,
|
||||
action: '检查填写的内容;是模型生成的就换个说法重试。',
|
||||
raw,
|
||||
}
|
||||
}
|
||||
if (/timed? ?out|timeout|超时/i.test(raw) && raw.length < 200) {
|
||||
return { title: '操作超时', reason: raw.replace(PY_EXC_RE, ''), action: '稍后重试;反复超时就调大超时或检查下游服务。', raw }
|
||||
}
|
||||
// 类名前缀去掉,剩下的才是给人看的;类名留在 raw 里
|
||||
const stripped = raw.replace(PY_EXC_RE, '')
|
||||
const firstLine = stripped.split('\n')[0]
|
||||
return splitSentence(firstLine, raw)
|
||||
}
|
||||
|
||||
/** 长句拆成「标题。原因」,短句整句当标题 */
|
||||
function splitSentence(text: string, raw: string): Omit<HumanError, 'kind'> {
|
||||
const s = text.trim()
|
||||
if (s.length <= 48) return { title: s, raw: raw !== s ? raw : undefined }
|
||||
const cut = s.search(/[。;;!!??]/)
|
||||
if (cut > 0 && cut < s.length - 1) {
|
||||
return { title: s.slice(0, cut + 1).replace(/[。;;]$/, ''), reason: s.slice(cut + 1).trim(), raw: raw !== s ? raw : undefined }
|
||||
}
|
||||
const colon = s.indexOf(':')
|
||||
if (colon > 4 && colon < 40) {
|
||||
return { title: s.slice(0, colon), reason: s.slice(colon + 1).trim(), raw: raw !== s ? raw : undefined }
|
||||
}
|
||||
return { title: s, raw: raw !== s ? raw : undefined }
|
||||
}
|
||||
|
||||
export function humanizeError(e: unknown): HumanError {
|
||||
if (e instanceof ApiError) {
|
||||
if (e.kind === 'network') {
|
||||
return { ...NETWORK_ERROR, ...networkReason(e), raw: e.raw ?? e.message, status: e.status || undefined }
|
||||
}
|
||||
// 后端的 detail 按约定已经是「发生了什么 + 原因 + 怎么办」,优先用它
|
||||
const parsed = fromText(e.message, { network: false })
|
||||
const status = e.status
|
||||
let action = parsed.action
|
||||
if (!action && status >= 500) action = '稍后重试;反复出现就查看后端日志。'
|
||||
if (!action && (status === 401 || status === 403)) action = '检查设置里的署名和权限。'
|
||||
return {
|
||||
...parsed,
|
||||
action,
|
||||
kind: 'http',
|
||||
status,
|
||||
raw: e.raw ?? (parsed.raw || undefined) ?? `${status} ${e.message}`,
|
||||
}
|
||||
}
|
||||
if (e instanceof Error) {
|
||||
if (e.name === 'AbortError') return { title: '已取消', kind: 'client', raw: e.message }
|
||||
const parsed = fromText(e.message || e.name)
|
||||
const raw = parsed.raw ?? (e.message || e.name)
|
||||
return { ...parsed, kind: parsed.kind ?? (e instanceof TypeError && NETWORK_RE.test(e.message) ? 'network' : 'unknown'), raw }
|
||||
}
|
||||
if (typeof e === 'string') {
|
||||
const parsed = fromText(e)
|
||||
return { ...parsed, kind: parsed.kind ?? 'unknown' }
|
||||
}
|
||||
if (e && typeof e === 'object') {
|
||||
const obj = e as Record<string, unknown>
|
||||
// 测连接、试跑工具这类接口失败时回 {ok:false, error, hint, detail}:error 已经是
|
||||
// 人话、hint 是怎么办、detail 是驱动原文。这是后端回的话,连不上的是它测的那个服务
|
||||
if (typeof obj.error === 'string' && obj.error) {
|
||||
const parsed = fromText(obj.error, { network: false })
|
||||
return {
|
||||
...parsed,
|
||||
action: typeof obj.hint === 'string' && obj.hint ? obj.hint : parsed.action,
|
||||
raw: typeof obj.detail === 'string' && obj.detail ? obj.detail : parsed.raw,
|
||||
kind: parsed.kind ?? 'unknown',
|
||||
}
|
||||
}
|
||||
const msg = typeof obj.detail === 'string' ? obj.detail
|
||||
: typeof obj.message === 'string' ? obj.message
|
||||
: typeof obj.error === 'string' ? obj.error
|
||||
: ''
|
||||
if (msg) return { ...fromText(msg), kind: 'unknown' }
|
||||
let raw = ''
|
||||
try { raw = JSON.stringify(e) } catch { raw = String(e) }
|
||||
return { title: '出错了,但没有给出原因', kind: 'unknown', raw }
|
||||
}
|
||||
return { title: '出错了,但没有给出原因', kind: 'unknown' }
|
||||
}
|
||||
|
||||
function networkReason(e: ApiError): Partial<HumanError> {
|
||||
// 超时和连不上是两回事:前者后端在、只是没回,后者根本够不着
|
||||
if (e.timeoutMs) {
|
||||
return { title: '后端没有响应', reason: `等了 ${Math.round(e.timeoutMs / 1000)} 秒没有回应,后端可能卡住了或负载太高。` }
|
||||
}
|
||||
if (e.status >= 500) {
|
||||
return { reason: `代理回了 ${e.status},后端可能没启动或正在重启。` }
|
||||
}
|
||||
return { reason: NETWORK_ERROR.reason }
|
||||
}
|
||||
|
||||
/** 一行文字:「标题:原因」。给 toast 和状态行用 */
|
||||
export function errorMessage(e: unknown): string {
|
||||
const h = humanizeError(e)
|
||||
return h.reason ? `${h.title}:${h.reason}` : h.title
|
||||
}
|
||||
|
||||
export function isNetworkError(e: unknown): boolean {
|
||||
return humanizeError(e).kind === 'network'
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
/**
|
||||
* 数字、时长、时间的唯一一份格式化。
|
||||
*
|
||||
* 之前有三套并行:decode 的 formatDuration 写「1m14s」,AssistantStream 的 fmtMs
|
||||
* 注释说"同一套规则"却写「2min」,各页面直接拼 `${ms}ms` 出现「12345ms」;token
|
||||
* 没有千分位,成本固定四位小数。数字是这个产品"可计量、可审计"的门面,同一个
|
||||
* 耗时两处说法不一,人就会怀疑数据本身。
|
||||
*
|
||||
* 约定:拿不到的数一律写「—」,不写 0,也不猜。显示这些数字的地方都要配
|
||||
* tabular-nums(.tnum),刷新时宽度才不跳。
|
||||
*/
|
||||
|
||||
export const NONE = '—'
|
||||
|
||||
const isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v)
|
||||
|
||||
const pad2 = (n: number) => String(n).padStart(2, '0')
|
||||
|
||||
/**
|
||||
* 耗时:「820 ms」「7.6 s」「1 分 14 秒」「1 小时 02 分」。
|
||||
*
|
||||
* 先按目标精度取整再判断落在哪一档,否则 59.96 秒会写成「60.0 s」、119.6 秒会
|
||||
* 写成「1m60s」(旧实现的边界 bug:秒数单独四舍五入,可能进到 60)。
|
||||
*/
|
||||
export function formatDuration(ms: number | null | undefined): string {
|
||||
if (!isNum(ms) || ms < 0) return NONE
|
||||
const whole = Math.round(ms)
|
||||
if (whole < 1000) return `${whole} ms`
|
||||
const tenths = Math.round(ms / 100)
|
||||
if (tenths < 600) return `${(tenths / 10).toFixed(1)} s`
|
||||
const secs = Math.round(ms / 1000)
|
||||
if (secs < 3600) return `${Math.floor(secs / 60)} 分 ${pad2(secs % 60)} 秒`
|
||||
return `${Math.floor(secs / 3600)} 小时 ${pad2(Math.floor((secs % 3600) / 60))} 分`
|
||||
}
|
||||
|
||||
/**
|
||||
* 实时计时器:「01:14.3」,一小时以上「1:02:03.4」。固定位数,配 tabular-nums
|
||||
* 跳字时不抖。截断而不是四舍五入:计时器读数不该跑在真实时间前面。
|
||||
*/
|
||||
export function formatClock(ms: number | null | undefined): string {
|
||||
if (!isNum(ms) || ms < 0) return NONE
|
||||
const t = Math.floor(ms / 100)
|
||||
const tenth = t % 10
|
||||
const secs = Math.floor(t / 10)
|
||||
const s = secs % 60
|
||||
const m = Math.floor(secs / 60) % 60
|
||||
const h = Math.floor(secs / 3600)
|
||||
return h > 0 ? `${h}:${pad2(m)}:${pad2(s)}.${tenth}` : `${pad2(m)}:${pad2(s)}.${tenth}`
|
||||
}
|
||||
|
||||
/** 带千分位的整数:「56,034」 */
|
||||
export function formatNumber(n: number | null | undefined): string {
|
||||
if (!isNum(n)) return NONE
|
||||
return Math.round(n).toLocaleString('en-US')
|
||||
}
|
||||
|
||||
function compact(n: number): string {
|
||||
const abs = Math.abs(n)
|
||||
if (abs < 1000) return String(Math.round(n))
|
||||
// 先取整到一位小数再判断档位:999,950 应当是「1.0M」而不是「1000.0k」
|
||||
const k = Math.round(n / 100) / 10
|
||||
if (Math.abs(k) < 1000) return `${k.toFixed(1)}k`
|
||||
const m = Math.round(n / 100_000) / 10
|
||||
return `${m.toFixed(1)}M`
|
||||
}
|
||||
|
||||
/** tokens:「56,034 tokens」;紧凑场景「56.0k tok」 */
|
||||
export function formatTokens(n: number | null | undefined, opts?: { compact?: boolean }): string {
|
||||
if (!isNum(n)) return NONE
|
||||
return opts?.compact ? `${compact(n)} tok` : `${formatNumber(n)} tokens`
|
||||
}
|
||||
|
||||
/**
|
||||
* 成本:「$0.031」,一美元以上「$1.24」,不足 0.001 写「<$0.001」。
|
||||
* 正好为 0(本地模型、没有计价)写「$0」——写成「<$0.001」会让人以为花了钱。
|
||||
*/
|
||||
export function formatCost(usd: number | null | undefined): string {
|
||||
if (!isNum(usd)) return NONE
|
||||
if (usd === 0) return '$0'
|
||||
if (usd < 0.001) return '<$0.001'
|
||||
if (usd < 1) return `$${usd.toFixed(3)}`
|
||||
return `$${usd.toFixed(2)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析服务器给的时间。
|
||||
*
|
||||
* SQLite 会丢时区,后端吐出来的 '2026-09-26T01:11:19.891698' 其实是 UTC;
|
||||
* JS 把不带偏移的 ISO 串当本地时间,于是全站慢 8 小时。没有 Z 也没有偏移的
|
||||
* 一律补 Z。数字按 epoch 处理:事件的 ts 是秒(带小数),小于 1e12 的当秒。
|
||||
*/
|
||||
export function parseServerTime(v: string | number | Date | null | undefined): Date | null {
|
||||
if (v == null || v === '') return null
|
||||
if (v instanceof Date) return Number.isNaN(v.getTime()) ? null : v
|
||||
if (typeof v === 'number') {
|
||||
if (!Number.isFinite(v)) return null
|
||||
return new Date(v < 1e12 ? v * 1000 : v)
|
||||
}
|
||||
let s = v.trim()
|
||||
// 只有日期没有时间的串('2026-09-26')JS 本来就按 UTC 解析,不用补
|
||||
if (/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}/.test(s) && !/(Z|[+-]\d{2}:?\d{2})$/i.test(s)) {
|
||||
s = s.replace(' ', 'T') + 'Z'
|
||||
}
|
||||
const d = new Date(s)
|
||||
return Number.isNaN(d.getTime()) ? null : d
|
||||
}
|
||||
|
||||
const sameDay = (a: Date, b: Date) =>
|
||||
a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate()
|
||||
|
||||
const hm = (d: Date) => `${pad2(d.getHours())}:${pad2(d.getMinutes())}`
|
||||
|
||||
/**
|
||||
* 列表里的时间:今天只写「10:05」,今年更早的写「9/25 12:52」,跨年的写
|
||||
* 「2025/9/25 12:52」。完整时间放进 title,用 formatDateTime。
|
||||
*/
|
||||
export function formatTime(v: string | number | Date | null | undefined, now: Date = new Date()): string {
|
||||
const d = parseServerTime(v)
|
||||
if (!d) return NONE
|
||||
if (sameDay(d, now)) return hm(d)
|
||||
const md = `${d.getMonth() + 1}/${d.getDate()} ${hm(d)}`
|
||||
return d.getFullYear() === now.getFullYear() ? md : `${d.getFullYear()}/${md}`
|
||||
}
|
||||
|
||||
function tzLabel(d: Date): string {
|
||||
const off = -d.getTimezoneOffset()
|
||||
const sign = off >= 0 ? '+' : '-'
|
||||
const abs = Math.abs(off)
|
||||
return `UTC${sign}${pad2(Math.floor(abs / 60))}:${pad2(abs % 60)}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 完整时间:「2026-09-26 10:05:12 (UTC+08:00)」。给 title 和审计场景用——要能
|
||||
* 和外部系统日志、审批时间逐秒对上,所以带秒、带时区。
|
||||
*/
|
||||
export function formatDateTime(v: string | number | Date | null | undefined): string {
|
||||
const d = parseServerTime(v)
|
||||
if (!d) return NONE
|
||||
const date = `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`
|
||||
return `${date} ${hm(d)}:${pad2(d.getSeconds())} (${tzLabel(d)})`
|
||||
}
|
||||
|
||||
/** 按天分组的组名:「今天」「昨天」「9 月 24 日」,跨年带年份 */
|
||||
export function formatDay(v: string | number | Date | null | undefined, now: Date = new Date()): string {
|
||||
const d = parseServerTime(v)
|
||||
if (!d) return NONE
|
||||
if (sameDay(d, now)) return '今天'
|
||||
const y = new Date(now)
|
||||
y.setDate(now.getDate() - 1)
|
||||
if (sameDay(d, y)) return '昨天'
|
||||
const md = `${d.getMonth() + 1} 月 ${d.getDate()} 日`
|
||||
return d.getFullYear() === now.getFullYear() ? md : `${d.getFullYear()} 年 ${md}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 相对时间:「刚刚」「52 分钟前」「3 小时前」,超过一天回落到 formatTime。
|
||||
* 只用在"新鲜度"有意义的地方(最后连通、最近召回),审计时间用绝对时间。
|
||||
*/
|
||||
export function formatRelative(v: string | number | Date | null | undefined, now: Date = new Date()): string {
|
||||
const d = parseServerTime(v)
|
||||
if (!d) return NONE
|
||||
const diff = now.getTime() - d.getTime()
|
||||
if (diff < 0) return formatTime(d, now)
|
||||
if (diff < 45_000) return '刚刚'
|
||||
// 先取整再判档,和 formatDuration 同理:59.6 分钟按分钟取整是「60 分钟前」
|
||||
const m = Math.round(diff / 60_000)
|
||||
if (m < 60) return `${Math.max(1, m)} 分钟前`
|
||||
const h = Math.round(diff / 3_600_000)
|
||||
if (h < 24) return `${h} 小时前`
|
||||
return formatTime(d, now)
|
||||
}
|
||||
|
||||
/** 短 id:「#66a5a6」。完整 id 放 title,点击复制由调用方决定 */
|
||||
export function shortId(id: string | null | undefined, len = 6): string {
|
||||
if (!id) return NONE
|
||||
return `#${id.slice(0, len)}`
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* 快捷键:平台判断、显示格式、事件匹配。
|
||||
*
|
||||
* 提示文字和处理器必须出自同一份描述——之前界面上写着 ⌥V,全仓却没有一个
|
||||
* 监听处理 V;RunControl 的处理器接受 Ctrl+Enter,提示却只写 ⌘⏎,Windows
|
||||
* 用户照着按不出来。组合键一律写成 'Mod+Enter' 这样的串,显示走
|
||||
* formatShortcut,判定走 matchShortcut。
|
||||
*
|
||||
* Mod 在 Mac 上是 ⌘,其他平台是 Ctrl。
|
||||
*/
|
||||
|
||||
export const isMac: boolean = (() => {
|
||||
if (typeof navigator === 'undefined') return false
|
||||
const nav = navigator as Navigator & { userAgentData?: { platform?: string } }
|
||||
const platform = nav.userAgentData?.platform || navigator.platform || navigator.userAgent
|
||||
return /mac|iphone|ipad|ipod/i.test(platform)
|
||||
})()
|
||||
|
||||
/** 这个平台上"主修饰键"对应事件上的哪个字段:e[modKey] */
|
||||
export const modKey: 'metaKey' | 'ctrlKey' = isMac ? 'metaKey' : 'ctrlKey'
|
||||
|
||||
/** 主修饰键的显示名 */
|
||||
export const modLabel: string = isMac ? '⌘' : 'Ctrl'
|
||||
|
||||
const MAC: Record<string, string> = {
|
||||
mod: '⌘', meta: '⌘', cmd: '⌘', ctrl: '⌃', alt: '⌥', option: '⌥', shift: '⇧',
|
||||
enter: '⏎', return: '⏎', backspace: '⌫', delete: '⌦', tab: '⇥', esc: 'Esc', escape: 'Esc',
|
||||
up: '↑', down: '↓', left: '←', right: '→', space: '空格',
|
||||
}
|
||||
|
||||
const OTHER: Record<string, string> = {
|
||||
mod: 'Ctrl', meta: 'Win', cmd: 'Ctrl', ctrl: 'Ctrl', alt: 'Alt', option: 'Alt', shift: 'Shift',
|
||||
enter: 'Enter', return: 'Enter', backspace: 'Backspace', delete: 'Del', tab: 'Tab',
|
||||
esc: 'Esc', escape: 'Esc', up: '↑', down: '↓', left: '←', right: '→', space: '空格',
|
||||
}
|
||||
|
||||
function split(combo: string): string[] {
|
||||
// 'Mod++' 这种以加号本身为键的写法:最后一段是空串时补回 '+'
|
||||
const parts = combo.split('+').map((p) => p.trim())
|
||||
if (parts.length > 1 && parts[parts.length - 1] === '') parts[parts.length - 1] = '+'
|
||||
return parts.filter(Boolean)
|
||||
}
|
||||
|
||||
/** 组合键拆成一个个键帽的文字:'Mod+Shift+K' → ['⌘','⇧','K'] 或 ['Ctrl','Shift','K'] */
|
||||
export function shortcutParts(combo: string): string[] {
|
||||
const table = isMac ? MAC : OTHER
|
||||
return split(combo).map((p) => table[p.toLowerCase()] ?? (p.length === 1 ? p.toUpperCase() : p))
|
||||
}
|
||||
|
||||
/**
|
||||
* 给人看的组合键。Mac 上符号连写(⌘⏎、⌥V),其他平台用加号(Ctrl+Enter、Alt+V),
|
||||
* 这是两边各自系统菜单的写法。
|
||||
*/
|
||||
export function formatShortcut(combo: string): string {
|
||||
return shortcutParts(combo).join(isMac ? '' : '+')
|
||||
}
|
||||
|
||||
/** aria-keyshortcuts 的键名:修饰键和功能键按 UI Events 的 key 值写,不是给人看的简写 */
|
||||
const ARIA: Record<string, string> = {
|
||||
meta: 'Meta', cmd: 'Meta', ctrl: 'Control', alt: 'Alt', option: 'Alt', shift: 'Shift',
|
||||
enter: 'Enter', return: 'Enter', esc: 'Escape', escape: 'Escape', up: 'ArrowUp', down: 'ArrowDown',
|
||||
left: 'ArrowLeft', right: 'ArrowRight', space: 'Space', tab: 'Tab', backspace: 'Backspace', delete: 'Delete',
|
||||
}
|
||||
|
||||
/**
|
||||
* 写进 aria-keyshortcuts 的串:'Mod+Enter' 在 Mac 上是 'Meta+Enter',其他平台是
|
||||
* 'Control+Enter'。读屏照这个念,Windows 上念成 Meta 就是在教人按错键。
|
||||
*/
|
||||
export function ariaShortcut(combo: string): string {
|
||||
return split(combo).map((raw) => {
|
||||
const p = raw.toLowerCase()
|
||||
if (p === 'mod') return isMac ? 'Meta' : 'Control'
|
||||
return ARIA[p] ?? (raw.length === 1 ? raw.toUpperCase() : raw)
|
||||
}).join('+')
|
||||
}
|
||||
|
||||
/**
|
||||
* 键盘事件是否就是这个组合键。
|
||||
*
|
||||
* 字母和数字按 e.code 比:Mac 上 Option+V 产生的 e.key 是「√」,按 e.key 比
|
||||
* ⌥V 永远按不中。修饰键要求完全一致,免得 ⌘⇧S 也触发 ⌘S。
|
||||
* Mod 在 Mac 上只认 ⌘:Mac 的 Ctrl+字母另有系统含义(比如 Ctrl+A 回行首)。
|
||||
*/
|
||||
export function matchShortcut(e: KeyboardEvent | { key: string; code?: string; metaKey: boolean; ctrlKey: boolean; altKey: boolean; shiftKey: boolean }, combo: string): boolean {
|
||||
const want = { meta: false, ctrl: false, alt: false, shift: false }
|
||||
let key = ''
|
||||
for (const raw of split(combo)) {
|
||||
const p = raw.toLowerCase()
|
||||
if (p === 'mod') want[isMac ? 'meta' : 'ctrl'] = true
|
||||
else if (p === 'meta' || p === 'cmd') want.meta = true
|
||||
else if (p === 'ctrl') want.ctrl = true
|
||||
else if (p === 'alt' || p === 'option') want.alt = true
|
||||
else if (p === 'shift') want.shift = true
|
||||
else key = p
|
||||
}
|
||||
if (e.metaKey !== want.meta || e.ctrlKey !== want.ctrl || e.altKey !== want.alt) return false
|
||||
// '?' 这类本身就要按 Shift 才打得出的键,不强求 shift 一致
|
||||
const shiftNeutral = key.length === 1 && !/[a-z0-9]/.test(key)
|
||||
if (!shiftNeutral && e.shiftKey !== want.shift) return false
|
||||
if (/^[a-z]$/.test(key)) return e.code === `Key${key.toUpperCase()}` || e.key.toLowerCase() === key
|
||||
if (/^[0-9]$/.test(key)) return e.code === `Digit${key}` || e.key === key
|
||||
const alias: Record<string, string> = {
|
||||
enter: 'Enter', return: 'Enter', esc: 'Escape', escape: 'Escape', up: 'ArrowUp',
|
||||
down: 'ArrowDown', left: 'ArrowLeft', right: 'ArrowRight', space: ' ', tab: 'Tab',
|
||||
backspace: 'Backspace', delete: 'Delete',
|
||||
}
|
||||
return e.key === (alias[key] ?? key)
|
||||
}
|
||||
|
||||
/**
|
||||
* 焦点是不是在一个能打字的地方。全局快捷键遇到它要让路:用户在输入框里按
|
||||
* Esc 是给输入法的,按 ⌥V 是要打字符的。
|
||||
*/
|
||||
export function isTypingTarget(target: EventTarget | null = typeof document !== 'undefined' ? document.activeElement : null): boolean {
|
||||
if (!(target instanceof HTMLElement)) return false
|
||||
if (target.isContentEditable) return true
|
||||
const tag = target.tagName
|
||||
if (tag === 'TEXTAREA' || tag === 'SELECT') return true
|
||||
if (tag !== 'INPUT') return false
|
||||
const type = (target as HTMLInputElement).type
|
||||
// 复选框、按钮之类的 input 不接收文字
|
||||
return !['checkbox', 'radio', 'button', 'submit', 'reset', 'range', 'color', 'file'].includes(type)
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
/**
|
||||
* 标签页在后台时的三路提醒:标题前缀、favicon 状态点、系统通知。
|
||||
*
|
||||
* 多 Agent 协作一跑就是一两分钟,审批更是要等人——用户切去别的标签页是常态。
|
||||
* 之前标题写死、favicon 写死、也没有通知,一个待签批能被晾上几天没人发现,
|
||||
* 只能不停切回来看。
|
||||
*
|
||||
* 这里只管浏览器那一层(document.title、<link rel=icon>、Notification),
|
||||
* 不读任何 store:什么时候该提醒,由外壳(App)从运行态和待审批推出来。
|
||||
* 这样页面也能用 usePageTitle 报自己的名字,不必知道前缀是怎么拼的。
|
||||
*/
|
||||
import { useEffect } from 'react'
|
||||
import { create } from 'zustand'
|
||||
|
||||
export type NotifyPermission = 'granted' | 'denied' | 'default' | 'unsupported'
|
||||
|
||||
/** 回来之前一直挂在标题和 favicon 上的那件事:后台时结束的运行 */
|
||||
export interface Attention {
|
||||
tone: 'ok' | 'err' | 'warn'
|
||||
/** 标题前缀,比如「✕ 运行失败」 */
|
||||
text: string
|
||||
}
|
||||
|
||||
interface SignalState {
|
||||
/** 用户开没开后台提醒(且浏览器已授权) */
|
||||
notify: boolean
|
||||
permission: NotifyPermission
|
||||
hidden: boolean
|
||||
attention: Attention | null
|
||||
/** 页面自己报的标题,盖过外壳按路径推的那个。404 页用它 */
|
||||
pageTitle: string | null
|
||||
}
|
||||
|
||||
const PREF_KEY = 'agentlab.notify'
|
||||
|
||||
export const notifySupported = (): boolean =>
|
||||
typeof window !== 'undefined' && 'Notification' in window
|
||||
|
||||
function readPermission(): NotifyPermission {
|
||||
return notifySupported() ? Notification.permission : 'unsupported'
|
||||
}
|
||||
|
||||
function readPref(): boolean {
|
||||
try {
|
||||
return localStorage.getItem(PREF_KEY) === '1'
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function writePref(on: boolean) {
|
||||
try {
|
||||
localStorage.setItem(PREF_KEY, on ? '1' : '0')
|
||||
} catch {
|
||||
// 隐私模式:这次会话里照样生效,只是下次打开要重新开
|
||||
}
|
||||
}
|
||||
|
||||
export const useSignals = create<SignalState>(() => ({
|
||||
notify: readPref() && readPermission() === 'granted',
|
||||
permission: readPermission(),
|
||||
hidden: typeof document !== 'undefined' ? document.hidden : false,
|
||||
attention: null,
|
||||
pageTitle: null,
|
||||
}))
|
||||
|
||||
if (typeof document !== 'undefined') {
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
const hidden = document.hidden
|
||||
// 人回来了,「在你离开时结束了」这件事就算传达到了。权限也可能是在浏览器
|
||||
// 设置里改的,回来时顺手对一次
|
||||
const permission = readPermission()
|
||||
useSignals.setState((s) => ({
|
||||
hidden,
|
||||
permission,
|
||||
notify: s.notify && permission === 'granted',
|
||||
...(hidden ? {} : { attention: null }),
|
||||
}))
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开后台提醒。只在用户点开关的那一刻调用:浏览器的权限弹窗是一次性的,
|
||||
* 进页面就弹,多数人会顺手点「拒绝」,之后就再也要不回来了。
|
||||
*/
|
||||
export async function enableNotify(): Promise<NotifyPermission> {
|
||||
if (!notifySupported()) return 'unsupported'
|
||||
let permission = Notification.permission as NotifyPermission
|
||||
if (permission === 'default') {
|
||||
try {
|
||||
permission = (await Notification.requestPermission()) as NotifyPermission
|
||||
} catch {
|
||||
permission = Notification.permission as NotifyPermission
|
||||
}
|
||||
}
|
||||
const on = permission === 'granted'
|
||||
writePref(on)
|
||||
useSignals.setState({ permission, notify: on })
|
||||
return permission
|
||||
}
|
||||
|
||||
export function disableNotify(): void {
|
||||
writePref(false)
|
||||
useSignals.setState({ notify: false })
|
||||
}
|
||||
|
||||
/**
|
||||
* 页面在后台时发一条系统通知;页面在前台、没开提醒、没授权都不发。
|
||||
* 点通知回到这个标签页并执行 onClick(通常是跳到对应的运行)。
|
||||
* tag 相同的通知互相替换,同一条运行不会叠出一串。
|
||||
*/
|
||||
export function notifyInBackground(opts: { title: string; body?: string; tag?: string; onClick?: () => void }): boolean {
|
||||
if (typeof document === 'undefined' || !document.hidden) return false
|
||||
if (!useSignals.getState().notify || readPermission() !== 'granted') return false
|
||||
try {
|
||||
const n = new Notification(opts.title, { body: opts.body, tag: opts.tag, icon: '/favicon.svg', lang: 'zh-CN' })
|
||||
n.onclick = () => {
|
||||
window.focus()
|
||||
opts.onClick?.()
|
||||
n.close()
|
||||
}
|
||||
return true
|
||||
} catch {
|
||||
// 安卓 Chrome 之类只允许经 Service Worker 发通知,直接 new 会抛
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** 后台时结束的运行:挂到标题和 favicon 上,直到人切回这个标签页 */
|
||||
export function flagAttention(attention: Attention): void {
|
||||
if (typeof document === 'undefined' || !document.hidden) return
|
||||
useSignals.setState({ attention })
|
||||
}
|
||||
|
||||
/**
|
||||
* 页面报自己的标题(「页面不存在」这类外壳按路径推不出来的)。卸载时撤掉。
|
||||
* 前缀(待审批、运行中)照样由外壳加。
|
||||
*/
|
||||
export function usePageTitle(name: string | null): void {
|
||||
useEffect(() => {
|
||||
useSignals.setState({ pageTitle: name })
|
||||
return () => {
|
||||
if (useSignals.getState().pageTitle === name) useSignals.setState({ pageTitle: null })
|
||||
}
|
||||
}, [name])
|
||||
}
|
||||
|
||||
/**
|
||||
* 标签页标题:「(2) 待审批 · ● 运行中 3/8 · 编排 · 多 Agent 协作 — AgentLab」。
|
||||
*
|
||||
* 待审批数放最前:它是要人去做的事,标签页窄到只剩几个字时也得看得见。
|
||||
* 后台时结束的运行(attention)盖过「运行中」——它已经不在跑了。
|
||||
*/
|
||||
export function composeTitle(p: {
|
||||
pending: number
|
||||
activity?: string | null
|
||||
attention?: Attention | null
|
||||
page: string
|
||||
object?: string | null
|
||||
}): string {
|
||||
const lead: string[] = []
|
||||
if (p.pending > 0) lead.push(`(${p.pending}) 待审批`)
|
||||
const state = p.attention?.text ?? p.activity
|
||||
if (state) lead.push(state)
|
||||
const base = p.object ? `${p.page} · ${p.object}` : p.page
|
||||
return `${[...lead, base].join(' · ')} — AgentLab`
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// favicon 状态点
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
export type FaviconDot = 'running' | 'waiting' | 'failed' | 'done'
|
||||
|
||||
/**
|
||||
* 标签栏跟着系统配色走,不跟页面主题,所以这里按系统深浅挑色,而不是读页面
|
||||
* 的 CSS 变量。取值与 public/favicon.svg、index.css 的状态色一致。
|
||||
*/
|
||||
const FAVICON = {
|
||||
light: {
|
||||
tile: '#eef3fe', tileStroke: '#c3d3f3', mark: '#2563eb',
|
||||
dot: { running: '#2563eb', waiting: '#d29922', failed: '#cf222e', done: '#1f883d' },
|
||||
},
|
||||
dark: {
|
||||
tile: '#141926', tileStroke: '#333c52', mark: '#4f8cff',
|
||||
dot: { running: '#4f8cff', waiting: '#d29922', failed: '#f85149', done: '#3fb950' },
|
||||
},
|
||||
} as const
|
||||
|
||||
/** 与 components/Logo.tsx、public/favicon.svg 同一个图形 */
|
||||
const EDGES = 'M8.5 12H12V6h3.5M12 12v6h3.5'
|
||||
|
||||
let originalHref: string | null = null
|
||||
let painted: string | null = null
|
||||
|
||||
function iconLink(): HTMLLinkElement | null {
|
||||
return document.querySelector<HTMLLinkElement>('link[rel~="icon"]')
|
||||
}
|
||||
|
||||
function systemScheme(): 'light' | 'dark' {
|
||||
return window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
|
||||
}
|
||||
|
||||
function roundRect(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number) {
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(x + r, y)
|
||||
ctx.arcTo(x + w, y, x + w, y + h, r)
|
||||
ctx.arcTo(x + w, y + h, x, y + h, r)
|
||||
ctx.arcTo(x, y + h, x, y, r)
|
||||
ctx.arcTo(x, y, x + w, y, r)
|
||||
ctx.closePath()
|
||||
}
|
||||
|
||||
function draw(dot: FaviconDot, scheme: 'light' | 'dark'): string | null {
|
||||
const c = FAVICON[scheme]
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = 64
|
||||
canvas.height = 64
|
||||
const ctx = canvas.getContext('2d')
|
||||
if (!ctx) return null
|
||||
ctx.scale(2, 2)
|
||||
roundRect(ctx, 0.5, 0.5, 31, 31, 7)
|
||||
ctx.fillStyle = c.tile
|
||||
ctx.fill()
|
||||
ctx.strokeStyle = c.tileStroke
|
||||
ctx.lineWidth = 1
|
||||
ctx.stroke()
|
||||
|
||||
ctx.save()
|
||||
ctx.translate(4, 4)
|
||||
ctx.strokeStyle = c.mark
|
||||
ctx.lineWidth = 2.25
|
||||
ctx.lineCap = 'round'
|
||||
ctx.lineJoin = 'round'
|
||||
ctx.stroke(new Path2D(EDGES))
|
||||
roundRect(ctx, 2.5, 9, 6, 6, 1.5)
|
||||
ctx.fillStyle = c.mark
|
||||
ctx.fill()
|
||||
ctx.stroke()
|
||||
roundRect(ctx, 15.5, 3, 6, 6, 1.5)
|
||||
ctx.stroke()
|
||||
roundRect(ctx, 15.5, 15, 6, 6, 1.5)
|
||||
ctx.stroke()
|
||||
ctx.restore()
|
||||
|
||||
// 右下角的状态点,外面一圈底板色把它从字标上"抠"出来,16px 下也分得清
|
||||
ctx.beginPath()
|
||||
ctx.arc(24.5, 24.5, 7.5, 0, Math.PI * 2)
|
||||
ctx.fillStyle = c.tile
|
||||
ctx.fill()
|
||||
ctx.beginPath()
|
||||
ctx.arc(24.5, 24.5, 5.5, 0, Math.PI * 2)
|
||||
ctx.fillStyle = c.dot[dot]
|
||||
ctx.fill()
|
||||
return canvas.toDataURL('image/png')
|
||||
}
|
||||
|
||||
/**
|
||||
* 换 favicon:有状态就画一个带状态点的,没有就还原成 /favicon.svg。
|
||||
* 静态,不闪不转:标签页里闪烁的图标只会让人烦,而且减少动效的用户也看得到。
|
||||
*/
|
||||
export function paintFavicon(dot: FaviconDot | null): void {
|
||||
if (typeof document === 'undefined') return
|
||||
const link = iconLink()
|
||||
if (!link) return
|
||||
if (originalHref == null) originalHref = link.getAttribute('href') ?? '/favicon.svg'
|
||||
const key = dot ? `${dot}:${systemScheme()}` : null
|
||||
if (key === painted) return
|
||||
painted = key
|
||||
if (!dot) {
|
||||
link.type = 'image/svg+xml'
|
||||
link.href = originalHref
|
||||
link.removeAttribute('data-status')
|
||||
return
|
||||
}
|
||||
const url = draw(dot, systemScheme())
|
||||
if (!url) return
|
||||
link.type = 'image/png'
|
||||
link.href = url
|
||||
link.setAttribute('data-status', dot)
|
||||
}
|
||||
|
||||
if (typeof window !== 'undefined' && window.matchMedia) {
|
||||
// 系统换了深浅,底板色要跟着换;只在有状态点时才需要重画
|
||||
window.matchMedia('(prefers-color-scheme: dark)').addEventListener?.('change', () => {
|
||||
const dot = painted?.split(':')[0] as FaviconDot | undefined
|
||||
painted = null
|
||||
if (dot) paintFavicon(dot)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
/**
|
||||
* 运行状态与节点状态的唯一一份文案和外观。
|
||||
*
|
||||
* 之前有五张映射表:StatusDot 写「成功 / 等待人工」,运行页轮次头写「完成 /
|
||||
* 等待人工介入」,问数据写「完成 / 出错了」,运行条写「等你确认」……同一屏上
|
||||
* 「成功」和「完成」并存,人会以为是两个状态。加一个状态就得去五处各补一遍。
|
||||
*
|
||||
* 每个状态同时有剪影(shape)、颜色和文字三条通道:去掉颜色还能靠剪影认出来,
|
||||
* 去掉剪影还能读字。颜色走 index.css 的状态令牌 --st-*;令牌还没定义时回落到
|
||||
* ok / warn / err / accent 这几个基础色。
|
||||
*/
|
||||
|
||||
import type { RunStatus } from '../types'
|
||||
|
||||
/** 所有能被显示的状态。运行层和节点层共用一张表,其中几个只出现在一层 */
|
||||
export type StatusCode =
|
||||
| 'idle' // 节点:还没跑过
|
||||
| 'queued' // 运行:排队;节点:上游都交付了、自己还没开始(推导)
|
||||
| 'running'
|
||||
| 'waiting' // 等人审批
|
||||
| 'done' // 节点跑完
|
||||
| 'succeeded' // 运行跑完
|
||||
| 'failed'
|
||||
| 'cancelled'
|
||||
| 'suspended' // 服务重启后挂起,可续跑
|
||||
| 'held' // 后端的 interrupted 但没有待审批:已挂起 · 可续跑
|
||||
| 'skipped' // 被 skip_if 跳过
|
||||
| 'blocked' // 失败节点的下游,这次再也跑不到了(推导)
|
||||
| 'unreached' // 运行结束时一次都没轮到,比如分支没走的那一侧(推导)
|
||||
|
||||
/**
|
||||
* 九种剪影,外加挂起用的暂停符和未运行用的小空心点。
|
||||
* 形状是给"去掉颜色也能认"准备的:灰度打印、色弱、投影仪偏色时都要分得开。
|
||||
*/
|
||||
export type StatusShape =
|
||||
| 'ring' // 圆环:运行中
|
||||
| 'dashed-ring' // 虚线环:排队
|
||||
| 'square' // 实心圆角方(带勾):完成
|
||||
| 'diamond' // 菱形:等人
|
||||
| 'triangle' // 三角:失败
|
||||
| 'slashed' // 斜杠圆:跳过
|
||||
| 'stop' // 实心小方:取消
|
||||
| 'dashed-x' // 虚线方加 ×:阻断
|
||||
| 'bar' // 横杠:未到达
|
||||
| 'pause' // 两竖条:挂起
|
||||
| 'dot' // 小空心点:未运行
|
||||
|
||||
export interface StatusMeta {
|
||||
code: StatusCode
|
||||
/** 完整叫法,状态标签和 tooltip 用 */
|
||||
label: string
|
||||
/** 窄处用的短叫法(节点卡的运行槽、HUD 计数) */
|
||||
short: string
|
||||
shape: StatusShape
|
||||
/** 前景色,CSS 颜色表达式 */
|
||||
color: string
|
||||
/** 淡底色,CSS 颜色表达式 */
|
||||
soft: string
|
||||
/** 是不是异常态。正常态安静、异常态醒目:只有它们该用底色和强调 */
|
||||
alert: boolean
|
||||
/** 是不是终态(这次运行里不会再变了) */
|
||||
terminal: boolean
|
||||
/** 推导出来的状态:tooltip 里要写明"推导",别让人以为是后端说的 */
|
||||
derived?: boolean
|
||||
/** 一句话解释,放 title */
|
||||
hint?: string
|
||||
}
|
||||
|
||||
const tok = (name: string, fallback: string) => ({
|
||||
color: `var(--st-${name}, ${fallback})`,
|
||||
soft: `var(--st-${name}-soft, color-mix(in srgb, ${fallback} 14%, transparent))`,
|
||||
})
|
||||
|
||||
export const STATUS: Record<StatusCode, StatusMeta> = {
|
||||
idle: {
|
||||
code: 'idle', label: '未运行', short: '未运行', shape: 'dot', alert: false, terminal: false,
|
||||
...tok('idle', 'var(--text-faint)'),
|
||||
},
|
||||
queued: {
|
||||
code: 'queued', label: '排队中', short: '排队', shape: 'dashed-ring', alert: false, terminal: false,
|
||||
hint: '上游已经交付,等同一步里别的节点跑完', ...tok('queued', 'var(--text-dim)'),
|
||||
},
|
||||
running: {
|
||||
code: 'running', label: '运行中', short: '运行中', shape: 'ring', alert: false, terminal: false,
|
||||
...tok('running', 'var(--accent)'),
|
||||
},
|
||||
waiting: {
|
||||
code: 'waiting', label: '等待审批', short: '待审批', shape: 'diamond', alert: true, terminal: false,
|
||||
hint: '停在人工审批上,处理之后接着跑', ...tok('waiting', 'var(--warn)'),
|
||||
},
|
||||
done: {
|
||||
code: 'done', label: '已完成', short: '完成', shape: 'square', alert: false, terminal: true,
|
||||
...tok('done', 'var(--ok)'),
|
||||
},
|
||||
succeeded: {
|
||||
code: 'succeeded', label: '已完成', short: '完成', shape: 'square', alert: false, terminal: true,
|
||||
hint: '执行层面跑完了。结论是否可用看出具档位和复核', ...tok('done', 'var(--ok)'),
|
||||
},
|
||||
failed: {
|
||||
code: 'failed', label: '失败', short: '失败', shape: 'triangle', alert: true, terminal: true,
|
||||
...tok('failed', 'var(--err)'),
|
||||
},
|
||||
cancelled: {
|
||||
code: 'cancelled', label: '已取消', short: '已取消', shape: 'stop', alert: false, terminal: true,
|
||||
...tok('cancelled', 'var(--text-faint)'),
|
||||
},
|
||||
suspended: {
|
||||
code: 'suspended', label: '已中断(服务重启)', short: '已中断', shape: 'pause', alert: true, terminal: true,
|
||||
hint: '服务重启时这次运行还没结束,已从断点挂起,可以接着跑', ...tok('suspended', 'var(--warn)'),
|
||||
},
|
||||
held: {
|
||||
code: 'held', label: '已挂起 · 可续跑', short: '已挂起', shape: 'pause', alert: true, terminal: true,
|
||||
hint: '运行停在断点上,但没有待处理的审批——多半是服务重启打断的,可以接着跑',
|
||||
...tok('suspended', 'var(--warn)'),
|
||||
},
|
||||
skipped: {
|
||||
code: 'skipped', label: '已跳过', short: '跳过', shape: 'slashed', alert: false, terminal: true,
|
||||
hint: '跳过条件成立,这一步没有执行', ...tok('skipped', 'var(--text-faint)'),
|
||||
},
|
||||
blocked: {
|
||||
code: 'blocked', label: '已阻断', short: '阻断', shape: 'dashed-x', alert: true, terminal: true,
|
||||
derived: true, hint: '推导:上游失败,这次运行再也走不到这里', ...tok('blocked', 'var(--err)'),
|
||||
},
|
||||
unreached: {
|
||||
code: 'unreached', label: '未到达', short: '未到达', shape: 'bar', alert: false, terminal: true,
|
||||
derived: true, hint: '推导:运行结束时一次都没轮到,比如分支没走的那一侧', ...tok('unreached', 'var(--text-faint)'),
|
||||
},
|
||||
}
|
||||
|
||||
/** 旧代码和后端里的别名。未知状态码原样落到 idle 的外观上,文字照写原码 */
|
||||
const ALIAS: Record<string, StatusCode> = {
|
||||
success: 'succeeded', ok: 'succeeded', completed: 'succeeded', finished: 'succeeded',
|
||||
error: 'failed', canceled: 'cancelled', pending: 'queued', interrupted: 'waiting',
|
||||
}
|
||||
|
||||
/**
|
||||
* 把后端的运行状态落到显示用的状态上。
|
||||
*
|
||||
* 后端的 interrupted 有两种:停在审批上(等待审批),和服务重启打断后没有
|
||||
* 待审批(已挂起 · 可续跑)。二者要看审批列表里有没有这条运行的 pending
|
||||
* 才分得开——传 pendingApproval。不知道时(没传)按等待审批处理,这是
|
||||
* interrupted 最常见的来源,也是改造前的说法,不会比原来更错。
|
||||
*/
|
||||
export function resolveStatus(status: string | null | undefined, opts?: { pendingApproval?: boolean }): StatusCode {
|
||||
if (!status) return 'idle'
|
||||
if (status === 'interrupted') return opts?.pendingApproval === false ? 'held' : 'waiting'
|
||||
if (status in STATUS) return status as StatusCode
|
||||
return ALIAS[status] ?? 'idle'
|
||||
}
|
||||
|
||||
/** 状态的完整外观。未知状态码回落到 idle 的外观,文字写原码,免得静默吞掉 */
|
||||
export function statusMeta(status: string | null | undefined, opts?: { pendingApproval?: boolean }): StatusMeta {
|
||||
const code = resolveStatus(status, opts)
|
||||
const meta = STATUS[code]
|
||||
if (status && code === 'idle' && status !== 'idle' && !(status in ALIAS)) {
|
||||
return { ...meta, label: status, short: status }
|
||||
}
|
||||
return meta
|
||||
}
|
||||
|
||||
/** 只要文字 */
|
||||
export function statusLabel(status: string | null | undefined, opts?: { pendingApproval?: boolean; short?: boolean }): string {
|
||||
const meta = statusMeta(status, opts)
|
||||
return opts?.short ? meta.short : meta.label
|
||||
}
|
||||
|
||||
/**
|
||||
* 运行列表的状态筛选用:按显示顺序排好的运行状态。
|
||||
* 这是显示用的码,不能直接当查询参数——waiting / held 在后端都是 interrupted,
|
||||
* 查询前用 serverStatusOf 换回去。
|
||||
*/
|
||||
export const RUN_STATUS_ORDER: StatusCode[] = [
|
||||
'running', 'waiting', 'held', 'failed', 'succeeded', 'cancelled', 'queued',
|
||||
]
|
||||
|
||||
/**
|
||||
* 显示用的状态码换回后端 runs.status 认的值,给 api.runs.list({status}) 用。
|
||||
*
|
||||
* waiting、held、suspended 在后端都是 interrupted:按它查回来的是两种混在一起,
|
||||
* 要再用 resolveStatus(run.status, {pendingApproval: hasPendingApproval(approvals,
|
||||
* run.id)}) 在前端分开。节点才有的状态(idle / skipped / blocked / unreached)
|
||||
* 不是运行状态,返回 null。
|
||||
*/
|
||||
export function serverStatusOf(code: StatusCode): RunStatus | null {
|
||||
switch (code) {
|
||||
case 'waiting': case 'held': case 'suspended': return 'interrupted'
|
||||
case 'done': case 'succeeded': return 'succeeded'
|
||||
case 'queued': case 'running': case 'failed': case 'cancelled': return code
|
||||
default: return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 运行是不是还"活着"(会有新事件)。held / suspended 虽然后端写的是
|
||||
* interrupted,但不会自己动,不算。
|
||||
*/
|
||||
export function isLiveStatus(status: string | null | undefined, opts?: { pendingApproval?: boolean }): boolean {
|
||||
const code = resolveStatus(status, opts)
|
||||
return code === 'queued' || code === 'running' || code === 'waiting'
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* 术语表:界面文案里同一件事只有一种叫法。
|
||||
*
|
||||
* 之前「正式」一个词指三件事(发布等级、运行类别、出具档位),探索态有四五种
|
||||
* 叫法;「工作流 / 图 / 画布 / 流程」「审批 / 确认 / 介入 / 放行」混用,门禁报错
|
||||
* 引用的词界面上从没出现过。这三层(发布等级、运行类别、出具档位)是「受限动态
|
||||
* 编排」的骨架,彼此独立:一次正式运行完全可能降档出具。说法必须分开。
|
||||
*
|
||||
* 规则:
|
||||
* - 「工作流」指存下来的资产,「画布」指编辑区,「图」只在技术细节里出现
|
||||
* (执行图、走线)。
|
||||
* - 「运行」名词动词都用它;导航里的历史页叫「记录」。
|
||||
* - 人工节点叫「人工审批」,agent / tool / code 上的选项叫「审批策略」,等人
|
||||
* 处理的那张卡叫「审批卡」。
|
||||
* - 右栏叫「助手」;Copilot 只作为产品功能名出现在按钮提示里。
|
||||
*
|
||||
* 枚举值(formal / degraded / withheld 等)不动,只换显示。
|
||||
*/
|
||||
|
||||
import type { NodeType } from '../types'
|
||||
|
||||
export const TERMS = {
|
||||
workflow: '工作流',
|
||||
canvas: '画布',
|
||||
run: '运行',
|
||||
records: '记录',
|
||||
assistant: '助手',
|
||||
copilot: 'Copilot',
|
||||
humanNode: '人工审批',
|
||||
approvalPolicy: '审批策略',
|
||||
approvalCard: '审批卡',
|
||||
formalRun: '正式运行',
|
||||
exploratoryRun: '探索运行',
|
||||
} as const
|
||||
|
||||
/** 工作流状态(发布等级) */
|
||||
export const WORKFLOW_STATUS_LABEL: Record<'draft' | 'published' | 'governed', string> = {
|
||||
draft: '草稿',
|
||||
published: '已发布',
|
||||
governed: '受管',
|
||||
}
|
||||
|
||||
/** 发布弹窗里的选项说明:和工具栏 chip「已发布 v4」说法对得上 */
|
||||
export const WORKFLOW_STATUS_HINT: Record<'draft' | 'published' | 'governed', string> = {
|
||||
draft: '草稿 — 只能发起探索运行',
|
||||
published: '已发布 — 可发起正式运行',
|
||||
governed: '受管 — 可发起正式运行,并受治理门禁约束',
|
||||
}
|
||||
|
||||
/** 运行类别 */
|
||||
export const RUN_CLASS_LABEL: Record<'formal' | 'exploratory', string> = {
|
||||
formal: '正式运行',
|
||||
exploratory: '探索运行',
|
||||
}
|
||||
|
||||
/** 按钮上的运行类别:「正式运行 v3」 */
|
||||
export function runClassLabel(runClass: 'formal' | 'exploratory' | null | undefined, version?: number | null): string {
|
||||
if (runClass === 'formal') return version != null ? `正式运行 v${version}` : '正式运行'
|
||||
return '探索运行'
|
||||
}
|
||||
|
||||
/** 出具档位 */
|
||||
export const ISSUANCE_LABEL: Record<'formal' | 'degraded' | 'withheld', string> = {
|
||||
formal: '完整出具',
|
||||
degraded: '降档出具',
|
||||
withheld: '不予出具',
|
||||
}
|
||||
|
||||
export function issuanceLabel(tier: string | null | undefined): string {
|
||||
if (!tier) return '—'
|
||||
return (ISSUANCE_LABEL as Record<string, string>)[tier] ?? tier
|
||||
}
|
||||
|
||||
/**
|
||||
* 节点类型的中文名。画布节点库、运行流、门禁报错、GraphPeek 的 chip 都用这一张。
|
||||
*
|
||||
* 这是短名:节点库条目上的「成果 / 出具」是在短名后面补了一句用途,那是节点库
|
||||
* 自己的展示,不是另一个名字。后端 schema.py / governance.py 的报错也按这张表写。
|
||||
*/
|
||||
export const NODE_TYPE_LABEL: Record<NodeType, string> = {
|
||||
input: '输入',
|
||||
output: '成果',
|
||||
llm: '模型调用',
|
||||
agent: 'Agent',
|
||||
supervisor: '多 Agent 协作',
|
||||
tool: '调用工具',
|
||||
code: '沙箱代码',
|
||||
branch: '条件分支',
|
||||
loop: '循环',
|
||||
subgraph: '子工作流',
|
||||
memory: '长期记忆',
|
||||
retrieve: '知识检索',
|
||||
transform: '数据整形',
|
||||
human: '人工审批',
|
||||
validate: '结构校验',
|
||||
metrics: '口径卡',
|
||||
}
|
||||
|
||||
/** 与 decode.ts 里旧名字同名的出口,第二波改成从这里导入时不用改调用处 */
|
||||
export const TYPE_LABEL: Record<string, string> = NODE_TYPE_LABEL
|
||||
|
||||
/** 未知类型原样返回:Copilot 可能编出不存在的类型,显示原码比显示空白好查 */
|
||||
export function nodeTypeLabel(type: string | null | undefined): string {
|
||||
if (!type) return '—'
|
||||
return TYPE_LABEL[type] ?? type
|
||||
}
|
||||
|
||||
/** 审批策略的选项文字:agent / tool / code 三处共用一套说法 */
|
||||
export const APPROVAL_POLICY_LABEL: Record<'dangerous' | 'always' | 'never', string> = {
|
||||
dangerous: '仅危险工具需要审批',
|
||||
always: '每次调用都审批',
|
||||
never: '全部自动放行',
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* 主题偏好。
|
||||
*
|
||||
* 真源是后端 settings 的 ui.theme;localStorage 只是它的首帧缓存。index.html
|
||||
* 里那段内联脚本要在 React 起来之前就决定画深色还是浅色——等 /api/settings
|
||||
* 回来再切,浅色用户每次打开都会先看到一整帧深色。所以每次应用主题都顺手写回
|
||||
* 缓存,键名和取值必须和 index.html 那段脚本一致。
|
||||
*
|
||||
* 「跟随系统」就是不写 data-theme:index.css 的 prefers-color-scheme 分支接管,
|
||||
* 系统切换时页面跟着变,不需要这边监听 matchMedia。
|
||||
*/
|
||||
|
||||
export type ThemePref = 'system' | 'light' | 'dark'
|
||||
|
||||
export const THEME_STORAGE_KEY = 'agentlab.theme'
|
||||
|
||||
/** 后端和缓存里的值都可能是旧的或手改坏的,认不出来的一律当「跟随系统」 */
|
||||
export function normalizeTheme(value: unknown): ThemePref {
|
||||
return value === 'light' || value === 'dark' ? value : 'system'
|
||||
}
|
||||
|
||||
export function readThemePref(): ThemePref {
|
||||
try {
|
||||
return normalizeTheme(localStorage.getItem(THEME_STORAGE_KEY))
|
||||
} catch {
|
||||
return 'system'
|
||||
}
|
||||
}
|
||||
|
||||
export function applyTheme(pref: ThemePref): void {
|
||||
const root = document.documentElement
|
||||
// 切换这一帧关掉过渡:带 transition 的按钮、输入框会各自花 120ms 慢慢变色,
|
||||
// 整页看着像在闪。先让新配色在无过渡的状态下落定(读一次样式逼它重算),
|
||||
// 下一帧再把过渡还回去
|
||||
root.classList.add('theme-switching')
|
||||
if (pref === 'system') root.removeAttribute('data-theme')
|
||||
else root.setAttribute('data-theme', pref)
|
||||
void getComputedStyle(root).backgroundColor
|
||||
requestAnimationFrame(() => root.classList.remove('theme-switching'))
|
||||
try {
|
||||
localStorage.setItem(THEME_STORAGE_KEY, pref)
|
||||
} catch {
|
||||
// 隐私模式下写不进去:只是下次首帧跟随系统,等设置接口回来再纠正
|
||||
}
|
||||
}
|
||||
|
||||
/** 眼下实际画的是哪一套。「跟随系统」时要问系统,给主题切换按钮挑图标用 */
|
||||
export function resolvedTheme(): 'light' | 'dark' {
|
||||
const attr = document.documentElement.getAttribute('data-theme')
|
||||
if (attr === 'light' || attr === 'dark') return attr
|
||||
return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark'
|
||||
}
|
||||
Reference in New Issue
Block a user