普通用户建应用集成收尾:

- 问数据和个人应用的图放行绑定只读查询等合规工具的调用工具节点,只读和遮罩在这条路径上生效;被治理成写入的工具在只读运行里直接拒;知识库范围在工具层固定(图级默认值、参数名纠错、Agent 都改不了)
- 个人应用的刷新和个人蓝图的试运行只有拥有者能读:运行、事件、证据、工件、文件、运行与审批列表、对比、可验证报告、质询、假设分析、提取工作流一并收紧;个人蓝图的试运行不论谁发起都按个人应用约束
- 共享蓝图只给拥有者、对应应用的管理者、管理员,看不到的一律 404;审核副本归审核人;管理员看别人的个人应用只有元数据、可以归档
- 记录表跨版本汇总(只读挂载旧版本、按当前列 UNION ALL、各版本各自固定高水位,缺的版本照实写进印章);停用前发起的运行可以继续写旧版本;更正沿用原提交人、更正人记审计
- 约定收口:待办种类 review、事件 file.extracted、表单错误 file、模板定义带示例与预置;前端类型一次补齐、去掉临时的局部类型;审核待办卡不再给打不开的链接;读附件事件有中文说法;检查脚本补断言
This commit is contained in:
ThearchyHelios
2026-10-15 13:55:19 +08:00
parent a702a5c14b
commit 7739340607
95 changed files with 3107 additions and 611 deletions
+2 -2
View File
@@ -5,7 +5,7 @@
* 入口提交校验失败回 422,ApiError 的 body 里带 {errors: FormError[]}。
*/
import type {
AppBindings, AppDetail, AppGrant, AppHookRow, AppSpec, AppSummary, AppVersionRow, BackfillPlan, BackfillResult,
AppBindings, AppDetail, AppGrant, AppHookRow, AppList, AppSpec, AppSummary, AppVersionRow, BackfillPlan, BackfillResult,
ComponentCatalog, Disposition, InstanceRow, LintIssue, PublishResult, ViewModel,
} from '../typesApp'
import type { ConversationDetail, EvidenceSegmentDetail } from '../types'
@@ -16,7 +16,7 @@ const hookAt = (id: string, name: string) => `${at(id)}/hooks/${encodeURICompone
export const apps = {
catalog: (opts?: RequestOptions) => get<ComponentCatalog>('/apps/catalog', opts),
list: (opts?: RequestOptions) => get<{ items: AppSummary[] }>('/apps', opts),
list: (opts?: RequestOptions) => get<AppList>('/apps', opts),
get: (id: string, opts?: RequestOptions) => get<AppDetail>(at(id), opts),
create: (body: { name: string; description?: string; spec?: AppSpec }) => post<AppDetail>('/apps', body),
/** 从工作流版本确定性派生一份应用草稿(不落库),编辑器拿去预览 / 新建 */
+5 -4
View File
@@ -14,6 +14,7 @@
* 开流之前就被拒(4xx/5xx)时 onEnd 带服务端那句话、状态码和机读码;流到一半断了和一开始就连不上一样,说无法连接服务。
* 请求函数从 ./http 导入,不要从 ./client 导入(循环导入,见 http.ts 开头)。
*/
import type { BlueprintStreamEvent, FillJointsEvent } from '../typesBlueprint'
import { ApiError, BASE, NETWORK_MESSAGE, actorHeader, codeOf, describeDetail, isGatewayFailure, parseBody, report } from './http'
export interface BlueprintStreamRequest {
@@ -31,8 +32,8 @@ export interface FillJointsRequest {
export type StreamEnd = (error?: string, info?: { status?: number; code?: string; aborted?: boolean }) => void
/** 一条 SSE:返回取消函数 */
function sse(path: string, body: unknown, onOp: (op: any) => void, onEnd: StreamEnd): () => void {
/** 一条 SSE:返回取消函数。帧的形状以服务端为准(typesBlueprint 的 BlueprintStreamEvent、FillJointsEvent),这里不逐帧核对 */
function sse<E>(path: string, body: unknown, onOp: (op: E) => void, onEnd: StreamEnd): () => void {
const controller = new AbortController()
void (async () => {
try {
@@ -94,8 +95,8 @@ function sse(path: string, body: unknown, onOp: (op: any) => void, onEnd: Stream
return () => controller.abort()
}
export const streamBlueprint = (body: BlueprintStreamRequest, onOp: (op: any) => void, onEnd: StreamEnd) =>
export const streamBlueprint = (body: BlueprintStreamRequest, onOp: (op: BlueprintStreamEvent) => void, onEnd: StreamEnd) =>
sse('/copilot/blueprint-stream', body, onOp, onEnd)
export const streamFillJoints = (body: FillJointsRequest, onOp: (op: any) => void, onEnd: StreamEnd) =>
export const streamFillJoints = (body: FillJointsRequest, onOp: (op: FillJointsEvent) => void, onEnd: StreamEnd) =>
sse('/copilot/fill-joints-stream', body, onOp, onEnd)
+2 -3
View File
@@ -44,9 +44,8 @@ export interface ViewEditMarks {
const EditMarksCtx = createContext<ViewEditMarks | null>(null)
/** 服务端按草稿解析时给隐藏的组件带的标记(发布版里没有这样的组件) */
const isHidden = (node: ViewNode, marks: ViewEditMarks | null) =>
(node as ViewNode & { hidden?: boolean }).hidden === true || !!marks?.hidden.has(node.id)
/** 服务端按草稿解析时给隐藏的组件带的标记(ViewNode.hidden,发布版里没有这样的组件),加上这一次刚隐藏的 */
const isHidden = (node: ViewNode, marks: ViewEditMarks | null) => node.hidden === true || !!marks?.hidden.has(node.id)
export function ViewRenderer({ model, appId, runId, preview = false, onNavigate, onReload, editing }: ViewRendererProps) {
const [evidence, setEvidence] = useState<EvidenceTarget | null>(null)
+4 -1
View File
@@ -129,7 +129,8 @@ function pointLabel(asOf: string, sameDay: boolean): string {
/**
* 趋势:服务端按处置给好线和断点——dual 两条线(旧版本、新版本),incomparable 两段之间断开并写明前后不可比,
* recompute 只给新版本、写一句说明。点一个点打开那一次运行里这个指标的出处
* recompute 只给新版本、写一句说明;试运行预览里只有一个点,服务端写在 note 里的说明照写。点一个点打开那一次运行里
* 这个指标的出处
*/
export function SeriesBlock({ node }: NodeProps) {
const { openEvidence } = useView()
@@ -161,6 +162,8 @@ export function SeriesBlock({ node }: NodeProps) {
if (index > 0 && index < keys.length) brk.push({ index, label: VIEW_TEXT.incomparable })
if (str(b?.text)) extra.push(str(b.text))
}
// 服务端照实写的说明:试运行预览里只有这一次试运行一个点,写明没有趋势
if (str(data.note)) extra.push(str(data.note))
return { categories: keys.map((k) => pointLabel(k, sameDay)), series: lines, breaks: brk, notes: extra }
}, [data, label])
const unit = str(data.unit)
+19 -14
View File
@@ -22,14 +22,16 @@ import { RECORDS_TEXT as T } from '../../lib/termsApp'
import type { RecordRow, RecordsPage } from '../../typesBlueprint'
import { str, useView, type NodeProps } from '../context'
/** 服务端可能给的下一页游标、状态(typesBlueprint.RecordsPage 还没有这两项,契约待补):empty 是这个应用还没有记录表 */
type Page = RecordsPage & { next_cursor?: string | null; state?: string }
/** 服务端解析页面时给的第一页(node.data):形状对得上才用 */
function pageOf(data: unknown): Page | null {
return data && typeof data === 'object' && Array.isArray((data as Page).items) && Array.isArray((data as Page).columns)
? data as Page : null
/**
* 服务端解析页面时给的第一页(node.data,形状同 RecordsPage):形状对得上才用。state=empty 是这个应用还没有记录表,
* preview 是按草稿预览(不列真实的记录)
*/
function isPage(data: unknown): data is RecordsPage {
if (!data || typeof data !== 'object') return false
const d: { items?: unknown; columns?: unknown } = data
return Array.isArray(d.items) && Array.isArray(d.columns)
}
const pageOf = (data: unknown): RecordsPage | null => (isPage(data) ? data : null)
/** 一格的值写给人看:文件是可下载的链接,数组用顿号连,布尔写是或否,其余原样 */
function Value({ v }: { v: unknown }) {
@@ -56,7 +58,7 @@ export function RecordsList({ node }: NodeProps) {
const table = str(node.props.table) || undefined
const who = node.props.who === 'mine' || node.props.who === 'all' ? node.props.who : undefined
const initial = pageOf(node.data)
const [page, setPage] = useState<Page | null>(initial)
const [page, setPage] = useState<RecordsPage | null>(initial)
const [error, setError] = useState<unknown>(null)
const [more, setMore] = useState(false)
const [query, setQuery] = useState('')
@@ -82,7 +84,7 @@ export function RecordsList({ node }: NodeProps) {
if (!page?.next_cursor) return
setMore(true)
try {
const next: Page = await api.personal.records(appId, { table, who, cursor: page.next_cursor })
const next = await api.personal.records(appId, { table, who, cursor: page.next_cursor })
setPage({ ...next, items: [...page.items, ...next.items] })
} catch (e) {
setError(e)
@@ -124,12 +126,15 @@ export function RecordsList({ node }: NodeProps) {
{page && page.items.length > 0 && (
<span className="tnum shrink-0 text-2xs text-faint" data-records-count="">{T.count(rows.length, page.items.length)}</span>
)}
<button type="button" className="btn btn-xs btn-ghost shrink-0" onClick={() => { setHistory(null); setHistoryError(null); load() }}
aria-label={T.reload} title={T.reload}>
<RotateCw size={11} aria-hidden />
</button>
{page?.state !== 'preview' && (
<button type="button" className="btn btn-xs btn-ghost shrink-0" onClick={() => { setHistory(null); setHistoryError(null); load() }}
aria-label={T.reload} title={T.reload}>
<RotateCw size={11} aria-hidden />
</button>
)}
</div>
{page?.state === 'empty' && !page.items.length ? <div className="px-3 py-3 text-2xs text-faint">{T.tableMissing}</div>
{page?.state === 'preview' ? <div className="px-3 py-3 text-2xs text-faint" data-records-preview="">{T.preview}</div>
: page?.state === 'empty' && !page.items.length ? <div className="px-3 py-3 text-2xs text-faint">{T.tableMissing}</div>
: error && !page ? <ErrorState compact error={error} onRetry={load} className="m-2" />
: !page ? <div className="flex items-center gap-2 px-3 py-3 text-2xs text-faint"><Spinner size={11} /></div>
: (
+2 -1
View File
@@ -20,7 +20,8 @@ import type { UploadProgress } from '../api/http'
import { formatBytes } from '../lib/format'
import { humanizeError } from '../lib/errors'
import { FILE_TEXT } from '../lib/termsApp'
import { isFileRef, toFileRef, type FileLimits } from '../lib/schemaForm'
import { isFileRef, toFileRef } from '../lib/schemaForm'
import type { FileLimits } from '../typesApp'
import type { FileRef } from '../typesBlueprint'
import { Spinner } from './ui'
+29 -16
View File
@@ -8,26 +8,28 @@
* 只有一层:顶层 object,字段是 string / number / integer / boolean,数组只装枚举字符串(多选)。
*
* 文件(normal-user-apps N9、§3.8):字段 type 为 object、x-widget 为 file,只有这个控件能用 object。值是上传后拿回的
* 引用 {file_id, name, size, sha256, type},规则和服务端 apps/forms.py 同一份:必填,形状是文件引用。允许的类型和大小
* 写在 x-file(accept、max_mb),只在上传时用,提交时不再查(上传那一步服务端已经核对过)。
* 引用 {file_id, name, size, sha256, type},规则和服务端 apps/forms.py 同一份:必填,形状是文件引用,不合时错误的 code 是
* file(同服务端 files/store.FILE_ERROR_CODE)。允许的类型和大小写在 x-file(accept、max_mb),只在上传时用,提交时不再查
* (上传那一步服务端已经核对过)。
*/
import type { FormError, FormField, FormSchema, FormWidget } from '../typesApp'
import type { FileLimits, FormError, FormField, FormSchema, FormWidget } from '../typesApp'
import type { FileRef } from '../typesBlueprint'
import { FILE_TEXT, FORM_TEXT } from './termsApp'
/** 文件控件的限制:允许的类型(MIME 或扩展名)、大小上限(MB)。x-file 由服务端随表单给 */
export interface FileLimits { accept?: string[]; max_mb?: number | null }
/** 表单字段上的 x-file(typesApp.FormField 还没有这一项,见报告的接口约定请求) */
/**
* 表单字段上的 x-file(FormField['x-file'])整理成控件用的样子:可选类型去掉空的,大小上限不是正数的当没写。
* 服务端保存表单时已经按同一套规则查过(apps/forms._file_field_problems),这里只防手写的老表单
*/
export function fileLimitsOf(field: FormField): FileLimits {
const raw = (field as FormField & { 'x-file'?: unknown })['x-file']
if (!raw || typeof raw !== 'object') return {}
const x = raw as { accept?: unknown; max_mb?: unknown }
const accept = Array.isArray(x.accept) ? x.accept.filter((a): a is string => typeof a === 'string' && !!a.trim())
: typeof x.accept === 'string' ? x.accept.split(',').map((a) => a.trim()).filter(Boolean) : undefined
const x = field['x-file']
if (!x || typeof x !== 'object') return {}
// 画布上手写的老图可能把可选类型写成一串逗号分隔的字
const raw: unknown = x.accept
const accept = Array.isArray(raw) ? raw.filter((a): a is string => typeof a === 'string' && !!a.trim())
: typeof raw === 'string' ? raw.split(',').map((a) => a.trim()).filter(Boolean) : undefined
return {
accept: accept?.length ? accept : undefined,
max_mb: typeof x.max_mb === 'number' && Number.isFinite(x.max_mb) && x.max_mb > 0 ? x.max_mb : null,
max_mb: typeof x.max_mb === 'number' && Number.isFinite(x.max_mb) && x.max_mb > 0 ? x.max_mb : undefined,
}
}
@@ -44,6 +46,17 @@ export function toFileRef(raw: FileRef): FileRef {
return { file_id: raw.file_id, name: raw.name, size: raw.size, sha256: raw.sha256, type: raw.type }
}
/** 表单引用的写法(同服务端 apps/tree.FORM_REF_PREFIX):{"$ref": "#/forms/<名字>"} */
const FORM_REF_PREFIX = '#/forms/'
/** 内联的表单原样交回;引用换成 forms 里的那一份;引用不到的是 null(同服务端 apps/tree.resolve_form) */
export function resolveForm(forms: Record<string, FormSchema> | null | undefined,
form: FormSchema | { $ref: string } | null | undefined): FormSchema | null {
if (!form) return null
if (!('$ref' in form)) return form
return form.$ref.startsWith(FORM_REF_PREFIX) ? forms?.[form.$ref.slice(FORM_REF_PREFIX.length)] ?? null : null
}
/** 字段顺序:x-order 里写到的在前(按写的顺序),没写到的按 properties 的原顺序跟在后面;不存在的名字跳过 */
export function fieldOrder(schema: FormSchema): string[] {
const props = schema.properties ?? {}
@@ -54,8 +67,8 @@ export function fieldOrder(schema: FormSchema): string[] {
/** 这个字段画成哪种控件:写了 x-widget 照它,没写按类型推 */
export function widgetOf(field: FormField): FormWidget {
if (field['x-widget']) return field['x-widget']
// 只有文件控件用 object(typesApp.FormField 的 type 还没列 object)
if ((field.type as string) === 'object') return 'file'
// 只有文件控件用 object
if (field.type === 'object') return 'file'
switch (field.type) {
case 'boolean': return 'checkbox'
case 'array': return 'multiselect'
@@ -139,7 +152,7 @@ export function validateForm(schema: FormSchema, values: Record<string, unknown>
function fieldError(field: FormField, v: unknown, required: boolean): Omit<FormError, 'path'> | null {
if (isEmpty(v)) return required ? { code: 'required', message: FORM_TEXT.required } : null
if (widgetOf(field) === 'file') return isFileRef(v) ? null : { code: 'type', message: FILE_TEXT.invalid }
if (widgetOf(field) === 'file') return isFileRef(v) ? null : { code: 'file', message: FILE_TEXT.invalid }
switch (field.type) {
case 'string': {
if (typeof v !== 'string') return { code: 'type', message: FORM_TEXT.type.string }
+5 -1
View File
@@ -4934,6 +4934,8 @@ export const ORIGIN_LABEL: Record<OriginKind, string> = {
app_backfill: '按新口径补算',
hook: '外部系统触发',
api: '接口',
trial: '蓝图试运行',
personal_app: '个人应用刷新',
}
export const ORIGIN_TEXT = {
@@ -5188,6 +5190,8 @@ export const NOTIFY_TEXT = {
'task.opened': '待办打开', 'task.escalated': '待办升级', 'task.expired': '待办超时', 'task.resolved': '待办处理完',
'action.unknown': '动作结果未知', 'action.failed': '动作失败', 'action.confirmed': '动作已生效',
'run.failed': '运行失败', 'run.finished': '运行结束',
// 个人应用提交审核有了结果(发布了或退回了),通知提交人:只对个人渠道、全局渠道有意义(服务端 notify/service.notify_review)
'review.done': '我提交审核的应用有结果',
} as Record<string, string>,
enabled: '启用',
signed: '已签名',
@@ -5624,7 +5628,7 @@ export const TASK_NOTIFY_TEXT = {
export const SETTINGS_ROLE_TEXT = {
subtitleUser: '个人的主题和通知',
themeLocal: '主题只保存在当前浏览器中,更换设备后需重新选择',
prefsReadOnly: '运行默认值、证据裁判和核查的设置全站共用,只有管理员可以修改',
prefsReadOnly: '运行默认值、证据裁判、核查和应用的设置全站共用,只有管理员可以修改',
notifyPersonal: '个人渠道只推送派给你的待办和你发起的实例的事件',
}
+30 -5
View File
@@ -65,11 +65,8 @@ export const APP_HOME_TEXT = {
taskNotFound: '待办不存在,所属的运行可能已被删除',
}
/**
* 待办的种类:看中断内容里的 kind,不看 mode(§3.7)。review 是个人应用提交审核(docs/design/normal-user-apps.md N7):
* typesApp 的 TaskKind 还没有它(契约待补),这里先按多一种写
*/
export const TASK_KIND_LABEL: Record<TaskKind | 'review', string> = {
/** 待办的种类:看中断内容里的 kind,不看 mode(§3.7)。review 是个人应用提交审核(docs/design/normal-user-apps.md N7) */
export const TASK_KIND_LABEL: Record<TaskKind, string> = {
approve: '人工审批',
input: '补充输入',
edit: '改稿',
@@ -547,6 +544,14 @@ export const FILE_TEXT = {
/** 值不是上传后拿回的引用(前后端同一条:必填,形状是文件引用) */
invalid: '请上传文件',
empty: '未上传',
// ---- 运行详情里读入附件的一行(file.extracted,服务端 files/text.py 的模板函数 file_text)。数由调用方按千分位写好 ----
extracted: (name: string, chars: string | null) => {
const what = name ? `读入附件「${name}」` : '读入附件'
return chars == null ? what : `${what}${name ? '' : ' '}${chars} 字`
},
extractedAll: (total: string) => `全文 ${total} 字,已全部读入`,
extractedCut: (chars: string, total: string) => `全文 ${total} 字,只读入了前 ${chars} 字,其余没有读入`,
extractFailed: (name: string) => (name ? `附件「${name}」抽不出文字` : '附件抽不出文字'),
typeLabels: {
'application/pdf': 'PDF', 'application/msword': 'Word', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'Word',
'application/vnd.ms-excel': 'Excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'Excel',
@@ -586,6 +591,7 @@ export const RECORDS_TEXT = {
more: '加载更多',
reload: '重新读取',
tableMissing: '这个应用还没有记录表:发布之后、有人提交过才会有记录',
preview: '按草稿预览:这里不列真实的记录,发布之后按看的人列出',
yes: '是',
no: '否',
}
@@ -625,6 +631,25 @@ export const PERSONAL_TEXT = {
rejectedNote: (note: string) => `上次的审核已退回:${note}`,
graphChanged: '蓝图在存成个人应用之后又改过:刷新按存下的那一版运行,要用改过的,请回到蓝图重新存成你的应用。',
graphChangedGo: '回到蓝图',
switchedOff: '管理员关闭了「使用者可以建个人应用」:已有的结果还能看,暂时不能刷新、提交审核',
// ---- 管理员看别人的个人应用:只有名称、拥有者、时间,可以归档,看不到内容
othersGroup: '使用者的个人应用',
othersGroupHint: '使用者自己建的个人应用。管理员只看得到名称、拥有者和时间,可以归档,看不到页面、运行和蓝图的内容',
owner: (who: string) => `拥有者:${who}`,
ownerUnknown: '拥有者未记录',
createdAt: (t: string) => `创建于 ${t}`,
updatedAt: (t: string) => `更新于 ${t}`,
stubTitle: (who: string) => `这是 ${who} 的个人应用`,
stubBody: '个人应用只有拥有者看得见。管理员看得到名称、拥有者和时间,可以归档,但看不到页面、运行和蓝图的内容。',
archive: '归档',
archiveTitle: (name: string) => `归档「${name}」?`,
archiveConsequences: [
'拥有者的应用列表里不再列出它,不能再刷新或提交审核',
'它的蓝图和以前的刷新记录照常保留,你看不到它们的内容',
'目前没有恢复的操作',
],
archiveConfirm: '归档个人应用',
archiveDone: (name: string) => `已归档「${name}」`,
}
/** 审核待办(个人应用提交审核,N7):处理人在待办里取一份共享副本,在副本上试运行、走发布单;不发布就退回 */
-1
View File
@@ -131,7 +131,6 @@ export const BLUEPRINT_TEXT = {
templateOf: (label: string, version: number) => `${label}(模板 v${version})`,
// 对到数据的项
dataTable: '表',
dataTableLabel: '中文名',
dataGrain: '粒度',
dataDate: '业务日期',
dataReuseText: (metric: string, version: number) => `复用口径卡里的「${metric}」(v${version}),不重写指标式`,
+10 -5
View File
@@ -5,8 +5,8 @@
* 每 5 秒重取一次,生成完自动换上;引用的版本退役了照实提示,入口暂停发起。
*
* 另取一次应用详情:有 manage 的人点「编辑」在页面上直接改(地址上记 edit=1,见 PageEdit.tsx,normal-user-apps N6);
* 个人应用(scope 为 personal)顶上写明是个人应用,给「刷新」和「提交审核」(personal.tsx,N7)。详情取不到不挡页面:
* 照只能用的人画。
* 个人应用(scope 为 personal)顶上写明是个人应用,给「刷新」和「提交审核」(personal.tsx,N7);开了登录的管理员打开别人的
* 个人应用只拿到元数据,换成只写名称、拥有者、时间和「归档」的一页。详情取不到不挡页面:照只能用的人画。
*/
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
import { LayoutGrid, PencilLine, RotateCw, Settings2 } from 'lucide-react'
@@ -14,14 +14,14 @@ import { api } from '../../api/client'
import { ViewRenderer } from '../../apps/ViewRenderer'
import { parseViewParams } from '../../apps/components/input'
import { Notice, PageHeader, Skeleton, Spinner, Tabs } from '../../components/ui'
import { useAtLeast } from '../../store/auth'
import { loginOn, useAtLeast, useAuth } from '../../store/auth'
import { usePageTitle } from '../../lib/notify'
import { APP_TEXT, PAGE_EDIT_TEXT, PERSONAL_TEXT } from '../../lib/termsApp'
import type { AppDetail } from '../../typesApp'
import { AppMeta, BackLink, LoadError, appPath, loadHome, useLoad, usePoll } from './shared'
import { BackfillPanel } from './backfill'
import { PageEditor } from './PageEdit'
import { PersonalBar } from './personal'
import { PersonalBar, PersonalStubPage, isPersonalStub } from './personal'
const POLL_MS = 5000
@@ -34,7 +34,9 @@ export function AppPage() {
const [search, setSearch] = useSearchParams()
const raw = search.get('params')
const navigate = useNavigate()
const { data: detail, reload: reloadDetail } = useLoad((signal) => api.apps.get(appId, { signal }), [appId])
const { data: detail, error: detailError, reload: reloadDetail } = useLoad((signal) => api.apps.get(appId, { signal }), [appId])
// 开了登录的管理员打开的可能是别人的个人应用(只有元数据):等详情回来再决定画哪一种,免得先去取一次看不到的页面
const mayBeStub = useAuth((s) => loginOn(s.me) && s.me?.role === 'admin')
const editing = editableOf(detail) && search.get('edit') === '1'
const setEditing = (on: boolean) => setSearch((prev) => {
const next = new URLSearchParams(prev)
@@ -51,6 +53,9 @@ export function AppPage() {
navigate(`${appPath(appId)}/p/${encodeURIComponent(id)}${tail ? `?${tail}` : ''}`)
}
// 别人的个人应用(开了登录的管理员):服务端只给元数据,页面、运行都看不到,不去取
if (detail && isPersonalStub(detail)) return <PersonalStubPage app={detail} onArchived={reloadDetail} />
if (mayBeStub && !detail && !detailError) return <div className="p-4"><Skeleton rows={6} /></div>
if (editing && detail) {
return (
<PageEditor key={appId} appId={appId} detail={detail} pageId={pageId} rawParams={raw} onNavigate={go}
+24 -10
View File
@@ -21,6 +21,7 @@ import type { AppSummary, InstanceRow, Task } from '../../typesApp'
import { LoadError, appPath, useLoad } from './shared'
import { NEW_APP_TEXT } from '../../lib/termsBlueprint'
import { CREATE_APP_PATH, useCreateScope } from '../blueprints/shared'
import { PersonalStubCard, isPersonalStub } from './personal'
const TABS = ['inbox', 'apps', 'mine'] as const
type Tab = (typeof TABS)[number]
@@ -160,19 +161,23 @@ function AppsTab() {
const { data, error, reload } = useLoad((signal) => api.apps.list({ signal }), [])
if (error && !data) return <LoadError error={error} onRetry={reload} />
if (!data) return <Skeleton rows={4} />
// 个人应用(N7)单独一组「我的应用」放在前面:只有拥有者看得见,服务端只把自己的交来
const mine = data.items.filter((a) => a.scope === 'personal')
// 个人应用(N7)单独一组「我的应用」放在前面:只有拥有者看得见,服务端只把自己的交来。开了登录的管理员另看得到别人的
// 个人应用在不在(服务端只给元数据,my_role 为空):单列一组「使用者的个人应用」放在最后,不链到页面,只给归档
const others = data.items.filter(isPersonalStub)
const mine = data.items.filter((a) => a.scope === 'personal' && !isPersonalStub(a))
const shared = data.items.filter((a) => a.scope !== 'personal')
if (mine.length) {
if (mine.length || others.length) {
return (
<div className="space-y-4">
<section aria-labelledby="apps-home-personal" data-app-group="personal">
<h2 id="apps-home-personal" className="text-xs font-semibold">{PERSONAL_TEXT.group}</h2>
<p className="mb-2 text-2xs text-faint">{PERSONAL_TEXT.groupHint}</p>
<ul className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3" data-app-list-personal="">
{mine.map((a) => <AppCard key={a.id} app={a} canEdit={false} />)}
</ul>
</section>
{mine.length > 0 && (
<section aria-labelledby="apps-home-personal" data-app-group="personal">
<h2 id="apps-home-personal" className="text-xs font-semibold">{PERSONAL_TEXT.group}</h2>
<p className="mb-2 text-2xs text-faint">{PERSONAL_TEXT.groupHint}</p>
<ul className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3" data-app-list-personal="">
{mine.map((a) => <AppCard key={a.id} app={a} canEdit={false} />)}
</ul>
</section>
)}
{shared.length > 0 && (
<section aria-labelledby="apps-home-shared" data-app-group="shared">
<h2 id="apps-home-shared" className="mb-2 text-xs font-semibold">{PERSONAL_TEXT.sharedGroup}</h2>
@@ -181,6 +186,15 @@ function AppsTab() {
</ul>
</section>
)}
{others.length > 0 && (
<section aria-labelledby="apps-home-others" data-app-group="others">
<h2 id="apps-home-others" className="text-xs font-semibold">{PERSONAL_TEXT.othersGroup}</h2>
<p className="mb-2 text-2xs text-faint">{PERSONAL_TEXT.othersGroupHint}</p>
<ul className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3" data-app-list-others="">
{others.map((a) => <PersonalStubCard key={a.id} app={a} onArchived={reload} />)}
</ul>
</section>
)}
</div>
)
}
+3 -6
View File
@@ -45,13 +45,10 @@ import { AppMeta, BackLink, LoadError, appPath } from './shared'
interface Box { top: number; left: number; width: number; height: number }
/**
* 服务端给的「草稿和当前发布版是否一致」(AppDetail.draft_changed,见报告的接口约定请求)。没给的当不知道:
* 只在这一次改过之后说「有未发布的改动」,不在浏览器里拿草稿和发布版逐项比(发布时服务端会规整 spec,比不准)
* 服务端给的「草稿和当前发布版是否一致」(AppDetail.draft_changed)。没给的当不知道:只在这一次改过之后说「有未发布的
* 改动」,不在浏览器里拿草稿和发布版逐项比(发布时服务端会规整 spec,比不准)
*/
const draftChangedOf = (d: AppDetail): boolean | null => {
const v = (d as AppDetail & { draft_changed?: unknown }).draft_changed
return typeof v === 'boolean' ? v : null
}
const draftChangedOf = (d: AppDetail): boolean | null => d.draft_changed ?? null
/** 组件在界面上叫什么:属性里写的名字、标题,再退到目录里的中文名 */
function labelOf(comp: AppComponent | undefined, entry: CatalogComponent | undefined): string {
@@ -344,7 +344,8 @@ export function NotifySection() {
const [channels, setChannels] = useState<NotifyChannelRow[] | null>(null)
useEffect(() => { api.notify.channels().then(({ items }) => setChannels(items)).catch(() => setChannels([])) }, [])
const set = (notify: typeof draft.notify) => setDraft((s) => ({ ...s, notify }))
const events = Object.keys(NOTIFY_TEXT.eventLabel)
// 「我提交审核的应用有结果」是发给提交人的,不归哪个应用:应用的通知里不列
const events = Object.keys(NOTIFY_TEXT.eventLabel).filter((e) => e !== 'review.done')
return (
<div className="mx-auto max-w-3xl p-4" data-app-notify={draft.notify.length}>
<SectionBar title={T.sections.notify} hint={T.notifyHint}>
+113 -36
View File
@@ -3,47 +3,30 @@
* 结果遮罩、探索运行未经发布审核),「刷新」写明今天还剩几次,「提交审核」交给一位搭建者或一个组。
*
* 印章上的「探索 · 未经发布审核」由服务端写,这里不另编(P1)。剩余次数以服务端为准:详情里给了(AppDetail.personal,
* 服务端 blueprints/personal.personal_state 的形状,typesApp 还没有它、契约待补)就写,刷新的回包里也带;不知道的不猜,
* 只说有上限。超了上限服务端回 429,照实说用完了。蓝图改过、还没重新存的(graph_changed),照实说刷新要先重新存。
* 服务端 blueprints/personal.personal_state)就写,刷新的回包里也带;不知道的不猜,只说有上限。超了上限服务端回 429,
* 照实说用完了。蓝图改过、还没重新存的(graph_changed),照实说刷新要先重新存。
*
* 审核状态同样以服务端为准:最近一条审核待办还在等(pending)写「审核中」;搭建者发布了(decision=published)写
* 「已有正式版本:去看看」,链到发布的那个应用;退回了写退回和原因,可以再提交。详情没给时看蓝图的状态(in_review)。
*
* 别人的个人应用(开了登录的管理员看到的,my_role 为空):服务端只给名称、拥有者、状态、创建和更新时间(api/apps._personal_stub),
* 这里照它写,给「归档」;页面、运行、蓝图的内容都看不到,也不去取(PersonalStubCard、PersonalStubPage)。
*/
import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { FileCheck2, Hourglass, RotateCw, Send, UserRound } from 'lucide-react'
import { Archive, FileCheck2, Hourglass, LayoutGrid, RotateCw, Send, UserRound } from 'lucide-react'
import { ApiError, api } from '../../api/client'
import { PrincipalPicker, type Principal } from '../../components/PrincipalPicker'
import { Modal, Notice, Spinner, toast } from '../../components/ui'
import { PERSONAL_TEXT as T } from '../../lib/termsApp'
import type { AppDetail } from '../../typesApp'
import { Modal, Notice, PageHeader, Spinner, confirmDialog, toast } from '../../components/ui'
import { formatDateTime } from '../../lib/format'
import { APP_TEXT, PERSONAL_TEXT as T } from '../../lib/termsApp'
import type { AppDetail, AppSummary, PersonalReview } from '../../typesApp'
import { blueprintPath } from '../blueprints/shared'
import { appPath } from './shared'
/** 最近一条审核待办(服务端 personal_state.review):status 是待办的状态,decision 是结论(published / reject) */
export interface PersonalReview {
task_id: string
status: 'pending' | 'resolving' | 'resolved' | 'cancelled' | 'expired'
decision?: 'published' | 'reject' | null
note?: string
/** 发布出来的正式应用(decision=published 时) */
app_id?: string | null
to?: { kind: 'user' | 'group'; name: string }[]
resolved_at?: string | null
}
/** 个人应用在详情里多给的(服务端 blueprints/personal.personal_state):今天还能刷新几次、蓝图改过没有、审核到哪了 */
export interface PersonalInfo {
remaining_today?: number | null
daily_limit?: number | null
blueprint_status?: string | null
graph_changed?: boolean
review?: PersonalReview | null
}
import { BackLink, appPath } from './shared'
/** 界面上的审核状态:在等、发布了、退回了;还没提交过(或审核取消、过期)为 null */
type ReviewView =
| { state: 'in_review'; to?: { kind: 'user' | 'group'; name: string }[] }
| { state: 'in_review'; to?: PersonalReview['to'] }
| { state: 'published'; appId?: string | null }
| { state: 'rejected'; note?: string }
@@ -55,11 +38,11 @@ function reviewView(r: PersonalReview | null | undefined): ReviewView | null {
return null
}
export const personalOf = (d: AppDetail | undefined): PersonalInfo | null =>
((d as (AppDetail & { personal?: PersonalInfo }) | undefined)?.personal) ?? null
export function PersonalBar({ detail, onRefreshed }: { detail: AppDetail; onRefreshed: () => void }) {
const info = personalOf(detail)
const info = detail.personal ?? null
// 管理员关了开关:刷新、提交审核服务端都会拒,详情里照同一条规则给了 allowed(blueprints/personal.allowed),这里照它写明、
// 按钮置灰。详情没给(老服务端)的不猜,按钮照常,由服务端拒并说清
const allowed = info?.allowed !== false
const [remaining, setRemaining] = useState<number | null>(info?.remaining_today ?? null)
const [busy, setBusy] = useState(false)
const [review, setReview] = useState<ReviewView | null>(reviewView(info?.review))
@@ -102,6 +85,7 @@ export function PersonalBar({ detail, onRefreshed }: { detail: AppDetail; onRefr
return (
<div className="space-y-2" data-personal-bar={detail.id}>
<Notice tone="info" attr={{ 'data-personal-banner': '' }}>{T.banner}</Notice>
{!allowed && <Notice tone="warn" attr={{ 'data-personal-off': '' }}>{T.switchedOff}</Notice>}
{info?.graph_changed && detail.blueprint_id && (
<Notice tone="warn" attr={{ 'data-personal-graph-changed': '' }}>
{T.graphChanged}{' '}
@@ -109,8 +93,8 @@ export function PersonalBar({ detail, onRefreshed }: { detail: AppDetail; onRefr
</Notice>
)}
<div className="flex flex-wrap items-center gap-2 text-xs">
<button type="button" className="btn btn-sm" disabled={busy || usedUp} onClick={() => void refresh()}
title={usedUp ? T.refreshUsedUp : T.refreshLimitHint} data-personal-refresh="">
<button type="button" className="btn btn-sm" disabled={busy || usedUp || !allowed} onClick={() => void refresh()}
title={!allowed ? T.switchedOff : usedUp ? T.refreshUsedUp : T.refreshLimitHint} data-personal-refresh="">
{busy ? <Spinner size={11} /> : <RotateCw size={11} aria-hidden />} {busy ? T.refreshing : T.refresh}
</button>
<span className="text-2xs text-dim" data-personal-remaining={remaining ?? ''}>
@@ -137,7 +121,8 @@ export function PersonalBar({ detail, onRefreshed }: { detail: AppDetail; onRefr
{review.note ? T.rejectedNote(review.note) : T.rejected}
</span>
)}
<button type="button" className="btn btn-sm" title={T.submitReviewHint} onClick={() => setAsking(true)}
<button type="button" className="btn btn-sm" title={allowed ? T.submitReviewHint : T.switchedOff} disabled={!allowed}
onClick={() => setAsking(true)}
data-personal-submit-review="">
<Send size={11} aria-hidden /> {T.submitReview}
</button>
@@ -198,3 +183,95 @@ function ReviewDialog({ appId, onClose, onSent }: {
</Modal>
)
}
// ---------------------------------------------------------------- 别人的个人应用(管理员)
/** 别人的个人应用:开了登录的管理员看到的只有元数据(服务端 api/apps._personal_stub,my_role 为空) */
export const isPersonalStub = (a: AppSummary): boolean => a.scope === 'personal' && a.my_role == null
/** 归档别人的个人应用:确认框写明后果;成功交回服务端的那一份(同样只有元数据),取消或失败为 null */
async function archiveStub(app: AppSummary): Promise<AppSummary | null> {
if (!(await confirmDialog({
title: T.archiveTitle(app.name), consequences: T.archiveConsequences, confirmLabel: T.archiveConfirm, danger: true,
}))) return null
try {
const next = await api.apps.archive(app.id)
toast.ok(T.archiveDone(next.name))
return next
} catch (e) {
toast.error(e)
return null
}
}
/** 拥有者、创建和更新时间:服务端只给这几样 */
function StubMeta({ app }: { app: AppSummary }) {
return (
<div className="space-y-0.5 text-2xs leading-relaxed text-dim" data-app-stub-meta="">
<p data-app-stub-owner={app.owner ?? ''}>{app.owner ? T.owner(app.owner) : T.ownerUnknown}</p>
{app.created_at && <p data-app-stub-created="">{T.createdAt(formatDateTime(app.created_at))}</p>}
<p data-app-stub-updated="">{T.updatedAt(formatDateTime(app.updated_at))}</p>
</div>
)
}
function ArchiveButton({ app, onArchived }: { app: AppSummary; onArchived: (next: AppSummary) => void }) {
const [busy, setBusy] = useState(false)
if (app.status === 'archived') return <span className="chip">{APP_TEXT.archived}</span>
return (
<button type="button" className="btn btn-xs" disabled={busy} data-app-stub-archive=""
onClick={async () => {
setBusy(true)
const next = await archiveStub(app)
setBusy(false)
if (next) onArchived(next)
}}>
{busy ? <Spinner size={10} /> : <Archive size={11} aria-hidden />} {T.archive}
</button>
)
}
/** 应用首页「使用者的个人应用」一组里的一张卡:不链到应用页(看不到内容),只写元数据,给「归档」 */
export function PersonalStubCard({ app, onArchived }: { app: AppSummary; onArchived: () => void }) {
return (
<li className="flex flex-col rounded-lg border bg-panel p-3" data-app-stub={app.id}>
<div className="flex items-start gap-2">
<span aria-hidden className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md border bg-elev text-dim">
<LayoutGrid size={14} />
</span>
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-semibold text-fg">{app.name}</div>
<StubMeta app={app} />
</div>
</div>
<div className="mt-2.5 flex flex-wrap items-center gap-1.5 text-2xs">
<span className="chip" style={{ color: 'var(--accent)' }}>{T.badge}</span>
<span className="flex-1" />
<ArchiveButton app={app} onArchived={onArchived} />
</div>
</li>
)
}
/** 管理员打开别人的个人应用:写明看不到内容,只给元数据和「归档」,不去取页面 */
export function PersonalStubPage({ app, onArchived }: { app: AppSummary; onArchived: () => void }) {
const who = app.owner ?? T.ownerUnknown
return (
<div className="flex h-full flex-col" data-app-stub-page={app.id}>
<PageHeader icon={<LayoutGrid size={14} />} title={app.name}
actions={<span className="chip" title={T.badgeHint} data-app-personal="">{T.badge}</span>} />
<div className="min-h-0 flex-1 overflow-y-auto">
<div className="mx-auto max-w-5xl space-y-3 p-4">
<div className="text-2xs"><BackLink to="/apps?tab=apps" label={APP_TEXT.backToApps} /></div>
<Notice tone="info" attr={{ 'data-app-stub-notice': '' }}>
<span className="font-medium">{T.stubTitle(who)}</span>:{T.stubBody}
</Notice>
<div className="flex flex-wrap items-start gap-3 rounded-lg border bg-panel p-3">
<div className="min-w-0 flex-1"><StubMeta app={app} /></div>
<ArchiveButton app={app} onArchived={onArchived} />
</div>
</div>
</div>
</div>
)
}
@@ -342,16 +342,18 @@ function AddButton({ ctx, label, prompt, path, make }: {
)
}
/** 「看哪些数」的一项:先写对到的数据(表、中文名、粒度、业务日期、为什么),再逐项列 */
/**
* 「看哪些数」的一项:先写对到的数据(表、粒度、业务日期、为什么),再逐项列。表只写「源.表」(服务端 BpDataItem.table 是
* {source, table}):表的中文名不在蓝图里,要看去数据目录,这里不另取
*/
function DataBlock({ ctx, item, index }: { ctx: CardCtx; item: BpDataItem; index: number }) {
const table = (item.table?.value ?? null) as { source?: string; table?: string; label?: string } | null
const date = item.date?.value as { column?: string; rule?: string } | null
const table = item.table?.value ?? null
const date = item.date?.value ?? null
const head = table?.table ? (
<div className="mb-1.5 rounded border bg-bg px-2 py-1.5 text-2xs leading-relaxed" data-bp-match={`${table.source}.${table.table}`}>
<div className="flex flex-wrap items-center gap-x-3 gap-y-0.5">
<span className="inline-flex items-center gap-1 text-fg"><Database size={11} aria-hidden className="text-faint" />
{BLUEPRINT_TEXT.dataTable}:<span className="mono">{table.source}.{table.table}</span></span>
{table.label && <span>{BLUEPRINT_TEXT.dataTableLabel}:<span className="text-fg">{table.label}</span></span>}
{item.grain?.value != null && <span>{BLUEPRINT_TEXT.dataGrain}:<span className="text-fg">{String(item.grain.value)}</span></span>}
{date?.column && <span>{BLUEPRINT_TEXT.dataDate}:<span className="text-fg">{valueText('date', date)}</span></span>}
</div>
@@ -448,9 +450,6 @@ function AccessCard({ ctx, note, issues }: { ctx: CardCtx; note?: string; issues
// ---------------------------------------------------------------- 关节
/** 关节的说明:服务端在关节状态上给了名字和种类时用它,没给写关节 id */
type JointView = JointState & { label?: string | null; kind?: string | null }
/** 按卡片直接填好的确定性关节(表单、处理人、定时这些):不经模型,不逐个列 */
const deterministic = (j: JointState) => j.status === 'filled' && j.by === 'template'
@@ -460,7 +459,7 @@ function Joints({ blueprintId }: { blueprintId: string }) {
const bp = entry?.blueprint
if (!bp) return null
const fill = entry?.fill
const all = Object.entries(bp.joints ?? {}) as [string, JointView][]
const all = Object.entries(bp.joints ?? {})
// 只列生成关节(取数的 SQL、指标的算法):确定性关节按卡片填,汇总成一句
const joints = all.filter(([, j]) => !deterministic(j))
const fixed = all.length - joints.length
@@ -479,8 +478,9 @@ function Joints({ blueprintId }: { blueprintId: string }) {
setBusy(false)
}
}
// 关节的说法:模板声明的名字,没有就写种类和 id(实例化之前存下的关节没有这两项)
const nameOf = (id: string) => {
const j = (bp.joints?.[id] ?? {}) as JointView
const j: Partial<JointState> = bp.joints?.[id] ?? {}
return j.label || (j.kind ? `${JOINT_KIND_LABEL[j.kind] ?? j.kind}(${id})` : id)
}
return (
@@ -16,10 +16,14 @@ import { decodeCopilot, type CopilotOp } from '../../run/decode'
import { BLUEPRINT_TEXT } from '../../lib/terms'
import { chatBusy, openAsk, useBlueprint, type BpTurn } from '../../store/blueprint'
import type { ConversationTurn } from '../../types'
import type { BlueprintTurnMeta } from '../../typesBlueprint'
/** 落过库的一轮 → 显示用的一轮。meta.asked 是服务端记的反问 {question, options};answer 是回答或这一轮的说明 */
/**
* 落过库的一轮 → 显示用的一轮。meta 的形状见 BlueprintTurnMeta(ConversationTurn.meta 是各种对话共用的宽类型,这里按蓝图
* 对话的约定读,缺字段、类型不对的照样不崩);answer 是回答或这一轮的说明
*/
function pastTurn(t: ConversationTurn): StreamTurn {
const meta = (t.meta ?? {}) as { looks?: CopilotOp[]; asked?: { question?: string; options?: string[] } | null }
const meta: BlueprintTurnMeta = t.meta ?? {}
const asked = meta.asked && typeof meta.asked === 'object' ? meta.asked : null
const ops: CopilotOp[] = [...(Array.isArray(meta.looks) ? meta.looks.map((l) => ({ ...l, op: 'look' })) : [])]
if (t.status !== 'error') ops.push({ op: 'done', explanation: t.explanation || '' })
@@ -29,8 +29,6 @@ import { blueprintPath, useCreateScope } from './shared'
/** 起点:建蓝图的请求体里 source 那一段 */
type Source = { kind: BlueprintSourceKind; id?: string; version?: number }
/** 模板说明:服务端给了会产出什么、要准备什么时用它的,没给时按模板 id 说(termsBlueprint.TEMPLATE_PRODUCES) */
type TemplateCardInfo = TemplateInfo & { produces?: string | null; prepare?: string[] | null }
export function NewAppStart() {
const scope = useCreateScope()
@@ -155,7 +153,7 @@ function TemplateStart({ scope, busy, onPick }: {
}) {
const { data, error, reload } = useLoad(() => api.templates.list(), [])
// 「自由形」是从已有的运行或工作流导入用的,不作为从零开始的场景
const items = (data?.items ?? []).filter((t) => t.id !== 'freeform') as TemplateCardInfo[]
const items = (data?.items ?? []).filter((t) => t.id !== 'freeform')
return (
<section className="space-y-2" data-new-app-start="template" aria-labelledby="new-app-template">
<div>
@@ -177,14 +175,15 @@ function TemplateStart({ scope, busy, onPick }: {
}
function TemplateCard({ t, scope, busy, onPick }: {
t: TemplateCardInfo; scope: BlueprintScope; busy: string | null; onPick: (t: TemplateInfo) => void
t: TemplateInfo; scope: BlueprintScope; busy: string | null; onPick: (t: TemplateInfo) => void
}) {
// 个人应用只能用模板里只读的那部分;整个模板都用不了的(要派人审批、写外部系统)照实说,不给选
const blocked = scope === 'personal' && !t.personal
const produces = t.produces || TEMPLATE_PRODUCES[t.id]
const prepare = t.prepare?.length ? t.prepare
: t.cards.filter((c) => c.card !== 'purpose' && c.card !== 'template')
.map((c) => (c.note ? `${CARD_LABEL[c.card] ?? c.card}:${c.note}` : CARD_LABEL[c.card] ?? c.card))
// 会产出什么:按模板 id 说(termsBlueprint.TEMPLATE_PRODUCES,模板说明里没有这一项);要准备什么:用模板说明里各张卡片的
// 说明拼(服务端 TemplateInfo.cards)
const produces = TEMPLATE_PRODUCES[t.id]
const prepare = t.cards.filter((c) => c.card !== 'purpose' && c.card !== 'template')
.map((c) => (c.note ? `${CARD_LABEL[c.card] ?? c.card}:${c.note}` : CARD_LABEL[c.card] ?? c.card))
const key = `template:${t.id}`
return (
<li className="flex flex-col rounded-lg border bg-panel p-3" data-template={t.id} aria-disabled={blocked || undefined}>
@@ -23,10 +23,10 @@ import { appPath, usePoll } from '../apps/shared'
const WHO: ProblemWho[] = ['you', 'assistant', 'admin']
/**
* 这条问题归谁:服务端在问题顶层给的 who(发布单按自动修复的种类、要管理员的编号算好的)为准,没有再看白话里登记的
* 那一档。PlainIssue 还没有顶层的 who(契约待补),先按多一项读
* 这条问题归谁:服务端在问题顶层给的 who(发布单按自动修复的种类、要管理员的编号算好的,没登记白话的也有)为准;
* 没给的(老服务端)再看白话里登记的那一档
*/
const whoOf = (p: PlainIssue): ProblemWho => (p as PlainIssue & { who?: ProblemWho }).who ?? p.plain?.who ?? 'you'
const whoOf = (p: PlainIssue): ProblemWho => p.who ?? p.plain?.who ?? 'you'
const DISPOSITIONS: Disposition[] = ['recompute', 'dual', 'incomparable']
const POLL_MS = 1000
@@ -97,7 +97,8 @@ export function PublishSummary({ blueprintId, open, onClose, onFix }: {
}
const problems = plan?.problems ?? []
const blocked = problems.some((p) => p.level === 'error')
// 能不能确认以服务端为准(ok:没有 error 级问题、也没停下),界面不另算
const blocked = !!plan && !plan.ok
const started = !!plan && plan.status !== 'planned'
const scheduled = !!plan?.steps.some((s) => s.kind === 'create_schedule' && s.status !== 'skipped')
const when = scheduled ? cadenceWhen(bp?.spec.cadence?.value) : ''
@@ -264,16 +265,7 @@ function ProblemColumn({ who, items, onFix, onDispose, busy }: {
<div style={{ color: p.level === 'error' ? 'var(--st-failed)' : 'var(--st-waiting)' }}>{p.plain?.title ?? p.message}</div>
{p.plain?.why && <div className="text-dim">{p.plain.why}</div>}
{p.plain?.action && <div className="text-faint">{p.plain.action}</div>}
{p.code === 'app.upgrade_policy' && typeof (p as { alias?: unknown }).alias === 'string' && (
<div className="mt-1 flex flex-wrap gap-1" role="group" data-plan-disposition={(p as { alias?: string }).alias}>
{DISPOSITIONS.map((d) => (
<button key={d} type="button" className="btn btn-xs" disabled={busy} title={APP_EDITOR_TEXT.dispositionHint[d]}
onClick={() => onDispose((p as { alias?: string }).alias!, d)}>
{APP_EDITOR_TEXT.dispositions[d]}
</button>
))}
</div>
)}
{p.code === 'app.upgrade_policy' && p.alias && <DispositionChoice alias={p.alias} busy={busy} onDispose={onDispose} />}
</li>
))}
</ul>
@@ -286,3 +278,19 @@ function ProblemColumn({ who, items, onFix, onDispose, busy }: {
</div>
)
}
/** 钉住项升了版、要选处置的(app.upgrade_policy 带 alias):就地给三种处置,选了带着处置重出发布单 */
function DispositionChoice({ alias, busy, onDispose }: {
alias: string; busy: boolean; onDispose: (alias: string, d: Disposition) => void
}) {
return (
<div className="mt-1 flex flex-wrap gap-1" role="group" data-plan-disposition={alias}>
{DISPOSITIONS.map((d) => (
<button key={d} type="button" className="btn btn-xs" disabled={busy} title={APP_EDITOR_TEXT.dispositionHint[d]}
onClick={() => onDispose(alias, d)}>
{APP_EDITOR_TEXT.dispositions[d]}
</button>
))}
</div>
)
}
@@ -21,7 +21,7 @@ import { cleanValues, validateForm, withDefaults } from '../../lib/schemaForm'
import { TRIAL_TEXT } from '../../lib/terms'
import { TaskCard } from '../../run/TaskCard'
import { useBlueprint } from '../../store/blueprint'
import type { AppSpec, FormError, FormSchema, ViewModel } from '../../typesApp'
import type { FormError, FormSchema, ViewModel } from '../../typesApp'
import { useLoad, usePoll } from '../apps/shared'
import { blueprintPath } from './shared'
@@ -29,12 +29,11 @@ const POLL_MS = 4000
/** 流程类模板:试运行里有人工步骤,右侧要列待办 */
const PROCESS_TEMPLATES = new Set(['approval', 'exception_handling', 'reconcile_writeback'])
/** 应用骨架里第一个入口的表单(试运行的输入) */
function entryForm(spec: AppSpec | null | undefined): FormSchema | null {
const form = spec?.entries?.[0]?.form
if (!form) return null
return '$ref' in form ? spec?.forms?.[String((form as { $ref: string }).$ref)] ?? null : form as FormSchema
}
/**
* 「换一期再试」填的表单:服务端随预览给(ViewModel.trial.form,blueprints/trial.retry_form,和试运行时认表单是同一条规则),
* 这里照着画,不自己从骨架里挑。没有的只能原样再试一次
*/
const trialForm = (model: ViewModel | null | undefined): FormSchema | null => model?.trial?.form ?? null
/** 视图里报错的那一块:服务端在来源上写了为什么 */
function failureOf(model: ViewModel | null | undefined): string | null {
@@ -136,8 +135,7 @@ function TrialBanner({ blueprintId, runId, model, onRetried }: {
}) {
const entry = useBlueprint((s) => s.byId[blueprintId])
const last = entry?.lastTrial?.run_id === runId ? entry.lastTrial : null
// 输入表单:服务端随试运行给的,没给就用按卡片生成的应用骨架里的入口表单
const form = last?.form ?? entryForm(entry?.instantiated?.app_spec)
const form = trialForm(model)
const [open, setOpen] = useState(false)
const [values, setValues] = useState<Record<string, unknown>>({})
const [errors, setErrors] = useState<FormError[]>([])
+2 -2
View File
@@ -19,10 +19,10 @@ export const blueprintPath = (id: string, section?: 'trial', query?: Record<stri
/**
* 管理员开没开「使用者建个人应用」(设置 apps.user_personal_apps,默认关)。使用者读不到设置,开关随认人接口
* (GET /api/auth/me)一起给,同问数据的 user_can_chat。老服务端不给时按关。
* (GET /api/auth/me 的 Principal.user_personal_apps)一起给,同问数据的 user_can_chat。老服务端不给时按关。
*/
export function personalAppsOn(me: Principal | null | undefined): boolean {
return (me as (Principal & { user_personal_apps?: boolean }) | null | undefined)?.user_personal_apps === true
return me?.user_personal_apps === true
}
/** 这个人新建应用时建哪种蓝图;null = 没有入口 */
+16 -11
View File
@@ -41,7 +41,7 @@ import { REVIEW_TASK_TEXT } from '../lib/termsApp'
import { blueprintPath } from '../pages/blueprints/shared'
import type { Approval, ApprovalReport } from '../types'
import type {
FormError, Task, TaskAssignment, TaskKind, TaskMyResponse, TaskProgress, TaskRespond,
FormError, ReviewTaskPayload, Task, TaskAssignment, TaskKind, TaskMyResponse, TaskProgress, TaskRespond,
} from '../typesApp'
import { Markdown } from './Markdown'
import { ApprovalReports, ApprovalRunClass } from './ApprovalReport'
@@ -71,10 +71,7 @@ export interface TaskCardProps {
trial?: boolean
}
/** 待办的种类,多一种 review(个人应用提交审核):typesApp 的 TaskKind 还没有它(契约待补),先在这里按多一种认 */
type CardKind = TaskKind | 'review'
const KIND_ICON: Record<CardKind, typeof Hand> = {
const KIND_ICON: Record<TaskKind, typeof Hand> = {
approve: Hand, input: Keyboard, edit: PenLine, tool: Wrench, code: Code, dual_check: Hand,
action_confirm: Send, reconcile: SearchCheck, signal: Webhook, review: UserCheck,
}
@@ -85,7 +82,7 @@ const STALE_MS = 24 * 3_600_000
export function TaskCard({ task, onResolved, compact = false, send, showOwner = true, showSignoffs = true, trial = false }: TaskCardProps) {
const toast = useToast()
const payload: Record<string, any> = task.payload ?? {}
const kind = task.kind as CardKind
const kind = task.kind
const pending = task.status === 'pending'
const canAct = pending && task.can_respond
const inquiring = useInquiryBusy(task.run_id)
@@ -301,9 +298,10 @@ function Review({ task, canAct, busy, note, setNote, onReject }: {
const me = usePrincipal()
const actor = useLocalActor()
const [copying, setCopying] = useState(false)
const payload: Record<string, any> = task.payload ?? {}
const payload: Partial<ReviewTaskPayload> = task.payload ?? {}
const blueprintId = typeof payload.blueprint_id === 'string' ? payload.blueprint_id : null
const copies: { id: string; owner: string | null; status: string }[] = Array.isArray(payload.copies) ? payload.copies : []
const copies = Array.isArray(payload.copies) ? payload.copies : []
// 审核副本归取它的那位搭建者:取过的打开自己那一份(别的处理人取的副本不算)
const myName = me?.username ?? actor ?? null
const mine = copies.find((c) => c.owner === myName)
const submitter = typeof payload.submitted_by === 'string' ? payload.submitted_by : null
@@ -382,7 +380,7 @@ function TaskMeta({ task, showOwner }: { task: Task; showOwner: boolean }) {
const owner = !showOwner ? null : task.app_name ? task.app_name : task.workflow_name ? runName(task) : null
return (
<div className="tnum mb-2 flex flex-wrap items-center gap-x-1.5 gap-y-0.5 text-2xs text-dim">
<span>{TASK_KIND_LABEL[task.kind as CardKind] ?? task.kind}</span>
<span>{TASK_KIND_LABEL[task.kind] ?? task.kind}</span>
{owner && <><span aria-hidden>·</span><span>{owner}</span></>}
{where && <><span aria-hidden>·</span><span>{TASK_TEXT.node(where)}</span></>}
{created && <><span aria-hidden>·</span><span title={formatDateTime(created)}>{TASK_TEXT.createdAt(formatTime(created))}</span></>}
@@ -774,15 +772,22 @@ function Signer() {
)
}
/** 去实例页(应用里的)或记录页(别处的,搭建者以上才看得到记录页) */
/**
* 去实例页(应用里的)或记录页(别处的,搭建者以上才看得到记录页)。
*
* 审核个人应用的待办不给这两个:run_id 是提交人那次个人应用的刷新、app_id 是他的个人应用,只有拥有者读得到(服务端
* auth/access.private_owner,处理人是管理员、搭建者也不例外),链出去只会是打不开的页面。处理人要看的是取副本之后在副本
* 蓝图上试运行出来的(Review 里的「取副本,去发布」「打开我的副本」)
*/
function TaskLinks({ task }: { task: Task }) {
const builder = useAtLeast('builder')
const links = useMemo(() => {
const out: { to: string; label: string }[] = []
if (task.kind === 'review') return out
if (task.app_id) out.push({ to: `/apps/${encodeURIComponent(task.app_id)}/i/${encodeURIComponent(task.run_id)}`, label: TASK_TEXT.openInstance })
if (builder) out.push({ to: `/runs/${encodeURIComponent(task.run_id)}`, label: TASK_TEXT.openRun })
return out
}, [task.app_id, task.run_id, builder])
}, [task.kind, task.app_id, task.run_id, builder])
if (!links.length) return null
return (
<div className="mt-1.5 flex flex-wrap gap-x-3 text-2xs">
+28 -12
View File
@@ -6,7 +6,7 @@ import {
ABSENCE_CLAIM_TEXT, ACTION_CONFIRM_TEXT, ACTION_ENV_LABEL, ACTION_LOG_TEXT, CATALOG_DRIFT_TEXT, CATALOG_PATCH_TEXT, COPILOT_CONTEXT_TEXT, JUDGE_TEXT, LOOK_TEXT, MERGE_TEXT,
ORIGIN_TEXT, RUN_SQL_CHECK_TEXT, SQL_CHECK_TEXT, TASK_KIND_LABEL, TASK_LOG_TEXT, TASK_STATUS_LABEL, TASK_TEXT, TYPE_LABEL, originLabel,
CATALOG_TABLE_FIELD_LABEL, CHALLENGE_TEXT, DUAL_CHECK_TEXT, INQUIRY_TEXT, JUDGE_TRUNCATED_TEXT, MASKED_CELL_TEXT, NODE_TYPE_LABEL,
VERIFY_TRUNCATED_TEXT, BP_OP_TEXT, TEMPLATE_LABEL, bpPathText,
VERIFY_TRUNCATED_TEXT, BP_OP_TEXT, TEMPLATE_LABEL, bpPathText, FILE_TEXT,
claimTally,
evidenceTally, issuanceLabel, nodeTypeLabel,
} from '../lib/terms'
@@ -2798,6 +2798,28 @@ export function decodeRun(events: RunEvent[], final?: RunFinal, opts?: DecodeOpt
break
}
case 'file.extracted': {
// 模板函数 file_text 读入一个附件的文字(服务端 files/text.py):读入多少字、全文多少字、是否截断,读入的那一段存成
// 工件可以点开;抽不出时 ok=false、reason 写原因。截断、抽不出都要看得见:下游拿到的不是全文
const name = typeof d.name === 'string' ? d.name.trim() : ''
const chars = num(d.chars)
const total = num(d.total_chars)
const failedRead = d.ok === false
const cut = !failedRead && d.truncated === true
const reason = typeof d.reason === 'string' && d.reason.trim() ? d.reason.trim() : undefined
push({
id: `fx-${seq}`, seq, kind: 'tool', nodeId, status: 'done', code: 'file_extracted',
...(failedRead || cut ? { level: 'warn' as const } : {}),
title: failedRead ? FILE_TEXT.extractFailed(name) : FILE_TEXT.extracted(name, chars != null ? formatNumber(chars) : null),
...(failedRead ? (reason ? { sub: reason } : {})
: total == null ? {}
: !cut ? { sub: FILE_TEXT.extractedAll(formatNumber(total)) }
: chars != null ? { sub: FILE_TEXT.extractedCut(formatNumber(chars), formatNumber(total)) } : {}),
...(typeof d.artifact === 'string' && d.artifact ? { artifact: d.artifact } : {}),
}, nodeId)
break
}
default:
// 新增事件类型时不要静默吞掉——宁可显示一条,也比让人觉得"什么都没
// 发生"好。但内部类型名(agent.route.end 这种)对使用者是一串代码,
@@ -3171,13 +3193,6 @@ export function catalogDrift(d: Record<string, any>): {
}
}
/**
* 查看对象的类型。口径卡(caliber,docs/design/normal-user-apps.md N2:蓝图对到已发布的口径卡)typesApp 的 LookObject 还没有,
* 契约待补,先在这里按多一种认
*/
type LookKind = LookObject['kind'] | 'caliber'
const kindOf = (o: LookObject): LookKind => o.kind as LookKind
/**
* look 事件(L2,服务端 app/look/base.py 的形状)读进来:objects 按类型标记;字段缺了的补空,认不出的形状返回 null
* (不出这一行,也不报错)。旧写法 sources[] 当作表类型读
@@ -3190,7 +3205,7 @@ export function lookEventOf(op: CopilotOp): LookEvent | null {
const objects: LookObject[] = list
.filter((x): x is Record<string, any> => !!x && typeof x === 'object')
.map((x) => {
const kind = (x.kind === 'capability' || x.kind === 'workflow_version' || x.kind === 'caliber' ? x.kind : 'table') as LookObject['kind']
const kind: LookObject['kind'] = x.kind === 'capability' || x.kind === 'workflow_version' || x.kind === 'caliber' ? x.kind : 'table'
const total = num(x.total)
const explored = num(x.explored)
return {
@@ -3213,10 +3228,10 @@ export function lookEventOf(op: CopilotOp): LookEvent | null {
}
/** 这一类对象一共给了几个(表:点名的 + 挑出的 + 补上的,去重) */
function lookCount(objects: LookObject[], kind: LookKind): number {
function lookCount(objects: LookObject[], kind: LookObject['kind']): number {
const seen = new Set<string>()
for (const o of objects) {
if (kindOf(o) !== kind) continue
if (o.kind !== kind) continue
for (const n of [...o.named, ...(o.picked ?? []), ...(o.joined ?? [])]) seen.add(`${o.source ?? ''}\u0000${n}`)
}
return seen.size
@@ -3236,7 +3251,8 @@ function lookLine(o: LookObject): string {
o.picked?.length ? LOOK_TEXT.picked(o.picked) : '',
o.joined?.length ? LOOK_TEXT.joined(o.joined) : '',
].filter(Boolean)
const kind = kindOf(o)
// 口径卡(caliber)是蓝图对到的已发布口径卡上的指标(docs/design/normal-user-apps.md N2)
const kind = o.kind
const head = kind === 'table' ? `「${o.source ?? ''}」` : kind === 'capability' ? '能力' : kind === 'caliber' ? '口径卡' : '工作流版本'
const partial = o.total != null && o.explored != null ? `(${LOOK_TEXT.partial(o.total, o.explored)})` : ''
return parts.length ? `${head}${partial}:${parts.join(';')}` : ''
+8 -8
View File
@@ -8,7 +8,7 @@
* 文件字段(normal-user-apps N9):输入节点的字段写 type: file,转成 type 为 object、x-widget 为 file 的字段,允许的类型
* 和大小(accept、max_mb)进 x-file。值是上传后拿回的引用,没上传的不传。
*/
import type { FormField, FormSchema } from '../typesApp'
import type { FileLimits, FormField, FormSchema } from '../typesApp'
/** 输入节点的一个字段(canvas/nodeDefs 的 ioFields;type / enum / format / 上下限是应用平台新加的,老图没有) */
export interface InputField {
@@ -17,8 +17,8 @@ export interface InputField {
description?: string
default?: unknown
example?: unknown
/** file:文件(上传后拿回的引用) */
type?: FormField['type'] | 'file'
/** file:文件(上传后拿回的引用);表单里的 object 只给文件控件,输入节点上写 file */
type?: Exclude<FormField['type'], 'object'> | 'file'
enum?: (string | number)[]
format?: FormField['format']
/** 数字类型的上下限(闭区间,表单子集没有 exclusiveMinimum:「大于 0」的金额写 0.01) */
@@ -29,15 +29,15 @@ export interface InputField {
max_mb?: number
}
/** 文件字段:type 为 object(typesApp.FormField 还没列 object 和 x-file,见报告的接口约定请求) */
/** 文件字段:type 为 object、x-widget 为 file,限制进 x-file(同服务端 apps/forms.input_schema) */
function fileField(f: InputField): FormField {
const limits: { accept?: string[]; max_mb?: number } = {}
const limits: FileLimits = {}
if (Array.isArray(f.accept) && f.accept.length) limits.accept = f.accept.filter((a) => typeof a === 'string' && a)
if (typeof f.max_mb === 'number' && Number.isFinite(f.max_mb) && f.max_mb > 0) limits.max_mb = f.max_mb
const field: Record<string, unknown> = { type: 'object', title: f.name, 'x-widget': 'file' }
const field: FormField = { type: 'object', title: f.name, 'x-widget': 'file' }
if (f.description) field.description = f.description
if (Object.keys(limits).length) field['x-file'] = limits
return field as unknown as FormField
return field
}
const TYPES = new Set(['string', 'number', 'integer', 'boolean', 'array'])
@@ -53,7 +53,7 @@ export function inputSchemaOf(fields: InputField[]): FormSchema {
if (f.required) required.push(f.name)
continue
}
const type = f.type && TYPES.has(f.type) ? f.type as FormField['type'] : 'string'
const type = f.type && TYPES.has(f.type) ? f.type as Exclude<FormField['type'], 'object'> : 'string'
const options = Array.isArray(f.enum) && f.enum.length ? f.enum : null
const field: FormField = { type, title: f.name }
if (f.description) field.description = f.description
+60 -47
View File
@@ -4,8 +4,8 @@ import { streamBlueprint, streamFillJoints } from '../api/blueprintCopilot'
import { COPILOT_PHASE_TEXT, copilotLook, type CopilotOp } from '../run/decode'
import { BLUEPRINT_TEXT, LOOK_TEXT } from '../lib/terms'
import type { ConversationTurn } from '../types'
import type { AppSpec, FormSchema } from '../typesApp'
import type { Blueprint, BpAsk, BpOp, JointState, PlainIssue, TrialStart } from '../typesBlueprint'
import type { AppSpec } from '../typesApp'
import type { Blueprint, BpAsk, BpOp, JointState, PlainIssue } from '../typesBlueprint'
/**
* 蓝图页的状态(docs/design/normal-user-apps.md §2.2、§2.11、§4.2):每个蓝图一桶——蓝图本身、对话的轮次、填关节的进度。
@@ -71,13 +71,10 @@ export interface BpEntry {
answered: string[]
/** 最近一次按卡片生成的结果:应用骨架(试运行的输入表单从它的入口取)和检查出的问题 */
instantiated?: { app_spec: AppSpec; problems: PlainIssue[] } | null
/** 这一页里发起的最近一次试运行:用了什么输入、输入表单(服务端给了的话) */
lastTrial?: { run_id: string; inputs?: Record<string, unknown> | null; form?: FormSchema | null } | null
/** 这一页里发起的最近一次试运行:实际用了什么输入(服务端交回的,看板类补齐了统计期) */
lastTrial?: { run_id: string; inputs?: Record<string, unknown> | null } | null
}
/** 试运行的回包:服务端可以多给这次用的输入(按「多久更新」算出的最近一期)和输入表单 */
export type TrialStartOut = TrialStart & { inputs?: Record<string, unknown> | null; form?: FormSchema | null }
interface BlueprintState {
byId: Record<string, BpEntry>
/** force:手上有也再取一次 */
@@ -193,15 +190,15 @@ export const useBlueprint = create<BlueprintState>((set, get) => {
const key = `${id}:chat`
const stop = streamBlueprint(
{ blueprint_id: id, instruction },
(op: CopilotOp) => {
(op) => {
got.push(op)
patchTurn(id, turnId, (t) => ({ ops: pushOp(t.ops, op) }))
switch (op.op) {
case 'heartbeat':
patchTurn(id, turnId, () => ({
status: op.phase === 'looking' ? LOOK_TEXT.running : COPILOT_PHASE_TEXT[String(op.phase)] ?? COPILOT_PHASE_TEXT.planning,
}))
case 'heartbeat': {
const status = op.phase === 'looking' ? LOOK_TEXT.running : COPILOT_PHASE_TEXT[op.phase] ?? COPILOT_PHASE_TEXT.planning
patchTurn(id, turnId, () => ({ status }))
break
}
case 'look': {
const look = copilotLook(op)
if (look) patchTurn(id, turnId, () => ({ status: look.title }))
@@ -212,13 +209,17 @@ export const useBlueprint = create<BlueprintState>((set, get) => {
// 模型写成通用的 ask 也认(服务端存进蓝图时换成 bp_ask)
patchTurn(id, turnId, () => ({ status: BLUEPRINT_TEXT.turnAsked }))
break
case 'final':
case 'final': {
// 服务端落地后的整份蓝图为准
if (isBlueprint(op.blueprint)) { finalSeen = true; patch(id, () => ({ blueprint: op.blueprint as Blueprint })) }
const bp = op.blueprint
if (isBlueprint(bp)) { finalSeen = true; patch(id, () => ({ blueprint: bp })) }
break
case 'error':
patchTurn(id, turnId, () => ({ phase: 'error', error: String(op.message ?? BLUEPRINT_TEXT.turnFailed) }))
}
case 'error': {
const error = op.message || BLUEPRINT_TEXT.turnFailed
patchTurn(id, turnId, () => ({ phase: 'error', error }))
break
}
default:
if (BP_EDIT_OPS.has(op.op)) patchTurn(id, turnId, () => ({ status: BLUEPRINT_TEXT.turnRunning }))
}
@@ -257,10 +258,10 @@ export const useBlueprint = create<BlueprintState>((set, get) => {
},
trial: async (id, inputs) => {
const res = await api.blueprints.trial(id, inputs ? { inputs } : {}) as TrialStartOut
const res = await api.blueprints.trial(id, inputs ? { inputs } : {})
patch(id, () => ({
blueprint: res.blueprint, loadState: 'ready',
lastTrial: { run_id: res.run_id, inputs: res.inputs ?? inputs ?? null, form: res.form ?? null },
lastTrial: { run_id: res.run_id, inputs: res.inputs ?? inputs ?? null },
}))
return res.run_id
},
@@ -281,52 +282,64 @@ export const useBlueprint = create<BlueprintState>((set, get) => {
})
const stop = streamFillJoints(
{ blueprint_id: id, ...(groups?.length ? { groups } : {}) },
(op: CopilotOp) => {
const gid = typeof op.group === 'string' && op.group ? op.group : null
const joint = typeof op.joint === 'string' ? op.joint : null
(op) => {
const gid = op.group || null
switch (op.op) {
case 'group':
case 'group': {
// 组的结局:started / retrying(并行出错退回串行再试)是在填,filled 填好,failed 没填上(带原因或没过的检查)
if (gid) {
const issue = Array.isArray(op.issues) ? op.issues.find((i: any) => i?.message) : null
group(gid, (g) => ({
joints: Array.isArray(op.joints) ? op.joints.map(String) : g.joints,
status: op.status === 'filled' ? 'done' : op.status === 'failed' ? 'failed' : 'running',
line: op.status === 'retrying' ? BLUEPRINT_TEXT.groupRetrying : g.line,
...(op.message || issue ? { message: String(op.message ?? issue.message) } : {}),
}))
}
const message = op.message || op.issues?.find((i) => i.message)?.message
const status = op.status === 'filled' ? 'done' : op.status === 'failed' ? 'failed' : 'running'
const joints = op.joints?.map(String)
const retrying = op.status === 'retrying'
group(op.group, (g) => ({
joints: joints ?? g.joints, status, line: retrying ? BLUEPRINT_TEXT.groupRetrying : g.line,
...(message ? { message } : {}),
}))
break
case 'plan':
if (gid && op.summary) group(gid, () => ({ line: String(op.summary) }))
}
case 'plan': {
const line = op.summary
if (gid && line) group(gid, () => ({ line }))
break
case 'check':
if (gid) group(gid, () => ({ line: op.status === 'repairing' ? COPILOT_PHASE_TEXT.repairing : BLUEPRINT_TEXT.groupChecked }))
}
case 'check': {
const line = op.status === 'repairing' ? COPILOT_PHASE_TEXT.repairing : BLUEPRINT_TEXT.groupChecked
if (gid) group(gid, () => ({ line }))
break
case 'fill_joint':
if (joint) patchFill(id, (f) => ({ joints: { ...f.joints, [joint]: { status: 'filled' } } }))
if (gid && joint) group(gid, (g) => ({ joints: g.joints.includes(joint) ? g.joints : [...g.joints, joint] }))
}
case 'fill_joint': {
const joint = op.joint
patchFill(id, (f) => ({ joints: { ...f.joints, [joint]: { status: 'filled' } } }))
if (gid) group(gid, (g) => ({ joints: g.joints.includes(joint) ? g.joints : [...g.joints, joint] }))
break
case 'heartbeat':
if (gid) group(gid, () => ({ line: op.phase === 'looking' ? LOOK_TEXT.running : COPILOT_PHASE_TEXT[String(op.phase)] }))
}
case 'heartbeat': {
const line = op.phase === 'looking' ? LOOK_TEXT.running : COPILOT_PHASE_TEXT[op.phase]
if (gid) group(gid, () => ({ line }))
break
}
case 'look': {
const look = copilotLook(op)
if (gid && look) group(gid, () => ({ line: look.title }))
break
}
case 'final':
if (isBlueprint(op.blueprint)) { finalSeen = true; patch(id, () => ({ blueprint: op.blueprint as Blueprint })) }
if (Array.isArray(op.problems)) patchFill(id, () => ({ problems: op.problems as PlainIssue[] }))
case 'final': {
const bp = op.blueprint
const problems = op.problems
if (isBlueprint(bp)) { finalSeen = true; patch(id, () => ({ blueprint: bp })) }
if (Array.isArray(problems)) patchFill(id, () => ({ problems }))
// 各组的结局以 final 为准(卡片在填的时候又改过的组,服务端判它不算数)
for (const [g, r] of Object.entries((op.groups ?? {}) as Record<string, { status?: string }>)) {
for (const [g, r] of Object.entries(op.groups ?? {})) {
group(g, () => ({ status: r?.status === 'filled' ? 'done' : 'failed' }))
}
break
case 'error':
if (gid) group(gid, () => ({ status: 'failed', message: String(op.message ?? BLUEPRINT_TEXT.groupFailed) }))
else patchFill(id, () => ({ error: String(op.message ?? BLUEPRINT_TEXT.fillFailed) }))
}
case 'error': {
const message = op.message
if (gid) group(gid, () => ({ status: 'failed', message: message || BLUEPRINT_TEXT.groupFailed }))
else patchFill(id, () => ({ error: message || BLUEPRINT_TEXT.fillFailed }))
break
}
}
},
(error, info) => {
+5 -1
View File
@@ -1569,7 +1569,11 @@ export interface VarIssue {
export interface Conversation {
id: string
title: string
kind: 'chat' | 'canvas'
/**
* 前端建的只有 chat、canvas;服务端另建两种:app 是应用编辑器的助手对话,blueprint 是蓝图对话(docs/design/normal-user-apps.md
* §2.2,权限跟着蓝图走,经 GET /api/blueprints/{id}/conversation 读)
*/
kind: 'chat' | 'canvas' | 'app' | 'blueprint'
workflow_id?: string | null
archived: boolean
created_at?: string
+130 -10
View File
@@ -21,6 +21,11 @@ export interface Principal {
verified: boolean
/** 开登录后 user 角色能不能问数据(Q2,管理员开关) */
user_can_chat?: boolean
/**
* 管理员开没开「使用者可以建个人应用」(设置 apps.user_personal_apps,docs/design/normal-user-apps.md N7)。使用者读不到
* 设置,开关随认人、登录接口一起给(服务端 api/auth.principal_full);老服务端不给时按关
*/
user_personal_apps?: boolean
}
export interface UserRow {
@@ -70,8 +75,15 @@ export type FormWidget =
/** 文件(N9):字段 type 为 object,值是上传后拿回的引用 FileRef(typesBlueprint.ts) */
| 'file'
/** 文件控件的限制(x-file,服务端 apps/forms._file_field_problems):可选的类型(扩展名或 MIME)、大小上限(MB) */
export interface FileLimits {
accept?: string[]
max_mb?: number
}
export interface FormField {
type: 'string' | 'number' | 'integer' | 'boolean' | 'array'
/** object 只有文件控件能用(x-widget 为 file,服务端 apps/spec.FILE_FIELD_TYPE),值是 FileRef */
type: 'string' | 'number' | 'integer' | 'boolean' | 'array' | 'object'
title?: string
description?: string
default?: unknown
@@ -86,6 +98,8 @@ export interface FormField {
format?: 'date' | 'date-time' | 'email' | 'uri'
items?: { type: 'string'; enum?: string[] }
'x-widget'?: FormWidget
/** 文件控件的限制,只配 x-widget: file */
'x-file'?: FileLimits
}
export interface FormSchema {
@@ -97,10 +111,13 @@ export interface FormSchema {
'x-order'?: string[]
}
/** 前后端同一种错误格式 */
/**
* 前后端同一种错误格式(服务端 apps/spec.FORM_ERROR_CODES)。file:文件控件的值不是上传后拿回的引用、类型或大小不合
* x-file 的限制,或提交时核对引用没过(不是这个人传的、已经用过)
*/
export interface FormError {
path: string
code: 'required' | 'type' | 'enum' | 'minimum' | 'maximum' | 'min_length' | 'max_length' | 'max_items' | 'format'
code: 'required' | 'type' | 'enum' | 'minimum' | 'maximum' | 'min_length' | 'max_length' | 'max_items' | 'format' | 'file'
message: string
}
@@ -193,6 +210,10 @@ export interface CatalogComponent {
version: number
children: boolean
bindings: string[]
/**
* 属性的 JSON Schema(服务端 apps/catalog.py)。给人看的文字标了 `x-text: true`(页面编辑「改文字」只列这几项,N6);
* 写给解析器的字符串(列名、换算)不标。注解不参与校验
*/
props: Record<string, any>
}
@@ -221,8 +242,12 @@ export interface AppSummary {
needs_upgrade: boolean
/** 当前用户在这个应用里的待办数 */
pending_tasks: number
/** 当前用户的授权(关登录时为 manage) */
/**
* 当前用户的授权(关登录时为 manage)。为 null 的只有一种:开了登录的管理员看别人的个人应用(服务端 api/apps._personal_stub,
* 列表、详情、归档的回包同一份)——只有名称、拥有者、状态、创建和更新时间,能归档;说明、页面、运行、蓝图一概不给(N7)
*/
my_role: GrantRole | null
created_at: string | null
updated_at: string
/** 个人应用(N7):只有拥有者看得见、跑探索运行;老服务端不给时按 shared */
scope?: 'shared' | 'personal'
@@ -230,6 +255,15 @@ export interface AppSummary {
blueprint_id?: string | null
}
/**
* GET /api/apps(scope=shared|personal 只列那一种):items 是这个人看得到的应用;can_create 是他能建哪种应用(共享要搭建者及
* 以上,个人看管理员的开关),和认人接口的 user_personal_apps 出自同一条规则(服务端 blueprints/personal.allowed)
*/
export interface AppList {
items: AppSummary[]
can_create: { shared: boolean; personal: boolean }
}
export interface AppDetail extends AppSummary {
/** 草稿和岗位绑定只给 manage(D-m);use / observe 拿到的详情里没有 */
draft?: AppSpec
@@ -239,6 +273,47 @@ export interface AppDetail extends AppSummary {
published?: { version: number; pages: { id: string; title: string }[]; entries: { id: string; label: string }[] } | null
/** 能按新口径补算的视图(只在 manage 取详情时算,D-f) */
backfill?: BackfillPlan[]
/** 个人应用给拥有者的那一块(服务端 blueprints/personal.personal_state):只在拥有者取个人应用的详情时给 */
personal?: PersonalState
/**
* 草稿(连同岗位绑定)和当前发布版是否一致(服务端 api/apps._draft_changed,按发布时的规整方式比,normal-user-apps N6)。
* 只给 manage,而且只在有发布版、发布版规整得了时给;没给的是不知道:界面只在这一次改过之后说「有未发布的改动」,
* 不在浏览器里逐项比
*/
draft_changed?: boolean
}
/**
* 个人应用的状态(N7、§4.6):能不能刷新、提交审核,今天还能刷新几次(和按需视图共用每日上限,按人计)、蓝图改过没有、
* 审核到哪了。blueprint_status 同 typesBlueprint.BlueprintStatus;蓝图被删了为 null
*/
export interface PersonalState {
/**
* 这个人现在能不能刷新、提交审核(服务端 blueprints/personal.allowed:开了登录的搭建者及以上随时能,使用者和关登录时看
* 管理员的开关)。为假时个人应用照样看得到,按钮置灰
*/
allowed: boolean
remaining_today: number
daily_limit: number
blueprint_status: import('./typesBlueprint').BlueprintStatus | null
/** 蓝图在存成个人应用之后又改过(图的哈希对不上):刷新按存下的那一版跑,要用改过的得回蓝图重新存 */
graph_changed: boolean
/** 最近一条审核待办;没提交过审核为 null */
review: PersonalReview | null
}
/** 个人应用最近一条审核待办:status 是待办的状态,decision 是结论(published 搭建者发布了副本,reject 退回) */
export interface PersonalReview {
task_id: string
status: TaskStatus
decision: 'published' | 'reject' | null
/** 退回的原因(没写为空串) */
note: string
/** 发布出来的正式应用(decision=published 时);别的时候为 null */
app_id: string | null
/** 派给了谁(没撤回的那几份) */
to: { kind: TaskAssignment['principal_kind']; name: string }[]
resolved_at: string | null
}
/** 按新口径补算会发起几次(GET /api/apps/{id}/views/{view}/backfill,不发起运行) */
@@ -313,6 +388,8 @@ export interface Stamp {
tier_text: string
from: string
sealed: boolean
/** 蓝图的试运行(N4):来源写「试运行」、说明里写这不是正式结果。不是试运行时不给 */
trial?: boolean
/** 照实标出的错位:定时任务已改跑新版本、应用还钉在旧版本,等 */
notes?: string[]
}
@@ -341,17 +418,26 @@ export interface ViewNode {
id: string
type: string
props: Record<string, any>
/**
* 作者隐藏了它(N6):只在按草稿解析(编辑状态,draft=1)时下发并带上这个标记,界面画成半透明;发布版、个人应用的
* 使用面不下发隐藏的组件
*/
hidden?: boolean
/**
* 服务端解析好的数据(backend/app/apps/resolve.py 的 _data),形状随组件而定;绑定了视图的都带 state 和可选的 message:
* - stamp:{view, state, stamp};metric:{state, text, name, unit, evidence}
* - series:{state, mode: single|dual|incomparable|recompute, unit, series: [{version, label, points: [{run_id, as_of,
* value, text, evidence}]}], breaks: [{after_run?, from, to, text}]}
* value, text, evidence, backfill?}]}], breaks: [{after_run?, from, to, text}], note?, trial?}——version 是固定的工作流
* 版本号;试运行预览里只有这一次试运行一个点,version 为 null、trial 为真、note 照实写没有趋势;钉住项还没有版本号
* (试运行派生的草稿)时 state=empty、message 说明
* - table、chart:{state, columns, rows(遮罩的格子已换成「已遮罩」), column_types, masked, total_rows, truncated, evidence}
* - report:{state, node, doc_artifact, evidence};field:{state, text, value?, evidence?};status:{state, value, text}
* - form:{form};entry_button:{entry, label, disabled, reason?};instance_list:{who, entry, items}
* - form:{form};entry_button:{entry, label, disabled, reason?};instance_list:{who, entry, items, trial?}
* - instance_header:InstanceRow + {state, stamp};instance_timeline:{state, status, status_code, status_text, steps}
* - task_list:{scope, items};task_form、signoffs:{state, task, task_ui, handler, assignments, progress, my_response}
* - task_list:{scope, items};task_form、signoffs:{state, task, task_ui, handler, assignments, progress, my_response,
* people, signoffs_on_page?, trial?}——trial:试运行里的待办派给了试运行的人自己
* - action_status:{state, node, records: [{id, state, environment, attempt, payload_hash, error?, note?, receipt?}]}
* - records_list:RecordsPage(typesBlueprint.ts):服务端取好的第一页,界面翻页再取
*/
data?: Record<string, any> | null
children?: ViewNode[]
@@ -366,6 +452,12 @@ export interface ViewModel {
tree: ViewNode[]
forms: Record<string, FormSchema>
problems: { component: string; code: string; message: string }[]
/**
* 蓝图的试运行预览(GET /api/blueprints/{id}/preview,N4):对着的是哪次试运行、跑到哪了。应用页上不给。
* 试运行没有应用版本,app.version 为 0。form 是「换一期再试」填的表单(服务端 blueprints/trial.retry_form,按这次试运行
* 对应的草稿:流程类、填报登记是入口的示例表单,看板类是按条件查看的条件表单);没有为 null,只能原样再试一次
*/
trial?: { run_id: string; status: string; status_text: string; form?: FormSchema | null }
}
export interface InstanceRow {
@@ -388,8 +480,12 @@ export interface InstanceRow {
// 待办(§3.7)
// ---------------------------------------------------------------------------
/**
* 待办的种类。review 是个人应用提交审核(docs/design/normal-user-apps.md N7):不挂在运行的中断上,同意不在待办上点——
* 处理人取一份共享副本、走发布单(发布单做完这条自动记为已发布),不发布就退回(decision=reject);payload 见 ReviewTaskPayload
*/
export type TaskKind =
| 'approve' | 'input' | 'edit' | 'tool' | 'code' | 'dual_check' | 'action_confirm' | 'reconcile' | 'signal'
| 'approve' | 'input' | 'edit' | 'tool' | 'code' | 'dual_check' | 'action_confirm' | 'reconcile' | 'signal' | 'review'
export type TaskStatus = 'pending' | 'resolving' | 'resolved' | 'cancelled' | 'expired'
export type TaskPolicy = { kind: 'any' } | { kind: 'all' } | { kind: 'quorum'; m: number }
@@ -452,7 +548,10 @@ export interface Task {
status: TaskStatus
due_at: string | null
escalation_level: number
/** 给人看的上下文:人工节点的 message / context / draft / reports,工具审批的参数,动作确认的预览等(原样来自中断内容) */
/**
* 给人看的上下文:人工节点的 message / context / draft / reports,工具审批的参数,动作确认的预览等(原样来自中断内容);
* 审核个人应用(kind=review)是 ReviewTaskPayload
*/
payload: Record<string, any>
assignments: TaskAssignment[]
/** 当前用户能不能回复这一条 */
@@ -471,6 +570,24 @@ export interface Task {
people?: Record<string, string>
}
/**
* 审核个人应用的待办给处理人看的(服务端 blueprints/personal.review_payload):提交的是哪个蓝图、哪个个人应用、谁提交的、
* 留了什么话,取过的共享副本(审核副本归取它的那位搭建者,owner 是他)。不含个人应用页面上的数:要看数,取副本后在
* 副本上用真数试一次。键总是都在;蓝图被删了时 name、submitted_by 为 null、copies 为空
*/
export interface ReviewTaskPayload {
kind: 'review'
blueprint_id: string | null
/** 提交审核的那个个人应用 */
app_id: string | null
name: string | null
purpose: string
template_id: string | null
submitted_by: string | null
note: string
copies: { id: string; owner: string | null; status: import('./typesBlueprint').BlueprintStatus; app_id: string | null }[]
}
export interface TaskRespond {
decision: 'approve' | 'reject' | 'submit' | 'confirmed' | 'not_applied_resend' | 'not_applied_abandon'
values?: Record<string, any>
@@ -582,11 +699,14 @@ export interface NotifyChannelRow {
// 运行来源(§2.10 X3)与助手查看(§2.9 L2)
// ---------------------------------------------------------------------------
/** 运行来源(服务端 engine/origin.ORIGIN_KINDS,顺序相同)。trial:蓝图的试运行;personal_app:个人应用的刷新(都是探索运行) */
export type OriginKind =
| 'chat' | 'canvas' | 'launcher' | 'schedule' | 'app_entry' | 'app_view' | 'app_backfill' | 'hook' | 'api'
| 'trial' | 'personal_app'
/** 查看的对象。caliber 是已发布口径卡上的指标(蓝图助手复用口径时看,服务端 look/calibers.py) */
export interface LookObject {
kind: 'table' | 'capability' | 'workflow_version'
kind: 'table' | 'capability' | 'workflow_version' | 'caliber'
source?: string
/** 点名了不在这一轮范围里的数据源时为 null,missing 里是点名的表 */
source_id?: string | null
+161 -12
View File
@@ -2,7 +2,7 @@
* 普通用户建应用的接口约定(docs/design/normal-user-apps.md 第三部分):蓝图、场景模板、试运行、发布单、文件、记录。
* 和后端 app/blueprints/spec.py、app/db/models_blueprints.py 一一对应。改这里要同时改后端(骨架阶段冻结)。
*/
import type { AppSpec, LintIssue, ViewModel } from './typesApp'
import type { AppComponent, Disposition, LintIssue, LookEvent, ViewModel } from './typesApp'
// ---------------------------------------------------------------- 蓝图 agentlab.blueprint/1
@@ -87,7 +87,23 @@ export type BlueprintScope = 'personal' | 'shared'
export type BlueprintStatus = 'drafting' | 'trialed' | 'published' | 'personal' | 'in_review'
export type BlueprintSourceKind = 'conversation' | 'template' | 'run' | 'workflow_version'
export interface JointState { status: 'filled' | 'pending' | 'refused'; by: 'template' | 'assistant' | 'user'; note?: string | null }
/** 关节的类型(服务端 blueprints/templates.JOINT_KINDS):sql、metric_expr 交给助手填(生成关节),其余按卡片确定性地填 */
export type JointKind =
| 'sql' | 'metric_expr' | 'fields' | 'assignee' | 'policy' | 'due' | 'on_timeout' | 'threshold' | 'capability' | 'contract'
/**
* 一个关节的状态(服务端 blueprints/store.blueprint_out,只给状态,不给填的值——值在图上看)。by:确定性关节和还没填的
* 生成关节是 template,助手填上的是 assistant。label、kind、group 是模板声明的说法、类型和分组(同一组的关节一起交给
* 助手填,组之间并行);实例化之前存下的关节没有这三项
*/
export interface JointState {
status: 'filled' | 'pending' | 'refused'
by: 'template' | 'assistant' | 'user'
note?: string | null
label?: string
kind?: JointKind
group?: string | null
}
export interface Blueprint {
id: string
@@ -116,8 +132,24 @@ export interface Blueprint {
export type ProblemWho = 'you' | 'assistant' | 'admin'
export interface Plain { title: string; why: string; who: ProblemWho; action: string }
/** 检查问题加上白话(后端 app/plain.with_plain);没登记白话的 plain 为空,照旧显示 message */
export type PlainIssue = LintIssue & { plain?: Plain | null }
/** 发布单的问题出自哪一项预检(服务端 blueprints/publish_plan._preflight) */
export type PlanProblemSource = 'blueprint' | 'plan' | 'workflow' | 'schedule' | 'app' | 'grants'
/**
* 检查问题加上白话(后端 app/plain.with_plain);没登记白话的 plain 为空,照旧显示 message。
*
* 发布单上的问题另带(blueprints/publish_plan._with_who):who 归谁处理(摘要按它分「你来定 / 助手可以修 / 要找管理员」三栏,
* 没登记白话的也有);source 出自哪一项预检;工作流检查带 fix_kind(自动修复的种类:choice 要人选,auto、assist 助手能做);
* 应用检查的 app.upgrade_policy 带 alias(要选处置的那个钉住项)。蓝图检查带 joint(还没填的关节)。
*/
export type PlainIssue = LintIssue & {
plain?: Plain | null
who?: ProblemWho
source?: PlanProblemSource
fix_kind?: 'choice' | 'auto' | 'assist' | null
alias?: string
joint?: string
field?: string | null
}
// ---------------------------------------------------------------- 场景模板
@@ -136,8 +168,32 @@ export interface TemplateInfo {
// ---------------------------------------------------------------- 试运行
export interface TrialStart { run_id: string; blueprint: Blueprint }
/** 试运行解析出来的一页:和应用页同一个视图模型,印章 trial=true */
/**
* POST /api/blueprints/{id}/trial 的回包(服务端 api/blueprints.trial)。inputs 是这次运行实际用的输入(运行的 input):看板类
* 补齐了按「多久更新」算出的统计期,流程类是示例表单按入口映射换成的图输入。「换一期再试」的表单不随回包给,取自按卡片
* 生成的应用骨架(入口的示例表单,看板类是按条件查看的条件表单)
*/
export interface TrialStart {
run_id: string
blueprint: Blueprint
inputs: Record<string, unknown>
}
/** 试运行、预览自己的拒绝码(服务端 blueprints/trial 的 NOT_READY、NO_GRAPH、POLICY、FORM、NO_RUN) */
export type TrialRefusalCode = 'trial_not_ready' | 'trial_no_graph' | 'trial_policy' | 'trial_form' | 'trial_no_run'
/**
* 试运行(POST /api/blueprints/{id}/trial)、按卡片生成(/instantiate)、预览(/preview)被拒的回包(服务端
* blueprints/trial.TrialRefused,api/blueprints 转成 {detail, code, issues?}):
* - 409 trial_not_ready:缺项、待填的关节挡住,issues 逐条列(带白话);
* - 409 trial_no_graph:蓝图还没有能运行的图(没选场景、自由形没导入图);
* - 403 trial_policy:出的图过不了个人应用的约束(auth/chat_policy,同问数据)。个人蓝图一律按它(任何人的,搭建者
* 自己的也一样:试运行是刷新的预演),开了登录的使用者也一样;
* - 422 trial_form:示例表单没通过校验;
* - 404 trial_no_run:预览指的不是这张蓝图的试运行,或者还没试运行过;
* - 别处的拒绝照原样透传 status 和 code:记录表起草被拒(records.*,422)、附件核对没过(files.*,404 / 403 / 422)、
* 发起被拒(engine/launch.LaunchRefused)
*/
export interface TrialRefusal { detail: string; code?: TrialRefusalCode | (string & {}); issues?: PlainIssue[] }
/** 试运行解析出来的一页:和应用页同一个视图模型,印章 trial=true,ViewModel.trial 写对着哪次试运行 */
export type TrialPage = ViewModel
// ---------------------------------------------------------------- 发布单
@@ -154,6 +210,11 @@ export interface PlanStep {
message?: string | null
at?: string | null
}
/**
* 发布单(服务端 blueprints/publish_plan.plan_out)。ok:没有挡路的问题(error 级)、也没停下,能确认执行。actor 是出单的人。
* options 是出单时定下的:first_run(发布后立即跑一次,不给时看板类为真、流程类为假)、dispositions(钉住项升版的处置)、
* spec_hash(出单那一刻卡片内容的指纹,执行时重算,对不上回 409 plan.graph_changed;服务端自己用,界面不读)
*/
export interface PublishPlanRow {
id: string
blueprint_id: string
@@ -164,7 +225,11 @@ export interface PublishPlanRow {
/** 白话摘要:每一步一句 */
summary: { step: PlanStepKind; text: string }[]
problems: PlainIssue[]
options: { first_run?: boolean }
options: { first_run?: boolean; dispositions?: Record<string, Disposition>; spec_hash?: string }
ok: boolean
actor: string | null
created_at: string | null
updated_at: string | null
}
// ---------------------------------------------------------------- 文件、记录
@@ -172,19 +237,103 @@ export interface PublishPlanRow {
/** 上传后拿回的引用,作为表单值提交 */
export interface FileRef { file_id: string; name: string; size: number; sha256: string; type: string }
/**
* 记录表的一行(服务端 records/listing.py)。系统列照 records.SYSTEM_COLUMNS:_seq 只增不减的序号,_run_id 写入它的那次运行,
* _schema_version 写入时表单的版本;_version 是这一行在第几版表里(表单不兼容地改过之后出新一版,列表把各版合在一起列)。
* 更正行的 _submitted_by 沿用原行的提交人(原提交人照样看得见),更正人记在动作记录和审计里。别人提交的行里遮罩列的值已
* 换成「已遮罩」
*/
export interface RecordRow {
_id: string
_seq: number
_submitted_by: string | null
_submitted_at: string
_run_id: string | null
_supersedes: string | null
/** 被更正过(有更新的一行指向它) */
superseded?: boolean
_schema_version: number
_version: number
/** 被更正过(有更新的一行指向它)。默认只列当前有效的行,要了更正历史(history)时才会有为真的 */
superseded: boolean
values: Record<string, unknown>
}
export interface RecordsPage { table: string; version: number; columns: { name: string; label: string; type: string }[]; items: RecordRow[]; mine_only: boolean }
/**
* 一页记录(GET /api/apps/{id}/records、组件 records_list 的数据,服务端 records/listing.page)。mine_only:服务端只给了这个人
* 自己提交的(use 权限,或组件写了 who=mine)。next_cursor 是下一页的游标(「版本:序号」),没有下一页为 null。state:ok 有
* 这张表(items 可能为空);empty 这个应用还没有记录表(table 是请求里写的、version 为 0);preview 按草稿预览,不列真实的
* 记录(apps/resolve._records_list)
*/
export interface RecordsPage {
table: string | null
version: number
columns: { name: string; label: string; type: string }[]
items: RecordRow[]
mine_only: boolean
next_cursor: string | null
state: 'ok' | 'empty' | 'preview'
}
// ---------------------------------------------------------------- 页面编辑
/** 「加一张数据卡片」的候选(GET /api/apps/{id}/candidates) */
export interface AppCandidate { kind: 'metric' | 'report' | 'table' | 'series'; label: string; group: string; component: AppSpec['pages'][number]['body'][number] }
/**
* 「加一张数据卡片」的候选(GET /api/apps/{id}/candidates,服务端 apps/candidates.py):component 可以直接 app_add——绑定的
* 视图一定在这份草稿的 views 里(候选只从草稿里有图的视图列,实例视图不列),id 在草稿里不重名。草稿里已经有一模一样的
* 不再列。group 是出自哪个节点(草稿里不止一个视图时加上来源的说法)
*/
export interface AppCandidate { kind: 'metric' | 'report' | 'table' | 'series'; label: string; group: string; component: AppComponent }
// ---------------------------------------------------------------- 助手流(蓝图对话、填关节)
/**
* 两条流共有的过程事件(服务端 api/copilot_gen.Generation、api/copilot._with_heartbeat):用的哪个模型、心跳(阶段和已用时长)、
* 思考、开场的打算(plan)、收尾的说明(done)、查看(look,同问数据)、自查(check:repairing 交回模型改、error 修不成、
* passed / failed 交付前的结论)、出错(error,这一轮没完成)
*/
export type CopilotStreamStep =
| { op: 'model'; model: string }
| { op: 'heartbeat'; phase: string; elapsed_ms: number }
| { op: 'thinking'; delta: string }
| { op: 'plan'; summary: string }
| { op: 'done'; explanation?: string }
| Omit<LookEvent, never>
| { op: 'check'; status: 'repairing' | 'error' | 'passed' | 'failed'; round?: number; repaired?: number;
issues?: LintIssue[]; message?: string; detail?: string }
| { op: 'error'; message: string; hint?: string | null; detail?: string | null }
/**
* 蓝图对话落库的一轮的 meta(ConversationTurn.meta,服务端 api/copilot_blueprint 的 _close_turn):这一轮查看了什么(looks,
* 同流里的 look 事件)、模型调了几次(calls)、问回来的那一句和候选(asked,没问为空)。之前的轮次只重放这些,改动已经落在
* 卡片上
*/
export interface BlueprintTurnMeta {
looks?: LookEvent[]
calls?: number
asked?: { question: string; options: string[] } | null
}
/**
* 蓝图对话(POST /api/copilot/blueprint-stream,服务端 api/copilot_blueprint.blueprint_stream)的事件:模型提的 bp_* 操作(服务端
* 已经落到它维护的那一份上,来源记 assistant);bp_ask 问回来一句(模型写成通用的 ask 也认),这一轮就此结束;reply 只回答、
* 不改卡片;最后 final 带存好的整份蓝图(以它为准)、这一轮的说明、没采纳的操作(issues,警告级)和问了什么(asked)
*/
export type BlueprintStreamEvent =
| CopilotStreamStep
| { op: 'bp_set' | 'bp_add' | 'bp_remove'; path: string; value?: unknown }
| { op: 'bp_template'; template: { id: string; version: number } | null }
| { op: 'bp_ask' | 'ask'; question: string; options?: string[]; path?: string | null; id?: string }
| { op: 'reply'; text: string }
| { op: 'final'; blueprint: Blueprint; explanation: string; issues: LintIssue[];
asked?: { question: string; options: string[] } }
/**
* 填关节(POST /api/copilot/fill-joints-stream,服务端 api/copilot_blueprint.fill_joints_stream)的事件。不同组并行,组里的过程
* 事件都带 group;group 事件报一组的进展(started 开始、retrying 并行出错退回串行再试、filled 填好、failed 没填上,带没过的
* 检查或原因);fill_joint 是模型填了一个关节。最后 final 带存好的蓝图、各组的结局(以它为准:填的时候卡片又改过的组不算数)
* 和实例化查出的问题(带白话)
*/
export type FillJointsEvent =
| (CopilotStreamStep & { group?: string })
| { op: 'group'; group: string; status: 'started' | 'retrying' | 'filled' | 'failed'; joints?: string[];
issues?: LintIssue[]; message?: string }
| { op: 'fill_joint'; joint: string; value: string; group?: string }
| { op: 'final'; blueprint: Blueprint; problems: PlainIssue[]; group?: undefined;
groups: Record<string, { status: 'filled' | 'failed'; calls: number; refusals: LintIssue[] }> }