全栈安全加固、性能提速与架构演进:连接池与沙箱止血、双路混合检索、多版本归档及前端分包治理

- 第一批(安全加固与生命周期止血):隔离测试宿主机密钥与 .env 泄漏;修复 SQLite 取消查询挂死、:memory: 连接池报错与 EngineCache 世代竞态;补齐运行与评测删除时的 Checkpointer 线程、Artifact 磁盘文件与无主附件回收;加固三套沙箱路径越界、进程组清理与 Seatbelt 数据目录隔离,封堵 SSRF IPv4-mapped IPv6 元数据绕过与响应体 OOM;修复推理模型多轮 reasoning_content、结构化输出 Token 漏计与缓存折扣计费
- 第二批(数据库/集群/问数提速与首屏分包):补齐核心表索引与 SQLite WAL 调优,列表接口按需 defer 大列,收敛启动扫描并打通跨进程 slot 槽位唤醒;优化跨源全局选表、哈希桶数字绑定、流式 CSV 导入及多方言分析算子;剥离首屏静态引入的 @xyflow/react 与全局样式(首屏主包降至 461.59 kB),补充流式 rAF 攒批、Store 精细订阅与表单无障碍绑定
- 第三批(架构演进与工程自动化闭环):记录库超挂接阈值历史版本自动增量归档至单库多表(解除 SQLite 10 库 ATTACH 硬上限);重构知识库为词面 BM25 与全集合归一化向量矩阵真·双路独立召回并支持游标分批重建;升级多方言感知 SQL 模板词法分析(E'...' / $$...$$ / q'[...]' / # / 嵌套注释)与 Decimal / bool / NaN 参数校验,消除 ledger 层对 api 路由层的反向依赖;拆分 3101 行 CaliberDrafts 页面为 7 个领域子模块,消除检查脚本本机路径硬编码并新增 GitHub Actions CI 门禁与三批回归测试套件
This commit is contained in:
ThearchyHelios
2026-11-13 14:51:36 +08:00
parent 09949fc8ac
commit eddeded2a4
106 changed files with 7178 additions and 3913 deletions
+28 -5
View File
@@ -12,9 +12,9 @@ import { useConversations } from './store/conversations'
import { personalAppsOn } from './pages/blueprints/shared'
import { Logo } from './components/Logo'
import {
CommandPalette, PAGES, ShortcutHelp, flushThemePref, openShortcutHelp, toggleCommandPalette, toggleNotify,
toggleTheme, usePages, useTheme, visiblePages, waitedFor,
} from './components/CommandPalette'
PAGES, flushThemePref, openShortcutHelp, toggleCommandPalette, toggleNotify,
toggleTheme, usePages, useShellOverlay, useTheme, visiblePages, waitedFor,
} from './components/shellCommands'
import { atLeast, authSettled, loginOn, loginUrl, needsLogin, prefsLocalOnly, principalName, useAuth } from './store/auth'
import { ErrorBoundary, Kbd, OfflineBanner, Spinner, StatusBadge, isComposing, toast, useTicker } from './components/ui'
import { applyTheme, normalizeTheme } from './lib/theme'
@@ -57,6 +57,16 @@ const NewAppStart = lazy(() => import('./pages/blueprints/NewAppStart').then((mo
const BlueprintPage = lazy(() => import('./pages/blueprints/BlueprintPage').then((module) => ({ default: module.BlueprintPage })))
const LoginPage = lazy(() => import('./pages/LoginPage').then((module) => ({ default: module.LoginPage })))
const SharePage = lazy(() => import('./pages/apps/SharePage').then((module) => ({ default: module.SharePage })))
const LazyShellOverlays = lazy(() => import('./components/CommandPalette').then((m) => ({
default: function Overlays() {
return (
<>
<m.CommandPalette />
<m.ShortcutHelp />
</>
)
},
})))
/** 启动时认人(/auth/me)最多等多久再取目录 */
const AUTH_WAIT_MS = 2500
@@ -230,8 +240,7 @@ function Shell() {
</div>
</main>
<CommandPalette />
<ShortcutHelp />
<ShellOverlays />
<ShellKeys />
<ShellSignals />
<LeaveBlocker />
@@ -239,6 +248,20 @@ function Shell() {
)
}
function ShellOverlays() {
const open = useShellOverlay()
const [everOpened, setEverOpened] = useState(false)
useEffect(() => {
if (open) setEverOpened(true)
}, [open])
if (!open && !everOpened) return null
return (
<Suspense fallback={null}>
<LazyShellOverlays />
</Suspense>
)
}
/** 首页:使用者(开了登录的 user 角色)落到应用首页,其余落到问数据 */
function HomeRedirect() {
const me = useAuth((s) => s.me)
+8 -3
View File
@@ -1205,6 +1205,7 @@ export function streamRun(
/** 握手连续失败(一次都没打开过就断了)几次 */
let refused = 0
let pollTimer: ReturnType<typeof setTimeout> | undefined
let wsRetryTimer: ReturnType<typeof setTimeout> | undefined
const finish = (status?: string) => {
if (closed) return
@@ -1253,7 +1254,8 @@ export function streamRun(
socket = new WebSocket(`${proto}://${location.host}/api/runs/${runId}/stream?after=${lastSeq}`)
socket.onmessage = (ev) => {
const event = parseBody(ev.data) as RunEvent & { type: string; status?: string }
const event = parseBody(ev.data) as (RunEvent & { type?: string; status?: string }) | null
if (!event || typeof event !== 'object' || typeof event.type !== 'string') return
if (event.type === 'stream.end') {
socket?.close()
// 新后端放在 data.status,老后端放在顶层 status
@@ -1261,7 +1263,7 @@ export function streamRun(
return
}
if (event.seq) lastSeq = Math.max(lastSeq, event.seq)
onEvent(event)
onEvent(event as RunEvent)
}
socket.onclose = () => {
if (closed) return
@@ -1273,12 +1275,14 @@ export function streamRun(
}
// 指数退避重连,最多等 5 秒
retry += 1
setTimeout(connect, Math.min(300 * 2 ** retry, 5000))
clearTimeout(wsRetryTimer)
wsRetryTimer = setTimeout(connect, Math.min(300 * 2 ** retry, 5000))
}
socket.onopen = () => {
opened = true
refused = 0
retry = 0
clearTimeout(wsRetryTimer)
report(true)
}
}
@@ -1287,6 +1291,7 @@ export function streamRun(
return () => {
closed = true
clearTimeout(pollTimer)
clearTimeout(wsRetryTimer)
socket?.close()
}
}
+5
View File
@@ -1,11 +1,14 @@
import './xyflow.css'
import './surface.css'
import {
createContext, memo, useCallback, useContext, useEffect, useId, useMemo, useRef, useState, type CSSProperties,
} from 'react'
import {
addEdge, applyEdgeChanges, applyNodeChanges,
Background, BackgroundVariant, ControlButton, Controls, MiniMap, ReactFlow, ReactFlowProvider,
useReactFlow, useStoreApi, ViewportPortal, type AriaLabelConfig, type Edge, type MiniMapNodeProps, type Viewport,
} from '@xyflow/react'
import { registerFlowHelpers } from '../store/flowChanges'
import { Crosshair, Lock, PanelRightOpen, Route as RouteIcon, Search } from 'lucide-react'
import clsx from 'clsx'
import { FlowEdge, MomentContext, RoutingContext, type EdgeRunState, type EdgeView } from './FlowEdge'
@@ -28,6 +31,8 @@ import { replayTraceCached } from '../run/useNodeView'
import { EDIT_LOCK_TEXT, useStudio, type FlowNode } from '../store/studio'
import type { NodeType } from '../types'
registerFlowHelpers({ addEdge, applyEdgeChanges, applyNodeChanges })
const nodeTypes = { card: NodeCard }
const edgeTypes = { flow: FlowEdge }
+1
View File
@@ -0,0 +1 @@
@import '@xyflow/react/dist/style.css' layer(xyflow);
+16 -213
View File
@@ -1,237 +1,40 @@
import { useEffect, useId, useMemo, useRef, useState, useSyncExternalStore } from 'react'
import type { ComponentType, KeyboardEvent as ReactKeyboardEvent, ReactNode } from 'react'
import { useEffect, useId, useMemo, useRef, useState } from 'react'
import type { KeyboardEvent as ReactKeyboardEvent, ReactNode } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import type { NavigateFunction } from 'react-router-dom'
import { create } from 'zustand'
import clsx from 'clsx'
import {
Bell, BellOff, BookOpen, CalendarClock, Database, FlaskConical, Gauge, History, Hourglass, Inbox, Keyboard, Layers,
LayoutGrid, MessageSquare, MessageSquarePlus, Monitor, Plus, Search, Settings, SunMoon, Workflow as WorkflowIcon, Wrench,
Bell, BellOff, Hourglass, Inbox, Keyboard,
MessageSquare, MessageSquarePlus, Monitor, Plus, Search, SunMoon, Workflow as WorkflowIcon,
} from 'lucide-react'
import { ApiError, api } from '../api/client'
import { api } from '../api/client'
import { hasPendingApproval, useCatalog } from '../store/catalog'
import { atLeast, loginOn, prefsLocalOnly, useAuth } from '../store/auth'
import { atLeast, useAuth } from '../store/auth'
import { useConversations } from '../store/conversations'
import { createWorkflow } from '../canvas/WorkflowPicker'
import { Kbd, Modal, StatusBadge, isComposing, toast } from './ui'
import { Kbd, Modal, StatusBadge, isComposing } from './ui'
import { Logo } from './Logo'
import { applyTheme, readThemePref, resolvedTheme } from '../lib/theme'
import type { ThemePref } from '../lib/theme'
import { isMac } from '../lib/keys'
import { formatDateTime, formatTime, parseServerTime, shortId } from '../lib/format'
import { statusLabel } from '../lib/status'
import { APP_TEXT, SCHEDULE_TEXT, WORKFLOW_STATUS_LABEL, runClassLabel, runName } from '../lib/terms'
import { EVAL_TEXT } from '../lib/termsEval'
import { errorMessage } from '../lib/errors'
import { disableNotify, enableNotify, notifySupported, useSignals } from '../lib/notify'
import { APP_TEXT, WORKFLOW_STATUS_LABEL, runClassLabel, runName } from '../lib/terms'
import { notifySupported, useSignals } from '../lib/notify'
import { canLeave, leavePass } from '../lib/leave'
import type { Run } from '../types'
import type { Principal } from '../typesApp'
import {
closeCommandPalette, closeShortcutHelp, newConversation, openShortcutHelp, setThemePref,
toggleNotify, toggleTheme, usePages, useShell, useTheme, waitedFor,
type PageDef,
} from './shellCommands'
/**
* 外壳的命令表:导航、⌘K 命令面板、快捷键说明共用这一份。
*
* 工作流、对话、运行都能深链,之前却只能点导航再翻列表去找;界面上还写着
* 一个根本不存在的 ⌥V。命令面板把"去哪、做什么"收到一个键盘入口里,快捷键
* 的显示和判定都出自同一份描述(lib/keys),提示写什么就真能按什么。
*/
export * from './shellCommands'
// -------------------------------------------------------------------------
// 页面表
// -------------------------------------------------------------------------
export interface PageDef {
to: string
label: string
/** 一句话说这一页是干什么的:导航悬停提示和命令面板里都用 */
hint: string
icon: ComponentType<{ size?: number; className?: string; strokeWidth?: number }>
shortcut: string
/** 命令面板的搜索词:英文路由名、旧叫法、同义词 */
keywords: string
}
// ⌥ + 数字切页:不和浏览器的 ⌘1–9(切标签页,页面拦不住)撞,也不和画布上的
// Backspace / Delete 以及各处输入框打架——「g c」这类两键序列就是栽在这上面
export const PAGES: PageDef[] = [
{ to: '/chat', label: '问数据', hint: '描述需求,自动接入数据源、构建工作流并给出结论', icon: MessageSquare, shortcut: 'Alt+1', keywords: 'chat ask 对话 提问 首页' },
{ to: '/studio', label: '编排', hint: '在画布上构建、调试和发布工作流', icon: FlaskConical, shortcut: 'Alt+2', keywords: 'studio canvas 画布 工作流 workflow' },
// 应用是后加的,紧跟在「编排」后面(用的是编排发布出来的东西);快捷键取下一个空着的 ⌥9,别的页一个都不动
{ to: '/apps', label: APP_TEXT.nav, hint: APP_TEXT.hint, icon: LayoutGrid, shortcut: 'Alt+9', keywords: 'apps app 应用 待办 inbox 流程 看板 发起' },
{ to: '/runs', label: '记录', hint: '每次运行的过程、成果和待审批', icon: History, shortcut: 'Alt+3', keywords: 'runs history 运行 运行记录 历史 审批' },
{ to: '/data', label: '数据', hint: '接入数据库和表格,供问数据和工作流查询', icon: Database, shortcut: 'Alt+4', keywords: 'data datasource 数据源 数据库 表格 excel csv' },
{ to: '/tools', label: '工具', hint: '工具库、沙箱试验台、自定义工具、MCP', icon: Wrench, shortcut: 'Alt+5', keywords: 'tools mcp sandbox 沙箱 函数' },
{ to: '/knowledge', label: '知识', hint: '知识库、长期记忆、方法论 Skill', icon: BookOpen, shortcut: 'Alt+6', keywords: 'knowledge kb memory skill 知识库 记忆 文档' },
// 后加的页排在设置前面,设置留在最底下、快捷键也不动:⌥7 按了好几个版本,改了等于让人重新记
{ to: '/schedules', label: SCHEDULE_TEXT.title, hint: SCHEDULE_TEXT.hint, icon: CalendarClock, shortcut: 'Alt+8', keywords: 'schedules schedule cron 定时 计划 周期 自动运行' },
// 评测(评测-D8):搭建者以上可见(使用者的页面表在 visiblePages 里收窄,用不着另判),同样排在设置前面;快捷键用最后一个空着的 ⌥0
{ to: '/evals', label: EVAL_TEXT.nav, hint: EVAL_TEXT.hint, icon: Gauge, shortcut: 'Alt+0', keywords: 'evals eval evaluation 评测 回归 题集 准确率 A/B 口径命中 重复度' },
// 口径目录:已发布口径的入口、依赖和试跑。后加的页,快捷键用没占用的 Alt+L
{ to: '/ledger/calibers', label: '口径', hint: '查看已发布口径的入口、依赖,并按参数试运行', icon: Layers, shortcut: 'Alt+L', keywords: 'caliber ledger 口径 指标 试运行 入口' },
{ to: '/settings', label: '设置', hint: '模型接入、偏好、运行环境', icon: Settings, shortcut: 'Alt+7', keywords: 'settings provider 模型 署名 主题 偏好' },
]
/**
* 这个人看得到哪几页。开了登录的使用者(user 角色)只有「应用」和「设置」(个人那几项),管理员开了「使用者可以问数据」
* 时加上问数据(Q2);搭建者以上和关登录时全部都在
*/
export function visiblePages(me: Principal | null | undefined): PageDef[] {
if (!loginOn(me) || atLeast(me, 'builder')) return PAGES
const keep = new Set(['/apps', '/settings', ...(me?.user_can_chat ? ['/chat'] : [])])
return PAGES.filter((p) => keep.has(p.to))
}
export function usePages(): PageDef[] {
const me = useAuth((s) => s.me)
return useMemo(() => visiblePages(me), [me])
}
// -------------------------------------------------------------------------
// 外壳浮层的开关
// -------------------------------------------------------------------------
const useShell = create<{ palette: boolean; help: boolean }>(() => ({ palette: false, help: false }))
export const openCommandPalette = () => useShell.setState({ palette: true, help: false })
export const closeCommandPalette = () => useShell.setState({ palette: false })
export const toggleCommandPalette = () => useShell.setState((s) => ({ palette: !s.palette, help: false }))
export const openShortcutHelp = () => useShell.setState({ help: true, palette: false })
export const closeShortcutHelp = () => useShell.setState({ help: false })
export const useShellOverlay = () => useShell((s) => s.palette || s.help)
// -------------------------------------------------------------------------
// 命令:导航和面板共用
// -------------------------------------------------------------------------
function subscribeTheme(cb: () => void): () => void {
// 设置页的下拉、这里的快速切换、系统换深浅,三条路都会改画出来的主题
const mo = new MutationObserver(cb)
mo.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] })
const mq = window.matchMedia('(prefers-color-scheme: light)')
mq.addEventListener('change', cb)
return () => {
mo.disconnect()
mq.removeEventListener('change', cb)
}
}
const themeSnapshot = () => `${readThemePref()}:${resolvedTheme()}`
/** 当前的主题偏好和实际画的那一套,谁改了都跟得上 */
export function useTheme(): { pref: ThemePref; resolved: 'light' | 'dark' } {
const snap = useSyncExternalStore(subscribeTheme, themeSnapshot, () => 'system:dark')
const [pref, resolved] = snap.split(':') as [ThemePref, 'light' | 'dark']
return { pref, resolved }
}
/** 最后一次选的主题,和它还没存进设置时的那个值(断线时换的) */
let latestTheme: ThemePref | null = null
let unsavedTheme: ThemePref | null = null
/**
* 换主题并存进设置。主题的真源是后端 settings 的 ui.theme(App 启动时按它
* 应用),只写 localStorage 的话下次打开又被改回去。
*
* 开了登录、又不是管理员(D-s):服务端的 ui 一组全站共用,改它要管理员,这里只存本机(applyTheme 已经写了
* localStorage),不发请求、不提示失败
*/
export async function setThemePref(pref: ThemePref): Promise<void> {
applyTheme(pref)
latestTheme = pref
// 设置页的下拉若开着,听这个事件同步,免得它手上的旧值被再存回去;App 听它
// 记下「人在这台设备上换过」,重连时就不再拿服务端的旧值翻回去
window.dispatchEvent(new CustomEvent('agentlab:theme', { detail: pref }))
if (prefsLocalOnly(useAuth.getState().me)) {
unsavedTheme = null
return
}
try {
await saveTheme(pref)
} catch (e) {
const offline = e instanceof ApiError && e.kind === 'network'
toast.warn(
offline ? '主题已在本设备生效,连接服务端后将自动保存到设置' : '主题仅在本设备生效,未能保存到设置',
{ detail: errorMessage(e), key: 'theme-save' },
)
}
}
/** PUT 按组整体替换,所以先取回 ui 这一组、只改 theme,别把画布吸附、自动保存这些冲掉 */
async function saveTheme(pref: ThemePref): Promise<void> {
try {
const current = await api.settings.get()
await api.settings.put({ ui: { ...(current?.ui ?? {}), theme: pref } })
if (latestTheme === pref) unsavedTheme = null
} catch (e) {
// 连点两下时先发的那次可能后失败:只记最后选的那个
if (latestTheme === pref) unsavedTheme = pref
throw e
}
}
/**
* 断线时换的主题当时没存上:后端恢复后补存。有要补的就返回 true,这时 App 不该
* 再去读服务端——那里还是换之前的旧值。补存又失败就留到下一次恢复,不再弹提示:
* 这一下不是人点的。
*/
export function flushThemePref(): boolean {
if (!unsavedTheme) return false
if (prefsLocalOnly(useAuth.getState().me)) {
unsavedTheme = null
return true
}
void saveTheme(unsavedTheme).catch(() => {})
return true
}
/** 在深浅之间翻:按眼下实际画的那一套翻,「跟随系统」时也一样 */
export const toggleTheme = () => void setThemePref(resolvedTheme() === 'dark' ? 'light' : 'dark')
export async function toggleNotify(): Promise<void> {
if (useSignals.getState().notify) {
disableNotify()
toast.info('后台提醒已关闭')
return
}
const permission = await enableNotify()
if (permission === 'granted') toast.ok('后台提醒已开启:标签页在后台时,运行结束、失败或有新的待审批、待办时发送系统通知')
else if (permission === 'denied') {
toast.warn('浏览器已拒绝通知权限', {
detail: '请在地址栏左侧的站点设置中将「通知」改为允许,然后重新打开此开关。',
key: 'notify-denied',
})
} else if (permission === 'unsupported') toast.warn('当前浏览器不支持系统通知')
}
export async function newConversation(navigate: NavigateFunction): Promise<void> {
// 先问再建:跳的时候才问的话,人点了「留下」,会话已经建出来了
if (!(await canLeave())) return
try {
const id = await useConversations.getState().create()
navigate(`/chat/${id}`, leavePass())
} catch (e) {
toast.error(e)
}
}
/** 同上:先问离开,再问名字、建工作流 */
/** 先问离开,再问名字、建工作流 */
async function newWorkflow(navigate: NavigateFunction): Promise<void> {
if (!(await canLeave())) return
// 和编排页的「新建工作流」同一条路:同名校验、画布上有没保存的改动先问
await createWorkflow((to, opts) => navigate(to, leavePass(opts)), () => useCatalog.getState().refresh())
}
/** 等了多久,给待审批用:「12 分钟」「3 小时」「8 天」。粗粒度就够,要的是一眼看出晾了多久 */
export function waitedFor(createdAt: string | null | undefined, now = Date.now()): string | null {
const d = parseServerTime(createdAt)
if (!d) return null
const mins = Math.max(0, Math.floor((now - d.getTime()) / 60_000))
if (mins < 1) return '不到 1 分钟'
if (mins < 60) return `${mins} 分钟`
const hours = Math.floor(mins / 60)
if (hours < 24) return `${hours} 小时`
return `${Math.floor(hours / 24)} 天`
}
// -------------------------------------------------------------------------
// ⌘K 命令面板
// -------------------------------------------------------------------------
+186
View File
@@ -0,0 +1,186 @@
import { useMemo, useSyncExternalStore } from 'react'
import type { ComponentType } from 'react'
import type { NavigateFunction } from 'react-router-dom'
import { create } from 'zustand'
import {
BookOpen, CalendarClock, Database, FlaskConical, Gauge, History, Layers,
LayoutGrid, MessageSquare, Settings, Wrench,
} from 'lucide-react'
import { ApiError, api } from '../api/client'
import { atLeast, loginOn, prefsLocalOnly, useAuth } from '../store/auth'
import { useConversations } from '../store/conversations'
import { toast } from './ui'
import { applyTheme, readThemePref, resolvedTheme } from '../lib/theme'
import type { ThemePref } from '../lib/theme'
import { parseServerTime } from '../lib/format'
import { APP_TEXT, SCHEDULE_TEXT } from '../lib/terms'
import { EVAL_TEXT } from '../lib/termsEval'
import { errorMessage } from '../lib/errors'
import { disableNotify, enableNotify, useSignals } from '../lib/notify'
import { canLeave, leavePass } from '../lib/leave'
import type { Principal } from '../typesApp'
export interface PageDef {
to: string
label: string
/** 一句话说这一页是干什么的:导航悬停提示和命令面板里都用 */
hint: string
icon: ComponentType<{ size?: number; className?: string; strokeWidth?: number }>
shortcut: string
/** 命令面板的搜索词:英文路由名、旧叫法、同义词 */
keywords: string
}
// ⌥ + 数字切页:不和浏览器的 ⌘1–9(切标签页,页面拦不住)撞,也不和画布上的
// Backspace / Delete 以及各处输入框打架——「g c」这类两键序列就是栽在这上面
export const PAGES: PageDef[] = [
{ to: '/chat', label: '问数据', hint: '描述需求,自动接入数据源、构建工作流并给出结论', icon: MessageSquare, shortcut: 'Alt+1', keywords: 'chat ask 对话 提问 首页' },
{ to: '/studio', label: '编排', hint: '在画布上构建、调试和发布工作流', icon: FlaskConical, shortcut: 'Alt+2', keywords: 'studio canvas 画布 工作流 workflow' },
// 应用是后加的,紧跟在「编排」后面(用的是编排发布出来的东西);快捷键取下一个空着的 ⌥9,别的页一个都不动
{ to: '/apps', label: APP_TEXT.nav, hint: APP_TEXT.hint, icon: LayoutGrid, shortcut: 'Alt+9', keywords: 'apps app 应用 待办 inbox 流程 看板 发起' },
{ to: '/runs', label: '记录', hint: '每次运行的过程、成果和待审批', icon: History, shortcut: 'Alt+3', keywords: 'runs history 运行 运行记录 历史 审批' },
{ to: '/data', label: '数据', hint: '接入数据库和表格,供问数据和工作流查询', icon: Database, shortcut: 'Alt+4', keywords: 'data datasource 数据源 数据库 表格 excel csv' },
{ to: '/tools', label: '工具', hint: '工具库、沙箱试验台、自定义工具、MCP', icon: Wrench, shortcut: 'Alt+5', keywords: 'tools mcp sandbox 沙箱 函数' },
{ to: '/knowledge', label: '知识', hint: '知识库、长期记忆、方法论 Skill', icon: BookOpen, shortcut: 'Alt+6', keywords: 'knowledge kb memory skill 知识库 记忆 文档' },
// 后加的页排在设置前面,设置留在最底下、快捷键也不动:⌥7 按了好几个版本,改了等于让人重新记
{ to: '/schedules', label: SCHEDULE_TEXT.title, hint: SCHEDULE_TEXT.hint, icon: CalendarClock, shortcut: 'Alt+8', keywords: 'schedules schedule cron 定时 计划 周期 自动运行' },
// 评测(评测-D8):搭建者以上可见(使用者的页面表在 visiblePages 里收窄,用不着另判),同样排在设置前面;快捷键用最后一个空着的 ⌥0
{ to: '/evals', label: EVAL_TEXT.nav, hint: EVAL_TEXT.hint, icon: Gauge, shortcut: 'Alt+0', keywords: 'evals eval evaluation 评测 回归 题集 准确率 A/B 口径命中 重复度' },
// 口径目录:已发布口径的入口、依赖和试跑。后加的页,快捷键用没占用的 Alt+L
{ to: '/ledger/calibers', label: '口径', hint: '查看已发布口径的入口、依赖,并按参数试运行', icon: Layers, shortcut: 'Alt+L', keywords: 'caliber ledger 口径 指标 试运行 入口' },
{ to: '/settings', label: '设置', hint: '模型接入、偏好、运行环境', icon: Settings, shortcut: 'Alt+7', keywords: 'settings provider 模型 署名 主题 偏好' },
]
/**
* 这个人看得到哪几页。开了登录的使用者(user 角色)只有「应用」和「设置」(个人那几项),管理员开了「使用者可以问数据」
* 时加上问数据(Q2);搭建者以上和关登录时全部都在
*/
export function visiblePages(me: Principal | null | undefined): PageDef[] {
if (!loginOn(me) || atLeast(me, 'builder')) return PAGES
const keep = new Set(['/apps', '/settings', ...(me?.user_can_chat ? ['/chat'] : [])])
return PAGES.filter((p) => keep.has(p.to))
}
export function usePages(): PageDef[] {
const me = useAuth((s) => s.me)
return useMemo(() => visiblePages(me), [me])
}
// -------------------------------------------------------------------------
// 外壳浮层的开关
// -------------------------------------------------------------------------
export const useShell = create<{ palette: boolean; help: boolean }>(() => ({ palette: false, help: false }))
export const openCommandPalette = () => useShell.setState({ palette: true, help: false })
export const closeCommandPalette = () => useShell.setState({ palette: false })
export const toggleCommandPalette = () => useShell.setState((s) => ({ palette: !s.palette, help: false }))
export const openShortcutHelp = () => useShell.setState({ help: true, palette: false })
export const closeShortcutHelp = () => useShell.setState({ help: false })
export const useShellOverlay = () => useShell((s) => s.palette || s.help)
// -------------------------------------------------------------------------
// 命令:导航和面板共用
// -------------------------------------------------------------------------
function subscribeTheme(cb: () => void): () => void {
const mo = new MutationObserver(cb)
mo.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] })
const mq = window.matchMedia('(prefers-color-scheme: light)')
mq.addEventListener('change', cb)
return () => {
mo.disconnect()
mq.removeEventListener('change', cb)
}
}
const themeSnapshot = () => `${readThemePref()}:${resolvedTheme()}`
/** 当前的主题偏好和实际画的那一套,谁改了都跟得上 */
export function useTheme(): { pref: ThemePref; resolved: 'light' | 'dark' } {
const snap = useSyncExternalStore(subscribeTheme, themeSnapshot, () => 'system:dark')
const [pref, resolved] = snap.split(':') as [ThemePref, 'light' | 'dark']
return { pref, resolved }
}
/** 最后一次选的主题,和它还没存进设置时的那个值(断线时换的) */
let latestTheme: ThemePref | null = null
let unsavedTheme: ThemePref | null = null
export async function setThemePref(pref: ThemePref): Promise<void> {
applyTheme(pref)
latestTheme = pref
window.dispatchEvent(new CustomEvent('agentlab:theme', { detail: pref }))
if (prefsLocalOnly(useAuth.getState().me)) {
unsavedTheme = null
return
}
try {
await saveTheme(pref)
} catch (e) {
const offline = e instanceof ApiError && e.kind === 'network'
toast.warn(
offline ? '主题已在本设备生效,连接服务端后将自动保存到设置' : '主题仅在本设备生效,未能保存到设置',
{ detail: errorMessage(e), key: 'theme-save' },
)
}
}
async function saveTheme(pref: ThemePref): Promise<void> {
try {
const current = await api.settings.get()
await api.settings.put({ ui: { ...(current?.ui ?? {}), theme: pref } })
if (latestTheme === pref) unsavedTheme = null
} catch (e) {
if (latestTheme === pref) unsavedTheme = pref
throw e
}
}
export function flushThemePref(): boolean {
if (!unsavedTheme) return false
if (prefsLocalOnly(useAuth.getState().me)) {
unsavedTheme = null
return true
}
void saveTheme(unsavedTheme).catch(() => {})
return true
}
export const toggleTheme = () => void setThemePref(resolvedTheme() === 'dark' ? 'light' : 'dark')
export async function toggleNotify(): Promise<void> {
if (useSignals.getState().notify) {
disableNotify()
toast.info('后台提醒已关闭')
return
}
const permission = await enableNotify()
if (permission === 'granted') toast.ok('后台提醒已开启:标签页在后台时,运行结束、失败或有新的待审批、待办时发送系统通知')
else if (permission === 'denied') {
toast.warn('浏览器已拒绝通知权限', {
detail: '请在地址栏左侧的站点设置中将「通知」改为允许,然后重新打开此开关。',
key: 'notify-denied',
})
} else if (permission === 'unsupported') toast.warn('当前浏览器不支持系统通知')
}
export async function newConversation(navigate: NavigateFunction): Promise<void> {
if (!(await canLeave())) return
try {
const id = await useConversations.getState().create()
navigate(`/chat/${id}`, leavePass())
} catch (e) {
toast.error(e)
}
}
export function waitedFor(createdAt: string | null | undefined, now = Date.now()): string | null {
const d = parseServerTime(createdAt)
if (!d) return null
const mins = Math.max(0, Math.floor((now - d.getTime()) / 60_000))
if (mins < 1) return '不到 1 分钟'
if (mins < 60) return `${mins} 分钟`
const hours = Math.floor(mins / 60)
if (hours < 24) return `${hours} 小时`
return `${Math.floor(hours / 24)} 天`
}
+35 -4
View File
@@ -1,4 +1,7 @@
import { Component, useCallback, useEffect, useId, useLayoutEffect, useRef, useState, useSyncExternalStore } from 'react'
import {
cloneElement, Component, isValidElement, useCallback, useEffect, useId, useLayoutEffect, useRef, useState,
useSyncExternalStore,
} from 'react'
import { useLocation, useNavigate, useParams } from 'react-router-dom'
import type {
ButtonHTMLAttributes, CSSProperties, ErrorInfo, KeyboardEvent as ReactKeyboardEvent, ReactNode, RefObject,
@@ -1514,15 +1517,43 @@ export function Field({ label, htmlFor, hint, error, required, children, classNa
const hintId = `${id}-hint`
const errorId = `${id}-error`
const describedBy = error ? errorId : hint ? hintId : undefined
const invalid = error ? true : undefined
const bindControl = (node: ReactNode): { node: ReactNode; bound: boolean } => {
if (isValidElement<Record<string, any>>(node)
&& (node.type === 'input' || node.type === 'select' || node.type === 'textarea')
&& node.props.id == null) {
return {
bound: true,
node: cloneElement(node, {
id,
'aria-describedby': node.props['aria-describedby'] ?? describedBy,
'aria-invalid': node.props['aria-invalid'] ?? invalid,
}),
}
}
return { node, bound: false }
}
let content: ReactNode
if (typeof children === 'function') {
content = children({ id, 'aria-describedby': describedBy, 'aria-invalid': invalid })
} else if (Array.isArray(children)) {
let bound = false
content = children.map((child) => {
if (bound) return child
const res = bindControl(child)
bound = res.bound
return res.node
})
} else {
content = bindControl(children).node
}
return (
<div className={clsx('min-w-0', className)}>
<label className="label" htmlFor={id}>
{label}
{required && <span className="ml-0.5 text-[var(--err)]" aria-hidden>*</span>}
</label>
{typeof children === 'function'
? children({ id, 'aria-describedby': describedBy, 'aria-invalid': error ? true : undefined })
: children}
{content}
{error
? <div id={errorId} className="mt-1 text-2xs leading-relaxed text-[var(--err)]">{error}</div>
: hint
+1
View File
@@ -1,3 +1,4 @@
import '../../canvas/xyflow.css'
import { useState, type JSX } from 'react'
import { ReactFlow, ReactFlowProvider } from '@xyflow/react'
import { Inspector } from '../../canvas/Inspector'
+1
View File
@@ -1,3 +1,4 @@
import '../../canvas/xyflow.css'
import { useState } from 'react'
import type { JSX } from 'react'
import { ReactFlow, ReactFlowProvider } from '@xyflow/react'
+1 -1
View File
@@ -1,5 +1,5 @@
@layer theme, base, xyflow, components, utilities;
@import 'tailwindcss';
@import '@xyflow/react/dist/style.css';
/* ==========================================================================
主题 token。深色是默认(长时间盯画布,深色更省眼),浅色由 data-theme 切换;
+1
View File
@@ -6335,6 +6335,7 @@ export const TOOL_ENDPOINT_TEXT = {
query: '查询参数(JSON,可插值)',
body: '请求体(JSON,可插值)',
noEndpoints: '还没有登记的端点,在「工具 → 端点」中登记',
loadFailed: '端点列表加载失败,已保留当前绑定的端点',
}
/**
+17 -9
View File
@@ -48,7 +48,13 @@ import {
* dense 一个开关。两边各写一套的话,同一次运行在两个页面会讲出不同的故事。
*/
export function ChatPage() {
const { ask, stop, load, hydrate, recheck, setScope, setDepth } = useChat()
const ask = useChat((s) => s.ask)
const stop = useChat((s) => s.stop)
const load = useChat((s) => s.load)
const hydrate = useChat((s) => s.hydrate)
const recheck = useChat((s) => s.recheck)
const setScope = useChat((s) => s.setScope)
const setDepth = useChat((s) => s.setDepth)
const depth = useChat((s) => s.depth)
const { conversationId } = useParams()
const navigate = useNavigate()
@@ -60,7 +66,12 @@ export function ChatPage() {
const turns = useChat((s) => (currentId ? s.byConversation[currentId] : undefined))
const loadState = useChat((s) => (currentId ? s.loadState[currentId] : undefined))
const loadError = useChat((s) => (currentId ? s.loadError[currentId] : undefined))
const byConversation = useChat((s) => s.byConversation)
const elsewhereId = useChat((s) => {
for (const [id, ts] of Object.entries(s.byConversation)) {
if (id !== currentId && isBusy(ts)) return id
}
return null
})
const backend = useCatalog((s) => s.backend)
// 在回收站里的对话可以点开看,但不能接着问:问了它也还在回收站里,左栏找不到
const trashed = useConversations((s) => (currentId ? s.trash.find((c) => c.id === currentId) : undefined))
@@ -147,13 +158,10 @@ export function ChatPage() {
const trashBusy = !!trashed && stillRunning(trashed, turns)
// 另一个会话在跑:这里照样能问(各跑各的),但得让人知道那边没停
const elsewhere = useMemo(() => {
for (const [id, ts] of Object.entries(byConversation)) {
if (id !== currentId && isBusy(ts)) {
return { id, title: list.find((c) => c.id === id)?.title || ts[ts.length - 1].question }
}
}
return null
}, [byConversation, currentId, list])
if (!elsewhereId) return null
const ts = useChat.getState().byConversation[elsewhereId]
return { id: elsewhereId, title: list.find((c) => c.id === elsewhereId)?.title || ts?.[ts.length - 1]?.question || '' }
}, [elsewhereId, list])
const blocked = loadState === 'loading' ? '正在加载对话历史…'
: loadState === 'error' ? '对话历史加载失败,请点击上方的「重试」'
+35 -11
View File
@@ -1,5 +1,6 @@
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
import { useNavigate, type NavigateFunction } from 'react-router-dom'
import { useShallow } from 'zustand/react/shallow'
import {
ArchiveRestore, ArrowLeft, Check, MessageSquarePlus, PanelLeftClose, PanelLeftOpen, Pencil, RotateCw, Search,
Trash2, X,
@@ -30,9 +31,19 @@ import type { Conversation } from '../types'
* 对话,过了那几秒就该还有地方找回来。真正的删除只在回收站里做,而且要确认。
*/
export function ConversationList() {
const { list, trash, showTrash, currentId, loading, error, load, create, rename, archive, restore, setShowTrash } =
useConversations()
const byConversation = useChat((s) => s.byConversation)
const list = useConversations((s) => s.list)
const trash = useConversations((s) => s.trash)
const showTrash = useConversations((s) => s.showTrash)
const currentId = useConversations((s) => s.currentId)
const loading = useConversations((s) => s.loading)
const error = useConversations((s) => s.error)
const load = useConversations((s) => s.load)
const create = useConversations((s) => s.create)
const rename = useConversations((s) => s.rename)
const archive = useConversations((s) => s.archive)
const restore = useConversations((s) => s.restore)
const setShowTrash = useConversations((s) => s.setShowTrash)
const runtimeByConv = useConversationRuntime()
const forget = useChat((s) => s.forget)
const navigate = useNavigate()
// 相对时间和分组一分钟重算一次就够:「刚刚」「3 分钟前」不需要更细
@@ -164,10 +175,10 @@ export function ConversationList() {
<section key={g.label} aria-label={g.label}>
<div className="px-2 pb-0.5 pt-2.5 text-2xs text-faint">{g.label}</div>
{g.items.map((c) => {
const turns = byConversation[c.id]
// 取回内存的以内存为准(它是这一刻的);没打开过的看列表接口带来的最后一轮状态
const live = turns ? liveStatus(turns) : listStatus(c)
const running = stillRunning(c, turns)
const mem = runtimeByConv[c.id]
const live = mem !== undefined ? (mem.split(':')[0] || null) : listStatus(c)
const running = mem !== undefined ? mem.endsWith(':1') : c.last_status === 'running'
const active = c.id === currentId
const when = c.last_active_at ?? c.created_at
return (
@@ -312,9 +323,12 @@ function TrashView({ items, currentId, onBack }: {
}) {
const navigate = useNavigate()
const emptyTrash = useConversations((s) => s.emptyTrash)
const byConversation = useChat((s) => s.byConversation)
const runtimeByConv = useConversationRuntime()
const sorted = useMemo(() => [...items].sort((a, b) => stamp(b) - stamp(a)), [items])
const idle = items.filter((c) => !stillRunning(c, byConversation[c.id]))
const idle = items.filter((c) => {
const mem = runtimeByConv[c.id]
return mem !== undefined ? !mem.endsWith(':1') : c.last_status !== 'running'
})
const emptyAll = async () => {
// 确认框开着的时候谁又跑起来了,以点确认那一刻为准,所以挑两次
@@ -376,9 +390,9 @@ function TrashView({ items, currentId, onBack }: {
const active = c.id === currentId
const title = c.title || '新对话'
const when = c.last_active_at ?? c.created_at
const turns = byConversation[c.id]
const live = turns ? liveStatus(turns) : listStatus(c)
const running = stillRunning(c, turns)
const mem = runtimeByConv[c.id]
const live = mem !== undefined ? (mem.split(':')[0] || null) : listStatus(c)
const running = mem !== undefined ? mem.endsWith(':1') : c.last_status === 'running'
return (
<div key={c.id}
className={clsx('group relative mb-0.5 rounded-lg text-xs',
@@ -503,6 +517,16 @@ export function stillRunning(c: Conversation, turns: ChatTurn[] | undefined): bo
return turns ? !!busyTurn(turns) : c.last_status === 'running'
}
function useConversationRuntime(): Record<string, string> {
return useChat(useShallow((s) => {
const out: Record<string, string> = {}
for (const [id, turns] of Object.entries(s.byConversation)) {
out[id] = `${liveStatus(turns) ?? ''}:${busyTurn(turns) ? 1 : 0}`
}
return out
}))
}
export const RUNNING_NO_DELETE = '该对话正在运行,请先停止再删除'
const titles = (list: Conversation[]) => list.map((c) => `「${c.title || '新对话'}」`).join('、')
+1 -1
View File
@@ -1,7 +1,7 @@
import { Link, useLocation, useNavigate } from 'react-router-dom'
import { ArrowLeft, Search } from 'lucide-react'
import { Kbd } from '../components/ui'
import { openCommandPalette } from '../components/CommandPalette'
import { openCommandPalette } from '../components/shellCommands'
import { usePageTitle } from '../lib/notify'
/**
+1 -1
View File
@@ -12,7 +12,7 @@ import {
confirmDialog, DeleteButton, EmptyState, ErrorState, Field, HealthPill, isComposing, Modal, PageHeader,
promptDialog, SectionBar, Skeleton, Spinner, TabPanel, Tabs, toast, useRadioGroup, useTabRoute,
} from '../components/ui'
import { setThemePref, useTheme } from '../components/CommandPalette'
import { setThemePref, useTheme } from '../components/shellCommands'
import { errorMessage } from '../lib/errors'
import { formatNumber, shortLabel } from '../lib/format'
import { checkHealth, forgetHealth, healthFromServer, setHealth, useHealth } from '../lib/health'
+20 -10
View File
@@ -631,7 +631,7 @@ function CustomTools() {
const [rows, setRows] = useState<any[] | null>(null)
const [error, setError] = useState<unknown>(null)
const [editing, setEditing] = useState<any | null>(null)
const endpoints = useEndpoints()
const { items: endpoints } = useEndpoints()
// ?edit=<工具名>:运行失败说「参数定义写坏了」时直接打开那一个的编辑框,不用再翻列表。
// 读完就从地址里摘掉,免得关了弹窗、刷新一下又弹出来
@@ -774,7 +774,7 @@ function CustomToolEditor({ row, onClose, onSaved }: { row: any; onClose: () =>
const nameError = form.name && !TOOL_NAME_RE.test(form.name) ? '只能包含英文字母、数字和下划线,且不能以数字开头' : null
const dirty = JSON.stringify(form) !== JSON.stringify(initial)
// 绑定登记的端点(§3.9):config 是 {endpoint, method, path, query, body},只填路径,地址和认证头由端点按环境提供
const endpoints = useEndpoints()
const { items: endpoints, failed: endpointsFailed } = useEndpoints()
const bound = form.kind === 'http' && !!form.config.endpoint
const missingConfig = [
form.kind === 'http' && !bound && !form.config.url && 'URL',
@@ -892,13 +892,15 @@ function CustomToolEditor({ row, onClose, onSaved }: { row: any; onClose: () =>
</div>
{form.kind === 'http' && (
<Field label={TOOL_ENDPOINT_TEXT.bind} hint={endpoints && !endpoints.length ? TOOL_ENDPOINT_TEXT.noEndpoints : TOOL_ENDPOINT_TEXT.hint}
<Field label={TOOL_ENDPOINT_TEXT.bind}
hint={endpointsFailed ? TOOL_ENDPOINT_TEXT.loadFailed : endpoints && !endpoints.length ? TOOL_ENDPOINT_TEXT.noEndpoints : TOOL_ENDPOINT_TEXT.hint}
error={endpointMissing ? TOOL_ENDPOINT_TEXT.missing(String(form.config.endpoint)) : undefined}>
{(p) => (
<select {...p} className="field" value={endpointValue} onChange={(e) => bindEndpoint(e.target.value)}
data-custom-tool-endpoint="">
<option value="">{TOOL_ENDPOINT_TEXT.none}</option>
{(endpoints ?? []).map((ep) => <option key={ep.id} value={ep.id}>{ep.name}</option>)}
{bound && !endpoints && <option value={endpointValue}>{String(form.config.endpoint)}</option>}
{endpointMissing && <option value={endpointValue} disabled>{String(form.config.endpoint)}</option>}
</select>
)}
@@ -1019,11 +1021,16 @@ function mcpServerRecord(row: any): HealthRecord | undefined {
const mcpConnection = (f: any) => JSON.stringify([f.transport, f.command.trim(), f.args.trim(), f.env ?? {}, f.url.trim(),
f.headers ?? {}, f.endpoint_id ?? null])
/** 登记的端点(绑定用)。取不到时为空列表,照样能不绑定 */
function useEndpoints(): EndpointRow[] | null {
const [rows, setRows] = useState<EndpointRow[] | null>(null)
useEffect(() => { api.endpoints.list().then(({ items }) => setRows(items), () => setRows([])) }, [])
return rows
/** 登记的端点(绑定用)。加载失败时保留 null,避免把已绑定的端点误报为已删除 */
function useEndpoints(): { items: EndpointRow[] | null; failed: boolean } {
const [state, setState] = useState<{ items: EndpointRow[] | null; failed: boolean }>({ items: null, failed: false })
useEffect(() => {
api.endpoints.list().then(
({ items }) => setState({ items, failed: false }),
() => setState({ items: null, failed: true }),
)
}, [])
return state
}
/**
@@ -1242,7 +1249,7 @@ function McpEditor({ row, onClose, onSaved }: {
onSaved: (name: string, reconnected: boolean) => void
}) {
const admin = useAtLeast('admin')
const endpoints = useEndpoints()
const { items: endpoints, failed: endpointsFailed } = useEndpoints()
const [initial] = useState(() => ({
name: row.name ?? '', transport: row.transport ?? 'stdio', command: row.command ?? '',
args: (row.args ?? []).join(' '), env: row.env ?? {}, url: row.url ?? '', enabled: row.enabled ?? true,
@@ -1326,12 +1333,15 @@ function McpEditor({ row, onClose, onSaved }: {
</>
) : (
<>
<Field label={MCP_AUTH_TEXT.endpoint} hint={MCP_AUTH_TEXT.endpointHint}>
<Field label={MCP_AUTH_TEXT.endpoint} hint={endpointsFailed ? TOOL_ENDPOINT_TEXT.loadFailed : MCP_AUTH_TEXT.endpointHint}>
{(p) => (
<select {...p} className="field" value={form.endpoint_id ?? ''} data-mcp-endpoint=""
onChange={(e) => setForm({ ...form, endpoint_id: e.target.value || null })}>
<option value="">{MCP_AUTH_TEXT.endpointNone}</option>
{(endpoints ?? []).map((ep) => <option key={ep.id} value={ep.id}>{ep.name}</option>)}
{form.endpoint_id && !endpoints && (
<option value={form.endpoint_id}>{form.endpoint_id}</option>
)}
{form.endpoint_id && endpoints && !endpoints.some((ep) => ep.id === form.endpoint_id) && (
<option value={form.endpoint_id} disabled>{TOOL_ENDPOINT_TEXT.missing(form.endpoint_id)}</option>
)}
@@ -1143,6 +1143,13 @@ export function RecipePanel({ recipe, problems, units, candidates, labelOptions,
const [assigned, setAssigned] = useState<{ map: Map<string, RecipeProblem[]>; top: RecipeProblem[] }>({ map: new Map(), top: [] })
const sig = useRef('')
useLayoutEffect(() => {
if (!problems.length) {
if (sig.current) {
sig.current = ''
setAssigned({ map: new Map(), top: [] })
}
return
}
const paths = [...registry.current]
const map = new Map<string, RecipeProblem[]>()
const top: RecipeProblem[] = []
+1 -1
View File
@@ -230,7 +230,7 @@ export function CaliberCatalog() {
</div>
<label className="relative min-w-[240px] flex-1 sm:max-w-sm">
<Search size={13} className="pointer-events-none absolute left-2.5 top-1/2 -translate-y-1/2 text-faint" aria-hidden />
<input className="input w-full pl-8" value={query} onChange={(e) => setQuery(e.target.value)}
<input className="field w-full pl-8" value={query} onChange={(e) => setQuery(e.target.value)}
placeholder="按指标名、标识、物理表或工作流查找" aria-label="查找口径" />
</label>
</div>
File diff suppressed because it is too large Load Diff
@@ -420,18 +420,18 @@ export function MetricEditorModal({
<div className="grid gap-3 sm:grid-cols-2">
<Field label="指标中文名称" required>
<input className="input w-full" value={name} onChange={(e) => setName(e.target.value)}
<input className="field w-full" value={name} onChange={(e) => setName(e.target.value)}
placeholder="例如:设备综合效率 OEE(跨表精算)" />
</Field>
<Field label="唯一英文标识" required hint="小写字母、数字与下划线,供问数工具调用">
<input className="input mono w-full" value={key} onChange={(e) => setKey(e.target.value)}
<input className="field mono w-full" value={key} onChange={(e) => setKey(e.target.value)}
placeholder="例如:oee_multi_table" />
</Field>
</div>
<div className="grid gap-3 sm:grid-cols-3">
<Field label="所属数据源" required>
<select className="input w-full" value={sourceId} onChange={(e) => { setSourceId(e.target.value); setTableName('') }}>
<select className="field w-full" value={sourceId} onChange={(e) => { setSourceId(e.target.value); setTableName('') }}>
<option value="">请选择数据源</option>
{sources.map((s) => (
<option key={s.id} value={s.id}>{s.name}</option>
@@ -441,19 +441,19 @@ export function MetricEditorModal({
<Field label={isTemplate ? '主事实表(可选锚点)' : '物理表名'} required={!isTemplate}
hint={isTemplate ? '留空时自动从模板首张物理表识别' : undefined}>
{tables.length > 0 ? (
<select className="input mono w-full" value={tableName} onChange={(e) => setTableName(e.target.value)}>
<select className="field mono w-full" value={tableName} onChange={(e) => setTableName(e.target.value)}>
<option value="">{isTemplate ? '(自动识别主物理表)' : '请选择物理表'}</option>
{tables.map((t) => (
<option key={t} value={t}>{t}</option>
))}
</select>
) : (
<input className="input mono w-full" value={tableName} onChange={(e) => setTableName(e.target.value)}
<input className="field mono w-full" value={tableName} onChange={(e) => setTableName(e.target.value)}
placeholder="物理表名" />
)}
</Field>
<Field label="单位">
<input className="input w-full" value={unit} onChange={(e) => setUnit(e.target.value)}
<input className="field w-full" value={unit} onChange={(e) => setUnit(e.target.value)}
placeholder="例如:% / 秒 / 人次 / 元" />
</Field>
</div>
@@ -466,7 +466,7 @@ export function MetricEditorModal({
{!isTemplate ? (
<Field label="聚合 SQL 表达式" required hint="单表聚合表达式(禁止嵌套查询),点击下方列名可快速填入 SUM(列名)">
<input className="input mono w-full" value={sqlExpression} onChange={(e) => setSqlExpression(e.target.value)}
<input className="field mono w-full" value={sqlExpression} onChange={(e) => setSqlExpression(e.target.value)}
placeholder="例如:SUM(total_sys) 或 ROUND(SUM(good_qty) * 100.0 / NULLIF(SUM(total_qty), 0), 2)" />
{columns.length > 0 && (
<div className="mt-1.5 flex max-h-20 flex-wrap gap-1 overflow-y-auto">
@@ -510,7 +510,7 @@ export function MetricEditorModal({
ref={tplRef}
rows={8}
data-metric-sql-template=""
className="input mono w-full resize-y py-2 text-xs leading-relaxed"
className="field mono w-full resize-y py-2 text-xs leading-relaxed"
value={sqlTemplate}
onChange={(e) => setSqlTemplate(e.target.value)}
placeholder={'WITH mj AS (\n SELECT prod_code, AVG(mjxs) AS mjxs FROM mes_jzhmjxs GROUP BY prod_code\n)\nSELECT\n {{select_dims}}\n ROUND(SUM(s.good_qty * COALESCE(mj.mjxs, 0.5)) * 100.0 / NULLIF(SUM(s.total_qty), 0), 2) AS oee_val\nFROM mes_shift_daily s\nLEFT JOIN mj ON mj.prod_code = s.prod_code\nWHERE 1=1 {{and_where}}\n{{group_by}}\n{{order_by}}'}
@@ -521,23 +521,23 @@ export function MetricEditorModal({
<div className="grid gap-3 sm:grid-cols-3">
<Field label="业务时间列" hint={isTemplate ? '多表请带主表别名前缀,如 s.stat_date' : '用于按日期筛选与趋势分组'}>
{!isTemplate && columns.length > 0 ? (
<select className="input mono w-full" value={dateColumn} onChange={(e) => setDateColumn(e.target.value)}>
<select className="field mono w-full" value={dateColumn} onChange={(e) => setDateColumn(e.target.value)}>
<option value="">(无时间列)</option>
{columns.map((c) => (
<option key={c.name} value={c.name}>{c.name}{c.label ? `(${c.label})` : ''}</option>
))}
</select>
) : (
<input className="input mono w-full" value={dateColumn} onChange={(e) => setDateColumn(e.target.value)}
<input className="field mono w-full" value={dateColumn} onChange={(e) => setDateColumn(e.target.value)}
placeholder={isTemplate ? '例如:s.stat_date' : '例如:stat_date'} />
)}
</Field>
<Field label="默认有效过滤条件" hint="自动拼入 WHERE 子句">
<input className="input mono w-full" value={filterSql} onChange={(e) => setFilterSql(e.target.value)}
<input className="field mono w-full" value={filterSql} onChange={(e) => setFilterSql(e.target.value)}
placeholder={isTemplate ? '例如:s.is_deleted = 0' : '例如:status = 1 AND is_deleted = 0'} />
</Field>
<Field label="默认时间粒度">
<select className="input w-full" value={defaultTimeGrain} onChange={(e) => setDefaultTimeGrain(e.target.value)}>
<select className="field w-full" value={defaultTimeGrain} onChange={(e) => setDefaultTimeGrain(e.target.value)}>
<option value="day">按日(day)</option>
<option value="month">按月(month)</option>
<option value="hour">按小时(hour)</option>
@@ -547,11 +547,11 @@ export function MetricEditorModal({
<div className="grid gap-3 sm:grid-cols-2">
<Field label="口语别名(顿号或逗号分隔)" hint="帮助问数快速直查毫秒级命中,如:OEE、综合效率">
<input className="input w-full" value={aliasesText} onChange={(e) => setAliasesText(e.target.value)}
<input className="field w-full" value={aliasesText} onChange={(e) => setAliasesText(e.target.value)}
placeholder="例如:OEE、设备综合效率、跨表OEE" />
</Field>
<Field label="业务口径说明与判异提示" hint="统计范围、兜底系数、物理红线等说明">
<input className="input w-full" value={description} onChange={(e) => setDescription(e.target.value)}
<input className="field w-full" value={description} onChange={(e) => setDescription(e.target.value)}
placeholder="例如:无模具系数时按 0.5 兜底;超过 200% 视为异常数据" />
</Field>
</div>
@@ -575,12 +575,12 @@ export function MetricEditorModal({
<div className="space-y-1.5">
{dimensions.map((dim, idx) => (
<div key={idx} className="grid grid-cols-12 items-center gap-1.5">
<input className="input mono col-span-3 text-xs" placeholder="维度键(如 line_code)" value={dim.key}
<input className="field mono col-span-3 text-xs" placeholder="维度键(如 line_code)" value={dim.key}
onChange={(e) => setDimensions((ds) => ds.map((x, i) => (i === idx ? { ...x, key: e.target.value } : x)))} />
<input className="input col-span-3 text-xs" placeholder="中文名(如 产线)" value={dim.label}
<input className="field col-span-3 text-xs" placeholder="中文名(如 产线)" value={dim.label}
onChange={(e) => setDimensions((ds) => ds.map((x, i) => (i === idx ? { ...x, label: e.target.value } : x)))} />
{!isTemplate && columns.length > 0 ? (
<select className="input mono col-span-3 text-xs" value={dim.column}
<select className="field mono col-span-3 text-xs" value={dim.column}
onChange={(e) => setDimensions((ds) => ds.map((x, i) => (i === idx ? { ...x, column: e.target.value } : x)))}>
<option value="">选择物理列</option>
{columns.map((c) => (
@@ -588,10 +588,10 @@ export function MetricEditorModal({
))}
</select>
) : (
<input className="input mono col-span-3 text-xs" placeholder={isTemplate ? 's.line_code' : '物理列名'} value={dim.column}
<input className="field mono col-span-3 text-xs" placeholder={isTemplate ? 's.line_code' : '物理列名'} value={dim.column}
onChange={(e) => setDimensions((ds) => ds.map((x, i) => (i === idx ? { ...x, column: e.target.value } : x)))} />
)}
<select className="input col-span-2 text-xs" value={dim.entity_key ?? ''}
<select className="field col-span-2 text-xs" value={dim.entity_key ?? ''}
title="关联标准业务实体后,按名称筛选将自动转换为该数据源物理编码"
onChange={(e) => setDimensions((ds) => ds.map((x, i) => (i === idx ? { ...x, entity_key: e.target.value } : x)))}>
<option value="">无关联实体</option>
@@ -1249,7 +1249,7 @@ export function MetricSuggestModal({
<div className="grid gap-3 sm:grid-cols-2">
<Field label="目标数据源" required>
<select className="input w-full" value={sourceId} onChange={(e) => setSourceId(e.target.value)}>
<select className="field w-full" value={sourceId} onChange={(e) => setSourceId(e.target.value)}>
<option value="">请选择数据源</option>
{sources.map((s) => (
<option key={s.id} value={s.id}>{s.name}</option>
@@ -1257,7 +1257,7 @@ export function MetricSuggestModal({
</select>
</Field>
<Field label="补充拆解要求(可选)">
<input className="input w-full" value={note} onChange={(e) => setNote(e.target.value)}
<input className="field w-full" value={note} onChange={(e) => setNote(e.target.value)}
placeholder="例如:重点拆解 OEE 与 TEEP 跨表精算公式及产线维度" />
</Field>
</div>
@@ -1291,7 +1291,7 @@ export function MetricSuggestModal({
{docMode === 'paste' && (
<div className="space-y-2 pt-1">
<input
className="input w-full text-xs"
className="field w-full text-xs"
value={docTitle}
onChange={(e) => setDocTitle(e.target.value)}
placeholder="文档标题(可选,留空时自动取首行标题,如:TEEP / OEE 及相关指标公式总表)"
@@ -1299,7 +1299,7 @@ export function MetricSuggestModal({
<textarea
rows={7}
data-decompose-paste-input=""
className="input mono w-full resize-y py-2 text-xs leading-relaxed"
className="field mono w-full resize-y py-2 text-xs leading-relaxed"
value={docText}
onChange={(e) => setDocText(e.target.value)}
placeholder="在此直接粘贴业务指标口径文档(支持 Markdown 表格、字段符号对照、跨表公式与判异红线说明)…"
@@ -1696,12 +1696,14 @@ export function SemanticMetricCardsSection({
<div className="flex flex-wrap items-end gap-2 rounded-md border bg-elev p-2.5">
<div>
<label className="mb-0.5 block text-[11px] text-faint">起始日期(可选)</label>
<input type="date" className="input text-xs" value={dateFrom} onChange={(e) => setDateFrom(e.target.value)} />
<label className="mb-0.5 block text-[11px] text-faint">起始日期(可选)
<input type="date" className="field mt-0.5 block text-xs" value={dateFrom} onChange={(e) => setDateFrom(e.target.value)} />
</label>
</div>
<div>
<label className="mb-0.5 block text-[11px] text-faint">结束日期(可选)</label>
<input type="date" className="input text-xs" value={dateTo} onChange={(e) => setDateTo(e.target.value)} />
<label className="mb-0.5 block text-[11px] text-faint">结束日期(可选)
<input type="date" className="field mt-0.5 block text-xs" value={dateTo} onChange={(e) => setDateTo(e.target.value)} />
</label>
</div>
{m.date_column && (
<label className="flex cursor-pointer items-center gap-1.5 pb-1.5 text-xs text-dim">
@@ -0,0 +1,589 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { Check, FileSearch, RotateCw, X } from 'lucide-react'
import clsx from 'clsx'
import { api, ApiError } from '../../../api/client'
import { ErrorState, Notice, Spinner, toast } from '../../../components/ui'
import { formatDateTime } from '../../../lib/format'
import { LEDGER_UI } from '../../../lib/termsLedger'
import type {
CaliberDraft, DraftImportAcceptOut, DraftImportItem, DraftImportRun, DraftValidationsOut,
} from '../../../typesLedger'
import {
cellText, cleanPaths, fieldLabel, itemAccepts, newRequestId, pickKey, prunePicks, unfinishedItems,
} from './helpers'
const I = LEDGER_UI.imports
export interface ImportStaleInfo {
code: 'stale_revision' | 'import_stale_l'
current: number | null
base: number | null
names: string
}
export function useDraftImports({
openSeq, refreshDetail, loadValidations, loadList,
}: {
openSeq: React.MutableRefObject<number>
refreshDetail: (id: string) => Promise<void>
loadValidations: (id: string) => void
loadList: () => void
}) {
const [importRuns, setImportRuns] = useState<DraftImportRun[] | null>(null)
const [importsError, setImportsError] = useState<unknown>(null)
const [importId, setImportId] = useState<string | null>(null)
const [importBusy, setImportBusy] = useState<string | null>(null)
const [importError, setImportError] = useState<unknown>(null)
const [importPicks, setImportPicks] = useState<Record<string, 'accept' | 'reject'>>({})
const [alignPicks, setAlignPicks] = useState<Record<string, string>>({})
const [importStale, setImportStale] = useState<ImportStaleInfo | null>(null)
const [importResult, setImportResult] = useState<DraftImportAcceptOut | null>(null)
const [importAccepted, setImportAccepted] = useState(false)
const [importRejected, setImportRejected] = useState(false)
const [importNote, setImportNote] = useState('')
const importRequest = useRef<{ signature: string; requestId: string }>({ signature: '', requestId: '' })
const [importPollId, setImportPollId] = useState<string | null>(null)
const resetImports = useCallback(() => {
setImportRuns(null)
setImportsError(null)
setImportId(null)
setImportBusy(null)
setImportError(null)
setImportPicks({})
setAlignPicks({})
setImportStale(null)
setImportResult(null)
setImportAccepted(false)
setImportRejected(false)
setImportNote('')
setImportPollId(null)
importRequest.current = { signature: '', requestId: '' }
}, [])
const putImport = useCallback((run: DraftImportRun) => {
setImportRuns((cur) => [run, ...(cur ?? []).filter((row) => row.run_id !== run.run_id)])
}, [])
const loadImports = useCallback((id: string) => {
const seq = openSeq.current
api.caliberLedger.imports(id).then(
(out) => {
if (seq !== openSeq.current) return
setImportRuns(out.runs)
setImportsError(null)
setImportId((cur) => (cur && out.runs.some((run) => run.run_id === cur) ? cur : (out.runs[0]?.run_id ?? null)))
const running = out.runs.find((run) => run.status === 'queued' || run.status === 'running')
if (running) setImportPollId(running.run_id)
},
(e) => { if (seq === openSeq.current) { setImportRuns(null); setImportsError(e) } },
)
}, [openSeq])
/**
* 正在跑的那一次重导入:每两秒取一次现状(后台在抽候选、算三方),到终态就停。被中断的不会自动续跑,
* 页面上由人点「恢复」显式排回后台。
*/
useEffect(() => {
if (!importPollId) return
const until = Date.now() + 5 * 60_000
let alive = true
const timer = setInterval(() => {
api.caliberLedger.importRun(importPollId).then((run) => {
if (!alive) return
putImport(run)
if (run.status === 'queued' || run.status === 'running') {
if (Date.now() > until) setImportPollId(null)
return
}
setImportPollId(null)
}, (e) => {
if (!alive) return
setImportPollId(null)
setImportError(e)
})
}, 2000)
return () => { alive = false; clearInterval(timer) }
}, [importPollId, putImport])
const reloadImportRun = useCallback(async (runId: string): Promise<DraftImportRun | null> => {
try {
const fresh = await api.caliberLedger.importRun(runId)
putImport(fresh)
setImportPicks((cur) => prunePicks(cur, fresh))
return fresh
} catch (e) {
setImportError(e)
return null
}
}, [putImport])
const refreshImportRun = useCallback(async (runId: string): Promise<DraftImportRun | null> => {
try {
const fresh = await api.caliberLedger.refreshImport(runId)
putImport(fresh)
setImportPicks((cur) => prunePicks(cur, fresh))
return fresh
} catch (e) {
setImportError(e)
return null
}
}, [putImport])
const createImport = useCallback(async (draft: CaliberDraft) => {
if (!draft.workflow_id) { toast.warn(I.readOnly); return }
setImportBusy('create')
setImportError(null)
setImportStale(null)
setImportResult(null)
setImportAccepted(false)
setImportRejected(false)
const signature = `import|${draft.id}|${draft.revision ?? ''}`
if (importRequest.current.signature !== signature) {
importRequest.current = { signature, requestId: newRequestId() }
}
try {
const run = await api.caliberLedger.createImport(draft.id, importRequest.current.requestId)
putImport(run)
setImportId(run.run_id)
setImportPicks({})
setAlignPicks({})
importRequest.current = { signature: '', requestId: '' }
if (run.status === 'queued' || run.status === 'running') setImportPollId(run.run_id)
toast.ok(I.started)
} catch (e) {
setImportError(e)
} finally {
setImportBusy(null)
}
}, [putImport])
const alignImportItem = useCallback(async (run: DraftImportRun, item: DraftImportItem, metricId: string) => {
setImportBusy(`align:${item.item_id}`)
setImportError(null)
try {
const fresh = await api.caliberLedger.alignImportItem(run.run_id, item.item_id, metricId)
putImport(fresh)
setImportPicks((cur) => {
const next: Record<string, 'accept' | 'reject'> = {}
for (const [key, value] of Object.entries(cur)) if (!key.startsWith(`${item.item_id}\u0000`)) next[key] = value
return next
})
} catch (e) {
setImportError(e)
} finally {
setImportBusy(null)
}
}, [putImport])
const acceptImportFields = useCallback(async (
draft: CaliberDraft,
run: DraftImportRun,
items: { item_id: string; metric_id?: string; fields: string[] }[],
) => {
const picked = items.filter((item) => item.fields.length)
if (!picked.length) { toast.warn(I.nothingSelected); return }
if (draft.revision == null) { toast.warn(I.needRevision); return }
setImportBusy('accept')
setImportError(null)
setImportStale(null)
setImportResult(null)
setImportRejected(false)
const signature = `accept|${run.run_id}|${JSON.stringify(picked)}`
if (importRequest.current.signature !== signature) {
importRequest.current = { signature, requestId: newRequestId() }
}
try {
const out = await api.caliberLedger.acceptImport(run.run_id, {
items: picked, expected_revision: draft.revision, request_id: importRequest.current.requestId,
})
putImport(out)
setImportResult(out)
setImportAccepted(true)
setImportPicks({})
importRequest.current = { signature: '', requestId: '' }
toast.ok(I.accepted(out.revision))
void refreshDetail(draft.id)
loadValidations(draft.id)
loadList()
} catch (e) {
const code = e instanceof ApiError && e.status === 409 ? e.code : null
if (code === 'stale_revision' || code === 'import_stale_l') {
const body = e instanceof ApiError ? (e.body as { current_version?: unknown
fields?: { path?: string }[] } | undefined) : undefined
const told = Number(body?.current_version)
const names = (body?.fields ?? []).map((row) => fieldLabel(String(row.path ?? ''), draft.binding)).join('、')
setImportStale({
code: code === 'import_stale_l' ? 'import_stale_l' : 'stale_revision',
current: Number.isFinite(told) ? told : null, base: draft.revision ?? null, names,
})
if (code === 'import_stale_l') await refreshImportRun(run.run_id)
else await reloadImportRun(run.run_id)
void refreshDetail(draft.id)
} else {
setImportError(e)
}
} finally {
setImportBusy(null)
}
}, [loadList, loadValidations, putImport, refreshDetail, refreshImportRun, reloadImportRun])
const rejectImportFields = useCallback(async (
run: DraftImportRun,
items: { item_id: string; metric_id?: string; seq?: number; fields: string[] }[],
) => {
const picked = items.filter((item) => item.fields.length)
if (!picked.length) { toast.warn(I.nothingSelected); return }
setImportBusy('reject')
setImportError(null)
setImportResult(null)
setImportAccepted(false)
try {
const fresh = await api.caliberLedger.rejectImport(run.run_id, {
items: picked, ...(importNote.trim() ? { note: importNote.trim() } : {}),
})
putImport(fresh)
setImportRejected(true)
setImportPicks({})
} catch (e) {
setImportError(e)
} finally {
setImportBusy(null)
}
}, [importNote, putImport])
const resumeImportRun = useCallback(async (run: DraftImportRun) => {
setImportBusy('resume')
setImportError(null)
try {
const fresh = await api.caliberLedger.resumeImport(run.run_id)
putImport(fresh)
setImportPollId(fresh.run_id)
toast.ok(I.resumed)
} catch (e) {
setImportError(e)
} finally {
setImportBusy(null)
}
}, [putImport])
return {
importRuns, importsError, importId, setImportId, importBusy, importError,
importPicks, setImportPicks, alignPicks, setAlignPicks, importStale,
importResult, importAccepted, importRejected, importNote, setImportNote,
resetImports, loadImports, createImport, alignImportItem, acceptImportFields, rejectImportFields, resumeImportRun,
}
}
export function DraftImportsSection({
draft, validations, importRuns, importsError, importId, setImportId, importBusy, importError,
importPicks, setImportPicks, alignPicks, setAlignPicks, importStale,
importResult, importAccepted, importRejected, importNote, setImportNote,
onCreateImport, onAlignImportItem, onAcceptImportFields, onRejectImportFields, onResumeImportRun,
}: {
draft: CaliberDraft
validations: DraftValidationsOut | null
importRuns: DraftImportRun[] | null
importsError: unknown
importId: string | null
setImportId: (id: string | null) => void
importBusy: string | null
importError: unknown
importPicks: Record<string, 'accept' | 'reject'>
setImportPicks: React.Dispatch<React.SetStateAction<Record<string, 'accept' | 'reject'>>>
alignPicks: Record<string, string>
setAlignPicks: React.Dispatch<React.SetStateAction<Record<string, string>>>
importStale: ImportStaleInfo | null
importResult: DraftImportAcceptOut | null
importAccepted: boolean
importRejected: boolean
importNote: string
setImportNote: (value: string) => void
onCreateImport: (draft: CaliberDraft) => void
onAlignImportItem: (run: DraftImportRun, item: DraftImportItem, metricId: string) => void
onAcceptImportFields: (draft: CaliberDraft, run: DraftImportRun, items: { item_id: string; metric_id?: string; fields: string[] }[]) => void
onRejectImportFields: (run: DraftImportRun, items: { item_id: string; metric_id?: string; seq?: number; fields: string[] }[]) => void
onResumeImportRun: (run: DraftImportRun) => void
}) {
if (!draft.workflow_id) return null
const runs = importRuns ?? []
const active = runs.find((run) => run.run_id === importId) ?? null
const metrics = (draft.metrics ?? []).filter((metric) => metric.id)
const nameOf = (id: string) => metrics.find((metric) => metric.id === id)?.name ?? I.unknownMetric
const baseline = validations?.field_baseline ?? draft.field_baseline
const coverage = baseline?.coverage
const coverageStatus = coverage?.status ?? (baseline?.status === 'known' ? 'complete' : 'unknown')
const missingFields = Object.values(coverage?.metrics ?? {})
.reduce((total, row) => total + (row.missing?.length ?? 0), 0)
const uncoveredMetrics = coverage?.uncovered_metric_ids?.length ?? 0
const coverageText = coverageStatus === 'complete' ? I.coverageComplete
: coverageStatus === 'partial' ? I.coveragePartial(missingFields, uncoveredMetrics)
: I.coverageUnknown
const picking = active ? active.items.map((item) => ({
item,
paths: item.fields.filter((cell) => importPicks[pickKey(item.item_id, cell.path)] === 'accept'
&& cell.decided == null && cell.acceptable && itemAccepts(item)).map((cell) => cell.path),
rejects: item.fields.filter((cell) => importPicks[pickKey(item.item_id, cell.path)] === 'reject'
&& cell.decided == null).map((cell) => cell.path),
})) : []
const acceptItems = picking.filter((row) => row.paths.length)
.map((row) => ({ item_id: row.item.item_id, metric_id: row.item.metric_id, fields: row.paths }))
const rejectItems = picking.filter((row) => row.rejects.length).map((row) => ({
item_id: row.item.item_id, fields: row.rejects,
...(row.item.metric_id ? { metric_id: row.item.metric_id } : { seq: row.item.seq }),
}))
const acceptCount = acceptItems.reduce((total, item) => total + item.fields.length, 0)
const rejectCount = rejectItems.reduce((total, item) => total + item.fields.length, 0)
const resumable = active != null && (active.status === 'interrupted' || active.status === 'failed')
const busy = importBusy != null
return (
<div className="rounded-md border bg-elev px-3 py-2" data-draft-imports={active?.status ?? 'none'}>
<div className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5">
<h3 className="text-2xs font-semibold text-dim">{I.title}</h3>
<span className="text-[10px] text-faint">{I.hint}</span>
</div>
<p className="mt-1 text-2xs leading-relaxed text-faint" data-draft-import-coverage={coverageStatus}>
{I.coverageLabel}:{coverageText}。{I.coverageHint}
</p>
<div className="mt-1.5 flex flex-wrap items-center gap-2">
<button type="button" className="btn btn-xs" data-draft-import-create="" disabled={busy}
onClick={() => onCreateImport(draft)}>
{importBusy === 'create' ? <Spinner size={11} /> : <FileSearch size={11} aria-hidden />}
{importBusy === 'create' ? I.creating : I.create}
</button>
<span className="text-[10px] text-faint">{I.createHint}</span>
</div>
{importsError != null && <div className="mt-1"><ErrorState error={importsError} compact /></div>}
{runs.length === 0 ? (
<p className="mt-1 text-2xs leading-relaxed text-faint" data-draft-import-runs={0}>
{I.runs}:{I.runsEmpty}
</p>
) : (
<div className="mt-2" data-draft-import-runs={runs.length}>
<h4 className="text-2xs font-semibold text-faint">{I.runs}</h4>
<ul className="mt-0.5 space-y-0.5">
{runs.map((run) => (
<li key={run.run_id}>
<button type="button" className={clsx('btn btn-xs w-full justify-start text-left', 'btn-ghost')}
aria-pressed={run.run_id === importId} data-draft-import-run={run.run_id}
onClick={() => setImportId(run.run_id)}>
<span className="[overflow-wrap:anywhere]">
{I.runLabel(run.created_at ? formatDateTime(run.created_at) : '—', run.items_decided, run.items_total)}
</span>
<span className="text-faint"> · {I.status[run.status] ?? run.status}</span>
</button>
</li>
))}
</ul>
</div>
)}
{active && (
<div className="mt-2 rounded border bg-panel px-2 py-1.5" data-draft-import-detail={active.run_id}>
<div className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5 text-2xs">
<span className="font-medium text-dim" data-draft-import-status={active.status}>
{I.status[active.status] ?? active.status}
</span>
{(active.status === 'queued' || active.status === 'running') && <Spinner size={11} />}
<span className="text-faint">{I.itemsTotal(active.items_total)}</span>
{active.conflicts.length > 0 && (
<span className="text-[var(--warn)]" data-draft-import-conflicts={active.conflicts.length}>
{I.conflicts(active.conflicts.length)}
</span>
)}
{active.created_at && <span className="text-faint">{I.createdAt(formatDateTime(active.created_at))}</span>}
</div>
{active.error && <Notice tone="warn">{active.error}</Notice>}
{resumable && (
<div className="mt-1 flex flex-wrap items-center gap-2">
<button type="button" className="btn btn-xs" data-draft-import-resume="" disabled={busy}
onClick={() => onResumeImportRun(active)}>
{importBusy === 'resume' ? <Spinner size={11} /> : <RotateCw size={11} aria-hidden />}
{importBusy === 'resume' ? I.resuming : I.resume}
</button>
<span className="text-[10px] text-faint">{I.resumeHint}</span>
<span className="tnum text-[10px] text-faint" data-draft-import-unfinished={unfinishedItems(active)}>
{I.unfinished(unfinishedItems(active))}
</span>
</div>
)}
{active.items.length === 0 ? (
<p className="mt-1 text-2xs leading-relaxed text-faint" data-draft-import-empty="">{I.noItems}</p>
) : (
<ul className="mt-1.5 space-y-2">
{active.items.map((item) => {
const aligned = !!item.metric_id
const alignMode = String(item.align?.mode ?? '')
const needsAlign = !aligned || alignMode === 'manual'
const clean = cleanPaths(item)
return (
<li key={item.item_id} className="rounded border bg-elev px-2 py-1.5"
data-draft-import-item={item.metric_id || `#${item.seq}`} data-import-item-status={item.status}>
<div className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5 text-2xs">
<span className="font-medium text-dim [overflow-wrap:anywhere]">{item.name || I.unknownMetric}</span>
{aligned && <span className="text-faint">· {nameOf(item.metric_id)}</span>}
<span className={clsx(item.status === 'accepted' ? 'text-[var(--ok)]'
: item.status === 'rejected' || item.status === 'failed' ? 'text-faint' : 'text-[var(--warn)]')}
data-draft-import-item-status-label={item.status}>
{I.itemStatus[item.status] ?? I.state[item.status] ?? item.status}
</span>
</div>
{needsAlign && (
<div className="mt-1 flex flex-wrap items-center gap-2" data-draft-import-align="">
<span className="text-2xs text-[var(--warn)]">{I.itemUnaligned}</span>
<select className="field h-[26px] text-2xs" data-draft-import-align-select={item.item_id}
aria-label={I.align} disabled={busy}
value={alignPicks[item.item_id] ?? item.metric_id}
onChange={(e) => setAlignPicks((cur) => ({ ...cur, [item.item_id]: e.target.value }))}>
<option value="">{I.alignNone}</option>
{metrics.map((metric) => (
<option key={metric.id} value={metric.id as string}>{metric.name}</option>
))}
</select>
<button type="button" className="btn btn-xs" data-draft-import-align-submit={item.item_id}
disabled={busy} onClick={() => onAlignImportItem(active, item, alignPicks[item.item_id] ?? '')}>
{importBusy === `align:${item.item_id}` ? <Spinner size={11} /> : null} {I.alignAction}
</button>
<span className="text-[10px] text-faint">{I.alignHint}</span>
</div>
)}
{(alignMode === 'manual' || alignMode === 'new') && (
<p className="mt-0.5 text-2xs leading-relaxed text-[var(--warn)]"
data-draft-import-reason={alignMode}>
{I.reasonLabel}:{I.reason[alignMode] ?? alignMode}
{item.align?.reason ? ` · ${item.align.reason}` : ''}
</p>
)}
{item.error && <p className="mt-0.5 text-2xs leading-relaxed text-[var(--warn)]">{item.error}</p>}
<ul className="mt-1 space-y-1">
{item.fields.map((cell) => {
const choice = importPicks[pickKey(item.item_id, cell.path)] ?? ''
const canAccept = itemAccepts(item) && cell.acceptable && cell.decided !== 'accepted'
const values: [string, string | null, string][] = [
['b', cellText(cell, 'b', draft.binding), I.b],
['l', cellText(cell, 'l', draft.binding), I.l],
['r', cellText(cell, 'r', draft.binding), I.r],
]
return (
<li key={cell.path} className="text-2xs leading-relaxed"
data-draft-import-field={`${item.item_id}:${cell.path}`} data-import-field-state={cell.state}>
<div className="flex flex-wrap items-baseline gap-x-2">
<span className="font-medium text-dim">{fieldLabel(cell.path, draft.binding)}</span>
<span className="text-faint" data-draft-import-field-state-label={cell.state}>
{I.state[cell.state] ?? cell.state}
</span>
{cell.decided === 'accepted' && <span className="text-[var(--ok)]">{I.accept}</span>}
{cell.decided === 'rejected' && <span className="text-faint">{I.reject}</span>}
{cell.state === 'missing' && (
<span className="text-[var(--warn)]" data-draft-import-missing="">
{I.missingNoDelete}
</span>
)}
</div>
<ul className="mt-0.5 space-y-0.5 pl-2">
{values.map(([key, text, label]) => text != null && (
<li key={key} className="text-faint" data-draft-import-value={key}>
{label}:<span className="text-dim [overflow-wrap:anywhere]">{text}</span>
</li>
))}
</ul>
<p className="mt-0.5 text-faint">{I.stateHint[cell.state] ?? ''}</p>
{cell.decided == null && (
<div className="mt-0.5 flex flex-wrap items-center gap-2">
<label className="flex items-center gap-1 text-dim">
<input type="radio" className="accent-[var(--accent)]"
name={`pick:${item.item_id}:${cell.path}`} disabled={!canAccept || busy}
data-draft-import-pick-accept={`${item.item_id}:${cell.path}`}
checked={choice === 'accept'}
onChange={() => setImportPicks((cur) => ({
...cur, [pickKey(item.item_id, cell.path)]: 'accept' }))} />
{I.accept}
</label>
<label className="flex items-center gap-1 text-dim">
<input type="radio" className="accent-[var(--accent)]"
name={`pick:${item.item_id}:${cell.path}`} disabled={busy}
data-draft-import-pick-reject={`${item.item_id}:${cell.path}`}
checked={choice === 'reject'}
onChange={() => setImportPicks((cur) => ({
...cur, [pickKey(item.item_id, cell.path)]: 'reject' }))} />
{I.reject}
</label>
</div>
)}
</li>
)
})}
</ul>
{clean.length > 0 && (
<div className="mt-1">
<button type="button" className="btn btn-xs" data-draft-import-accept-clean={item.item_id}
disabled={busy}
onClick={() => onAcceptImportFields(draft, active,
[{ item_id: item.item_id, metric_id: item.metric_id, fields: clean }])}>
{I.acceptClean(clean.length)}
</button>
</div>
)}
</li>
)
})}
</ul>
)}
{active.items.length > 0 && (
<div className="mt-2 flex flex-wrap items-center gap-2">
<button type="button" className="btn btn-xs btn-primary" data-draft-import-accept=""
disabled={busy || !acceptCount}
onClick={() => onAcceptImportFields(draft, active, acceptItems)}>
{importBusy === 'accept' ? <Spinner size={11} /> : <Check size={11} aria-hidden />}
{importBusy === 'accept' ? I.accepting : I.acceptSelected(acceptCount)}
</button>
<button type="button" className="btn btn-xs" data-draft-import-reject="" disabled={busy || !rejectCount}
onClick={() => onRejectImportFields(active, rejectItems)}>
{importBusy === 'reject' ? <Spinner size={11} /> : <X size={11} aria-hidden />}
{importBusy === 'reject' ? I.rejecting : I.rejectSelected(rejectCount)}
</button>
{!acceptCount && !rejectCount && <span className="text-[10px] text-faint">{I.nothingSelected}</span>}
<input className="field h-[26px] w-44 text-2xs" data-draft-import-note="" aria-label={I.reject}
placeholder={I.notePlaceholder} value={importNote} disabled={busy}
onChange={(e) => setImportNote(e.target.value)} />
</div>
)}
{importStale && (
<div className="mt-1.5" data-draft-import-stale={importStale.code}>
<Notice tone="warn">
{importStale.code === 'import_stale_l'
? I.staleL(importStale.names)
: I.stale(importStale.current, importStale.base)}
</Notice>
</div>
)}
{importError != null && <div className="mt-1"><ErrorState error={importError} compact /></div>}
{(importAccepted || importRejected) && (
<div className="mt-1.5 rounded border bg-elev px-2 py-1 text-2xs leading-relaxed"
data-draft-import-result={importAccepted ? 'accepted' : 'rejected'}>
{importAccepted && (
<>
<p className="text-dim" data-draft-import-result-version={importResult?.revision ?? ''}>
{I.accepted(importResult?.revision ?? null)}
{importResult?.replayed && <span className="text-faint"> · {I.replayed}</span>}
</p>
<p className="text-faint">{I.acceptedHint}</p>
</>
)}
{importRejected && <p className="text-dim">{I.rejected}</p>}
</div>
)}
</div>
)}
</div>
)
}
@@ -0,0 +1,236 @@
import { useCallback, useRef, useState } from 'react'
import { Check, Sparkles } from 'lucide-react'
import { api } from '../../../api/client'
import { ErrorState, Spinner, toast } from '../../../components/ui'
import { LEDGER_UI } from '../../../lib/termsLedger'
import type { CaliberDraft, DraftBinding, NlChangeProposal } from '../../../typesLedger'
import { newRequestId, nlChanges, sameOperations } from './helpers'
const D = LEDGER_UI.drafts
const N = LEDGER_UI.nl
export interface NlAppliedResult {
revision: number | null
invalidated: boolean
replayed: boolean
mismatch: boolean | null
}
export function useDraftNlChange({
setDetail, syncRulesFromBinding, loadValidations, loadList,
}: {
setDetail: React.Dispatch<React.SetStateAction<CaliberDraft | null>>
syncRulesFromBinding: (binding?: DraftBinding) => void
loadValidations: (id: string) => void
loadList: () => void
}) {
const [nlText, setNlText] = useState('')
const [nlPreview, setNlPreview] = useState<NlChangeProposal | null>(null)
const [nlPreviewOf, setNlPreviewOf] = useState('')
const [nlNotice, setNlNotice] = useState<'idle' | 'preview' | 'clarify' | 'applied'>('idle')
const [nlBusy, setNlBusy] = useState<'preview' | 'confirm' | null>(null)
const [nlError, setNlError] = useState<unknown>(null)
const [nlResult, setNlResult] = useState<NlAppliedResult | null>(null)
const nlRequest = useRef<{ signature: string; requestId: string }>({ signature: '', requestId: '' })
const resetNl = useCallback(() => {
setNlText('')
setNlPreview(null)
setNlPreviewOf('')
setNlNotice('idle')
setNlBusy(null)
setNlError(null)
setNlResult(null)
nlRequest.current = { signature: '', requestId: '' }
}, [])
const previewNl = useCallback(async (draft: CaliberDraft) => {
const instruction = nlText.trim()
if (!instruction) { toast.warn(N.needText); return }
if (!draft.card_id) { toast.warn(draft.cards && draft.cards.length > 1 ? D.cardAmbiguous : D.cardMissing); return }
setNlBusy('preview')
setNlError(null)
setNlResult(null)
setNlPreview(null)
try {
const out = await api.caliberLedger.changeProposal(draft.id, {
instruction,
target: { workflow_id: draft.workflow_id ?? undefined, card_id: draft.card_id },
})
setNlPreview(out.proposal)
setNlPreviewOf(instruction)
setNlNotice(out.proposal.ready ? 'preview' : 'clarify')
const signature = `nl|${draft.id}|${instruction}`
if (nlRequest.current.signature !== signature) {
nlRequest.current = { signature, requestId: newRequestId() }
}
} catch (e) {
setNlNotice('idle')
setNlError(e)
} finally {
setNlBusy(null)
}
}, [nlText])
const confirmNl = useCallback(async (draft: CaliberDraft) => {
if (!nlPreviewOf || !nlPreview?.ready) { toast.warn(N.needConfirm); return }
if (nlText.trim() !== nlPreviewOf) { toast.warn(N.needPreviewAgain); return }
if (draft.revision == null) { toast.warn(N.noRevision); return }
setNlBusy('confirm')
setNlError(null)
const signature = `nl|${draft.id}|${nlPreviewOf}`
if (nlRequest.current.signature !== signature) {
nlRequest.current = { signature, requestId: newRequestId() }
}
try {
const out = await api.caliberLedger.nlChange(draft.id, {
instruction: nlPreviewOf,
confirm: true,
expected_revision: draft.revision,
request_id: nlRequest.current.requestId,
target: { workflow_id: draft.workflow_id ?? undefined, card_id: draft.card_id ?? undefined },
})
const fresh = 'proposal' in out ? null : out
const revision = fresh?.change?.revision ?? fresh?.revision ?? null
const same = sameOperations(nlPreview.operations, fresh?.change?.operations)
setNlResult({
revision,
invalidated: fresh?.change?.validation?.invalidated ?? false,
replayed: !!fresh?.replayed,
mismatch: same === null ? null : !same,
})
setNlNotice('applied')
nlRequest.current = { signature: '', requestId: '' }
toast.ok(N.applied(revision))
if (fresh) {
setDetail((cur) => (cur && cur.id === fresh.id ? fresh : cur))
syncRulesFromBinding(fresh.binding)
}
loadValidations(draft.id)
loadList()
} catch (e) {
setNlError(e)
} finally {
setNlBusy(null)
}
}, [loadList, loadValidations, nlPreview, nlPreviewOf, nlText, setDetail, syncRulesFromBinding])
return {
nlText, setNlText, nlPreview, nlPreviewOf, nlNotice, nlBusy, nlError, nlResult,
resetNl, previewNl, confirmNl,
}
}
export function DraftNlSection({
draft, nlText, setNlText, nlPreview, nlPreviewOf, nlNotice, nlBusy, nlError, nlResult,
onPreviewNl, onConfirmNl,
}: {
draft: CaliberDraft
nlText: string
setNlText: (value: string) => void
nlPreview: NlChangeProposal | null
nlPreviewOf: string
nlNotice: 'idle' | 'preview' | 'clarify' | 'applied'
nlBusy: 'preview' | 'confirm' | null
nlError: unknown
nlResult: NlAppliedResult | null
onPreviewNl: (draft: CaliberDraft) => void
onConfirmNl: (draft: CaliberDraft) => void
}) {
if (!draft.workflow_id) return null
const proposal = nlPreview
const changes = proposal?.ready ? nlChanges(draft, proposal.operations) : []
const clarifications = proposal?.clarifications ?? []
const touched = !!nlPreviewOf && nlText.trim() !== nlPreviewOf
const confirmable = !touched && proposal?.ready && changes.length > 0 && draft.revision != null
return (
<div className="rounded-md border bg-elev px-3 py-2" data-draft-nl={nlNotice} data-draft-nl-touched={touched}>
<div className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5">
<h3 className="text-2xs font-semibold text-dim">{N.title}</h3>
<span className="text-[10px] text-faint">{N.hint}</span>
</div>
<div className="mt-1.5 flex flex-wrap items-start gap-2">
<textarea className="field min-h-[40px] flex-1 text-2xs" rows={2} data-draft-nl-input=""
placeholder={N.placeholder} value={nlText} disabled={nlBusy != null}
onChange={(e) => setNlText(e.target.value)} />
<button type="button" className="btn btn-xs" data-draft-nl-preview="" disabled={nlBusy != null}
onClick={() => onPreviewNl(draft)}>
{nlBusy === 'preview' ? <Spinner size={11} /> : <Sparkles size={11} aria-hidden />}
{nlBusy === 'preview' ? N.previewing : N.preview}
</button>
</div>
{clarifications.length > 0 && (
<div className="mt-1.5 rounded border bg-panel px-2 py-1.5" data-draft-nl-clarify={clarifications.length}>
<p className="text-2xs font-medium text-[var(--warn)]">{N.clarifyTitle}</p>
<ul className="mt-0.5 space-y-0.5 text-2xs leading-relaxed text-dim">
{clarifications.map((item, index) => (
<li key={`${item.kind}:${index}`} data-draft-nl-clarify-item={item.kind}>
<span className="[overflow-wrap:anywhere]">{item.question}</span>
{item.kind === 'no_match' && <span className="text-faint"> · {N.clarifyNoMatch}</span>}
{!!item.options?.length && (
<span className="text-faint">
{' · '}{item.options.map((option) => option.label).join('、')}
</span>
)}
</li>
))}
</ul>
<p className="mt-0.5 text-2xs text-faint">{N.clarifyHint}</p>
</div>
)}
{changes.length > 0 && (
<div className="mt-1.5 rounded border bg-panel px-2 py-1.5" data-draft-nl-changes={changes.length}>
<p className="tnum text-2xs font-medium text-dim" data-draft-nl-count={changes.length}>
{N.changeCount(changes.length)}
</p>
<p className="text-[10px] text-faint" data-draft-nl-of={nlPreviewOf ? 'given' : 'none'}>
{touched ? N.changedNotice : N.previewedAs(nlPreviewOf)}
</p>
<ul className="mt-0.5 space-y-0.5">
{changes.map((change, index) => (
<li key={`${change.metricId}:${change.label}:${index}`} className="text-2xs leading-relaxed text-dim"
data-draft-nl-change={change.metricId}>
<span className="font-medium [overflow-wrap:anywhere]">{change.name}</span>
<span className="text-faint"> · {change.label}:</span>
<span className="text-faint">{N.now} {change.from}</span>
<span className="text-faint"> → </span>
<span>{N.after} {change.to}</span>
</li>
))}
</ul>
{confirmable ? (
<div className="mt-1 flex flex-wrap items-center gap-2">
<button type="button" className="btn btn-xs btn-primary" data-draft-nl-confirm=""
disabled={nlBusy != null} onClick={() => onConfirmNl(draft)}>
{nlBusy === 'confirm' ? <Spinner size={11} /> : <Check size={11} aria-hidden />}
{nlBusy === 'confirm' ? N.confirming : N.confirm}
</button>
<span className="text-[10px] text-faint">{N.confirmHint}</span>
</div>
) : touched ? (
<p className="mt-1 text-2xs text-[var(--warn)]" data-draft-nl-repreview="">{N.needPreviewAgain}</p>
) : (
<p className="mt-1 text-2xs text-faint" data-draft-nl-norevision="">{N.noRevision}</p>
)}
</div>
)}
{nlError != null && <div className="mt-1"><ErrorState error={nlError} compact /></div>}
{nlResult && (
<div className="mt-1.5 rounded border bg-panel px-2 py-1 text-2xs leading-relaxed"
data-draft-nl-result={nlResult.revision == null ? 'applied' : `v${nlResult.revision}`}>
<p className="text-dim" data-draft-nl-result-version={nlResult.revision ?? ''}>
{N.applied(nlResult.revision)}
{nlResult.replayed && <span className="text-faint"> · {N.replayed}</span>}
</p>
{nlResult.invalidated && <p className="text-faint">{N.invalidated}</p>}
{nlResult.mismatch === true && (
<p className="text-[var(--warn)]" data-draft-nl-mismatch="">{N.mismatch}</p>
)}
</div>
)}
</div>
)
}
@@ -0,0 +1,313 @@
import { useCallback, useRef, useState } from 'react'
import { Check, Undo2 } from 'lucide-react'
import { api, ApiError } from '../../../api/client'
import { ErrorState, Notice, Spinner, toast } from '../../../components/ui'
import { LEDGER_UI } from '../../../lib/termsLedger'
import type { CaliberDraft, DraftBinding, DraftChangeReceipt, DraftOperation } from '../../../typesLedger'
import { choiceLabel, declaringMetrics, newRequestId, ruleInitialValues, rulePlan, undoOperations } from './helpers'
const R = LEDGER_UI.rules
export function useDraftRules({
setDetail, refreshDetail, loadValidations, loadList,
}: {
setDetail: React.Dispatch<React.SetStateAction<CaliberDraft | null>>
refreshDetail: (id: string) => Promise<void>
loadValidations: (id: string) => void
loadList: () => void
}) {
const [ruleValues, setRuleValues] = useState<Record<string, string>>({})
const rulePending = useRef<{ signature: string; requestId: string }>({ signature: '', requestId: '' })
const [ruleBusy, setRuleBusy] = useState<'save' | 'undo' | null>(null)
const [ruleError, setRuleError] = useState<unknown>(null)
const [ruleStale, setRuleStale] = useState<{ current: number | null; base: number | null } | null>(null)
const [ruleResult, setRuleResult] = useState<DraftChangeReceipt | null>(null)
const [ruleReplayed, setRuleReplayed] = useState(false)
const [undoRecord, setUndoRecord] = useState<{ operations: DraftOperation[]; count: number } | null>(null)
const resetRules = useCallback(() => {
setRuleValues({})
setRuleBusy(null)
setRuleError(null)
setRuleStale(null)
setRuleResult(null)
setRuleReplayed(false)
setUndoRecord(null)
rulePending.current = { signature: '', requestId: '' }
}, [])
const syncRulesFromBinding = useCallback((binding?: DraftBinding) => {
setRuleValues(ruleInitialValues(binding))
}, [])
/**
* 保存这次业务规则的修改:把**所有**受影响指标的字段操作放在一次请求里(PATCH 的 operations),带上读到的
* 基准版本、目标卡和幂等键。一次原子变更:全成或全不成;回执(change)说清落成哪一版、绑定同步到哪一步。
* 被拒(基准版本过期)时什么都不改:这里的写法选择留着,刷新详情拿到新版本后由人显式再点一次。
*/
const saveRules = useCallback(async (draft: CaliberDraft, operations: DraftOperation[]) => {
if (!operations.length) { toast.warn(R.saveNeedChange); return }
if (!draft.card_id || draft.revision == null) { toast.warn(R.noCard); return }
setRuleBusy('save')
setRuleError(null)
const signature = `${draft.id}|${JSON.stringify(operations)}`
if (rulePending.current.signature !== signature) {
rulePending.current = { signature, requestId: newRequestId() }
}
try {
const fresh = await api.caliberLedger.patchDraft(draft.id, {
operations,
expected_revision: draft.revision,
request_id: rulePending.current.requestId,
target: { workflow_id: draft.workflow_id ?? undefined, card_id: draft.card_id },
})
setDetail(fresh)
setRuleResult(fresh.change ?? null)
setRuleReplayed(!!fresh.replayed)
setRuleStale(null)
setUndoRecord({ operations: undoOperations(draft.binding, operations), count: operations.length })
setRuleValues(ruleInitialValues(fresh.binding))
rulePending.current = { signature: '', requestId: '' }
toast.ok(R.saved(fresh.change?.revision ?? fresh.revision ?? null))
loadValidations(draft.id)
loadList()
} catch (e) {
const stale = e instanceof ApiError && e.status === 409 && e.code === 'stale_revision'
if (stale) {
const told = Number((e.body as { current_version?: unknown } | undefined)?.current_version)
setRuleStale({ current: Number.isFinite(told) ? told : null, base: draft.revision ?? null })
void refreshDetail(draft.id)
} else {
setRuleError(e)
}
} finally {
setRuleBusy(null)
}
}, [loadList, loadValidations, refreshDetail, setDetail])
/** 撤销这次修改:逆操作 + 当前版本 + 新的请求键,再新增一版;不是整份覆盖,也不改已经存下的版本 */
const undoRules = useCallback(async (draft: CaliberDraft, record: { operations: DraftOperation[]; count: number }) => {
if (draft.revision == null || !record.operations.length) return
setRuleBusy('undo')
setRuleError(null)
const signature = `undo|${draft.id}|${JSON.stringify(record.operations)}`
if (rulePending.current.signature !== signature) {
rulePending.current = { signature, requestId: newRequestId() }
}
try {
const fresh = await api.caliberLedger.patchDraft(draft.id, {
operations: record.operations,
expected_revision: draft.revision,
request_id: rulePending.current.requestId,
target: { workflow_id: draft.workflow_id ?? undefined, card_id: draft.card_id ?? undefined },
})
setDetail(fresh)
setRuleResult(fresh.change ?? null)
setRuleReplayed(!!fresh.replayed)
setRuleStale(null)
setUndoRecord(null)
setRuleValues(ruleInitialValues(fresh.binding))
rulePending.current = { signature: '', requestId: '' }
toast.ok(R.undone(fresh.change?.revision ?? fresh.revision ?? null))
loadValidations(draft.id)
loadList()
} catch (e) {
const stale = e instanceof ApiError && e.status === 409 && e.code === 'stale_revision'
if (stale) {
const told = Number((e.body as { current_version?: unknown } | undefined)?.current_version)
setRuleStale({ current: Number.isFinite(told) ? told : null, base: draft.revision ?? null })
void refreshDetail(draft.id)
} else {
setRuleError(e)
}
} finally {
setRuleBusy(null)
}
}, [loadList, loadValidations, refreshDetail, setDetail])
return {
ruleValues, setRuleValues, ruleBusy, ruleError, ruleStale, ruleResult, ruleReplayed, undoRecord,
resetRules, syncRulesFromBinding, saveRules, undoRules,
}
}
/**
* 业务规则(K06 的工作台):服务端的能力描述说得出这张卡能按字段改哪几项时才开表单。改完先列「会改到哪几条指标、
* 现在什么写法 → 保存后什么写法」,再把所有受影响指标的字段操作**一次**提交(原子变更);回执说清落成哪一版、
* 取数同步到哪一步、旧验证怎么失效,并按保存前的值给出「撤销这次修改」。这块只写业务说法:取数语句、内部编号、
* 字段路径和 JSON 都不上来。
*/
export function DraftRulesSection({
draft, ruleValues, setRuleValues, ruleBusy, ruleError, ruleStale, ruleResult, ruleReplayed, undoRecord,
onSave, onUndo,
}: {
draft: CaliberDraft
ruleValues: Record<string, string>
setRuleValues: React.Dispatch<React.SetStateAction<Record<string, string>>>
ruleBusy: 'save' | 'undo' | null
ruleError: unknown
ruleStale: { current: number | null; base: number | null } | null
ruleResult: DraftChangeReceipt | null
ruleReplayed: boolean
undoRecord: { operations: DraftOperation[]; count: number } | null
onSave: (draft: CaliberDraft, operations: DraftOperation[]) => void
onUndo: (draft: CaliberDraft, record: { operations: DraftOperation[]; count: number }) => void
}) {
const binding = draft.binding
if (!binding) return null
const fields = binding.editable_fields ?? []
const metrics = (draft.metrics ?? []).filter((metric) => metric.id)
const names = new Map(metrics.map((metric) => [metric.id as string, metric.name]))
const declared = new Set(Object.keys(binding.metric_values ?? {}))
const plan = rulePlan(binding, ruleValues)
const changes = plan.changes.map((change) => ({ ...change, name: names.get(change.metricId) ?? change.metricId }))
const readOnly = !draft.workflow_id ? R.noWorkflow
: !draft.card_id ? R.noCard
: draft.revision == null ? R.noRevision
: declared.size === 0 ? R.unbound : null
const label = R.status[binding.status] ?? binding.status
const tone = binding.status === 'aligned' ? 'var(--ok)'
: binding.status === 'unbound' ? 'var(--text-faint)' : 'var(--warn)'
const saved = ruleResult?.binding
const untouched = metrics.length - declared.size
return (
<div className="rounded-md border bg-elev px-3 py-2" data-draft-rules={binding.status}>
<div className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5">
<h3 className="text-2xs font-semibold text-dim">{R.title}</h3>
<span className="text-2xs" data-draft-rules-status={binding.status} style={{ color: tone }}>{label}</span>
<span className="text-[10px] text-faint">{R.hint}</span>
</div>
{binding.status === 'aligned' ? (
<p className="mt-1 text-2xs leading-relaxed text-faint" data-draft-rules-note="">{R.alignedNote}</p>
) : (
<>
<p className="mt-1 text-2xs leading-relaxed text-[var(--warn)]" data-draft-rules-reason="">
{R.reason}:{binding.reason}
</p>
{binding.fix && binding.fix !== 'none' && (
<p className="mt-0.5 text-2xs leading-relaxed text-dim" data-draft-rules-todo="">
{R.fixLabel}:{R.fix[binding.fix] ?? binding.fix}
</p>
)}
</>
)}
{readOnly ? (
<p className="mt-1.5 text-2xs leading-relaxed text-faint" data-draft-rules-readonly="">{R.readOnly}:{readOnly}</p>
) : (
<>
<ul className="mt-1.5 space-y-1.5">
{fields.map((field) => {
const declaring = declaringMetrics(binding, field.field)
const distinct = [...new Set(declaring.map((id) => binding.metric_values[id][field.field]))]
const chosen = ruleValues[field.field] ?? ''
return (
<li key={field.field} className="flex flex-wrap items-center gap-x-2 gap-y-1"
data-draft-rule-field={field.field}>
<span className="text-2xs font-medium text-dim">{field.label}</span>
<select className="field h-[26px] text-2xs" value={chosen} aria-label={field.label}
disabled={!declaring.length || ruleBusy != null} data-draft-rule-select={field.field}
title={distinct.length > 1 ? R.mixedHint : undefined}
onChange={(e) => setRuleValues((cur) => ({ ...cur, [field.field]: e.target.value }))}>
<option value="">{R.keep}</option>
{field.values.map((value) => (
<option key={value} value={value}>{choiceLabel(field, value)}</option>
))}
</select>
<span className="text-[10px] text-faint" data-draft-rule-current={field.field}>
{!declaring.length ? R.fieldNone
: distinct.length > 1 ? R.mixed
: `${R.before}:${choiceLabel(field, distinct[0])}`}
</span>
<span className="text-[10px] text-faint [overflow-wrap:anywhere]">{field.help}</span>
</li>
)
})}
</ul>
{untouched > 0 && (
<p className="mt-1 text-2xs leading-relaxed text-faint" data-draft-rule-untouched={untouched}>
{R.unaffected(untouched)}。{R.unaffectedHint}
</p>
)}
<div className="mt-2 rounded border bg-panel px-2 py-1.5" data-draft-rule-preview="">
<div className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5">
<span className="text-2xs font-semibold text-dim">{R.previewTitle}</span>
<span className="tnum text-2xs text-faint" data-draft-rule-affected={changes.length}>
{changes.length ? R.affected(changes.length) : R.noChange}
</span>
</div>
{changes.length > 0 && (
<ul className="mt-1 space-y-0.5">
{changes.map((change) => (
<li key={`${change.metricId}:${change.field.field}`} data-draft-rule-change={change.metricId}
className="text-2xs leading-relaxed text-dim">
<span className="font-medium [overflow-wrap:anywhere]">{change.name}</span>
<span className="text-faint"> · {change.field.label}:</span>
<span className="text-faint">{choiceLabel(change.field, change.from)}</span>
<span className="text-faint"> → </span>
<span>{choiceLabel(change.field, change.to)}</span>
</li>
))}
</ul>
)}
</div>
<div className="mt-1.5 flex flex-wrap items-center gap-2">
<button type="button" className="btn btn-xs btn-primary" data-draft-rule-save=""
disabled={ruleBusy != null || !plan.operations.length}
onClick={() => onSave(draft, plan.operations)}>
{ruleBusy === 'save' ? <Spinner size={11} /> : <Check size={11} aria-hidden />}
{ruleBusy === 'save' ? R.saving : R.save}
</button>
{undoRecord && (
<button type="button" className="btn btn-xs" data-draft-rule-undo="" title={R.undoHint}
disabled={ruleBusy != null}
onClick={() => onUndo(draft, undoRecord)}>
{ruleBusy === 'undo' ? <Spinner size={11} /> : <Undo2 size={11} aria-hidden />}
{ruleBusy === 'undo' ? R.undoing : R.undo(undoRecord.count)}
</button>
)}
</div>
</>
)}
{ruleStale && (
<div className="mt-1.5" data-draft-rule-stale="">
<Notice tone="warn">{R.stale(ruleStale.current, ruleStale.base)}</Notice>
</div>
)}
{ruleError != null && <div className="mt-1.5"><ErrorState error={ruleError} compact /></div>}
{ruleReplayed && !ruleResult && (
<div className="mt-1.5"><Notice tone="info">{R.replayed}</Notice></div>
)}
{ruleResult && (
<div className="mt-1.5 rounded border bg-panel px-2 py-1.5 text-2xs leading-relaxed"
data-draft-rule-result={ruleResult.applied ? 'applied' : 'none'}>
<p className="text-dim" data-draft-rule-result-version="">
{R.saved(ruleResult.revision)}
{ruleReplayed && <span className="text-faint"> · {R.replayed}</span>}
</p>
{ruleResult.applied ? (
<>
<p data-draft-rule-binding={saved?.status ?? ''}>
{saved?.synced ? R.savedAligned : R.savedNotSynced}
{!saved?.synced && saved?.reason ? `(${saved.reason})` : ''}
</p>
<p className="text-faint" data-draft-rule-invalidated="">{R.invalidated}</p>
<p className="text-faint">{R.nextStep}</p>
{!saved?.synced && saved?.fix && saved.fix !== 'none' && (
<p className="text-dim" data-draft-rule-fix="">
{R.fixLabel}:{R.fix[saved.fix] ?? saved.fix}。{R.fixNote}
</p>
)}
</>
) : (
<p className="text-faint">{R.savedNoChange}</p>
)}
</div>
)}
</div>
)
}
@@ -0,0 +1,443 @@
import { Link } from 'react-router-dom'
import { AlertTriangle, Check, FileText } from 'lucide-react'
import clsx from 'clsx'
import { ErrorState, Skeleton, Spinner } from '../../../components/ui'
import { formatTime } from '../../../lib/format'
import { LEDGER_UI } from '../../../lib/termsLedger'
import type { DataSourceName, KbDocument, Run } from '../../../types'
import type {
CaliberDraft, CaliberDraftStage, CaliberDraftStatus, DraftAlignment, DraftBinding, DraftCitation, DraftMetric,
DraftTrialMetric,
} from '../../../typesLedger'
import { choiceLabel, spanParts } from './helpers'
const D = LEDGER_UI.drafts
/** 阶段标签:起草中 / 待审 / 已丢弃 / 起草失败;细状态放在 title 里,鼠标悬停能看到「待确认问题」这类差别 */
export function StatusPill({ stage, status }: { stage: CaliberDraftStage; status?: CaliberDraftStatus }) {
const color = stage === 'review'
? (status === 'ready' || status === 'attached' ? 'var(--ok)' : 'var(--warn)')
: stage === 'drafting' ? 'var(--accent)' : stage === 'discarded' ? 'var(--text-faint)' : 'var(--err)'
return (
<span className="shrink-0 rounded border px-1.5 py-0.5 text-[10px]" title={status ? D.status[status] : undefined}
style={{ color, borderColor: `color-mix(in srgb, ${color} 40%, var(--border))` }}>
{D.stage[stage] ?? stage}
</span>
)
}
export function QuoteBody({ content, span, quote }: { content: string; span?: [number, number]; quote: string }) {
const parts = spanParts(content, span)
if (!content) return <>{quote}</>
if (!parts) return <>{content}</>
return (
<>
{parts[0]}
<mark className="rounded px-0.5 text-fg" style={{ background: 'color-mix(in srgb, var(--warn) 22%, transparent)' }}>
{parts[1]}
</mark>
{parts[2]}
</>
)
}
/** 草稿和已发布口径的对齐:新的、已有出处的、定义不同的 */
export function AlignmentBlock({ alignment }: { alignment: DraftAlignment }) {
const added = alignment.new ?? []
const duplicate = alignment.duplicate ?? []
const conflict = alignment.conflict ?? []
if (!added.length && !duplicate.length && !conflict.length) return null
const row = (label: string, items: { name: string; reason?: string }[]) => items.length > 0 && (
<li className="flex flex-wrap items-baseline gap-x-1.5">
<span className="text-faint">{label}</span>
{items.map((item) => (
<span key={item.name}>
{item.name}
{item.reason ? `(${item.reason})` : ''}
</span>
))}
</li>
)
return (
<div data-draft-alignment="">
<h3 className="mb-1 text-2xs font-semibold text-dim">{D.alignment}</h3>
<ul className="space-y-1 text-2xs leading-relaxed">
{row(D.alignmentNew, added.map((name) => ({ name })))}
{row(D.alignmentDuplicate, duplicate)}
{row(D.alignmentConflict, conflict)}
</ul>
</div>
)
}
export function DraftQuestionList({
questions, prefix, pickedQuestions, onToggle,
}: {
questions: string[] | undefined
prefix: string
pickedQuestions: string[]
onToggle: (question: string, checked: boolean) => void
}) {
const list = (questions ?? []).filter((q) => q.trim())
if (!list.length) return null
return (
<ul className="mt-1 space-y-0.5">
{list.map((q, i) => (
<li key={`${prefix}:${i}`}>
<label className="flex items-start gap-1.5 text-2xs leading-relaxed text-dim">
<input type="checkbox" className="mt-0.5 accent-[var(--accent)]" checked={pickedQuestions.includes(q)}
onChange={(e) => onToggle(q, e.target.checked)} />
<span className="min-w-0 [overflow-wrap:anywhere]">{q}</span>
</label>
</li>
))}
</ul>
)
}
/**
* 取数 SQL:草稿图里写好的模板,入口字段在运行时渲染;只读展示,不出现执行值。
* 默认折叠,SQL 可能为空(旧草稿、没写出取数),那时整块不画。
*/
export function DraftSqlSection({ draft }: { draft: CaliberDraft }) {
const groups = (draft.groups ?? []).filter((group) => (group.sql ?? '').trim())
const sql = (draft.sql ?? '').trim()
if (!groups.length && !sql) return null
const names = new Map((draft.metrics ?? []).filter((metric) => metric.id)
.map((metric) => [metric.id as string, metric.name]))
return (
<details className="rounded-md border bg-elev px-3 py-2" data-draft-sql="">
<summary className="cursor-pointer text-2xs font-semibold text-dim">{D.sqlTitle}</summary>
<p className="mt-0.5 text-2xs leading-relaxed text-faint">{D.sqlHint}</p>
{groups.length > 0 ? (
<div className="mt-1 space-y-2">
{groups.map((group, index) => (
<div key={`${index}:${group.sql}`} className="rounded bg-panel px-2 py-1.5"
data-draft-sql-group={index}>
<div className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5 text-2xs">
<span className="font-medium text-dim">{D.sqlGroup(index + 1, group.metric_ids?.length ?? 0)}</span>
{!!group.metric_ids?.length && (
<span className="text-faint [overflow-wrap:anywhere]">
{(group.metric_ids ?? []).map((id) => names.get(id) ?? id).join('、')}
</span>
)}
</div>
<div className="mt-1 overflow-x-auto">
<code className="mono block whitespace-pre-wrap text-2xs leading-relaxed text-dim">{group.sql}</code>
</div>
</div>
))}
</div>
) : (
<div className="mt-1 overflow-x-auto rounded bg-panel px-2 py-1.5">
<code className="mono block whitespace-pre-wrap text-2xs leading-relaxed text-dim">{sql}</code>
</div>
)}
</details>
)
}
/** 发布前检查:服务端从图和试跑状态算,只读;未通过的不拦人,逐项写原因 */
export function DraftChecksSection({ draft }: { draft: CaliberDraft }) {
const checks = draft.checks ?? []
if (!checks.length) return null
const passed = checks.filter((check) => check.ok).length
return (
<div className="rounded-md border bg-elev px-3 py-2" data-draft-checks="">
<div className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5">
<h3 className="text-2xs font-semibold text-dim">{D.checks}</h3>
<span className={clsx('tnum text-2xs', passed === checks.length ? 'text-[var(--ok)]' : 'text-[var(--warn)]')}>
{D.checksSummary(passed, checks.length)}
</span>
</div>
<ul className="mt-1 space-y-1">
{checks.map((check) => (
<li key={check.key} className="flex items-start gap-1.5 text-2xs leading-relaxed" data-draft-check={check.key}>
{check.ok ? <Check size={11} className="mt-px shrink-0 text-[var(--ok)]" aria-hidden />
: <AlertTriangle size={11} className="mt-px shrink-0 text-[var(--warn)]" aria-hidden />}
<span className="min-w-0 flex-1">
<span className={check.ok ? 'text-dim' : 'text-[var(--warn)]'}>{check.label}</span>
{!check.ok && <span className="text-faint">({D.checkFail})</span>}
{check.detail && <p className="mt-0.5 text-2xs text-faint [overflow-wrap:anywhere]">{check.detail}</p>}
</span>
</li>
))}
</ul>
<p className="mt-1 text-2xs text-faint">{D.checksHint}</p>
</div>
)
}
/**
* 一条指标:默认收成一行,名字、单位、值和未决问题数直接看得见;展开才是定义、表达式、引用。
* 指标多到几十条时这样一屏能扫完,找哪条再展开哪条。
*/
export function DraftMetricItem({
metric, index, values, binding, chunks, paragraphOf, pickedQuestions, onToggleQuestion,
}: {
metric: DraftMetric
index: number
values: Map<string, DraftTrialMetric>
binding?: DraftBinding
chunks: Record<string, { ordinal: number; content: string }>
paragraphOf: (citation: DraftCitation) => number | null
pickedQuestions: string[]
onToggleQuestion: (question: string, checked: boolean) => void
}) {
const definition = metric.definition ?? {}
const citations = definition.citations ?? []
const questions = metric.open_questions ?? []
const row = metric.id ? values.get(metric.id) : undefined
const value = row ? row.rendered ?? (row.value == null ? '' : String(row.value)) : ''
const rows = [
[D.unit, metric.unit],
[D.decimals, metric.decimals != null ? String(metric.decimals) : ''],
[D.grain, metric.grain],
[D.timeField, metric.time_field],
[D.numerator, metric.numerator],
[D.denominator, metric.denominator],
[D.scope, definition.scope],
[D.owner, definition.owner],
[D.effectiveFrom, definition.effective_from],
[D.dimensions, metric.dimensions?.join('、')],
[D.filters, metric.filters?.join(';')],
[D.exclusions, definition.exclusions?.join(';')],
].filter(([, text]) => typeof text === 'string' && text.trim()) as [string, string][]
const business = (binding?.editable_fields ?? [])
.map((field): [string, string] => {
const raw = (metric as unknown as Record<string, unknown>)[field.field]
return [field.label, typeof raw === 'string' ? choiceLabel(field, raw) : '']
})
.filter(([, text]) => !!text)
return (
<li data-draft-metric={metric.name}>
<details className="rounded-md border bg-panel">
<summary className="flex cursor-pointer flex-wrap items-baseline gap-x-2 gap-y-0.5 px-3 py-2"
title={D.metricSummaryHint}>
<span className="text-xs font-medium [overflow-wrap:anywhere]">{metric.name}</span>
{!!questions.length && <span className="text-2xs text-[var(--warn)]">{D.metricQuestions(questions.length)}</span>}
{!!value && (
<span className="tnum ml-auto text-xs font-medium" data-draft-metric-value={metric.id}>
{value}{metric.unit ? ` ${metric.unit}` : ''}
</span>
)}
</summary>
<div className="border-t px-3 py-2">
{!!metric.synonyms?.length && <p className="text-2xs text-faint">{D.synonyms(metric.synonyms.join('、'))}</p>}
{business.length > 0 && (
<p className="mb-1 text-2xs text-dim" data-draft-metric-business={metric.id}>
{business.map(([label, text]) => `${label}${D.businessValue(text)}`).join(' · ')}
</p>
)}
{(rows.length > 0 || business.length > 0) && (
<dl className="mt-1 grid gap-x-3 gap-y-0.5 text-2xs sm:grid-cols-[auto_1fr]">
{rows.map(([label, text]) => (
<div key={label} className="contents">
<dt className="text-faint">{label}</dt>
<dd className="text-dim">{text}</dd>
</div>
))}
</dl>
)}
{metric.expression && (
<div className="mt-1.5" data-draft-expression="">
<h4 className="text-2xs font-semibold text-faint">{D.expression}</h4>
<code className="mt-0.5 block whitespace-pre-wrap rounded bg-elev px-1.5 py-1 text-2xs text-dim [overflow-wrap:anywhere]">
{metric.expression}
</code>
</div>
)}
{definition.text && (
<div className="mt-1.5">
<h4 className="text-2xs font-semibold text-faint">{D.definition}</h4>
<p className="text-2xs leading-relaxed text-dim">{definition.text}</p>
</div>
)}
{citations.length > 0 && (
<div className="mt-1.5">
<h4 className="mb-1 text-2xs font-semibold text-faint">{D.citations}</h4>
<ul className="space-y-1">
{citations.map((citation, i) => {
const chunk = chunks[citation.chunk]
const ordinal = paragraphOf(citation)
return (
<li key={`${index}:${i}`}>
<details className="rounded border bg-elev px-2 py-1">
<summary className="cursor-pointer text-2xs leading-relaxed text-dim">
<span className="[overflow-wrap:anywhere]">「{citation.quote}」</span>
{ordinal != null && <span className="ml-1.5 text-faint">· {D.paragraph(ordinal)}</span>}
</summary>
<p className="mt-1 whitespace-pre-wrap text-2xs leading-relaxed text-faint">
{chunk
? <QuoteBody content={chunk.content} span={citation.span} quote={citation.quote} />
: D.citationMissing}
</p>
<p className="mt-0.5 text-[10px] text-faint">{metric.name}</p>
</details>
</li>
)
})}
</ul>
</div>
)}
{!!questions.length && (
<div className="mt-1.5" data-draft-questions="">
<h4 className="text-2xs font-semibold text-faint">{D.questions}</h4>
<DraftQuestionList questions={questions} prefix={`${index}`}
pickedQuestions={pickedQuestions} onToggle={onToggleQuestion} />
</div>
)}
</div>
</details>
</li>
)
}
export function DraftAttachSection({
draft, runId, setRunId, recentRuns, busy, attachOut, onAttach, showForm,
}: {
draft: CaliberDraft
runId: string
setRunId: (value: string) => void
recentRuns: Run[] | null
busy: string | null
attachOut: { workflow_id: string; version: number; warnings: string[] } | null
onAttach: (draft: CaliberDraft) => void
showForm: boolean
}) {
return (
<>
{showForm && (
<details className="rounded-md border bg-elev px-3 py-2" data-draft-attach="">
<summary className="cursor-pointer text-2xs font-semibold text-dim">{D.attach}</summary>
<p className="mt-0.5 text-2xs leading-relaxed text-faint">{D.attachHint}</p>
<div className="mt-1.5 flex flex-wrap items-end gap-2">
<label className="min-w-40 flex-1 text-2xs text-faint">
<span className="mb-0.5 block">{D.runId}</span>
<input className="field w-full" value={runId} placeholder={D.runIdPlaceholder}
onChange={(e) => setRunId(e.target.value)} aria-label={D.runId} data-draft-run-id="" />
</label>
<label className="w-56 text-2xs text-faint">
<span className="mb-0.5 block">{D.recentRuns}</span>
<select className="field h-[30px] w-full" value="" aria-label={D.recentRuns}
onChange={(e) => { if (e.target.value) setRunId(e.target.value) }}>
<option value="">
{recentRuns == null ? D.recentRunsPick : recentRuns.length ? D.recentRunsPick : D.recentRunsNone}
</option>
{(recentRuns ?? []).map((run) => (
<option key={run.id} value={run.id}>
{run.workflow_name || run.id}{run.created_at ? ` · ${formatTime(run.created_at)}` : ''}
</option>
))}
</select>
</label>
<button type="button" className="btn btn-sm" disabled={busy === `attach:${draft.id}`}
onClick={() => onAttach(draft)} data-draft-attach-submit="">
{busy === `attach:${draft.id}` ? <Spinner size={12} /> : null} {busy === `attach:${draft.id}` ? D.attaching : D.attachAction}
</button>
</div>
</details>
)}
{attachOut && (
<div className="rounded-md border bg-elev px-3 py-2 text-2xs leading-relaxed text-dim" data-draft-attached="">
<p>{D.attached(attachOut.version)}</p>
<Link to={`/studio/${attachOut.workflow_id}`} className="text-accent hover:underline">
{D.openWorkflow}
</Link>
{attachOut.warnings.length > 0 && (
<div className="mt-1">
<span className="text-faint">{D.attachWarnings}</span>
<ul className="mt-0.5 list-disc pl-4">
{attachOut.warnings.map((w) => <li key={w}>{w}</li>)}
</ul>
</div>
)}
</div>
)}
</>
)
}
export function DraftStartSection({
docs, docsError, sources, pickedDocs, setPickedDocs, datasourceId, setDatasourceId,
guidance, setGuidance, fixedFilters, setFixedFilters, submitting, onSubmit,
}: {
docs: KbDocument[] | null
docsError: unknown
sources: DataSourceName[]
pickedDocs: string[]
setPickedDocs: React.Dispatch<React.SetStateAction<string[]>>
datasourceId: string
setDatasourceId: (value: string) => void
guidance: string
setGuidance: (value: string) => void
fixedFilters: string
setFixedFilters: (value: string) => void
submitting: boolean
onSubmit: (definitions?: boolean) => void
}) {
const pendingDocs = !docs ? <Skeleton rows={4} height={22} />
: docs.length === 0 ? <p className="py-2 text-2xs leading-relaxed text-faint">{D.noDocuments}:{D.noDocumentsBody}</p>
: (
<ul className="max-h-40 space-y-0.5 overflow-y-auto pr-1">
{docs.map((doc) => {
const ready = doc.status !== 'processing' && doc.status !== 'failed'
return (
<li key={doc.id}>
<label className={clsx('flex items-start gap-1.5 text-2xs leading-relaxed',
ready ? 'text-dim' : 'text-faint')}>
<input type="checkbox" className="mt-0.5 accent-[var(--accent)]" disabled={!ready}
checked={pickedDocs.includes(doc.id)}
onChange={(e) => setPickedDocs((cur) => (e.target.checked
? [...cur, doc.id] : cur.filter((id) => id !== doc.id)))} />
<span className="min-w-0 flex-1 [overflow-wrap:anywhere]">{doc.title || doc.id}</span>
<span className="shrink-0 text-faint">{D.documentMeta(doc.collection, doc.chunk_count)}</span>
</label>
</li>
)
})}
</ul>
)
return (
<section className="rounded-lg border bg-panel px-3 py-2.5" data-draft-start="">
<h2 className="text-xs font-semibold">{D.start}</h2>
<div className="mt-2 grid gap-3 md:grid-cols-2">
<div>
<h3 className="text-2xs font-semibold text-dim">{D.documents}</h3>
<p className="mb-1 text-2xs text-faint">{D.documentsHint}</p>
{docsError ? <ErrorState error={docsError} compact /> : pendingDocs}
</div>
<div className="space-y-2">
<label className="block text-2xs text-faint">
<span className="mb-0.5 block font-semibold text-dim">{D.datasource}</span>
<select className="field w-full" value={datasourceId}
onChange={(e) => setDatasourceId(e.target.value)}>
<option value="">导入定义时可暂不选数据源</option>
{sources.map((s) => <option key={s.id} value={s.id}>{s.name}</option>)}
</select>
<span className="mt-0.5 block">先保留文档定义,选择指标后再绑定已探查的数据源。</span>
</label>
<label className="block text-2xs text-faint">
<span className="mb-0.5 block font-semibold text-dim">{D.guidance}</span>
<textarea className="field min-h-[64px] w-full text-xs" rows={3} value={guidance}
placeholder={D.guidancePlaceholder} onChange={(e) => setGuidance(e.target.value)} />
</label>
<label className="block text-2xs text-faint">
<span className="mb-0.5 block font-semibold text-dim">{D.fixedFilters}</span>
<textarea className="field min-h-[52px] w-full text-xs" rows={2} value={fixedFilters}
placeholder={D.fixedFiltersPlaceholder} data-draft-fixed-filters=""
onChange={(e) => setFixedFilters(e.target.value)} />
<span className="mt-0.5 block">{D.fixedFiltersHint}</span>
</label>
<button type="button" className="btn btn-primary btn-sm" disabled={submitting || !pickedDocs.length}
onClick={() => onSubmit()} data-draft-submit="">
{submitting ? <Spinner size={12} /> : <FileText size={12} aria-hidden />} {submitting ? '正在导入…' : '导入指标定义表'}
</button>
<button type="button" className="btn btn-ghost btn-sm ml-2" disabled={submitting || !datasourceId || !pickedDocs.length}
onClick={() => onSubmit(false)}>其他文档:AI 起草</button>
</div>
</div>
</section>
)
}
@@ -0,0 +1,316 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { Link } from 'react-router-dom'
import { Play } from 'lucide-react'
import { api } from '../../../api/client'
import { Notice, Spinner } from '../../../components/ui'
import { LEDGER_UI } from '../../../lib/termsLedger'
import { TrialResult, TrialValidation } from '../TrialResult'
import type { CaliberDraft, DraftExpectationSource, DraftTrialOut } from '../../../typesLedger'
import { coversText, defaultText, entryInitialValues, entryInputs, entryReady, qualityReportOf } from './helpers'
const D = LEDGER_UI.drafts
const V = LEDGER_UI.validation
export function useDraftTrial({
detail, setDetail, openSeq, loadList, loadValidations,
}: {
detail: CaliberDraft | null
setDetail: React.Dispatch<React.SetStateAction<CaliberDraft | null>>
openSeq: React.MutableRefObject<number>
loadList: () => void
loadValidations: (id: string) => void
}) {
const [trial, setTrial] = useState<DraftTrialOut | null>(null)
const trialRequestSeq = useRef(0)
const [trialPollId, setTrialPollId] = useState<string | null>(null)
const [trialTimedOut, setTrialTimedOut] = useState(false)
const [trialError, setTrialError] = useState<unknown>(null)
const [entryValues, setEntryValues] = useState<Record<string, string>>({})
const [prefilled, setPrefilled] = useState<Record<string, boolean>>({})
const [trialStarting, setTrialStarting] = useState(false)
const resetTrial = useCallback(() => {
setTrial(null)
setTrialPollId(null)
setTrialTimedOut(false)
setTrialError(null)
}, [])
const initEntryFields = useCallback((draft: CaliberDraft) => {
const marks: Record<string, boolean> = {}
setEntryValues(entryInitialValues(draft.entry_fields ?? [], marks))
setPrefilled(marks)
}, [])
/** 草稿有了试运行就取一次结果;还在 running 就交给下面的轮询 */
useEffect(() => {
const id = detail?.id
const run = detail?.trial?.run_id
if (!id || !run) return
let alive = true
setTrial((cur) => (cur?.run_id === run && detail?.trial?.status !== 'stale' ? cur : {
run_id: run, status: detail?.trial?.status ?? 'running', metrics: [], error: detail?.trial?.error ?? '',
}))
const request = ++trialRequestSeq.current
api.caliberLedger.draftTrial(id).then((out) => {
if (!alive || request !== trialRequestSeq.current) return
setTrial(out)
setTrialError(null)
setTrialTimedOut(false)
if (out.status === 'running') setTrialPollId(id)
}, (e) => {
if (!alive || request !== trialRequestSeq.current) return
setTrialError(e)
setTrialPollId(null)
})
return () => { alive = false }
}, [detail?.id, detail?.version, detail?.trial?.run_id, detail?.trial?.status])
/** 试运行还在跑:每两秒取一次,超过一分钟就停;收尾时顺带刷新详情(状态可能已变成待签字发布) */
useEffect(() => {
if (!trialPollId) return
const until = Date.now() + 60_000
let alive = true
let settled = false
const seq = openSeq.current
let timer: ReturnType<typeof setTimeout>
const poll = () => {
const request = ++trialRequestSeq.current
api.caliberLedger.draftTrial(trialPollId).then((out) => {
if (!alive || seq !== openSeq.current || request !== trialRequestSeq.current) return
setTrial(out)
setTrialError(null)
if (out.status === 'running') {
if (Date.now() > until) {
settled = true
setTrialPollId(null)
setTrialTimedOut(true)
}
return
}
settled = true
setTrialPollId(null)
setTrialTimedOut(false)
loadList()
// 试运行到终态时服务端会把这次跑完的验证记录补记一条:跟着取一次,结论按记录说
loadValidations(trialPollId)
api.caliberLedger.draft(trialPollId).then((fresh) => {
if (seq !== openSeq.current) return
setDetail((cur) => (cur && cur.id === fresh.id && (cur.revision ?? 0) <= (fresh.revision ?? 0) ? fresh : cur))
}, () => undefined)
}, (e) => {
if (!alive || seq !== openSeq.current || request !== trialRequestSeq.current) return
settled = true
setTrialPollId(null)
setTrialError(e)
}).finally(() => {
if (alive && !settled && seq === openSeq.current) timer = setTimeout(poll, 2000)
})
}
timer = setTimeout(poll, 2000)
return () => { alive = false; clearTimeout(timer) }
}, [trialPollId, loadList, loadValidations, openSeq, setDetail])
/**
* 按填好的入口字段再试运行一次:自动试跑缺必填输入时停在 needs_input,人在这里补上。
* 带 expect 时这一条会落成一条带独立期望的验证记录(对得上就是对得上,对不上照实记);不带就是只记试跑结果。
* 入口字段的写法变化只影响这一次请求的参数,不会创建口径定义版本。
*/
const runTrial = useCallback(async (
draft: CaliberDraft,
expect?: { metrics: Record<string, unknown>; source: DraftExpectationSource },
) => {
const fields = draft.entry_fields ?? []
if (!entryReady(fields, entryValues)) return
setTrialStarting(true)
setTrialError(null)
try {
const out = await api.caliberLedger.runDraftTrial(draft.id, entryInputs(fields, entryValues), expect)
setTrial(out)
setTrialTimedOut(false)
if (out.status === 'running' && out.run_id) setTrialPollId(draft.id)
const fresh = await api.caliberLedger.draft(draft.id)
setDetail((cur) => cur?.id === fresh.id ? fresh : cur)
loadValidations(draft.id)
} catch (e) {
setTrialError(e)
} finally {
setTrialStarting(false)
}
}, [entryValues, loadValidations, setDetail])
return {
trial, trialTimedOut, trialError, entryValues, setEntryValues, prefilled, trialStarting,
resetTrial, initEntryFields, runTrial,
}
}
/** 自动试运行:状态、每个指标的值(名字和值成对)、失败原因;没有试运行就整块不画 */
export function DraftTrialSection({
draft, trial, trialTimedOut, trialError,
}: {
draft: CaliberDraft
trial: DraftTrialOut | null
trialTimedOut: boolean
trialError: unknown
}) {
const status = draft.trial?.status === 'stale' ? 'stale' : trial?.status ?? draft.trial?.status
if (!status) return null
const rows = trial?.metrics ?? []
const quality = qualityReportOf(trial?.validation)
const brief = trial?.validation
const own = brief?.record ?? null
const color = status === 'succeeded' ? (quality?.status === 'pass' ? 'var(--ok)' : 'var(--warn)') : status === 'failed' ? 'var(--err)'
: status === 'needs_input' || status === 'stale' ? 'var(--warn)' : 'var(--accent)'
const label = status === 'succeeded' ? D.trialSucceeded : status === 'failed' ? D.trialFailed
: status === 'needs_input' ? D.trialNeedsInput : status === 'stale' ? D.trialStale : D.trialRunning
const unitOf = (id: string) => (draft.metrics ?? []).find((m) => m.id === id)?.unit
return (
<div className="rounded-md border bg-elev px-3 py-2" data-draft-trial={status}>
<div className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5">
<h3 className="text-2xs font-semibold text-dim">{D.trial}</h3>
<span className="text-2xs" style={{ color }}>{label}</span>
{trial?.run_id && (
<Link to={`/runs/${trial.run_id}`} className="text-2xs text-accent hover:underline" data-draft-trial-run="">
{D.trialRun}
</Link>
)}
<span className="text-[10px] text-faint">{D.trialHint}</span>
</div>
{status === 'running' && (
<p className="mt-1 flex items-center gap-1.5 text-2xs text-dim">
<Spinner size={11} /> {D.trialRunning}
</p>
)}
{status === 'running' && trialTimedOut && <div className="mt-1"><Notice tone="warn">{D.trialTimeout}</Notice></div>}
{status === 'failed' && (
<div className="mt-1">
<Notice tone="err">{D.trialFailed}:{trial?.error || draft.trial?.error || D.loadFailed}</Notice>
</div>
)}
{status === 'needs_input' && (
<p className="mt-1 text-2xs text-dim" data-draft-trial-needs-input="">
{D.trialNeedsInputHint}:{trial?.error || draft.trial?.error || ''}
</p>
)}
{status === 'stale' && <p className="mt-1 text-2xs text-dim">{D.trialStaleHint}</p>}
{status === 'succeeded' && (
<>
{rows.length > 0 ? (
<ul className="mt-1 grid gap-x-4 gap-y-0.5 text-2xs sm:grid-cols-[1fr_auto]">
{rows.map((row) => {
const unit = unitOf(row.id)
return (
<li key={row.id} className="contents" data-draft-trial-metric={row.id}>
<span className="text-dim [overflow-wrap:anywhere]">{row.name || row.id}</span>
<span className="tnum text-right font-medium">
{row.rendered ?? (row.value == null ? '—' : String(row.value))}{unit ? ` ${unit}` : ''}
</span>
</li>
)
})}
</ul>
) : (
<p className="mt-1 text-2xs text-faint">{D.trialNoMetrics}</p>
)}
<TrialValidation report={quality} />
<TrialResult queries={trial?.queries} />
</>
)}
{trialError != null && <div className="mt-1"><Notice tone="warn">{D.trialUnavailable}</Notice></div>}
{own ? (
<p className="mt-1.5 text-2xs leading-relaxed text-dim" data-draft-trial-record={own.status}
data-trial-record-covers={own.covers_current === true ? 'yes' : own.covers_current === false ? 'no' : 'unknown'}>
<span className="text-faint">{V.trialRecord}:</span>
{V.status[own.status] ?? own.status}
<span className="text-faint"> · {coversText(own.covers_current)}</span>
<span className="text-faint">
{' · '}{own.expected
? `${V.expected}:${V.sources[own.expected.source] ?? own.expected.source}`
: V.noExpectation}
</span>
</p>
) : status === 'running' ? (
<p className="mt-1.5 flex items-center gap-1.5 text-2xs text-dim" data-draft-trial-waiting="">
<Spinner size={11} /> {V.trialWaiting}
</p>
) : (
<p className="mt-1.5 text-2xs leading-relaxed text-faint" data-draft-trial-no-record="">
{brief?.note || V.trialNoRecord}
</p>
)}
</div>
)
}
/** 入口字段:发布后按这些字段收参数 */
export function DraftEntryFieldsSection({
draft, entryValues, setEntryValues, prefilled, trialStarting, onRunTrial,
}: {
draft: CaliberDraft
entryValues: Record<string, string>
setEntryValues: React.Dispatch<React.SetStateAction<Record<string, string>>>
prefilled: Record<string, boolean>
trialStarting: boolean
onRunTrial: (draft: CaliberDraft) => void
}) {
const fields = draft.entry_fields
const notes = draft.entry_notes ?? []
if (!fields) return null
const canTrial = !!draft.workflow_id
return (
<div data-draft-entry-fields="">
<h3 className="mb-1 text-2xs font-semibold text-dim">{D.entryFields}</h3>
<p className="mb-1 text-2xs text-faint">{D.entryFieldsHint}</p>
{fields.length > 0 ? (
<ul className="space-y-0.5 text-2xs leading-relaxed">
{fields.map((field) => {
const hasDefault = field.default !== undefined && field.default !== null && field.default !== ''
return (
<li key={field.name} className="flex flex-wrap items-center gap-x-2 gap-y-1"
data-draft-entry-field={field.name}>
<code className="font-medium text-dim">{field.name}</code>
<span className="text-faint">{field.type || 'string'}</span>
<span className="text-faint">{field.required ? D.required : D.optional}</span>
{hasDefault && <span className="text-faint">{D.defaultValue(defaultText(field.default))}</span>}
{field.description && <span className="text-dim [overflow-wrap:anywhere]">{field.description}</span>}
{canTrial && (field.type === 'boolean' ? (
<input type="checkbox" className="accent-[var(--accent)]" disabled={trialStarting}
data-draft-entry-input={field.name}
checked={(entryValues[field.name] ?? '') === 'true'}
onChange={(e) => setEntryValues((cur) => ({
...cur, [field.name]: e.target.checked ? 'true' : 'false',
}))} />
) : (
<input className="field w-36 text-2xs" value={entryValues[field.name] ?? ''}
disabled={trialStarting} data-draft-entry-input={field.name}
placeholder={prefilled[field.name] ? D.entryPrefilled : ''}
onChange={(e) => setEntryValues((cur) => ({ ...cur, [field.name]: e.target.value }))} />
))}
</li>
)
})}
</ul>
) : <p className="text-2xs text-faint">{D.entryFieldNone}</p>}
{notes.length > 0 && (
<ul className="mt-1 space-y-0.5 text-2xs leading-relaxed text-warn" data-draft-entry-notes="">
{notes.map((note, i) => <li key={`${i}:${note}`}>{note}</li>)}
</ul>
)}
{canTrial && (
<div className="mt-1.5 flex flex-wrap items-center gap-2">
<button type="button" className="btn btn-xs btn-primary"
disabled={trialStarting || !entryReady(fields, entryValues)}
onClick={() => onRunTrial(draft)} data-draft-trial-run-button="">
{trialStarting ? <Spinner size={11} /> : <Play size={11} aria-hidden />}
{trialStarting ? D.trialRunStarting : D.trialRunAction}
</button>
{Object.keys(prefilled).length > 0 && (
<span className="text-[10px] text-faint">{D.entryPrefilled}</span>
)}
</div>
)}
</div>
)
}
@@ -0,0 +1,372 @@
import { useCallback, useState } from 'react'
import { Link } from 'react-router-dom'
import { Check, Play } from 'lucide-react'
import clsx from 'clsx'
import { api } from '../../../api/client'
import { ErrorState, Spinner, toast } from '../../../components/ui'
import { formatDateTime } from '../../../lib/format'
import { LEDGER_UI } from '../../../lib/termsLedger'
import { useAtLeast } from '../../../store/auth'
import type {
CaliberDraft, DraftExpectationSource, DraftValidationsOut, DraftValidationRecord,
} from '../../../typesLedger'
import {
coversText, entryReady, expectValue, RECORDS_SHOWN, scopeCovers, uncoveredMetrics, valueText,
} from './helpers'
const V = LEDGER_UI.validation
export function useDraftValidations({
openSeq, refreshDetail,
}: {
openSeq: React.MutableRefObject<number>
refreshDetail: (id: string) => Promise<void>
}) {
const [validations, setValidations] = useState<DraftValidationsOut | null>(null)
const [validationsError, setValidationsError] = useState<unknown>(null)
const [reviewOut, setReviewOut] = useState<Record<string, DraftValidationRecord['review']>>({})
const [reviewNotes, setReviewNotes] = useState<Record<string, string>>({})
const [reviewBusy, setReviewBusy] = useState<string | null>(null)
const [reviewError, setReviewError] = useState<unknown>(null)
const [expectValues, setExpectValues] = useState<Record<string, string>>({})
const [expectSource, setExpectSource] = useState<DraftExpectationSource>('human_confirmed')
const [recordsShown, setRecordsShown] = useState(RECORDS_SHOWN)
const resetValidations = useCallback(() => {
setValidations(null)
setValidationsError(null)
setReviewOut({})
setReviewNotes({})
setReviewError(null)
setExpectValues({})
setExpectSource('human_confirmed')
setRecordsShown(RECORDS_SHOWN)
}, [])
const loadValidations = useCallback((id: string) => {
const seq = openSeq.current
api.caliberLedger.draftValidations(id).then(
(out) => { if (seq === openSeq.current) { setValidations(out); setValidationsError(null) } },
(e) => { if (seq === openSeq.current) { setValidations(null); setValidationsError(e) } },
)
}, [openSeq])
const reviewRecord = useCallback(async (
draft: CaliberDraft,
recordId: string,
decision: 'confirmed' | 'rejected',
) => {
setReviewBusy(recordId)
setReviewError(null)
try {
const note = (reviewNotes[recordId] ?? '').trim()
const out = await api.caliberLedger.reviewValidation(draft.id, recordId,
{ decision, ...(note ? { note } : {}) })
setReviewOut((cur) => ({ ...cur, [recordId]: out.record.review ?? null }))
setReviewNotes((cur) => ({ ...cur, [recordId]: '' }))
toast.ok(V.reviewDone(decision === 'confirmed' ? V.reviewConfirmed : V.reviewRejected))
loadValidations(draft.id)
void refreshDetail(draft.id)
} catch (e) {
setReviewError(e)
} finally {
setReviewBusy(null)
}
}, [loadValidations, refreshDetail, reviewNotes])
return {
validations, validationsError, reviewOut, reviewNotes, setReviewNotes,
reviewBusy, reviewError, expectValues, setExpectValues, expectSource, setExpectSource,
recordsShown, setRecordsShown, resetValidations, loadValidations, reviewRecord,
}
}
export function DraftValidationSection({
draft, validations, validationsError, reviewOut, reviewNotes, setReviewNotes,
reviewBusy, reviewError, expectValues, setExpectValues, expectSource, setExpectSource,
recordsShown, setRecordsShown, entryValues, trialStarting, onReviewRecord, onRunTrial,
}: {
draft: CaliberDraft
validations: DraftValidationsOut | null
validationsError: unknown
reviewOut: Record<string, DraftValidationRecord['review']>
reviewNotes: Record<string, string>
setReviewNotes: React.Dispatch<React.SetStateAction<Record<string, string>>>
reviewBusy: string | null
reviewError: unknown
expectValues: Record<string, string>
setExpectValues: React.Dispatch<React.SetStateAction<Record<string, string>>>
expectSource: DraftExpectationSource
setExpectSource: (source: DraftExpectationSource) => void
recordsShown: number
setRecordsShown: React.Dispatch<React.SetStateAction<number>>
entryValues: Record<string, string>
trialStarting: boolean
onReviewRecord: (draft: CaliberDraft, recordId: string, decision: 'confirmed' | 'rejected') => void
onRunTrial: (draft: CaliberDraft, expect?: { metrics: Record<string, unknown>; source: DraftExpectationSource }) => void
}) {
const canReview = useAtLeast('builder')
if (!validations && !validationsError) return null
const metrics = (draft.metrics ?? []).filter((metric) => metric.id)
const names = new Map(metrics.map((metric) => [metric.id as string, metric.name]))
const summary = validations?.summary
const records = validations?.records ?? []
const baseline = validations?.field_baseline
const basisRecord = summary?.record_id ? records.find((record) => record.id === summary.record_id) ?? null : null
const basisReview = basisRecord ? (reviewOut[basisRecord.id] ?? basisRecord.review) : null
const computedMissed = basisRecord ? uncoveredMetrics(basisRecord, basisReview) : []
const serverMissed = summary?.unconfirmed
const missed = serverMissed?.length ? serverMissed : computedMissed
const confirmedNames = (summary?.confirmed?.length ? summary.confirmed : basisReview?.scope ?? [])
.filter((id) => (basisRecord?.metric_ids ?? []).includes(id))
const scopeIncomplete = basisRecord !== null && basisReview?.decision === 'confirmed' && missed.length > 0
const partial = summary?.verdict === 'verified'
&& (scopeIncomplete || (basisRecord !== null && !scopeCovers(basisRecord, basisReview)))
const nameOf = (id: string) => names.get(id) ?? id
const verdict = partial ? 'unverified' : summary?.verdict ?? 'none'
const tone = verdict === 'verified' ? 'var(--ok)'
: verdict === 'mismatched' || verdict === 'failed' || verdict === 'rejected' ? 'var(--err)'
: verdict === 'none' || verdict === 'stale' ? 'var(--text-faint)' : 'var(--warn)'
const fields = draft.entry_fields ?? []
const filled = metrics.filter((metric) => (expectValues[metric.id as string] ?? '').trim())
const ready = filled.length === metrics.length
const wanted: Record<string, unknown> = {}
for (const metric of metrics) wanted[metric.id as string] = expectValue(expectValues[metric.id as string] ?? '')
return (
<div className="rounded-md border bg-elev px-3 py-2" data-draft-validation={verdict}
data-validation-partial={partial ? 'recalled' : scopeIncomplete ? 'scope' : 'no'}>
<div className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5">
<h3 className="text-2xs font-semibold text-dim">{V.title}</h3>
<span className="text-2xs" data-draft-validation-verdict={verdict} style={{ color: tone }}>
{V.verdict[verdict] ?? verdict}
</span>
{summary?.method?.version != null && <span className="text-[10px] text-faint">{V.method(summary.method.version)}</span>}
</div>
{summary && <p className="mt-1 text-2xs leading-relaxed text-dim" data-draft-validation-reason="">{summary.reason}</p>}
{(partial || scopeIncomplete) && (
<p className="mt-0.5 text-2xs leading-relaxed text-[var(--warn)]" data-draft-validation-partial="">
{V.partialVerdict(confirmedNames.map(nameOf).join('、'), missed.map(nameOf).join('、') || '—',
basisRecord?.metric_ids?.length ?? 0)}
</p>
)}
{summary && (
<p className="mt-0.5 text-2xs text-faint" data-draft-validation-basis="">
{basisRecord
? V.basis(basisRecord.created_at ? formatDateTime(basisRecord.created_at) : '—',
V.status[basisRecord.status] ?? basisRecord.status)
: V.basisNone}
</p>
)}
{summary && (
<p className="mt-0.5 tnum text-2xs text-faint" data-draft-validation-counts="">
{V.counts(summary.counts?.total ?? 0, summary.counts?.covering ?? 0)}
</p>
)}
{!!summary?.semantic_gaps?.length && (
<p className="mt-0.5 text-2xs text-faint" data-draft-validation-gaps="">
{V.semanticGaps(summary.semantic_gaps.length)}
</p>
)}
{baseline && (
<p className="mt-0.5 text-2xs leading-relaxed text-faint" data-draft-baseline={baseline.status}>
{V.baseline}:{baseline.status === 'known'
? V.baselineKnown(baseline.accepted_revision ?? null, (baseline.metric_ids ?? []).length,
baseline.field_count ?? 0)
: V.baselineUnknown}
{baseline.status === 'known' ? `。${V.baselineHint}` : ''}
</p>
)}
{validationsError != null && <div className="mt-1"><ErrorState error={validationsError} compact /></div>}
{reviewError != null && <div className="mt-1"><ErrorState error={reviewError} compact /></div>}
{records.length === 0 ? (
<p className="mt-1 text-2xs leading-relaxed text-faint" data-draft-validations-empty="">
{V.empty}:{V.emptyBody}
</p>
) : (
<>
<div className="mt-1.5 flex flex-wrap items-baseline gap-x-2">
<h4 className="text-2xs font-semibold text-faint">{V.records}</h4>
<span className="text-[10px] text-faint">{V.fieldsHint}</span>
</div>
<ul className="mt-1 space-y-1.5">
{records.slice(0, recordsShown).map((record) => {
const review = reviewOut[record.id] ?? record.review
const expected = record.expected
const ids = record.metric_ids ?? []
const covering = record.covers_current
return (
<li key={record.id} className="rounded border bg-panel px-2 py-1.5"
data-draft-validation-record={record.id} data-record-status={record.status}>
<div className="flex flex-wrap items-baseline gap-x-2 gap-y-0.5 text-2xs">
<span className="font-medium text-dim" data-record-status-label="">
{V.status[record.status] ?? record.status}
</span>
<span className={clsx(covering === true ? 'text-dim' : 'text-faint')}
data-record-covers={covering === true ? 'yes' : covering === false ? 'no' : 'unknown'}>
{coversText(covering)}
</span>
{record.created_at && <span className="text-faint">{formatDateTime(record.created_at)}</span>}
{record.run_id && (
<Link to={`/runs/${record.run_id}`} className="text-accent hover:underline" data-record-run="">
{V.openRun}
</Link>
)}
</div>
<div className="mt-1 text-2xs leading-relaxed" data-record-expect={expected ? 'given' : 'none'}>
<span className="text-faint">{V.expected}</span>
{expected ? (
<>
<span className="text-faint"> · {V.expectedSource}:{V.sources[expected.source] ?? expected.source}</span>
<ul className="mt-0.5 space-y-0.5">
{ids.map((metricId) => (
<li key={metricId} className="flex flex-wrap items-baseline gap-x-2"
data-record-expect-value={metricId}>
<span className="text-dim [overflow-wrap:anywhere]">{names.get(metricId) ?? metricId}</span>
<span className="tnum">{valueText(expected.metrics?.[metricId])}</span>
</li>
))}
</ul>
</>
) : (
<span className="text-[var(--warn)]" data-record-no-expect="">:{V.expectedNone}</span>
)}
</div>
<div className="mt-1 text-2xs leading-relaxed">
<span className="text-faint">{V.actual}</span>
<ul className="mt-0.5 space-y-0.5">
{ids.map((metricId) => {
const actual = record.actual?.[metricId] ?? {}
const shown = actual.masked ? V.masked : (actual.rendered || valueText(actual.value) || V.noValue)
return (
<li key={metricId} className="flex flex-wrap items-baseline gap-x-2"
data-record-actual={metricId} data-record-actual-ok={String(actual.ok ?? 'unknown')}>
<span className="text-dim [overflow-wrap:anywhere]">{names.get(metricId) ?? metricId}</span>
<span className="tnum">{shown}</span>
{actual.rows != null && <span className="text-faint">{V.rowsHint(actual.rows)}</span>}
<span style={{ color: actual.ok === true ? 'var(--ok)'
: actual.ok === false ? 'var(--err)' : 'var(--text-faint)' }}>
{actual.ok === true ? V.ok : actual.ok === false ? V.notOk : V.unknown}
</span>
</li>
)
})}
</ul>
</div>
{!!record.problems?.length && (
<ul className="mt-1 list-disc space-y-0.5 pl-4 text-2xs leading-relaxed text-[var(--warn)]"
data-record-problems="">
{record.problems.map((problem, i) => <li key={`${i}:${problem}`}>{problem}</li>)}
</ul>
)}
<div className="mt-1 border-t pt-1" data-record-review={review?.decision ?? 'none'}>
{review ? (
<p className="text-2xs leading-relaxed text-dim" data-record-review-line="">
{review.decision === 'rejected' ? V.reviewRejected : V.reviewConfirmed}
<span className="text-faint"> · {V.reviewBy(review.actor || '—', !!review.verified)}</span>
{review.created_at ? <span className="text-faint"> · {formatDateTime(review.created_at)}</span> : ''}
{!!review.scope?.length && (
<span className="text-faint">
{' · '}{V.reviewScope}:{review.scope.map((id) => names.get(id) ?? id).join('、')}
</span>
)}
{review.decision === 'confirmed' && !scopeCovers(record, review) && (
<span className="text-[var(--warn)]" data-record-review-partial="">
{' · '}{V.reviewPartial}
{uncoveredMetrics(record, review).length > 0
? `(没盖住${uncoveredMetrics(record, review).map((id) => names.get(id) ?? id).join('、')})`
: ''}
</span>
)}
{review.covers_current === true ? (
<span className="text-faint" data-record-review-covers="yes"> · {V.reviewCovers}</span>
) : review.covers_current === false ? (
<span className="text-faint" data-record-review-covers="no"> · {V.reviewNotCovering}</span>
) : (
<span className="text-faint" data-record-review-covers="unknown">
{' · '}{V.reviewCoversUnknown}
</span>
)}
{review.note && <span className="text-faint"> · {review.note}</span>}
</p>
) : <p className="text-2xs text-faint">{V.noReview}</p>}
{canReview && (
<div className="mt-1 flex flex-wrap items-center gap-2">
<input className="field w-44 text-2xs" data-draft-review-note={record.id}
aria-label={V.reviewNote} placeholder={V.reviewNotePlaceholder}
value={reviewNotes[record.id] ?? ''} disabled={reviewBusy === record.id}
onChange={(e) => setReviewNotes((cur) => ({ ...cur, [record.id]: e.target.value }))} />
<button type="button" className="btn btn-xs" data-draft-review="confirmed"
disabled={reviewBusy === record.id}
onClick={() => onReviewRecord(draft, record.id, 'confirmed')}>
{reviewBusy === record.id ? <Spinner size={11} /> : <Check size={11} aria-hidden />} {V.confirm}
</button>
<button type="button" className="btn btn-xs btn-ghost" data-draft-review="rejected"
disabled={reviewBusy === record.id}
onClick={() => onReviewRecord(draft, record.id, 'rejected')}>
{V.reject}
</button>
<span className="text-[10px] text-faint">{V.reviewScopeHint}</span>
</div>
)}
</div>
</li>
)
})}
</ul>
{records.length > recordsShown && (
<button type="button" className="btn btn-xs btn-ghost mt-1" data-draft-validations-more=""
onClick={() => setRecordsShown((cur) => cur + RECORDS_SHOWN)}>
{V.more(records.length - recordsShown)}
</button>
)}
</>
)}
{metrics.length > 0 && (
<details className="mt-2 rounded border bg-panel px-2 py-1.5" data-draft-expect="">
<summary className="cursor-pointer text-2xs font-semibold text-dim">{V.trialWithExpect}</summary>
<p className="mt-0.5 text-2xs leading-relaxed text-faint">
{V.trialWithExpectHint}。{V.expectedHint}
</p>
<ul className="mt-1 space-y-0.5">
{metrics.map((metric) => (
<li key={metric.id} className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-2xs">
<span className="text-dim [overflow-wrap:anywhere]">{V.expectFor(metric.name)}</span>
<input className="field w-32 text-2xs" data-draft-expect-input={metric.id}
aria-label={V.expectFor(metric.name)} disabled={trialStarting}
value={expectValues[metric.id as string] ?? ''}
onChange={(e) => setExpectValues((cur) => ({ ...cur, [metric.id as string]: e.target.value }))} />
</li>
))}
</ul>
<div className="mt-1 flex flex-wrap items-center gap-2 text-2xs">
<label className="flex items-center gap-1 text-faint">
{V.expectSourceLabel}
<select className="field h-[26px] text-2xs" value={expectSource} data-draft-expect-source=""
disabled={trialStarting}
onChange={(e) => setExpectSource(e.target.value as DraftExpectationSource)}>
{(Object.keys(V.sources) as DraftExpectationSource[]).map((key) => (
<option key={key} value={key}>{V.sources[key]}</option>
))}
</select>
</label>
<button type="button" className="btn btn-xs" data-draft-expect-submit=""
disabled={trialStarting || !ready || !entryReady(fields, entryValues)}
onClick={() => onRunTrial(draft, { metrics: wanted, source: expectSource })}>
{trialStarting ? <Spinner size={11} /> : <Play size={11} aria-hidden />}
{trialStarting ? V.expectSubmitting : V.expectSubmit}
</button>
{!ready && <span className="text-faint" data-draft-expect-needall="">{V.expectNeedAll}</span>}
</div>
</details>
)}
</div>
)
}
+371
View File
@@ -0,0 +1,371 @@
import { LEDGER_UI } from '../../../lib/termsLedger'
import type {
CaliberDraft, CaliberDraftStage, CaliberDraftSummary, DraftBinding, DraftEditableField, DraftEntryField,
DraftImportField, DraftImportItem, DraftImportRun, DraftOperation, DraftTrialValidation,
DraftValidationRecord, DraftValidationReview, QualityReport,
} from '../../../typesLedger'
const I = LEDGER_UI.imports
const N = LEDGER_UI.nl
const V = LEDGER_UI.validation
/** 列表按阶段筛:全部、起草中、待审、已丢弃、失败;细状态不再单独占筛选项 */
export type Filter = '' | CaliberDraftStage
export const FILTERS: Filter[] = ['', 'drafting', 'review', 'discarded', 'failed']
/** 细状态 → 界面阶段;旧服务端没有 stage 时按 status 推,页面不会因为少一个字段就空 */
export const stageOf = (draft: CaliberDraftSummary | CaliberDraft): CaliberDraftStage =>
draft.stage ?? (draft.status === 'drafting' ? 'drafting' : draft.status === 'rejected' ? 'discarded'
: draft.status === 'failed' ? 'failed' : 'review')
/** 起草轮询:每两秒一次,多轮续跑要几分钟,最多等十五分钟无进展 */
export const DRAFT_POLL_MS = 2_000
export const DRAFT_POLL_LIMIT_MS = 15 * 60_000
/** 验证记录默认摆最近几条,其余收在「展开其余 N 条」后面 */
export const RECORDS_SHOWN = 3
/**
* 幂等键(K02):服务端按「主体 + 工作流 + 目标卡 + request_id」认这一次修改。同一批勾选的问题反复提交(网络
* 断了、手点重试)用同一个键,服务端认得出是同一件事、不会多存一版;勾选或草稿变了才换一个。
*/
export const newRequestId = () =>
typeof crypto !== 'undefined' && 'randomUUID' in crypto
? crypto.randomUUID()
: `patch-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`
/** span 是引用在段落原文里的 [start, end):切成「前 / 引用 / 后」三段高亮 */
export function spanParts(content: string, span?: [number, number]): [string, string, string] | null {
if (!span) return null
const [start, end] = span
if (start < 0 || end > content.length || start >= end) return null
return [content.slice(0, start), content.slice(start, end), content.slice(end)]
}
/** 缺省值直接读:字符串照写,其他转成 JSON 文本 */
export function defaultText(value: unknown): string {
if (typeof value === 'string') return value
const text = JSON.stringify(value)
return text ?? String(value)
}
/** 入口字段预填的日期:YYYY-MM-DD,按本地日期算 */
export function dayText(offsetDays: number): string {
const day = new Date()
day.setDate(day.getDate() + offsetDays)
const pad = (n: number) => String(n).padStart(2, '0')
return `${day.getFullYear()}-${pad(day.getMonth() + 1)}-${pad(day.getDate())}`
}
/**
* 名字或说明里带「开始 / start」的日期字段预填七天前,带「结束 / end」的预填今天:
* 这两个值基本总是要填的,给个能改的范围比留空省一步。其余必填字段留空,让人自己写。
*/
export function datePrefill(field: DraftEntryField): string | null {
if ((field.type || 'string') !== 'string') return null
const hint = `${field.name} ${field.description ?? ''}`.toLowerCase()
if (hint.includes('开始') || /(^|[^a-z])start([^a-z]|$)/.test(hint)) return dayText(-7)
if (hint.includes('结束') || /(^|[^a-z])end([^a-z]|$)/.test(hint)) return dayText(0)
return null
}
/** 入口字段的初值:有缺省值就用缺省值,日期字段按上面的规则预填,其余留空 */
export function entryInitialValues(fields: DraftEntryField[], prefilled: Record<string, boolean>): Record<string, string> {
const values: Record<string, string> = {}
for (const field of fields) {
const hasDefault = field.default !== undefined && field.default !== null && field.default !== ''
if (hasDefault) { values[field.name] = defaultText(field.default); continue }
const guess = datePrefill(field)
values[field.name] = guess ?? ''
if (guess) prefilled[field.name] = true
}
return values
}
/** 必填字段是不是都填了:布尔量总有值,数字要能读成数 */
export function entryReady(fields: DraftEntryField[], values: Record<string, string>): boolean {
return fields.every((field) => {
if (!field.required) return true
const type = field.type || 'string'
if (type === 'boolean') return true
const text = (values[field.name] ?? '').trim()
if (!text) return false
return type === 'number' || type === 'integer' ? Number.isFinite(Number(text)) : true
})
}
/** 表单值换成接口要的 inputs:空字符串不传(服务端会用缺省值),数字转成数,布尔转成开关 */
export function entryInputs(fields: DraftEntryField[], values: Record<string, string>): Record<string, unknown> {
const inputs: Record<string, unknown> = {}
for (const field of fields) {
const type = field.type || 'string'
const text = values[field.name] ?? ''
if (type === 'boolean') { inputs[field.name] = text === 'true'; continue }
if (!text.trim()) continue
if (type === 'number' || type === 'integer') {
const num = Number(text)
if (Number.isFinite(num)) inputs[field.name] = num
continue
}
inputs[field.name] = text
}
return inputs
}
// ---------------------------------------------------------------- K06:业务规则、变更预览、验证记录
/** 业务值的说法:能力描述给了机器值 → 给人看的说法就用它,没有就照原样写 */
export const choiceLabel = (field: DraftEditableField | undefined, value: string): string =>
field?.value_labels?.[value] ?? value
/** 一个值转成页面上的一行文字:字符串照写,数字、布尔照写,对象转成 JSON 文本 */
export function valueText(value: unknown): string {
if (value == null) return ''
if (typeof value === 'string') return value
if (typeof value === 'number' || typeof value === 'boolean') return String(value)
const text = JSON.stringify(value)
return text ?? String(value)
}
/**
* 表单初值:这一项在**所有**声明它的指标上写法一致时就是那个值,不一致(或没人声明)时留空。
* 留空表示「保持各自现在的写法」——不替人选一个默认值,也就不会因为打开页面就凭空改掉谁。
*/
export function ruleInitialValues(binding?: DraftBinding): Record<string, string> {
const out: Record<string, string> = {}
if (!binding) return out
const declared = Object.values(binding.metric_values ?? {})
for (const field of binding.editable_fields ?? []) {
const seen = new Set(declared.map((values) => values[field.field]).filter((value): value is string => !!value))
out[field.field] = seen.size === 1 ? [...seen][0] : ''
}
return out
}
/** 这一项这些指标里有没有人声明:一个都没有时这一项改不了(没有落点的取数不会被硬改) */
export const declaringMetrics = (binding: DraftBinding | undefined, field: string): string[] =>
Object.entries(binding?.metric_values ?? {})
.filter(([, values]) => !!values[field]).map(([metricId]) => metricId)
/** 这次选中的写法会改到哪几条指标、每条从什么变成什么:只有声明了这一项、而且写法和选中的不一样才算 */
export function rulePlan(binding: DraftBinding | undefined, values: Record<string, string>) {
const operations: DraftOperation[] = []
const changes: { metricId: string; name: string; field: DraftEditableField; from: string; to: string }[] = []
for (const field of binding?.editable_fields ?? []) {
const chosen = values[field.field] ?? ''
if (!chosen) continue
for (const [metricId, declared] of Object.entries(binding?.metric_values ?? {})) {
const now = declared[field.field]
if (!now || now === chosen) continue
operations.push({ op: 'set', metric_id: metricId, path: `/${field.field}`, value: chosen })
changes.push({ metricId, name: '', field, from: now, to: chosen })
}
}
return { operations, changes }
}
/**
* 撤销这次修改要提交的逆操作:按**保存前**每一条指标声明的值构造——原来有值就设回去,原来没声明就删掉。
* 撤销和保存一样是新增一版(当前版本 + 新的请求键),不整份覆盖、不改写已经存下的版本。
*/
export function undoOperations(binding: DraftBinding | undefined, operations: DraftOperation[]): DraftOperation[] {
return operations.map((op) => {
const field = op.path.replace(/^\//, '')
const before = binding?.metric_values?.[op.metric_id]?.[field]
return before
? { op: 'set', metric_id: op.metric_id, path: op.path, value: before }
: { op: 'remove', metric_id: op.metric_id, path: op.path }
})
}
// ---------------------------------------------------------------- K11 / K12:字段的说法、三方值、一句话的影响
/**
* 字段路径 → 给人看的标签(K03 白名单和 app/ledger/changes.FIELDS 同一套,业务字段另有能力描述里的标签)。
* 页面上只写这些业务说法,路径本身不上来。
*/
const FIELD_LABELS: Record<string, string> = {
'/synonyms': '同义词',
'/unit': '单位',
'/decimals': '小数位',
'/format': '展示格式',
'/expression': '取值表达式',
'/grain': '粒度',
'/time_field': '时间字段',
'/numerator': '分子',
'/denominator': '分母',
'/dimensions': '维度',
'/filters': '过滤条件',
'/definition/text': '口径说明',
'/definition/scope': '适用范围',
'/definition/exclusions': '不包含',
'/definition/citations': '引用原文',
'/time_role': '统计时间口径',
'/refund_rule': '退款处理',
}
/** 引用原文在 B / L / R 里是一段带段落 id 的结构化内容:只写有几段,不摆内容 */
const CITATIONS_PATH = '/definition/citations'
export const fieldLabel = (path: string, binding?: DraftBinding): string => {
const name = path.replace(/^\//, '')
const editable = (binding?.editable_fields ?? []).find((field) => field.field === name)
return editable?.label ?? FIELD_LABELS[path] ?? I.otherField
}
/** 业务字段的机器值 → 给人看的说法(能力描述里有就用它,没有就照原样写) */
export const valueLabelOf = (value: unknown, binding?: DraftBinding, path?: string): string => {
if (value == null) return I.noValue
if (typeof value === 'boolean') return value ? '是' : '否'
if (typeof value === 'number') return String(value)
if (typeof value === 'string') {
const name = String(path ?? '').replace(/^\//, '')
const editable = (binding?.editable_fields ?? []).find((field) => field.field === name)
return editable?.value_labels?.[value] ?? value
}
if (Array.isArray(value)) {
if (path === CITATIONS_PATH) return I.citationCount(value.length)
const parts = value.map((item) => valueLabelOf(item, binding, path))
return parts.length ? parts.join('、') : I.emptyValue
}
if (typeof value === 'object') return I.objectValue
return String(value)
}
/** 一格的一行字:这一格没有时返回 null(整行不画),不把「没有这一格」写成空值 */
export function cellText(cell: DraftImportField, which: 'b' | 'l' | 'r', binding?: DraftBinding): string | null {
const present = which === 'b' ? cell.b_present : which === 'l' ? cell.l_present : cell.r_present
if (!present) return null
return valueLabelOf(cell[which], binding, cell.path)
}
/** 选中的格子:一条工作项 + 一条字段路径(未对齐的工作项没有可接受的字段,拒绝对齐前不能选) */
export const pickKey = (itemId: string, path: string): string => `${itemId}\u0000${path}`
/** 服务端标的「这条抽坏了」(引用没有给过模型的原文):也可能是老服务端只给了状态 */
export const itemFailed = (item: DraftImportItem): boolean => item.failed ?? item.status === 'failed'
/** 这个工作项现在能不能接受:抽坏了的(failed)、没对齐上的,一律不能 */
export const itemAccepts = (item: DraftImportItem): boolean => !itemFailed(item) && !!item.metric_id
/**
* 这条工作项上「无冲突更新 + 新增候选」的格子:一次收掉的按钮按它算有几格,并把这几格**明确列给服务端**
* (不发 auto:页面列了几格就只接受几格)。已经接受 / 拒绝过的格子不再算进来,抽坏了的工作项一个也不收。
*/
export const cleanPaths = (item: DraftImportItem): string[] =>
itemFailed(item) ? [] : item.fields.filter((cell) => (cell.state === 'update' || cell.state === 'new')
&& cell.decided !== 'accepted' && cell.decided !== 'rejected').map((cell) => cell.path)
/**
* 按这一次导入**现在**的现状裁掉不再适用的选择:格子没了、已经决定过、不能接受、工作项抽坏了的都不留下。
* stale 之后重新读回现状时用它——不拿旧的选择去提交(旧的选择可能对着已经变了的 L)。
*/
export function prunePicks(picks: Record<string, 'accept' | 'reject'>, run: DraftImportRun):
Record<string, 'accept' | 'reject'> {
const out: Record<string, 'accept' | 'reject'> = {}
for (const item of run.items) {
for (const cell of item.fields) {
const choice = picks[pickKey(item.item_id, cell.path)]
if (!choice || cell.decided != null) continue
if (choice === 'accept' && (!itemAccepts(item) || !cell.acceptable)) continue
out[pickKey(item.item_id, cell.path)] = choice
}
}
return out
}
/** 还没处置完的工作项:恢复只对这些有意义(已接受 / 拒绝 / 不变的不动) */
export const unfinishedItems = (run: DraftImportRun): number =>
run.items.filter((item) => !['accepted', 'rejected', 'unchanged'].includes(item.status)).length
/** 一句话提案里的一处影响:哪条指标、哪一项写法、现在什么 → 保存后什么(页面上只写业务说法) */
export interface NlChange {
metricId: string
name: string
label: string
from: string
to: string
remove: boolean
}
/** 提案里的字段操作 → 人读得懂的影响:指标名 + 字段标签 + 前后值,不摆 path / metric_id / JSON */
export function nlChanges(draft: CaliberDraft, operations: DraftOperation[]): NlChange[] {
const metrics = new Map((draft.metrics ?? []).filter((metric) => metric.id).map((metric) => [metric.id as string, metric]))
return (operations ?? []).map((operation) => {
const name = operation.path.replace(/^\//, '')
const metric = metrics.get(operation.metric_id)
const declared = draft.binding?.metric_values?.[operation.metric_id]?.[name]
?? (metric ? (metric as unknown as Record<string, unknown>)[name] : undefined)
const remove = operation.op === 'remove'
return {
metricId: operation.metric_id,
name: metric?.name ?? N.unknownMetric,
label: fieldLabel(operation.path, draft.binding),
from: valueLabelOf(declared, draft.binding, operation.path),
to: remove ? N.removeValue : valueLabelOf(operation.value, draft.binding, operation.path),
remove,
}
})
}
/**
* 落版之后服务端交回的操作和预览里的是不是同一批(按「改哪条指标的哪个字段、怎么改」比)。
* 同一段原文应当解析出同一批;不一样就说明页面显示的和实际落下的不是一回事,要照实提示。
* 审计读不回来(老服务端不给这一段)时返回 null:判不了就说判不了,不假装一致。
*/
export function sameOperations(previewed: DraftOperation[],
applied: { op: string; metric_id: string; path: string }[] | undefined): boolean | null {
if (!applied) return null
const key = (op: { op: string; metric_id: string; path: string }) => `${op.op}|${op.metric_id}|${op.path}`
const before = [...new Set(previewed.map(key))].sort()
const after = [...new Set(applied.map(key))].sort()
return before.length === after.length && before.every((item, index) => item === after[index])
}
/**
* 独立期望里填的一格:整数、小数写成数,true / false 写成布尔,方括号花括号按 JSON 读,其余照字面写。
* 服务端按**原值**比较(不做隐式舍入),这里也不替它换算。
*/
export function expectValue(text: string): unknown {
const trimmed = text.trim()
if (/^-?\d+(?:\.\d+)?$/.test(trimmed)) return Number(trimmed)
if (trimmed === 'true' || trimmed === 'false') return trimmed === 'true'
if (trimmed.startsWith('[') || trimmed.startsWith('{')) {
try { return JSON.parse(trimmed) } catch { return trimmed }
}
return trimmed
}
/**
* 试跑响应里的质量结论:只有服务端给了认得的状态才算一份质量报告。
* stale / needs_input / running 这些分支的 validation 可能只有验证记录那一段、甚至什么都没有——
* 读不到状态就是「没有质量结论」,不能当成通过(也不能拿一次试跑成功代替验证)。
*/
export function qualityReportOf(validation?: DraftTrialValidation | null): QualityReport | null {
const status = validation?.status
if (status !== 'pass' && status !== 'fail' && status !== 'unknown') return null
return { status, checks: validation?.checks ?? [] }
}
/**
* 覆盖判断:**只有 === true 才算覆盖**。false 是不覆盖,null / 缺字段是判不了(读不到当前依据),
* 三者要在界面上分开写,不能把判不了默认成覆盖。
*/
export const coversText = (value: boolean | null | undefined): string =>
value === true ? V.covers : value === false ? V.notCovers : V.coversUnknown
/**
* 一条审阅的确认范围有没有盖住整条记录的全部指标:只确认了其中几条时不能写成整卡通过。
* scope 空着(或者读数缺字段)一律按「没盖住」算——宁可不写通过,不替服务端把范围补全。
*/
export function scopeCovers(record: DraftValidationRecord, review: DraftValidationReview | null | undefined): boolean {
const scope = new Set(review?.scope ?? [])
const ids = record.metric_ids ?? []
if (!ids.length) return scope.size > 0
return ids.every((id) => scope.has(id))
}
/** 这条记录里没有被确认范围盖住的指标 */
export function uncoveredMetrics(record: DraftValidationRecord, review: DraftValidationReview | null | undefined): string[] {
const scope = new Set(review?.scope ?? [])
return (record.metric_ids ?? []).filter((id) => !scope.has(id))
}
+3 -1
View File
@@ -33,7 +33,9 @@ export function Composer({ hero, onFocusChange }: {
}) {
const nodes = useStudio((s) => s.nodes)
const copilot = useStudio((s) => s.copilot)
const { runCopilot, stopCopilot, retryCopilot } = useStudio()
const runCopilot = useStudio((s) => s.runCopilot)
const stopCopilot = useStudio((s) => s.stopCopilot)
const retryCopilot = useStudio((s) => s.retryCopilot)
const providers = useCatalog((s) => s.providers)
const tools = useCatalog((s) => s.tools)
// 数据源和检查器挑工具读的是 catalog 里同一份(数据页改了会 reload)。停用的助手看不见,不算
+45 -4
View File
@@ -49,11 +49,29 @@ export interface TaskCounts {
latest?: string | null
}
/** 心跳间隔:连着时复用 4 秒一次的待审批轮询,不另起请求 */
/** 心跳间隔:连着时复用 4 秒一次的待审批轮询,不另起请求;标签页切到后台时放慢到 16 秒,回到前台立即补刷 */
const HEARTBEAT_MS = 4000
const HIDDEN_HEARTBEAT_MS = 16_000
/** 断开后的重试退避 */
const BACKOFF_MS = [4000, 8000, 16000]
function sameTaskCounts(a: TaskCounts | null, b: TaskCounts): boolean {
return !!a && a.mine === b.mine && a.apps === b.apps && a.other === b.other && (a.latest ?? null) === (b.latest ?? null)
}
function sameApprovals(a: Approval[], b: Approval[]): boolean {
if (a.length !== b.length) return false
for (let i = 0; i < a.length; i++) {
const x = a[i]
const y = b[i]
if (x.id !== y.id || x.status !== y.status || x.run_id !== y.run_id
|| x.title !== y.title || x.created_at !== y.created_at) {
return false
}
}
return true
}
/** 全局参照数据:属性面板的各种下拉都从这里取,只加载一次。 */
export interface CatalogState {
providers: Provider[]
@@ -156,6 +174,7 @@ export const useCatalog = create<CatalogState>((set, get) => {
const applyCounts = (seq: number, counts: TaskCounts) => {
if (seq < countApplied) return
countApplied = seq
if (sameTaskCounts(get().taskCounts, counts)) return
set({ taskCounts: counts })
}
@@ -284,7 +303,12 @@ export const useCatalog = create<CatalogState>((set, get) => {
if (approvals.status === 'fulfilled' && approvals.value) {
// 这一拍在路上时又发起了 refresh、而且那次已经填过了:以那次为准
const list = approvals.value
if (claim('approvals', seq)) set((s) => ({ approvals: list, loadedAt: { ...s.loadedAt, approvals: Date.now() } }))
if (claim('approvals', seq)) {
set((s) => ({
...(sameApprovals(s.approvals, list) ? {} : { approvals: list }),
loadedAt: { ...s.loadedAt, approvals: Date.now() },
}))
}
}
// 后端回了错误码说明它还活着,列表保持原样;够不着才去确认是否断开
const e = probe.status === 'rejected' ? probe.reason : null
@@ -324,17 +348,34 @@ export const useCatalog = create<CatalogState>((set, get) => {
const me = Symbol('heartbeat')
heartbeatOwner = me
let timer: ReturnType<typeof setTimeout> | undefined
const nextDelay = () =>
(typeof document !== 'undefined' && document.visibilityState === 'hidden'
? HIDDEN_HEARTBEAT_MS
: HEARTBEAT_MS)
// 链式 setTimeout 而不是 setInterval:后端慢的时候上一拍没回来,不叠下一拍
const tick = async () => {
if (heartbeatOwner !== me) return
await get().refreshApprovals()
if (heartbeatOwner !== me) return
timer = setTimeout(() => void tick(), HEARTBEAT_MS)
timer = setTimeout(() => void tick(), nextDelay())
}
timer = setTimeout(() => void tick(), HEARTBEAT_MS)
const onVisibility = () => {
if (heartbeatOwner !== me) return
if (document.visibilityState === 'visible') {
if (timer) clearTimeout(timer)
void tick()
}
}
if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', onVisibility)
}
timer = setTimeout(() => void tick(), nextDelay())
return () => {
if (heartbeatOwner === me) heartbeatOwner = null
if (timer) clearTimeout(timer)
if (typeof document !== 'undefined') {
document.removeEventListener('visibilitychange', onVisibility)
}
}
},
}
+124
View File
@@ -0,0 +1,124 @@
import type { Connection, Edge, EdgeChange, Node, NodeChange } from '@xyflow/react'
type FlowHelpers = {
applyNodeChanges: <NodeType extends Node = Node>(changes: NodeChange<NodeType>[], nodes: NodeType[]) => NodeType[]
applyEdgeChanges: <EdgeType extends Edge = Edge>(changes: EdgeChange<EdgeType>[], edges: EdgeType[]) => EdgeType[]
addEdge: <EdgeType extends Edge = Edge>(edgeParams: EdgeType | Connection, edges: EdgeType[]) => EdgeType[]
}
function applySingleChange(change: any, element: any): void {
switch (change.type) {
case 'select':
element.selected = change.selected
break
case 'position':
if (typeof change.position !== 'undefined') element.position = change.position
if (typeof change.dragging !== 'undefined') element.dragging = change.dragging
break
case 'dimensions':
if (typeof change.dimensions !== 'undefined') {
element.measured = { ...change.dimensions }
if (change.setAttributes) {
if (change.setAttributes === true || change.setAttributes === 'width') {
element.width = change.dimensions.width
}
if (change.setAttributes === true || change.setAttributes === 'height') {
element.height = change.dimensions.height
}
}
}
if (typeof change.resizing === 'boolean') element.resizing = change.resizing
break
}
}
function applyChangesFallback<Item extends { id: string }>(changes: any[], elements: Item[]): Item[] {
const updatedElements: Item[] = []
const changesMap = new Map<string, any[]>()
const addItemChanges: any[] = []
for (const change of changes) {
if (change.type === 'add') {
addItemChanges.push(change)
} else if (change.type === 'remove' || change.type === 'replace') {
changesMap.set(change.id, [change])
} else {
const list = changesMap.get(change.id)
if (list) list.push(change)
else changesMap.set(change.id, [change])
}
}
for (const element of elements) {
const queued = changesMap.get(element.id)
if (!queued) {
updatedElements.push(element)
continue
}
if (queued[0].type === 'remove') continue
if (queued[0].type === 'replace') {
updatedElements.push({ ...queued[0].item })
continue
}
const copy = { ...element }
for (const change of queued) applySingleChange(change, copy)
updatedElements.push(copy)
}
for (const change of addItemChanges) {
if (change.index !== undefined) updatedElements.splice(change.index, 0, { ...change.item })
else updatedElements.push({ ...change.item })
}
return updatedElements
}
function addEdgeFallback<EdgeType extends Edge = Edge>(
edgeParams: EdgeType | Connection,
edges: EdgeType[],
): EdgeType[] {
if (!edgeParams.source || !edgeParams.target) return edges
const sourceHandle = edgeParams.sourceHandle ?? null
const targetHandle = edgeParams.targetHandle ?? null
const exists = edges.some(
(e) => e.source === edgeParams.source
&& e.target === edgeParams.target
&& (e.sourceHandle ?? null) === sourceHandle
&& (e.targetHandle ?? null) === targetHandle,
)
if (exists) return edges
const id = ('id' in edgeParams && edgeParams.id)
? edgeParams.id
: `xy-edge__${edgeParams.source}${sourceHandle || ''}-${edgeParams.target}${targetHandle || ''}`
return [...edges, { ...edgeParams, id, sourceHandle, targetHandle } as EdgeType]
}
let impl: FlowHelpers = {
applyNodeChanges: applyChangesFallback,
applyEdgeChanges: applyChangesFallback,
addEdge: addEdgeFallback,
}
export function registerFlowHelpers(next: FlowHelpers): void {
impl = next
}
export function applyNodeChanges<NodeType extends Node = Node>(
changes: NodeChange<NodeType>[],
nodes: NodeType[],
): NodeType[] {
return impl.applyNodeChanges(changes, nodes)
}
export function applyEdgeChanges<EdgeType extends Edge = Edge>(
changes: EdgeChange<EdgeType>[],
edges: EdgeType[],
): EdgeType[] {
return impl.applyEdgeChanges(changes, edges)
}
export function addEdge<EdgeType extends Edge = Edge>(
edgeParams: EdgeType | Connection,
edges: EdgeType[],
): EdgeType[] {
return impl.addEdge(edgeParams, edges)
}
+58 -18
View File
@@ -1,8 +1,6 @@
import { create } from 'zustand'
import {
addEdge, applyEdgeChanges, applyNodeChanges,
type Connection, type Edge, type EdgeChange, type Node, type NodeChange,
} from '@xyflow/react'
import type { Connection, Edge, EdgeChange, Node, NodeChange } from '@xyflow/react'
import { addEdge, applyEdgeChanges, applyNodeChanges } from './flowChanges'
import { api, ApiError, streamCopilot, streamRun } from '../api/client'
import { copilotReceipt, mergeNodeConfig, toolChangesOf } from '../canvas/copilotMerge'
import { connectMergeInput, isQueryNode } from '../canvas/mergeInputs'
@@ -714,6 +712,24 @@ interface StudioState {
const EMPTY_RUNTIME: NodeRuntime = { status: 'idle' }
/**
* 流式增量(llm.token / llm.thinking.delta)按帧合并提交:一次运行几千个 token,
* 每帧最多刷一次 store,避免在高速流下每秒触发几百次 Zustand 订阅者对账。
* 遇到任何非增量事件(node.started / node.finished / run.* 等)或运行切换时同步刷出,
* 保证事件因果顺序和同步断言不丢半个字。
*/
const pendingDeltas = new Map<string, { tokens: string; thinking: string }>()
let deltaRaf: number | null = null
let flushPendingDeltas: () => void = () => {}
function cancelPendingDeltas(): void {
if (deltaRaf !== null && typeof cancelAnimationFrame === 'function') {
cancelAnimationFrame(deltaRaf)
}
deltaRaf = null
pendingDeltas.clear()
}
// -------------------------------------------------------------------------
// 运行态:事件 → 航迹 → store 的其余字段
// -------------------------------------------------------------------------
@@ -739,6 +755,7 @@ function snapshotOf(nodes: FlowNode[], edges: Edge[]): StudioState['runSnapshot'
/** 开始一次新运行、换一条运行、清掉结果时要一起清的运行态 */
function runReset(): Partial<StudioState> {
cancelPendingDeltas()
return {
events: [], runtime: {}, activeEdges: [], trace: emptyTrace(), usageLive: ZERO_USAGE,
runPhase: 'idle', replayAt: null, follow: true, runSnapshot: null,
@@ -1169,7 +1186,27 @@ function selectionOf(s: StudioState): FlowNode[] {
return one ? [one] : []
}
export const useStudio = create<StudioState>((set, get) => ({
export const useStudio = create<StudioState>((set, get) => {
flushPendingDeltas = () => {
if (deltaRaf !== null && typeof cancelAnimationFrame === 'function') {
cancelAnimationFrame(deltaRaf)
}
deltaRaf = null
if (!pendingDeltas.size) return
const runtime = { ...get().runtime }
for (const [nid, buf] of pendingDeltas) {
const r = runtime[nid] ?? EMPTY_RUNTIME
runtime[nid] = {
...r,
...(buf.tokens ? { tokens: (r.tokens ?? '') + buf.tokens } : {}),
...(buf.thinking ? { thinking: (r.thinking ?? '') + buf.thinking } : {}),
}
}
pendingDeltas.clear()
set({ runtime })
}
return {
workflow: null,
nodes: [],
edges: [],
@@ -2485,26 +2522,28 @@ export const useStudio = create<StudioState>((set, get) => ({
* 显示的正文、思考、工具调用、协作矩阵这些内容。
*/
applyEvent: (event) => {
const state = get()
const type = String(event.type)
const nodeId = event.node_id
// 流式增量:只长正文和思考,不进 events、不碰航迹。一次运行有几千条,
// 每条都复制整个事件数组、重算一遍航迹,量级是 O(n²),而它们本来就不落库
// 流式增量:只长正文和思考,不进 events、不碰航迹;按帧合并为一次 set
if (type === 'llm.token' || type === 'llm.thinking.delta') {
if (!nodeId) return
const r = state.runtime[nodeId] ?? EMPTY_RUNTIME
const delta = String(event.data?.delta ?? '')
set({
runtime: {
...state.runtime,
[nodeId]: type === 'llm.token'
? { ...r, tokens: (r.tokens ?? '') + delta }
: { ...r, thinking: (r.thinking ?? '') + delta },
},
})
if (!delta) return
const prev = pendingDeltas.get(nodeId) ?? { tokens: '', thinking: '' }
if (type === 'llm.token') prev.tokens += delta
else prev.thinking += delta
pendingDeltas.set(nodeId, prev)
if (typeof requestAnimationFrame !== 'function') {
flushPendingDeltas()
} else if (deltaRaf === null) {
deltaRaf = requestAnimationFrame(() => flushPendingDeltas())
}
return
}
// 非增量事件到达前同步刷出已排队的增量,确保 node.started 清空与终态落定顺序严格一致
if (pendingDeltas.size) flushPendingDeltas()
const state = get()
// 重连补发、审批恢复重接时收过的那几条
if ((event.seq ?? 0) > 0 && event.seq <= state.trace.lastSeq) return
@@ -2564,7 +2603,8 @@ export const useStudio = create<StudioState>((set, get) => ({
set({ events: [...state.events, event], runtime, ...advance(state, runtime, event) })
},
}))
}
})
// 开发期把 store 挂到 window 上,好让 playwright 直接读状态做断言——
// 界面上看不出"事件收全了没有",只能问 store。生产构建里去掉。
+10
View File
@@ -18,6 +18,16 @@ const CACHE_DIR = process.env.AGENTLAB_VITE_CACHE_DIR || (NO_WATCH ? 'node_modul
export default defineConfig({
plugins: [react(), tailwindcss()],
...(CACHE_DIR ? { cacheDir: CACHE_DIR } : {}),
build: {
rollupOptions: {
output: {
manualChunks(id) {
if (id.includes('node_modules/@xyflow/') || id.includes('node_modules/d3-')) return 'xyflow'
if (id.includes('node_modules/lucide-react/')) return 'icons'
},
},
},
},
server: {
// 5173 太容易和别的项目撞车,挪开一点
port: 5273,