应用平台集成(前端):钩子按名字管理并只显示一次密钥、按新口径补算、应用助手对话历史、设置页按角色收起与身份设置补管理员用户名、按需视图每日上限、界面偏好按角色只存本地、使用者问数据用数据源名单并在运行流连不上时改轮询、能力字段待审阅、记录页按来源筛选与待办 id、编辑器的入口 / 表单 / 待办外观 JSON 分区、画布 ?publish=1、工具页绑定端点与 MCP 认证头掩码编辑、派给自己的新待办系统通知、样例与检查脚本改走待办接口(含统一复核后的修复)

This commit is contained in:
ThearchyHelios
2026-10-14 21:55:51 +08:00
parent d67349562a
commit 1dd4f93579
48 changed files with 2651 additions and 308 deletions
+115 -6
View File
@@ -5,25 +5,94 @@
* 入口提交校验失败回 422,ApiError 的 body 里带 {errors: FormError[]}。
*/
import type {
AppBindings, AppDetail, AppGrant, AppSpec, AppSummary, AppVersionRow, ComponentCatalog, Disposition, InstanceRow,
LintIssue, PublishResult, ViewModel,
AppBindings, AppDetail, AppGrant, AppHookRow, AppSpec, AppSummary, AppVersionRow, ComponentCatalog, Disposition,
InstanceRow, LintIssue, PublishResult, ViewModel,
} from '../typesApp'
import type { EvidenceSegmentDetail } from '../types'
import { get, patch, post, put, qs, type RequestOptions } from './http'
import type { ConversationDetail, EvidenceSegmentDetail } from '../types'
import { del, get, patch, post, put, qs, type RequestOptions } from './http'
const at = (id: string) => `/apps/${encodeURIComponent(id)}`
const hookAt = (id: string, name: string) => `${at(id)}/hooks/${encodeURIComponent(name)}`
/**
* 钩子管理里的一行(D-g):草稿里声明的 ∪ 已经生成过密钥的,按名字合成一行。
* - declared:草稿的 spec.hooks 里有这个名字;published:当前发布版里有(入站请求按发布版认种类和入口,没有就拒收);
* - has_secret:已经生成过密钥(app_hooks 里有这一行)。密钥本身只在生成、轮换时交回一次(AppHookRow.secret)。
* 服务端几种写法都认(hookStateOf),缺的项按「没有」算
*/
export interface AppHookState {
name: string
kind: 'start' | 'signal' | null
entry_id: string | null
declared: boolean
published: boolean
has_secret: boolean
enabled: boolean
/** app_hooks 那一行的 id:入站地址是 /api/hooks/{id}。还没生成密钥时为 null */
id: string | null
/** 收请求的地址(服务端给的路径);没给时按 id 拼 */
url_path: string | null
created_at: string | null
}
function hookStateOf(raw: Record<string, any>): AppHookState {
const id = typeof raw.id === 'string' && raw.id ? raw.id : null
const flag = (...keys: string[]) => keys.some((k) => raw[k] === true)
return {
name: String(raw.name ?? ''),
kind: raw.kind === 'start' || raw.kind === 'signal' ? raw.kind : null,
entry_id: raw.entry_id ?? raw.entry ?? null,
declared: flag('declared', 'in_draft'),
published: flag('published', 'in_published'),
has_secret: raw.has_secret != null || raw.secret_set != null ? flag('has_secret', 'secret_set') : !!id,
enabled: raw.enabled !== false,
id,
url_path: typeof raw.url_path === 'string' && raw.url_path ? raw.url_path : id ? `/api/hooks/${encodeURIComponent(id)}` : null,
created_at: raw.created_at ?? null,
}
}
/** 按新口径补算的结果(D-f):发起了几次、跳过了几次(同一输入已经补算过) */
export interface BackfillResult {
started: number
skipped: number
run_ids?: string[]
/** 发起到一半被拒(比如版本刚被退役):已经发起的照算,原因照实交回 */
refused?: string | null
}
/** 补算会发起几次(服务端 apps/backfill.Plan.out,不发起运行):这个视图、哪个固定版本从几升到几、趋势画几期 */
export interface BackfillPlan {
view: string
alias: string
source: string
from_version: number
to_version: number
periods: number
will_launch: number
will_skip: number
}
/**
* 应用详情。manage 才有草稿和岗位绑定(D-m);另带能按新口径补算的视图(backfill,只在取详情时算)。use / observe
* 只有概况和当前发布版的页面、入口目录(published)
*/
export type AppDetailOut = AppDetail & {
backfill?: BackfillPlan[]
published?: { version: number; pages: { id: string; title: string }[]; entries: { id: string; label: string }[] } | null
}
export const apps = {
catalog: (opts?: RequestOptions) => get<ComponentCatalog>('/apps/catalog', opts),
list: (opts?: RequestOptions) => get<{ items: AppSummary[] }>('/apps', opts),
get: (id: string, opts?: RequestOptions) => get<AppDetail>(at(id), opts),
get: (id: string, opts?: RequestOptions) => get<AppDetailOut>(at(id), opts),
create: (body: { name: string; description?: string; spec?: AppSpec }) => post<AppDetail>('/apps', body),
/** 从工作流版本确定性派生一份应用草稿(不落库),编辑器拿去预览 / 新建 */
derive: (body: { workflow_id: string; version: number; name?: string }) =>
post<{ spec: AppSpec }>('/apps/derive', body),
/** 改草稿:spec、岗位绑定、名称等,只带改了的字段 */
update: (id: string, body: { name?: string; description?: string; icon?: string; draft?: AppSpec;
draft_bindings?: AppBindings }) => patch<AppDetail>(at(id), body),
draft_bindings?: AppBindings }) => patch<AppDetailOut>(at(id), body),
archive: (id: string) => post<AppDetail>(`${at(id)}/archive`),
lint: (id: string) => post<{ issues: LintIssue[]; level: string | null }>(`${at(id)}/lint`),
publish: (id: string, body: { note?: string; dispositions?: Record<string, Disposition> }) =>
@@ -56,8 +125,48 @@ export const apps = {
/** 按需视图:发起一次运行(或命中缓存) */
refreshView: (id: string, view: string, params?: Record<string, unknown>) =>
post<{ run_id: string; cached: boolean }>(`${at(id)}/views/${encodeURIComponent(view)}/refresh`, { params: params ?? {} }),
/**
* 按新口径补算(D-f,manage):这个视图的固定版本相对上一个应用版本升了版、处置为按新口径重算时,取旧版本在同一来源上
* 最近几次封存的正式运行的输入,用新版本逐个发起正式运行(来源记为按新口径补算),同一输入补算过的跳过
*/
backfill: async (id: string, view: string): Promise<BackfillResult> => {
const raw = await post<Record<string, any>>(`${at(id)}/views/${encodeURIComponent(view)}/backfill`)
const n = (...keys: string[]) => Number(keys.map((k) => raw?.[k]).find((v) => typeof v === 'number') ?? 0)
return { started: n('launched', 'started'), skipped: n('skipped'), run_ids: Array.isArray(raw?.run_ids) ? raw.run_ids : undefined,
refused: typeof raw?.refused === 'string' ? raw.refused : null }
},
/** 补算会发起几次、跳过几次(不发起运行):确认框按它写明次数 */
backfillPlan: (id: string, view: string) => get<BackfillPlan>(`${at(id)}/views/${encodeURIComponent(view)}/backfill`),
/** 钩子(D-g):草稿声明 ∪ 已有的行,按名字 */
hooks: async (id: string): Promise<AppHookState[]> => {
const raw = await get<{ items: Record<string, any>[] } | Record<string, any>[]>(`${at(id)}/hooks`)
return (Array.isArray(raw) ? raw : raw?.items ?? []).map(hookStateOf).filter((h) => h.name)
},
/** 生成或轮换签名密钥:secret 只在这一次交回;url_path 是收请求的地址 */
rotateHook: (id: string, name: string) => post<AppHookRow & { url_path?: string | null }>(`${hookAt(id, name)}/rotate`),
setHookEnabled: (id: string, name: string, enabled: boolean) => patch<AppHookRow>(hookAt(id, name), { enabled }),
/** 删掉这个名字的密钥行:外部系统再用旧密钥签的请求一律拒收 */
deleteHook: (id: string, name: string) => del(hookAt(id, name)),
/**
* 应用编辑器里助手的对话(D-e,manage):取这个应用的那段对话,没有就建(kind=app、归属这个应用)。带着历史轮次;
* 老服务端只回对话本身时由调用方再按 id 取一次
*/
assistantConversation: (id: string): Promise<AssistantConversation> => {
// 同一个应用正在取的合并成一次:开发模式下 effect 执行两次,两个请求同时到服务端各建一段对话,历史就拆开了
const pending = assistantInflight.get(id)
if (pending) return pending
const request = get<AssistantConversation>(`${at(id)}/assistant-conversation`)
.finally(() => assistantInflight.delete(id))
assistantInflight.set(id, request)
return request
},
}
type AssistantConversation =
ConversationDetail | (Omit<ConversationDetail, 'turns'> & { turns?: ConversationDetail['turns'] })
/** 正在取的助手对话,按应用 id(见 apps.assistantConversation) */
const assistantInflight = new Map<string, Promise<AssistantConversation>>()
export const ledger = {
/** 一个工作流版本被哪些应用钉住、生效记录数、正式运行数 */
version: (workflowId: string, version: number) =>
+100 -1
View File
@@ -2,9 +2,84 @@
* 能力登记、端点、通知渠道的接口(/api/capabilities、/api/endpoints、/api/notify),挂在 api.capabilities /
* api.endpoints / api.notify 上。形状见 typesApp.ts。端点和渠道的密钥只回掩码;提交掩码值表示保持原值。
*/
import type { CapabilityRow, EndpointRow, NotifyChannelRow } from '../typesApp'
import type { CatalogReviewAction, CatalogSource, CatalogStatus } from '../types'
import type { CapabilityEffect, CapabilityRow, EndpointRow, NotifyChannelRow } from '../typesApp'
import { del, get, patch, post, put, qs, type RequestOptions } from './http'
/**
* 能力字段语义的审阅(D-i):沿用数据目录「项」的状态(推断 / 已核实 / 已确认 / 已驳回,带理由),按被多少运行用过、
* 是不是写入能力、来源排好序(服务端 data/capability_review.py,同 data/catalog_review.py 的思路)。一项是某个能力
* 返回里某个位置(JSON 指针)的某个字段(中文名、含义、单位、度量类型、码值)
*/
export interface CapabilityReviewItem {
/** 能力名(同图里工具的名字) */
name: string
title: string | null
/** 审阅队列里这一项的键:字段@位置(同一个能力里不重复)。成批审阅时拆回位置和字段 */
path: string
/** 返回里的位置(JSON 指针) */
pointer: string
field: string
/** 给人看的位置(服务端写好的「返回字段 /amount 的单位」) */
where: string
value: unknown
display: string
source: CatalogSource
status: CatalogStatus
note: string | null
priority: number
reasons: string[]
/** 用到这个能力的运行次数 */
usage: number
effect: CapabilityEffect | null
/** 能力的治理版本:成批审阅时逐项带上(乐观锁) */
version: number
}
export interface CapabilityReviewResult {
name: string
path: string
ok: boolean
version?: number | null
error: string | null
code?: string | null
}
const str = (v: unknown): string | null => (typeof v === 'string' && v ? v : null)
const num = (...vs: unknown[]): number => Number(vs.find((v) => typeof v === 'number') ?? 0)
/** 队列一项的键:字段@位置。字段只有几个固定的英文名,不含 @,拆的时候按第一个 @ 拆 */
export const reviewPathOf = (field: string, pointer: string) => `${field}@${pointer}`
export function splitReviewPath(path: string): { field: string; pointer: string } {
const at = path.indexOf('@')
return at < 0 ? { field: '', pointer: path } : { field: path.slice(0, at), pointer: path.slice(at + 1) }
}
function reviewItemOf(raw: Record<string, any>): CapabilityReviewItem {
const pointer = String(raw.pointer ?? '')
const field = String(raw.field ?? '')
const short = String(raw.field_text ?? raw.field ?? '')
return {
name: String(raw.capability ?? raw.name ?? ''),
title: str(raw.title),
path: reviewPathOf(field, pointer),
pointer,
field,
// 服务端写好的位置说法;老写法只给了字段名时自己拼
where: str(raw.field_label) ?? (pointer ? `${pointer} 的${short}` : short),
value: raw.value,
display: typeof raw.display === 'string' ? raw.display : raw.value == null ? '' : String(raw.value),
source: raw.source,
status: raw.status ?? 'proposed',
note: str(raw.note),
priority: num(raw.priority),
reasons: Array.isArray(raw.reasons) ? raw.reasons.map(String) : [],
usage: num(raw.runs, raw.usage, raw.run_count),
effect: raw.effect ?? null,
version: num(raw.version),
}
}
export const capabilities = {
list: (params?: { system?: string; effect?: string; q?: string }, opts?: RequestOptions) =>
get<{ items: CapabilityRow[] }>(`/capabilities${qs(params)}`, opts),
@@ -14,6 +89,30 @@ export const capabilities = {
govern: (name: string, body: Partial<CapabilityRow> & { version: number }) =>
put<CapabilityRow>(`/capabilities/${encodeURIComponent(name)}/governance`, body),
sync: () => post<{ changed: number }>('/capabilities/sync'),
/** 待审阅的能力字段(D-i):顺序服务端排好;capability 只看这一个能力 */
reviewQueue: async (params: { limit?: number; offset?: number; capability?: string | null }, opts?: RequestOptions) => {
const raw = await get<{ total?: number; items?: Record<string, any>[] }>(`/capabilities/review-queue${qs({
limit: params.limit, offset: params.offset, capability: params.capability || undefined,
})}`, opts)
const items = (raw?.items ?? []).map(reviewItemOf).filter((i) => i.name && i.field)
return { total: typeof raw?.total === 'number' ? raw.total : items.length, items }
},
/**
* 成批审阅(只给管理员):逐个能力按治理版本做乐观锁,逐条交回结果(一个能力冲突只记在那几条上,code 为
* capability_conflict);写审计。path 是队列一项的键(字段@位置),这里拆回位置和字段
*/
reviewBatch: async (items: { name: string; path: string; action: CatalogReviewAction; if_version: number }[]) => {
const raw = await post<{ results?: Record<string, any>[] }>('/capabilities/review/batch', {
items: items.map((i) => ({ capability: i.name, ...splitReviewPath(i.path), action: i.action, if_version: i.if_version })),
})
return {
results: (raw?.results ?? []).map((r): CapabilityReviewResult => ({
name: String(r.capability ?? r.name ?? ''), path: reviewPathOf(String(r.field ?? ''), String(r.pointer ?? '')),
ok: r.ok === true, version: typeof r.version === 'number' ? r.version : null,
error: str(r.error) ?? str(r.message), code: str(r.code),
})),
}
},
}
export const endpoints = {
+72 -3
View File
@@ -8,7 +8,7 @@ import type {
RevokeAcceptanceBody, RevokeAcceptanceOut, SnapshotOut, Staging,
} from '../types'
import type {
Approval, AutofixResult, Conversation, ConversationDetail, ConversationTurn, CustomTool, DataSource, EvidenceGraph,
Approval, AutofixResult, Conversation, ConversationDetail, ConversationTurn, CustomTool, DataSource, DataSourceName, EvidenceGraph,
EvidenceAudit, EvidenceJudgeResult, EvidenceProvenance, EvidenceSegmentDetail, GraphSpec, KbDocument, MemoryItem, Provider, PublishCheck, PublishLevel, ReviewResult, Run,
RunEvent, RunStatus, Skill, ToolChange, ToolInfo, ToolTrust, UpgradeResult, UploadDecision, UploadMixedColumn, UploadResult,
UploadShapeReason, ValidationIssue, VarIssue, Variable, Workflow, WorkflowVersion,
@@ -261,6 +261,14 @@ export const api = {
// ---- 运行 ----
datasources: {
list: (opts?: RequestOptions) => get<DataSource[]>('/datasources', opts),
/**
* 只有名字和说明(D-c):开了登录、管理员允许使用者问数据时,使用者的问数据页按它列数据源(完整列表只给搭建者)。
* 形状按 {items} 或数组两种都认
*/
names: async (opts?: RequestOptions): Promise<DataSourceName[]> => {
const raw = await get<DataSourceName[] | { items: DataSourceName[] }>('/datasources/names', opts)
return Array.isArray(raw) ? raw : raw?.items ?? []
},
kinds: () => get<any>('/datasources/kinds'),
create: (body: any) => post<any>('/datasources', body),
update: (id: string, body: any) => patch<any>(`/datasources/${id}`, body),
@@ -1025,7 +1033,16 @@ export function streamCatalogAssistant(
* 审批恢复时会重新 attachRun,不传 after 就是 after=0,后端按 `seq > after`
* 把整条历史再推一遍,而消费方多半是无条件追加——事件就这么重复累积了。
* 已经有事件在手的场景(重新接上一条运行)应当传当前最大 seq。
*
* 连不上 WebSocket 时退回轮询(应用平台 D-c):握手连续 WS_GIVE_UP 次都没打开(服务端按运行判权限,拒绝时握手
* 直接断开;代理不转发 WebSocket 也是这样),改为每 POLL_MS 取一次 /runs/{id}/events?after= 和运行状态,运行不在
* 进行中时照 stream.end 的样子收尾。第一批是补的历史,同 WebSocket 的回放一样标 replay
*/
const WS_GIVE_UP = 2
const POLL_MS = 1500
/** 不在进行中的状态:同服务端 api/runs._SETTLED,另加服务重启挂起的 suspended(轮询时没有后续事件会来) */
const SETTLED_STATUS = new Set(['succeeded', 'failed', 'cancelled', 'interrupted', 'suspended'])
export function streamRun(
runId: string,
onEvent: (event: RunEvent) => void,
@@ -1038,19 +1055,62 @@ export function streamRun(
let closed = false
let lastSeq = after
let retry = 0
/** 握手连续失败(一次都没打开过就断了)几次 */
let refused = 0
let pollTimer: ReturnType<typeof setTimeout> | undefined
const finish = (status?: string) => {
if (closed) return
closed = true
onClose?.({ status })
}
const poll = async (first: boolean) => {
if (closed) return
let delay = POLL_MS
try {
const events = await api.runs.events(runId, lastSeq)
if (closed) return
for (const event of events) {
if (event.seq) lastSeq = Math.max(lastSeq, event.seq)
onEvent(first ? { ...event, replay: true } : event)
}
// 这一批没有新事件时才看状态:运行刚结束时最后几条事件和状态可能前后脚落库,先把事件收完
if (!events.length) {
const run = await api.runs.get(runId)
if (closed) return
if (SETTLED_STATUS.has(String(run.status))) {
// 状态落了、最后几条事件可能刚落库:再补一次再收尾
const rest = await api.runs.events(runId, lastSeq).catch(() => [] as RunEvent[])
for (const event of rest) {
if (event.seq) lastSeq = Math.max(lastSeq, event.seq)
onEvent(event)
}
finish(run.status)
return
}
}
retry = 0
} catch {
// 断线、服务重启:退避重试,最多等 10 秒
retry += 1
delay = Math.min(POLL_MS * 2 ** retry, 10_000)
}
if (!closed) pollTimer = setTimeout(() => void poll(false), delay)
}
const connect = () => {
if (closed) return
const proto = location.protocol === 'https:' ? 'wss' : 'ws'
let opened = false
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 }
if (event.type === 'stream.end') {
closed = true
socket?.close()
// 新后端放在 data.status,老后端放在顶层 status
onClose?.({ status: event.data?.status ?? event.status })
finish(event.data?.status ?? event.status)
return
}
if (event.seq) lastSeq = Math.max(lastSeq, event.seq)
@@ -1058,11 +1118,19 @@ export function streamRun(
}
socket.onclose = () => {
if (closed) return
if (!opened) refused += 1
if (refused >= WS_GIVE_UP) {
socket = null
void poll(true)
return
}
// 指数退避重连,最多等 5 秒
retry += 1
setTimeout(connect, Math.min(300 * 2 ** retry, 5000))
}
socket.onopen = () => {
opened = true
refused = 0
retry = 0
report(true)
}
@@ -1071,6 +1139,7 @@ export function streamRun(
return () => {
closed = true
clearTimeout(pollTimer)
socket?.close()
}
}