diff --git a/e2e/rdm-audit.playwright.ts b/e2e/rdm-audit.playwright.ts index 7b1f21c..f874bb9 100644 --- a/e2e/rdm-audit.playwright.ts +++ b/e2e/rdm-audit.playwright.ts @@ -71,7 +71,7 @@ test.describe.serial('U4 项目追溯审计工作区', () => { await page.getByRole('tab', { name: '资料与文档' }).click() await page.locator('.rdm-audit-tree-node').first().click() const sectionNode = page.locator('.rdm-audit-tree-children .rdm-audit-tree-node') - .filter({ has: page.locator('.rdm-audit-tree-kind', { hasText: 'section' }) }).first() + .filter({ has: page.locator('.rdm-audit-tree-kind', { hasText: '章节' }) }).first() await expect(sectionNode).toBeVisible() await sectionNode.click() await expect(page.locator('.rdm-audit-detail')).toBeVisible() diff --git a/src/components/RdmAuditWorkspace.tsx b/src/components/RdmAuditWorkspace.tsx index 28d877b..2825b52 100644 --- a/src/components/RdmAuditWorkspace.tsx +++ b/src/components/RdmAuditWorkspace.tsx @@ -5,6 +5,15 @@ import { useCallback, useEffect, useRef, useState } from 'react' import { api } from '../api' import { Chip, Collapsible, EmptyState, SectionLabel } from '@ui' import { classifyRdmError } from '../rdmErrors' +import { + describeAuditEvent, describeTreeItem, humanizeKind, humanizeRelation, humanizeState, isTreeItemExpandable, + relationOtherEndpoint, + type AuditEventViewInput, +} from '../rdmAuditPresentation' +import { + collectRecursiveTree, isTreeItemInspectable, mergeTreePage, + type AuditTreeItem, type AuditTreePage, +} from '../rdmAuditTree' import { store, useStore } from '../store' import { exportNeedsDraft } from '../workspaces' import { DocumentRenderWorkspace, saveBase64File } from './DocumentRenderWorkspace' @@ -14,11 +23,11 @@ import { DocumentRenderWorkspace, saveBase64File } from './DocumentRenderWorkspa interface InspectProject { projectId: string; name: string; canAudit: boolean } interface Capabilities { actor: string; projects: InspectProject[]; crossProject: boolean } interface CoverageItem { face: string; reason: string } -interface ListShell { items: T[]; nextCursor?: string; hasMore: boolean; truncated: boolean; coverage?: CoverageItem[] } +interface ListShell { items: T[]; businessAudit?: T[]; nextCursor?: string; hasMore: boolean; truncated: boolean; coverage?: CoverageItem[] } interface SummaryData { projectId: string; counts: Record; watermark: number; lastOpAt: string; coverage?: CoverageItem[] } -interface TreeItem { kind: string; id: string; title: string; state?: string } +type TreeItem = AuditTreeItem interface RelationEntry { layer: string; edgeId?: string; kind?: string; type?: string; state: string; depth?: number; from: any; to: any; conf?: number } -interface EventDTO { seq: number; at: string; op: string; actor: string; source: string; target: { kind: string; id: string }; detail: string; operationId: string; disclosure: string } +interface EventDTO extends AuditEventViewInput {} interface OpGroup { operationId: string; actor: string; at: string; events: EventDTO[] } interface ObjectDetail { kind: string; id: string; title?: string; state?: string; versions?: any[]; formal?: any; labels?: any; batch?: string; ver?: number; relations: RelationEntry[]; recentEvents: EventDTO[]; coverage?: CoverageItem[] } interface HistoryData { projectId: string; watermark: number; atSeq: number; object?: any; formal?: any; formalMissing?: string; countOnlySnapshots?: number; coverage?: CoverageItem[]; empty?: boolean } @@ -33,6 +42,23 @@ const TABS = [ ] as const type TabId = (typeof TABS)[number]['id'] +const OPERATION_FILTERS = [ + ['', '全部操作'], + ['doc.instantiate', '创建文档实例'], + ['section.add', '新增文档章节'], + ['slice.ingest', '新增项目资料'], + ['edge.candidate', '提出追溯候选'], + ['edge.confirm', '确认追溯关系'], + ['change.requested', '提出变更申请'], + ['change.applied', '应用变更'], + ['open-item.add', '登记项目问题'], + ['open-item.close', '关闭项目问题'], + ['rdm.work.observe', '拆解工作来源'], + ['rdm.work.risk', '发现项目风险'], + ['rdm.work.risk.answer', '回答风险澄清'], + ['rdm.structure.decide', '决定结构变更'], +] as const + /** 错误态(增量 2):分类文案(能力缺失/登录失效/查询失败)+ 原始回执折叠供诊断; * 「无可审计项目」由调用处独立空态承担,不走本组件。 */ function RdmErrorState({ raw }: { raw: string }) { @@ -287,14 +313,15 @@ function TreeList({ pid, kind, onOpenDoc }: { pid: string; kind: 'notes' | 'docs const [err, setErr] = useState('') const [selected, setSelected] = useState(null) const [detail, setDetail] = useState(null) - // docs 树是层级结构(rdm.inspect.tree parent= 才返回章节):文档节点 - // 点击展开子章节,不直接查对象详情(doc 不在 inspect.object 支持面)。 - const [children, setChildren] = useState>({}) + const [detailErr, setDetailErr] = useState('') + const [children, setChildren] = useState>({}) const genRef = useRef(0) + const detailGenRef = useRef(0) useEffect(() => { const gen = ++genRef.current - setShell(null); setErr(''); setSelected(null); setDetail(null); setChildren({}) + detailGenRef.current++ + setShell(null); setErr(''); setSelected(null); setDetail(null); setDetailErr(''); setChildren({}) api.rdmCommand>('rdm.inspect.tree', { projectId: pid, kind, cursor: '' }) .then(s => { if (gen === genRef.current) setShell(s) }) .catch(e => { if (gen === genRef.current) setErr(e.message) }) @@ -308,24 +335,42 @@ function TreeList({ pid, kind, onOpenDoc }: { pid: string; kind: 'notes' | 'docs .catch(e => { if (gen === genRef.current) setErr(e.message) }) } - const toggleDoc = (item: TreeItem) => { + const toggleNode = (item: TreeItem) => { if (children[item.id]) { setChildren(prev => { const next = { ...prev }; delete next[item.id]; return next }) return } const gen = genRef.current - api.rdmCommand>('rdm.inspect.tree', { projectId: pid, kind: 'docs', parent: item.id, cursor: '' }) - .then(s => { if (gen === genRef.current) setChildren(prev => ({ ...prev, [item.id]: s.items })) }) + api.rdmCommand>('rdm.inspect.tree', { projectId: pid, kind, parent: item.id, cursor: '' }) + .then(s => { if (gen === genRef.current) setChildren(prev => ({ ...prev, [item.id]: s })) }) + .catch(e => { if (gen === genRef.current) setErr(e.message) }) + } + + const loadMoreChildren = (item: TreeItem) => { + const current = children[item.id] + if (!current?.nextCursor) return + const gen = genRef.current + api.rdmCommand>('rdm.inspect.tree', { + projectId: pid, kind, parent: item.id, cursor: current.nextCursor, + }) + .then(s => { + if (gen !== genRef.current) return + setChildren(prev => ({ ...prev, [item.id]: mergeTreePage(prev[item.id], s) })) + }) .catch(e => { if (gen === genRef.current) setErr(e.message) }) } const selectNode = (item: TreeItem) => { - if (item.kind === 'doc') { toggleDoc(item); return } - setSelected(item); setDetail(null) - const gen = genRef.current + if (isTreeItemExpandable(item)) toggleNode(item) + const detailGen = ++detailGenRef.current + if (!isTreeItemInspectable(item)) { + setSelected(null); setDetail(null); setDetailErr('') + return + } + setSelected(item); setDetail(null); setDetailErr('') api.rdmCommand('rdm.inspect.object', { projectId: pid, kind: item.kind, id: item.id }) - .then(d => { if (gen === genRef.current) setDetail(d) }) - .catch(e => { if (gen === genRef.current) setErr(e.message) }) + .then(d => { if (detailGen === detailGenRef.current) setDetail(d) }) + .catch(e => { if (detailGen === detailGenRef.current) setDetailErr(e.message) }) } if (err) return @@ -335,43 +380,52 @@ function TreeList({ pid, kind, onOpenDoc }: { pid: string; kind: 'notes' | 'docs return (
- {shell.items.map(item => ( -
-
- - {item.kind === 'doc' && ( - - )} -
- {item.kind === 'doc' && children[item.id] && ( -
- {children[item.id].length === 0 &&
无章节
} - {children[item.id].map(sub => ( - - ))} -
- )} -
- ))} + {shell.items.map(item => )} {shell.hasMore && } {shell.truncated &&
已截断(深度或数量上限)
}
{selected && (
对象详情 - {!detail ?
加载中…
: } + {detailErr ? : !detail ?
加载中…
: } +
+ )} +
+ ) +} + +function TreeNodeRow({ item, selectedId, children, onSelect, onLoadMore, onOpenDoc }: { + item: TreeItem + selectedId?: string + children: Record + onSelect: (item: TreeItem) => void + onLoadMore: (item: TreeItem) => void + onOpenDoc: (doc: TreeItem) => void +}) { + const expandable = isTreeItemExpandable(item) + const nestedPage = children[item.id] + const nested = nestedPage?.items + const readable = describeTreeItem(item) + return ( +
+
+ + {item.kind === 'doc' && ( + + )} +
+ {nested && ( +
+ {nested.length === 0 &&
无下级节点
} + {nested.map(child => )} + {nestedPage.hasMore && } + {nestedPage.truncated &&
该节点的下级内容已截断
}
)}
@@ -396,21 +450,17 @@ function TraceTab({ pid }: { pid: string }) { .catch(e => { if (gen === genRef.current) setErr(e.message) }) }, [pid, sel]) - // 未选对象时列出章节供选择。docs 树是层级结构:章节挂在各文档下 - // (parent=),按文档聚合后合并展示。 - const [sections, setSections] = useState([]) + const [treeItems, setTreeItems] = useState([]) + const [pickErr, setPickErr] = useState('') useEffect(() => { if (sel) return let c = false ;(async () => { - const top = await api.rdmCommand>('rdm.inspect.tree', { projectId: pid, kind: 'docs' }) - const secs: TreeItem[] = [] - for (const d of top.items.filter(i => i.kind === 'doc')) { - const sub = await api.rdmCommand>('rdm.inspect.tree', { projectId: pid, kind: 'docs', parent: d.id }) - secs.push(...sub.items.filter(i => i.kind === 'section')) - } - if (!c) setSections(secs) - })().catch(() => {}) + setTreeItems([]); setPickErr('') + const items = await collectRecursiveTree((parent, cursor) => + api.rdmCommand>('rdm.inspect.tree', { projectId: pid, kind: 'docs', parent, cursor })) + if (!c) setTreeItems(items.filter(item => item.kind !== 'doc')) + })().catch(e => { if (!c) setPickErr(e instanceof Error ? e.message : String(e)) }) return () => { c = true } }, [pid, sel]) @@ -418,13 +468,14 @@ function TraceTab({ pid }: { pid: string }) { return (
选择对象查看来源与影响 - {sections.length === 0 ? 暂无章节 : ( + {pickErr ? : treeItems.length === 0 ? 暂无可追溯对象 : (
- {sections.map(s => ( - - ))} + })}
)}
@@ -439,7 +490,7 @@ function TraceTab({ pid }: { pid: string }) {
{sel.title} - {sel.kind}:{sel.id} + {humanizeKind(sel.kind)} · {sel.id}
{err && } {!relations && !err &&
加载中…
} @@ -448,11 +499,11 @@ function TraceTab({ pid }: { pid: string }) {
来源依据({sources.length}) - {sources.length === 0 ?
无来源
: sources.map((r, i) => )} + {sources.length === 0 ?
无来源
: sources.map((r, i) => )}
影响对象({impacts.length}) - {impacts.length === 0 ?
无影响
: impacts.map((r, i) => )} + {impacts.length === 0 ?
无影响
: impacts.map((r, i) => )}
)} @@ -461,14 +512,15 @@ function TraceTab({ pid }: { pid: string }) { ) } -function RelationRow({ r }: { r: RelationEntry }) { - const other = r.from?.id && r.to?.id ? (r.from?.id < r.to?.id ? r.from : r.to) : (r.from || r.to) +function RelationRow({ r, selected }: { r: RelationEntry; selected: { kind: string; id: string } }) { + const other = relationOtherEndpoint(r, selected) + const readable = humanizeRelation(r) return (
- {r.layer} - {r.type || r.kind || '关联'} - {other?.kind}:{other?.id}{other?.ver ? `@${other.ver}` : ''} - {r.state} + {readable.layer} + {readable.type} + {humanizeKind(other?.kind)}“{other?.title || other?.id || '未知对象'}”{other?.ver ? `(版本 ${other.ver})` : ''} + {readable.state}
) } @@ -496,7 +548,8 @@ function TimelineTab({ pid }: { pid: string }) { api.rdmCommand>('rdm.inspect.events', params) .then(s => { if (gen !== genRef.current) return - setItems(prev => replace ? s.items : [...prev, ...s.items]) + const page = replace ? [...(s.businessAudit || []), ...s.items] : s.items + setItems(prev => replace ? page : [...prev, ...page]) setCursor(s.nextCursor || '') setHasMore(s.hasMore) }) @@ -520,8 +573,9 @@ function TimelineTab({ pid }: { pid: string }) {
setFilterActor(e.target.value)} /> - setFilterOp(e.target.value)} /> + @@ -572,27 +626,38 @@ function TimelineTab({ pid }: { pid: string }) { } function OpGroupView({ group }: { group: OpGroup }) { - const [open, setOpen] = useState(false) + const first = group.events[0] ? describeAuditEvent(group.events[0]) : null return (
- - {open && group.events.map(ev => )} + + {first?.subject || group.actor} + {first?.action || '项目操作'} + {new Date(group.at).toLocaleString('zh-CN')} + 包含 {group.events.length} 项记录 + + )}> + {group.events.map(ev => )} +
) } function EventRow({ ev }: { ev: EventDTO }) { + const view = describeAuditEvent(ev) return (
- {new Date(ev.at).toLocaleTimeString('zh-CN')} - {ev.op} - {ev.actor} - {ev.detail && {ev.detail.slice(0, 80)}} - {ev.disclosure !== 'ok' && {ev.disclosure === 'model-candidate' ? '模型候选' : '来源受限'}} +
+ {new Date(ev.at).toLocaleString('zh-CN')} + {view.action} + {view.outcome} +
+
{view.subject}处理了{view.object}
+
+
原因
{view.reason}
+
影响
{view.impact}
+
依据
{view.source}
+
) } @@ -603,8 +668,8 @@ function ObjectDetailView({ detail }: { detail: ObjectDetail }) { return (
{detail.title || detail.id}
-
{detail.kind}:{detail.id}{detail.ver ? `@${detail.ver}` : ''}
- {detail.state &&
状态:{detail.state}
} +
{humanizeKind(detail.kind)} · 对象编号 {detail.id}{detail.ver ? ` · 版本 ${detail.ver}` : ''}
+ {detail.state &&
状态:{humanizeState(detail.state)}
} {detail.labels &&
标签:{detail.labels.stage}{detail.labels.topics?.length ? ` / ${detail.labels.topics.join(', ')}` : ''}
} {detail.versions && detail.versions.length > 0 && (
@@ -624,7 +689,7 @@ function ObjectDetailView({ detail }: { detail: ObjectDetail }) { {detail.relations && detail.relations.length > 0 && (
一跳关系({detail.relations.length}) - {detail.relations.map((r, i) => )} + {detail.relations.map((r, i) => )}
)} {detail.recentEvents && detail.recentEvents.length > 0 && ( diff --git a/src/rdmAuditPresentation.test.ts b/src/rdmAuditPresentation.test.ts new file mode 100644 index 0000000..e359c4d --- /dev/null +++ b/src/rdmAuditPresentation.test.ts @@ -0,0 +1,121 @@ +import { describe, expect, it } from 'vitest' +import { + describeAuditEvent, describeTreeItem, humanizeKind, humanizeRelation, humanizeState, + isTreeItemExpandable, relationOtherEndpoint, +} from './rdmAuditPresentation' + +describe('RDM audit presentation', () => { + it('turns a structured document event into a readable action and impact', () => { + expect(describeAuditEvent({ + seq: 18, + at: '2026-10-15T08:00:00Z', + op: 'doc.instantiate', + actor: 'alice', + source: 'template:dhf-proposal@v2', + target: { kind: 'doc', id: 'doc-1', title: '项目建议书' }, + detail: '{"raw":"must not be shown"}', + operationId: 'op-1', + disclosure: 'ok', + result: 'committed', + impact: '新增 12 个递归节点', + reason: '从已发布模板建立项目实例', + })).toEqual({ + action: '创建文档实例', + subject: 'Alice', + object: '文档“项目建议书”', + outcome: '已生效', + reason: '从已发布模板建立项目实例', + impact: '新增 12 个递归节点', + source: '模板:DHF 项目建议书(版本 v2)', + }) + }) + + it('does not expose unknown operation codes or raw JSON as user-facing text', () => { + const view = describeAuditEvent({ + seq: 19, + at: '2026-10-15T08:01:00Z', + op: 'internal.weird_opcode', + actor: 'user-42', + source: 'host', + target: { kind: 'node', id: 'node-secret' }, + detail: '{"secret":"raw payload"}', + operationId: 'op-2', + disclosure: 'restricted', + }) + expect(view.action).toBe('更新项目内容') + expect(JSON.stringify(view)).not.toContain('internal.weird_opcode') + expect(JSON.stringify(view)).not.toContain('raw payload') + expect(view.outcome).toBe('部分信息受限') + expect(view.object).toBe('节点(node-secret)') + expect(view.source).toBe('系统受信操作记录') + }) + + it('preserves domain provenance and object identity in readable audit rows', () => { + expect(describeAuditEvent({ + seq: 20, + at: '2026-10-15T08:02:00Z', + op: 'edge.candidate', + actor: 'model-runner', + source: 'model', + target: { kind: 'edge', id: 'edg-7' }, + operationId: 'op-3', + disclosure: 'model-candidate', + })).toMatchObject({ + action: '提出追溯关系候选', + object: '追溯边(edg-7)', + source: '模型分析候选', + }) + expect(describeAuditEvent({ + seq: 21, + at: '2026-10-15T08:03:00Z', + op: 'section.add', + actor: 'alice', + source: 'human', + target: { kind: 'section', id: 'sec-2' }, + operationId: 'op-4', + disclosure: 'ok', + }).source).toBe('项目成员操作') + }) + + it('humanizes tree, relationship, and lifecycle vocabulary', () => { + expect(humanizeKind('section')).toBe('章节') + expect(humanizeState('candidate')).toBe('待确认') + expect(humanizeState('retired')).toBe('已停用') + expect(humanizeState('stale')).toBe('待复核') + expect(humanizeRelation({ layer: 'compliance', type: 'verifies', state: 'active' })).toEqual({ + layer: '合规关系', + type: '验证', + state: '已生效', + }) + }) + + it('allows recursive sections to expand when the server reports children', () => { + expect(isTreeItemExpandable({ kind: 'doc', id: 'doc-1', title: '文档', hasChildren: true })).toBe(true) + expect(isTreeItemExpandable({ kind: 'doc', id: 'doc-2', title: '空文档', hasChildren: false })).toBe(false) + expect(isTreeItemExpandable({ kind: 'section', id: 'sec-1', title: '章节', hasChildren: true })).toBe(true) + expect(isTreeItemExpandable({ kind: 'paragraph', id: 'p-1', title: '段落', hasChildren: false })).toBe(false) + }) + + it('gives untitled template nodes a distinct readable name', () => { + expect(describeTreeItem({ + kind: 'paragraph', + id: 'dn-1', + title: '', + order: 6, + templateBlockId: 'dhf.dx.a7850d1881.3.placeholder', + })).toEqual({ kind: '段落', title: '模板内容 7(3)' }) + expect(describeTreeItem({ kind: 'table', id: 'dn-2', title: '', order: 2 })).toEqual({ + kind: '表格', + title: '模板内容 3', + }) + }) + + it('shows the endpoint opposite the selected object in a trace relationship', () => { + const relation = { + from: { kind: 'slice', id: 'slc-6' }, + to: { kind: 'section', id: 'sec-2' }, + } + expect(relationOtherEndpoint(relation, { kind: 'section', id: 'sec-2' })).toEqual(relation.from) + expect(relationOtherEndpoint(relation, { kind: 'slice', id: 'slc-6' })).toEqual(relation.to) + }) +}) diff --git a/src/rdmAuditPresentation.ts b/src/rdmAuditPresentation.ts new file mode 100644 index 0000000..0370386 --- /dev/null +++ b/src/rdmAuditPresentation.ts @@ -0,0 +1,184 @@ +export interface AuditEventViewInput { + seq: number + at: string + op: string + actor: string + source: string + target: { kind: string; id: string; title?: string } + detail?: string + operationId: string + disclosure: string + summary?: string + result?: string + reason?: string + impact?: string +} + +interface AuditEventPresentation { + action: string + subject: string + object: string + outcome: string + reason: string + impact: string + source: string +} + +const KIND_LABELS: Record = { + doc: '文档', section: '章节', node: '节点', note: '知识', slice: '资料切片', spine: '知识主题', edge: '追溯边', + paragraph: '段落', table: '表格', row: '表格行', cell: '表格单元格', + field: '填写字段', attachment: '附件', + requirement: '要求', risk: '风险', proposal: '变更提案', relation: '追溯关系', + template: '模板', project: '项目', conclusion: '结论', issue: '问题', +} + +const STATE_LABELS: Record = { + active: '已生效', candidate: '待确认', pending: '待处理', baselined: '已建立基线', + retired: '已停用', stale: '待复核', + approved: '已批准', rejected: '已拒绝', revoked: '已撤销', superseded: '已被取代', + failed: '失败', committed: '已生效', accepted: '已接受', cancelled: '已取消', + delivered: '已记录', + unknown: '结果未知', restricted: '部分信息受限', +} + +const OP_LABELS: Record = { + 'doc.instantiate': '创建文档实例', + 'section.add': '新增文档章节', + 'section.version': '更新文档内容', + 'section.state': '变更章节状态', + 'section.tombstone': '停用文档章节', + 'slice.ingest': '新增项目资料', + 'slice.retag': '更新资料标签', + 'slice.tombstone': '停用项目资料', + 'spine.add': '新增知识主题', + 'mount.add': '挂接项目资料', + 'mount.move': '移动项目资料', + 'mount.remove': '移除资料挂接', + 'edge.candidate': '提出追溯关系候选', + 'edge.confirm': '确认追溯关系', + 'edge.retire': '停用追溯关系', + 'change.requested': '提出变更申请', + 'change.approved': '批准变更申请', + 'change.applied': '应用变更', + 'open-item.add': '登记项目问题', + 'open-item.close': '关闭项目问题', + 'dictionary.revise': '修订项目字典', + 'req.change': '更新项目要求', +} + +const RELATION_LABELS: Record = { + verifies: '验证', supports: '支持', derives: '派生自', impacts: '影响', + traces: '追溯到', replaces: '取代', conflicts: '存在冲突', references: '引用', +} + +const LAYER_LABELS: Record = { + compliance: '合规关系', knowledge: '知识关系', document: '文档关系', project: '项目关系', +} + +export function humanizeKind(kind: string): string { + return KIND_LABELS[kind] || '项目对象' +} + +export function describeTreeItem(item: { + kind: string + id: string + title?: string + order?: number + templateBlockId?: string +}): { kind: string; title: string } { + const title = item.title?.trim() + if (title) return { kind: humanizeKind(item.kind), title } + + const position = typeof item.order === 'number' ? item.order + 1 : undefined + const parts = (item.templateBlockId || '').split('.').filter(Boolean) + const semantic = new Set(['placeholder', 'example', 'fixed']) + while (parts.length > 0 && semantic.has(parts[parts.length - 1])) parts.pop() + const hint = parts.at(-1) + const numbered = position ? `模板内容 ${position}` : '未命名模板内容' + return { + kind: humanizeKind(item.kind), + title: hint ? `${numbered}(${hint})` : numbered, + } +} + +export function humanizeState(state: string): string { + return STATE_LABELS[state] || '状态已记录' +} + +function humanizeOperation(op: string): string { + if (OP_LABELS[op]) return OP_LABELS[op] + if (op.startsWith('doc.')) return '更新文档内容' + if (op.startsWith('section.')) return '更新文档内容' + if (op.startsWith('slice.') || op.startsWith('spine.') || op.startsWith('mount.') || op.startsWith('knowledge.')) return '更新项目知识' + if (op.startsWith('edge.') || op.startsWith('relation.') || op.startsWith('trace.')) return '更新追溯关系' + if (op.startsWith('change.')) return '处理项目变更' + if (op.startsWith('open-item.')) return '处理项目问题' + if (op.startsWith('risk.')) return '处理项目风险' + if (op.startsWith('proposal.')) return '处理结构变更' + return '更新项目内容' +} + +function humanizeActor(actor: string): string { + if (!actor) return '未知成员' + if (/^[a-z][a-z0-9._-]*$/i.test(actor) && !actor.includes('-') && !actor.includes('_')) { + return actor.charAt(0).toUpperCase() + actor.slice(1) + } + return actor +} + +function humanizeSource(source: string): string { + if (!source) return '当时未记录来源' + const template = /^template:([^@]+)@(.+)$/.exec(source) + if (template) { + const title = template[1] === 'dhf-proposal' ? 'DHF 项目建议书' : template[1] + return `模板:${title}(版本 ${template[2]})` + } + if (source === 'host') return '系统受信操作记录' + if (source === 'human') return '项目成员操作' + if (source === 'rule') return '项目规则推导' + if (source === 'model') return '模型分析候选' + if (source.startsWith('message:')) return '项目对话' + if (source.startsWith('artifact:')) return '项目文件' + return '已登记项目来源' +} + +function humanizeOutcome(input: AuditEventViewInput): string { + if (input.disclosure !== 'ok') return input.disclosure === 'model-candidate' ? '模型候选,尚未确认' : '部分信息受限' + return humanizeState(input.result || 'committed') +} + +export function describeAuditEvent(input: AuditEventViewInput): AuditEventPresentation { + const targetTitle = input.target?.title ? `“${input.target.title}”` : '' + const targetIdentity = targetTitle || (input.target?.id ? `(${input.target.id})` : '') + return { + action: input.summary || humanizeOperation(input.op), + subject: humanizeActor(input.actor), + object: `${humanizeKind(input.target?.kind)}${targetIdentity}`, + outcome: humanizeOutcome(input), + reason: input.reason || '未记录具体原因', + impact: input.impact || '影响范围尚未记录', + source: humanizeSource(input.source), + } +} + +export function humanizeRelation(input: { layer?: string; type?: string; kind?: string; state?: string }) { + const type = input.type || input.kind || '' + return { + layer: LAYER_LABELS[input.layer || ''] || '项目关系', + type: RELATION_LABELS[type] || '关联', + state: humanizeState(input.state || ''), + } +} + +export function relationOtherEndpoint( + relation: { from?: T; to?: T }, + selected: { kind: string; id: string }, +): T | undefined { + if (relation.to?.kind === selected.kind && relation.to.id === selected.id) return relation.from + if (relation.from?.kind === selected.kind && relation.from.id === selected.id) return relation.to + return relation.from || relation.to +} + +export function isTreeItemExpandable(item: { kind: string; hasChildren?: boolean; id?: string; title?: string }): boolean { + return item.kind === 'spine' || item.hasChildren === true +} diff --git a/src/rdmAuditTree.test.ts b/src/rdmAuditTree.test.ts new file mode 100644 index 0000000..235a3cc --- /dev/null +++ b/src/rdmAuditTree.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from 'vitest' +import { collectRecursiveTree, isTreeItemInspectable, mergeTreePage, type AuditTreePage } from './rdmAuditTree' + +describe('RDM audit tree traversal', () => { + it('keeps child cursors and appends later pages', () => { + const first: AuditTreePage = { + items: [{ kind: 'paragraph', id: 'p-1', title: '一' }], + nextCursor: 'next', hasMore: true, truncated: false, + } + const second: AuditTreePage = { + items: [{ kind: 'paragraph', id: 'p-2', title: '二' }], + hasMore: false, truncated: false, + } + expect(mergeTreePage(first, second)).toEqual({ + items: [...first.items, ...second.items], + hasMore: false, + truncated: false, + }) + }) + + it('collects every page and every server-reported depth for trace selection', async () => { + const pages = new Map([ + ['|', { items: [{ kind: 'doc', id: 'doc-1', title: '文档', hasChildren: true }], nextCursor: 'root-2', hasMore: true, truncated: false }], + ['|root-2', { items: [{ kind: 'doc', id: 'doc-2', title: '文档二', hasChildren: false }], hasMore: false, truncated: false }], + ['doc-1|', { items: [{ kind: 'section', id: 'dn-sec', title: '模板章', templateBlockId: 'tpl.sec', hasChildren: true }], nextCursor: 'child-2', hasMore: true, truncated: false }], + ['doc-1|child-2', { items: [{ kind: 'section', id: 'sec-2', title: '正文', hasChildren: false }], hasMore: false, truncated: false }], + ['dn-sec|', { items: [{ kind: 'paragraph', id: 'p-deep', title: '深层内容', hasChildren: false }], hasMore: false, truncated: false }], + ]) + const items = await collectRecursiveTree(async (parent, cursor) => { + const page = pages.get(`${parent}|${cursor}`) + if (!page) throw new Error(`unexpected page ${parent}|${cursor}`) + return page + }) + expect(items.map(item => item.id)).toEqual(['doc-1', 'doc-2', 'dn-sec', 'sec-2', 'p-deep']) + }) + + it('only requests object details for legacy sections supported by the server', () => { + expect(isTreeItemInspectable({ kind: 'section', id: 'sec-2', title: '正文', templateBlockId: '' })).toBe(true) + expect(isTreeItemInspectable({ kind: 'section', id: 'dn-sec', title: '模板章', templateBlockId: 'tpl.sec' })).toBe(false) + expect(isTreeItemInspectable({ kind: 'paragraph', id: 'p-1', title: '内容' })).toBe(false) + }) +}) diff --git a/src/rdmAuditTree.ts b/src/rdmAuditTree.ts new file mode 100644 index 0000000..a0da08c --- /dev/null +++ b/src/rdmAuditTree.ts @@ -0,0 +1,59 @@ +export interface AuditTreeItem { + kind: string + id: string + title: string + state?: string + hasChildren?: boolean + order?: number + templateBlockId?: string +} + +export interface AuditTreePage { + items: AuditTreeItem[] + nextCursor?: string + hasMore: boolean + truncated: boolean +} + +type AuditTreePageFetcher = (parent: string, cursor: string) => Promise + +export function mergeTreePage(current: AuditTreePage, next: AuditTreePage): AuditTreePage { + return { ...next, items: [...current.items, ...next.items] } +} + +async function collectParentPages(fetchPage: AuditTreePageFetcher, parent: string): Promise { + const items: AuditTreeItem[] = [] + const seenCursors = new Set() + let cursor = '' + for (let pageNo = 0; pageNo < 100; pageNo++) { + if (seenCursors.has(cursor)) throw new Error('树分页游标重复,已停止加载') + seenCursors.add(cursor) + const page = await fetchPage(parent, cursor) + items.push(...page.items) + if (!page.hasMore) return items + if (!page.nextCursor) throw new Error('树分页缺少后续游标') + cursor = page.nextCursor + } + throw new Error('树分页超过安全上限') +} + +export async function collectRecursiveTree(fetchPage: AuditTreePageFetcher): Promise { + const roots = await collectParentPages(fetchPage, '') + const out = [...roots] + const queue = roots.filter(item => item.hasChildren === true) + const seenParents = new Set() + while (queue.length > 0) { + const parent = queue.shift()! + if (seenParents.has(parent.id)) continue + seenParents.add(parent.id) + const children = await collectParentPages(fetchPage, parent.id) + out.push(...children) + if (out.length > 5000) throw new Error('树节点超过安全上限') + queue.push(...children.filter(item => item.hasChildren === true)) + } + return out +} + +export function isTreeItemInspectable(item: AuditTreeItem): boolean { + return item.kind === 'section' && !item.templateBlockId && !item.id.startsWith('dn-') +} diff --git a/src/styles.css b/src/styles.css index 4961fc8..2998d40 100644 --- a/src/styles.css +++ b/src/styles.css @@ -625,12 +625,17 @@ button { font-family: inherit; font-size: inherit; color: inherit; } .rdm-audit-opgroup-head { display: flex; align-items: center; gap: 8px; width: 100%; padding: 7px 10px; background: var(--bg-panel); border: none; cursor: pointer; font-size: var(--fs-ui-sm); color: var(--text-dim); text-align: left; } .rdm-audit-opgroup-head:hover { background: var(--bg-hover); } .rdm-audit-opgroup-actor { font-weight: 550; color: var(--text); } +.rdm-audit-opgroup-action { color: var(--text-dim); } .rdm-audit-opgroup-time { font-size: var(--fs-ui-xs); color: var(--text-faint); } -.rdm-audit-event { display: flex; align-items: center; gap: 8px; padding: 4px 10px; font-size: var(--fs-ui-sm); border-top: 1px solid var(--border-soft); } -.rdm-audit-event-time { font-size: var(--fs-ui-xs); color: var(--text-faint); min-width: 5em; } -.rdm-audit-event-op { font-family: var(--mono); font-size: var(--fs-ui-xs); color: var(--accent-text); min-width: 8em; } -.rdm-audit-event-actor { color: var(--text-dim); min-width: 4em; } -.rdm-audit-event-detail { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text-dim); } +.rdm-audit-event { display: flex; flex-direction: column; gap: 8px; padding: 10px 12px; font-size: var(--fs-ui-sm); border-top: 1px solid var(--border-soft); } +.rdm-audit-event-head { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; } +.rdm-audit-event-time { font-size: var(--fs-ui-xs); color: var(--text-dim); } +.rdm-audit-event-action { color: var(--text); } +.rdm-audit-event-summary { color: var(--text); } +.rdm-audit-event-fields { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; margin: 0; } +.rdm-audit-event-fields > div { min-width: 0; padding: 8px; background: var(--bg-raised); border-radius: var(--radius-sm); } +.rdm-audit-event-fields dt { color: var(--text-dim); font-size: var(--fs-ui-xs); } +.rdm-audit-event-fields dd { margin: 3px 0 0; color: var(--text); overflow-wrap: anywhere; } .rdm-audit-coverage { margin-top: 12px; } .rdm-audit-export { margin-top: 16px; display: flex; flex-direction: column; gap: 8px; } .rdm-audit-export-row { display: flex; align-items: flex-end; gap: 8px; flex-wrap: wrap; } @@ -864,3 +869,7 @@ button.cockpit-tree-more { cursor: pointer; text-decoration: underline; } .cockpit-panel-label { color: var(--text); } .cockpit-panel-conflict { flex-direction: column; } .cockpit-conflict-side { color: var(--text); } +@media (max-width: 760px) { + .rdm-audit-event-fields { grid-template-columns: 1fr; } + .rdm-audit-trace-cols { grid-template-columns: 1fr; } +}