feat: 知识治理平台(含已验证发布/回滚契约)
全栈知识治理平台首次入库(P1-P10 + 发布链路模拟验证闭环): - 治理核心:源目录/变更集/人工审核/发布批次/发布执行(fail-closed 闸口) - 测试通道:WeKnora 测试 KB 上传/轮询/验收;poll 完成时写入 parser_generation/index_generation,修复 manual/seed 路径发布闸口永久拦截 - 发布适配器 v071(本地 source=测试角色 / 云端 target=生产角色 模拟验证通过): * ES 导出/导入 mapping 自适应(.keyword 子字段、可选 tenant_id) * OSS locator 支持嵌套 scheme;chunks.seq_id 由目标序列分配 * bundle 归档同身份重试原子替换;verifier 按 bundle chunk_type 计数 * 回滚 job payload 支持 prior_execution_id(strict 解码) - 三通道发布+回滚演练实测:publish 4/4 verified,检索命中, rollback 4/4 rolled_back,目标端 PG is_enabled=false、ES is_enabled=false - 前端 A·Data-console 风格全站统一,120 用例通过 - 门禁:go vet / go test 全包通过,gofmt 干净
This commit is contained in:
@@ -0,0 +1,483 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import App, { JobDashboard, KnowledgeInventory, ModulePage, ReleaseManagement, SourceConnections, WorkspaceShell, reviewGateLabel } from './App'
|
||||
import type { SourceAssetPage } from './assets'
|
||||
import type { Job } from './jobs'
|
||||
import type { ReleaseBatchDetail, ReleaseBatchPage, ReleaseExecutionDetail, ReleaseExecutionPage, ReleasePlan, ReviewCandidatePage } from './reviewRelease'
|
||||
import type { SourceConnectionPage, SourceScanDetail, SourceScanPage } from './sourceConnections'
|
||||
|
||||
const baseJob: Job = {
|
||||
id: 'job-1',
|
||||
type: 'demo',
|
||||
payload: {},
|
||||
state: 'pending',
|
||||
priority: 0,
|
||||
available_at: '2026-09-03T13:00:00Z',
|
||||
attempt: 0,
|
||||
max_attempts: 5,
|
||||
idempotency_key: 'demo:1',
|
||||
created_at: '2026-09-03T13:00:00Z',
|
||||
updated_at: '2026-09-03T13:00:00Z',
|
||||
}
|
||||
|
||||
describe('WorkspaceShell', () => {
|
||||
it('renders the approved modules in the left navigation', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<WorkspaceShell
|
||||
workspace={{ openTabs: ['dashboard'], activeTab: 'dashboard' }}
|
||||
onOpen={vi.fn()}
|
||||
onClose={vi.fn()}
|
||||
>
|
||||
<div>工作区内容</div>
|
||||
</WorkspaceShell>,
|
||||
)
|
||||
|
||||
expect(html).toContain('aria-label="功能导航"')
|
||||
for (const label of ['来源与目录', '解析监控', '发布管理', '系统设置']) {
|
||||
expect(html).toContain(label)
|
||||
}
|
||||
expect(html).not.toContain('来源链接')
|
||||
expect(html).not.toContain('待处理文件')
|
||||
expect(html).toContain('本地治理环境')
|
||||
expect(html).not.toContain('P2 本地治理环境')
|
||||
})
|
||||
|
||||
it('renders open tabs and marks the active tab', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<WorkspaceShell
|
||||
workspace={{ openTabs: ['dashboard', 'tasks', 'releases'], activeTab: 'tasks' }}
|
||||
onOpen={vi.fn()}
|
||||
onClose={vi.fn()}
|
||||
>
|
||||
<div>工作区内容</div>
|
||||
</WorkspaceShell>,
|
||||
)
|
||||
|
||||
expect(html).toContain('aria-label="已打开页面"')
|
||||
expect(html).toContain('来源与目录')
|
||||
expect(html).toContain('解析监控')
|
||||
expect(html).toContain('发布管理')
|
||||
expect(html).toContain('aria-current="page"')
|
||||
})
|
||||
|
||||
it('offers close controls only for unpinned tabs', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<WorkspaceShell
|
||||
workspace={{ openTabs: ['dashboard', 'tasks'], activeTab: 'tasks' }}
|
||||
onOpen={vi.fn()}
|
||||
onClose={vi.fn()}
|
||||
>
|
||||
<div>工作区内容</div>
|
||||
</WorkspaceShell>,
|
||||
)
|
||||
|
||||
expect(html).toContain('aria-label="关闭解析监控标签"')
|
||||
expect(html).not.toContain('aria-label="关闭来源与目录标签"')
|
||||
})
|
||||
|
||||
it('renders a collapsed mobile navigation control', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<WorkspaceShell
|
||||
workspace={{ openTabs: ['dashboard'], activeTab: 'dashboard' }}
|
||||
onOpen={vi.fn()}
|
||||
onClose={vi.fn()}
|
||||
>
|
||||
<div>工作区内容</div>
|
||||
</WorkspaceShell>,
|
||||
)
|
||||
|
||||
expect(html).toContain('aria-label="切换功能导航"')
|
||||
expect(html).toContain('aria-expanded="false"')
|
||||
})
|
||||
})
|
||||
|
||||
describe('App', () => {
|
||||
it('renders the dashboard inside the multi-tab workspace by default', () => {
|
||||
const html = renderToStaticMarkup(<App />)
|
||||
|
||||
expect(html).toContain('aria-label="功能导航"')
|
||||
expect(html).toContain('aria-label="已打开页面"')
|
||||
expect(html).toContain('<h1>来源与目录</h1>')
|
||||
expect(html).not.toContain('最近任务')
|
||||
})
|
||||
})
|
||||
|
||||
describe('ModulePage', () => {
|
||||
it('renders the governance overview for the dashboard module', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ModulePage
|
||||
moduleId="dashboard"
|
||||
jobs={[baseJob, { ...baseJob, id: 'job-2', state: 'completed' }]}
|
||||
loading={false}
|
||||
error={null}
|
||||
onRefresh={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(html).toContain('治理工作台')
|
||||
expect(html).toContain('P2 · 知识治理总览')
|
||||
expect(html).toContain('PP历史来源清单已接管')
|
||||
expect(html).toContain('本地测试WeKnora已连接')
|
||||
expect(html).toContain('生产WeKnora仍未连接')
|
||||
expect(html).not.toContain('尚未连接测试或生产WeKnora')
|
||||
expect(html).toContain('任务概览')
|
||||
expect(html).toContain('Release Worker 默认关闭')
|
||||
expect(html).toContain('最近任务')
|
||||
expect(html).toContain('job-2')
|
||||
})
|
||||
|
||||
it('renders the test publication table for the tasks module', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ModulePage
|
||||
moduleId="tasks"
|
||||
jobs={[]}
|
||||
loading={false}
|
||||
error={null}
|
||||
onRefresh={vi.fn()}
|
||||
publicationPage={{
|
||||
items: [{
|
||||
id: 'pub-1', title: 'Safe title', ingest_state: 'failed', processing_state: 'failed',
|
||||
retrieval_state: 'unpublished', target_scope: 'internal', change_set_id: 'cs-1', change_type: 'added', can_start: false,
|
||||
retry_count: 2, last_error: 'remote_parse_failed',
|
||||
can_retry: true, updated_at: '2026-09-04T05:00:00Z',
|
||||
}],
|
||||
total: 1,
|
||||
limit: 50,
|
||||
offset: 0,
|
||||
}}
|
||||
publicationLoading={false}
|
||||
publicationError={null}
|
||||
publicationState=""
|
||||
onPublicationStateChange={vi.fn()}
|
||||
onPublicationPageChange={vi.fn()}
|
||||
onPublicationRefresh={vi.fn()}
|
||||
onRetry={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(html).toContain('<h1>解析监控</h1>')
|
||||
expect(html).toContain('总体概览')
|
||||
expect(html).toContain('失败或停滞')
|
||||
expect(html).toContain('pub-1')
|
||||
expect(html).toContain('remote_parse_failed')
|
||||
expect(html).toContain('重试')
|
||||
})
|
||||
|
||||
it('renders the real inventory for the knowledge module', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ModulePage
|
||||
moduleId="knowledge"
|
||||
jobs={[]}
|
||||
loading={false}
|
||||
error={null}
|
||||
onRefresh={vi.fn()}
|
||||
assetPage={{ items: [], summary: { total: 613, completed: 530, content_alias: 29, over_limit: 54 }, limit: 50, offset: 0 }}
|
||||
assetLoading={false}
|
||||
assetError={null}
|
||||
assetState=""
|
||||
onAssetStateChange={vi.fn()}
|
||||
onAssetPageChange={vi.fn()}
|
||||
onAssetRefresh={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(html).toContain('统一治理清单')
|
||||
expect(html).toContain('613')
|
||||
expect(html).not.toContain('功能将在后续阶段接入')
|
||||
})
|
||||
|
||||
it('renders the real source connection workbench', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<ModulePage
|
||||
moduleId="sources"
|
||||
jobs={[]}
|
||||
loading={false}
|
||||
error={null}
|
||||
onRefresh={vi.fn()}
|
||||
connectionPage={{
|
||||
items: [
|
||||
{
|
||||
id: 'conn-pp', source_type: 'pp', name: 'PP历史公开知识', enabled: false,
|
||||
schedule_configured: false, health_status: 'healthy', item_count: 613, updated_at: '2026-09-06T01:00:00Z',
|
||||
last_scan: {
|
||||
id: 'scan-1', state: 'completed', observed_items: 613, unchanged_items: 559,
|
||||
added_items: 0, updated_items: 0, over_limit_items: 54, missing_items: 0,
|
||||
planned_uploads: 0, error_code: '', created_at: '2026-09-06T00:59:00Z', completed_at: '2026-09-06T01:00:00Z',
|
||||
},
|
||||
},
|
||||
{ id: 'conn-alist', source_type: 'alist', name: 'AList只读源', enabled: true, schedule_configured: true, health_status: 'healthy', item_count: 42, updated_at: '2026-09-06T01:00:00Z' },
|
||||
],
|
||||
summary: { total: 2, enabled: 1, disabled: 1, healthy: 1, degraded: 0, unhealthy: 0, unknown: 1 },
|
||||
}}
|
||||
connectionLoading={false}
|
||||
connectionError={null}
|
||||
onConnectionRefresh={vi.fn()}
|
||||
scanningConnectionId={null}
|
||||
onTriggerSourceScan={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(html).toContain('<h1>来源连接</h1>')
|
||||
expect(html).not.toContain('<code>conn-pp</code>')
|
||||
for (const text of ['来源连接', 'PP历史公开知识', 'AList只读源', '613', '已配置', '健康', '最近扫描', '未变化 559', '超过上限 54', '检查快照变化']) {
|
||||
expect(html).toContain(text)
|
||||
}
|
||||
expect(html).toContain('class="source-connections-table"')
|
||||
expect(html).not.toContain('将在后续阶段接入')
|
||||
})
|
||||
})
|
||||
|
||||
describe('KnowledgeInventory', () => {
|
||||
it('renders real source summary and safe paginated asset fields', () => {
|
||||
const page: SourceAssetPage = {
|
||||
items: [{
|
||||
id: 'si-safe', source_type: 'pp', connection_name: 'PP历史公开知识', size_bytes: 52428801,
|
||||
visibility: 'external', source_change: 'unchanged', content_state: 'over_limit', legacy_status: 'over_limit',
|
||||
has_publication: false, processing_state: '', retrieval_state: '', updated_at: '2026-09-04T00:00:00Z',
|
||||
}, {
|
||||
id: 'si-manual', source_type: 'manual' as never, connection_name: '本地验收', size_bytes: 128,
|
||||
visibility: 'internal', source_change: 'added', content_state: 'verified', legacy_status: '',
|
||||
has_publication: true, processing_state: 'pending', retrieval_state: 'unpublished', updated_at: '2026-09-05T00:00:00Z',
|
||||
}],
|
||||
summary: { total: 613, completed: 530, content_alias: 29, over_limit: 54 },
|
||||
limit: 50,
|
||||
offset: 0,
|
||||
}
|
||||
const html = renderToStaticMarkup(
|
||||
<KnowledgeInventory page={page} loading={false} error={null} state="" onStateChange={vi.fn()} onPageChange={vi.fn()} onRefresh={vi.fn()} />,
|
||||
)
|
||||
|
||||
for (const text of ['知识资产', '613', '530', '29', '54', 'PP', '手工验收', '50.0 MiB', '超过旧同步上限']) {
|
||||
expect(html).toContain(text)
|
||||
}
|
||||
expect(html).toContain('统一来源清单')
|
||||
expect(html).not.toContain('当前展示PP历史公开来源')
|
||||
})
|
||||
})
|
||||
|
||||
describe('SourceConnections scan workbench', () => {
|
||||
it('renders scan history and selected safe change records', () => {
|
||||
const now = '2026-09-06T06:00:00Z'
|
||||
const page: SourceConnectionPage = {
|
||||
items: [{ id: 'conn-pp', source_type: 'pp', name: 'PP历史公开知识', enabled: false, schedule_configured: false, health_status: 'healthy', item_count: 613, updated_at: now }],
|
||||
summary: { total: 1, enabled: 0, disabled: 1, healthy: 1, degraded: 0, unhealthy: 0, unknown: 0 },
|
||||
}
|
||||
const scanPage: SourceScanPage = {
|
||||
items: [{ id: 'scan-1', state: 'completed', observed_items: 613, unchanged_items: 558, added_items: 0, updated_items: 1, over_limit_items: 54, missing_items: 0, planned_uploads: 1, error_code: '', created_at: now, completed_at: now }],
|
||||
total: 1, limit: 20, offset: 0,
|
||||
}
|
||||
const detail: SourceScanDetail = {
|
||||
...scanPage.items[0], changes: [{ id: 'chg-1', source_item_id: 'si-safe', change_type: 'updated', observed_size_bytes: 2048, created_at: now }],
|
||||
}
|
||||
const html = renderToStaticMarkup(<SourceConnections
|
||||
page={page} loading={false} error={null} scanningConnectionId={null}
|
||||
scanPage={scanPage} scanDetail={detail} scanLoading={false} scanError={null}
|
||||
selectedScanId="scan-1" onRefresh={vi.fn()} onTriggerScan={vi.fn()} onSelectScan={vi.fn()}
|
||||
/>)
|
||||
for (const text of ['扫描历史与变化记录', 'scan-1', '已选择', '变化记录', '内容更新', 'si-safe', '2.0 KiB']) {
|
||||
expect(html).toContain(text)
|
||||
}
|
||||
expect(html).not.toContain('stable_external_id')
|
||||
expect(html).not.toContain('observed_revision')
|
||||
})
|
||||
|
||||
it('states explicitly when a selected scan has no changes', () => {
|
||||
const now = '2026-09-06T06:00:00Z'
|
||||
const scan = { id: 'scan-1', state: 'completed' as const, observed_items: 613, unchanged_items: 559, added_items: 0, updated_items: 0, over_limit_items: 54, missing_items: 0, planned_uploads: 0, error_code: '', created_at: now, completed_at: now }
|
||||
const html = renderToStaticMarkup(<SourceConnections
|
||||
page={{ items: [], summary: { total: 0, enabled: 0, disabled: 0, healthy: 0, degraded: 0, unhealthy: 0, unknown: 0 } }}
|
||||
loading={false} error={null} scanningConnectionId={null}
|
||||
scanPage={{ items: [scan], total: 1, limit: 20, offset: 0 }} scanDetail={{ ...scan, changes: [] }} scanLoading={false} scanError={null}
|
||||
selectedScanId="scan-1" onRefresh={vi.fn()} onTriggerScan={vi.fn()} onSelectScan={vi.fn()}
|
||||
/>)
|
||||
expect(html).toContain('本次扫描未发现新增、更新或不可用变化')
|
||||
})
|
||||
})
|
||||
|
||||
describe('JobDashboard', () => {
|
||||
it('renders summary counts and task states', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<JobDashboard
|
||||
jobs={[
|
||||
baseJob,
|
||||
{ ...baseJob, id: 'job-2', state: 'running', attempt: 1 },
|
||||
{ ...baseJob, id: 'job-3', state: 'completed', attempt: 1 },
|
||||
]}
|
||||
loading={false}
|
||||
error={null}
|
||||
onRefresh={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(html).toContain('同步任务')
|
||||
expect(html).toContain('任务总数')
|
||||
expect(html).toContain('>3<')
|
||||
expect(html).toContain('运行中')
|
||||
expect(html).toContain('已完成')
|
||||
expect(html).toContain('job-2')
|
||||
})
|
||||
})
|
||||
|
||||
describe('ReleaseManagement', () => {
|
||||
it('renders human review, draft and seal gates without implying production release', () => {
|
||||
const now = '2026-09-06T10:00:00Z'
|
||||
const priorNow = '2026-09-06T09:00:00Z'
|
||||
const reviewPage: ReviewCandidatePage = {
|
||||
items: [{
|
||||
publication_id: 'tp-safe', title: 'Synthetic', source_type: 'manual', current_visibility: 'internal',
|
||||
knowledge_exists: 'passed', chunks_present: 'passed', retrieval_hit: 'manual_required',
|
||||
gate_status: 'ready', gate_code: 'ready', review_state: 'pending', decided_visibility: '', decision_code: '',
|
||||
reviewer_ref: '', reviewed_at: null, updated_at: now,
|
||||
}], total: 1, limit: 20, offset: 0,
|
||||
}
|
||||
const batchPage: ReleaseBatchPage = {
|
||||
items: [{ id: 'rb-safe', name: 'Synthetic batch', state: 'draft', policy_version: 'release-gate-v1', created_by: 'engineer-1', sealed_by: '', item_count: 1, created_at: now, sealed_at: null }],
|
||||
total: 1, limit: 20, offset: 0,
|
||||
}
|
||||
const batchDetail: ReleaseBatchDetail = { ...batchPage.items[0], items: [{ publication_id: 'tp-safe', title: 'Synthetic', decided_visibility: 'internal', action: 'delete' }] }
|
||||
const executionPage: ReleaseExecutionPage = {
|
||||
items: [{ id: 'rx-auto', release_batch_id: 'rb-safe', operation: 'rollback', prior_execution_id: 'rx-safe', state: 'running', target_environment: 'production', authorized_by: 'system:auto-rollback', job_id: 'job-auto', item_count: 1, batch_size: 50, current_batch: 1, total_batches: 1, completed_item_count: 0, failed_item_count: 0, error_code: '', created_at: now, started_at: now, completed_at: null }, { id: 'rx-safe', release_batch_id: 'rb-safe', operation: 'publish', prior_execution_id: '', state: 'failed', target_environment: 'production', authorized_by: 'owner', job_id: 'job-safe', item_count: 2, batch_size: 50, current_batch: 1, total_batches: 1, completed_item_count: 1, failed_item_count: 1, error_code: 'release_item_failed', created_at: priorNow, started_at: priorNow, completed_at: priorNow }],
|
||||
total: 2, limit: 20, offset: 0,
|
||||
}
|
||||
const executionDetail: ReleaseExecutionDetail = { ...executionPage.items[0], items: [{ publication_id: 'tp-safe', title: 'Synthetic', action: 'delete', state: 'verified', previous_production_revision: 'prod-v0', production_revision: 'absent', error_code: '', created_at: now, completed_at: now }, { publication_id: 'tp-restored', title: 'Restored', action: 'delete', state: 'rolled_back', previous_production_revision: 'prod-v0', production_revision: 'prod-v0', error_code: '', created_at: now, completed_at: now }] }
|
||||
const releasePlan: ReleasePlan = { items: [{ publication_id: 'tp-safe', title: 'B.pdf', target_scope: 'external', action: 'add', test_state: 'ready', production_state: 'absent', can_release: true, blocker: '' }, { publication_id: 'tp-delete', title: 'C.pdf', target_scope: 'internal', action: 'delete', test_state: 'not_required', production_state: 'present', can_release: true, blocker: '' }, { publication_id: '', title: 'D.pdf', target_scope: 'internal', action: 'blocked', test_state: 'ready', production_state: 'present', can_release: false, blocker: 'source_unavailable' }], summary: { add: 1, update: 0, delete: 1, blocked: 1, unchanged: 11284 } }
|
||||
const html = renderToStaticMarkup(<ReleaseManagement
|
||||
reviewPage={reviewPage} reviewLoading={false} reviewError={null} reviewingId={null}
|
||||
batchPage={batchPage} batchDetail={batchDetail} batchLoading={false} batchError={null} mutatingBatchId={null}
|
||||
onReview={vi.fn()} onReviewRefresh={vi.fn()} onCreateBatch={vi.fn()} onSealBatch={vi.fn()} onSelectBatch={vi.fn()} onBatchRefresh={vi.fn()}
|
||||
releaseCapabilities={{ production_release_requests_enabled: true, production_backup_restore_verified: false }} executionPage={executionPage} executionDetail={executionDetail} executionLoading={false} executionError={null} onSelectExecution={vi.fn()} onExecutionRefresh={vi.fn()}
|
||||
releasePlan={releasePlan}
|
||||
selectedDeleteIDs={['tp-delete']} onToggleDelete={vi.fn()}
|
||||
/>)
|
||||
for (const text of ['来源与目录 → 测试知识库 → 生产知识库','自动发布计划','新增 1','更新 0','删除 1','未变化 11284','B.pdf','C.pdf','D.pdf','将从生产检索中移除','我确认所选删除项会停止生产检索','已选择删除:1(待确认)','已选 1 项(删除待确认)','为什么按钮不能点:请先填写操作人姓名或工号;请确认所选删除项会停止生产检索;至少 1 项动作通过确认;请填写批次名称','至少 1 项动作通过确认','来源当前不可用,保留生产知识','正在执行自动回滚','批次 1 / 1','每批最多 50 项','Snapshot #20260906-090000Z','审核要发布的知识', '需人工确认', '批准', '驳回', '创建草稿批次', '锁定清单(不会上线)', 'Synthetic batch', '删除生产知识', '已从生产检索中移除', '已恢复生产知识', '仍可检查调整', 'Release Worker保持关闭', '锁定清单 ≠ 上线', '生产确认、发布验证与回滚', '生产操作权限:已阻断', '生产请求门禁已开启', '快照恢复验证未通过', '生产发布已阻断']) {
|
||||
expect(html).toContain(text)
|
||||
}
|
||||
for (const text of [
|
||||
'从检查到发布,只走这 8 步',
|
||||
'1. 查看来源变化',
|
||||
'2. 确认测试结果',
|
||||
'3. 审核发布内容',
|
||||
'4. 创建发布批次',
|
||||
'5. 锁定发布清单',
|
||||
'6. 生产负责人确认',
|
||||
'7. 发布并验证',
|
||||
'8. 必要时回滚',
|
||||
'当前在第 3 步,共 8 步',
|
||||
'现在要做:审核 1 项知识',
|
||||
'还有 1 项等待审核;已批准文件可先创建批次',
|
||||
'完成本步的 4 件事',
|
||||
'填写操作人姓名或工号',
|
||||
'只审核本次准备发布的文件',
|
||||
'勾选要发布的已批准知识',
|
||||
'填写批次名称并创建草稿',
|
||||
'现在先做:填写操作人姓名或工号,逐条选择“批准”或“驳回”',
|
||||
'完成后进入:第 4 步,创建发布批次',
|
||||
'为什么按钮不能点:请先填写操作人姓名或工号',
|
||||
'如何决定批准或驳回',
|
||||
'可以批准:基础测试通过,你已确认搜索结果相关,而且发布范围正确',
|
||||
'应该驳回:内容错误、过期、敏感、搜索结果不相关,或者你无法确认',
|
||||
'创建批次还需要',
|
||||
'确认所选发布动作',
|
||||
'查看审核与发布说明',
|
||||
'至少 1 项动作通过确认',
|
||||
'填写批次名称',
|
||||
'普通业务操作,不会影响生产',
|
||||
'生产危险操作',
|
||||
]) {
|
||||
expect(html).toContain(text)
|
||||
}
|
||||
expect(html).not.toContain('>授权生产发布</button>')
|
||||
expect(html).not.toContain('knowledge_id')
|
||||
expect(html).not.toContain('acceptance_run_id')
|
||||
expect(html).toContain('aria-label="选择删除C.pdf"')
|
||||
expect(html).toContain('筛选 3 / 全部 3')
|
||||
expect(html).toContain('aria-label="确认删除生产知识"')
|
||||
expect(html).toContain('class="plan-delete"')
|
||||
expect(html).toContain('<span class="unmet">至少 1 项动作通过确认</span>')
|
||||
expect(reviewGateLabel({ review_state: 'approved', gate_status: 'ready' })).toBe('测试已通过')
|
||||
expect(reviewGateLabel({ review_state: 'pending', gate_status: 'ready' })).toBe('可以审核')
|
||||
for (const technicalValue of ['tp-safe', 'rb-safe', 'rx-safe', 'job-safe', 'release-gate-v1', 'prod-v0', 'prod-v1', '>verified<']) {
|
||||
expect(html).not.toContain(technicalValue)
|
||||
}
|
||||
expect(html).not.toContain('工程师标识')
|
||||
})
|
||||
})
|
||||
|
||||
describe('release plan pagination (R3)', () => {
|
||||
const baseProps = {
|
||||
reviewPage: { items: [], total: 0, limit: 20, offset: 0 } as any,
|
||||
reviewLoading: false, reviewError: null, reviewingId: null,
|
||||
batchPage: { items: [], total: 0, limit: 20, offset: 0 } as any,
|
||||
batchDetail: null, batchLoading: false, batchError: null, mutatingBatchId: null,
|
||||
onReview: vi.fn(), onReviewRefresh: vi.fn(), onCreateBatch: vi.fn(), onSealBatch: vi.fn(), onSelectBatch: vi.fn(), onBatchRefresh: vi.fn(),
|
||||
releaseCapabilities: { production_release_requests_enabled: false, production_backup_restore_verified: false },
|
||||
executionPage: { items: [], total: 0, limit: 20, offset: 0 } as any,
|
||||
executionDetail: null, executionLoading: false, executionError: null, onSelectExecution: vi.fn(), onExecutionRefresh: vi.fn(),
|
||||
selectedDeleteIDs: [] as string[], onToggleDelete: vi.fn(),
|
||||
}
|
||||
const planWith = (count: number): ReleasePlan => ({
|
||||
items: Array.from({ length: count }, (_, i) => ({ publication_id: `tp-${i}`, title: `文档${i}.pdf`, target_scope: 'internal' as const, action: 'add' as const, test_state: 'ready', production_state: 'absent', can_release: true, blocker: '' })),
|
||||
summary: { add: count, update: 0, delete: 0, blocked: 0, unchanged: 0 },
|
||||
})
|
||||
it('renders at most one page (25 rows) instead of the full 618-row plan', () => {
|
||||
const html = renderToStaticMarkup(<ReleaseManagement {...baseProps} releasePlan={planWith(618)} />)
|
||||
expect(html).toContain('筛选 618 / 全部 618')
|
||||
expect(html).toContain('第 1 / 25 页 · 每页 25 条')
|
||||
expect(html.match(/class="release-plan-table"/g)?.length ?? 0).toBeLessThanOrEqual(1)
|
||||
// Only page-1 titles render; a page-2 row and a late row are absent from the DOM.
|
||||
expect(html).toContain('文档0.pdf')
|
||||
expect(html).not.toContain('文档25.pdf')
|
||||
expect(html).not.toContain('文档617.pdf')
|
||||
expect(html).toContain('仅可发布')
|
||||
expect(html).toContain('下一页')
|
||||
})
|
||||
it('keeps small plans pagination-free and pages exactly at the 25-item boundary', () => {
|
||||
const small = renderToStaticMarkup(<ReleaseManagement {...baseProps} releasePlan={planWith(3)} />)
|
||||
expect(small).toContain('筛选 3 / 全部 3')
|
||||
expect(small).not.toContain('上一页')
|
||||
const exact = renderToStaticMarkup(<ReleaseManagement {...baseProps} releasePlan={planWith(25)} />)
|
||||
expect(exact).not.toContain('上一页')
|
||||
expect(exact).toContain('文档24.pdf')
|
||||
const over = renderToStaticMarkup(<ReleaseManagement {...baseProps} releasePlan={planWith(26)} />)
|
||||
expect(over).toContain('第 1 / 2 页 · 每页 25 条')
|
||||
expect(over).not.toContain('文档25.pdf')
|
||||
const huge = renderToStaticMarkup(<ReleaseManagement {...baseProps} releasePlan={planWith(5000)} />)
|
||||
expect(huge.match(/<tr /g)?.length ?? 0).toBeLessThanOrEqual(60)
|
||||
expect(huge).toContain('第 1 / 200 页')
|
||||
})
|
||||
})
|
||||
|
||||
describe('R4 rollback levels in the execution timeline', () => {
|
||||
const baseProps = {
|
||||
reviewPage: { items: [], total: 0, limit: 20, offset: 0 } as any,
|
||||
reviewLoading: false, reviewError: null, reviewingId: null,
|
||||
batchPage: { items: [], total: 0, limit: 20, offset: 0 } as any,
|
||||
batchDetail: null, batchLoading: false, batchError: null, mutatingBatchId: null,
|
||||
onReview: vi.fn(), onReviewRefresh: vi.fn(), onCreateBatch: vi.fn(), onSealBatch: vi.fn(), onSelectBatch: vi.fn(), onBatchRefresh: vi.fn(),
|
||||
releaseCapabilities: { production_release_requests_enabled: true, production_backup_restore_verified: false },
|
||||
releasePlan: { items: [], summary: { add: 0, update: 0, delete: 0, blocked: 0, unchanged: 0 } } as ReleasePlan,
|
||||
executionDetail: null, executionLoading: false, executionError: null, onSelectExecution: vi.fn(), onExecutionRefresh: vi.fn(),
|
||||
selectedDeleteIDs: [] as string[], onToggleDelete: vi.fn(),
|
||||
}
|
||||
const exec = (over: Record<string, unknown>) => ({
|
||||
id: 'rx-1', release_batch_id: 'rb-1', operation: 'rollback', prior_execution_id: 'rx-0',
|
||||
state: 'rolling_back', target_environment: 'production', authorized_by: 'system:auto-rollback', job_id: 'job-1',
|
||||
item_count: 2, batch_size: 50, current_batch: 1, total_batches: 1, completed_item_count: 1, failed_item_count: 0,
|
||||
error_code: '', failure_level: '', restore_trigger: 'auto_rollback_after_failure',
|
||||
created_at: '2026-09-12T09:00:00Z', started_at: '2026-09-12T09:01:00Z', completed_at: null, ...over,
|
||||
}) as any
|
||||
it('labels the compensating stage and the escalation after a failed rollback', () => {
|
||||
const html = renderToStaticMarkup(<ReleaseManagement {...baseProps} executionPage={{ items: [exec({})], total: 1, limit: 20, offset: 0 }} />)
|
||||
expect(html).toContain('正在回滚')
|
||||
expect(html).toContain('正在执行自动回滚')
|
||||
const failed = renderToStaticMarkup(<ReleaseManagement {...baseProps} executionPage={{ items: [exec({ state: 'rollback_failed', failed_item_count: 1 })], total: 1, limit: 20, offset: 0 }} />)
|
||||
expect(failed).toContain('回滚失败')
|
||||
expect(failed).toContain('整体恢复')
|
||||
const done = renderToStaticMarkup(<ReleaseManagement {...baseProps} executionPage={{ items: [exec({ state: 'rolled_back', completed_item_count: 2 })], total: 1, limit: 20, offset: 0 }} />)
|
||||
expect(done).toContain('已回滚')
|
||||
expect(done).toContain('已恢复')
|
||||
const graded = renderToStaticMarkup(<ReleaseManagement {...baseProps} executionPage={{ items: [exec({ operation: 'publish', state: 'failed', failure_level: 'batch' })], total: 1, limit: 20, offset: 0 }} />)
|
||||
expect(graded).toContain('本批后续已停止')
|
||||
})
|
||||
})
|
||||
+1576
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { DocumentWorkbenchView } from './DocumentWorkbench'
|
||||
import { document } from './documentFixture'
|
||||
|
||||
describe('document engineer workbench', () => {
|
||||
it('shows real file names, source categories and scope without technical identifiers', () => {
|
||||
const manual={...document,id:'manual',title:'P3 验收文档',source_type:'manual' as const,connection_id:'manual-1'}
|
||||
const html = renderToStaticMarkup(<DocumentWorkbenchView items={[document,manual]} connections={[]} mode="directory" loading={false} error={null} onRefresh={vi.fn()} onRetry={vi.fn()} retryingId={null} />)
|
||||
for (const text of ['来源与目录','手册.pdf','使用指南','对外','解析完成','PP分类','未接通目录','文件名','显示 1 份验收文档']) expect(html).toContain(text)
|
||||
expect(html).not.toContain('P3 验收文档')
|
||||
expect(html).not.toContain('<code>a</code>')
|
||||
expect(html).not.toContain('只走这 8 步')
|
||||
})
|
||||
it('shows monitoring and no fabricated page progress or production availability', () => {
|
||||
const html = renderToStaticMarkup(<DocumentWorkbenchView items={[document,{...document,id:'active',processing_state:'processing'}]} connections={[]} mode="monitor" loading={false} error={null} onRefresh={vi.fn()} onRetry={vi.fn()} retryingId={null} />)
|
||||
expect(html).toContain('解析监控')
|
||||
expect(html).toContain('来源处理概览')
|
||||
expect(html).toContain('已就绪 1 / 2')
|
||||
expect(html).toContain('独立解析')
|
||||
expect(html).toContain('内容复用')
|
||||
expect(html).toContain('处理中 1')
|
||||
expect(html).toContain('解析完成不代表已上线')
|
||||
expect(html).not.toContain('100%')
|
||||
expect(html).not.toContain('生产可用')
|
||||
})
|
||||
it('does not display zero as a successful load when the request failed', () => {
|
||||
const html = renderToStaticMarkup(<DocumentWorkbenchView items={[]} connections={[]} mode="directory" loading={false} error="加载失败" onRefresh={vi.fn()} onRetry={vi.fn()} retryingId={null} />)
|
||||
expect(html).toContain('加载失败')
|
||||
expect(html).not.toContain('aria-label="当前目录统计"')
|
||||
expect(html).not.toContain('没有符合条件的文件')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,160 @@
|
||||
import { useContext, useEffect, useMemo, useState } from 'react'
|
||||
import type { SourceAsset } from './assets'
|
||||
import type { SourceConnectionPage } from './sourceConnections'
|
||||
import { retryPublication } from './testPublications'
|
||||
import { clearScopeRule, fetchScopeRules, setScopeRule } from './scopeRules'
|
||||
import type { ClearScopeRuleDecision, ScopeRule, ScopeRuleDecision } from './scopeRules'
|
||||
import { ScopeRuleEditor } from './ScopeRuleEditor'
|
||||
import { WorkspaceContextTabsSetter } from './workspaceContext'
|
||||
import { connectionKey, directoryGroups, documentPipeline, documentProblem, documentStage, fetchDocumentCatalog, filterDocuments, operationalDocuments, sourceProgress, stageLabels, visibilityOrigin } from './documentWorkbench'
|
||||
import type { DocumentStage } from './documentWorkbench'
|
||||
import './documentWorkbench.css'
|
||||
|
||||
type Mode = 'directory' | 'monitor' | 'attention'
|
||||
const sourceNames: Record<string, string> = {pp:'PP公开文档', alist:'AList文件源', dingtalk:'钉钉知识库', manual:'手工验收文档'}
|
||||
const activeStages: DocumentStage[] = ['downloading','uploading','parsing','indexing']
|
||||
interface ViewProps {
|
||||
items: SourceAsset[]
|
||||
connections: SourceConnectionPage['items']
|
||||
mode: Mode
|
||||
loading: boolean
|
||||
error: string | null
|
||||
onRefresh: () => void
|
||||
onRetry: (id:string) => void
|
||||
retryingId: string | null
|
||||
}
|
||||
const time = (value:string) => new Date(value).toLocaleString('zh-CN', {hour12:false})
|
||||
const bytes = (value:number) => value >= 1048576 ? `${(value/1048576).toFixed(1)} MB` : `${(value/1024).toFixed(1)} KB`
|
||||
|
||||
export function DocumentWorkbenchView({items, connections, mode, loading, error, onRefresh, onRetry, retryingId}: ViewProps) {
|
||||
const [connection, setConnection] = useState('')
|
||||
const [directory, setDirectory] = useState<string|null>(null)
|
||||
const [query, setQuery] = useState('')
|
||||
const [visibility, setVisibility] = useState('')
|
||||
const [stage, setStage] = useState('')
|
||||
const [page, setPage] = useState(0)
|
||||
const [selectedID, setSelectedID] = useState<string|null>(null)
|
||||
const [showTestDocuments,setShowTestDocuments]=useState(false)
|
||||
const [scopeRules,setScopeRules]=useState<ScopeRule[]>([])
|
||||
const [scopeLoading,setScopeLoading]=useState(false)
|
||||
const [scopeError,setScopeError]=useState<string|null>(null)
|
||||
const setWorkspaceContextTabs=useContext(WorkspaceContextTabsSetter)
|
||||
const visibleItems=useMemo(()=>operationalDocuments(items,showTestDocuments),[items,showTestDocuments])
|
||||
const groups = useMemo(()=>directoryGroups(visibleItems),[visibleItems])
|
||||
const sources = useMemo(()=> {
|
||||
const map = new Map(connections.filter(c=>showTestDocuments||c.source_type!=='manual').map(c=>[c.id, {id:c.id,type:c.source_type,name:c.name}]))
|
||||
for (const item of visibleItems) if (!map.has(connectionKey(item))) map.set(connectionKey(item), {id:connectionKey(item),type:item.source_type,name:item.connection_name})
|
||||
return [...map.values()]
|
||||
},[visibleItems,connections,showTestDocuments])
|
||||
const scoped = filterDocuments(visibleItems,{connection,directory,query:'',visibility:'',stage:''})
|
||||
const filtered = filterDocuments(visibleItems,{connection,directory,query,visibility,stage}).filter(item => mode !== 'attention' || ['blocked','failed'].includes(documentStage(item)))
|
||||
const shownPage = Math.min(page,Math.max(0,Math.ceil(filtered.length/40)-1))
|
||||
const selected = filtered.find(item=>item.id===selectedID)
|
||||
const reset = () => {setPage(0);setSelectedID(null)}
|
||||
const selectFolder = (id:string,path:string|null) => {setConnection(id);setDirectory(path);reset()}
|
||||
const title = mode === 'monitor' ? '解析监控' : mode === 'attention' ? '待处理文件' : '来源与目录'
|
||||
const unavailable = items.length === 0 && Boolean(loading || error)
|
||||
const progress=sourceProgress(visibleItems)
|
||||
const manualCount=items.filter(item=>item.source_type==='manual').length
|
||||
const directDirectoryRule=scopeRules.find(rule=>rule.target_type==='directory'&&rule.connection_id===connection&&rule.directory_path===(directory??''))
|
||||
const selectedItemRule=scopeRules.find(rule=>rule.target_type==='item'&&rule.source_item_id===selectedID)
|
||||
const selectedSourceLabel=sourceNames[sources.find(item=>item.id===connection)?.type||'']||'当前来源'
|
||||
useEffect(()=>{
|
||||
if(!connection){setScopeRules([]);setScopeError(null);return}
|
||||
const controller=new AbortController()
|
||||
setScopeLoading(true)
|
||||
void fetchScopeRules(connection,controller.signal).then(setScopeRules).catch(cause=>{if(!controller.signal.aborted)setScopeError(cause instanceof Error?cause.message:'加载范围规则失败')}).finally(()=>{if(!controller.signal.aborted)setScopeLoading(false)})
|
||||
return()=>controller.abort()
|
||||
},[connection])
|
||||
useEffect(()=>{
|
||||
if(!connection){setWorkspaceContextTabs([]);return}
|
||||
const tabs=[{key:'source',label:selectedSourceLabel,onActivate:()=>{setDirectory(null);setSelectedID(null);setPage(0)}}]
|
||||
if(directory!==null)tabs.push({key:'directory',label:directory||'分类待补齐',onActivate:()=>setSelectedID(null)})
|
||||
if(selected)tabs.push({key:'file',label:selected.title||'当前文件',onActivate:()=>setSelectedID(selected.id)})
|
||||
setWorkspaceContextTabs(tabs)
|
||||
return()=>setWorkspaceContextTabs([])
|
||||
},[connection,directory,selected,selectedSourceLabel,setWorkspaceContextTabs])
|
||||
const mutateScope=async(decision:ScopeRuleDecision|ClearScopeRuleDecision,clear:boolean)=>{
|
||||
if(scopeLoading)return
|
||||
setScopeLoading(true);setScopeError(null)
|
||||
try{if(clear)await clearScopeRule(decision as ClearScopeRuleDecision);else await setScopeRule(decision as ScopeRuleDecision);setScopeRules(await fetchScopeRules(connection));onRefresh()}catch(cause){setScopeError(cause instanceof Error?cause.message:'保存范围规则失败')}finally{setScopeLoading(false)}
|
||||
}
|
||||
return <main className="page-shell document-workbench">
|
||||
<header className="hero compact"><div><p className="eyebrow">文档工作台</p><h1>{title}</h1><p className="subtitle">{mode === 'monitor' ? '看每份文件处理到哪一步。解析完成不代表已上线。' : mode === 'attention' ? '只列出超限、失败或来源不可访问的文件。内容审核请进入发布管理。' : '先选来源和目录,再看文件、对内/对外和处理状态。'}</p></div><button onClick={onRefresh} disabled={loading}>{loading?'刷新中…':'刷新状态'}</button></header>
|
||||
{error ? <div role="alert" className="error-banner">{error}(旧数据仅供参考)</div> : null}
|
||||
{mode==='monitor'&&!unavailable?<section className="source-progress" aria-label="来源处理概览"><div className="section-title"><strong>来源处理概览</strong><span>直接看各来源完成、处理中和异常数量</span></div><div className="source-progress-grid">{progress.map(item=>{const source=sources.find(value=>value.id===item.connection);return <button key={item.connection} className={connection===item.connection?'source-progress-card active':'source-progress-card'} onClick={()=>selectFolder(item.connection,null)}><strong>{sourceNames[source?.type||'']||source?.name||'当前来源'}</strong><span>已就绪 {item.completed+item.reused} / {item.total}</span><small>独立解析 {item.completed} · 内容复用 {item.reused}</small><small>处理中 {item.active} · 需处理 {item.attention} · 等待 {item.waiting}</small></button>})}</div></section>:null}
|
||||
<div className="document-layout">
|
||||
<aside className="directory-panel" aria-label="来源目录">
|
||||
<button className={!connection?'folder active':'folder'} onClick={()=>selectFolder('',null)}>全部来源 <b>{unavailable?'—':visibleItems.length}</b></button>
|
||||
{sources.map(source=><section key={source.id}>
|
||||
<button className={connection===source.id && directory===null?'folder active':'folder'} onClick={()=>selectFolder(source.id,null)} title={source.name}><span>{sourceNames[source.type] || source.name}</span><b>{visibleItems.filter(x=>connectionKey(x)===source.id).length}</b></button>
|
||||
<small className="directory-note">{source.type === 'pp'?'PP分类 · 不代表完整原始目录':source.type === 'manual'?'隔离验收用文档':'已收录目录'}</small>
|
||||
{groups.filter(g=>g.connection===source.id).map(group=><button key={group.key} className={connection===source.id && directory===group.path?'folder child active':'folder child'} onClick={()=>selectFolder(source.id,group.path)}><span>▸ {group.path || (source.type==='pp'?'分类待补齐':'目录待补齐')}</span><b>{group.count}</b></button>)}
|
||||
</section>)}
|
||||
{(['dingtalk','alist'] as const).filter(type=>!sources.some(s=>s.type===type)).map(type=><div className="source-unconnected" key={type}><strong>{sourceNames[type]}</strong><small>未接通目录</small></div>)}
|
||||
{manualCount?<label className="test-document-toggle"><input type="checkbox" checked={showTestDocuments} onChange={event=>{setShowTestDocuments(event.target.checked);selectFolder('',null)}} />显示 {manualCount} 份验收文档</label>:null}
|
||||
</aside>
|
||||
<section className="document-content">
|
||||
|
||||
{!unavailable ? <div className="document-counts" aria-label="当前目录统计">
|
||||
<span>文件 <b>{scoped.length}</b></span>
|
||||
{mode==='monitor'?<><span>独立解析 <b>{scoped.filter(x=>documentStage(x)==='completed').length}</b></span><span>内容复用 <b>{scoped.filter(x=>documentStage(x)==='reused').length}</b></span><span>处理中 <b>{scoped.filter(x=>activeStages.includes(documentStage(x))).length}</b></span><span>等待 <b>{scoped.filter(x=>documentStage(x)==='waiting').length}</b></span><span>需处理(含超限) <b>{scoped.filter(x=>['blocked','failed'].includes(documentStage(x))).length}</b></span></>:<><span>对内 <b>{scoped.filter(x=>x.visibility==='internal').length}</b></span><span>对外 <b>{scoped.filter(x=>x.visibility==='external').length}</b></span><span>处理中 <b>{scoped.filter(x=>activeStages.includes(documentStage(x))).length}</b></span><span>已解析 <b>{scoped.filter(x=>documentStage(x)==='completed').length}</b></span><span>需处理 <b>{scoped.filter(x=>['blocked','failed'].includes(documentStage(x))).length}</b></span></>}
|
||||
</div> : <p className="directory-note">文件数量尚未核实</p>}
|
||||
{mode==='directory'&&connection&&directory!==''?<ScopeRuleEditor target={{target_type:'directory',connection_id:connection,directory_path:directory??'',source_item_id:''}} currentRule={directDirectoryRule} saving={scopeLoading} error={scopeError} onSave={decision=>void mutateScope(decision,false)} onClear={decision=>void mutateScope(decision,true)} />:mode==='directory'&&connection&&directory===''?<p className="scope-unavailable">“分类待补齐”不是可靠目录,不能单独设置范围。请先补齐来源目录,或返回来源级设置。</p>:null}
|
||||
<div className="document-filters">
|
||||
<label>找文件<input type="search" placeholder="输入文件名" value={query} onChange={e=>{setQuery(e.target.value);reset()}} /></label>
|
||||
<label>对内/对外<select value={visibility} onChange={e=>{setVisibility(e.target.value);reset()}}><option value="">全部范围</option><option value="internal">对内</option><option value="external">对外</option></select></label>
|
||||
<label>处理状态<select value={stage} onChange={e=>{setStage(e.target.value);reset()}}><option value="">全部状态</option>{Object.entries(stageLabels).map(([value,label])=><option value={value} key={value}>{label}</option>)}</select></label>
|
||||
</div>
|
||||
<div className="document-location">{!connection?'全部来源':sourceNames[sources.find(s=>s.id===connection)?.type || ''] || '当前来源'} / {directory === null?'全部文件':directory || '目录待补齐'} {!unavailable ? <span>筛选结果 {filtered.length} 份</span> : null}</div>
|
||||
{loading && !items.length ? <div className="empty-state">正在核对完整文档清单…</div> : null}
|
||||
{!loading && !error && !filtered.length ? <div className="empty-state">没有符合条件的文件。</div> : null}
|
||||
{filtered.length ? <div className="table-wrap"><table className="document-table"><thead><tr><th>文件名</th><th>对内/对外</th><th>处理状态</th><th>大小</th><th>状态更新时间</th></tr></thead><tbody>
|
||||
{filtered.slice(shownPage*40,(shownPage+1)*40).map(item=><tr key={item.id} className={item.id===selectedID?'selected-row':''}>
|
||||
<td><button className="file-link" onClick={()=>setSelectedID(item.id)}>{item.title || '文件名待补齐'}</button><small>{sourceNames[item.source_type]} / {item.directory_path || '目录待补齐'}</small></td>
|
||||
<td><span className={`scope-badge ${item.visibility}`}>{item.visibility==='external'?'对外':'对内'}</span><small>{visibilityOrigin(item)}</small></td>
|
||||
<td><span className={`document-stage ${documentStage(item)}`}>{stageLabels[documentStage(item)]}</span></td><td>{bytes(item.size_bytes)}</td><td><time>{time(item.updated_at)}</time></td>
|
||||
</tr>)}
|
||||
</tbody></table></div> : null}
|
||||
<div className="pagination"><span>第 {shownPage+1} / {Math.max(1,Math.ceil(filtered.length/40))} 页</span><div><button disabled={shownPage===0} onClick={()=>setPage(shownPage-1)}>上一页</button><button disabled={(shownPage+1)*40>=filtered.length} onClick={()=>setPage(shownPage+1)}>下一页</button></div></div>
|
||||
{mode === 'monitor' ? <p className="directory-note">每15秒自动刷新。当前接口未提供页数或逐页百分比,因此只显示真实阶段。时间为状态更新时间,不是源文件修改时间。</p> : null}
|
||||
</section>
|
||||
</div>
|
||||
{selected ? <section className="document-inspector panel" aria-label="文件详情"><div className="panel-heading"><h2>{selected.title || '文件名待补齐'}</h2><button onClick={()=>setSelectedID(null)}>关闭详情</button></div><div className="inspector-body">
|
||||
<dl><dt>来源位置</dt><dd>{sourceNames[selected.source_type]} / {selected.directory_path || '目录待补齐'}</dd><dt>对内/对外</dt><dd>{selected.visibility==='external'?'对外':'对内'} · {visibilityOrigin(selected)}</dd><dt>当前进度</dt><dd>{stageLabels[documentStage(selected)]}</dd></dl>
|
||||
{documentProblem(selected) ? <p role="status">{documentProblem(selected)}</p> : null}
|
||||
<div className="file-facts"><span>文件大小 <b>{bytes(selected.size_bytes)}</b></span><span>状态更新时间 <b>{time(selected.updated_at)}</b></span><span>来源变化 <b>{selected.source_change==='unchanged'?'无变化':'需要核对'}</b></span><span>检索状态 <b>{selected.retrieval_state==='enabled'?'测试环境已启用':'未证明已启用'}</b></span></div>
|
||||
<div className="document-pipeline" aria-label="文件处理链路">{documentPipeline(selected).map(step=><div className={`pipeline-step ${step.state}`} key={step.label}><span aria-hidden="true"/><div><strong>{step.label}</strong><small>{step.detail}</small></div></div>)}</div>
|
||||
<p>原文与版本差异尚未接通,请在源系统核对内容;不要仅凭“解析完成”批准发布。</p>
|
||||
{mode==='directory'?<ScopeRuleEditor target={{target_type:'item',connection_id:'',directory_path:'',source_item_id:selected.id}} currentRule={selectedItemRule} saving={scopeLoading} error={scopeError} onSave={decision=>void mutateScope(decision,false)} onClear={decision=>void mutateScope(decision,true)} />:null}
|
||||
{selected.can_retry && selected.publication_id ? <button disabled={!!retryingId} onClick={()=>onRetry(selected.publication_id!)}>{retryingId===selected.publication_id?'提交中…':'重试此文件'}</button> : null}
|
||||
{selected.last_error ? <details><summary>错误详情</summary><code>{selected.last_error}</code></details> : null}
|
||||
</div></section> : null}
|
||||
</main>
|
||||
}
|
||||
|
||||
export function DocumentWorkbench({mode,connections}: {mode:Mode;connections:SourceConnectionPage['items']}) {
|
||||
const [items,setItems] = useState<SourceAsset[]>([])
|
||||
const [loading,setLoading] = useState(true)
|
||||
const [error,setError] = useState<string|null>(null)
|
||||
const [revision,setRevision] = useState(0)
|
||||
const [retryingId,setRetryingId] = useState<string|null>(null)
|
||||
useEffect(()=>{
|
||||
const controller = new AbortController()
|
||||
setLoading(true)
|
||||
void fetchDocumentCatalog(controller.signal).then(data=>{if (!controller.signal.aborted) {setItems(data);setError(null)}}).catch(cause=>{if (!controller.signal.aborted) setError(cause instanceof Error?cause.message:'加载文件失败')}).finally(()=>{if (!controller.signal.aborted) setLoading(false)})
|
||||
return ()=>controller.abort()
|
||||
},[revision])
|
||||
useEffect(()=>{
|
||||
if (mode!=='monitor' || loading) return
|
||||
const timer = window.setTimeout(()=>setRevision(r=>r+1),15000)
|
||||
return ()=>window.clearTimeout(timer)
|
||||
},[mode,loading,revision])
|
||||
const retry = async(id:string)=>{
|
||||
if (retryingId) return
|
||||
if (!window.confirm('仅重试这份失败文件,不影响已成功文件或生产。继续吗?')) return
|
||||
setRetryingId(id)
|
||||
try {await retryPublication(id);setRevision(r=>r+1)} catch(cause) {setError(cause instanceof Error?cause.message:'重试失败')} finally {setRetryingId(null)}
|
||||
}
|
||||
return <DocumentWorkbenchView items={items} connections={connections} mode={mode} loading={loading} error={error} onRefresh={()=>setRevision(r=>r+1)} onRetry={id=>void retry(id)} retryingId={retryingId} />
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe,expect,it,vi } from 'vitest'
|
||||
import { ReleasePlannerView } from './ReleasePlanner'
|
||||
import { simulatedReleaseCandidates } from './releasePlanner'
|
||||
|
||||
describe('ReleasePlannerView',()=>{
|
||||
it('shows a four-step document release plan with explicit closure and production gates',()=>{
|
||||
const html=renderToStaticMarkup(<ReleasePlannerView candidates={simulatedReleaseCandidates} selectedIDs={['sim-cr5']} onToggle={vi.fn()} onClear={vi.fn()} />)
|
||||
for(const text of ['本地模拟发布准备','1. 选择文档','2. 检查数据闭包','3. 锁定清单','4. 生产负责人授权','[模拟] CR5用户手册.pdf','切片 186','向量 186','Wiki 完整','图谱 完整','闭包完整','文档级:','闭包可独立验证','整知识库:','Wiki或图谱共享','推荐方式','文档级同步','生产发布已关闭','生产备份到OSS:尚未配置'])expect(html).toContain(text)
|
||||
expect(html).not.toContain('>授权生产发布</button>')
|
||||
})
|
||||
it('forces whole knowledge-base mode for shared graph data and blocks failed parsing',()=>{
|
||||
const whole=renderToStaticMarkup(<ReleasePlannerView candidates={simulatedReleaseCandidates} selectedIDs={['sim-params']} onToggle={vi.fn()} onClear={vi.fn()} />)
|
||||
expect(whole).toContain('整知识库同步')
|
||||
expect(whole).toContain('图谱 共享,需整库')
|
||||
const failed=renderToStaticMarkup(<ReleasePlannerView candidates={simulatedReleaseCandidates} selectedIDs={['sim-failed']} onToggle={vi.fn()} onClear={vi.fn()} />)
|
||||
expect(failed).toContain('当前清单不能同步')
|
||||
expect(failed).toContain('闭包不完整')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useState } from 'react'
|
||||
import { evaluateReleaseSelection,simulatedReleaseCandidates } from './releasePlanner'
|
||||
import type { ClosureState,ReleaseCandidate } from './releasePlanner'
|
||||
import './releasePlanner.css'
|
||||
const closure=(value:ClosureState)=>value==='ready'?'完整':value==='shared'?'共享,需整库':value==='missing'?'缺失':'不适用'
|
||||
const modeLabel={none:'尚未选择',document:'文档级同步',knowledge_base:'整知识库同步',blocked:'当前清单不能同步'} as const
|
||||
interface Props{candidates:ReleaseCandidate[];selectedIDs:string[];onToggle:(id:string)=>void;onClear:()=>void;onGenerate?:()=>void;generated?:boolean}
|
||||
export function ReleasePlannerView({candidates,selectedIDs,onToggle,onClear,onGenerate=()=>undefined,generated=false}:Props){
|
||||
const selected=candidates.filter(item=>selectedIDs.includes(item.id));const plan=evaluateReleaseSelection(selected);const totals=selected.reduce((sum,item)=>({chunks:sum.chunks+item.chunks,vectors:sum.vectors+item.vectors,assets:sum.assets+item.assets}),{chunks:0,vectors:0,assets:0})
|
||||
return <main className="page-shell release-planner">
|
||||
<header className="hero compact"><div><p className="eyebrow">同步准备</p><h1>发布管理</h1><p className="subtitle">确认测试环境哪些文档具备完整数据,再决定文档级或整知识库同步。</p></div><span className="production-off">生产发布已关闭</span></header>
|
||||
<div className="simulation-banner"><strong>本地模拟发布准备</strong><span>候选文档和闭包数量均为模拟,用于确认工作流程;不会连接生产。</span></div>
|
||||
<ol className="release-four-steps"><li className="active">1. 选择文档</li><li>2. 检查数据闭包</li><li>3. 锁定清单</li><li className="danger">4. 生产负责人授权</li></ol>
|
||||
<div className="release-plan-layout">
|
||||
<section className="release-candidates"><div className="release-plan-heading"><div><h2>测试环境候选文档</h2><span>解析失败或核心数据缺失的文件不可加入</span></div><button className="secondary" onClick={onClear} disabled={!selectedIDs.length}>清空选择</button></div>
|
||||
<div className="release-candidate-list">{candidates.map(item=>{const blocked=item.parse_status!=='completed'||item.chunks<1||item.vectors!==item.chunks||item.assets<1||item.wiki==='missing'||item.graph==='missing';const shared=item.wiki==='shared'||item.graph==='shared';return <label className={blocked?'release-candidate blocked':'release-candidate'} key={item.id}><input type="checkbox" checked={selectedIDs.includes(item.id)} disabled={blocked} onChange={()=>onToggle(item.id)} /><div className="candidate-title"><strong>{item.title}</strong><small>{item.knowledge_base_name} · {item.visibility==='external'?'对外':'对内'} · {item.parse_status}</small></div><div className="closure-grid"><span className={item.chunks?'ready':'missing'}>切片 {item.chunks||'缺失'}</span><span className={item.vectors===item.chunks&&item.vectors?'ready':'missing'}>向量 {item.vectors||'缺失'}</span><span className={item.assets?'ready':'missing'}>文件 {item.assets||'缺失'}</span><span className={item.wiki}>Wiki {closure(item.wiki)}</span><span className={item.graph}>图谱 {closure(item.graph)}</span></div><b className={`closure-result ${blocked?'missing':shared?'shared':'ready'}`}>{blocked?'闭包不完整':shared?'共享需整库':'闭包完整'}</b></label>})}</div>
|
||||
</section>
|
||||
<aside className="release-plan-summary"><h2>本次同步清单</h2><div className="release-decision-key"><span><b>文档级:</b>闭包可独立验证</span><span><b>整知识库:</b>Wiki或图谱共享</span><span><b>阻断:</b>解析失败或数据缺失</span></div><div className={`release-mode ${plan.mode}`}><span>推荐方式</span><strong>{modeLabel[plan.mode]}</strong><small>{plan.reason}</small></div><dl><dt>已选文档</dt><dd>{selected.length}</dd><dt>切片</dt><dd>{totals.chunks}</dd><dt>向量</dt><dd>{totals.vectors}</dd><dt>文件资源</dt><dd>{totals.assets}</dd></dl>{plan.mode==='knowledge_base'?<p className="kb-warning">检测到共享Wiki或图谱关系,将同步整个“{selected[0]?.knowledge_base_name}”,不会覆盖整个WeKnora数据库。</p>:null}<div className="release-gates"><span>生产备份到OSS:尚未配置</span><span>生产授权:关闭</span><span>Release Worker:关闭</span></div><button disabled={plan.blocked} title={plan.blocked?plan.reason:'仅生成本地模拟清单'} onClick={onGenerate}>{generated?'模拟清单已生成':'生成模拟清单'}</button><small>模拟清单不会锁定真实数据,也不会创建生产任务。</small></aside>
|
||||
</div>
|
||||
</main>
|
||||
}
|
||||
export function ReleasePlanner(){
|
||||
const [selectedIDs,setSelectedIDs]=useState<string[]>([]);const [generated,setGenerated]=useState(false)
|
||||
const toggle=(id:string)=>{setGenerated(false);setSelectedIDs(current=>current.includes(id)?current.filter(value=>value!==id):[...current,id])}
|
||||
return <ReleasePlannerView candidates={simulatedReleaseCandidates} selectedIDs={selectedIDs} onToggle={toggle} onClear={()=>{setSelectedIDs([]);setGenerated(false)}} onGenerate={()=>setGenerated(true)} generated={generated} />
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { ScopeRuleEditor } from './ScopeRuleEditor'
|
||||
|
||||
describe('ScopeRuleEditor',()=>{
|
||||
it('explains directory inheritance and keeps production publication separate',()=>{
|
||||
const html=renderToStaticMarkup(<ScopeRuleEditor target={{target_type:'directory',connection_id:'conn-1',directory_path:'产品',source_item_id:''}} currentRule={{target_type:'directory',connection_id:'conn-1',directory_path:'产品',visibility:'internal',updated_by:'engineer',reason:'内部资料',updated_at:'2026-09-08T00:00:00Z'}} saving={false} onSave={vi.fn()} onClear={vi.fn()} />)
|
||||
for(const text of ['此目录及子目录','当前设置:对内','人工:engineer','移除本级设置,恢复继承','不会自动发布到生产']) expect(html).toContain(text)
|
||||
})
|
||||
it('shows an honest inherited state when no direct rule exists',()=>{
|
||||
const html=renderToStaticMarkup(<ScopeRuleEditor target={{target_type:'directory',connection_id:'conn-1',directory_path:'',source_item_id:''}} saving={false} onSave={vi.fn()} onClear={vi.fn()} />)
|
||||
expect(html).toContain('整个来源')
|
||||
expect(html).toContain('当前没有本级设置')
|
||||
expect(html).toContain('拟修改为')
|
||||
expect(html).toContain('选择新范围')
|
||||
expect(html).not.toContain('移除本级设置')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,33 @@
|
||||
import { useState } from 'react'
|
||||
import type { ClearScopeRuleDecision, ScopeRule, ScopeRuleDecision, ScopeRuleTarget, Visibility } from './scopeRules'
|
||||
|
||||
interface Props {
|
||||
target: ScopeRuleTarget
|
||||
currentRule?: ScopeRule
|
||||
saving: boolean
|
||||
error?: string|null
|
||||
onSave: (decision:ScopeRuleDecision)=>void
|
||||
onClear: (decision:ClearScopeRuleDecision)=>void
|
||||
}
|
||||
|
||||
export function ScopeRuleEditor({target,currentRule,saving,error,onSave,onClear}:Props){
|
||||
const [visibility,setVisibility]=useState<Visibility|''>(currentRule?.visibility||'')
|
||||
const [operator,setOperator]=useState('')
|
||||
const [reason,setReason]=useState('')
|
||||
const identityReady=operator.trim()!==''&&reason.trim()!==''&&!saving
|
||||
const saveReady=identityReady&&visibility!==''
|
||||
const label=target.target_type==='item'?'仅此文件':target.directory_path?'此目录及子目录':'整个来源'
|
||||
const base={...target,operator_ref:operator.trim(),reason:reason.trim()}
|
||||
return <section className="scope-editor" aria-label="对内对外范围设置">
|
||||
<div className="scope-editor-heading"><div><strong>对内/对外设置</strong><span>{label}</span></div>{currentRule?<span className={`scope-badge ${currentRule.visibility}`}>当前设置:{currentRule.visibility==='external'?'对外':'对内'}</span>:<span className="inherited-badge">当前没有本级设置</span>}</div>
|
||||
{currentRule?<p className="scope-rule-meta">人工:{currentRule.updated_by} · 原因:{currentRule.reason}</p>:<p className="scope-rule-meta">当前继承上级规则或来源原始标记。</p>}
|
||||
<div className="scope-editor-fields">
|
||||
<label>拟修改为<select value={visibility} onChange={event=>setVisibility(event.target.value as Visibility|'')}><option value="">选择新范围</option><option value="internal">对内</option><option value="external">对外</option></select></label>
|
||||
<label>操作人<input value={operator} maxLength={128} placeholder="姓名或工号" onChange={event=>setOperator(event.target.value)} /></label>
|
||||
<label className="scope-reason">判断原因<input value={reason} maxLength={500} placeholder="例如:官网已公开 / 含内部参数" onChange={event=>setReason(event.target.value)} /></label>
|
||||
</div>
|
||||
{error?<p className="scope-error" role="alert">{error}</p>:null}
|
||||
<div className="scope-editor-actions"><button disabled={!saveReady} onClick={()=>onSave({...base,visibility:visibility as Visibility})}>{saving?'保存中…':'保存范围'}</button>{currentRule?<button className="secondary" disabled={!identityReady} onClick={()=>onClear(base)}>移除本级设置,恢复继承</button>:null}</div>
|
||||
<small>这里只更新治理规则并记录审计,不会修改源文件,也不会自动发布到生产。</small>
|
||||
</section>
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe,expect,it,vi } from 'vitest'
|
||||
import { SnapshotHistoryView } from './SnapshotHistory'
|
||||
import type { CatalogSnapshot } from './sourceCatalog'
|
||||
|
||||
const head:CatalogSnapshot={snapshot_id:'ss-new',connection_id:'conn-1',root_node_id:'root',source_name:'国内工业',node_count:2,folder_count:1,file_count:1,observed_at:'2026-09-11T00:00:00Z',created_at:'2026-09-11T00:00:05Z',is_head:true}
|
||||
const older:CatalogSnapshot={...head,snapshot_id:'ss-old',observed_at:'2026-09-10T00:00:00Z',is_head:false}
|
||||
const fileNode={node_id:'file-old',parent_node_id:'root',node_type:'file' as const,name:'手册.pdf',direct_child_count:0,subtree_file_count:1,subtree_bytes:20,size_bytes:20,modified_at:'2026-09-09T00:00:00Z',content_sha256:'ab'.repeat(32),visibility:'unknown' as const,imported_count:0,parsed_count:0,active_count:0,failed_count:0,routable_count:0}
|
||||
const page={current:{node_id:'root',node_type:'folder' as const,name:'国内工业',direct_child_count:1,subtree_file_count:1,subtree_bytes:20,visibility:'unknown' as const,imported_count:0,parsed_count:0,active_count:0,failed_count:0,routable_count:0},breadcrumbs:[{node_id:'root',name:'国内工业'}],items:[fileNode],total:1,limit:50,offset:0}
|
||||
|
||||
describe('SnapshotHistoryView',()=>{
|
||||
it('lists snapshot history, flags head and opens a historical snapshot read-only',()=>{
|
||||
const html=renderToStaticMarkup(<SnapshotHistoryView snapshots={[head,older]} active={older} page={page} loading={false} error={null} onClose={vi.fn()} onOpenSnapshot={vi.fn()} onOpenFolder={vi.fn()} />)
|
||||
expect(html).toContain('历史快照')
|
||||
expect(html).toContain('当前')
|
||||
expect(html).toContain('只读')
|
||||
expect(html).toContain('手册.pdf')
|
||||
expect(html).toContain('内容Hash')
|
||||
expect(html).toContain('abababababab')
|
||||
// hash is displayable but never turns into an interactive policy checkbox/button
|
||||
expect(html).not.toContain('checkbox')
|
||||
expect(html).not.toContain('policy-button')
|
||||
})
|
||||
it('shows 内容Hash未获取 instead of faking a hash',()=>{
|
||||
const missing={...page,items:[{...fileNode,content_sha256:undefined}]}
|
||||
const html=renderToStaticMarkup(<SnapshotHistoryView snapshots={[head,older]} active={older} page={missing} loading={false} error={null} onClose={vi.fn()} onOpenSnapshot={vi.fn()} onOpenFolder={vi.fn()} />)
|
||||
expect(html).toContain('内容Hash未获取')
|
||||
})
|
||||
it('lists snapshots without an active page and offers opening each one',()=>{
|
||||
const html=renderToStaticMarkup(<SnapshotHistoryView snapshots={[head,older]} active={null} page={null} loading={false} error={null} onClose={vi.fn()} onOpenSnapshot={vi.fn()} onOpenFolder={vi.fn()} />)
|
||||
expect((html.match(/查看该快照/g)||[]).length).toBe(2)
|
||||
expect(html).toContain('份文件')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { CatalogNodePage, CatalogSnapshot } from './sourceCatalog'
|
||||
import './sourceCatalogBrowser.css'
|
||||
|
||||
const stamp=(value:string)=>new Date(value).toLocaleString('zh-CN',{hour12:false})
|
||||
const shortHash=(value:string)=>`${value.slice(0,12)}…${value.slice(-8)}`
|
||||
|
||||
interface Props{snapshots:CatalogSnapshot[];active:CatalogSnapshot|null;page:CatalogNodePage|null;loading:boolean;error:string|null
|
||||
onClose:()=>void;onOpenSnapshot:(snapshot:CatalogSnapshot)=>void;onOpenFolder:(snapshot:CatalogSnapshot,nodeID:string)=>void}
|
||||
|
||||
export function SnapshotHistoryView({snapshots,active,page,loading,error,onClose,onOpenSnapshot,onOpenFolder}:Props){
|
||||
return <section className="snapshot-history" aria-label="历史快照">
|
||||
<header><h2>历史快照</h2><p>只读查看不可变快照;切换查看不会改变当前生效版本。</p><button type="button" onClick={onClose}>返回当前目录</button></header>
|
||||
{error?<div className="error-banner" role="alert">{error}</div>:null}
|
||||
<ul className="snapshot-history-list">{snapshots.map(snapshot=><li key={snapshot.snapshot_id}>
|
||||
<div><strong>{stamp(snapshot.observed_at)}</strong>{snapshot.is_head?<span className="scope-badge internal">当前</span>:null}<small>{snapshot.node_count} 个节点 · {snapshot.file_count} 份文件 · 入库 {stamp(snapshot.created_at)}</small></div>
|
||||
<button type="button" onClick={()=>onOpenSnapshot(snapshot)}>{active?.snapshot_id===snapshot.snapshot_id?'刷新该快照':'查看该快照'}</button>
|
||||
</li>)}</ul>
|
||||
{loading?<div className="empty-state">正在读取历史快照目录…</div>:null}
|
||||
{active&&page?<div className="snapshot-history-table"><div className="catalog-pathbar"><span>{active.source_name}</span><span>只读历史快照</span></div>
|
||||
<table className="catalog-table"><thead><tr><th>名称</th><th>类型</th><th>大小</th><th>更新时间</th><th>内容Hash</th></tr></thead>
|
||||
<tbody>{page.items.map(node=><tr key={node.node_id}>
|
||||
<td>{node.node_type==='folder'?<button type="button" className="catalog-name" onClick={()=>onOpenFolder(active,node.node_id)}>📁 {node.name}</button>:<>📄 {node.name}</>}</td>
|
||||
<td>{node.node_type==='folder'?'文件夹':'文件'}</td>
|
||||
<td>{typeof node.size_bytes==='number'?`${node.size_bytes} B`:'—'}</td>
|
||||
<td>{node.modified_at?stamp(node.modified_at):'—'}</td>
|
||||
<td>{node.content_sha256?shortHash(node.content_sha256):'内容Hash未获取'}</td>
|
||||
</tr>)}</tbody></table>
|
||||
{page.total>page.limit?<p className="pagination"><span>共 {page.total} 项 · 每页 {page.limit} 项</span></p>:null}
|
||||
</div>:null}
|
||||
{!loading&&active&&!page&&!error?<div className="empty-state">该快照暂无可见内容。</div>:null}
|
||||
</section>
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe,expect,it,vi } from 'vitest'
|
||||
import { SourceCatalogBrowserView } from './SourceCatalogBrowser'
|
||||
import type { CatalogNode,CatalogNodePage,CatalogSource } from './sourceCatalog'
|
||||
import type { Job } from './jobs'
|
||||
|
||||
const source:CatalogSource={connection_id:'conn-1',source_type:'dingtalk',name:'公司级技术支持知识库',root_node_id:'root-1',folder_count:1080,file_count:3468,observed_at:'2026-09-08T00:00:00Z',snapshot_only:true,snapshot_status:'ready',last_refresh_duration_ms:12000}
|
||||
const node=(name:string,type:'folder'|'file',id:string)=>({node_id:id,parent_node_id:'root-1',node_type:type,name,direct_child_count:type==='folder'?2:0,subtree_file_count:type==='folder'?10:1,subtree_bytes:1024,size_bytes:type==='file'?1024:undefined,visibility:type==='folder'?'internal' as const:'unknown' as const,imported_count:type==='folder'?8:0,parsed_count:type==='folder'?7:0,active_count:1,failed_count:0,routable_count:type==='file'?1:8})
|
||||
const page:CatalogNodePage={current:{...node('公司级技术支持知识库','folder','root-1'),parent_node_id:undefined},breadcrumbs:[{node_id:'root-1',name:'公司级技术支持知识库'}],items:[node('01|产品总览与定位','folder','folder-1'),node('根目录说明.pdf','file','file-1')],total:2,limit:50,offset:0}
|
||||
|
||||
describe('SourceCatalogBrowserView',()=>{
|
||||
|
||||
it('uses a Windows-style path bar instead of a directory tree',()=>{
|
||||
const html=renderToStaticMarkup(<SourceCatalogBrowserView sources={[source]} selectedSource={source} page={page} loading={false} error={null} onSelectSource={vi.fn()} onOpenFolder={vi.fn()} onNavigateTo={vi.fn()} onBack={vi.fn()} onPageChange={vi.fn()} onRefresh={vi.fn()} />)
|
||||
expect(html).toContain('aria-label="当前目录路径"')
|
||||
expect(html).toContain('aria-label="目录面包屑"')
|
||||
expect(html).toContain('aria-label="返回上一级"')
|
||||
expect(html).not.toContain('role="tree"')
|
||||
expect(html).not.toContain('目录树')
|
||||
})
|
||||
|
||||
it('looks like a folder browser and shows only direct children',()=>{
|
||||
const html=renderToStaticMarkup(<SourceCatalogBrowserView sources={[source]} selectedSource={source} page={page} loading={false} error={null} onSelectSource={vi.fn()} onOpenFolder={vi.fn()} onNavigateTo={vi.fn()} onBack={vi.fn()} onPageChange={vi.fn()} onRefresh={vi.fn()} />)
|
||||
for(const text of ['各个知识源头的资料总览与标注','公司级技术支持知识库','01|产品总览与定位','文件夹','已解析 7 / 已导入 8','本地只读快照','含所有子目录文件'])expect(html).toContain(text)
|
||||
expect(html).not.toContain('真实目录')
|
||||
expect(html).toContain('根目录说明.pdf')
|
||||
expect(html).not.toContain('显示根目录文件')
|
||||
expect(html).toContain('aria-label="当前目录路径"')
|
||||
expect(html).not.toContain('第 1 / 1 页')
|
||||
expect(html).not.toContain('PP分类 · 不代表完整原始目录')
|
||||
expect(html).toContain('快照时间')
|
||||
expect(html).toContain('快照就绪')
|
||||
expect(html).toContain('上次刷新耗时 12秒')
|
||||
expect(html).toContain('实时刷新目录')
|
||||
expect(html).not.toContain('aria-label="处理策略01|产品总览与定位"')
|
||||
expect(html).not.toContain('递归作用于全部子目录')
|
||||
})
|
||||
it('shows current directory, discovered file counts and the estimate marker during refresh',()=>{
|
||||
const job:Job={id:'job-scan',type:'source.catalog.refresh',payload:{connection_id:'conn-1',stage:'scanning',progress:43,message:'正在扫描目录:已完成 125 个文件夹,待处理 55 个',processed:125,total:180,current_directory:'产品资料/CR系列',scanned_files:2438,estimated_total_files:5662,total_is_estimate:true},state:'running',priority:20,available_at:'2026-09-09T00:00:00Z',attempt:1,max_attempts:3,idempotency_key:'safe',created_at:'2026-09-09T00:00:00Z',updated_at:'2026-09-09T00:00:00Z'}
|
||||
const html=renderToStaticMarkup(<SourceCatalogBrowserView sources={[source]} selectedSource={source} page={page} loading={false} error={null} refreshJob={job} onSelectSource={vi.fn()} onOpenFolder={vi.fn()} onNavigateTo={vi.fn()} onBack={vi.fn()} onPageChange={vi.fn()} onRefresh={vi.fn()} />)
|
||||
expect(html).toContain('当前目录:产品资料/CR系列')
|
||||
expect(html).toContain('已发现 2438 份文件')
|
||||
expect(html).toContain('(估算)')
|
||||
})
|
||||
it('hides the running refresh to a compact pill that expands back on click without blocking browsing',()=>{
|
||||
const job:Job={id:'job-hide',type:'source.catalog.refresh',payload:{connection_id:'conn-1',stage:'scanning',progress:60,message:'正在扫描目录:已完成 1000 个文件夹',processed:1000,total:1339,current_directory:'产品资料/CR系列',scanned_files:2438},state:'running',priority:20,available_at:'2026-09-09T00:00:00Z',attempt:1,max_attempts:3,idempotency_key:'safe',created_at:'2026-09-09T00:00:00Z',updated_at:'2026-09-09T00:00:00Z'}
|
||||
const common={sources:[source],selectedSource:source,page,loading:false,error:null,refreshJob:job,onSelectSource:vi.fn(),onOpenFolder:vi.fn(),onNavigateTo:vi.fn(),onBack:vi.fn(),onPageChange:vi.fn(),onRefresh:vi.fn()}
|
||||
const full=renderToStaticMarkup(<SourceCatalogBrowserView {...common} refreshHidden={false} onToggleRefreshHidden={vi.fn()} />)
|
||||
expect(full).toContain('隐藏到后台')
|
||||
expect(full).toContain('实时快照进度')
|
||||
expect(full).toContain('产品资料/CR系列')
|
||||
const hidden=renderToStaticMarkup(<SourceCatalogBrowserView {...common} refreshHidden onToggleRefreshHidden={vi.fn()} />)
|
||||
expect(hidden).not.toContain('实时快照进度')
|
||||
expect(hidden).toContain('catalog-refresh-pill')
|
||||
expect(hidden).toContain('60%')
|
||||
expect(hidden).toContain('公司级技术支持知识库') // pill still names the source
|
||||
// browsing and annotation stay interactive in hidden mode (only a duplicate refresh is blocked)
|
||||
expect(hidden).toContain('aria-label="选择01|产品总览与定位"')
|
||||
expect(hidden).toContain('aria-label="选择根目录说明.pdf"')
|
||||
expect(hidden).toContain('全选当前页')
|
||||
expect(hidden).toContain('实时刷新中…')
|
||||
})
|
||||
it('announces failure safely and keeps old snapshot usable',()=>{
|
||||
const job:Job={id:'job-fail',type:'source.catalog.refresh',payload:{connection_id:'conn-1',stage:'failed',progress:0,message:'AList API Token 未配置,请联系管理员更新来源凭据;旧快照仍然保留',processed:0,total:0},state:'failed',priority:20,available_at:'2026-09-09T00:00:00Z',attempt:3,max_attempts:3,idempotency_key:'safe',created_at:'2026-09-09T00:00:00Z',updated_at:'2026-09-09T00:00:00Z'}
|
||||
const html=renderToStaticMarkup(<SourceCatalogBrowserView sources={[source]} selectedSource={source} page={page} loading={false} error={null} refreshJob={job} onSelectSource={vi.fn()} onOpenFolder={vi.fn()} onNavigateTo={vi.fn()} onBack={vi.fn()} onPageChange={vi.fn()} onRefresh={vi.fn()} />)
|
||||
expect(html).toContain('实时刷新失败')
|
||||
expect(html).toContain('刷新失败;旧快照仍然保留,目录浏览与标注不受影响。')
|
||||
expect(html).toContain('快照就绪')
|
||||
expect(html).toContain('01|产品总览与定位')
|
||||
})
|
||||
it('keeps the progress bar free of directory details when the scanner reports none',()=>{
|
||||
const job:Job={id:'job-plain',type:'source.catalog.refresh',payload:{connection_id:'conn-1',stage:'building',progress:80,message:'正在校验目录结构',processed:10,total:10},state:'running',priority:20,available_at:'2026-09-09T00:00:00Z',attempt:1,max_attempts:3,idempotency_key:'safe',created_at:'2026-09-09T00:00:00Z',updated_at:'2026-09-09T00:00:00Z'}
|
||||
const html=renderToStaticMarkup(<SourceCatalogBrowserView sources={[source]} selectedSource={source} page={page} loading={false} error={null} refreshJob={job} onSelectSource={vi.fn()} onOpenFolder={vi.fn()} onNavigateTo={vi.fn()} onBack={vi.fn()} onPageChange={vi.fn()} onRefresh={vi.fn()} />)
|
||||
expect(html).toContain('正在校验目录结构')
|
||||
expect(html).not.toContain('刷新明细')
|
||||
})
|
||||
it('uses durable background refresh progress and the current stage message',()=>{
|
||||
const job:Job={id:'job-refresh',type:'source.catalog.refresh',payload:{connection_id:'conn-1',stage:'scanning',progress:50,message:'正在扫描目录:已完成 50 个',processed:50,total:100},state:'running',priority:20,available_at:'2026-09-09T00:00:00Z',attempt:1,max_attempts:3,idempotency_key:'safe',created_at:'2026-09-09T00:00:00Z',updated_at:'2026-09-09T00:00:00Z'}
|
||||
const html=renderToStaticMarkup(<SourceCatalogBrowserView sources={[source]} selectedSource={source} page={page} loading={false} error={null} refreshJob={job} onSelectSource={vi.fn()} onOpenFolder={vi.fn()} onNavigateTo={vi.fn()} onBack={vi.fn()} onPageChange={vi.fn()} onRefresh={vi.fn()} />)
|
||||
expect(html).toContain('实时刷新中')
|
||||
expect(html).toContain('正在扫描目录:已完成 50 个')
|
||||
expect(html).toContain('value="50"')
|
||||
})
|
||||
it('uses clickable breadcrumbs and an explicit back action below the source root',()=>{
|
||||
const nested={...page,current:{...page.current,node_id:'folder-1',parent_node_id:'root-1',name:'01|产品总览与定位'},breadcrumbs:[...page.breadcrumbs,{node_id:'folder-1',name:'01|产品总览与定位'}]}
|
||||
const html=renderToStaticMarkup(<SourceCatalogBrowserView sources={[source]} selectedSource={source} page={nested} loading={false} error={null} onSelectSource={vi.fn()} onOpenFolder={vi.fn()} onNavigateTo={vi.fn()} onBack={vi.fn()} onPageChange={vi.fn()} onRefresh={vi.fn()} />)
|
||||
expect(html).toContain('aria-label="返回上一级"')
|
||||
expect(html).toContain('公司级技术支持知识库')
|
||||
expect(html).toContain('01|产品总览与定位')
|
||||
})
|
||||
it('shows policy as a read-only table state and offers top-level policy buttons',()=>{
|
||||
const nested={...page,current:{...page.current,node_id:'folder-1',parent_node_id:'root-1',name:'01|产品总览与定位'},breadcrumbs:[...page.breadcrumbs,{node_id:'folder-1',name:'01|产品总览与定位'}],items:[node('可入队.pdf','file','file-ready'),node('已知目录','folder','folder-known'),{...node('大小未知目录','folder','folder-unknown'),subtree_bytes:0},{...node('只有元数据.pdf','file','file-meta'),size_bytes:undefined,routable_count:0}],total:4}
|
||||
const html=renderToStaticMarkup(<SourceCatalogBrowserView sources={[source]} selectedSource={source} page={nested} loading={false} error={null} routingCapabilities={{internal_enabled:true,external_enabled:true}} onSelectSource={vi.fn()} onOpenFolder={vi.fn()} onNavigateTo={vi.fn()} onBack={vi.fn()} onPageChange={vi.fn()} onRefresh={vi.fn()} onRoute={vi.fn()} />)
|
||||
for(const text of ['名称','处理策略','全选当前页','对内','对外','禁止导入','禁止导入只保存期望策略;经“快照差异”确认后才会从测试知识库移除','aria-label="选择可入队.pdf"','大小未提供','已知合计 1.0 KB'])expect(html).toContain(text)
|
||||
for(const text of ['class="catalog-policy-actions"','class="internal-policy-button"','class="external-policy-button"','class="blocked-policy-button"','class="selected-count"'])expect(html).toContain(text)
|
||||
for(const text of ['操作人','判断原因','名称与处理策略','当前策略','选择策略','批量处理策略','应用策略','对内 + 对外','<select'])expect(html).not.toContain(text)
|
||||
expect(html).not.toContain('批量标注对内并入队')
|
||||
expect(html).not.toContain('已请求移除')
|
||||
expect(html).not.toContain('新增待确认计划')
|
||||
expect(html).not.toContain('批量标注对外并入队')
|
||||
expect(html).not.toContain('递归全选当前目录')
|
||||
})
|
||||
it('freezes the S6 batch annotation contract: exactly three policy buttons and current-page selection only',()=>{
|
||||
const nested={...page,current:{...page.current,node_id:'folder-1'},breadcrumbs:[...page.breadcrumbs,{node_id:'folder-1',name:'01|产品总览与定位'}],items:[node('可入队.pdf','file','file-ready'),node('已知目录','folder','folder-known')],total:2}
|
||||
const html=renderToStaticMarkup(<SourceCatalogBrowserView sources={[source]} selectedSource={source} page={nested} loading={false} error={null} routingCapabilities={{internal_enabled:true,external_enabled:true}} onSelectSource={vi.fn()} onOpenFolder={vi.fn()} onNavigateTo={vi.fn()} onBack={vi.fn()} onPageChange={vi.fn()} onRefresh={vi.fn()} onRoute={vi.fn()} />)
|
||||
// exactly three top-level policy buttons: 对内 / 对外 / 禁止导入 (docs/SOURCE_SCOPE_POLICY.md rules 4-6)
|
||||
expect((html.match(/class="[a-z-]+-policy-button"/g)||[]).length).toBe(3)
|
||||
// rule 2: only current-page select-all exists
|
||||
expect(html).toContain('全选当前页')
|
||||
expect(html).not.toContain('递归全选')
|
||||
// rule 1: both file and folder rows expose selection checkboxes
|
||||
expect(html).toContain('aria-label="选择可入队.pdf"')
|
||||
expect(html).toContain('aria-label="选择已知目录"')
|
||||
// rules 5-6: no batch entry for historical 对内 + 对外 or for unset state
|
||||
expect(html).not.toContain('对内 + 对外')
|
||||
expect(html).not.toContain('批量未选择')
|
||||
})
|
||||
it('lets an engineer select a directory without opening it',()=>{
|
||||
const html=renderToStaticMarkup(<SourceCatalogBrowserView sources={[source]} selectedSource={source} page={page} loading={false} error={null} onSelectSource={vi.fn()} onOpenFolder={vi.fn()} onNavigateTo={vi.fn()} onBack={vi.fn()} onPageChange={vi.fn()} onRefresh={vi.fn()} />)
|
||||
expect(html).toContain('aria-label="选择01|产品总览与定位"')
|
||||
})
|
||||
it('does not claim an empty source loaded when the request failed',()=>{
|
||||
const html=renderToStaticMarkup(<SourceCatalogBrowserView sources={[]} selectedSource={null} page={null} loading={false} error="加载失败" onSelectSource={vi.fn()} onOpenFolder={vi.fn()} onNavigateTo={vi.fn()} onBack={vi.fn()} onPageChange={vi.fn()} onRefresh={vi.fn()} />)
|
||||
expect(html).toContain('加载失败')
|
||||
expect(html).not.toContain('尚无来源目录')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,111 @@
|
||||
import { useContext,useEffect,useState } from 'react'
|
||||
import { fetchCatalogNodes,fetchCatalogRoutingCapabilities,fetchCatalogSnapshotNodes,fetchCatalogSnapshots,fetchCatalogSources,routeCatalogFiles } from './sourceCatalog'
|
||||
import type { CatalogNode,CatalogNodePage,CatalogPolicy,CatalogRoutingCapabilities,CatalogSnapshot,CatalogSource } from './sourceCatalog'
|
||||
import { SnapshotHistoryView } from './SnapshotHistory'
|
||||
import { triggerCatalogRefresh } from './sourceCatalog'
|
||||
import { fetchJobs } from './jobs'
|
||||
import type { Job } from './jobs'
|
||||
import { WorkspaceContextTabsSetter } from './workspaceContext'
|
||||
import './sourceCatalogBrowser.css'
|
||||
|
||||
const sourceLabels:Record<string,string>={dingtalk:'钉钉知识库',pp:'PP资料下载中心',alist:'AList文件源'}
|
||||
const bytes=(value:number)=>value>=1073741824?`${(value/1073741824).toFixed(1)} GB`:value>=1048576?`${(value/1048576).toFixed(1)} MB`:value>=1024?`${(value/1024).toFixed(1)} KB`:`${value} B`
|
||||
const duration=(milliseconds:number)=>milliseconds<=0?'未记录':milliseconds<1000?`${milliseconds}毫秒`:milliseconds<60000?`${Math.round(milliseconds/1000)}秒`:`${Math.floor(milliseconds/60000)}分${Math.round(milliseconds%60000/1000)}秒`
|
||||
const scope=(value:string)=>value==='internal'?'对内':value==='external'?'对外':value==='both'?'对内 + 对外':value==='blocked'?'禁止导入':value==='mixed'?'混合':'未选择'
|
||||
const progress=(node:CatalogNode)=>node.imported_count?`已解析 ${node.parsed_count} / 已导入 ${node.imported_count}`:'尚未导入'
|
||||
|
||||
interface ViewProps{
|
||||
sources:CatalogSource[];selectedSource:CatalogSource|null;page:CatalogNodePage|null;loading:boolean;error:string|null
|
||||
routingCapabilities?:CatalogRoutingCapabilities;routingMessage?:string;routingLoading?:boolean
|
||||
refreshJob?:Job|null
|
||||
onSelectSource:(source:CatalogSource)=>void;onOpenFolder:(node:CatalogNode)=>void;onNavigateTo:(nodeID:string)=>void;onBack:()=>void;onPageChange:(offset:number)=>void;onRefresh:()=>void;onRoute?:(nodeIDs:string[],policy:CatalogPolicy)=>Promise<boolean>
|
||||
history?:{open:boolean;snapshots:CatalogSnapshot[];active:CatalogSnapshot|null;page:CatalogNodePage|null;loading:boolean;error:string|null;onOpen:()=>void;onClose:()=>void;onOpenSnapshot:(snapshot:CatalogSnapshot)=>void;onOpenFolder:(snapshot:CatalogSnapshot,nodeID:string)=>void}
|
||||
refreshHidden?:boolean;onToggleRefreshHidden?:()=>void
|
||||
}
|
||||
export function SourceCatalogBrowserView({sources,selectedSource,page,loading,error,routingCapabilities={internal_enabled:false,external_enabled:false},routingMessage='',routingLoading=false,refreshJob=null,onSelectSource,onOpenFolder,onNavigateTo,onBack,onPageChange,onRefresh,onRoute=async()=>false,history,refreshHidden=false,onToggleRefreshHidden}:ViewProps){
|
||||
const [selectedIDs,setSelectedIDs]=useState<string[]>([])
|
||||
const [appliedPolicies,setAppliedPolicies]=useState<Record<string,CatalogPolicy>>({})
|
||||
const atSourceRoot=Boolean(page&&page.breadcrumbs.length===1)
|
||||
const visibleItems=page?.items||[]
|
||||
useEffect(()=>{setSelectedIDs([]);setAppliedPolicies({})},[selectedSource?.connection_id,page?.current.node_id])
|
||||
useEffect(()=>{if(routingMessage)setSelectedIDs([])},[routingMessage])
|
||||
const selectableNodes=visibleItems
|
||||
const selectedNodeIDs=selectedIDs
|
||||
const selectedCount=selectedIDs.length
|
||||
const routeReady=!routingLoading
|
||||
const policyEnabled=(policy:CatalogPolicy)=>policy==='blocked'||policy==='both'?(policy==='blocked'||routingCapabilities.internal_enabled&&routingCapabilities.external_enabled):policy==='internal'?routingCapabilities.internal_enabled:routingCapabilities.external_enabled
|
||||
const toggleNode=(id:string)=>setSelectedIDs(current=>current.includes(id)?current.filter(value=>value!==id):[...current,id])
|
||||
const applyPolicy=async(policy:CatalogPolicy)=>{if(!selectedNodeIDs.length)return;const changed=await onRoute(selectedNodeIDs,policy);if(changed)setAppliedPolicies(current=>({...current,...Object.fromEntries(selectedNodeIDs.map(id=>[id,policy]))}))}
|
||||
const refreshPayload=refreshJob?.payload&&typeof refreshJob.payload==='object'?refreshJob.payload as Record<string,unknown>:{}
|
||||
const refreshProgress=typeof refreshPayload.progress==='number'?refreshPayload.progress:0
|
||||
const refreshMessage=typeof refreshPayload.message==='string'?refreshPayload.message:'等待后台刷新'
|
||||
const refreshDirectory=typeof refreshPayload.current_directory==='string'&&refreshPayload.current_directory?refreshPayload.current_directory:''
|
||||
const refreshFiles=typeof refreshPayload.scanned_files==='number'&&refreshPayload.scanned_files>0?refreshPayload.scanned_files:0
|
||||
const refreshEstimate=refreshPayload.total_is_estimate===true
|
||||
const stageLabels:Record<string,string>={queued:'排队中',connecting:'连接来源',scanning:'扫描目录',building:'构建快照',activating:'写入快照',completed:'完成',failed:'失败'}
|
||||
const refreshStageLabel=typeof refreshPayload.stage==='string'?stageLabels[refreshPayload.stage]||refreshPayload.stage:'排队中'
|
||||
const pillSource=typeof refreshPayload.source_name==='string'?refreshPayload.source_name:''
|
||||
const refreshPillSource=pillSource||selectedSource?.name||''
|
||||
const refreshActive=refreshJob?.state==='pending'||refreshJob?.state==='running'||refreshJob?.state==='retry'
|
||||
return <main className="page-shell catalog-browser">
|
||||
<header className="hero compact"><div><h1>来源与目录</h1><p className="subtitle">各个知识源头的资料总览与标注</p></div><button onClick={onRefresh} disabled={loading||refreshActive}>{refreshActive?'实时刷新中…':'实时刷新目录'}</button></header>
|
||||
{error?<div className="error-banner" role="alert">{error}</div>:null}
|
||||
{refreshJob&&refreshActive&&refreshHidden?<button type="button" className="catalog-refresh-pill" aria-label="刷新进行中,点击展开" onClick={onToggleRefreshHidden}><span className={`pill-dot ${refreshJob.state}`} aria-hidden="true"/>后台刷新中 · {refreshPillSource} · {refreshProgress}%{refreshEstimate?'(估算)':''}</button>:null}
|
||||
{refreshJob&&!(refreshActive&&refreshHidden)?<><section className={`catalog-refresh-progress ${refreshJob.state}`} aria-label="实时快照进度"><div><strong>{refreshActive?'实时刷新中':refreshJob.state==='completed'?'实时快照已完成':'实时刷新失败'}</strong><span>{selectedSource?selectedSource.name+' · ':''}{refreshStageLabel}</span><span>{refreshMessage}</span></div><progress max="100" value={refreshProgress}/><small>{refreshProgress}%{refreshEstimate?'(估算)':''} · 后台运行,可以切换页面</small>{refreshActive&&onToggleRefreshHidden?<button type="button" className="catalog-refresh-hide" onClick={onToggleRefreshHidden}>隐藏到后台</button>:null}</section>{refreshActive&&(refreshDirectory||refreshFiles)?<div className="catalog-refresh-detail" aria-label="刷新明细">{refreshDirectory?<span>当前目录:{refreshDirectory}</span>:null}{refreshFiles?<span>已发现 {refreshFiles} 份文件</span>:null}</div>:null}{refreshJob.state==='failed'?<p className="catalog-refresh-failed-note" role="status">刷新失败;旧快照仍然保留,目录浏览与标注不受影响。</p>:null}</>:null}
|
||||
<div className="catalog-layout">
|
||||
<aside className="catalog-sources" aria-label="内容来源">
|
||||
<h2>内容来源</h2>
|
||||
{sources.map(source=><button key={source.connection_id} className={selectedSource?.connection_id===source.connection_id?'catalog-source active':'catalog-source'} onClick={()=>onSelectSource(source)}><span><b>{source.name}</b><small>{sourceLabels[source.source_type]} · 本地只读快照</small></span><strong>{source.file_count}</strong></button>)}
|
||||
{!loading&&!error&&!sources.length?<div className="empty-state">尚无来源目录。</div>:null}
|
||||
</aside>
|
||||
<section className="catalog-content">
|
||||
{selectedSource&&page?<>
|
||||
<div className="catalog-pathbar" aria-label="当前目录路径">
|
||||
<button type="button" className="catalog-back-button" aria-label="返回上一级" disabled={page.breadcrumbs.length<2} onClick={onBack}>←</button>
|
||||
<nav aria-label="目录面包屑">{page.breadcrumbs.map((crumb,index)=><span key={crumb.node_id}>{index>0?<i aria-hidden="true">/</i>:null}<button type="button" className={index===page.breadcrumbs.length-1?'current':''} disabled={index===page.breadcrumbs.length-1} onClick={()=>onNavigateTo(crumb.node_id)}>{crumb.name}</button></span>)}</nav>
|
||||
</div>
|
||||
<div className="catalog-summary"><div><strong>{page.current.name}</strong><small>{selectedSource.snapshot_only?'本地只读快照,不代表实时连接':'实时目录'}</small></div><span>{atSourceRoot?`第一层目录 ${page.items.filter(node=>node.node_type==='folder').length}`:`当前子项 ${page.total}`}</span><span>含所有子目录文件 {page.current.subtree_file_count}</span><span>总大小 {bytes(page.current.subtree_bytes)}</span></div>
|
||||
|
||||
{visibleItems.length?<section className="catalog-routing">
|
||||
<div className="routing-actions">
|
||||
<label className="routing-check"><input type="checkbox" checked={selectableNodes.length>0&&selectableNodes.every(node=>selectedIDs.includes(node.node_id))} disabled={!selectableNodes.length} onChange={event=>setSelectedIDs(event.target.checked?selectableNodes.map(node=>node.node_id):[])} />全选当前页</label>
|
||||
<div className="catalog-policy-actions"><button className="internal-policy-button" disabled={!routeReady||!selectedNodeIDs.length||!policyEnabled('internal')} onClick={()=>void applyPolicy('internal')}>对内</button><button className="external-policy-button" disabled={!routeReady||!selectedNodeIDs.length||!policyEnabled('external')} onClick={()=>void applyPolicy('external')}>对外</button><div className="blocked-policy-stack"><button className="blocked-policy-button" disabled={!routeReady||!selectedNodeIDs.length} onClick={()=>void applyPolicy('blocked')}>禁止导入</button><small className="selected-count">已选 {selectedCount} 项</small></div></div>
|
||||
</div>
|
||||
<small className="blocked-policy-note">禁止导入只保存期望策略;经“快照差异”确认后才会从测试知识库移除,不删除来源文件,也不操作生产知识库。</small>
|
||||
{routingMessage?<p role="status">{routingMessage}</p>:null}
|
||||
</section>:null}
|
||||
{visibleItems.length?<div className="catalog-table-wrap"><table className="catalog-table"><thead><tr><th>名称</th><th>类型</th><th>处理策略</th><th>文件数量</th><th>导入与解析</th><th>大小</th><th>更新时间</th></tr></thead><tbody>{visibleItems.map(node=>{const visibility=appliedPolicies[node.node_id]||node.visibility;const size=node.node_type==='folder'?(node.subtree_bytes>0?`已知合计 ${bytes(node.subtree_bytes)}`:'大小未提供'):typeof node.size_bytes==='number'?bytes(node.size_bytes):'大小未提供';return <tr key={node.node_id}><td>{node.node_type==='folder'?<div className="catalog-node-control"><input type="checkbox" aria-label={`选择${node.name}`} checked={selectedIDs.includes(node.node_id)} onChange={()=>toggleNode(node.node_id)} /><button className="catalog-name" onClick={()=>onOpenFolder(node)}><span aria-hidden="true">📁</span>{node.name}</button></div>:<label className="catalog-file"><input type="checkbox" aria-label={`选择${node.name}`} checked={selectedIDs.includes(node.node_id)} onChange={()=>toggleNode(node.node_id)} /><span aria-hidden="true">📄</span>{node.name}</label>}</td><td>{node.node_type==='folder'?'文件夹':'文件'}</td><td><div className="catalog-policy-cell"><span className={`scope-badge ${visibility}`}>{scope(visibility)}</span></div></td><td>{node.node_type==='folder'?`${node.subtree_file_count} 份`:'—'}</td><td><span>{progress(node)}</span>{node.active_count?<small>处理中 {node.active_count}</small>:null}{node.failed_count?<small className="problem-text">失败 {node.failed_count}</small>:null}</td><td>{size}</td><td>{node.modified_at?new Date(node.modified_at).toLocaleString('zh-CN',{hour12:false}):'—'}</td></tr>})}</tbody></table></div>:<div className="empty-state">当前目录为空。</div>}
|
||||
{page.total>page.limit?<div className="pagination"><span>第 {Math.floor(page.offset/page.limit)+1} / {Math.max(1,Math.ceil(page.total/page.limit))} 页</span><div><button disabled={page.offset===0||loading} onClick={()=>onPageChange(Math.max(0,page.offset-page.limit))}>上一页</button><button disabled={page.offset+page.limit>=page.total||loading} onClick={()=>onPageChange(page.offset+page.limit)}>下一页</button></div></div>:null}
|
||||
<div className="snapshot-timestamp"><span>快照就绪</span><span>快照时间:{new Date(selectedSource.observed_at).toLocaleString('zh-CN',{hour12:false})}</span><span>上次刷新耗时 {duration(selectedSource.last_refresh_duration_ms)}</span>{history?<button type="button" className="catalog-history-button" onClick={history.onOpen}>{history.open?'返回当前目录':'快照历史'}</button>:null}</div>
|
||||
{history&&history.open?<SnapshotHistoryView snapshots={history.snapshots} active={history.active} page={history.page} loading={history.loading} error={history.error} onClose={history.onClose} onOpenSnapshot={history.onOpenSnapshot} onOpenFolder={history.onOpenFolder} />:null}
|
||||
</>:loading?<div className="empty-state">正在读取第一层目录…</div>:!error?<div className="empty-state">请选择一个内容来源。</div>:null}
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
}
|
||||
|
||||
export function SourceCatalogBrowser(){
|
||||
const [sources,setSources]=useState<CatalogSource[]>([]);const [selected,setSelected]=useState<CatalogSource|null>(null);const [parentID,setParentID]=useState('');const [page,setPage]=useState<CatalogNodePage|null>(null);const [offset,setOffset]=useState(0);const [revision,setRevision]=useState(0);const [loading,setLoading]=useState(true);const [error,setError]=useState<string|null>(null);const setContextTabs=useContext(WorkspaceContextTabsSetter)
|
||||
const [routingCapabilities,setRoutingCapabilities]=useState<CatalogRoutingCapabilities>({internal_enabled:false,external_enabled:false});const [routingMessage,setRoutingMessage]=useState('');const [routingLoading,setRoutingLoading]=useState(false)
|
||||
const [refreshJob,setRefreshJob]=useState<Job|null>(null)
|
||||
const [historySnapshots,setHistorySnapshots]=useState<CatalogSnapshot[]>([]);const [historyActive,setHistoryActive]=useState<CatalogSnapshot|null>(null);const [historyPage,setHistoryPage]=useState<CatalogNodePage|null>(null);const [historyLoading,setHistoryLoading]=useState(false);const [historyError,setHistoryError]=useState<string|null>(null);const [historyOpen,setHistoryOpen]=useState(false)
|
||||
const [refreshHidden,setRefreshHidden]=useState(false)
|
||||
|
||||
const openHistory=async()=>{if(!selected||historyLoading)return;if(historyOpen){closeHistory();return}setHistoryOpen(true);setHistoryLoading(true);setHistoryError(null);try{const result=await fetchCatalogSnapshots(selected.connection_id,20,0);setHistorySnapshots(result.items);const head=result.items.find(item=>item.is_head)||result.items[0]||null;setHistoryActive(head);if(head)setHistoryPage(await fetchCatalogSnapshotNodes(selected.connection_id,head.snapshot_id,head.root_node_id));else setHistoryPage(null)}catch(cause){setHistoryError(cause instanceof Error?cause.message:'加载快照历史失败')}finally{setHistoryLoading(false)}}
|
||||
const openHistorySnapshot=async(snapshot:CatalogSnapshot)=>{if(!selected||historyLoading)return;setHistoryLoading(true);setHistoryError(null);try{setHistoryActive(snapshot);setHistoryPage(await fetchCatalogSnapshotNodes(selected.connection_id,snapshot.snapshot_id,snapshot.root_node_id))}catch(cause){setHistoryError(cause instanceof Error?cause.message:'加载历史快照目录失败')}finally{setHistoryLoading(false)}}
|
||||
const openHistoryFolder=async(snapshot:CatalogSnapshot,nodeID:string)=>{if(!selected||historyLoading)return;setHistoryLoading(true);setHistoryError(null);try{setHistoryPage(await fetchCatalogSnapshotNodes(selected.connection_id,snapshot.snapshot_id,nodeID))}catch(cause){setHistoryError(cause instanceof Error?cause.message:'加载历史快照目录失败')}finally{setHistoryLoading(false)}}
|
||||
const closeHistory=()=>{setHistoryOpen(false);setHistoryActive(null);setHistoryPage(null);setHistoryError(null)}
|
||||
|
||||
useEffect(()=>{const controller=new AbortController();setLoading(true);void fetchCatalogSources(controller.signal).then(result=>{if(controller.signal.aborted)return;setSources(result);setSelected(current=>current&&result.find(source=>source.connection_id===current.connection_id)||result[0]||null);setParentID(current=>current||result[0]?.root_node_id||'');setError(null)}).catch(cause=>{if(!controller.signal.aborted)setError(cause instanceof Error?cause.message:'加载来源目录失败')}).finally(()=>{if(!controller.signal.aborted)setLoading(false)});return()=>controller.abort()},[revision])
|
||||
useEffect(()=>{if(!selected||!parentID)return;const controller=new AbortController();setLoading(true);void fetchCatalogNodes(selected.connection_id,parentID,50,offset,controller.signal).then(result=>{if(!controller.signal.aborted){setPage(result);setError(null)}}).catch(cause=>{if(!controller.signal.aborted)setError(cause instanceof Error?cause.message:'加载目录失败')}).finally(()=>{if(!controller.signal.aborted)setLoading(false)});return()=>controller.abort()},[selected,parentID,offset,revision])
|
||||
|
||||
useEffect(()=>{const controller=new AbortController();void fetchCatalogRoutingCapabilities(controller.signal).then(setRoutingCapabilities).catch(()=>setRoutingCapabilities({internal_enabled:false,external_enabled:false}));return()=>controller.abort()},[revision])
|
||||
useEffect(()=>{if(!selected)return;const controller=new AbortController();void fetchJobs(controller.signal).then(items=>{if(controller.signal.aborted)return;const match=items.find(job=>job.type==='source.catalog.refresh'&&job.payload&&typeof job.payload==='object'&&(job.payload as Record<string,unknown>).connection_id===selected.connection_id);setRefreshJob(match||null)}).catch(()=>undefined);return()=>controller.abort()},[selected])
|
||||
useEffect(()=>{if(!refreshJob||!['pending','running','retry'].includes(refreshJob.state))return;const timer=window.setTimeout(()=>void fetchJobs().then(items=>{const current=items.find(job=>job.id===refreshJob.id);if(!current)return;setRefreshJob(previous=>{if(previous?.state!=='completed'&¤t.state==='completed')setRevision(value=>value+1);return current})}).catch(()=>undefined),750);return()=>window.clearTimeout(timer)},[refreshJob])
|
||||
useEffect(()=>{if(!selected||!page){setContextTabs([]);return}setContextTabs(page.breadcrumbs.map(item=>({key:item.node_id,label:item.name,onActivate:()=>{setParentID(item.node_id);setOffset(0)}})));return()=>setContextTabs([])},[selected,page,setContextTabs])
|
||||
const selectSource=(source:CatalogSource)=>{setSelected(source);setParentID(source.root_node_id);setOffset(0);setPage(null);setRefreshJob(null);closeHistory()}
|
||||
const back=()=>{if(!page||page.breadcrumbs.length<2)return;setParentID(page.breadcrumbs[page.breadcrumbs.length-2].node_id);setOffset(0)}
|
||||
const route=async(nodeIDs:string[],policy:CatalogPolicy):Promise<boolean>=>{if(!selected||routingLoading)return false;setRoutingLoading(true);setRoutingMessage('');try{const result=await routeCatalogFiles({connection_id:selected.connection_id,node_ids:nodeIDs,policy,operator_ref:'web-console',reason:`目录页策略:${scope(policy)}`});setRoutingMessage(`策略已保存 ${result.selected_files} 份;可处理 ${result.routable_files} 份;内容未校验 ${result.hash_unknown_files} 份;未关联来源文件 ${result.unbound_files} 份;其余 ${result.unavailable_files} 份暂不可处理。变化需到“快照差异”确认后才会进入解析队列。`);setRevision(value=>value+1);return true}catch(cause){setRoutingMessage(cause instanceof Error?cause.message:'文件处理失败');return false}finally{setRoutingLoading(false)}}
|
||||
const refresh=async()=>{if(!selected||refreshJob&&['pending','running','retry'].includes(refreshJob.state))return;setError(null);try{setRefreshJob(await triggerCatalogRefresh(selected.connection_id))}catch(cause){setError(cause instanceof Error?cause.message:'启动实时刷新失败')}}
|
||||
return <SourceCatalogBrowserView sources={sources} selectedSource={selected} page={page} loading={loading} error={error} routingCapabilities={routingCapabilities} routingMessage={routingMessage} routingLoading={routingLoading} refreshJob={refreshJob} onSelectSource={source=>{setRoutingMessage('');selectSource(source)}} onOpenFolder={node=>{setRoutingMessage('');setParentID(node.node_id);setOffset(0)}} onNavigateTo={nodeID=>{setRoutingMessage('');setParentID(nodeID);setOffset(0)}} onBack={back} onPageChange={setOffset} onRefresh={()=>void refresh()} onRoute={(nodeIDs,visibility)=>route(nodeIDs,visibility)} history={{open:historyOpen,snapshots:historySnapshots,active:historyActive,page:historyPage,loading:historyLoading,error:historyError,onOpen:()=>void openHistory(),onClose:closeHistory,onOpenSnapshot:snapshot=>void openHistorySnapshot(snapshot),onOpenFolder:(snapshot,nodeID)=>void openHistoryFolder(snapshot,nodeID)}} refreshHidden={refreshHidden} onToggleRefreshHidden={()=>setRefreshHidden(value=>!value)} />
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe,expect,it,vi } from 'vitest'
|
||||
import { SourceLinkManagerView } from './SourceLinkManager'
|
||||
import type { CatalogSource } from './sourceCatalog'
|
||||
const sources:CatalogSource[]=[
|
||||
{connection_id:'ding',source_type:'dingtalk',name:'公司级技术支持知识库',root_node_id:'r1',folder_count:8,file_count:3468,observed_at:'2026-09-08T00:00:00Z',snapshot_only:true,snapshot_status:'ready',last_refresh_duration_ms:0},
|
||||
{connection_id:'pp',source_type:'pp',name:'PP资料下载中心',root_node_id:'r2',folder_count:64,file_count:613,observed_at:'2026-09-08T00:00:00Z',snapshot_only:true,snapshot_status:'ready',last_refresh_duration_ms:0},
|
||||
{connection_id:'alist',source_type:'alist',name:'国内工业',root_node_id:'r3',folder_count:1688,file_count:4880,observed_at:'2026-09-08T00:00:00Z',snapshot_only:true,snapshot_status:'ready',last_refresh_duration_ms:0},
|
||||
]
|
||||
describe('SourceLinkManagerView',()=>{
|
||||
it('shows understandable URL credential and login fields without accepting real secrets locally',()=>{
|
||||
const html=renderToStaticMarkup(<SourceLinkManagerView sources={sources} selected={sources[0]} validated={false} loading={false} error={null} onSelect={vi.fn()} onValidate={vi.fn()} onRefresh={vi.fn()} />)
|
||||
for(const text of ['来源链接','本地模拟配置','公司级技术支持知识库','PP资料下载中心','国内工业','知识库链接','认证方式','专用浏览器扫码登录','Key或Token','本地模拟阶段不接收真实Key','模拟登录并验证目录','不保存真实Key'])expect(html).toContain(text)
|
||||
expect(html).not.toContain('secret_ref')
|
||||
expect(html).not.toContain('base_url')
|
||||
})
|
||||
it('separates an AList site address from its starting directory and labels simulated status honestly',()=>{
|
||||
const html=renderToStaticMarkup(<SourceLinkManagerView sources={sources} selected={sources[2]} validated={false} loading={false} error={null} onSelect={vi.fn()} onValidate={vi.fn()} onRefresh={vi.fn()} />)
|
||||
for(const text of ['AList站点地址','起始目录','/国内工业','模拟验证待执行','不下载文件内容,只读取目录和元数据'])expect(html).toContain(text)
|
||||
expect(html).not.toContain('实时连接待验证')
|
||||
})
|
||||
it('does not show a successful zero-source state after errors',()=>{
|
||||
const html=renderToStaticMarkup(<SourceLinkManagerView sources={[]} selected={null} validated={false} loading={false} error="加载失败" onSelect={vi.fn()} onValidate={vi.fn()} onRefresh={vi.fn()} />)
|
||||
expect(html).toContain('加载失败');expect(html).not.toContain('尚无来源链接')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,35 @@
|
||||
import { useContext,useEffect,useState } from 'react'
|
||||
import { fetchCatalogSources } from './sourceCatalog'
|
||||
import type { CatalogSource } from './sourceCatalog'
|
||||
import { WorkspaceContextTabsSetter } from './workspaceContext'
|
||||
import './sourceLinkManager.css'
|
||||
const typeLabel={dingtalk:'钉钉知识库',pp:'PP资料下载中心',alist:'AList文件源'}
|
||||
const authLabel={dingtalk:'专用浏览器扫码登录',pp:'公开访问,无需Key',alist:'只读Token'}
|
||||
const actionLabel={dingtalk:'模拟登录并验证目录',pp:'模拟验证公开目录',alist:'模拟验证只读Token'}
|
||||
const placeholder={dingtalk:'粘贴钉钉知识库网页链接(模拟)',pp:'粘贴PP资料下载中心链接(模拟)',alist:'例如:https://alist.example.com(模拟)'}
|
||||
const linkLabel={dingtalk:'知识库链接',pp:'资料中心地址',alist:'AList站点地址'}
|
||||
interface Props{sources:CatalogSource[];selected:CatalogSource|null;validated:boolean;loading:boolean;error:string|null;onSelect:(source:CatalogSource)=>void;onValidate:()=>void;onRefresh:()=>void}
|
||||
export function SourceLinkManagerView({sources,selected,validated,loading,error,onSelect,onValidate,onRefresh}:Props){
|
||||
const [link,setLink]=useState('')
|
||||
return <main className="page-shell source-link-manager">
|
||||
<header className="hero compact"><div><p className="eyebrow">连接配置</p><h1>来源链接</h1><p className="subtitle">配置钉钉、PP和AList的入口、认证方式及目录验证。</p></div><button onClick={onRefresh} disabled={loading}>{loading?'刷新中…':'刷新来源'}</button></header>
|
||||
{error?<div className="error-banner" role="alert">{error}</div>:null}
|
||||
<div className="simulation-banner"><strong>本地模拟配置</strong><span>使用真实来源名称和快照数量,但不连接登录服务、不保存真实Key。</span></div>
|
||||
<div className="source-link-layout">
|
||||
<aside className="source-link-list"><h2>内容来源</h2>{sources.map(source=><button className={selected?.connection_id===source.connection_id?'active':''} key={source.connection_id} onClick={()=>{setLink('');onSelect(source)}}><span><b>{source.name}</b><small>{typeLabel[source.source_type]}</small></span><strong>{source.file_count}份</strong></button>)}{!loading&&!error&&!sources.length?<div className="empty-state">尚无来源链接。</div>:null}</aside>
|
||||
<section className="source-link-editor">{selected?<><div className="source-link-title"><div><h2>{selected.name}</h2><span>{typeLabel[selected.source_type]} · 本地只读快照</span></div><span className="connection-unverified">模拟验证待执行</span></div>
|
||||
<div className="source-link-fields"><label>{linkLabel[selected.source_type]}<input value={link} onChange={event=>setLink(event.target.value)} placeholder={placeholder[selected.source_type]} /></label><label>认证方式<input value={authLabel[selected.source_type]} readOnly /></label><label>Key或Token<input value="" disabled placeholder="本地模拟阶段不接收真实Key" /></label><label>起始目录<input value={selected.source_type==='alist'?`/${selected.name}`:selected.name} readOnly /></label></div>
|
||||
<div className="source-link-boundary"><b>当前快照</b><span>文件 {selected.file_count}</span><span>目录 {selected.folder_count}</span><span>不下载文件内容,只读取目录和元数据</span><span>不执行上传、移动、重命名或删除</span></div>
|
||||
<button className="validate-source-link" onClick={onValidate}>{actionLabel[selected.source_type]}</button>
|
||||
{validated?<div className="validation-results" aria-label="模拟验证结果"><div><span>网络连接</span><b>模拟通过</b></div><div><span>登录或Token</span><b>模拟通过</b></div><div><span>根目录</span><b>模拟通过</b></div><div><span>读取第一层目录</span><b>模拟通过</b></div><div><span>只读边界</span><b>模拟通过</b></div><small>以上只是本地交互模拟;迁移到测试服务器后才执行真实验证。</small></div>:null}
|
||||
<p className="credential-note">真实模式下,新凭据先验证,成功后才替换旧凭据;网页永远不能读取已保存Key。</p>
|
||||
</>:loading?<div className="empty-state">正在加载来源…</div>:null}</section>
|
||||
</div>
|
||||
</main>
|
||||
}
|
||||
export function SourceLinkManager(){
|
||||
const [sources,setSources]=useState<CatalogSource[]>([]);const [selected,setSelected]=useState<CatalogSource|null>(null);const [validated,setValidated]=useState(false);const [loading,setLoading]=useState(true);const [error,setError]=useState<string|null>(null);const [revision,setRevision]=useState(0);const setContextTabs=useContext(WorkspaceContextTabsSetter)
|
||||
useEffect(()=>{const controller=new AbortController();setLoading(true);void fetchCatalogSources(controller.signal).then(result=>{if(!controller.signal.aborted){setSources(result);setSelected(current=>current&&result.find(item=>item.connection_id===current.connection_id)||result[0]||null);setError(null)}}).catch(cause=>{if(!controller.signal.aborted)setError(cause instanceof Error?cause.message:'加载来源链接失败')}).finally(()=>{if(!controller.signal.aborted)setLoading(false)});return()=>controller.abort()},[revision])
|
||||
useEffect(()=>{setContextTabs(selected?[{key:selected.connection_id,label:selected.name,onActivate:()=>undefined}]:[]);return()=>setContextTabs([])},[selected,setContextTabs])
|
||||
return <SourceLinkManagerView sources={sources} selected={selected} validated={validated} loading={loading} error={error} onSelect={source=>{setSelected(source);setValidated(false)}} onValidate={()=>setValidated(true)} onRefresh={()=>{setValidated(false);setRevision(value=>value+1)}} />
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe,expect,it,vi } from 'vitest'
|
||||
import { SystemSettingsView, visibleSaveMessage } from './SystemSettings'
|
||||
import type { MonitorOverview } from './monitor'
|
||||
import type { CatalogSource } from './sourceCatalog'
|
||||
import type { UISettings } from './uiSettings'
|
||||
import type { SourceConnectionListItem } from './sourceConnections'
|
||||
const monitor:MonitorOverview={mode:'simulation',simulated:true,observed_at:'2026-09-08T12:00:00Z',host:{cpu_percent:42,memory_used_bytes:1,memory_total_bytes:2,disk_used_bytes:1,disk_total_bytes:2,gpu_state:'unknown',gpu_detail:'未接入真实GPU监控',simulated:true},services:[{key:'mineru',name:'MinerU',state:'healthy',detail:'模拟',latency_ms:1,observed_at:'2026-09-08T12:00:00Z',simulated:true}],knowledge_bases:[],health:[{key:'mineru',name:'MinerU',liveness:'up',readiness:'blocked',reason:'服务可达但容量已满(429),暂时不可接单',latency_ms:30,observed_at:'2026-09-08T12:00:00Z',last_success_at:'2026-09-08T11:59:00Z',consecutive_failures:2,configured:true,applicable:true}]}
|
||||
const sources:CatalogSource[]=[{connection_id:'ding-1',source_type:'dingtalk',name:'公司级技术支持知识库',root_node_id:'root-1',folder_count:1079,file_count:3444,observed_at:'2026-09-09T09:30:32Z',snapshot_only:true,snapshot_status:'ready',last_refresh_duration_ms:0}]
|
||||
const connections:SourceConnectionListItem[]=[{id:'conn-ding',source_type:'dingtalk',name:'公司级技术支持知识库',enabled:true,schedule_configured:true,health_status:'healthy',item_count:3444,updated_at:'2026-09-09T09:30:32Z',next_refresh_at:'2026-09-12T10:00:00Z'},{id:'conn-man',source_type:'manual',name:'本地手工验收',enabled:false,schedule_configured:false,health_status:'unknown',item_count:5,updated_at:'2026-09-09T09:30:32Z',next_refresh_at:null}]
|
||||
const settings:UISettings={id:'settings-default',state:'active',document_refresh_seconds:15,resource_refresh_seconds:30,stalled_after_seconds:1800,finalizing_after_seconds:7200,updated_by:'system:migration',created_at:'2026-09-10T08:00:00Z',activated_at:'2026-09-10T08:00:00Z',retired_at:null,error_code:''}
|
||||
describe('SystemSettingsView',()=>{
|
||||
it('separates document-engineer settings from locked administrator and production controls',()=>{
|
||||
const html=renderToStaticMarkup(<SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={settings} productionEnabled={false} routingCapabilities={{internal_enabled:true,external_enabled:true}} loading={false} saving={false} error={null} saveMessage="刷新与告警参数已验证并启用:文档15秒、资源30秒、停滞30分钟、finalizing 2小时" onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} />)
|
||||
for(const text of ['系统设置','数据源配置','服务配置','存储与备份','刷新策略','设置服务已启用','当前活动版本','公司级技术支持知识库','钉钉知识库','认证方式','端点与凭据','文档工程师可调整','管理员设置已锁定'])expect(html).toContain(text)
|
||||
const servicesHtml=renderToStaticMarkup(<SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={settings} productionEnabled={false} routingCapabilities={{internal_enabled:true,external_enabled:true}} loading={false} saving={false} error={null} saveMessage={null} onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} initialSection="services" />)
|
||||
for(const text of ['测试 WeKnora','生产 WeKnora','MinerU','Embedding'])expect(servicesHtml).toContain(text)
|
||||
const storageHtml=renderToStaticMarkup(<SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={settings} productionEnabled={false} routingCapabilities={{internal_enabled:true,external_enabled:true}} loading={false} saving={false} error={null} saveMessage={null} onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} initialSection="storage" />)
|
||||
expect(storageHtml).toContain('生产发布请求')
|
||||
expect(storageHtml).toContain('仅保存凭据引用,不可回读')
|
||||
const refreshHtml=renderToStaticMarkup(<SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={settings} productionEnabled={false} routingCapabilities={{internal_enabled:true,external_enabled:true}} loading={false} saving={false} error={null} saveMessage="刷新与告警参数已验证并启用:文档15秒、资源30秒、停滞30分钟、finalizing 2小时" onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} initialSection="refresh" />)
|
||||
for(const text of ['刷新与告警参数已验证并启用','停滞30分钟','finalizing 2小时','文档状态刷新间隔','15秒','解析停滞判定','30分钟','保存并应用刷新与告警参数'])expect(refreshHtml).toContain(text)
|
||||
expect(visibleSaveMessage('已保存',true)).toBeNull();expect(visibleSaveMessage('已保存',false)).toBe('已保存')
|
||||
expect(html).not.toContain('本地模拟');expect(html).not.toContain('保存模拟设置')
|
||||
for(const forbidden of ['DATABASE_URL','RELEASE_CONFIG_FILE','API Key明文','secret_ref'])expect(html).not.toContain(forbidden)
|
||||
// P10 dual-state matrix: reachable-but-not-workable must be explicit (services section).
|
||||
expect(servicesHtml).toContain('可达 · 不可接单')
|
||||
expect(servicesHtml).toContain('服务可达但容量已满(429)')
|
||||
expect(servicesHtml).toContain('连续失败2次')
|
||||
expect(servicesHtml).toContain('PostgreSQL')
|
||||
expect(servicesHtml).toContain('对内解析队列:已配置')
|
||||
expect(servicesHtml).toContain('对外解析队列:已配置')
|
||||
// V1: left-nav section controls, per-source schedule editing, danger modal & history affordances.
|
||||
expect(html).toContain('settings-nav')
|
||||
expect(html).toContain('下次自动刷新')
|
||||
expect(html).toContain('仅手动刷新')
|
||||
expect(html).toContain('查看修订历史')
|
||||
expect(html).toContain('保存并启用调度')
|
||||
expect(html).toContain('停用来源')
|
||||
expect(html).toContain('本地手工导入来源不支持定时刷新')
|
||||
// dead buttons removed
|
||||
expect(html).not.toContain('添加内容源')
|
||||
expect(html).not.toContain('管理员编辑')
|
||||
})
|
||||
it('does not show healthy simulation when the settings data failed to load',()=>{
|
||||
const html=renderToStaticMarkup(<SystemSettingsView sources={[]} connections={[]} monitor={null} settings={null} productionEnabled={false} routingCapabilities={{internal_enabled:false,external_enabled:false}} loading={false} saving={false} error="加载失败" saveMessage={null} onSave={vi.fn()} onSourcesChanged={vi.fn()} onRefresh={vi.fn()} />)
|
||||
expect(html).toContain('加载失败');expect(html).not.toContain('模拟运行中')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,222 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
|
||||
import { fetchMonitorOverview } from './monitor'
|
||||
import type { MonitorOverview } from './monitor'
|
||||
import { fetchReleaseCapabilities } from './reviewRelease'
|
||||
import { fetchCatalogRoutingCapabilities, fetchCatalogSources } from './sourceCatalog'
|
||||
import type { CatalogRoutingCapabilities, CatalogSource } from './sourceCatalog'
|
||||
import { activateSourceSettingsRevision, createSourceSettingsRevision, fetchSourceConnectionList, fetchSourceSettingsRevisions } from './sourceConnections'
|
||||
import type { SourceConnectionListItem, SourceSettingsRevision } from './sourceConnections'
|
||||
import { activateUISettings, createUISettingsCandidate, fetchActiveUISettings } from './uiSettings'
|
||||
import type { UISettings, UISettingsCandidateInput } from './uiSettings'
|
||||
import './systemSettings.css'
|
||||
|
||||
interface Props {
|
||||
sources: CatalogSource[]
|
||||
connections: SourceConnectionListItem[]
|
||||
monitor: MonitorOverview | null
|
||||
settings: UISettings | null
|
||||
productionEnabled: boolean
|
||||
routingCapabilities: CatalogRoutingCapabilities
|
||||
loading: boolean
|
||||
saving: boolean
|
||||
error: string | null
|
||||
saveMessage: string | null
|
||||
onSave: (input: UISettingsCandidateInput) => void
|
||||
onSourcesChanged: () => void
|
||||
onRefresh: () => void
|
||||
initialSection?: SectionKey
|
||||
}
|
||||
|
||||
type SectionKey = 'sources' | 'services' | 'storage' | 'refresh'
|
||||
|
||||
const sections: { key: SectionKey; label: string }[] = [
|
||||
{ key: 'sources', label: '数据源配置' },
|
||||
{ key: 'services', label: '服务配置' },
|
||||
{ key: 'storage', label: '存储与备份' },
|
||||
{ key: 'refresh', label: '刷新策略' },
|
||||
]
|
||||
|
||||
const sourceTypeLabels: Record<string, string> = { dingtalk: '钉钉知识库', pp: 'PP 资料下载中心', alist: 'AList 文件源', manual: '本地手工导入' }
|
||||
const sourceAuthLabels: Record<string, string> = { dingtalk: '专用浏览器扫码会话', pp: '公开只读访问', alist: '直连 API Token', manual: '离线导入,无在线认证' }
|
||||
const secondsLabel = (value: number) => value < 60 ? `${value}秒` : value < 3600 ? `${value / 60}分钟` : `${value / 3600}小时`
|
||||
export const visibleSaveMessage = (message: string | null, dirty: boolean) => dirty ? null : message
|
||||
|
||||
const intervalChoices: { value: number; label: string }[] = [
|
||||
{ value: 0, label: '仅手动刷新' },
|
||||
{ value: 3600, label: '每小时' },
|
||||
{ value: 21600, label: '每6小时' },
|
||||
{ value: 86400, label: '每24小时' },
|
||||
]
|
||||
|
||||
function formatHorizon(value: string | null): string {
|
||||
if (!value) return '仅手动刷新'
|
||||
const at = new Date(value)
|
||||
if (Number.isNaN(at.getTime())) return '仅手动刷新'
|
||||
return `下次自动刷新 ${at.toLocaleString('zh-CN', { hour12: false })}`
|
||||
}
|
||||
|
||||
function SourceSettingsCard({ connection, onSourcesChanged }: { connection: SourceConnectionListItem; onSourcesChanged: () => void }) {
|
||||
const [operator, setOperator] = useState('')
|
||||
const [interval, setInterval] = useState<number>(() => {
|
||||
if (!connection.next_refresh_at) return 0
|
||||
const remaining = new Date(connection.next_refresh_at).getTime() - Date.now()
|
||||
if (remaining <= 0 || remaining > 10 * 3600_000) return 86400
|
||||
return remaining > 3 * 3600_000 ? 21600 : 3600
|
||||
})
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [message, setMessage] = useState<string | null>(null)
|
||||
const [failure, setFailure] = useState<string | null>(null)
|
||||
const [showHistory, setShowHistory] = useState(false)
|
||||
const [history, setHistory] = useState<SourceSettingsRevision[] | null>(null)
|
||||
const [pendingDisable, setPendingDisable] = useState(false)
|
||||
const scheduled = connection.source_type !== 'manual'
|
||||
|
||||
const submit = async (nextEnabled: boolean) => {
|
||||
setBusy(true); setMessage(null); setFailure(null)
|
||||
try {
|
||||
const draft = {
|
||||
source_type: connection.source_type, name: connection.name, endpoint: '', credential_ref: '',
|
||||
enabled: nextEnabled, schedule: { refresh_interval_seconds: nextEnabled && interval > 0 ? interval : null },
|
||||
operator: operator.trim(),
|
||||
}
|
||||
const created = await createSourceSettingsRevision(connection.id, draft)
|
||||
const activated = await activateSourceSettingsRevision(connection.id, created.id)
|
||||
setMessage(`${connection.name}:调度设置已验证并启用${activated.operation === 'replayed' ? '(沿用上次结果)' : ''};${nextEnabled ? formatHorizon(new Date(Date.now() + interval * 1000).toISOString()) : '已停用,新的自动扫描与刷新任务不再入队,历史记录全部保留'}。`)
|
||||
onSourcesChanged()
|
||||
} catch (cause) {
|
||||
setFailure(cause instanceof Error ? cause.message : '保存来源设置失败')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
setPendingDisable(false)
|
||||
}
|
||||
}
|
||||
|
||||
const loadHistory = async () => {
|
||||
setShowHistory(true)
|
||||
if (history) return
|
||||
try { setHistory(await fetchSourceSettingsRevisions(connection.id)) }
|
||||
catch (cause) { setFailure(cause instanceof Error ? cause.message : '加载修订历史失败') }
|
||||
}
|
||||
|
||||
const canApply = operator.trim().length >= 2 && !busy
|
||||
|
||||
return <article className="settings-source-row">
|
||||
<div className="settings-source-name"><strong>{connection.name}</strong><span>{sourceTypeLabels[connection.source_type] ?? connection.source_type}{connection.enabled ? '' : ' · 已停用'}</span></div>
|
||||
<dl>
|
||||
<div><dt>认证方式</dt><dd>{sourceAuthLabels[connection.source_type] ?? '按连接配置'}</dd></div>
|
||||
<div><dt>端点与凭据</dt><dd>已保存,不可回读(草稿留空即沿用现值)</dd></div>
|
||||
<div><dt>当前调度</dt><dd>{connection.enabled ? formatHorizon(connection.next_refresh_at) : '停用中(不入队)'}</dd></div>
|
||||
</dl>
|
||||
<div className="source-schedule-form">
|
||||
{scheduled ? <label>自动刷新周期<select value={interval} onChange={(event) => setInterval(Number(event.target.value))}>{intervalChoices.map((choice) => <option key={choice.value} value={choice.value}>{choice.label}</option>)}</select></label>
|
||||
: <small className="manual-source-note">本地手工导入来源不支持定时刷新,只能手动触发扫描。</small>}
|
||||
<label className="settings-operator">操作人(必填)<input value={operator} onChange={(event) => setOperator(event.target.value)} placeholder="姓名或工号" maxLength={128}/></label>
|
||||
{connection.enabled
|
||||
? <div className="source-schedule-actions"><button className="secondary" disabled={!canApply || (scheduled && interval === 0 && !connection.schedule_configured)} onClick={() => void submit(true)}>{busy ? '正在验证并启用…' : '保存并启用调度'}</button>
|
||||
<button className="danger" disabled={!canApply} onClick={() => setPendingDisable(true)}>停用来源</button></div>
|
||||
: <div className="source-schedule-actions"><button className="secondary" disabled={!canApply} onClick={() => void submit(true)}>保存并启用</button></div>}
|
||||
<button className="link" onClick={() => void loadHistory()}>{showHistory ? '收起修订历史' : '查看修订历史'}</button>
|
||||
</div>
|
||||
{message ? <p className="success-message" role="status">{message}</p> : null}
|
||||
{failure ? <p className="error-message" role="alert">{failure}</p> : null}
|
||||
{showHistory && history ? <ul className="revision-list">{history.map((item) => <li key={item.id}><b>修订 {item.revision_number}</b><span>{item.state === 'active' ? '当前启用' : item.state === 'validated' ? '待启用' : item.state === 'retired' ? '已退休' : '失败'}</span><small>{item.created_by} · {new Date(item.created_at).toLocaleString('zh-CN', { hour12: false })} · {item.refresh_interval_seconds ? `每${secondsLabel(Number(item.refresh_interval_seconds))}` : '仅手动'}</small></li>)}</ul> : null}
|
||||
{showHistory && !history ? <small>正在加载修订历史…</small> : null}
|
||||
{pendingDisable ? <div className="modal-backdrop" role="dialog" aria-modal="true"><div className="modal-card">
|
||||
<h3>停用「{connection.name}」?</h3>
|
||||
<p>停用会立即停止该来源的自动扫描与新刷新任务入队;历史快照、标注和审计全部保留,随时可以重新启用。此操作会先由后端再次校验权限。</p>
|
||||
<div className="modal-actions"><button className="danger" disabled={busy} onClick={() => void submit(false)}>{busy ? '正在停用…' : '确认停用'}</button><button className="secondary" disabled={busy} onClick={() => setPendingDisable(false)}>取消</button></div>
|
||||
</div></div> : null}
|
||||
</article>
|
||||
}
|
||||
|
||||
export function SystemSettingsView({ sources, connections, monitor, settings, productionEnabled, routingCapabilities, loading, saving, error, saveMessage, onSave, onSourcesChanged, onRefresh, initialSection = 'sources' }: Props) {
|
||||
const [section, setSection] = useState<SectionKey>(initialSection)
|
||||
const [documentRefresh, setDocumentRefresh] = useState<15 | 30 | 60>(settings?.document_refresh_seconds ?? 15)
|
||||
const [resourceRefresh, setResourceRefresh] = useState<30 | 60>(settings?.resource_refresh_seconds ?? 30)
|
||||
const [stalled, setStalled] = useState<1800 | 3600>(settings?.stalled_after_seconds ?? 1800)
|
||||
const [finalizing, setFinalizing] = useState<7200 | 14400>(settings?.finalizing_after_seconds ?? 7200)
|
||||
const [operator, setOperator] = useState('')
|
||||
const [dirty, setDirty] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (!settings) return
|
||||
setDocumentRefresh(settings.document_refresh_seconds)
|
||||
setResourceRefresh(settings.resource_refresh_seconds)
|
||||
setStalled(settings.stalled_after_seconds)
|
||||
setFinalizing(settings.finalizing_after_seconds)
|
||||
setDirty(false)
|
||||
}, [settings])
|
||||
|
||||
const canSave = Boolean(settings && operator.trim().length >= 2 && !saving)
|
||||
return <main className="page-shell system-settings">
|
||||
<header className="hero compact"><div><h1>系统设置</h1><p className="subtitle">查看内容源、服务与备份状态;来源调度与刷新参数采用版本化保存。</p></div><button onClick={onRefresh} disabled={loading}>{loading ? '刷新中…' : '刷新状态'}</button></header>
|
||||
{error ? <div className="error-banner" role="alert">{error}</div> : null}
|
||||
{monitor && settings ? <div className="settings-layout">
|
||||
<nav className="settings-nav" aria-label="系统设置分区">{sections.map((item) => <button key={item.key} className={section === item.key ? 'active' : ''} onClick={() => setSection(item.key)}>{item.label}</button>)}</nav>
|
||||
<div className="settings-content">
|
||||
<div className="settings-role-strip"><span className="engineer-role">文档工程师可调整:来源调度周期、刷新间隔、停滞判断</span><span className="admin-role">管理员设置已锁定:端点、凭据、映射、生产开关</span></div>
|
||||
<div className="simulation-banner server-settings-banner"><strong>设置服务已启用</strong><span>当前活动版本 · 启用人 {settings.updated_by} · 启用时间 {settings.activated_at ? new Date(settings.activated_at).toLocaleString('zh-CN') : '待激活'};新设置先验证,再原子切换。</span></div>
|
||||
{section === 'sources' ? <section className="settings-panel wide source-settings-panel" id="settings-sources">
|
||||
<div className="settings-section-heading"><div><h2>数据源配置</h2><p>逐来源设置自动刷新周期或保持仅手动;保存会先生成修订、验证后原子启用,旧版本保留用于审计。</p></div></div>
|
||||
{connections.length ? <div className="settings-source-list">
|
||||
{connections.map((connection) => <SourceSettingsCard key={connection.id} connection={connection} onSourcesChanged={onSourcesChanged}/>)}
|
||||
{sources.length ? null : <small className="empty-inline">尚无快照数据;快照将在来源首次刷新完成后出现。</small>}
|
||||
</div> : <div className="empty-state">尚无可显示的来源连接。</div>}
|
||||
</section> : null}
|
||||
{section === 'services' ? <section className="settings-panel wide" id="settings-services">
|
||||
<div className="settings-section-heading"><div><h2>服务配置</h2><p>测试、生产必须独立配置端点、凭据引用和知识库 ID;凭据只写不读。</p></div></div>
|
||||
<div className="environment-cards"><article><b>测试 WeKnora</b><span>本地真实连接</span><small>端点 / 凭据 / 知识库 ID:管理员受限配置,页面上不可回读</small></article><article className="production"><b>生产 WeKnora</b><span>未连接</span><small>生产写入:关闭;凭据不可回读</small></article></div>
|
||||
<div className="mapping-row"><span>测试知识库映射</span><b>对内解析队列:{routingCapabilities.internal_enabled ? '已配置' : '未配置'}</b><b>对外解析队列:{routingCapabilities.external_enabled ? '已配置' : '未配置'}</b><b>生产映射:未配置</b></div>
|
||||
<div className="dependency-grid">{['PostgreSQL', 'MinerU', 'Embedding', 'LLM API', 'Redis / MQ', 'OSS'].map((name) => { const health = (monitor.health || []).find((item) => item.name === name || item.name.startsWith(name)); const service = monitor.services.find((item) => item.name === name || item.name.startsWith(name)); const liveLabel = !health ? (service ? (service.state === 'healthy' ? '正常' : service.state === 'unknown' ? '未接入' : '需关注') : '待配置') : health.readiness === 'ready' ? '可达 · 可接单' : health.readiness === 'not_configured' ? '状态未知 · 未配置' : health.readiness === 'not_applicable' ? '未部署' : (health.liveness === 'up' ? '可达 · 不可接单' : '不可达 · 不可接单'); return <article key={name} className={health && health.readiness !== 'ready' && health.readiness !== 'not_applicable' ? 'warn' : ''}><span>{name}</span><b>{liveLabel}</b><small>{health ? [health.reason, health.last_success_at ? `最近成功 ${new Date(health.last_success_at).toLocaleTimeString('zh-CN', { hour12: false })}` : '', health.consecutive_failures ? `连续失败${health.consecutive_failures}次` : ''].filter(Boolean).join(';') || (health.readiness === 'ready' ? `延迟 ${health.latency_ms}ms` : '') : service?.detail || '真实 Provider 未接入'}</small></article> })}</div>
|
||||
</section> : null}
|
||||
{section === 'storage' ? <section className="settings-panel wide storage-settings-panel" id="settings-storage">
|
||||
<div className="settings-section-heading"><div><h2>存储与备份</h2><p>文件资源与生产发布前快照使用独立受限配置。</p></div></div>
|
||||
<div className="storage-settings-grid"><dl><dt>Endpoint / Bucket</dt><dd>尚未配置</dd><dt>AccessKey / Secret</dt><dd>仅保存凭据引用,不可回读</dd><dt>CDN / 公开访问域名</dt><dd>尚未配置</dd><dt>临时签名有效期</dt><dd>待配置</dd></dl><dl><dt>测试备份前缀</dt><dd>/backup/weknora/test/</dd><dt>生产备份前缀</dt><dd>/backup/weknora/prod/</dd><dt>快照保留</dt><dd>最近 30 个生产快照</dd><dt>恢复验证</dt><dd>由生产门禁读回</dd></dl><ul className="target-list"><li>PostgreSQL <b>未配置</b></li><li>Elasticsearch <b>未配置</b></li><li>对象存储 <b>未配置</b></li><li>Neo4j <b>未配置</b></li><li>生产发布请求 <b>{productionEnabled ? '等待管理员核对' : '关闭'}</b></li><li>Release Worker <b>网页不可启用</b></li></ul></div>
|
||||
</section> : null}
|
||||
{section === 'refresh' ? <section className="settings-panel wide" id="settings-refresh">
|
||||
<div className="settings-section-heading"><div><h2>刷新策略</h2><p>这些值保存在服务器活动版本中;保存不会修改端点、凭据或生产开关。</p></div><span className="safe-badge">当前活动版本</span></div>
|
||||
<div className="safe-setting-grid">
|
||||
<label>文档状态刷新间隔<select value={documentRefresh} onChange={(event) => { setDocumentRefresh(Number(event.target.value) as 15 | 30 | 60); setDirty(true) }}><option value={15}>15秒</option><option value={30}>30秒</option><option value={60}>1分钟</option></select></label>
|
||||
<label>资源刷新间隔<select value={resourceRefresh} onChange={(event) => { setResourceRefresh(Number(event.target.value) as 30 | 60); setDirty(true) }}><option value={30}>30秒</option><option value={60}>1分钟</option></select></label>
|
||||
<label>解析停滞判定<select value={stalled} onChange={(event) => { setStalled(Number(event.target.value) as 1800 | 3600); setDirty(true) }}><option value={1800}>30分钟</option><option value={3600}>1小时</option></select></label>
|
||||
<label>finalizing 告警<select value={finalizing} onChange={(event) => { setFinalizing(Number(event.target.value) as 7200 | 14400); setDirty(true) }}><option value={7200}>2小时</option><option value={14400}>4小时</option></select></label>
|
||||
</div>
|
||||
<label className="settings-operator">操作人(必填)<input value={operator} onChange={(event) => setOperator(event.target.value)} placeholder="姓名或工号" maxLength={128}/></label>
|
||||
<button onClick={() => { setDirty(false); onSave({ document_refresh_seconds: documentRefresh, resource_refresh_seconds: resourceRefresh, stalled_after_seconds: stalled, finalizing_after_seconds: finalizing, updated_by: operator.trim() }) }} disabled={!canSave}>{saving ? '正在验证并应用…' : '保存并应用刷新与告警参数'}</button>
|
||||
{visibleSaveMessage(saveMessage, dirty) ? <p className="success-message" role="status">{saveMessage}</p> : null}
|
||||
<small>当前:文档 {secondsLabel(settings.document_refresh_seconds)}、资源 {secondsLabel(settings.resource_refresh_seconds)}、停滞 {secondsLabel(settings.stalled_after_seconds)}、finalizing {secondsLabel(settings.finalizing_after_seconds)}。</small>
|
||||
</section> : null}
|
||||
</div>
|
||||
</div> : null}
|
||||
</main>
|
||||
}
|
||||
|
||||
export function SystemSettings() {
|
||||
const [sources, setSources] = useState<CatalogSource[]>([])
|
||||
const [connections, setConnections] = useState<SourceConnectionListItem[]>([])
|
||||
const [monitor, setMonitor] = useState<MonitorOverview | null>(null)
|
||||
const [settings, setSettings] = useState<UISettings | null>(null)
|
||||
const [productionEnabled, setProductionEnabled] = useState(false)
|
||||
const [routingCapabilities, setRoutingCapabilities] = useState<CatalogRoutingCapabilities>({ internal_enabled: false, external_enabled: false })
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [saveMessage, setSaveMessage] = useState<string | null>(null)
|
||||
const [revision, setRevision] = useState(0)
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController(); setLoading(true)
|
||||
void Promise.all([fetchCatalogSources(controller.signal), fetchSourceConnectionList(controller.signal), fetchMonitorOverview(controller.signal), fetchReleaseCapabilities(controller.signal), fetchCatalogRoutingCapabilities(controller.signal), fetchActiveUISettings(controller.signal)]).then(([nextSources, nextConnections, overview, capabilities, routing, active]) => { if (!controller.signal.aborted) { setSources(nextSources); setConnections(nextConnections); setMonitor(overview); setProductionEnabled(capabilities.production_release_requests_enabled); setRoutingCapabilities(routing); setSettings(active); setError(null) } }).catch((cause) => { if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : '加载系统设置失败') }).finally(() => { if (!controller.signal.aborted) setLoading(false) })
|
||||
return () => controller.abort()
|
||||
}, [revision])
|
||||
|
||||
const save = async (input: UISettingsCandidateInput) => {
|
||||
setSaving(true); setSaveMessage(null); setError(null)
|
||||
try { const candidate = await createUISettingsCandidate(input); const active = await activateUISettings(candidate.id); setSettings(active); setSaveMessage(`刷新与告警参数已验证并启用:文档${secondsLabel(active.document_refresh_seconds)}、资源${secondsLabel(active.resource_refresh_seconds)}、停滞${secondsLabel(active.stalled_after_seconds)}、finalizing ${secondsLabel(active.finalizing_after_seconds)};旧版本已保留用于审计。`) }
|
||||
catch (cause) { setError(cause instanceof Error ? cause.message : '保存系统设置失败') }
|
||||
finally { setSaving(false) }
|
||||
}
|
||||
const reloadSources = useCallback(() => { setSaveMessage(null); setRevision((value) => value + 1) }, [])
|
||||
return <SystemSettingsView sources={sources} connections={connections} monitor={monitor} settings={settings} productionEnabled={productionEnabled} routingCapabilities={routingCapabilities} loading={loading} saving={saving} error={error} saveMessage={saveMessage} onSave={(input) => void save(input)} onSourcesChanged={reloadSources} onRefresh={reloadSources}/>
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe,expect,it,vi } from 'vitest'
|
||||
import { WeKnoraMonitorView } from './WeKnoraMonitor'
|
||||
import type { MonitorFilePage,MonitorOverview,RunMetrics } from './monitor'
|
||||
import type { TestPublicationPage } from './testPublications'
|
||||
import type { CatalogChangeSetDetail } from './sourceCatalog'
|
||||
|
||||
const overview:MonitorOverview={mode:'simulation',simulated:true,observed_at:'2026-09-08T12:00:00Z',host:{cpu_percent:42,memory_used_bytes:19971597926,memory_total_bytes:34359738368,disk_used_bytes:128849018880,disk_total_bytes:536870912000,gpu_state:'unknown',gpu_detail:'未接入真实GPU监控',simulated:true},services:[{key:'weknora',name:'WeKnora API',state:'healthy',detail:'模拟连接正常',latency_ms:86,observed_at:'2026-09-08T12:00:00Z',simulated:true},{key:'mineru',name:'MinerU',state:'healthy',detail:'模拟处理中2,队列5',latency_ms:24,observed_at:'2026-09-08T12:00:00Z',simulated:true},{key:'postgres',name:'PostgreSQL',state:'unknown',detail:'未接入真实监控',latency_ms:0,observed_at:'2026-09-08T12:00:00Z',simulated:true},{key:'redis',name:'Redis / MQ',state:'unknown',detail:'未接入真实监控',latency_ms:0,observed_at:'2026-09-08T12:00:00Z',simulated:true},{key:'oss',name:'OSS',state:'unknown',detail:'未接入真实监控',latency_ms:0,observed_at:'2026-09-08T12:00:00Z',simulated:true}],knowledge_bases:[{id:'kb-sim',name:'公司级技术支持知识库',visibility:'mixed',imported:5750,completed:4530,pending:450,processing:50,finalizing:714,failed:6,cancelled:0,internal_imported:4200,internal_completed:3300,external_imported:1550,external_completed:1230}],health:[]}
|
||||
const files:MonitorFilePage={items:[{name:'[模拟] 产品参数总表.xlsx',directory:'02|产品资料',visibility:'external',status:'finalizing',stage_detail:'基础检索可用,Wiki与图谱仍在生成',elapsed_seconds:2100,error_code:''}],total:1,limit:20,offset:0,sample_only:true}
|
||||
const metrics:RunMetrics={observed_at:'2026-09-12T00:00:00Z',active_workers:2,worker_source:'pg_lease',queue:{pending:3,running:4,retry:1,failed:2,oldest_pending_age_seconds:120},short_window:{window_seconds:3600,jobs_started:50,jobs_completed:48,jobs_failed:6,success_rate:88.9,failure_rate:11.1,duration_avg_seconds:55,duration_p50_seconds:30,duration_p95_seconds:1800},long_window:{window_seconds:86400,jobs_started:500,jobs_completed:482,jobs_failed:18,success_rate:96.4,failure_rate:3.6,duration_avg_seconds:70,duration_p50_seconds:45,duration_p95_seconds:2400}}
|
||||
const queue:TestPublicationPage={items:[{id:'tp-plan',title:'API.docx',ingest_state:'pending',processing_state:'pending',retrieval_state:'unpublished',target_scope: 'internal', change_set_id: 'cs-1', change_type:'added',can_start:true,retry_count:0,last_error:'',can_retry:false,updated_at:'2026-09-09T10:01:00Z'},{id:'tp-failed',title:'CR20A.pdf',ingest_state:'uploaded',processing_state:'failed',retrieval_state:'unpublished',target_scope: 'external', change_set_id: 'cs-1', change_type:'updated',can_start:false,retry_count:1,last_error:'remote_parse_failed',can_retry:true,updated_at:'2026-09-09T10:00:00Z'}],total:2,limit:50,offset:0}
|
||||
const changeSets:CatalogChangeSetDetail[]=[{id:'cs-1',connection_id:'conn-1',source_name:'国内工业',state:'planned',add_count:2,update_count:1,move_count:1,move_scope_count:1,delete_count:1,no_change_count:10,created_at:'2026-09-10T00:00:00Z',items:[{action:'delete',title:'旧手册.pdf',old_path:'旧目录/旧手册.pdf',new_path:'',reason_code:'source_missing',seq:7}],total:15,limit:20,offset:0}]
|
||||
|
||||
const baseProps={overview,files,queue,changeSets,selectedKB:overview.knowledge_bases[0],status:'' as const,queueStatus:'' as const,queueScope:'' as const,loading:false,error:null as string|null,retryingIDs:[] as string[],starting:false,startMessage:'',onSelectKB:vi.fn(),onStatus:vi.fn(),onQueueStatus:vi.fn(),onQueueScope:vi.fn(),lane:'queue',onLaneChange:vi.fn(),metrics,onRetry:vi.fn(),onBatchRetry:vi.fn(),onStart:vi.fn(),onRefresh:vi.fn()}
|
||||
describe('WeKnoraMonitorView',()=>{
|
||||
it('filters the processing queue by target knowledge base and shows each task target',()=>{
|
||||
const html=renderToStaticMarkup(<WeKnoraMonitorView {...baseProps} queueScope="internal" onQueueScope={vi.fn()} />)
|
||||
expect(html).toContain('aria-label="队列目标知识库"')
|
||||
expect(html).toContain('对内知识库</option>')
|
||||
expect(html).toContain('对外知识库</option>')
|
||||
expect(html).toContain('<option value="internal" selected="">对内知识库')
|
||||
expect(html).toContain('目标知识库')
|
||||
// the one internal task row shows its target (select option matches are not counted)
|
||||
expect(html).toContain('scope-badge internal">对内')
|
||||
expect(html).toContain('scope-badge external">对外')
|
||||
})
|
||||
it('offers explicit change-set confirmation with operator, selection and result message',()=>{
|
||||
const html=renderToStaticMarkup(<WeKnoraMonitorView {...baseProps} lane='changes' changeSets={changeSets} confirmingSetID='cs-1' confirmMessage='已提交:确认 2 项;新建上传任务 2 个' onConfirmChangeSet={vi.fn()} />)
|
||||
expect(html).toContain('预览并选择变更文件')
|
||||
expect(html).toContain('aria-label="选择旧手册.pdf"')
|
||||
expect(html).toContain('确认处理(0)')
|
||||
expect(html).toContain('aria-label="确认操作人"')
|
||||
expect(html).toContain('已提交:确认 2 项;新建上传任务 2 个')
|
||||
})
|
||||
it('hides confirmation controls after the change set leaves planned state',()=>{
|
||||
const confirmed=[{...changeSets[0],state:'confirmed' as const}]
|
||||
const html=renderToStaticMarkup(<WeKnoraMonitorView {...baseProps} lane='changes' changeSets={confirmed} onConfirmChangeSet={vi.fn()} />)
|
||||
expect(html).toContain('已确认')
|
||||
expect(html).not.toContain('确认处理')
|
||||
expect(html).toContain('aria-label="选择旧手册.pdf" disabled')
|
||||
expect(html).not.toContain('确认操作人')
|
||||
})
|
||||
it('shows a plainly labelled simulation with per-lane inbox controls',()=>{
|
||||
const changes=renderToStaticMarkup(<WeKnoraMonitorView {...baseProps} lane='changes' />)
|
||||
for(const text of ['本地模拟数据','持久快照差异','国内工业','新增 2','更新 1','移动 1','删除 1','未变化 10','旧手册.pdf','操作人','确认原因','开始处理(1)','刷新来源 ≠ 马上导入知识库','不代表测试服务器真实数据'])expect(changes).toContain(text)
|
||||
const attention=renderToStaticMarkup(<WeKnoraMonitorView {...baseProps} lane='attention' />)
|
||||
for(const text of ['需要你出手','CR20A.pdf','tp-failed'.slice(0,0)+'remote_parse_failed','失败阶段 文档解析','批量重试所选(1)','死信(尝试耗尽,不可自动重试)','下载 ✓','文档解析 ✗','建议先在 WeKnora 手动解析该文件确认格式'])expect(attention).toContain(text)
|
||||
const inflight=renderToStaticMarkup(<WeKnoraMonitorView {...baseProps} lane='inflight' />)
|
||||
for(const text of ['处理中','知识库解析进度','已导入 5750','completed 4530','pending 450','finalizing 714','对内 3300 / 4200','对外 1230 / 1550','[模拟] 产品参数总表.xlsx','基础检索可用,Wiki与图谱仍在生成','下载 → Hash → OSS → 文档解析 → WeKnora 上传 → 索引 → 完成'])expect(inflight).toContain(text)
|
||||
const queueView=renderToStaticMarkup(<WeKnoraMonitorView {...baseProps} lane='queue' />)
|
||||
expect(queueView).toContain('全部任务(2)')
|
||||
expect(queueView).toContain('确认并解析')
|
||||
expect(queueView).toContain('重试')
|
||||
expect(queueView).toContain('等待人工确认')
|
||||
expect(queueView).toContain('1小时·成功')
|
||||
expect(queueView).toContain('88.9%')
|
||||
const nav=renderToStaticMarkup(<WeKnoraMonitorView {...baseProps} lane='pending' />)
|
||||
for(const text of ['今天需要我做什么','需人工处理','等待我确认的差异','排队等待','已完成','全部任务'])expect(nav).toContain(text)
|
||||
})
|
||||
it('does not show simulated success totals after a load error without data',()=>{
|
||||
const html=renderToStaticMarkup(<WeKnoraMonitorView overview={null} files={null} selectedKB={null} status="" queueStatus="" queueScope="" loading={false} error="加载失败" onSelectKB={vi.fn()} onStatus={vi.fn()} onQueueStatus={vi.fn()} onQueueScope={vi.fn()} onRefresh={vi.fn()} />)
|
||||
expect(html).toContain('加载失败')
|
||||
expect(html).not.toContain('completed 0')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,398 @@
|
||||
import { useContext, useEffect, useMemo, useState } from 'react'
|
||||
|
||||
import { fetchMonitorFiles, fetchMonitorOverview, fetchRunMetrics } from './monitor'
|
||||
import type { RunMetrics } from './monitor'
|
||||
import type { KnowledgeProgress, MonitorFilePage, MonitorOverview, MonitorStatus } from './monitor'
|
||||
import { fetchJobFailures, fetchTestPublications, retryPublication, retryPublicationsBatch, startTestPublications } from './testPublications'
|
||||
import type { JobFailure, ProcessingState, TestPublication, TestPublicationPage } from './testPublications'
|
||||
import { fetchActiveUISettings, settingsRefreshDelays } from './uiSettings'
|
||||
import { confirmCatalogChangeSet, fetchCatalogSources, fetchLatestCatalogChangeSet } from './sourceCatalog'
|
||||
import type { CatalogChangeSetDetail } from './sourceCatalog'
|
||||
import { WorkspaceContextTabsSetter } from './workspaceContext'
|
||||
import './weknoraMonitor.css'
|
||||
|
||||
const emptyQueue: TestPublicationPage = { items: [], total: 0, limit: 50, offset: 0 }
|
||||
const gb = (value: number) => `${(value / 1073741824).toFixed(1)}`
|
||||
const scope = (value: string) => value === 'internal' ? '对内' : value === 'external' ? '对外' : '混合'
|
||||
const duration = (seconds: number) => seconds <= 0 ? '完成' : seconds < 60 ? `${seconds}秒` : seconds < 3600 ? `${Math.floor(seconds / 60)}分钟` : `${(seconds / 3600).toFixed(1)}小时`
|
||||
const serviceState = (state: string) => state === 'healthy' ? '正常' : state === 'degraded' ? '异常' : state === 'unknown' ? '未接入' : '不可用'
|
||||
const statusLabels: Record<MonitorStatus, string> = { completed: 'completed', pending: 'pending', processing: 'processing', finalizing: 'finalizing', failed: 'failed', cancelled: 'cancelled' }
|
||||
const processingLabels: Record<ProcessingState, string> = { pending: '等待解析', processing: '解析中', finalizing: '索引与增强', completed: '成功', failed: '失败', stalled: '停滞' }
|
||||
|
||||
const secondsSince = (iso: string) => Math.max(0, Math.round((Date.now() - new Date(iso).getTime()) / 1000))
|
||||
const adviceFor = (stage: string, code: string) => {
|
||||
if (stage === '文档解析') return '建议先在 WeKnora 手动解析该文件确认格式,再决定是否重试。'
|
||||
if (stage === '索引 / 增强') return '多为 MinerU 容量或超时问题,确认服务恢复接单后重试。'
|
||||
if (stage === 'WeKnora 上传') return '上传失败,确认 WeKnora 可达后重试;重复提交不会创建第二份知识。'
|
||||
if (stage === 'Hash / 文件校验' || stage === 'OSS') return '文件或暂存校验问题,重新入队会重新拉取来源文件。'
|
||||
if (stage === '测试知识移除') return '移除失败,请先在测试知识库确认该文档当前状态。'
|
||||
if (stage === '治理策略') return '按治理策略阻止,请先在来源目录修正对内/对外标注。'
|
||||
if (code.includes('429')) return '远端容量已满,恢复后可一键重新入队。'
|
||||
return '确认错误码后可直接重试;尝试次数耗尽将进入死信队列。'
|
||||
}
|
||||
|
||||
const pipelineStages = ['下载', 'Hash', 'OSS', '文档解析', 'WeKnora 上传', '索引', '完成']
|
||||
const stageIndex = (label: string) => label === 'Hash / 文件校验' ? 1 : label === 'OSS' ? 2 : label === '文档解析' ? 3 : label === 'WeKnora 上传' ? 4 : label === '索引 / 增强' || label === '测试知识移除' || label === '治理策略' || label === '处理链路' ? 5 : -1
|
||||
function chainSteps(item: TestPublication) {
|
||||
const broken = item.processing_state === 'failed' || item.processing_state === 'stalled'
|
||||
const stopAt = broken ? stageIndex(failureStage(item)) : -1
|
||||
const activeAt = item.processing_state === 'completed' ? 7 : item.processing_state === 'finalizing' ? 5 : item.processing_state === 'processing' ? 3 : 0
|
||||
return pipelineStages.map((stage, index) => {
|
||||
if (stopAt >= 0 && index === stopAt) return { stage, state: 'bad' as const }
|
||||
if (stopAt >= 0) return { stage, state: index < stopAt ? 'done' as const : 'todo' as const }
|
||||
if (index < activeAt) return { stage, state: 'done' as const }
|
||||
if (index === activeAt && item.processing_state !== 'pending' && item.processing_state !== 'completed') return { stage, state: 'active' as const }
|
||||
if (item.processing_state === 'pending' && index === 0) return { stage, state: 'active' as const }
|
||||
return { stage, state: 'todo' as const }
|
||||
})
|
||||
}
|
||||
|
||||
function failureStage(item: TestPublication) {
|
||||
const code = item.last_error
|
||||
if (code.includes('artifact') || code.includes('hash')) return 'Hash / 文件校验'
|
||||
if (code.includes('oss')) return 'OSS'
|
||||
if (code.includes('upload')) return 'WeKnora 上传'
|
||||
if (code.includes('parse')) return '文档解析'
|
||||
if (code.includes('stalled') || code.includes('index')) return '索引 / 增强'
|
||||
if (code.includes('removal')) return '测试知识移除'
|
||||
if (code.includes('blocked')) return '治理策略'
|
||||
return item.processing_state === 'failed' ? '处理链路' : '—'
|
||||
}
|
||||
|
||||
interface ViewProps {
|
||||
overview: MonitorOverview | null
|
||||
files: MonitorFilePage | null
|
||||
queue?: TestPublicationPage
|
||||
plans?: TestPublication[]
|
||||
changeSets?: CatalogChangeSetDetail[]
|
||||
confirmingSetID?: string | null
|
||||
confirmMessage?: string
|
||||
onConfirmChangeSet?: (changeSetID: string, itemSeqs: number[], operator: string, reason: string) => void
|
||||
selectedKB: KnowledgeProgress | null
|
||||
status: MonitorStatus | ''
|
||||
queueStatus?: ProcessingState | ''
|
||||
queueScope?: 'internal' | 'external' | ''
|
||||
loading: boolean
|
||||
error: string | null
|
||||
retryingIDs?: string[]
|
||||
starting?: boolean
|
||||
startMessage?: string
|
||||
batchMessage?: string
|
||||
failures?: JobFailure[]
|
||||
metrics?: RunMetrics | null
|
||||
onSelectKB: (kb: KnowledgeProgress) => void
|
||||
onStatus: (status: MonitorStatus | '') => void
|
||||
onQueueStatus: (value: ProcessingState | '') => void
|
||||
onQueueScope: (value: 'internal' | 'external' | '') => void
|
||||
lane?: string
|
||||
onLaneChange?: (lane: string) => void
|
||||
onRetry?: (id: string) => void
|
||||
onBatchRetry?: (ids: string[], operator: string) => void
|
||||
onStart?: (ids: string[], operator: string, reason: string) => void
|
||||
onRefresh: () => void
|
||||
}
|
||||
|
||||
function ChangeSetCard({changeSet,confirming,message,onConfirm}:{changeSet:CatalogChangeSetDetail;confirming:boolean;message:string;onConfirm?:(changeSetID:string,itemSeqs:number[],operator:string,reason:string)=>void}){
|
||||
const [open,setOpen]=useState(false)
|
||||
const [selected,setSelected]=useState<number[]>([])
|
||||
const [operator,setOperator]=useState('')
|
||||
const actionable=changeSet.items.filter(item=>item.action!=='no_change')
|
||||
const confirmable=changeSet.state==='planned'&&actionable.length>0&&Boolean(onConfirm)
|
||||
const toggle=(seq:number)=>setSelected(current=>current.includes(seq)?current.filter(value=>value!==seq):[...current,seq])
|
||||
return <article><div><strong>{changeSet.source_name}</strong><small>{new Date(changeSet.created_at).toLocaleString('zh-CN',{hour12:false})}</small>{changeSet.state!=='planned'?<span className="scope-badge internal">已确认</span>:null}</div><div className="persisted-change-counts"><span>新增 {changeSet.add_count}</span><span>更新 {changeSet.update_count}</span><span>移动 {changeSet.move_count}</span><span>范围变化 {changeSet.move_scope_count}</span><span>删除 {changeSet.delete_count}</span><span>未变化 {changeSet.no_change_count}</span></div>{actionable.length?<details open={open} onToggle={event=>setOpen((event.target as HTMLDetailsElement).open)}><summary>预览并选择变更文件</summary><div className="changeset-selection">{actionable.map(item=><label key={item.seq} className="changeset-choice"><input type="checkbox" aria-label={`选择${item.title}`} disabled={!confirmable} checked={selected.includes(item.seq)} onChange={()=>toggle(item.seq)} /><b>{item.action==='add'?'新增':item.action==='update'?'更新':item.action==='move'?'移动(改名)':item.action==='move_scope'?'范围变化':'删除'}</b><span>{item.title}</span><small>{item.new_path||item.old_path}</small>{item.action==='delete'&&item.reason_code==='source_missing'?<small>来源缺失</small>:null}</label>)}</div>{confirmable?<div className="changeset-confirm"><label>操作人<input aria-label="确认操作人" placeholder="姓名或工号" value={operator} onChange={event=>setOperator(event.target.value)} /></label><button disabled={confirming||selected.length===0||!operator.trim()} onClick={()=>onConfirm?.(changeSet.id,[...selected].sort((a,b)=>a-b),operator.trim(),'人工确认快照差异执行')}>确认处理({selected.length})</button></div>:null}{message?<p role="status">{message}</p>:null}</details>:null}</article>
|
||||
}
|
||||
|
||||
export function WeKnoraMonitorView({
|
||||
overview,
|
||||
files,
|
||||
queue = emptyQueue,
|
||||
plans = queue.items,
|
||||
changeSets = [],
|
||||
confirmingSetID = null,
|
||||
confirmMessage = '',
|
||||
onConfirmChangeSet,
|
||||
selectedKB,
|
||||
status,
|
||||
queueStatus = '',
|
||||
queueScope = '',
|
||||
lane = 'attention',
|
||||
onLaneChange = () => undefined,
|
||||
loading,
|
||||
error,
|
||||
retryingIDs = [],
|
||||
starting = false,
|
||||
startMessage = '',
|
||||
batchMessage = '',
|
||||
failures = [],
|
||||
metrics = null,
|
||||
onSelectKB,
|
||||
onStatus,
|
||||
onQueueStatus = () => undefined,
|
||||
onQueueScope = () => undefined,
|
||||
onRetry = () => undefined,
|
||||
onBatchRetry = () => undefined,
|
||||
onStart = () => undefined,
|
||||
onRefresh,
|
||||
}: ViewProps) {
|
||||
const [startOperator, setStartOperator] = useState('')
|
||||
const [startReason, setStartReason] = useState('已核对来源快照与测试知识库差异')
|
||||
const [retryOperator, setRetryOperator] = useState('')
|
||||
const [selectedRetryIDs, setSelectedRetryIDs] = useState<string[]>([])
|
||||
const toggleRetrySelection = (id: string) => setSelectedRetryIDs((current) => current.includes(id) ? current.filter((value) => value !== id) : [...current, id])
|
||||
const stages: Array<[MonitorStatus, number]> = selectedKB ? [
|
||||
['completed', selectedKB.completed], ['pending', selectedKB.pending], ['finalizing', selectedKB.finalizing],
|
||||
['processing', selectedKB.processing], ['failed', selectedKB.failed], ['cancelled', selectedKB.cancelled],
|
||||
] : []
|
||||
const orderedQueue = useMemo(() => [...queue.items].sort((left, right) => {
|
||||
const priority = (item: TestPublication) => item.processing_state === 'failed' || item.processing_state === 'stalled' ? 0 : 1
|
||||
return priority(left) - priority(right)
|
||||
}), [queue.items])
|
||||
const retryableIDs = queue.items.filter((item) => item.can_retry).map((item) => item.id)
|
||||
const batchTargets = selectedRetryIDs.length ? retryableIDs.filter((id) => selectedRetryIDs.includes(id)) : retryableIDs
|
||||
const pendingPlans = plans.filter((item) => item.can_start)
|
||||
const addedPlans = pendingPlans.filter((item) => item.change_type === 'added').length
|
||||
const updatedPlans = pendingPlans.filter((item) => item.change_type === 'updated').length
|
||||
const attentionItems = queue.items.filter((item) => item.processing_state === 'failed' || item.processing_state === 'stalled')
|
||||
const inflightItems = queue.items.filter((item) => item.processing_state === 'processing' || item.processing_state === 'finalizing' || (item.processing_state === 'pending' && !item.can_start))
|
||||
const doneTodayItems = queue.items.filter((item) => item.processing_state === 'completed')
|
||||
const waitingItems = queue.items.filter((item) => item.processing_state === 'pending' && !item.can_start)
|
||||
const laneCounts: Record<string, number> = { attention: attentionItems.length + failures.length, changes: changeSets.filter((set) => set.state === 'planned').length, inflight: inflightItems.length, pending: waitingItems.length, done: doneTodayItems.length, queue: queue.total }
|
||||
const queueFiltered = waitingItems
|
||||
const queueFilteredAll = orderedQueue
|
||||
|
||||
const actionTask = (item: TestPublication) => <article className="inbox-task" key={item.id}>
|
||||
<div className="inbox-task-mark">{item.can_retry ? <input type="checkbox" aria-label={`选择重试${item.title}`} checked={selectedRetryIDs.includes(item.id)} onChange={() => toggleRetrySelection(item.id)} /> : null}</div>
|
||||
<div>
|
||||
<h4>{item.title} <span className={`scope-badge ${item.target_scope}`}>{scope(item.target_scope)}</span> {item.change_type === 'added' ? <span className="task-badge add">新增</span> : item.change_type === 'updated' ? <span className="task-badge update">更新</span> : null}</h4>
|
||||
<div className="why">{item.processing_state === 'failed' || item.processing_state === 'stalled' ? <>{item.processing_state === 'stalled' ? '任务停滞:' : '为什么失败:'}错误码 <code>{item.last_error || '—'}</code> · 第{item.retry_count + 1}次尝试 · 已停留{duration(secondsSince(item.updated_at))} · 失败阶段 {failureStage(item)}</> : <>状态 <code>{item.can_start ? '等待人工确认' : processingLabels[item.processing_state]}</code>{item.last_error ? <> · 最近错误 <code>{item.last_error}</code></> : null} · 已停留{duration(secondsSince(item.updated_at))}</>}</div>
|
||||
<div className="task-chain" aria-label={`处理链${item.title}`}>{chainSteps(item).map((step) => <span key={step.stage} className={`chain-step ${step.state}`}>{step.stage}{step.state === 'done' ? ' ✓' : step.state === 'bad' ? ' ✗' : step.state === 'active' ? ` 中 ${duration(secondsSince(item.updated_at))}` : ''}</span>)}</div>
|
||||
<div className={item.processing_state === 'failed' || item.processing_state === 'stalled' ? 'errline' : 'tiny muted-line'}>{item.processing_state === 'failed' || item.processing_state === 'stalled' ? adviceFor(failureStage(item), item.last_error) : item.can_start ? '确认后将创建解析任务' : '无需操作,等待自动处理'}{item.change_set_id ? <> · 来源变更集 <code>{item.change_set_id}</code></> : null} · <code>{item.id}</code></div>
|
||||
</div>
|
||||
<div className="inbox-task-actions">{item.can_start ? <button className="primary" disabled={starting || !startOperator.trim() || !startReason.trim()} onClick={() => onStart([item.id], startOperator.trim(), startReason.trim())}>确认并解析</button> : null}{item.can_retry ? <button className="primary" disabled={retryingIDs.includes(item.id)} onClick={() => onRetry(item.id)}>{retryingIDs.includes(item.id) ? '重试中…' : '重试'}</button> : null}</div>
|
||||
</article>
|
||||
const emptyLane = (text: string) => <div className="empty-state">{text}</div>
|
||||
return <main className="page-shell weknora-monitor inbox-layout">
|
||||
<header className="hero compact"><div><h1>解析监控</h1><p className="subtitle">今天需要我做什么,一目了然;处理链进度、失败原因与建议直接摆在任务卡片上。</p></div><span className="monitor-meta">{overview ? `快照 ${new Date(overview.observed_at).toLocaleString('zh-CN', { hour12: false })}` : ''} · 队列 等待{queue.total}条</span><button onClick={onRefresh} disabled={loading}>{loading ? '刷新中…' : '刷新'}</button></header>
|
||||
{error ? <div className="error-banner" role="alert">{error}</div> : null}
|
||||
{overview?.simulated ? <div className="simulation-banner"><strong>本地模拟数据</strong><span>资源和知识库汇总用于确认页面流程,不代表测试服务器真实数据;任务卡片来自真实治理 API。</span></div> : null}
|
||||
<div className="inbox-grid">
|
||||
<nav className="inbox-nav" aria-label="解析监控收件箱">
|
||||
<h2>今天需要我做什么</h2>
|
||||
{[['attention', '需人工处理', 'blocked'], ['changes', '等待我确认的差异', ''], ['inflight', '处理中', ''], ['pending', '排队等待', ''], ['done', '已完成', 'okall']].map(([value, label, tone]) => <button key={value} className={`${lane === value ? 'active' : ''} ${laneCounts[value] ? tone : ''}`} aria-label={`切换到${label}`} onClick={() => onLaneChange(value)}><span>{label}</span><em className="lane-count">{laneCounts[value]}</em></button>)}
|
||||
<button className={`${lane === 'queue' ? 'active' : ''}`} aria-label="切换到全部任务" onClick={() => onLaneChange('queue')}><span>全部任务</span><em className="lane-count">{queue.total}</em></button>
|
||||
</nav>
|
||||
<div className="inbox-work">
|
||||
{lane === 'attention' ? <section className="inbox-section" aria-label="需人工处理">
|
||||
<div className="section-head"><h2>需要你出手({attentionItems.length})</h2><span className="spacer" /><span className="tiny">操作人</span><input className="operator-input" aria-label="批量重试操作人" placeholder="姓名或工号" value={retryOperator} onChange={(event) => setRetryOperator(event.target.value)} /><button className="danger" disabled={!batchTargets.length || retryingIDs.length > 0} onClick={() => onBatchRetry(batchTargets, retryOperator)}>{retryingIDs.length ? '重试中…' : `批量重试所选(${batchTargets.length})`}</button></div>
|
||||
{batchMessage ? <p className="queue-batch-message" role="status">{batchMessage}</p> : null}
|
||||
{attentionItems.length ? attentionItems.map(actionTask) : emptyLane('没有失败或停滞的任务。')}
|
||||
<div className="section-head sub"><h3>死信(尝试耗尽,不可自动重试)</h3><span className="tiny">原始任务与审计行保留不动;重新入队会创建新尝试</span></div>
|
||||
{failures.length ? <ul className="dlq-list">{failures.map((failure) => <li key={failure.id}><span className="monitor-status failed">{failure.error_code}</span><b>{failure.job_type === 'test.upload' ? '上传解析' : failure.job_type}</b>{failure.publication_id ? <code>{failure.publication_id}</code> : null}<small>{failure.attempt}/{failure.max_attempts_at_failure} 次 · {new Date(failure.created_at).toLocaleString('zh-CN', { hour12: false })}</small>{failure.publication_id ? <button disabled={retryingIDs.includes(failure.publication_id) || !retryOperator.trim()} onClick={() => onBatchRetry([failure.publication_id as string], retryOperator)}>重新入队</button> : null}</li>)}</ul> : emptyLane('当前没有等待处理的死信记录。')}
|
||||
</section> : null}
|
||||
{lane === 'changes' ? <section className="inbox-section" aria-label="等待确认的差异">
|
||||
<div className="section-head"><h2>持久快照差异 · 等待确认({changeSets.filter((set) => set.state === 'planned').length} 个来源)</h2><span className="tiny">刷新来源 ≠ 马上导入知识库;勾选变更项并确认后才创建解析任务</span></div>
|
||||
{changeSets.length ? <div className="persisted-change-grid">{changeSets.map(changeSet => <ChangeSetCard key={changeSet.id} changeSet={changeSet} confirming={confirmingSetID === changeSet.id} message={confirmingSetID === changeSet.id ? confirmMessage : ''} onConfirm={onConfirmChangeSet} />)}</div> : emptyLane('当前没有持久快照差异。')}
|
||||
<div className="difference-confirmation">
|
||||
<label>操作人<input value={startOperator} onChange={(event) => setStartOperator(event.target.value)} placeholder="姓名或工号" /></label>
|
||||
<label>确认原因<input value={startReason} onChange={(event) => setStartReason(event.target.value)} /></label>
|
||||
<button disabled={starting || !pendingPlans.length || !startOperator.trim() || !startReason.trim()} onClick={() => onStart(pendingPlans.map((item) => item.id), startOperator.trim(), startReason.trim())}>{starting ? '正在生成任务…' : `开始处理(${pendingPlans.length})`}</button>
|
||||
</div>
|
||||
<p className="tiny">待确认 {pendingPlans.length} · 新增 {addedPlans} · 更新 {updatedPlans}</p>
|
||||
{startMessage ? <p className="difference-message" role="status">{startMessage}</p> : null}
|
||||
</section> : null}
|
||||
{lane === 'inflight' ? <section className="inbox-section" aria-label="处理中">
|
||||
<div className="section-head"><h2>处理中({inflightItems.length})</h2><span className="tiny">无需操作,仅供查看</span></div>
|
||||
{inflightItems.length ? inflightItems.map(actionTask) : emptyLane('当前没有正在处理或索引增强的任务。')}
|
||||
{overview ? <>
|
||||
<div className="pipeline-strip" aria-label="解析处理链">下载 → Hash → OSS → 文档解析 → WeKnora 上传 → 索引 → 完成</div>
|
||||
<div className="monitor-kb-layout" id="monitor-kb-progress">
|
||||
<aside className="monitor-kb-list"><h2>知识库解析进度</h2>{overview.knowledge_bases.map((kb) => <button key={kb.id} className={selectedKB?.id === kb.id ? 'active' : ''} onClick={() => onSelectKB(kb)}><span><b>{kb.name}</b><small>{scope(kb.visibility)} · 已导入 {kb.imported}</small></span><strong>{kb.completed}完成</strong></button>)}</aside>
|
||||
<div className="monitor-kb-detail">{selectedKB ? <>
|
||||
<div className="monitor-kb-heading"><div><h2>{selectedKB.name}</h2><span>{scope(selectedKB.visibility)} · 已导入 {selectedKB.imported}</span></div><div><span>对内 {selectedKB.internal_completed} / {selectedKB.internal_imported}</span><span>对外 {selectedKB.external_completed} / {selectedKB.external_imported}</span></div></div>
|
||||
<div className="monitor-stage-tabs"><button className={status === '' ? 'active' : ''} onClick={() => onStatus('')}>全部 {selectedKB.imported}</button>{stages.filter(([, count]) => count > 0).map(([value, count]) => <button className={status === value ? 'active' : ''} key={value} onClick={() => onStatus(value)}>{statusLabels[value]} {count}</button>)}</div>
|
||||
<p className="finalizing-note"><b>finalizing:</b>基础解析、切片和向量通常已完成,Wiki、摘要或图谱仍在生成;不能算全部完成。</p>
|
||||
{files?.sample_only ? <p className="sample-note">当前只展示本地模拟文件样例;真实模式会列出所选状态下的实际文件。</p> : null}
|
||||
{files?.items.length ? <div className="monitor-file-wrap"><table className="monitor-file-table"><thead><tr><th>文件名</th><th>来源目录</th><th>对内/对外</th><th>当前阶段</th><th>已停留</th><th>说明</th></tr></thead><tbody>{files.items.map((file) => <tr key={`${file.name}-${file.status}`}><td>{file.name}</td><td>{file.directory}</td><td><span className={`scope-badge ${file.visibility}`}>{scope(file.visibility)}</span></td><td><span className={`monitor-status ${file.status}`}>{file.status}</span></td><td>{duration(file.elapsed_seconds)}</td><td>{file.stage_detail}{file.error_code ? <small>{file.error_code}</small> : null}</td></tr>)}</tbody></table></div> : !loading ? <div className="empty-state">当前筛选没有文件。</div> : null}
|
||||
</> : null}</div>
|
||||
</div>
|
||||
</> : null}
|
||||
</section> : null}
|
||||
{lane === 'pending' ? <section className="inbox-section" aria-label="排队等待">
|
||||
<div className="section-head"><h2>排队等待({queueFiltered.length})</h2><span className="spacer" /><label>目标知识库<select aria-label="队列目标知识库" value={queueScope} onChange={(event) => onQueueScope(event.target.value as 'internal' | 'external' | '')}><option value="">内/外全部</option><option value="internal">对内知识库</option><option value="external">对外知识库</option></select></label></div>
|
||||
{queueFiltered.length ? queueFiltered.map(actionTask) : emptyLane('当前筛选没有排队任务。')}
|
||||
</section> : null}
|
||||
{lane === 'done' ? <section className="inbox-section" aria-label="已完成">
|
||||
<div className="section-head"><h2>已完成({doneTodayItems.length})</h2><span className="tiny">最近一页数据中的成功任务</span></div>
|
||||
{doneTodayItems.length ? doneTodayItems.map(actionTask) : emptyLane('当前页没有已完成任务;用全部任务视图翻页查看。')}
|
||||
</section> : null}
|
||||
{lane === 'queue' ? <section className="inbox-section" aria-label="全部任务">
|
||||
<div className="section-head"><h2>全部任务({queue.total})</h2><span className="spacer" /><label>目标知识库<select aria-label="队列目标知识库" value={queueScope} onChange={(event) => onQueueScope(event.target.value as 'internal' | 'external' | '')}><option value="">内/外全部</option><option value="internal">对内知识库</option><option value="external">对外知识库</option></select><select aria-label="队列状态" value={queueStatus} onChange={(event) => onQueueStatus(event.target.value as ProcessingState | '')}><option value="">全部状态</option><option value="pending">等待解析</option><option value="processing">解析中</option><option value="finalizing">索引与增强</option><option value="completed">成功</option><option value="failed">失败</option><option value="stalled">停滞</option></select></label></div>
|
||||
{queueFilteredAll.length ? queueFilteredAll.map(actionTask) : !loading ? emptyLane('当前筛选没有解析任务。') : null}
|
||||
</section> : null}
|
||||
{metrics ? <footer className="monitor-strip" aria-label="真实运行指标"><div>1小时·成功 <b className={metrics.short_window.failure_rate !== null && metrics.short_window.failure_rate > 5 ? 'bad' : 'good'}>{metrics.short_window.success_rate === null ? '数据不足' : `${metrics.short_window.success_rate}%`}</b></div><div>24小时·成功 <b>{metrics.long_window.success_rate === null ? '数据不足' : `${metrics.long_window.success_rate}%`}</b></div><div>p50 {metrics.short_window.duration_p50_seconds === null ? '—' : duration(Math.round(metrics.short_window.duration_p50_seconds))} · p95 {metrics.short_window.duration_p95_seconds === null ? '—' : duration(Math.round(metrics.short_window.duration_p95_seconds))}</div><div>Worker {metrics.active_workers} · 等待 {metrics.queue.pending} · 运行 {metrics.queue.running}{metrics.queue.failed ? <span className="bad"> · 失败 {metrics.queue.failed}</span> : null}</div>{overview?.health.map((service) => <div key={service.key}>{service.name} <b className={service.readiness === 'ready' ? 'good' : service.readiness === 'blocked' || service.readiness === 'down' ? 'bad' : ''}>{service.readiness === 'ready' ? '可接单' : service.readiness === 'degraded' ? '降级' : service.readiness === 'not_configured' ? '未配置' : service.readiness === 'down' ? '不可达' : '阻断'}</b></div>)}{overview ? <div>CPU {overview.host.cpu_percent.toFixed(0)}% · 内存 {gb(overview.host.memory_used_bytes)}/{gb(overview.host.memory_total_bytes)}GB</div> : null}</footer> : null}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
}
|
||||
|
||||
export function WeKnoraMonitor() {
|
||||
const [overview, setOverview] = useState<MonitorOverview | null>(null)
|
||||
const [selected, setSelected] = useState<KnowledgeProgress | null>(null)
|
||||
const [files, setFiles] = useState<MonitorFilePage | null>(null)
|
||||
const [queue, setQueue] = useState<TestPublicationPage>(emptyQueue)
|
||||
const [plans, setPlans] = useState<TestPublication[]>([])
|
||||
const [changeSets, setChangeSets] = useState<CatalogChangeSetDetail[]>([])
|
||||
const [confirmingSetID, setConfirmingSetID] = useState<string | null>(null)
|
||||
const [lastConfirmSetID, setLastConfirmSetID] = useState<string | null>(null)
|
||||
const [confirmMessage, setConfirmMessage] = useState('')
|
||||
const [status, setStatus] = useState<MonitorStatus | ''>('')
|
||||
const [queueStatus, setQueueStatus] = useState<ProcessingState | ''>('')
|
||||
const [queueScope, setQueueScope] = useState<'internal' | 'external' | ''>('')
|
||||
const [lane, setLane] = useState<'attention' | 'changes' | 'inflight' | 'pending' | 'done' | 'queue'>('attention')
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const [documentRevision, setDocumentRevision] = useState(0)
|
||||
const [resourceRevision, setResourceRevision] = useState(0)
|
||||
const [documentRefreshMs, setDocumentRefreshMs] = useState(15000)
|
||||
const [resourceRefreshMs, setResourceRefreshMs] = useState(30000)
|
||||
const [retryingIDs, setRetryingIDs] = useState<string[]>([])
|
||||
const [starting, setStarting] = useState(false)
|
||||
const [startMessage, setStartMessage] = useState('')
|
||||
const [batchMessage, setBatchMessage] = useState('')
|
||||
const [failures, setFailures] = useState<JobFailure[]>([])
|
||||
const [metrics, setMetrics] = useState<RunMetrics | null>(null)
|
||||
const setContextTabs = useContext(WorkspaceContextTabsSetter)
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController()
|
||||
void fetchActiveUISettings(controller.signal).then((active) => {
|
||||
const delays = settingsRefreshDelays(active)
|
||||
if (!controller.signal.aborted) { setDocumentRefreshMs(delays.documentMs); setResourceRefreshMs(delays.resourceMs) }
|
||||
}).catch((cause) => { if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : '加载刷新设置失败') })
|
||||
return () => controller.abort()
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController(); setLoading(true)
|
||||
void fetchMonitorOverview(controller.signal).then((result) => {
|
||||
if (controller.signal.aborted) return
|
||||
setOverview(result)
|
||||
setSelected((current) => current && result.knowledge_bases.find((kb) => kb.id === current.id) || result.knowledge_bases[0] || null)
|
||||
setError(null)
|
||||
}).catch((cause) => { if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : '加载资源监控失败') }).finally(() => { if (!controller.signal.aborted) setLoading(false) })
|
||||
return () => controller.abort()
|
||||
}, [resourceRevision])
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController(); setLoading(true)
|
||||
void Promise.all([
|
||||
fetchTestPublications({ processing_state: queueStatus, target_scope: queueScope, limit: 50, offset: 0 }, controller.signal),
|
||||
fetchTestPublications({ processing_state: 'pending', limit: 100, offset: 0 }, controller.signal),
|
||||
fetchCatalogSources(controller.signal).then(async sources => {
|
||||
const results=await Promise.allSettled(sources.map(source=>fetchLatestCatalogChangeSet(source.connection_id,'',20,0,controller.signal)))
|
||||
return results.flatMap(result=>result.status==='fulfilled'?[result.value]:[])
|
||||
}),
|
||||
]).then(([queuePage, planPage, latestChangeSets]) => {
|
||||
if (!controller.signal.aborted) { setQueue(queuePage); setPlans(planPage.items.filter((item) => item.can_start)); setChangeSets(latestChangeSets); setError(null) }
|
||||
}).catch((cause) => { if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : '加载解析队列失败') }).finally(() => { if (!controller.signal.aborted) setLoading(false) })
|
||||
return () => controller.abort()
|
||||
}, [queueStatus, queueScope, documentRevision])
|
||||
|
||||
useEffect(() => {
|
||||
if (!selected) return
|
||||
const controller = new AbortController()
|
||||
setLoading(true)
|
||||
void fetchMonitorFiles(selected.id, status, 20, 0, controller.signal).then((result) => {
|
||||
if (!controller.signal.aborted) setFiles(result)
|
||||
}).catch((cause) => {
|
||||
if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : '加载文档阶段失败')
|
||||
}).finally(() => {
|
||||
if (!controller.signal.aborted) setLoading(false)
|
||||
})
|
||||
return () => controller.abort()
|
||||
}, [selected, status, documentRevision])
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setTimeout(() => setDocumentRevision((value) => value + 1), documentRefreshMs)
|
||||
return () => window.clearTimeout(timer)
|
||||
}, [documentRevision, documentRefreshMs])
|
||||
useEffect(() => {
|
||||
const timer = window.setTimeout(() => setResourceRevision((value) => value + 1), resourceRefreshMs)
|
||||
return () => window.clearTimeout(timer)
|
||||
}, [resourceRevision, resourceRefreshMs])
|
||||
useEffect(() => {
|
||||
setContextTabs(selected ? [{ key: selected.id, label: selected.name, onActivate: () => setStatus('') }] : [])
|
||||
return () => setContextTabs([])
|
||||
}, [selected, setContextTabs])
|
||||
useEffect(() => {
|
||||
const controller = new AbortController()
|
||||
void fetchJobFailures(controller.signal).then((items) => { if (!controller.signal.aborted) setFailures(items) }).catch(() => undefined)
|
||||
return () => controller.abort()
|
||||
}, [documentRevision, resourceRevision])
|
||||
useEffect(() => {
|
||||
const controller = new AbortController()
|
||||
void fetchRunMetrics(controller.signal).then((result) => { if (!controller.signal.aborted) setMetrics(result) }).catch(() => undefined)
|
||||
return () => controller.abort()
|
||||
}, [documentRevision, resourceRevision])
|
||||
|
||||
const retryOne = async (id: string) => {
|
||||
setRetryingIDs((current) => [...current, id])
|
||||
try {
|
||||
await retryPublication(id)
|
||||
setError(null)
|
||||
setDocumentRevision((value) => value + 1)
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : '重试失败')
|
||||
} finally {
|
||||
setRetryingIDs((current) => current.filter((value) => value !== id))
|
||||
}
|
||||
}
|
||||
|
||||
const retryBatch = async (ids: string[], operatorRaw: string) => {
|
||||
const operator = operatorRaw.trim()
|
||||
if (!operator) { setError('批量重试需要填写操作人'); return }
|
||||
setRetryingIDs(ids)
|
||||
setBatchMessage('')
|
||||
try {
|
||||
const result = await retryPublicationsBatch(ids, operator, '解析队列批量重试')
|
||||
setError(null)
|
||||
const skipped = result.already_running + result.not_retryable
|
||||
setBatchMessage(`已重新入队 ${result.started} 项${skipped ? `,跳过 ${skipped} 项(处理中或不可重试)` : ''}`)
|
||||
setDocumentRevision((value) => value + 1)
|
||||
} catch (cause) {
|
||||
setError(cause instanceof Error ? cause.message : '批量重试失败')
|
||||
} finally {
|
||||
setRetryingIDs([])
|
||||
}
|
||||
}
|
||||
|
||||
const startPlans = async (ids: string[], operator: string, reason: string) => {
|
||||
setStarting(true)
|
||||
setStartMessage('')
|
||||
try {
|
||||
const result = await startTestPublications(ids, operator, reason)
|
||||
setStartMessage(`已确认 ${result.selected} 项;新建解析任务 ${result.started} 项;已开始 ${result.already_started} 项;不可处理 ${result.unavailable} 项。`)
|
||||
setError(null)
|
||||
setDocumentRevision((value) => value + 1)
|
||||
} catch (cause) {
|
||||
setStartMessage(cause instanceof Error ? cause.message : '开始处理失败')
|
||||
} finally {
|
||||
setStarting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const confirmChangeSet = async (changeSetID: string, itemSeqs: number[], operator: string, reason: string) => {
|
||||
if (confirmingSetID) return
|
||||
setConfirmingSetID(changeSetID); setLastConfirmSetID(changeSetID); setConfirmMessage('')
|
||||
try {
|
||||
const {result,operation} = await confirmCatalogChangeSet(changeSetID, itemSeqs, operator, reason)
|
||||
setConfirmMessage(`已${operation==='replayed'?'沿用上次结果':'提交'}:确认 ${result.confirmed_items} 项;新建上传任务 ${result.uploads_created} 个;已有任务 ${result.uploads_existing} 个;请求移除 ${result.removals_requested} 份;内容未就绪 ${result.skipped_no_artifact} 份;缺少目标知识库 ${result.skipped_no_target} 份;未变化 ${result.no_change_ignored} 项已忽略。`)
|
||||
setDocumentRevision((value) => value + 1)
|
||||
} catch (cause) {
|
||||
setConfirmMessage(cause instanceof Error ? cause.message : '确认快照差异失败')
|
||||
} finally {
|
||||
setConfirmingSetID(null)
|
||||
}
|
||||
}
|
||||
return <WeKnoraMonitorView overview={overview} files={files} queue={queue} plans={plans} changeSets={changeSets} confirmingSetID={confirmingSetID ?? lastConfirmSetID} confirmMessage={confirmMessage} onConfirmChangeSet={(id,seqs,operator,reason)=>void confirmChangeSet(id,seqs,operator,reason)} selectedKB={selected} status={status} queueStatus={queueStatus} queueScope={queueScope} loading={loading} error={error} retryingIDs={retryingIDs} starting={starting} startMessage={startMessage} batchMessage={batchMessage} failures={failures} metrics={metrics} onSelectKB={(kb) => { setSelected(kb); setStatus(''); setFiles(null) }} onStatus={(value) => { setStatus(value); setFiles(null) }} onQueueStatus={setQueueStatus} onQueueScope={setQueueScope} lane={lane} onLaneChange={(value) => setLane(value as typeof lane)} onRetry={(id) => void retryOne(id)} onBatchRetry={(ids, operator) => void retryBatch(ids, operator)} onStart={(ids, operator, reason) => void startPlans(ids, operator, reason)} onRefresh={() => { setDocumentRevision((value) => value + 1); setResourceRevision((value) => value + 1) }} />
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { fetchSourceAssets, parseSourceAssetsResponse } from './assets'
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
describe('parseSourceAssetsResponse', () => {
|
||||
it('parses the read-only source inventory envelope', () => {
|
||||
const result = parseSourceAssetsResponse({
|
||||
data: [{
|
||||
id: 'si-safe', source_type: 'pp', connection_name: 'PP历史公开知识', size_bytes: 52428801,
|
||||
visibility: 'external', source_change: 'unchanged', content_state: 'over_limit',
|
||||
legacy_status: 'over_limit', has_publication: false, processing_state: '', retrieval_state: '',
|
||||
updated_at: '2026-09-04T00:00:00Z',
|
||||
}],
|
||||
summary: { total: 613, completed: 530, content_alias: 29, over_limit: 54 },
|
||||
limit: 50,
|
||||
offset: 0,
|
||||
})
|
||||
|
||||
expect(result.summary.total).toBe(613)
|
||||
expect(result.items[0].content_state).toBe('over_limit')
|
||||
})
|
||||
})
|
||||
|
||||
describe('fetchSourceAssets', () => {
|
||||
it('requests the selected state and server-side page', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ data: [], summary: { total: 613, completed: 530, content_alias: 29, over_limit: 54 }, limit: 50, offset: 50 }),
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
await fetchSourceAssets({ state: 'over_limit', limit: 50, offset: 50 })
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/api/v1/source-items?state=over_limit&limit=50&offset=50',
|
||||
expect.objectContaining({ headers: { Accept: 'application/json' } }),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,78 @@
|
||||
export type LegacyStatus = 'completed' | 'content_alias' | 'over_limit'
|
||||
|
||||
export interface SourceAsset {
|
||||
title?: string
|
||||
directory_path?: string
|
||||
connection_id?: string
|
||||
visibility_origin?: string
|
||||
scope_rule_path?: string
|
||||
ingest_state?: string
|
||||
last_error?: string
|
||||
publication_id?: string
|
||||
can_retry?: boolean
|
||||
id: string
|
||||
source_type: 'pp' | 'alist' | 'dingtalk' | 'manual'
|
||||
connection_name: string
|
||||
size_bytes: number
|
||||
visibility: 'internal' | 'external'
|
||||
source_change: 'unchanged' | 'added' | 'updated' | 'deleted' | 'unavailable'
|
||||
content_state: 'unknown' | 'downloading' | 'verified' | 'invalid' | 'over_limit' | 'failed'
|
||||
legacy_status: LegacyStatus | ''
|
||||
has_publication: boolean
|
||||
processing_state: string
|
||||
retrieval_state: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface SourceAssetSummary {
|
||||
total: number
|
||||
completed: number
|
||||
content_alias: number
|
||||
over_limit: number
|
||||
}
|
||||
|
||||
export interface SourceAssetPage {
|
||||
items: SourceAsset[]
|
||||
summary: SourceAssetSummary
|
||||
limit: number
|
||||
offset: number
|
||||
}
|
||||
|
||||
export interface SourceAssetQuery {
|
||||
state: LegacyStatus | ''
|
||||
limit: number
|
||||
offset: number
|
||||
}
|
||||
|
||||
export function parseSourceAssetsResponse(value: unknown): SourceAssetPage {
|
||||
if (
|
||||
typeof value !== 'object' || value === null ||
|
||||
!('data' in value) || !Array.isArray(value.data) ||
|
||||
!('summary' in value) || typeof value.summary !== 'object' || value.summary === null ||
|
||||
!('limit' in value) || typeof value.limit !== 'number' ||
|
||||
!('offset' in value) || typeof value.offset !== 'number'
|
||||
) {
|
||||
throw new Error('invalid source assets response')
|
||||
}
|
||||
return {
|
||||
items: value.data as SourceAsset[],
|
||||
summary: value.summary as SourceAssetSummary,
|
||||
limit: value.limit,
|
||||
offset: value.offset,
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchSourceAssets(query: SourceAssetQuery, signal?: AbortSignal): Promise<SourceAssetPage> {
|
||||
const parameters = new URLSearchParams()
|
||||
if (query.state) parameters.set('state', query.state)
|
||||
parameters.set('limit', String(query.limit))
|
||||
parameters.set('offset', String(query.offset))
|
||||
const response = await fetch(`/api/v1/source-items?${parameters.toString()}`, {
|
||||
headers: { Accept: 'application/json' },
|
||||
signal,
|
||||
})
|
||||
if (!response.ok) {
|
||||
throw new Error(`加载知识资产失败(HTTP ${response.status})`)
|
||||
}
|
||||
return parseSourceAssetsResponse(await response.json())
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { SourceAsset } from './assets'
|
||||
|
||||
export const document: SourceAsset = {
|
||||
id: 'a', connection_id: 'pp-1', connection_name: 'PP', source_type: 'pp', title: '手册.pdf', directory_path: '使用指南', visibility_origin: 'pp_public_tag', visibility: 'external', size_bytes: 1024,
|
||||
content_state: 'verified', source_change: 'unchanged', legacy_status: 'completed', has_publication: true, ingest_state: 'uploaded', processing_state: 'completed', retrieval_state: 'unpublished', last_error: '', publication_id: 'p-a', updated_at: '2026-09-06T01:00:00Z',
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
.document-workbench { max-width: 1800px; }
|
||||
.document-layout { display: grid; grid-template-columns: 250px minmax(0, 1fr); gap: 18px; align-items: start; }
|
||||
.directory-panel, .document-content { min-width: 0; background: white; border: 1px solid var(--border-base); border-radius: 14px; }
|
||||
.directory-panel { padding: 10px; max-height: calc(100vh - 220px); overflow-y: auto; }
|
||||
.directory-panel .folder { display: flex; width: 100%; align-items: center; justify-content: space-between; gap: 10px; border: 0; border-radius: 8px; padding: 11px 10px; background: transparent; color: var(--ink-base); text-align: left; box-shadow: none; }
|
||||
.directory-panel .folder:hover { background: var(--c-run-bg); }
|
||||
.directory-panel .folder.active { background: var(--c-run-bg); color: var(--c-run); }
|
||||
.directory-panel .folder span { overflow-wrap: anywhere; }
|
||||
.directory-panel .folder.child { padding-left: 23px; font-size: 12px; font-weight: 500; }
|
||||
.directory-panel .folder b { flex: 0 0 auto; font-size: 12px; }
|
||||
.directory-note { display: block; padding: 8px 12px; color: var(--ink-mute); font-size: 12px; line-height: 1.6; }
|
||||
.source-unconnected { margin: 8px 0; padding: 12px; border-top: 1px solid var(--bg-soft); color: var(--ink-mute); }
|
||||
.source-unconnected small { display: block; margin-top: 6px; }
|
||||
.test-document-toggle { display: flex; align-items: center; gap: 8px; margin: 12px 8px 4px; padding-top: 12px; border-top: 1px solid var(--border-base); color: var(--ink-mute); font-size: 12px; }
|
||||
.source-progress { margin-bottom: 16px; padding: 16px 18px; border: 1px solid var(--border-base); border-radius: 14px; background: var(--bg-panel); }
|
||||
.section-title { display: flex; justify-content: space-between; gap: 16px; margin-bottom: 12px; color: var(--ink-base); }
|
||||
.section-title span { color: var(--ink-mute); font-size: 12px; }
|
||||
.source-progress-grid { display: grid; grid-template-columns: repeat(auto-fit,minmax(230px,1fr)); gap: 10px; }
|
||||
.source-progress-card { display: grid; gap: 6px; padding: 13px 15px; border: 1px solid var(--border-base); border-radius: 10px; background: var(--bg-soft); color: var(--ink-base); text-align: left; box-shadow: none; }
|
||||
.source-progress-card.active { border-color: var(--c-run); background: var(--c-run-bg); }
|
||||
.source-progress-card span { font-weight: 700; }
|
||||
.source-progress-card small { color: var(--ink-mute); }
|
||||
|
||||
.document-counts { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); padding: 18px; border-bottom: 1px solid var(--border-base); gap: 10px; }
|
||||
.document-counts span { font-size: 12px; color: var(--ink-mute); }
|
||||
.document-counts b { display: block; margin-top: 5px; font-size: 24px; color: var(--ink-strong); }
|
||||
.document-filters { display: flex; flex-wrap: wrap; gap: 12px; padding: 16px 18px; align-items: end; }
|
||||
.document-filters label { display: grid; gap: 6px; font-size: 12px; color: var(--ink-base); }
|
||||
.document-filters label:first-child { flex: 1; min-width: 140px; }
|
||||
.document-filters input, .document-filters select { width: 100%; min-width: 0; border: 1px solid var(--border-strong); border-radius: 8px; padding: 10px; background: white; color: var(--ink-strong); }
|
||||
.scope-editor { margin: 14px 18px 2px; padding: 13px 14px; border: 1px solid var(--border-strong); border-radius: 10px; background: var(--bg-soft); }
|
||||
.scope-editor-heading { display: flex; justify-content: space-between; gap: 12px; align-items: center; }
|
||||
.scope-editor-heading > div { display: grid; gap: 3px; }
|
||||
.scope-editor-heading span, .scope-rule-meta, .scope-editor small { color: var(--ink-mute); font-size: 11px; }
|
||||
.inherited-badge { padding: 5px 7px; border-radius: 6px; background: var(--bg-soft); color: var(--ink-mute); font-weight: 650; }
|
||||
.scope-rule-meta { margin: 7px 0 10px; }
|
||||
.scope-editor-fields { display: grid; grid-template-columns: 120px 160px minmax(180px,1fr); gap: 9px; }
|
||||
.scope-editor-fields label { display: grid; gap: 4px; color: var(--ink-base); font-size: 11px; }
|
||||
.scope-editor-fields input, .scope-editor-fields select { min-width: 0; padding: 8px; border: 1px solid var(--border-strong); border-radius: 7px; background: var(--bg-panel); }
|
||||
.scope-editor-actions { display: flex; gap: 8px; align-items: center; margin: 10px 0 7px; }
|
||||
.scope-editor-actions button { padding: 8px 12px; }
|
||||
.scope-editor-actions .secondary { background: var(--bg-panel); color: var(--ink-base); border-color: var(--ink-faint); box-shadow: none; }
|
||||
.scope-error, .scope-unavailable { margin: 10px 18px; padding: 10px 12px; border-radius: 8px; background: var(--c-warn-bg); color: var(--c-warn); font-size: 12px; }
|
||||
.document-location { padding: 0 18px 14px; font-size: 13px; font-weight: 650; color: var(--ink-base); }
|
||||
.document-location span { float: right; color: var(--ink-mute); font-weight: 400; }
|
||||
.document-table { table-layout: fixed; width: 100%; }
|
||||
.document-content .table-wrap { max-height: max(300px, calc(100vh - 470px)); overflow: auto; }
|
||||
.document-table thead th { position: sticky; top: 0; z-index: 1; background: var(--bg-soft); }
|
||||
.document-table th:nth-child(1) { width: 37%; }
|
||||
.document-table th:nth-child(2) { width: 16%; }
|
||||
.document-table th:nth-child(3) { width: 19%; }
|
||||
.document-table th:nth-child(4) { width: 10%; }
|
||||
.document-table th:nth-child(5) { width: 18%; }
|
||||
.document-table th, .document-table td { padding: 13px 12px; white-space: normal; overflow-wrap: anywhere; font-size: 12px; }
|
||||
.document-table small { display: block; margin-top: 7px; color: var(--ink-mute); font-size: 11px; }
|
||||
.document-workbench .file-link { padding: 0; border: 0; background: transparent; color: var(--c-run); text-align: left; font-size: 13px; box-shadow: none; white-space: normal; overflow-wrap: anywhere; line-height: 1.55; }
|
||||
.document-workbench .file-link:hover { text-decoration: underline; }
|
||||
.scope-badge, .document-stage { display: inline-block; border-radius: 6px; padding: 5px 7px; font-size: 12px; font-weight: 650; background: var(--border-soft); color: var(--ink-base); }
|
||||
.scope-badge.external { color: var(--c-done); background: var(--c-done-bg); }
|
||||
.scope-badge.internal { color: var(--ink-base); background: var(--c-run-bg); }
|
||||
.document-stage.completed, .document-stage.reused { color: var(--c-done); background: var(--c-done-bg); }
|
||||
.document-stage.blocked, .document-stage.failed { color: var(--c-warn); background: var(--c-warn-bg); }
|
||||
.document-stage.parsing, .document-stage.indexing, .document-stage.uploading, .document-stage.downloading { color: var(--c-run); background: var(--c-run-bg); }
|
||||
.document-inspector { position: fixed; top: 80px; right: 20px; bottom: 20px; z-index: 50; width: min(480px, calc(100vw - 40px)); overflow-y: auto; background: white; border: 2px solid var(--c-run-border); box-shadow: 0 12px 48px #12345240; margin: 0; }
|
||||
.document-inspector h2 { overflow-wrap: anywhere; font-size: 17px; }
|
||||
.inspector-body { padding: 0 22px 20px; font-size: 13px; line-height: 1.7; color: var(--ink-base); }
|
||||
.inspector-body dl { display: grid; grid-template-columns: 100px minmax(0,1fr); gap: 8px; }
|
||||
.inspector-body dd { margin: 0; overflow-wrap: anywhere; }
|
||||
.file-facts { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 8px; margin: 14px 0; }
|
||||
.file-facts span { display: grid; padding: 9px; border-radius: 8px; background: var(--bg-soft); color: var(--ink-mute); font-size: 11px; }
|
||||
.file-facts b { margin-top: 3px; color: var(--ink-base); font-size: 12px; }
|
||||
.document-pipeline { display: grid; grid-template-columns: repeat(4,minmax(0,1fr)); gap: 5px; margin: 14px 0; }
|
||||
.pipeline-step { display: grid; grid-template-columns: 9px minmax(0,1fr); gap: 6px; align-items: start; padding: 8px 5px; border-radius: 7px; background: var(--bg-soft); }
|
||||
.pipeline-step > span { width: 8px; height: 8px; margin-top: 5px; border-radius: 50%; background: var(--ink-faint); }
|
||||
.pipeline-step div { display: grid; min-width: 0; }
|
||||
.pipeline-step strong { font-size: 10px; color: var(--ink-base); }
|
||||
.pipeline-step small { color: var(--ink-mute); font-size: 9px; overflow-wrap: anywhere; }
|
||||
.pipeline-step.done > span { background: var(--c-done); }
|
||||
.pipeline-step.active > span { background: var(--c-run); }
|
||||
.pipeline-step.problem > span { background: var(--c-warn); }
|
||||
.document-inspector .scope-editor { margin: 16px 0; }
|
||||
.document-workbench button:disabled { cursor: not-allowed; color: var(--ink-faint); background: var(--bg-soft); border-color: var(--border-base); }
|
||||
@media (max-width: 1150px) {
|
||||
.document-layout { grid-template-columns: 205px minmax(0,1fr); }
|
||||
.document-counts { grid-template-columns: repeat(3,minmax(0,1fr)); }
|
||||
.document-table th, .document-table td { padding: 10px 7px; }
|
||||
.scope-editor-fields { grid-template-columns: 1fr 1fr; }
|
||||
.scope-reason { grid-column: 1/-1; }
|
||||
}
|
||||
@media (max-width: 860px) {
|
||||
.document-layout { grid-template-columns: 1fr; }
|
||||
.directory-panel { max-height: 260px; }
|
||||
.document-table { min-width: 650px; }
|
||||
.document-counts { grid-template-columns: repeat(3,minmax(0,1fr)); }
|
||||
.section-title { display: grid; }
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { documentPipeline, documentStage, directoryGroups, filterDocuments, fetchDocumentCatalog, operationalDocuments, sourceProgress, visibilityOrigin } from './documentWorkbench'
|
||||
import { document } from './documentFixture'
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
describe('document workbench', () => {
|
||||
it('groups by actual connection and directory, never merges independent sources', () => {
|
||||
const groups = directoryGroups([document, {...document, id:'b',connection_id:'pp-2'}])
|
||||
expect(groups).toHaveLength(2)
|
||||
expect(groups[0].count).toBe(1)
|
||||
expect(groups[0].path).toBe('使用指南')
|
||||
})
|
||||
it('maps observed stages and never treats missing publication as failure or published', () => {
|
||||
expect(documentStage(document)).toBe('completed')
|
||||
expect(documentStage({...document, has_publication:false, legacy_status:''})).toBe('waiting')
|
||||
expect(documentStage({...document, content_state:'over_limit',has_publication:false})).toBe('blocked')
|
||||
expect(documentStage({...document, legacy_status:'content_alias',has_publication:false})).toBe('reused')
|
||||
expect(documentStage({...document, processing_state:'stalled'})).toBe('failed')
|
||||
expect(documentStage({...document, processing_state:'finalizing'})).toBe('indexing')
|
||||
})
|
||||
it('builds a factual pipeline without inventing page progress or production status',()=>{
|
||||
expect(documentPipeline(document)).toEqual([
|
||||
{label:'取得文件',state:'done',detail:'文件已校验'},
|
||||
{label:'上传测试库',state:'done',detail:'上传完成'},
|
||||
{label:'解析与索引',state:'done',detail:'解析完成'},
|
||||
{label:'测试检索',state:'waiting',detail:'未证明已启用'},
|
||||
])
|
||||
expect(documentPipeline({...document,content_state:'over_limit',has_publication:false})[0]).toEqual({label:'取得文件',state:'problem',detail:'文件超限'})
|
||||
})
|
||||
it('shows whether scope comes from a file override, directory inheritance or source metadata',()=>{
|
||||
expect(visibilityOrigin({...document,visibility_origin:'file_override'})).toBe('文件单独设置')
|
||||
expect(visibilityOrigin({...document,visibility_origin:'directory_rule',scope_rule_path:'产品'})).toBe('继承目录设置:产品')
|
||||
expect(visibilityOrigin({...document,visibility_origin:'configured_scope'})).toBe('来源范围设置')
|
||||
})
|
||||
it('filters source directory, scope, stage and filename together', () => {
|
||||
expect(filterDocuments([document, {...document,id:'b',visibility:'internal'}], {connection:'pp-1',directory:'使用指南',query:'手册',visibility:'external',stage:'completed'}).map(x=>x.id)).toEqual(['a'])
|
||||
})
|
||||
it('hides isolated acceptance fixtures unless the engineer asks to see them',()=>{
|
||||
const manual={...document,id:'manual',source_type:'manual' as const,connection_id:'manual-1'}
|
||||
expect(operationalDocuments([document,manual],false).map(x=>x.id)).toEqual(['a'])
|
||||
expect(operationalDocuments([document,manual],true)).toHaveLength(2)
|
||||
})
|
||||
it('aggregates truthful source-level processing stages without fabricated percentages',()=>{
|
||||
const progress=sourceProgress([
|
||||
document,
|
||||
{...document,id:'active',processing_state:'processing'},
|
||||
{...document,id:'blocked',content_state:'over_limit',has_publication:false},
|
||||
{...document,id:'waiting',has_publication:false,legacy_status:''},
|
||||
{...document,id:'reused',legacy_status:'content_alias',has_publication:false},
|
||||
])
|
||||
expect(progress).toEqual([{connection:'pp-1',total:5,completed:1,active:1,attention:1,waiting:1,reused:1}])
|
||||
})
|
||||
it('collects every page before claiming a complete directory tree', async () => {
|
||||
const fetch = vi.fn().mockResolvedValueOnce(new Response(JSON.stringify({data:[document],summary:{total:2},limit:1,offset:0}))).mockResolvedValueOnce(new Response(JSON.stringify({data:[{...document,id:'b'}],summary:{total:2},limit:1,offset:1})))
|
||||
vi.stubGlobal('fetch',fetch)
|
||||
expect(await fetchDocumentCatalog()).toHaveLength(2)
|
||||
expect(fetch).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
it('rejects incomplete or duplicate pages rather than reporting wrong totals', async () => {
|
||||
vi.stubGlobal('fetch',vi.fn()
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({data:[document],summary:{total:2},limit:1,offset:0})))
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({data:[document],summary:{total:2},limit:1,offset:1}))))
|
||||
await expect(fetchDocumentCatalog()).rejects.toThrow('文档分页发生变化')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,128 @@
|
||||
import { fetchSourceAssets } from './assets'
|
||||
import type { SourceAsset } from './assets'
|
||||
|
||||
export type DocumentStage = 'waiting' | 'downloading' | 'uploading' | 'parsing' | 'indexing' | 'completed' | 'reused' | 'blocked' | 'failed'
|
||||
export const stageLabels: Record<DocumentStage, string> = {
|
||||
waiting: '等待处理', downloading: '下载中', uploading: '上传中', parsing: '解析中', indexing: '建立索引', completed: '解析完成', reused: '内容重复,复用已有文档', blocked: '文件超限', failed: '需要处理',
|
||||
}
|
||||
export type PipelineState='waiting'|'active'|'done'|'problem'
|
||||
export interface PipelineStep {label:string;state:PipelineState;detail:string}
|
||||
export function documentPipeline(item:SourceAsset):PipelineStep[]{
|
||||
let source:PipelineStep={label:'取得文件',state:'waiting',detail:'等待取得文件'}
|
||||
if(item.content_state==='verified')source={label:'取得文件',state:'done',detail:'文件已校验'}
|
||||
else if(item.content_state==='downloading')source={label:'取得文件',state:'active',detail:'下载中'}
|
||||
else if(item.content_state==='over_limit')source={label:'取得文件',state:'problem',detail:'文件超限'}
|
||||
else if(['invalid','failed'].includes(item.content_state))source={label:'取得文件',state:'problem',detail:'文件校验失败'}
|
||||
let upload:PipelineStep={label:'上传测试库',state:'waiting',detail:'等待上传'}
|
||||
if(item.legacy_status==='content_alias')upload={label:'上传测试库',state:'done',detail:'复用已有内容'}
|
||||
else if(item.ingest_state==='uploaded')upload={label:'上传测试库',state:'done',detail:'上传完成'}
|
||||
else if(item.ingest_state==='uploading')upload={label:'上传测试库',state:'active',detail:'上传中'}
|
||||
else if(item.ingest_state==='failed')upload={label:'上传测试库',state:'problem',detail:'上传失败'}
|
||||
let processing:PipelineStep={label:'解析与索引',state:'waiting',detail:'等待解析'}
|
||||
if(item.legacy_status==='content_alias')processing={label:'解析与索引',state:'done',detail:'复用已有解析结果'}
|
||||
else if(item.processing_state==='completed')processing={label:'解析与索引',state:'done',detail:'解析完成'}
|
||||
else if(item.processing_state==='processing')processing={label:'解析与索引',state:'active',detail:'解析中'}
|
||||
else if(item.processing_state==='finalizing')processing={label:'解析与索引',state:'active',detail:'建立索引中'}
|
||||
else if(['failed','stalled'].includes(item.processing_state))processing={label:'解析与索引',state:'problem',detail:item.processing_state==='stalled'?'处理停滞':'解析失败'}
|
||||
let retrieval:PipelineStep={label:'测试检索',state:'waiting',detail:'未证明已启用'}
|
||||
if(item.retrieval_state==='enabled')retrieval={label:'测试检索',state:'done',detail:'测试环境已启用'}
|
||||
else if(['enabling','disabling'].includes(item.retrieval_state))retrieval={label:'测试检索',state:'active',detail:'状态变更中'}
|
||||
else if(item.retrieval_state==='failed')retrieval={label:'测试检索',state:'problem',detail:'检索状态失败'}
|
||||
return [source,upload,processing,retrieval]
|
||||
}
|
||||
export function documentStage(item: SourceAsset): DocumentStage {
|
||||
if (item.source_change === 'unavailable' || item.source_change === 'deleted') return 'failed'
|
||||
if (item.content_state === 'over_limit') return 'blocked'
|
||||
if (['invalid','failed'].includes(item.content_state) || item.ingest_state === 'failed' || ['failed','stalled'].includes(item.processing_state)) return 'failed'
|
||||
if (item.content_state === 'downloading') return 'downloading'
|
||||
if (item.legacy_status === 'content_alias' && !item.has_publication) return 'reused'
|
||||
if (!item.has_publication) return 'waiting'
|
||||
if (item.ingest_state === 'uploading') return 'uploading'
|
||||
switch (item.processing_state) {
|
||||
case 'completed': return 'completed'
|
||||
case 'processing': return 'parsing'
|
||||
case 'finalizing': return 'indexing'
|
||||
default: return 'waiting'
|
||||
}
|
||||
}
|
||||
export function documentProblem(item: SourceAsset): string {
|
||||
if (item.source_change === 'unavailable' || item.source_change === 'deleted') return '来源文件缺失或暂不可访问,请核对来源权限和文件位置。'
|
||||
if (documentStage(item) === 'blocked') return '超过当前导入大小上限,尚未上传;请拆分文件或由管理员调整限制。'
|
||||
if (item.processing_state === 'stalled') return '长时间未收到处理进展,请检查解析服务。'
|
||||
if (documentStage(item) === 'failed') return '处理未完成,请查看错误详情;符合重试条件时可重新处理。'
|
||||
if (documentStage(item) === 'reused') return '文件内容完全相同,未重复上传。'
|
||||
return ''
|
||||
}
|
||||
export function visibilityOrigin(item: SourceAsset): string {
|
||||
switch (item.visibility_origin) {
|
||||
case 'pp_public_tag': return '来自PP公开标记'
|
||||
case 'manual': return '人工指定'
|
||||
case 'configured_scope': return '来源范围设置'
|
||||
case 'file_override': return '文件单独设置'
|
||||
case 'directory_rule': return item.scope_rule_path ? `继承目录设置:${item.scope_rule_path}` : '继承来源范围设置'
|
||||
default: return '设置来源待核对'
|
||||
}
|
||||
}
|
||||
export function connectionKey(item: SourceAsset): string {
|
||||
return item.connection_id || `${item.source_type}:${item.connection_name}`
|
||||
}
|
||||
export function directoryGroups(items: SourceAsset[]) {
|
||||
const groups = new Map<string, {key:string; connection:string; path:string; count:number}>()
|
||||
for (const item of items) {
|
||||
const connection = connectionKey(item)
|
||||
const path = item.directory_path || ''
|
||||
// JSON tuple avoids cross-source collisions, even when labels contain separators.
|
||||
const key = JSON.stringify([connection, path])
|
||||
const group = groups.get(key) || {key, connection, path, count:0}
|
||||
group.count++
|
||||
groups.set(key, group)
|
||||
}
|
||||
return [...groups.values()].sort((a,b) => a.path.localeCompare(b.path,'zh-CN') || a.connection.localeCompare(b.connection))
|
||||
}
|
||||
export function operationalDocuments(items:SourceAsset[],includeTestDocuments:boolean) {
|
||||
return includeTestDocuments ? items : items.filter(item=>item.source_type!=='manual')
|
||||
}
|
||||
export interface SourceProgress {connection:string;total:number;completed:number;active:number;attention:number;waiting:number;reused:number}
|
||||
export function sourceProgress(items:SourceAsset[]):SourceProgress[] {
|
||||
const result=new Map<string,SourceProgress>()
|
||||
for(const item of items){
|
||||
const connection=connectionKey(item)
|
||||
const progress=result.get(connection)||{connection,total:0,completed:0,active:0,attention:0,waiting:0,reused:0}
|
||||
const stage=documentStage(item)
|
||||
progress.total++
|
||||
if(stage==='completed') progress.completed++
|
||||
if(['downloading','uploading','parsing','indexing'].includes(stage)) progress.active++
|
||||
if(['blocked','failed'].includes(stage)) progress.attention++
|
||||
if(stage==='waiting') progress.waiting++
|
||||
if(stage==='reused') progress.reused++
|
||||
result.set(connection,progress)
|
||||
}
|
||||
return [...result.values()].sort((a,b)=>a.connection.localeCompare(b.connection))
|
||||
}
|
||||
export interface DocumentFilter { connection:string; directory:string|null; query:string; visibility:string; stage:string }
|
||||
export function filterDocuments(items: SourceAsset[], filter: DocumentFilter) {
|
||||
const query = filter.query.trim().toLocaleLowerCase()
|
||||
return items.filter(item => (!filter.connection || connectionKey(item) === filter.connection)
|
||||
&& (filter.directory === null || (item.directory_path || '') === filter.directory)
|
||||
&& (!filter.visibility || item.visibility === filter.visibility)
|
||||
&& (!filter.stage || documentStage(item) === filter.stage)
|
||||
&& (!query || `${item.title || ''} ${item.directory_path || ''}`.toLocaleLowerCase().includes(query)))
|
||||
}
|
||||
export async function fetchDocumentCatalog(signal?: AbortSignal): Promise<SourceAsset[]> {
|
||||
const items: SourceAsset[] = []
|
||||
const ids = new Set<string>()
|
||||
let expected: number | undefined
|
||||
do {
|
||||
const page = await fetchSourceAssets({state:'',limit:100,offset:items.length},signal)
|
||||
if (expected === undefined) expected = page.summary.total
|
||||
if (!Number.isInteger(expected) || expected < 0 || expected > 10000 || page.summary.total !== expected || page.offset !== items.length) throw new Error('文档清单已变化或过大,请刷新后重试。')
|
||||
for (const item of page.items) {
|
||||
if (!item.id || ids.has(item.id)) throw new Error('文档分页发生变化,请刷新后重试。')
|
||||
ids.add(item.id)
|
||||
items.push(item)
|
||||
}
|
||||
if (!page.items.length && items.length !== expected) throw new Error('文档清单未加载完整,请重试。')
|
||||
} while (items.length < expected)
|
||||
if (items.length !== expected) throw new Error('文档数量核验失败,请重试。')
|
||||
return items
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { fetchJobs, parseJobsResponse } from './jobs'
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
describe('parseJobsResponse', () => {
|
||||
it('returns typed jobs from the API envelope', () => {
|
||||
const result = parseJobsResponse({
|
||||
data: [
|
||||
{
|
||||
id: 'job-1',
|
||||
type: 'demo',
|
||||
payload: { message: 'hello' },
|
||||
state: 'running',
|
||||
priority: 2,
|
||||
available_at: '2026-09-03T13:00:00Z',
|
||||
attempt: 1,
|
||||
max_attempts: 5,
|
||||
idempotency_key: 'demo:1',
|
||||
created_at: '2026-09-03T13:00:00Z',
|
||||
updated_at: '2026-09-03T13:00:01Z',
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
expect(result).toHaveLength(1)
|
||||
expect(result[0]).toMatchObject({ id: 'job-1', state: 'running', attempt: 1 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('fetchJobs', () => {
|
||||
it('loads the latest 50 jobs from the read-only list endpoint', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ data: [] }),
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
await expect(fetchJobs()).resolves.toEqual([])
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/jobs?limit=50', {
|
||||
headers: { Accept: 'application/json' },
|
||||
signal: undefined,
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,36 @@
|
||||
export type JobState = 'pending' | 'running' | 'retry' | 'completed' | 'failed'
|
||||
|
||||
export interface Job {
|
||||
id: string
|
||||
type: string
|
||||
payload: unknown
|
||||
state: JobState
|
||||
priority: number
|
||||
available_at: string
|
||||
lease_owner?: string
|
||||
lease_until?: string
|
||||
attempt: number
|
||||
max_attempts: number
|
||||
last_error?: string
|
||||
idempotency_key: string
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export function parseJobsResponse(value: unknown): Job[] {
|
||||
if (typeof value !== 'object' || value === null || !('data' in value) || !Array.isArray(value.data)) {
|
||||
throw new Error('invalid jobs response')
|
||||
}
|
||||
return value.data as Job[]
|
||||
}
|
||||
|
||||
export async function fetchJobs(signal?: AbortSignal): Promise<Job[]> {
|
||||
const response = await fetch('/api/v1/jobs?limit=50', {
|
||||
headers: { Accept: 'application/json' },
|
||||
signal,
|
||||
})
|
||||
if (!response.ok) {
|
||||
throw new Error(`加载任务失败(HTTP ${response.status})`)
|
||||
}
|
||||
return parseJobsResponse(await response.json())
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
|
||||
import App from './App'
|
||||
import './styles.css'
|
||||
|
||||
const root = document.getElementById('root')
|
||||
if (!root) {
|
||||
throw new Error('missing #root element')
|
||||
}
|
||||
|
||||
createRoot(root).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -0,0 +1,34 @@
|
||||
import { afterEach,describe,expect,it,vi } from 'vitest'
|
||||
import { fetchMonitorFiles,fetchMonitorOverview,fetchRunMetrics } from './monitor'
|
||||
|
||||
afterEach(()=>vi.unstubAllGlobals())
|
||||
const overview={mode:'simulation',simulated:true,observed_at:'2026-09-08T12:00:00Z',host:{cpu_percent:42,memory_used_bytes:19971597926,memory_total_bytes:34359738368,simulated:true},services:[{key:'mineru',name:'MinerU',state:'healthy',detail:'模拟',latency_ms:24,observed_at:'2026-09-08T12:00:00Z',simulated:true}],knowledge_bases:[{id:'kb-sim',name:'公司级技术支持知识库',visibility:'mixed',imported:5750,completed:4530,pending:450,processing:50,finalizing:714,failed:6,cancelled:0,internal_imported:4200,internal_completed:3300,external_imported:1550,external_completed:1230}]}
|
||||
describe('monitor API',()=>{
|
||||
it('requires the backend to label simulation mode explicitly',async()=>{
|
||||
vi.stubGlobal('fetch',vi.fn().mockResolvedValue(new Response(JSON.stringify(overview))))
|
||||
expect((await fetchMonitorOverview()).simulated).toBe(true)
|
||||
})
|
||||
it('filters files by real WeKnora status contract',async()=>{
|
||||
const fetchMock=vi.fn().mockResolvedValue(new Response(JSON.stringify({items:[{name:'[模拟] 文件.pdf',directory:'02 产品资料',visibility:'internal',status:'finalizing',stage_detail:'Wiki生成中',elapsed_seconds:120,error_code:''}],total:1,limit:20,offset:0,sample_only:true})))
|
||||
vi.stubGlobal('fetch',fetchMock)
|
||||
const page=await fetchMonitorFiles('kb-sim','finalizing',20,0)
|
||||
expect(page.sample_only).toBe(true)
|
||||
expect(fetchMock.mock.calls[0][0]).toBe('/api/v1/monitor/knowledge-bases/kb-sim/files?status=finalizing&limit=20&offset=0')
|
||||
})
|
||||
it('keeps insufficient metric samples null and requires a source label',async()=>{
|
||||
const payload={data:{observed_at:'2026-09-12T08:00:00Z',active_workers:2,worker_source:'pg_lease',
|
||||
queue:{pending:1,running:4,retry:1,failed:4,oldest_pending_age_seconds:10800},
|
||||
short_window:{window_seconds:3600,jobs_started:9,jobs_completed:6,jobs_failed:2,success_rate:75,failure_rate:25,duration_avg_seconds:411.4,duration_p50_seconds:30,duration_p95_seconds:1800},
|
||||
long_window:{window_seconds:86400,jobs_started:10,jobs_completed:0,jobs_failed:0,success_rate:null,failure_rate:null,duration_avg_seconds:null,duration_p50_seconds:null,duration_p95_seconds:null}}}
|
||||
vi.stubGlobal('fetch',vi.fn().mockResolvedValue(new Response(JSON.stringify(payload))))
|
||||
const metrics=await fetchRunMetrics()
|
||||
expect(metrics.worker_source).toBe('pg_lease')
|
||||
expect(metrics.long_window.success_rate).toBeNull()
|
||||
expect(metrics.long_window.duration_p95_seconds).toBeNull()
|
||||
expect(metrics.short_window.success_rate).toBe(75)
|
||||
})
|
||||
it('rejects metrics without a worker source or with a fake zero rate',async()=>{
|
||||
vi.stubGlobal('fetch',vi.fn().mockResolvedValue(new Response(JSON.stringify({data:{observed_at:'',queue:{pending:0},short_window:{window_seconds:3600},long_window:{window_seconds:86400}}}))))
|
||||
await expect(fetchRunMetrics()).rejects.toThrow()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,38 @@
|
||||
export type MonitorStatus='completed'|'pending'|'processing'|'finalizing'|'failed'|'cancelled'
|
||||
export interface MonitorHost{cpu_percent:number;memory_used_bytes:number;memory_total_bytes:number;disk_used_bytes:number;disk_total_bytes:number;gpu_state:string;gpu_detail:string;simulated:boolean}
|
||||
export interface MonitorService{key:string;name:string;state:string;detail:string;latency_ms:number;observed_at:string;simulated:boolean}
|
||||
export interface KnowledgeProgress{id:string;name:string;visibility:string;imported:number;completed:number;pending:number;processing:number;finalizing:number;failed:number;cancelled:number;internal_imported:number;internal_completed:number;external_imported:number;external_completed:number}
|
||||
export interface ServiceHealth{key:string;name:string;liveness:string;readiness:string;reason:string;latency_ms:number;observed_at:string;last_success_at:string|null;consecutive_failures:number;configured:boolean;applicable:boolean}
|
||||
export interface MonitorOverview{mode:string;simulated:boolean;observed_at:string;host:MonitorHost;services:MonitorService[];knowledge_bases:KnowledgeProgress[];health:ServiceHealth[]}
|
||||
export interface MonitorFile{name:string;directory:string;visibility:string;status:MonitorStatus;stage_detail:string;elapsed_seconds:number;error_code:string}
|
||||
export interface MonitorFilePage{items:MonitorFile[];total:number;limit:number;offset:number;sample_only:boolean}
|
||||
const record=(value:unknown):value is Record<string,unknown>=>typeof value==='object'&&value!==null
|
||||
export async function fetchMonitorOverview(signal?:AbortSignal):Promise<MonitorOverview>{
|
||||
const response=await fetch('/api/v1/monitor/overview',{headers:{Accept:'application/json'},signal});if(!response.ok)throw new Error(`加载解析监控失败(HTTP ${response.status})`)
|
||||
const value=await response.json() as unknown;if(!record(value)||typeof value.mode!=='string'||typeof value.simulated!=='boolean'||!record(value.host)||!Array.isArray(value.services)||!Array.isArray(value.knowledge_bases))throw new Error('解析监控响应无效')
|
||||
const health=Array.isArray(value.health)?(value.health as unknown[]).filter(record):[]
|
||||
return {...value,health} as unknown as MonitorOverview
|
||||
}
|
||||
export async function fetchMonitorFiles(knowledgeBaseID:string,status:MonitorStatus|'',limit=20,offset=0,signal?:AbortSignal):Promise<MonitorFilePage>{
|
||||
const query=new URLSearchParams();if(status)query.set('status',status);query.set('limit',String(limit));query.set('offset',String(offset))
|
||||
const response=await fetch(`/api/v1/monitor/knowledge-bases/${encodeURIComponent(knowledgeBaseID)}/files?${query}`,{headers:{Accept:'application/json'},signal});if(!response.ok)throw new Error(`加载文档阶段失败(HTTP ${response.status})`)
|
||||
const value=await response.json() as unknown;if(!record(value)||!Array.isArray(value.items)||typeof value.total!=='number'||typeof value.sample_only!=='boolean')throw new Error('文档阶段响应无效')
|
||||
return value as unknown as MonitorFilePage
|
||||
}
|
||||
|
||||
export interface JobWindowMetrics{window_seconds:number;jobs_started:number;jobs_completed:number;jobs_failed:number;success_rate:number|null;failure_rate:number|null;duration_avg_seconds:number|null;duration_p50_seconds:number|null;duration_p95_seconds:number|null}
|
||||
export interface RunMetrics{observed_at:string;active_workers:number;worker_source:'pg_lease'|'simulation';queue:{pending:number;running:number;retry:number;failed:number;oldest_pending_age_seconds:number|null};short_window:JobWindowMetrics;long_window:JobWindowMetrics}
|
||||
const finiteOrNull=(value:unknown)=>typeof value==='number'&&Number.isFinite(value)?value:null
|
||||
const numberOr=(value:unknown,fallback=0)=>typeof value==='number'&&Number.isFinite(value)?value:fallback
|
||||
const windowMetrics=(value:unknown):JobWindowMetrics=>{if(!record(value))throw new Error('运行指标窗口响应无效')
|
||||
return{window_seconds:numberOr(value.window_seconds),jobs_started:numberOr(value.jobs_started),jobs_completed:numberOr(value.jobs_completed),jobs_failed:numberOr(value.jobs_failed),success_rate:finiteOrNull(value.success_rate),failure_rate:finiteOrNull(value.failure_rate),duration_avg_seconds:finiteOrNull(value.duration_avg_seconds),duration_p50_seconds:finiteOrNull(value.duration_p50_seconds),duration_p95_seconds:finiteOrNull(value.duration_p95_seconds)}}
|
||||
export async function fetchRunMetrics(signal?:AbortSignal):Promise<RunMetrics>{
|
||||
const response=await fetch('/api/v1/monitor/metrics',{headers:{Accept:'application/json'},signal});if(!response.ok)throw new Error(`加载运行指标失败(HTTP ${response.status})`)
|
||||
const value=await response.json() as unknown;if(!record(value)||!record(value.data))throw new Error('运行指标响应无效')
|
||||
const data=value.data as Record<string,unknown>
|
||||
if(data.worker_source!=='pg_lease'&&data.worker_source!=='simulation')throw new Error('运行指标缺少数据来源标记')
|
||||
if(!record(data.queue)||!record(data.short_window)||!record(data.long_window))throw new Error('运行指标字段不完整')
|
||||
return{observed_at:typeof data.observed_at==='string'?data.observed_at:'',active_workers:numberOr(data.active_workers),worker_source:data.worker_source as RunMetrics['worker_source'],
|
||||
queue:{pending:numberOr(data.queue.pending),running:numberOr(data.queue.running),retry:numberOr(data.queue.retry),failed:numberOr(data.queue.failed),oldest_pending_age_seconds:finiteOrNull(data.queue.oldest_pending_age_seconds)},
|
||||
short_window:windowMetrics(data.short_window),long_window:windowMetrics(data.long_window)}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { afterEach,describe,expect,it } from 'vitest'
|
||||
import { newOperationID } from './operationKey'
|
||||
|
||||
const uuidPattern=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
|
||||
const originalCrypto=globalThis.crypto
|
||||
|
||||
afterEach(()=>{
|
||||
Object.defineProperty(globalThis,'crypto',{value:originalCrypto,configurable:true,writable:true})
|
||||
})
|
||||
|
||||
describe('newOperationID',()=>{
|
||||
it('uses crypto.randomUUID when available (secure context)',()=>{
|
||||
expect(newOperationID()).toMatch(uuidPattern)
|
||||
})
|
||||
it('falls back to getRandomValues over plain-HTTP LAN (insecure context)',()=>{
|
||||
const randomUUID=globalThis.crypto?.randomUUID
|
||||
Object.defineProperty(globalThis,'crypto',{configurable:true,value:{randomUUID:undefined,getRandomValues:(buffer:Uint8Array)=>{const source=new Uint8Array([0x6f,0x1a,0x2b,0x3c,0x4d,0x5e,0x6f,0x70,0x81,0x92,0xa3,0xb4,0xc5,0xd6,0xe7,0xf8]);buffer.set(source);return buffer}}})
|
||||
try{
|
||||
const id=newOperationID()
|
||||
// version nibble forced to 4 and variant bits to 10x: 0x6f->0x4f, 0x81->0x81
|
||||
expect(id).toBe('6f1a2b3c-4d5e-4f70-8192-a3b4c5d6e7f8')
|
||||
expect(id).toMatch(uuidPattern)
|
||||
}finally{
|
||||
void randomUUID
|
||||
}
|
||||
})
|
||||
it('refuses to fabricate an identifier when no CSPRNG exists',()=>{
|
||||
Object.defineProperty(globalThis,'crypto',{configurable:true,value:{randomUUID:undefined,getRandomValues:undefined}})
|
||||
expect(()=>newOperationID()).toThrow('当前环境无法安全生成操作标识')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,13 @@
|
||||
export function newOperationID():string{
|
||||
const cryptoApi=globalThis.crypto
|
||||
if(typeof cryptoApi?.randomUUID==='function')return cryptoApi.randomUUID()
|
||||
if(typeof cryptoApi?.getRandomValues==='function'){
|
||||
const bytes=new Uint8Array(16)
|
||||
cryptoApi.getRandomValues(bytes)
|
||||
bytes[6]=(bytes[6]&0x0f)|0x40
|
||||
bytes[8]=(bytes[8]&0x3f)|0x80
|
||||
const hex=Array.from(bytes,value=>value.toString(16).padStart(2,'0')).join('')
|
||||
return `${hex.slice(0,8)}-${hex.slice(8,12)}-${hex.slice(12,16)}-${hex.slice(16,20)}-${hex.slice(20)}`
|
||||
}
|
||||
throw new Error('当前环境无法安全生成操作标识')
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
.release-planner{max-width:1700px}.production-off{border:1px solid var(--c-fail-border);border-radius:8px;padding:7px 10px;background:var(--c-fail-bg);color:var(--c-fail);font-size:12px;font-weight:700}.release-four-steps{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));margin:0 0 16px;padding:0;list-style:none}.release-four-steps li{border-top:3px solid var(--border-base);padding:9px;background:var(--bg-panel);color:var(--ink-mute);font-size:11px;text-align:center}.release-four-steps li.active{border-color:var(--c-run);background:var(--c-run-bg);color:var(--c-run);font-weight:700}.release-four-steps li.danger{border-color:var(--c-fail-border);background:var(--c-fail-bg);color:var(--c-fail)}.release-plan-layout{display:grid;grid-template-columns:minmax(0,1fr) 350px;gap:18px;align-items:start}.release-candidates,.release-plan-summary{border:1px solid var(--border-base);border-radius:14px;background:var(--bg-panel)}.release-plan-heading{display:flex;align-items:center;justify-content:space-between;gap:12px;border-bottom:1px solid var(--border-base);padding:14px 16px}.release-plan-heading>div{display:grid;gap:3px}.release-plan-heading h2,.release-plan-summary h2{margin:0;color:var(--ink-base);font-size:15px}.release-plan-heading span{color:var(--ink-mute);font-size:10px}.release-plan-heading button{padding:7px 10px}.release-candidate-list{display:grid}.release-candidate{display:grid;grid-template-columns:20px minmax(190px,1fr) minmax(330px,1.4fr) auto;gap:12px;align-items:center;border-bottom:1px solid var(--border-soft);padding:14px 16px;color:var(--ink-base)}.release-candidate.blocked{background:var(--c-fail-bg);color:var(--c-fail)}.candidate-title{display:grid;gap:5px}.candidate-title strong{overflow-wrap:anywhere;color:var(--ink-base);font-size:12px}.candidate-title small{color:var(--ink-mute);font-size:10px}.closure-grid{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:5px}.closure-grid span{border-radius:6px;padding:6px 5px;background:var(--bg-soft);color:var(--ink-mute);font-size:9px;text-align:center;white-space:nowrap}.closure-grid .ready{background:var(--c-done-bg);color:var(--c-done)}.closure-grid .shared{background:var(--c-warn-bg);color:var(--c-warn)}.closure-grid .missing{background:var(--c-fail-bg);color:var(--c-fail)}.blocked-reason{color:var(--c-fail);font-size:10px}.release-plan-summary{display:grid;gap:13px;padding:17px;position:sticky;top:80px}
|
||||
.closure-result{border-radius:6px;padding:6px 8px;font-size:9px;white-space:nowrap}.closure-result.ready{background:var(--c-done-bg);color:var(--c-done)}.closure-result.shared{background:var(--c-warn-bg);color:var(--c-warn)}.closure-result.missing{background:var(--c-fail-bg);color:var(--c-fail)}.release-decision-key{display:grid;gap:6px;border:1px solid var(--border-base);border-radius:8px;padding:9px;background:var(--bg-soft);color:var(--ink-mute);font-size:9px}.release-decision-key b{color:var(--ink-base)}.release-mode{display:grid;gap:5px;border-radius:10px;padding:13px;background:#f3f7fa}.release-mode span,.release-mode small{color:var(--ink-mute);font-size:10px;line-height:1.5}.release-mode strong{color:var(--ink-base)}.release-mode.document{background:var(--c-done-bg)}.release-mode.knowledge_base{background:var(--c-warn-bg)}.release-mode.blocked{background:var(--c-fail-bg)}.release-plan-summary dl{display:grid;grid-template-columns:1fr auto;gap:8px;margin:0;color:var(--ink-mute);font-size:11px}.release-plan-summary dd{margin:0;color:#1c4765;font-weight:700}.kb-warning{margin:0;border-radius:8px;padding:10px;background:var(--c-warn-bg);color:var(--c-warn);font-size:10px;line-height:1.6}.release-gates{display:grid;gap:6px;border-top:1px solid var(--border-base);padding-top:12px}.release-gates span{border-radius:6px;padding:7px;background:var(--c-fail-bg);color:var(--c-fail);font-size:10px}.release-plan-summary>small{color:var(--ink-mute);font-size:9px;line-height:1.5}@media(max-width:1100px){.release-plan-layout{grid-template-columns:1fr}.release-plan-summary{position:static}.release-candidate{grid-template-columns:20px minmax(180px,1fr)}.closure-grid{grid-column:2/-1}.blocked-reason{grid-column:2}}@media(max-width:700px){.release-four-steps{grid-template-columns:1fr 1fr}.closure-grid{grid-template-columns:repeat(2,minmax(0,1fr))}}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { describe,expect,it } from 'vitest'
|
||||
import { evaluateReleaseSelection } from './releasePlanner'
|
||||
import type { ReleaseCandidate } from './releasePlanner'
|
||||
|
||||
const ready:ReleaseCandidate={id:'a',title:'A.pdf',knowledge_base_id:'kb-1',knowledge_base_name:'公司级技术支持知识库',visibility:'internal',parse_status:'completed',chunks:100,vectors:100,assets:2,wiki:'ready',graph:'ready'}
|
||||
describe('release planner',()=>{
|
||||
it('uses document release only when every selected closure is independently complete',()=>{
|
||||
expect(evaluateReleaseSelection([ready])).toMatchObject({mode:'document',blocked:false})
|
||||
})
|
||||
it('escalates shared wiki or graph data to one whole knowledge-base release',()=>{
|
||||
expect(evaluateReleaseSelection([{...ready,id:'b',graph:'shared'}])).toMatchObject({mode:'knowledge_base',blocked:false,knowledge_base_id:'kb-1'})
|
||||
})
|
||||
it('blocks failed parsing, missing core data, or cross-KB fallback',()=>{
|
||||
expect(evaluateReleaseSelection([{...ready,parse_status:'failed'}]).blocked).toBe(true)
|
||||
expect(evaluateReleaseSelection([{...ready,vectors:0}]).blocked).toBe(true)
|
||||
expect(evaluateReleaseSelection([{...ready,graph:'shared'},{...ready,id:'c',knowledge_base_id:'kb-2'}]).blocked).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,16 @@
|
||||
export type ClosureState='ready'|'shared'|'missing'|'not_required'
|
||||
export interface ReleaseCandidate{id:string;title:string;knowledge_base_id:string;knowledge_base_name:string;visibility:'internal'|'external';parse_status:string;chunks:number;vectors:number;assets:number;wiki:ClosureState;graph:ClosureState}
|
||||
export interface ReleasePlan{mode:'none'|'document'|'knowledge_base'|'blocked';blocked:boolean;reason:string;knowledge_base_id?:string}
|
||||
export function evaluateReleaseSelection(items:ReleaseCandidate[]):ReleasePlan{
|
||||
if(!items.length)return{mode:'none',blocked:true,reason:'请先选择测试文档'}
|
||||
if(items.some(item=>item.parse_status!=='completed'))return{mode:'blocked',blocked:true,reason:'存在尚未完成解析的文档'}
|
||||
if(items.some(item=>item.chunks<1||item.vectors!==item.chunks||item.assets<1||item.wiki==='missing'||item.graph==='missing'))return{mode:'blocked',blocked:true,reason:'切片、向量、文件、Wiki或图谱闭包不完整'}
|
||||
const needsKB=items.some(item=>item.wiki==='shared'||item.graph==='shared')
|
||||
if(needsKB){const ids=new Set(items.map(item=>item.knowledge_base_id));if(ids.size!==1)return{mode:'blocked',blocked:true,reason:'整知识库发布不能跨知识库合并'};return{mode:'knowledge_base',blocked:false,reason:'Wiki或图谱包含共享数据,必须按整个知识库同步',knowledge_base_id:items[0].knowledge_base_id}}
|
||||
return{mode:'document',blocked:false,reason:'所选文档的切片、向量、文件、Wiki和图谱闭包可以独立验证'}
|
||||
}
|
||||
export const simulatedReleaseCandidates:ReleaseCandidate[]=[
|
||||
{id:'sim-cr5',title:'[模拟] CR5用户手册.pdf',knowledge_base_id:'simulation-company-support',knowledge_base_name:'公司级技术支持知识库',visibility:'internal',parse_status:'completed',chunks:186,vectors:186,assets:8,wiki:'ready',graph:'ready'},
|
||||
{id:'sim-params',title:'[模拟] 产品参数总表.xlsx',knowledge_base_id:'simulation-company-support',knowledge_base_name:'公司级技术支持知识库',visibility:'external',parse_status:'completed',chunks:94,vectors:94,assets:2,wiki:'ready',graph:'shared'},
|
||||
{id:'sim-failed',title:'[模拟] CRA-IP68产品介绍.pdf',knowledge_base_id:'simulation-company-support',knowledge_base_name:'公司级技术支持知识库',visibility:'external',parse_status:'failed',chunks:0,vectors:0,assets:1,wiki:'missing',graph:'missing'},
|
||||
]
|
||||
@@ -0,0 +1,12 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
// @ts-expect-error The test runner provides Node; the browser bundle intentionally omits @types/node.
|
||||
import { readFileSync } from 'node:fs'
|
||||
|
||||
const styles = readFileSync(new URL('./styles.css', import.meta.url), 'utf8')
|
||||
|
||||
describe('mobile workspace navigation styles', () => {
|
||||
it('keeps only the active workspace tab and hamburger navigation on narrow screens', () => {
|
||||
expect(styles).toMatch(/@media \(max-width: 760px\)[\s\S]*?\.workspace-tab:not\(\.active\)\s*\{\s*display:\s*none;/)
|
||||
expect(styles).toMatch(/@media \(max-width: 760px\)[\s\S]*?\.workspace-context-tabs\s*\{\s*display:\s*none;/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,192 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import {
|
||||
confirmReleaseChangeSet,
|
||||
createReleaseBatch,
|
||||
fetchLatestReleaseChangeSet,
|
||||
fetchReleaseAuditChain,
|
||||
generateReleaseChangeSet,
|
||||
fetchReleaseBatches,
|
||||
fetchReleaseCapabilities,
|
||||
fetchReleaseExecution,
|
||||
fetchReleaseExecutions,
|
||||
fetchReleasePlan,
|
||||
fetchReviewCandidates,
|
||||
parseReleaseBatchDetailResponse,
|
||||
parseReleaseBatchesResponse,
|
||||
parseReleaseCapabilitiesResponse,
|
||||
parseReleaseExecutionDetailResponse,
|
||||
parseReleaseExecutionsResponse,
|
||||
parseReleasePlanResponse,
|
||||
parseReviewCandidatesResponse,
|
||||
reviewPublication,
|
||||
sealReleaseBatch,
|
||||
} from './reviewRelease'
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
const candidate = {
|
||||
publication_id: 'tp-safe', title: 'Synthetic', source_type: 'manual', current_visibility: 'internal',
|
||||
knowledge_exists: 'passed', chunks_present: 'passed', retrieval_hit: 'manual_required',
|
||||
gate_status: 'ready', gate_code: 'ready', review_state: 'pending', decided_visibility: '',
|
||||
decision_code: '', reviewer_ref: '', reviewed_at: null, updated_at: '2026-09-06T10:00:00Z',
|
||||
acceptance_run_id: 'must-drop', knowledge_id: 'must-drop',
|
||||
}
|
||||
|
||||
const batch = {
|
||||
id: 'rb-safe', name: 'Batch', state: 'draft', policy_version: 'release-gate-v1',
|
||||
created_by: 'engineer-1', sealed_by: '', item_count: 1,
|
||||
created_at: '2026-09-06T10:00:00Z', sealed_at: null, acceptance_run_id: 'must-drop',
|
||||
}
|
||||
|
||||
describe('review and batch response parsing', () => {
|
||||
it('strictly rebuilds the source-truth release plan', () => {
|
||||
const plan = parseReleasePlanResponse({ data: { items: [{ publication_id: 'tp-safe', title: 'B.pdf', target_scope: 'external', action: 'add', test_state: 'ready', production_state: 'absent', can_release: true, blocker: '', production_revision: 'must-drop' }], summary: { add: 1, update: 0, delete: 0, blocked: 0, unchanged: 10 } } })
|
||||
expect(plan.summary).toEqual({ add: 1, update: 0, delete: 0, blocked: 0, unchanged: 10 })
|
||||
expect(plan.items[0]).toEqual({ publication_id: 'tp-safe', title: 'B.pdf', target_scope: 'external', action: 'add', test_state: 'ready', production_state: 'absent', can_release: true, blocker: '' })
|
||||
expect(plan.items[0]).not.toHaveProperty('production_revision')
|
||||
})
|
||||
|
||||
it('strictly rebuilds safe review candidates', () => {
|
||||
const page = parseReviewCandidatesResponse({ data: [candidate], total: 1, limit: 20, offset: 0 })
|
||||
expect(page).toEqual({ items: [{
|
||||
publication_id: 'tp-safe', title: 'Synthetic', source_type: 'manual', current_visibility: 'internal',
|
||||
knowledge_exists: 'passed', chunks_present: 'passed', retrieval_hit: 'manual_required',
|
||||
gate_status: 'ready', gate_code: 'ready', review_state: 'pending', decided_visibility: '',
|
||||
decision_code: '', reviewer_ref: '', reviewed_at: null, updated_at: '2026-09-06T10:00:00Z',
|
||||
}], total: 1, limit: 20, offset: 0 })
|
||||
expect(page.items[0]).not.toHaveProperty('acceptance_run_id')
|
||||
expect(page.items[0]).not.toHaveProperty('knowledge_id')
|
||||
})
|
||||
|
||||
it('strictly rebuilds safe batch list and detail', () => {
|
||||
expect(parseReleaseBatchesResponse({ data: [batch], total: 1, limit: 20, offset: 0 }).items[0]).toEqual({
|
||||
id: 'rb-safe', name: 'Batch', state: 'draft', policy_version: 'release-gate-v1', created_by: 'engineer-1',
|
||||
sealed_by: '', item_count: 1, created_at: '2026-09-06T10:00:00Z', sealed_at: null,
|
||||
})
|
||||
expect(parseReleaseBatchDetailResponse({ data: { ...batch, items: [{ publication_id: 'tp-safe', title: 'Synthetic', decided_visibility: 'internal', action: 'delete', publication_updated_at: 'must-drop' }] } }).items).toEqual([
|
||||
{ publication_id: 'tp-safe', title: 'Synthetic', decided_visibility: 'internal', action: 'delete' },
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('review and batch requests', () => {
|
||||
it('uses fixed scoped endpoints and explicit JSON fields', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ data: [candidate], total: 1, limit: 20, offset: 0 }), { status: 200 }))
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ data: { id: 'rv-safe', publication_id: 'tp-safe', decision: 'approved', decided_visibility: 'internal', reviewer_ref: 'engineer-1', decision_code: 'approved_for_release', created_at: '2026-09-06T10:01:00Z' } }), { status: 201 }))
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ data: batch }), { status: 201 }))
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ data: { ...batch, state: 'sealed', sealed_by: 'engineer-2', sealed_at: '2026-09-06T10:02:00Z' } }), { status: 200 }))
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ data: [batch], total: 1, limit: 20, offset: 0 }), { status: 200 }))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
await fetchReviewCandidates('pending')
|
||||
await reviewPublication('tp-safe', 'approved', 'internal', 'engineer-1', 'approved_for_release')
|
||||
await createReleaseBatch('Batch', 'engineer-1', ['tp-safe'], ['tp-delete'])
|
||||
await sealReleaseBatch('rb-safe', 'engineer-2')
|
||||
await fetchReleaseBatches('draft')
|
||||
|
||||
expect(fetchMock.mock.calls[0][0]).toBe('/api/v1/review-candidates?review_state=pending&limit=20&offset=0')
|
||||
expect(fetchMock.mock.calls[1][0]).toBe('/api/v1/review-candidates/tp-safe/decision')
|
||||
expect(JSON.parse((fetchMock.mock.calls[1][1] as RequestInit).body as string)).toEqual({ decision: 'approved', decided_visibility: 'internal', reviewer_ref: 'engineer-1', decision_code: 'approved_for_release' })
|
||||
expect(fetchMock.mock.calls[2][0]).toBe('/api/v1/release-batches')
|
||||
expect(JSON.parse((fetchMock.mock.calls[2][1] as RequestInit).body as string)).toEqual({ name: 'Batch', created_by: 'engineer-1', publication_ids: ['tp-safe'], delete_publication_ids: ['tp-delete'], release_change_set_id: '' })
|
||||
expect(fetchMock.mock.calls[3][0]).toBe('/api/v1/release-batches/rb-safe/seal')
|
||||
expect(fetchMock.mock.calls[4][0]).toBe('/api/v1/release-batches?state=draft&limit=20&offset=0')
|
||||
})
|
||||
})
|
||||
|
||||
describe('release execution audit parsing', () => {
|
||||
const execution = {
|
||||
id: 'rx-safe', release_batch_id: 'rb-safe', operation: 'publish', prior_execution_id: '', state: 'completed',
|
||||
target_environment: 'production', authorized_by: 'owner', job_id: 'job-safe', item_count: 105, batch_size: 50, current_batch: 2, total_batches: 3,
|
||||
completed_item_count: 1, failed_item_count: 0, error_code: '', created_at: '2026-09-06T10:00:00Z',
|
||||
started_at: '2026-09-06T10:01:00Z', completed_at: '2026-09-06T10:02:00Z',
|
||||
authorization_code: 'must-drop', manifest_sha256: 'must-drop', knowledge_id: 'must-drop',
|
||||
}
|
||||
|
||||
it('strictly rebuilds execution and capability responses', () => {
|
||||
const page = parseReleaseExecutionsResponse({ data: [execution], total: 1, limit: 20, offset: 0 })
|
||||
expect(page.items[0]).toMatchObject({ batch_size: 50, current_batch: 2, total_batches: 3 })
|
||||
expect(page.items[0]).not.toHaveProperty('authorization_code')
|
||||
expect(page.items[0]).not.toHaveProperty('manifest_sha256')
|
||||
const detail = parseReleaseExecutionDetailResponse({ data: { ...execution, items: [{ publication_id: 'tp-safe', title: 'Synthetic', action: 'delete', state: 'verified', previous_production_revision: 'prod-v0', production_revision: 'absent', error_code: '', created_at: '2026-09-06T10:00:00Z', completed_at: '2026-09-06T10:02:00Z', knowledge_id: 'must-drop' }] } })
|
||||
expect(detail.items[0]).toEqual({ publication_id: 'tp-safe', title: 'Synthetic', action: 'delete', state: 'verified', previous_production_revision: 'prod-v0', production_revision: 'absent', error_code: '', created_at: '2026-09-06T10:00:00Z', completed_at: '2026-09-06T10:02:00Z' })
|
||||
expect(parseReleaseCapabilitiesResponse({ data: { production_release_requests_enabled: true, production_backup_restore_verified: false, secret: 'drop' } })).toEqual({ production_release_requests_enabled: true, production_backup_restore_verified: false })
|
||||
})
|
||||
|
||||
it('fetches only read-only execution audit endpoints', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ data: [execution], total: 1, limit: 20, offset: 0 }), { status: 200 }))
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ data: { ...execution, items: [] } }), { status: 200 }))
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ data: { production_release_requests_enabled: false, production_backup_restore_verified: false } }), { status: 200 }))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
await fetchReleaseExecutions('publish', 'completed')
|
||||
await fetchReleaseExecution('rx-safe')
|
||||
await fetchReleaseCapabilities()
|
||||
expect(fetchMock.mock.calls.map((call) => call[0])).toEqual([
|
||||
'/api/v1/release-executions?operation=publish&state=completed&limit=20&offset=0',
|
||||
'/api/v1/release-executions/rx-safe',
|
||||
'/api/v1/release-capabilities',
|
||||
])
|
||||
expect(fetchMock.mock.calls.every((call) => !call[1] || (call[1] as RequestInit).method === undefined)).toBe(true)
|
||||
})
|
||||
|
||||
it('fetches the source-truth release plan from its fixed endpoint', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: { items: [], summary: { add: 0, update: 0, delete: 0, blocked: 0, unchanged: 0 } } }), { status: 200 }))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
await fetchReleasePlan()
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/release-plan', expect.objectContaining({ headers: { Accept: 'application/json' } }))
|
||||
})
|
||||
})
|
||||
|
||||
describe('release change set (R1)', () => {
|
||||
const changeSetPayload = { id: 'rcs-1', number: 1, name: '9月发布', state: 'planned', source_snapshot_ids: ['snap-a'], source_change_set_ids: [], acceptance_cutoff: '2026-09-11T21:00:00Z', production_baseline_ref: '', item_count: 1, add_count: 1, update_count: 0, delete_count: 0, blocked_count: 0, manifest_sha256: 'a'.repeat(64), created_by: 'engineer-1', created_at: '2026-09-12T07:00:00Z', confirmed_by: '', confirmed_at: null }
|
||||
it('generates with idempotency and rejects a manifest-less envelope', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: changeSetPayload, operation: 'created' }), { status: 201 }))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const set = await generateReleaseChangeSet('9月发布', 'engineer-1')
|
||||
expect(set.id).toBe('rcs-1')
|
||||
expect(set.manifest_sha256).toBe('a'.repeat(64))
|
||||
const [, init] = fetchMock.mock.calls[0] as [string, RequestInit]
|
||||
expect(init.headers).toMatchObject({ 'Idempotency-Key': expect.any(String) })
|
||||
expect((init.body as string)).toContain('"name":"9月发布"')
|
||||
const bad = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: { ...changeSetPayload, manifest_sha256: '' } }), { status: 201 }))
|
||||
vi.stubGlobal('fetch', bad)
|
||||
await expect(generateReleaseChangeSet('x', 'y')).rejects.toThrow('发布计划集响应缺少标识或清单摘要')
|
||||
})
|
||||
it('confirms via scoped endpoint and loads latest detail tolerating 404', async () => {
|
||||
const confirmMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: { ...changeSetPayload, state: 'confirmed', confirmed_by: 'boss', confirmed_at: '2026-09-12T08:00:00Z' }, operation: 'created' }), { status: 200 }))
|
||||
vi.stubGlobal('fetch', confirmMock)
|
||||
const confirmed = await confirmReleaseChangeSet('rcs-1', 'boss')
|
||||
expect(confirmed.state).toBe('confirmed')
|
||||
expect(confirmMock.mock.calls[0][0]).toBe('/api/v1/release-change-sets/rcs-1/confirm')
|
||||
const latest404 = vi.fn().mockResolvedValue(new Response('{}', { status: 404 }))
|
||||
vi.stubGlobal('fetch', latest404)
|
||||
expect(await fetchLatestReleaseChangeSet()).toBeNull()
|
||||
const detailMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: { ...changeSetPayload, items: [{ seq: 1, publication_id: 'tp-keep', title: '手册', target_scope: 'internal', action: 'add', test_state: 'ready', production_state: 'absent', can_release: true, blocker: '' }, { seq: 2, publication_id: 'x', title: '', target_scope: 'bogus', action: 'nope', test_state: '', production_state: '', can_release: false, blocker: '' }] } }), { status: 200 }))
|
||||
vi.stubGlobal('fetch', detailMock)
|
||||
const detail = await fetchLatestReleaseChangeSet()
|
||||
expect(detail?.items.length).toBe(1)
|
||||
expect(detail?.items[0].publication_id).toBe('tp-keep')
|
||||
})
|
||||
})
|
||||
|
||||
describe('release audit chain (R6)', () => {
|
||||
const chain = { execution_id:'rx-1', operation:'publish', state:'completed', failure_level:'', release_batch_id:'rb-1', release_batch_name:'9月批次', created_by:'e1', sealed_by:'e2', authorized_by:'own', release_change_set_id:'rcs-1', release_change_set_name:'9月发布', release_change_set_state:'confirmed', release_change_set_created_by:'e1', release_change_set_confirmed_by:'boss', release_change_set_confirmed_at:'2026-09-12T08:00:00Z', manifest_sha256:'a'.repeat(64), snapshots:[{id:'snap-1',source_name:'PP',node_count:66,file_count:621,observed_at:'2026-09-11T00:00:00Z'}], catalog_change_sets:[{id:'cs-1',state:'applied',add_count:2,update_count:1,move_count:0,delete_count:0}], prior_execution_id:'', rollback_execution_id:'', items:[{publication_id:'tp-1',title:'手册.pdf',action:'upsert',item_state:'verified',review_id:'rev-1',acceptance_run_id:'run-1',source_item_id:'si-1',source_item_version_id:'siv-1',production_revision:'v1',error_code:''}] }
|
||||
it('loads the chain and returns null on 404', async () => {
|
||||
const ok = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: chain }), { status: 200 }))
|
||||
vi.stubGlobal('fetch', ok)
|
||||
const result = await fetchReleaseAuditChain('rx-1')
|
||||
expect(result?.release_batch_name).toBe('9月批次')
|
||||
expect(result?.snapshots[0].file_count).toBe(621)
|
||||
expect(result?.items[0].publication_id).toBe('tp-1')
|
||||
expect(ok.mock.calls[0][0]).toBe('/api/v1/release-executions/rx-1/audit-chain')
|
||||
const missing = vi.fn().mockResolvedValue(new Response('{}', { status: 404 }))
|
||||
vi.stubGlobal('fetch', missing)
|
||||
expect(await fetchReleaseAuditChain('rx-x')).toBeNull()
|
||||
const bad = vi.fn().mockResolvedValue(new Response('{}', { status: 500 }))
|
||||
vi.stubGlobal('fetch', bad)
|
||||
await expect(fetchReleaseAuditChain('rx-1')).rejects.toThrow('HTTP 500')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,532 @@
|
||||
import { newOperationID } from './operationKey'
|
||||
export type ReviewState = 'pending' | 'approved' | 'rejected'
|
||||
export type Visibility = 'internal' | 'external'
|
||||
export type AcceptanceState = 'pending' | 'passed' | 'failed' | 'manual_required'
|
||||
export type ReviewGateStatus = 'ready' | 'blocked'
|
||||
export type ReleaseBatchState = 'draft' | 'sealed' | 'cancelled'
|
||||
export type ReleaseOperation = 'publish' | 'rollback'
|
||||
export type ReleaseExecutionState = 'pending' | 'running' | 'completed' | 'failed' | 'rolling_back' | 'rolled_back' | 'rollback_failed'
|
||||
|
||||
export interface ReviewCandidate {
|
||||
publication_id: string
|
||||
title: string
|
||||
source_type: 'pp' | 'alist' | 'dingtalk' | 'manual'
|
||||
current_visibility: Visibility
|
||||
knowledge_exists: AcceptanceState
|
||||
chunks_present: AcceptanceState
|
||||
retrieval_hit: AcceptanceState
|
||||
gate_status: ReviewGateStatus
|
||||
gate_code: string
|
||||
review_state: ReviewState
|
||||
decided_visibility: Visibility | ''
|
||||
decision_code: string
|
||||
reviewer_ref: string
|
||||
reviewed_at: string | null
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface ReviewCandidatePage {
|
||||
items: ReviewCandidate[]
|
||||
total: number
|
||||
limit: number
|
||||
offset: number
|
||||
}
|
||||
|
||||
export interface PublicationReview {
|
||||
id: string
|
||||
publication_id: string
|
||||
decision: 'approved' | 'rejected'
|
||||
decided_visibility: Visibility
|
||||
reviewer_ref: string
|
||||
decision_code: string
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export interface ReleaseBatch {
|
||||
release_change_set_id?: string
|
||||
id: string
|
||||
name: string
|
||||
state: ReleaseBatchState
|
||||
policy_version: string
|
||||
created_by: string
|
||||
sealed_by: string
|
||||
item_count: number
|
||||
created_at: string
|
||||
sealed_at: string | null
|
||||
}
|
||||
|
||||
export interface ReleaseBatchPage {
|
||||
items: ReleaseBatch[]
|
||||
total: number
|
||||
limit: number
|
||||
offset: number
|
||||
}
|
||||
|
||||
export interface ReleaseBatchItem {
|
||||
publication_id: string
|
||||
title: string
|
||||
decided_visibility: Visibility
|
||||
action: 'upsert' | 'delete'
|
||||
}
|
||||
|
||||
export interface ReleaseBatchDetail extends ReleaseBatch {
|
||||
items: ReleaseBatchItem[]
|
||||
}
|
||||
|
||||
export interface ReleaseExecution {
|
||||
id: string
|
||||
release_batch_id: string
|
||||
operation: ReleaseOperation
|
||||
prior_execution_id: string
|
||||
state: ReleaseExecutionState
|
||||
target_environment: 'production'
|
||||
authorized_by: string
|
||||
job_id: string
|
||||
item_count: number
|
||||
batch_size: number
|
||||
current_batch: number
|
||||
total_batches: number
|
||||
completed_item_count: number
|
||||
failed_item_count: number
|
||||
error_code: string
|
||||
failure_level?: string
|
||||
restore_trigger?: string
|
||||
created_at: string
|
||||
started_at: string | null
|
||||
completed_at: string | null
|
||||
}
|
||||
|
||||
export interface ReleaseExecutionPage {
|
||||
items: ReleaseExecution[]
|
||||
total: number
|
||||
limit: number
|
||||
offset: number
|
||||
}
|
||||
|
||||
export interface ReleaseItemExecution {
|
||||
publication_id: string
|
||||
title: string
|
||||
action: 'upsert' | 'delete'
|
||||
state: 'pending' | 'staged' | 'activated' | 'verified' | 'failed' | 'rolled_back'
|
||||
previous_production_revision: string
|
||||
production_revision: string
|
||||
error_code: string
|
||||
created_at: string
|
||||
completed_at: string | null
|
||||
}
|
||||
|
||||
export interface ReleaseExecutionDetail extends ReleaseExecution {
|
||||
items: ReleaseItemExecution[]
|
||||
}
|
||||
|
||||
export interface ReleaseCapabilities {
|
||||
production_release_requests_enabled: boolean
|
||||
production_backup_restore_verified: boolean
|
||||
}
|
||||
|
||||
export interface ReleasePlanItem {
|
||||
publication_id: string
|
||||
title: string
|
||||
target_scope: Visibility
|
||||
action: 'add' | 'update' | 'delete' | 'blocked'
|
||||
test_state: 'ready' | 'not_ready' | 'not_required'
|
||||
production_state: 'present' | 'absent'
|
||||
can_release: boolean
|
||||
blocker: string
|
||||
}
|
||||
|
||||
export interface ReleasePlan {
|
||||
items: ReleasePlanItem[]
|
||||
summary: { add: number; update: number; delete: number; blocked: number; unchanged: number }
|
||||
}
|
||||
|
||||
const sourceTypes = new Set(['pp', 'alist', 'dingtalk', 'manual'])
|
||||
const visibilities = new Set<Visibility>(['internal', 'external'])
|
||||
const acceptanceStates = new Set<AcceptanceState>(['pending', 'passed', 'failed', 'manual_required'])
|
||||
const reviewStates = new Set<ReviewState>(['pending', 'approved', 'rejected'])
|
||||
const gateStatuses = new Set<ReviewGateStatus>(['ready', 'blocked'])
|
||||
const batchStates = new Set<ReleaseBatchState>(['draft', 'sealed', 'cancelled'])
|
||||
const releaseOperations = new Set<ReleaseOperation>(['publish', 'rollback'])
|
||||
const releaseExecutionStates = new Set<ReleaseExecutionState>(['pending', 'running', 'completed', 'failed', 'rolling_back', 'rolled_back', 'rollback_failed'])
|
||||
const releaseItemStates = new Set<ReleaseItemExecution['state']>(['pending', 'staged', 'activated', 'verified', 'failed', 'rolled_back'])
|
||||
const releasePlanActions = new Set<ReleasePlanItem['action']>(['add', 'update', 'delete', 'blocked'])
|
||||
const releasePlanTestStates = new Set<ReleasePlanItem['test_state']>(['ready', 'not_ready', 'not_required'])
|
||||
|
||||
export function parseReviewCandidatesResponse(value: unknown): ReviewCandidatePage {
|
||||
const envelope = parsePageEnvelope(value, 'review candidates')
|
||||
return {
|
||||
items: envelope.rawItems.map(parseReviewCandidate),
|
||||
total: envelope.total,
|
||||
limit: envelope.limit,
|
||||
offset: envelope.offset,
|
||||
}
|
||||
}
|
||||
|
||||
export function parseReleaseBatchesResponse(value: unknown): ReleaseBatchPage {
|
||||
const envelope = parsePageEnvelope(value, 'release batches')
|
||||
return {
|
||||
items: envelope.rawItems.map(parseReleaseBatch),
|
||||
total: envelope.total,
|
||||
limit: envelope.limit,
|
||||
offset: envelope.offset,
|
||||
}
|
||||
}
|
||||
|
||||
export function parseReleaseBatchDetailResponse(value: unknown): ReleaseBatchDetail {
|
||||
if (!isRecord(value) || !isRecord(value.data) || !Array.isArray(value.data.items)) {
|
||||
throw new Error('invalid release batch detail response')
|
||||
}
|
||||
const batch = parseReleaseBatch(value.data)
|
||||
const items = value.data.items.map((raw): ReleaseBatchItem => {
|
||||
if (!isRecord(raw) || typeof raw.publication_id !== 'string' || typeof raw.title !== 'string' ||
|
||||
typeof raw.decided_visibility !== 'string' || !visibilities.has(raw.decided_visibility as Visibility) ||
|
||||
(raw.action !== 'upsert' && raw.action !== 'delete')) {
|
||||
throw new Error('invalid release batch item')
|
||||
}
|
||||
return { publication_id: raw.publication_id, title: raw.title, decided_visibility: raw.decided_visibility as Visibility, action: raw.action }
|
||||
})
|
||||
return { ...batch, items }
|
||||
}
|
||||
|
||||
export function parseReleaseExecutionsResponse(value: unknown): ReleaseExecutionPage {
|
||||
const envelope = parsePageEnvelope(value, 'release executions')
|
||||
return {
|
||||
items: envelope.rawItems.map(parseReleaseExecution),
|
||||
total: envelope.total,
|
||||
limit: envelope.limit,
|
||||
offset: envelope.offset,
|
||||
}
|
||||
}
|
||||
|
||||
export function parseReleaseExecutionDetailResponse(value: unknown): ReleaseExecutionDetail {
|
||||
if (!isRecord(value) || !isRecord(value.data) || !Array.isArray(value.data.items)) {
|
||||
throw new Error('invalid release execution detail response')
|
||||
}
|
||||
const execution = parseReleaseExecution(value.data)
|
||||
const items = value.data.items.map(parseReleaseItemExecution)
|
||||
return { ...execution, items }
|
||||
}
|
||||
|
||||
export function parseReleaseCapabilitiesResponse(value: unknown): ReleaseCapabilities {
|
||||
if (!isRecord(value) || !isRecord(value.data) || typeof value.data.production_release_requests_enabled !== 'boolean' || typeof value.data.production_backup_restore_verified !== 'boolean') {
|
||||
throw new Error('invalid release capabilities response')
|
||||
}
|
||||
return {
|
||||
production_release_requests_enabled: value.data.production_release_requests_enabled,
|
||||
production_backup_restore_verified: value.data.production_backup_restore_verified,
|
||||
}
|
||||
}
|
||||
|
||||
export function parseReleasePlanResponse(value: unknown): ReleasePlan {
|
||||
if (!isRecord(value) || !isRecord(value.data) || !Array.isArray(value.data.items) || !isRecord(value.data.summary)) {
|
||||
throw new Error('invalid release plan response')
|
||||
}
|
||||
const summary = value.data.summary
|
||||
if (!isCount(summary.add) || !isCount(summary.update) || !isCount(summary.delete) || !isCount(summary.blocked) || !isCount(summary.unchanged)) {
|
||||
throw new Error('invalid release plan response')
|
||||
}
|
||||
const items = value.data.items.map((raw): ReleasePlanItem => {
|
||||
if (!isRecord(raw) || typeof raw.publication_id !== 'string' || typeof raw.title !== 'string' ||
|
||||
typeof raw.target_scope !== 'string' || !visibilities.has(raw.target_scope as Visibility) ||
|
||||
typeof raw.action !== 'string' || !releasePlanActions.has(raw.action as ReleasePlanItem['action']) ||
|
||||
typeof raw.test_state !== 'string' || !releasePlanTestStates.has(raw.test_state as ReleasePlanItem['test_state']) ||
|
||||
(raw.production_state !== 'present' && raw.production_state !== 'absent') || typeof raw.can_release !== 'boolean' || typeof raw.blocker !== 'string') {
|
||||
throw new Error('invalid release plan item')
|
||||
}
|
||||
return {
|
||||
publication_id: raw.publication_id,
|
||||
title: raw.title,
|
||||
target_scope: raw.target_scope as Visibility,
|
||||
action: raw.action as ReleasePlanItem['action'],
|
||||
test_state: raw.test_state as ReleasePlanItem['test_state'],
|
||||
production_state: raw.production_state,
|
||||
can_release: raw.can_release,
|
||||
blocker: raw.blocker,
|
||||
}
|
||||
})
|
||||
return { items, summary: { add: summary.add, update: summary.update, delete: summary.delete, blocked: summary.blocked, unchanged: summary.unchanged } }
|
||||
}
|
||||
|
||||
export async function fetchReviewCandidates(reviewState: ReviewState | '' = '', limit = 20, offset = 0, signal?: AbortSignal): Promise<ReviewCandidatePage> {
|
||||
const params = new URLSearchParams({ review_state: reviewState, limit: String(limit), offset: String(offset) })
|
||||
return parseReviewCandidatesResponse(await getJSON(`/api/v1/review-candidates?${params}`, signal, '加载审核队列失败'))
|
||||
}
|
||||
|
||||
export async function reviewPublication(publicationID: string, decision: 'approved' | 'rejected', visibility: Visibility, reviewerRef: string, decisionCode: string): Promise<PublicationReview> {
|
||||
const value = await sendJSON(`/api/v1/review-candidates/${encodeURIComponent(publicationID)}/decision`, {
|
||||
decision, decided_visibility: visibility, reviewer_ref: reviewerRef, decision_code: decisionCode,
|
||||
}, '提交审核决定失败')
|
||||
if (!isRecord(value) || !isRecord(value.data)) throw new Error('invalid publication review response')
|
||||
const raw = value.data
|
||||
if (typeof raw.id !== 'string' || typeof raw.publication_id !== 'string' ||
|
||||
(raw.decision !== 'approved' && raw.decision !== 'rejected') || typeof raw.decided_visibility !== 'string' ||
|
||||
!visibilities.has(raw.decided_visibility as Visibility) || typeof raw.reviewer_ref !== 'string' ||
|
||||
typeof raw.decision_code !== 'string' || typeof raw.created_at !== 'string') {
|
||||
throw new Error('invalid publication review response')
|
||||
}
|
||||
return { id: raw.id, publication_id: raw.publication_id, decision: raw.decision, decided_visibility: raw.decided_visibility as Visibility, reviewer_ref: raw.reviewer_ref, decision_code: raw.decision_code, created_at: raw.created_at }
|
||||
}
|
||||
|
||||
export async function createReleaseBatch(name: string, createdBy: string, publicationIDs: string[], deletePublicationIDs: string[] = [], releaseChangeSetID = ''): Promise<ReleaseBatch> {
|
||||
return parseBatchEnvelope(await sendJSON('/api/v1/release-batches', { name, created_by: createdBy, publication_ids: publicationIDs, delete_publication_ids: deletePublicationIDs, release_change_set_id: releaseChangeSetID }, '创建封批失败'))
|
||||
}
|
||||
|
||||
export interface ReleaseChangeSetItem {
|
||||
seq: number
|
||||
publication_id: string
|
||||
title: string
|
||||
target_scope: Visibility
|
||||
action: 'add' | 'update' | 'delete' | 'blocked' | 'unchanged'
|
||||
test_state: string
|
||||
production_state: string
|
||||
can_release: boolean
|
||||
blocker: string
|
||||
}
|
||||
export interface ReleaseChangeSet {
|
||||
id: string
|
||||
number: number
|
||||
name: string
|
||||
state: 'planned' | 'confirmed' | 'consumed' | 'cancelled'
|
||||
source_snapshot_ids: string[]
|
||||
source_change_set_ids: string[]
|
||||
acceptance_cutoff: string
|
||||
production_baseline_ref: string
|
||||
item_count: number
|
||||
add_count: number
|
||||
update_count: number
|
||||
delete_count: number
|
||||
blocked_count: number
|
||||
manifest_sha256: string
|
||||
created_by: string
|
||||
created_at: string
|
||||
confirmed_by: string
|
||||
confirmed_at: string | null
|
||||
}
|
||||
export interface ReleaseChangeSetDetail extends ReleaseChangeSet {
|
||||
items: ReleaseChangeSetItem[]
|
||||
}
|
||||
|
||||
function parseChangeSetEnvelope(value: unknown): ReleaseChangeSet {
|
||||
if (!isRecord(value) || !isRecord(value.data)) throw new Error('发布计划集响应无效')
|
||||
const data = value.data
|
||||
const text = (key: string) => typeof data[key] === 'string' ? data[key] as string : ''
|
||||
const number = (key: string) => typeof data[key] === 'number' && Number.isFinite(data[key]) ? data[key] as number : 0
|
||||
const id = text('id')
|
||||
const manifest = text('manifest_sha256')
|
||||
if (!id || !/^[0-9a-f]{64}$/.test(manifest)) throw new Error('发布计划集响应缺少标识或清单摘要')
|
||||
const snapshots = Array.isArray(data.source_snapshot_ids) ? data.source_snapshot_ids.filter((item): item is string => typeof item === 'string') : []
|
||||
const catalogSets = Array.isArray(data.source_change_set_ids) ? data.source_change_set_ids.filter((item): item is string => typeof item === 'string') : []
|
||||
const confirmedRaw = data.confirmed_at
|
||||
return {
|
||||
id, number: number('number'), name: text('name'),
|
||||
state: data.state === 'confirmed' || data.state === 'consumed' || data.state === 'cancelled' ? data.state : 'planned',
|
||||
source_snapshot_ids: snapshots, source_change_set_ids: catalogSets,
|
||||
acceptance_cutoff: text('acceptance_cutoff'), production_baseline_ref: text('production_baseline_ref'),
|
||||
item_count: number('item_count'), add_count: number('add_count'), update_count: number('update_count'),
|
||||
delete_count: number('delete_count'), blocked_count: number('blocked_count'),
|
||||
manifest_sha256: manifest, created_by: text('created_by'), created_at: text('created_at'),
|
||||
confirmed_by: text('confirmed_by'), confirmed_at: typeof confirmedRaw === 'string' && confirmedRaw ? confirmedRaw : null,
|
||||
}
|
||||
}
|
||||
|
||||
// R1: freeze the live release plan into an immutable versioned change set.
|
||||
export async function generateReleaseChangeSet(name: string, createdBy: string): Promise<ReleaseChangeSet> {
|
||||
return parseChangeSetEnvelope(await sendJSON('/api/v1/release-change-sets', { name, created_by: createdBy }, '生成发布计划集失败'))
|
||||
}
|
||||
|
||||
export async function confirmReleaseChangeSet(changeSetID: string, confirmedBy: string): Promise<ReleaseChangeSet> {
|
||||
return parseChangeSetEnvelope(await sendJSON(`/api/v1/release-change-sets/${encodeURIComponent(changeSetID)}/confirm`, { confirmed_by: confirmedBy }, '确认发布计划集失败'))
|
||||
}
|
||||
|
||||
export async function fetchLatestReleaseChangeSet(signal?: AbortSignal): Promise<ReleaseChangeSetDetail | null> {
|
||||
const response = await fetch('/api/v1/release-change-sets/latest', { headers: { Accept: 'application/json' }, signal })
|
||||
if (response.status === 404) return null
|
||||
if (!response.ok) throw new Error(`加载发布计划集失败(HTTP ${response.status})`)
|
||||
const value = await response.json() as unknown
|
||||
const base = parseChangeSetEnvelope(value)
|
||||
const data = (value as Record<string, unknown>).data as Record<string, unknown>
|
||||
const rawItems = Array.isArray(data.items) ? data.items : []
|
||||
const items: ReleaseChangeSetItem[] = []
|
||||
for (const raw of rawItems) {
|
||||
if (!isRecord(raw)) continue
|
||||
const action = raw.action
|
||||
const scope = raw.target_scope
|
||||
if (typeof raw.publication_id !== 'string' || (action !== 'add' && action !== 'update' && action !== 'delete' && action !== 'blocked' && action !== 'unchanged') || (scope !== 'internal' && scope !== 'external')) continue
|
||||
items.push({
|
||||
seq: typeof raw.seq === 'number' ? raw.seq : 0, publication_id: raw.publication_id, title: typeof raw.title === 'string' ? raw.title : '',
|
||||
target_scope: scope, action, test_state: typeof raw.test_state === 'string' ? raw.test_state : '', production_state: typeof raw.production_state === 'string' ? raw.production_state : '',
|
||||
can_release: raw.can_release === true, blocker: typeof raw.blocker === 'string' ? raw.blocker : '',
|
||||
})
|
||||
}
|
||||
return { ...base, items }
|
||||
}
|
||||
|
||||
export async function sealReleaseBatch(batchID: string, sealedBy: string): Promise<ReleaseBatch> {
|
||||
return parseBatchEnvelope(await sendJSON(`/api/v1/release-batches/${encodeURIComponent(batchID)}/seal`, { sealed_by: sealedBy }, '封批失败'))
|
||||
}
|
||||
|
||||
export async function fetchReleaseBatches(state: ReleaseBatchState | '' = '', limit = 20, offset = 0, signal?: AbortSignal): Promise<ReleaseBatchPage> {
|
||||
const params = new URLSearchParams({ state, limit: String(limit), offset: String(offset) })
|
||||
return parseReleaseBatchesResponse(await getJSON(`/api/v1/release-batches?${params}`, signal, '加载封批列表失败'))
|
||||
}
|
||||
|
||||
export async function fetchReleaseBatch(batchID: string, signal?: AbortSignal): Promise<ReleaseBatchDetail> {
|
||||
return parseReleaseBatchDetailResponse(await getJSON(`/api/v1/release-batches/${encodeURIComponent(batchID)}`, signal, '加载封批详情失败'))
|
||||
}
|
||||
|
||||
export async function fetchReleaseExecutions(operation: ReleaseOperation | '' = '', state: ReleaseExecutionState | '' = '', limit = 20, offset = 0, signal?: AbortSignal): Promise<ReleaseExecutionPage> {
|
||||
const params = new URLSearchParams({ operation, state, limit: String(limit), offset: String(offset) })
|
||||
return parseReleaseExecutionsResponse(await getJSON(`/api/v1/release-executions?${params}`, signal, '加载生产发布审计失败'))
|
||||
}
|
||||
|
||||
export async function fetchReleaseExecution(executionID: string, signal?: AbortSignal): Promise<ReleaseExecutionDetail> {
|
||||
return parseReleaseExecutionDetailResponse(await getJSON(`/api/v1/release-executions/${encodeURIComponent(executionID)}`, signal, '加载生产发布详情失败'))
|
||||
}
|
||||
|
||||
export async function fetchReleaseCapabilities(signal?: AbortSignal): Promise<ReleaseCapabilities> {
|
||||
return parseReleaseCapabilitiesResponse(await getJSON('/api/v1/release-capabilities', signal, '加载生产发布门禁失败'))
|
||||
}
|
||||
|
||||
export async function fetchReleasePlan(signal?: AbortSignal): Promise<ReleasePlan> {
|
||||
return parseReleasePlanResponse(await getJSON('/api/v1/release-plan', signal, '加载发布计划失败'))
|
||||
}
|
||||
|
||||
function parseReviewCandidate(raw: unknown): ReviewCandidate {
|
||||
if (!isRecord(raw) || typeof raw.publication_id !== 'string' || typeof raw.title !== 'string' ||
|
||||
typeof raw.source_type !== 'string' || !sourceTypes.has(raw.source_type) ||
|
||||
typeof raw.current_visibility !== 'string' || !visibilities.has(raw.current_visibility as Visibility) ||
|
||||
typeof raw.knowledge_exists !== 'string' || !acceptanceStates.has(raw.knowledge_exists as AcceptanceState) ||
|
||||
typeof raw.chunks_present !== 'string' || !acceptanceStates.has(raw.chunks_present as AcceptanceState) ||
|
||||
typeof raw.retrieval_hit !== 'string' || !acceptanceStates.has(raw.retrieval_hit as AcceptanceState) ||
|
||||
typeof raw.gate_status !== 'string' || !gateStatuses.has(raw.gate_status as ReviewGateStatus) ||
|
||||
typeof raw.gate_code !== 'string' || typeof raw.review_state !== 'string' || !reviewStates.has(raw.review_state as ReviewState) ||
|
||||
typeof raw.decided_visibility !== 'string' || (raw.decided_visibility !== '' && !visibilities.has(raw.decided_visibility as Visibility)) ||
|
||||
typeof raw.decision_code !== 'string' || typeof raw.reviewer_ref !== 'string' ||
|
||||
(raw.reviewed_at !== null && typeof raw.reviewed_at !== 'string') || typeof raw.updated_at !== 'string') {
|
||||
throw new Error('invalid review candidate')
|
||||
}
|
||||
return {
|
||||
publication_id: raw.publication_id, title: raw.title, source_type: raw.source_type as ReviewCandidate['source_type'],
|
||||
current_visibility: raw.current_visibility as Visibility, knowledge_exists: raw.knowledge_exists as AcceptanceState,
|
||||
chunks_present: raw.chunks_present as AcceptanceState, retrieval_hit: raw.retrieval_hit as AcceptanceState,
|
||||
gate_status: raw.gate_status as ReviewGateStatus, gate_code: raw.gate_code, review_state: raw.review_state as ReviewState,
|
||||
decided_visibility: raw.decided_visibility as Visibility | '', decision_code: raw.decision_code, reviewer_ref: raw.reviewer_ref,
|
||||
reviewed_at: raw.reviewed_at as string | null, updated_at: raw.updated_at,
|
||||
}
|
||||
}
|
||||
|
||||
function parseReleaseExecution(raw: unknown): ReleaseExecution {
|
||||
if (!isRecord(raw) || typeof raw.id !== 'string' || typeof raw.release_batch_id !== 'string' ||
|
||||
typeof raw.operation !== 'string' || !releaseOperations.has(raw.operation as ReleaseOperation) ||
|
||||
typeof raw.prior_execution_id !== 'string' || typeof raw.state !== 'string' || !releaseExecutionStates.has(raw.state as ReleaseExecutionState) ||
|
||||
raw.target_environment !== 'production' || typeof raw.authorized_by !== 'string' || typeof raw.job_id !== 'string' ||
|
||||
!isCount(raw.item_count) || !isCount(raw.batch_size) || !isCount(raw.current_batch) || !isCount(raw.total_batches) || !isCount(raw.completed_item_count) || !isCount(raw.failed_item_count) ||
|
||||
typeof raw.error_code !== 'string' || typeof raw.created_at !== 'string' ||
|
||||
(raw.started_at !== null && typeof raw.started_at !== 'string') ||
|
||||
(raw.completed_at !== null && typeof raw.completed_at !== 'string')) {
|
||||
throw new Error('invalid release execution')
|
||||
}
|
||||
return {
|
||||
id: raw.id, release_batch_id: raw.release_batch_id, operation: raw.operation as ReleaseOperation,
|
||||
prior_execution_id: raw.prior_execution_id, state: raw.state as ReleaseExecutionState,
|
||||
target_environment: 'production', authorized_by: raw.authorized_by, job_id: raw.job_id,
|
||||
item_count: raw.item_count, batch_size: raw.batch_size, current_batch: raw.current_batch, total_batches: raw.total_batches, completed_item_count: raw.completed_item_count, failed_item_count: raw.failed_item_count,
|
||||
error_code: raw.error_code, created_at: raw.created_at, started_at: raw.started_at as string | null,
|
||||
completed_at: raw.completed_at as string | null,
|
||||
failure_level: typeof raw.failure_level === 'string' ? raw.failure_level : '',
|
||||
restore_trigger: typeof raw.restore_trigger === 'string' ? raw.restore_trigger : '',
|
||||
}
|
||||
}
|
||||
|
||||
function parseReleaseItemExecution(raw: unknown): ReleaseItemExecution {
|
||||
if (!isRecord(raw) || typeof raw.publication_id !== 'string' || typeof raw.title !== 'string' ||
|
||||
(raw.action !== 'upsert' && raw.action !== 'delete') ||
|
||||
typeof raw.state !== 'string' || !releaseItemStates.has(raw.state as ReleaseItemExecution['state']) ||
|
||||
typeof raw.previous_production_revision !== 'string' || typeof raw.production_revision !== 'string' ||
|
||||
typeof raw.error_code !== 'string' || typeof raw.created_at !== 'string' ||
|
||||
(raw.completed_at !== null && typeof raw.completed_at !== 'string')) {
|
||||
throw new Error('invalid release item execution')
|
||||
}
|
||||
return {
|
||||
publication_id: raw.publication_id, title: raw.title, action: raw.action, state: raw.state as ReleaseItemExecution['state'],
|
||||
previous_production_revision: raw.previous_production_revision, production_revision: raw.production_revision,
|
||||
error_code: raw.error_code, created_at: raw.created_at, completed_at: raw.completed_at as string | null,
|
||||
}
|
||||
}
|
||||
|
||||
function parseReleaseBatch(raw: unknown): ReleaseBatch {
|
||||
if (!isRecord(raw) || typeof raw.id !== 'string' || typeof raw.name !== 'string' ||
|
||||
typeof raw.state !== 'string' || !batchStates.has(raw.state as ReleaseBatchState) || typeof raw.policy_version !== 'string' ||
|
||||
typeof raw.created_by !== 'string' || typeof raw.sealed_by !== 'string' || !isCount(raw.item_count) ||
|
||||
typeof raw.created_at !== 'string' || (raw.sealed_at !== null && typeof raw.sealed_at !== 'string')) {
|
||||
throw new Error('invalid release batch')
|
||||
}
|
||||
return { id: raw.id, name: raw.name, state: raw.state as ReleaseBatchState, policy_version: raw.policy_version, created_by: raw.created_by, sealed_by: raw.sealed_by, item_count: raw.item_count, created_at: raw.created_at, sealed_at: raw.sealed_at as string | null }
|
||||
}
|
||||
|
||||
function parseBatchEnvelope(value: unknown): ReleaseBatch {
|
||||
if (!isRecord(value) || !isRecord(value.data)) throw new Error('invalid release batch response')
|
||||
return parseReleaseBatch(value.data)
|
||||
}
|
||||
|
||||
function parsePageEnvelope(value: unknown, label: string) {
|
||||
if (!isRecord(value) || !Array.isArray(value.data) || !isCount(value.total) || !isCount(value.limit) || value.limit < 1 || !isCount(value.offset)) {
|
||||
throw new Error(`invalid ${label} response`)
|
||||
}
|
||||
return { rawItems: value.data, total: value.total, limit: value.limit, offset: value.offset }
|
||||
}
|
||||
|
||||
async function getJSON(url: string, signal: AbortSignal | undefined, message: string): Promise<unknown> {
|
||||
const response = await fetch(url, { headers: { Accept: 'application/json' }, signal })
|
||||
if (!response.ok) throw new Error(`${message}(HTTP ${response.status})`)
|
||||
return response.json()
|
||||
}
|
||||
|
||||
async function sendJSON(url: string, body: unknown, message: string): Promise<unknown> {
|
||||
const response = await fetch(url, { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Idempotency-Key': newOperationID() }, body: JSON.stringify(body) })
|
||||
if (!response.ok) throw new Error(`${message}(HTTP ${response.status})`)
|
||||
return response.json()
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null
|
||||
}
|
||||
|
||||
function isCount(value: unknown): value is number {
|
||||
return typeof value === 'number' && Number.isInteger(value) && value >= 0
|
||||
}
|
||||
|
||||
const auditText = (row: Record<string, unknown>, key: string): string => typeof row[key] === 'string' ? row[key] as string : ''
|
||||
const auditNumber = (row: Record<string, unknown>, key: string): number => typeof row[key] === 'number' && Number.isFinite(row[key]) ? row[key] as number : 0
|
||||
export interface AuditSnapshot { id: string; source_name: string; node_count: number; file_count: number; observed_at: string }
|
||||
export interface AuditCatalogSet { id: string; state: string; add_count: number; update_count: number; move_count: number; delete_count: number }
|
||||
export interface AuditChainItem { publication_id: string; title: string; action: string; item_state: string; review_id: string; acceptance_run_id: string; source_item_id: string; source_item_version_id: string; production_revision: string; error_code: string }
|
||||
export interface ReleaseAuditChain {
|
||||
execution_id: string; operation: string; state: string; failure_level: string
|
||||
release_batch_id: string; release_batch_name: string; created_by: string; sealed_by: string; authorized_by: string
|
||||
release_change_set_id: string; release_change_set_name: string; release_change_set_state: string
|
||||
release_change_set_created_by: string; release_change_set_confirmed_by: string; release_change_set_confirmed_at: string | null
|
||||
manifest_sha256: string; snapshots: AuditSnapshot[]; catalog_change_sets: AuditCatalogSet[]
|
||||
prior_execution_id: string; rollback_execution_id: string; items: AuditChainItem[]
|
||||
}
|
||||
export async function fetchReleaseAuditChain(executionID: string, signal?: AbortSignal): Promise<ReleaseAuditChain | null> {
|
||||
const response = await fetch(`/api/v1/release-executions/${encodeURIComponent(executionID)}/audit-chain`, { headers: { Accept: 'application/json' }, signal })
|
||||
if (response.status === 404) return null
|
||||
if (!response.ok) throw new Error(`加载发布审计链失败(HTTP ${response.status})`)
|
||||
const value = await response.json() as unknown
|
||||
if (!isRecord(value) || !isRecord(value.data)) throw new Error('发布审计链响应无效')
|
||||
const data = value.data
|
||||
const rows = (key: string): Record<string, unknown>[] => Array.isArray(data[key]) ? (data[key] as unknown[]).filter(isRecord) : []
|
||||
return {
|
||||
execution_id: auditText(data, 'execution_id'), operation: auditText(data, 'operation'), state: auditText(data, 'state'), failure_level: auditText(data, 'failure_level'),
|
||||
release_batch_id: auditText(data, 'release_batch_id'), release_batch_name: auditText(data, 'release_batch_name'), created_by: auditText(data, 'created_by'), sealed_by: auditText(data, 'sealed_by'), authorized_by: auditText(data, 'authorized_by'),
|
||||
release_change_set_id: auditText(data, 'release_change_set_id'), release_change_set_name: auditText(data, 'release_change_set_name'), release_change_set_state: auditText(data, 'release_change_set_state'),
|
||||
release_change_set_created_by: auditText(data, 'release_change_set_created_by'), release_change_set_confirmed_by: auditText(data, 'release_change_set_confirmed_by'),
|
||||
release_change_set_confirmed_at: typeof data.release_change_set_confirmed_at === 'string' ? data.release_change_set_confirmed_at : null,
|
||||
manifest_sha256: auditText(data, 'manifest_sha256'),
|
||||
snapshots: rows('snapshots').map((row) => ({ id: auditText(row, 'id'), source_name: auditText(row, 'source_name'), node_count: auditNumber(row, 'node_count'), file_count: auditNumber(row, 'file_count'), observed_at: auditText(row, 'observed_at') })),
|
||||
catalog_change_sets: rows('catalog_change_sets').map((row) => ({ id: auditText(row, 'id'), state: auditText(row, 'state'), add_count: auditNumber(row, 'add_count'), update_count: auditNumber(row, 'update_count'), move_count: auditNumber(row, 'move_count'), delete_count: auditNumber(row, 'delete_count') })),
|
||||
prior_execution_id: auditText(data, 'prior_execution_id'), rollback_execution_id: auditText(data, 'rollback_execution_id'),
|
||||
items: rows('items').map((row) => ({ publication_id: auditText(row, 'publication_id'), title: auditText(row, 'title'), action: auditText(row, 'action'), item_state: auditText(row, 'item_state'), review_id: auditText(row, 'review_id'), acceptance_run_id: auditText(row, 'acceptance_run_id'), source_item_id: auditText(row, 'source_item_id'), source_item_version_id: auditText(row, 'source_item_version_id'), production_revision: auditText(row, 'production_revision'), error_code: auditText(row, 'error_code') })),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { clearScopeRule, fetchScopeRules, setScopeRule } from './scopeRules'
|
||||
|
||||
afterEach(()=>vi.unstubAllGlobals())
|
||||
|
||||
describe('scope rule API',()=>{
|
||||
it('lists rules for exactly one configured connection',async()=>{
|
||||
const fetchMock=vi.fn().mockResolvedValue(new Response(JSON.stringify({data:[{target_type:'directory',connection_id:'conn-1',directory_path:'产品',visibility:'internal',updated_by:'engineer',reason:'内部资料',updated_at:'2026-09-08T00:00:00Z'}],summary:{total:1}})))
|
||||
vi.stubGlobal('fetch',fetchMock)
|
||||
const rules=await fetchScopeRules('conn-1')
|
||||
expect(rules).toHaveLength(1)
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/scope-rules?connection_id=conn-1',expect.objectContaining({headers:{Accept:'application/json'}}))
|
||||
})
|
||||
it('sets and clears rules with explicit audited payloads',async()=>{
|
||||
const fetchMock=vi.fn().mockImplementation(()=>Promise.resolve(new Response(JSON.stringify({data:{target_type:'directory',connection_id:'conn-1',directory_path:'产品',visibility:'internal'}}))))
|
||||
vi.stubGlobal('fetch',fetchMock)
|
||||
const target={target_type:'directory' as const,connection_id:'conn-1',directory_path:'产品',source_item_id:''}
|
||||
await setScopeRule({...target,visibility:'internal',operator_ref:'engineer-1',reason:'内部资料'})
|
||||
await clearScopeRule({...target,operator_ref:'engineer-1',reason:'恢复来源设置'})
|
||||
expect(fetchMock.mock.calls[0][1]).toMatchObject({method:'PUT',headers:{Accept:'application/json','Content-Type':'application/json','Idempotency-Key':expect.any(String)}})
|
||||
expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({...target,visibility:'internal',operator_ref:'engineer-1',reason:'内部资料'})
|
||||
expect(fetchMock.mock.calls[1][1]).toMatchObject({method:'DELETE',headers:{Accept:'application/json','Content-Type':'application/json','Idempotency-Key':expect.any(String)}})
|
||||
expect(JSON.parse(fetchMock.mock.calls[1][1].body)).not.toHaveProperty('visibility')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,53 @@
|
||||
import { newOperationID } from './operationKey'
|
||||
export type ScopeTargetType = 'directory' | 'item'
|
||||
export type Visibility = 'internal' | 'external'
|
||||
|
||||
export interface ScopeRule {
|
||||
target_type: ScopeTargetType
|
||||
connection_id?: string
|
||||
directory_path?: string
|
||||
source_item_id?: string
|
||||
visibility: Visibility
|
||||
updated_by: string
|
||||
reason: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface ScopeRuleTarget {
|
||||
target_type: ScopeTargetType
|
||||
connection_id: string
|
||||
directory_path: string
|
||||
source_item_id: string
|
||||
}
|
||||
|
||||
export interface ScopeRuleDecision extends ScopeRuleTarget {
|
||||
visibility: Visibility
|
||||
operator_ref: string
|
||||
reason: string
|
||||
}
|
||||
|
||||
export interface ClearScopeRuleDecision extends ScopeRuleTarget {
|
||||
operator_ref: string
|
||||
reason: string
|
||||
}
|
||||
|
||||
|
||||
|
||||
export async function fetchScopeRules(connectionID:string,signal?:AbortSignal):Promise<ScopeRule[]> {
|
||||
const response=await fetch(`/api/v1/scope-rules?${new URLSearchParams({connection_id:connectionID})}`,{headers:{Accept:'application/json'},signal})
|
||||
if(!response.ok) throw new Error(`加载范围规则失败(HTTP ${response.status})`)
|
||||
const value=await response.json() as {data?:unknown}
|
||||
if(!Array.isArray(value.data)) throw new Error('范围规则响应无效')
|
||||
return value.data as ScopeRule[]
|
||||
}
|
||||
|
||||
async function mutateScopeRule(method:'PUT'|'DELETE',body:ScopeRuleDecision|ClearScopeRuleDecision):Promise<ScopeRule> {
|
||||
const response=await fetch('/api/v1/scope-rules',{method,headers:{Accept:'application/json','Content-Type':'application/json','Idempotency-Key':newOperationID()},body:JSON.stringify(body)})
|
||||
if(!response.ok) throw new Error(`${method==='PUT'?'保存':'清除'}范围规则失败(HTTP ${response.status})`)
|
||||
const value=await response.json() as {data?:ScopeRule}
|
||||
if(!value.data || typeof value.data!=='object') throw new Error('范围规则响应无效')
|
||||
return value.data
|
||||
}
|
||||
|
||||
export function setScopeRule(decision:ScopeRuleDecision){return mutateScopeRule('PUT',decision)}
|
||||
export function clearScopeRule(decision:ClearScopeRuleDecision){return mutateScopeRule('DELETE',decision)}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { afterEach,describe,expect,it,vi } from 'vitest'
|
||||
import { fetchAllCatalogFolders,fetchCatalogNodes,fetchCatalogRoutingCapabilities,fetchCatalogSources,fetchLatestCatalogChangeSet,routeCatalogFiles,triggerCatalogRefresh } from './sourceCatalog'
|
||||
|
||||
afterEach(()=>vi.unstubAllGlobals())
|
||||
|
||||
describe('source catalog API',()=>{
|
||||
it('loads safe source roots',async()=>{
|
||||
const fetchMock=vi.fn().mockResolvedValue(new Response(JSON.stringify({data:[{connection_id:'conn-1',source_type:'dingtalk',name:'公司级技术支持知识库',root_node_id:'root-1',folder_count:8,file_count:3468,observed_at:'2026-09-08T00:00:00Z',snapshot_only:true,snapshot_status:'ready',last_refresh_duration_ms:12000,secret:'drop'}],summary:{total:1}})))
|
||||
vi.stubGlobal('fetch',fetchMock)
|
||||
const sources=await fetchCatalogSources()
|
||||
expect(sources[0].name).toBe('公司级技术支持知识库')
|
||||
expect(sources[0].snapshot_status).toBe('ready')
|
||||
expect(sources[0].last_refresh_duration_ms).toBe(12000)
|
||||
expect(sources[0]).not.toHaveProperty('secret')
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/source-catalog/sources',expect.objectContaining({headers:{Accept:'application/json'}}))
|
||||
})
|
||||
it('loads every page for a complete deduplicated folder tree level',async()=>{
|
||||
const folderA={node_id:'folder-a',parent_node_id:'root',node_type:'folder',name:'A',direct_child_count:1,subtree_file_count:1,subtree_bytes:1,visibility:'unknown',imported_count:0,parsed_count:0,active_count:0,failed_count:0,routable_count:0}
|
||||
const file={...folderA,node_id:'file-a',node_type:'file',name:'a.pdf'}
|
||||
const folderB={...folderA,node_id:'folder-b',name:'B'}
|
||||
const response=(items:unknown[],offset:number)=>new Response(JSON.stringify({current:{...folderA,node_id:'root',name:'Root'},breadcrumbs:[{node_id:'root',name:'Root'}],items,total:3,limit:2,offset}))
|
||||
const fetchMock=vi.fn().mockResolvedValueOnce(response([folderA,file],0)).mockResolvedValueOnce(response([folderB,folderA],2))
|
||||
vi.stubGlobal('fetch',fetchMock)
|
||||
await expect(fetchAllCatalogFolders('conn-1','root')).resolves.toEqual([folderA,folderB])
|
||||
expect(fetchMock.mock.calls.map(call=>call[0])).toEqual(['/api/v1/source-catalog/nodes?connection_id=conn-1&parent_id=root&limit=100&offset=0','/api/v1/source-catalog/nodes?connection_id=conn-1&parent_id=root&limit=100&offset=2'])
|
||||
})
|
||||
it('requests only one parent page at a time',async()=>{
|
||||
const response={current:{node_id:'root-1',node_type:'folder',name:'公司级技术支持知识库',direct_child_count:1,subtree_file_count:10,subtree_bytes:20,visibility:'unknown',imported_count:0,parsed_count:0,active_count:0,failed_count:0,routable_count:0},breadcrumbs:[{node_id:'root-1',name:'公司级技术支持知识库'}],items:[{node_id:'folder-1',parent_node_id:'root-1',node_type:'folder',name:'01|产品资料',direct_child_count:2,subtree_file_count:10,subtree_bytes:20,visibility:'internal',imported_count:8,parsed_count:7,active_count:1,failed_count:0,routable_count:8}],total:1,limit:50,offset:0}
|
||||
const fetchMock=vi.fn().mockResolvedValue(new Response(JSON.stringify(response)))
|
||||
vi.stubGlobal('fetch',fetchMock)
|
||||
const page=await fetchCatalogNodes('conn-1','root-1',50,0)
|
||||
expect(page.items).toHaveLength(1)
|
||||
expect(fetchMock.mock.calls[0][0]).toBe('/api/v1/source-catalog/nodes?connection_id=conn-1&parent_id=root-1&limit=50&offset=0')
|
||||
expect(JSON.stringify(page)).not.toContain('relative_path')
|
||||
})
|
||||
it('routes selected files without exposing target knowledge-base IDs to the browser',async()=>{
|
||||
const fetchMock=vi.fn()
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({data:{internal_enabled:true,external_enabled:true}})))
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({data:{selected_files:2,routable_files:2,unbound_files:0,hash_unknown_files:0,unavailable_files:0}})))
|
||||
vi.stubGlobal('fetch',fetchMock)
|
||||
expect((await fetchCatalogRoutingCapabilities()).internal_enabled).toBe(true)
|
||||
const result=await routeCatalogFiles({connection_id:'conn-1',node_ids:['a','b'],policy:'both',operator_ref:'engineer-1',reason:'批量标注'})
|
||||
expect(result.routable_files).toBe(2)
|
||||
expect(result.unbound_files).toBe(0)
|
||||
const payload=JSON.parse(fetchMock.mock.calls[1][1].body)
|
||||
expect(payload.policy).toBe('both')
|
||||
expect(payload).not.toHaveProperty('visibility')
|
||||
expect(payload).not.toHaveProperty('target_knowledge_base_id')
|
||||
expect(fetchMock.mock.calls[1][1].headers).toMatchObject({Accept:'application/json','Content-Type':'application/json','Idempotency-Key':expect.any(String)})
|
||||
expect(fetchMock.mock.calls[1][1].headers['Idempotency-Key']).not.toBe('')
|
||||
})
|
||||
it('returns the number of test-knowledge removals requested by a blocked policy',async()=>{
|
||||
const fetchMock=vi.fn().mockResolvedValue(new Response(JSON.stringify({data:{selected_files:2,routable_files:0,unbound_files:2,hash_unknown_files:0,unavailable_files:0}})))
|
||||
vi.stubGlobal('fetch',fetchMock)
|
||||
const result=await routeCatalogFiles({connection_id:'conn-1',node_ids:['a','b'],policy:'blocked',operator_ref:'engineer-1',reason:'禁止导入'})
|
||||
expect(result.unbound_files).toBe(2)
|
||||
})
|
||||
it('starts a durable background refresh job with no source credential payload',async()=>{
|
||||
const job={id:'job-refresh',type:'source.catalog.refresh',payload:{connection_id:'conn-1',stage:'queued',progress:0,message:'等待后台刷新'},state:'pending',priority:20,available_at:'2026-09-09T00:00:00Z',attempt:0,max_attempts:3,idempotency_key:'safe',created_at:'2026-09-09T00:00:00Z',updated_at:'2026-09-09T00:00:00Z'}
|
||||
const fetchMock=vi.fn().mockResolvedValue(new Response(JSON.stringify({data:job})));vi.stubGlobal('fetch',fetchMock)
|
||||
const result=await triggerCatalogRefresh('conn-1')
|
||||
expect(result.id).toBe('job-refresh');expect(fetchMock.mock.calls[0][1].method).toBe('POST');expect(fetchMock.mock.calls[0][1].headers).toMatchObject({Accept:'application/json','Idempotency-Key':expect.any(String)});expect(fetchMock.mock.calls[0][1].headers['Idempotency-Key']).not.toBe('');expect(JSON.stringify(result.payload)).not.toContain('token')
|
||||
})
|
||||
it('loads the latest persisted snapshot change set without internal hashes',async()=>{
|
||||
const fetchMock=vi.fn().mockResolvedValue(new Response(JSON.stringify({data:{id:'cs-1',connection_id:'conn-1',source_name:'国内工业',state:'planned',add_count:2,update_count:1,move_count:0,move_scope_count:1,delete_count:1,no_change_count:10,created_at:'2026-09-10T00:00:00Z',items:[{action:'delete',title:'旧手册.pdf',old_path:'旧目录/旧手册.pdf',reason_code:'source_missing',seq:7}],total:1,limit:20,offset:0,source_locator_hash:'drop'}})))
|
||||
vi.stubGlobal('fetch',fetchMock)
|
||||
const result=await fetchLatestCatalogChangeSet('conn-1','delete',20,0)
|
||||
expect(result.add_count).toBe(2)
|
||||
expect(result.items[0]).toEqual({action:'delete',title:'旧手册.pdf',old_path:'旧目录/旧手册.pdf',new_path:'',reason_code:'source_missing',seq:7})
|
||||
expect(result).not.toHaveProperty('source_locator_hash')
|
||||
expect(fetchMock.mock.calls[0][0]).toBe('/api/v1/source-catalog/change-sets/latest?connection_id=conn-1&action=delete&limit=20&offset=0')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,112 @@
|
||||
import type { Job } from './jobs'
|
||||
import { newOperationID } from './operationKey'
|
||||
|
||||
export type CatalogSourceType='dingtalk'|'pp'|'alist'
|
||||
export type CatalogPolicy='internal'|'external'|'both'|'blocked'
|
||||
export interface CatalogSource {connection_id:string;source_type:CatalogSourceType;name:string;root_node_id:string;folder_count:number;file_count:number;observed_at:string;snapshot_only:boolean;snapshot_status:'ready';last_refresh_duration_ms:number}
|
||||
export interface CatalogBreadcrumb {node_id:string;name:string}
|
||||
export interface CatalogNode {node_id:string;parent_node_id?:string;node_type:'folder'|'file';name:string;direct_child_count:number;subtree_file_count:number;subtree_bytes:number;size_bytes?:number;modified_at?:string;content_sha256?:string;visibility:'internal'|'external'|'both'|'blocked'|'mixed'|'unknown';imported_count:number;parsed_count:number;active_count:number;failed_count:number;routable_count:number}
|
||||
export interface CatalogSnapshot {snapshot_id:string;connection_id:string;root_node_id:string;source_name:string;node_count:number;folder_count:number;file_count:number;observed_at:string;created_at:string;is_head:boolean}
|
||||
export interface CatalogSnapshotPage {items:CatalogSnapshot[];total:number;limit:number;offset:number}
|
||||
export interface CatalogNodePage {current:CatalogNode;breadcrumbs:CatalogBreadcrumb[];items:CatalogNode[];total:number;limit:number;offset:number}
|
||||
const sourceTypes=new Set(['dingtalk','pp','alist']);const nodeTypes=new Set(['folder','file']);const visibilities=new Set(['internal','external','both','blocked','mixed','unknown'])
|
||||
const record=(value:unknown):value is Record<string,unknown>=>typeof value==='object'&&value!==null
|
||||
const count=(value:unknown):value is number=>typeof value==='number'&&Number.isInteger(value)&&value>=0
|
||||
function parseNode(value:unknown):CatalogNode{
|
||||
if(!record(value)||typeof value.node_id!=='string'||typeof value.node_type!=='string'||!nodeTypes.has(value.node_type)||typeof value.name!=='string'||!count(value.direct_child_count)||!count(value.subtree_file_count)||!count(value.subtree_bytes)||typeof value.visibility!=='string'||!visibilities.has(value.visibility)||!count(value.imported_count)||!count(value.parsed_count)||!count(value.active_count)||!count(value.failed_count)||!count(value.routable_count)||value.content_sha256!==undefined&&typeof value.content_sha256!=='string')throw new Error('目录节点响应无效')
|
||||
return value as unknown as CatalogNode
|
||||
}
|
||||
export async function fetchCatalogSources(signal?:AbortSignal):Promise<CatalogSource[]>{
|
||||
const response=await fetch('/api/v1/source-catalog/sources',{headers:{Accept:'application/json'},signal})
|
||||
if(!response.ok)throw new Error(`加载来源目录失败(HTTP ${response.status})`)
|
||||
const value=await response.json() as unknown
|
||||
if(!record(value)||!Array.isArray(value.data))throw new Error('来源目录响应无效')
|
||||
return value.data.map(raw=>{
|
||||
if(!record(raw)||typeof raw.connection_id!=='string'||typeof raw.source_type!=='string'||!sourceTypes.has(raw.source_type)||typeof raw.name!=='string'||typeof raw.root_node_id!=='string'||!count(raw.folder_count)||!count(raw.file_count)||typeof raw.observed_at!=='string'||raw.snapshot_only!==true||raw.snapshot_status!=='ready'||!count(raw.last_refresh_duration_ms))throw new Error('来源目录响应无效')
|
||||
return {connection_id:raw.connection_id,source_type:raw.source_type as CatalogSourceType,name:raw.name,root_node_id:raw.root_node_id,folder_count:raw.folder_count,file_count:raw.file_count,observed_at:raw.observed_at,snapshot_only:true,snapshot_status:'ready',last_refresh_duration_ms:raw.last_refresh_duration_ms}
|
||||
})
|
||||
}
|
||||
export async function fetchCatalogSnapshots(connectionID:string,limit=20,offset=0,signal?:AbortSignal):Promise<CatalogSnapshotPage>{
|
||||
const query=new URLSearchParams({connection_id:connectionID,limit:String(limit),offset:String(offset)})
|
||||
const response=await fetch(`/api/v1/source-catalog/snapshots?${query}`,{headers:{Accept:'application/json'},signal})
|
||||
if(!response.ok)throw new Error(`加载快照历史失败(HTTP ${response.status})`)
|
||||
const value=await response.json() as unknown
|
||||
if(!record(value)||!Array.isArray(value.items)||!count(value.total)||!count(value.limit)||!count(value.offset))throw new Error('快照历史响应无效')
|
||||
const items=value.items.map(raw=>{if(!record(raw)||typeof raw.snapshot_id!=='string'||typeof raw.connection_id!=='string'||typeof raw.root_node_id!=='string'||typeof raw.source_name!=='string'||!count(raw.node_count)||!count(raw.folder_count)||!count(raw.file_count)||typeof raw.observed_at!=='string'||typeof raw.created_at!=='string'||typeof raw.is_head!=='boolean')throw new Error('快照历史条目无效');return raw as unknown as CatalogSnapshot})
|
||||
return {items,total:value.total,limit:value.limit,offset:value.offset}
|
||||
}
|
||||
export async function fetchCatalogSnapshotNodes(connectionID:string,snapshotID:string,parentID:string,limit=50,offset=0,signal?:AbortSignal):Promise<CatalogNodePage>{
|
||||
const query=new URLSearchParams({connection_id:connectionID,parent_id:parentID,limit:String(limit),offset:String(offset)})
|
||||
const response=await fetch(`/api/v1/source-catalog/snapshots/${encodeURIComponent(snapshotID)}/nodes?${query}`,{headers:{Accept:'application/json'},signal})
|
||||
if(!response.ok)throw new Error(`加载历史快照目录失败(HTTP ${response.status})`)
|
||||
const value=await response.json() as unknown
|
||||
if(!record(value)||!Array.isArray(value.items)||!count(value.total)||!count(value.limit)||!count(value.offset))throw new Error('历史快照目录响应无效')
|
||||
return {current:parseNode(value.current),breadcrumbs:Array.isArray(value.breadcrumbs)?value.breadcrumbs.map(raw=>{if(!record(raw)||typeof raw.node_id!=='string'||typeof raw.name!=='string')throw new Error('目录路径响应无效');return raw as unknown as CatalogBreadcrumb}):[],items:value.items.map(parseNode),total:value.total,limit:value.limit,offset:value.offset}
|
||||
}
|
||||
export interface ConfirmChangeSetResult{change_set_id:string;confirmed_items:number;uploads_created:number;uploads_existing:number;removals_requested:number;skipped_no_artifact:number;skipped_no_target:number;no_change_ignored:number}
|
||||
export async function confirmCatalogChangeSet(changeSetID:string,itemSeqs:number[],operatorRef:string,reason:string):Promise<{result:ConfirmChangeSetResult;operation:string}>{
|
||||
const response=await fetch(`/api/v1/source-catalog/change-sets/${encodeURIComponent(changeSetID)}/confirm`,{method:'POST',headers:{Accept:'application/json','Content-Type':'application/json','Idempotency-Key':newOperationID()},body:JSON.stringify({item_seqs:itemSeqs,operator_ref:operatorRef,reason})})
|
||||
if(!response.ok)throw new Error(response.status===409?'操作标识与另一请求冲突,请刷新后重试':`确认快照差异失败(HTTP ${response.status})`)
|
||||
const value=await response.json() as unknown;if(!record(value)||!record(value.data)||!count(value.data.confirmed_items)||!count(value.data.uploads_created)||!count(value.data.uploads_existing)||!count(value.data.removals_requested)||!count(value.data.skipped_no_artifact)||!count(value.data.skipped_no_target)||!count(value.data.no_change_ignored)||typeof value.operation!=='string')throw new Error('确认快照差异响应无效')
|
||||
return {result:value.data as unknown as ConfirmChangeSetResult,operation:value.operation}
|
||||
}
|
||||
export async function fetchCatalogNodes(connectionID:string,parentID:string,limit=50,offset=0,signal?:AbortSignal):Promise<CatalogNodePage>{
|
||||
const query=new URLSearchParams({connection_id:connectionID,parent_id:parentID,limit:String(limit),offset:String(offset)})
|
||||
const response=await fetch(`/api/v1/source-catalog/nodes?${query}`,{headers:{Accept:'application/json'},signal})
|
||||
if(!response.ok)throw new Error(response.status===404?'目录已更新,请返回来源首页':`加载目录失败(HTTP ${response.status})`)
|
||||
const value=await response.json() as unknown
|
||||
if(!record(value)||!Array.isArray(value.breadcrumbs)||!Array.isArray(value.items)||!count(value.total)||!count(value.limit)||!count(value.offset))throw new Error('目录列表响应无效')
|
||||
const breadcrumbs=value.breadcrumbs.map(raw=>{if(!record(raw)||typeof raw.node_id!=='string'||typeof raw.name!=='string')throw new Error('目录路径响应无效');return raw as unknown as CatalogBreadcrumb})
|
||||
return {current:parseNode(value.current),breadcrumbs,items:value.items.map(parseNode),total:value.total,limit:value.limit,offset:value.offset}
|
||||
}
|
||||
|
||||
export async function fetchAllCatalogFolders(connectionID:string,parentID:string,signal?:AbortSignal):Promise<CatalogNode[]>{
|
||||
const folders:CatalogNode[]=[]
|
||||
const seen=new Set<string>()
|
||||
let offset=0
|
||||
while(true){
|
||||
const page=await fetchCatalogNodes(connectionID,parentID,100,offset,signal)
|
||||
for(const node of page.items){
|
||||
if(node.node_type==='folder'&&!seen.has(node.node_id)){seen.add(node.node_id);folders.push(node)}
|
||||
}
|
||||
const next=page.offset+page.limit
|
||||
if(next>=page.total)return folders
|
||||
if(page.limit<=0||next<=offset)throw new Error('目录分页游标无效')
|
||||
offset=next
|
||||
}
|
||||
}
|
||||
|
||||
export interface CatalogRoutingCapabilities{internal_enabled:boolean;external_enabled:boolean}
|
||||
export interface CatalogRouteInput{connection_id:string;node_ids:string[];policy:CatalogPolicy;operator_ref:string;reason:string}
|
||||
export interface CatalogRouteResult{selected_files:number;routable_files:number;unbound_files:number;hash_unknown_files:number;unavailable_files:number}
|
||||
|
||||
export async function fetchCatalogRoutingCapabilities(signal?:AbortSignal):Promise<CatalogRoutingCapabilities>{
|
||||
const response=await fetch('/api/v1/source-catalog/routing-capabilities',{headers:{Accept:'application/json'},signal});if(!response.ok)throw new Error(`加载分流配置失败(HTTP ${response.status})`)
|
||||
const value=await response.json() as unknown;if(!record(value)||!record(value.data)||typeof value.data.internal_enabled!=='boolean'||typeof value.data.external_enabled!=='boolean')throw new Error('分流配置响应无效')
|
||||
return value.data as unknown as CatalogRoutingCapabilities
|
||||
}
|
||||
export async function routeCatalogFiles(input:CatalogRouteInput):Promise<CatalogRouteResult>{
|
||||
const response=await fetch('/api/v1/source-catalog/route',{method:'POST',headers:{Accept:'application/json','Content-Type':'application/json','Idempotency-Key':newOperationID()},body:JSON.stringify(input)});if(!response.ok)throw new Error(response.status===503?'对内/对外知识库尚未配置':`处理策略保存失败(HTTP ${response.status})`)
|
||||
const value=await response.json() as unknown;if(!record(value)||!record(value.data)||!count(value.data.selected_files)||!count(value.data.routable_files)||!count(value.data.unbound_files)||!count(value.data.hash_unknown_files)||!count(value.data.unavailable_files))throw new Error('文件处理响应无效')
|
||||
return value.data as unknown as CatalogRouteResult
|
||||
}
|
||||
export async function triggerCatalogRefresh(connectionID:string):Promise<Job>{
|
||||
const response=await fetch(`/api/v1/source-catalog/sources/${encodeURIComponent(connectionID)}/refresh`,{method:'POST',headers:{Accept:'application/json','Idempotency-Key':newOperationID()}});if(!response.ok)throw new Error(`启动实时刷新失败(HTTP ${response.status})`)
|
||||
const value=await response.json() as unknown;if(!record(value)||!record(value.data)||typeof value.data.id!=='string'||value.data.type!=='source.catalog.refresh')throw new Error('实时刷新任务响应无效')
|
||||
return value.data as unknown as Job
|
||||
}
|
||||
|
||||
export type CatalogChangeAction='add'|'update'|'move'|'move_scope'|'delete'|'no_change'
|
||||
export interface CatalogChangeItem{action:CatalogChangeAction;title:string;old_path:string;new_path:string;old_size_bytes?:number;new_size_bytes?:number;old_modified_at?:string;new_modified_at?:string;old_content_sha256?:string;new_content_sha256?:string;reason_code:string;seq:number;old_scope?:string;new_scope?:string;old_version_id?:string;new_version_id?:string}
|
||||
export interface CatalogChangeSetDetail{id:string;connection_id:string;source_name:string;state:'planned'|'confirmed'|'applying'|'applied'|'cancelled'|'failed';add_count:number;update_count:number;move_count:number;move_scope_count:number;delete_count:number;no_change_count:number;created_at:string;items:CatalogChangeItem[];total:number;limit:number;offset:number}
|
||||
const changeActions=new Set<CatalogChangeAction>(['add','update','move','move_scope','delete','no_change'])
|
||||
export async function fetchLatestCatalogChangeSet(connectionID:string,action:CatalogChangeAction|'',limit=20,offset=0,signal?:AbortSignal):Promise<CatalogChangeSetDetail>{
|
||||
const query=new URLSearchParams({connection_id:connectionID});if(action)query.set('action',action);query.set('limit',String(limit));query.set('offset',String(offset))
|
||||
const response=await fetch(`/api/v1/source-catalog/change-sets/latest?${query}`,{headers:{Accept:'application/json'},signal})
|
||||
if(!response.ok)throw new Error(response.status===404?'当前来源尚无快照差异':`加载快照差异失败(HTTP ${response.status})`)
|
||||
const envelope=await response.json() as unknown;if(!record(envelope)||!record(envelope.data))throw new Error('快照差异响应无效')
|
||||
const raw=envelope.data
|
||||
if(typeof raw.id!=='string'||typeof raw.connection_id!=='string'||typeof raw.source_name!=='string'||typeof raw.state!=='string'||!['planned','confirmed','applying','applied','cancelled','failed'].includes(raw.state)||!count(raw.add_count)||!count(raw.update_count)||!count(raw.move_count)||!count(raw.move_scope_count)||!count(raw.delete_count)||!count(raw.no_change_count)||typeof raw.created_at!=='string'||!Array.isArray(raw.items)||!count(raw.total)||!count(raw.limit)||!count(raw.offset))throw new Error('快照差异响应无效')
|
||||
const items=raw.items.map(item=>{if(!record(item)||typeof item.action!=='string'||!changeActions.has(item.action as CatalogChangeAction)||typeof item.title!=='string'||item.old_path!==undefined&&typeof item.old_path!=='string'||item.new_path!==undefined&&typeof item.new_path!=='string'||item.old_content_sha256!==undefined&&typeof item.old_content_sha256!=='string'||item.new_content_sha256!==undefined&&typeof item.new_content_sha256!=='string'||item.old_scope!==undefined&&typeof item.old_scope!=='string'||item.new_scope!==undefined&&typeof item.new_scope!=='string'||item.old_version_id!==undefined&&typeof item.old_version_id!=='string'||item.new_version_id!==undefined&&typeof item.new_version_id!=='string'||typeof item.reason_code!=='string'||!count(item.seq))throw new Error('快照差异条目无效');return {action:item.action as CatalogChangeAction,title:item.title,old_path:typeof item.old_path==='string'?item.old_path:'',new_path:typeof item.new_path==='string'?item.new_path:'',...(typeof item.old_size_bytes==='number'?{old_size_bytes:item.old_size_bytes}:{}),...(typeof item.new_size_bytes==='number'?{new_size_bytes:item.new_size_bytes}:{}),...(typeof item.old_modified_at==='string'?{old_modified_at:item.old_modified_at}:{}),...(typeof item.new_modified_at==='string'?{new_modified_at:item.new_modified_at}:{}),...(typeof item.old_content_sha256==='string'&&item.old_content_sha256?{old_content_sha256:item.old_content_sha256}:{}),...(typeof item.new_content_sha256==='string'&&item.new_content_sha256?{new_content_sha256:item.new_content_sha256}:{}),...(typeof item.old_scope==='string'&&item.old_scope?{old_scope:item.old_scope}:{}),...(typeof item.new_scope==='string'&&item.new_scope?{new_scope:item.new_scope}:{}),...(typeof item.old_version_id==='string'&&item.old_version_id?{old_version_id:item.old_version_id}:{}),...(typeof item.new_version_id==='string'&&item.new_version_id?{new_version_id:item.new_version_id}:{}),reason_code:item.reason_code,seq:item.seq}})
|
||||
return {id:raw.id,connection_id:raw.connection_id,source_name:raw.source_name,state:raw.state as CatalogChangeSetDetail['state'],add_count:raw.add_count,update_count:raw.update_count,move_count:raw.move_count,move_scope_count:raw.move_scope_count,delete_count:raw.delete_count,no_change_count:raw.no_change_count,created_at:raw.created_at,items,total:raw.total,limit:raw.limit,offset:raw.offset}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
.catalog-browser{max-width:1800px}.catalog-layout{display:grid;grid-template-columns:285px minmax(0,1fr);gap:18px;align-items:start}.catalog-sources,.catalog-content{min-width:0;border:1px solid var(--border-base);border-radius:14px;background:var(--bg-panel)}.catalog-sources{max-height:calc(100vh - 220px);overflow:auto;padding:12px}.catalog-sources h2{margin:4px 8px 12px;color:var(--ink-base);font-size:13px}.catalog-source{display:flex;width:100%;align-items:center;justify-content:space-between;gap:10px;margin:4px 0;border:1px solid transparent;border-radius:9px;padding:11px;background:transparent;box-shadow:none;color:var(--ink-base);text-align:left}.catalog-source:hover{background:var(--bg-soft)}.catalog-source.active{border-color:var(--c-run-border);background:var(--c-run-bg);color:var(--c-run)}.catalog-source>span{display:grid;min-width:0;gap:5px}.catalog-source b{overflow-wrap:anywhere;font-size:12px}.catalog-source small{color:var(--ink-mute);font-size:10px}.catalog-source strong{flex:0 0 auto;font-size:12px}.catalog-directory-tree{margin-top:14px;border-top:1px solid var(--border-base);padding-top:12px}.catalog-directory-tree h3{margin:0 8px 8px;color:var(--ink-base);font-size:11px}.catalog-directory-tree ul{display:grid;gap:2px;margin:0;padding:0;list-style:none}.catalog-directory-tree ul[role="group"]{margin-left:16px;border-left:1px solid var(--border-base);padding-left:5px}.catalog-tree-row{display:grid;grid-template-columns:24px minmax(0,1fr);align-items:center;gap:2px}.catalog-tree-toggle,.catalog-tree-name{border:0;background:transparent;box-shadow:none;color:var(--ink-mute)}.catalog-tree-toggle{display:grid;width:24px;height:24px;place-items:center;padding:0;border-radius:5px;font-weight:800}.catalog-tree-toggle:hover{background:#e9f4fb}.catalog-tree-name{overflow:hidden;padding:5px 4px;text-align:left;text-overflow:ellipsis;white-space:nowrap}.catalog-tree-name:hover{color:var(--c-run);text-decoration:underline}.catalog-breadcrumbs{display:flex;min-height:48px;align-items:center;gap:5px;overflow-x:auto;border-bottom:1px solid var(--border-base);padding:8px 16px;white-space:nowrap}.catalog-breadcrumbs span{display:flex;align-items:center;gap:5px}.catalog-breadcrumbs i{color:var(--ink-faint);font-style:normal}.catalog-breadcrumbs button{max-width:320px;overflow:hidden;border:0;padding:6px 8px;background:transparent;box-shadow:none;color:var(--c-run);text-overflow:ellipsis;white-space:nowrap}.catalog-breadcrumbs span:last-child button{border-radius:6px;background:#eaf4fc;color:var(--c-run);font-weight:700}.catalog-summary{display:flex;align-items:center;gap:20px;border-bottom:1px solid var(--border-base);padding:14px 18px;color:var(--ink-mute);font-size:12px}.catalog-summary>div{display:grid;min-width:220px;margin-right:auto;gap:4px}.catalog-summary strong{color:var(--ink-strong);font-size:16px}.catalog-summary small{color:var(--ink-mute);font-size:10px}.catalog-table-wrap{max-height:calc(100vh - 390px);overflow:auto}
|
||||
.root-file-notice{display:flex;align-items:center;justify-content:space-between;gap:12px;border-bottom:1px solid var(--border-base);padding:9px 18px;background:var(--c-warn-bg);color:var(--c-warn);font-size:11px}.root-file-notice button{flex:0 0 auto;border:1px solid var(--c-warn-border);padding:6px 9px;background:var(--bg-panel);box-shadow:none;color:var(--c-warn)}.catalog-table .scope-badge{white-space:nowrap}
|
||||
.catalog-back-row{border-bottom:1px solid var(--border-base);padding:8px 16px}.catalog-back-row button{border:0;padding:6px 8px;background:transparent;box-shadow:none;color:var(--c-run)}.snapshot-timestamp{padding:10px 16px;color:var(--ink-mute);font-size:10px;text-align:right}
|
||||
.catalog-routing{display:grid;gap:9px;border-bottom:1px solid var(--border-base);padding:11px 16px;background:var(--bg-soft)}.routing-fields,.routing-actions{display:flex;flex-wrap:wrap;align-items:end;gap:9px}.routing-fields label{display:grid;gap:4px;color:var(--ink-mute);font-size:9px}.routing-fields input{border:1px solid var(--border-strong);border-radius:6px;padding:7px}.routing-check{display:flex!important;align-items:center;gap:5px;padding-bottom:7px}.routing-actions span{margin-right:auto;color:var(--ink-mute);font-size:10px}.routing-actions button{padding:7px 9px}.catalog-routing p{margin:0;border-radius:6px;padding:7px;background:var(--c-done-bg);color:var(--c-done);font-size:10px}.catalog-file-routing{display:grid;gap:6px}.catalog-file-routing .catalog-file{align-items:center}.catalog-file-routing select{width:max-content;max-width:100%;border:1px solid var(--border-strong);border-radius:6px;padding:5px;background:var(--bg-panel);color:var(--ink-base);font-size:9px}.catalog-file-routing small{color:var(--c-warn);font-size:9px}
|
||||
.catalog-refresh-progress{display:grid;grid-template-columns:minmax(220px,1fr) minmax(180px,2fr) auto;align-items:center;gap:12px;margin-bottom:14px;border:1px solid var(--c-run-border);border-radius:10px;padding:10px 14px;background:var(--c-run-bg)}.catalog-refresh-progress>div{display:grid;gap:3px}.catalog-refresh-progress strong{color:var(--c-run);font-size:11px}.catalog-refresh-progress span,.catalog-refresh-progress small{color:var(--ink-mute);font-size:9px}.catalog-refresh-progress progress{width:100%;height:12px}.catalog-refresh-progress.completed{border-color:var(--c-done-border);background:var(--c-done-bg)}.catalog-refresh-progress.failed{border-color:var(--c-fail-border);background:var(--c-fail-bg)}@media(max-width:700px){.catalog-refresh-progress{grid-template-columns:1fr}.routing-fields{align-items:stretch;flex-direction:column}}
|
||||
.routing-actions button:disabled,.catalog-file-routing select:disabled{cursor:not-allowed;border-color:var(--border-base);background:var(--bg-soft);color:var(--ink-faint);box-shadow:none}.snapshot-timestamp{color:var(--ink-base);font-size:11px;font-weight:600}.catalog-table tbody tr{scroll-margin-top:42px}.catalog-table{width:100%;table-layout:fixed}.catalog-table thead th{position:sticky;z-index:2;top:0;background:var(--bg-soft)}.catalog-table th,.catalog-table td{padding:12px 10px;white-space:normal;overflow-wrap:anywhere;font-size:11px}.catalog-table th:nth-child(1){width:31%}.catalog-table th:nth-child(2){width:8%}.catalog-table th:nth-child(3){width:11%}.catalog-table th:nth-child(4){width:10%}.catalog-table th:nth-child(5){width:16%}.catalog-table th:nth-child(6){width:10%}.catalog-table th:nth-child(7){width:14%}.catalog-name{display:flex;align-items:flex-start;gap:7px;border:0;padding:0;background:transparent;box-shadow:none;color:var(--c-run);text-align:left;line-height:1.5}.catalog-name:hover{text-decoration:underline}.catalog-file{display:flex;align-items:flex-start;gap:7px;color:var(--ink-base);line-height:1.5}.catalog-table td>span:not(.scope-badge){display:block}.catalog-table td small{display:block;margin-top:4px;color:var(--ink-mute)}.problem-text{color:var(--c-warn)!important}.scope-badge.mixed{background:var(--c-run-bg);color:var(--c-run)}.scope-badge.unknown{background:var(--bg-soft);color:var(--ink-mute)}@media(max-width:1100px){.catalog-layout{grid-template-columns:220px minmax(0,1fr)}.catalog-summary{flex-wrap:wrap}.catalog-summary>div{width:100%;margin:0}.catalog-table{min-width:800px}}@media(max-width:800px){.catalog-layout{grid-template-columns:1fr}.catalog-sources{max-height:240px}.catalog-table-wrap{max-height:520px}}
|
||||
.routing-actions label{display:flex;align-items:center;gap:7px;color:var(--ink-mute);font-size:10px;font-weight:700}.routing-actions select,.catalog-folder-routing select{border:1px solid var(--border-strong);border-radius:7px;padding:7px 9px;background:var(--bg-panel);color:var(--ink-base);font:inherit}.blocked-policy-note{color:var(--c-warn);font-size:10px;line-height:1.5}.catalog-folder-routing{display:grid;gap:7px}.catalog-folder-routing select{width:max-content;max-width:100%;font-size:9px}.catalog-folder-routing small{color:var(--ink-mute)!important;font-size:9px}.scope-badge.both{background:var(--c-run-bg);color:var(--c-run)}.scope-badge.blocked{background:var(--c-fail-bg);color:var(--c-fail)}
|
||||
.catalog-pathbar{display:flex;align-items:center;gap:10px;min-height:48px;border-bottom:1px solid var(--border-base);padding:8px 16px;background:var(--bg-panel)}.catalog-back-button{display:grid;flex:0 0 auto;width:30px;height:30px;place-items:center;border:1px solid var(--border-strong);border-radius:7px;padding:0;background:var(--bg-panel);color:var(--c-run);box-shadow:none;font-size:18px}.catalog-back-button:hover:not(:disabled){background:var(--c-run-bg)}.catalog-pathbar nav{display:flex;min-width:0;align-items:center;gap:4px;overflow-x:auto;white-space:nowrap}.catalog-pathbar nav span{display:flex;min-width:0;align-items:center;gap:4px}.catalog-pathbar nav i{color:var(--ink-faint);font-style:normal}.catalog-pathbar nav button{overflow:hidden;border:0;border-radius:6px;padding:6px 7px;background:transparent;color:var(--c-run);box-shadow:none;text-overflow:ellipsis;white-space:nowrap}.catalog-pathbar nav button:hover:not(:disabled){background:var(--c-run-bg)}.catalog-pathbar nav button.current{color:var(--ink-base);font-weight:700}.catalog-pathbar nav button:disabled{cursor:default;background:transparent;color:var(--ink-base)}
|
||||
.catalog-policy-cell{display:grid;gap:6px;justify-items:start}.catalog-policy-cell select{max-width:100%;border:1px solid var(--border-strong);border-radius:7px;padding:6px 8px;background:var(--bg-panel);color:var(--ink-base);font-size:10px}.catalog-policy-cell small{min-height:14px;color:var(--ink-mute);font-size:9px}.catalog-table th:nth-child(1){width:22%}.catalog-table th:nth-child(2){width:8%}.catalog-table th:nth-child(3){width:15%}.catalog-table th:nth-child(4){width:9%}.catalog-table th:nth-child(5){width:16%}.catalog-table th:nth-child(6){width:16%}.catalog-table th:nth-child(7){width:14%}
|
||||
.routing-actions .blocked-policy-button{border-color:var(--c-fail-border);background:var(--c-fail-bg);color:var(--c-fail)}.routing-actions .blocked-policy-button:hover:not(:disabled){background:var(--c-fail-bg)}
|
||||
.catalog-node-control{display:flex;align-items:flex-start;gap:7px}.catalog-node-control input{margin-top:4px;flex:0 0 auto}
|
||||
.routing-actions .internal-policy-button{border-color:var(--c-done);background:var(--c-done);color:var(--bg-panel)}.routing-actions .internal-policy-button:hover:not(:disabled){background:var(--c-done)}.routing-actions .external-policy-button{border-color:var(--c-warn);background:var(--c-warn);color:var(--bg-panel)}.routing-actions .external-policy-button:hover:not(:disabled){background:var(--c-warn)}.routing-actions .blocked-policy-button{border-color:var(--c-fail);background:var(--c-fail);color:var(--bg-panel)}.routing-actions .blocked-policy-button:hover:not(:disabled){background:var(--c-fail)}
|
||||
.catalog-policy-cell .scope-badge.internal{background:var(--c-done-bg);color:var(--c-done)}.catalog-policy-cell .scope-badge.external{background:var(--c-warn-bg);color:var(--c-warn)}.catalog-policy-cell .scope-badge.blocked{background:var(--c-fail-bg);color:var(--c-fail)}
|
||||
.catalog-policy-actions{display:flex;align-items:flex-start;gap:8px;margin-left:auto}.blocked-policy-stack{display:grid;gap:4px}.blocked-policy-stack .selected-count{margin:0;color:var(--ink-mute);font-size:10px;line-height:1.2;text-align:center;white-space:nowrap}
|
||||
.snapshot-history{margin:12px 0;border:1px solid #d8e3f0;border-radius:10px;padding:14px 16px;background:var(--bg-soft)}
|
||||
.snapshot-history header{display:flex;align-items:center;gap:12px;flex-wrap:wrap}
|
||||
.snapshot-history header h2{margin:0;font-size:16px}
|
||||
.snapshot-history header p{margin:0;flex:1;color:var(--ink-mute);font-size:13px}
|
||||
.snapshot-history-list{list-style:none;margin:10px 0 0;padding:0;display:flex;flex-direction:column;gap:6px}
|
||||
.snapshot-history-list li{display:flex;align-items:center;gap:12px;padding:8px 10px;border:1px solid var(--border-base);border-radius:8px;background:var(--bg-panel)}
|
||||
.snapshot-history-list li>div{flex:1;display:flex;align-items:center;gap:8px;flex-wrap:wrap}
|
||||
.snapshot-history-list small{width:100%;color:var(--ink-mute)}
|
||||
.snapshot-history-table{margin-top:12px}
|
||||
.catalog-history-button{margin-left:auto}
|
||||
.catalog-refresh-detail{display:flex;gap:16px;flex-wrap:wrap;margin-top:6px;color:var(--ink-base);font-size:11px}
|
||||
.catalog-refresh-pill{display:flex;align-items:center;gap:8px;width:max-content;margin:8px 0;padding:7px 12px;border:1px solid var(--c-run-border);border-radius:999px;background:#eef6fc;color:var(--ink-base);font:inherit;font-size:11px;font-weight:700;box-shadow:none}
|
||||
.catalog-refresh-pill:hover{background:var(--c-run-bg)}
|
||||
.pill-dot{width:8px;height:8px;border-radius:50%;background:var(--c-run);display:inline-block}
|
||||
.pill-dot.retry{background:var(--c-warn)}
|
||||
.catalog-refresh-hide{margin-left:auto;border:0;background:transparent;color:#4c7d9e;font:inherit;font-size:11px;text-decoration:underline;padding:0 2px}
|
||||
.catalog-refresh-failed-note{margin:6px 0 0;color:var(--c-fail);font-size:11px}
|
||||
@@ -0,0 +1,181 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import {
|
||||
activateSourceSettingsRevision,
|
||||
createSourceSettingsRevision,
|
||||
fetchSourceConnectionList,
|
||||
fetchSourceConnections,
|
||||
fetchSourceScanDetail,
|
||||
fetchSourceSettingsRevisions,
|
||||
fetchSourceScans,
|
||||
parseSourceConnectionsResponse,
|
||||
parseSourceScanDetailResponse,
|
||||
parseSourceScansResponse,
|
||||
triggerSourceScan,
|
||||
} from './sourceConnections'
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
describe('parseSourceConnectionsResponse', () => {
|
||||
it('normalizes only the safe source connection projection', () => {
|
||||
const result = parseSourceConnectionsResponse({
|
||||
data: [{
|
||||
id: 'conn-safe', source_type: 'alist', name: 'AList只读源', enabled: true,
|
||||
schedule_configured: true, health_status: 'healthy', item_count: 42,
|
||||
updated_at: '2026-09-06T01:00:00Z', base_url: 'https://secret-origin.example', secret_ref: 'secret-name',
|
||||
last_scan: {
|
||||
id: 'scan-1', state: 'completed', observed_items: 42, unchanged_items: 40,
|
||||
added_items: 1, updated_items: 1, over_limit_items: 0, missing_items: 0,
|
||||
planned_uploads: 1, error_code: '', created_at: '2026-09-06T00:59:00Z',
|
||||
completed_at: '2026-09-06T01:00:00Z', snapshot_sha256: 'must-strip', previous_revision: 'must-strip',
|
||||
},
|
||||
}],
|
||||
summary: { total: 1, enabled: 1, disabled: 0, healthy: 1, degraded: 0, unhealthy: 0, unknown: 0 },
|
||||
})
|
||||
|
||||
expect(result.items).toEqual([{
|
||||
id: 'conn-safe', source_type: 'alist', name: 'AList只读源', enabled: true,
|
||||
schedule_configured: true, health_status: 'healthy', item_count: 42,
|
||||
updated_at: '2026-09-06T01:00:00Z',
|
||||
last_scan: {
|
||||
id: 'scan-1', state: 'completed', observed_items: 42, unchanged_items: 40,
|
||||
added_items: 1, updated_items: 1, over_limit_items: 0, missing_items: 0,
|
||||
planned_uploads: 1, error_code: '', created_at: '2026-09-06T00:59:00Z',
|
||||
completed_at: '2026-09-06T01:00:00Z',
|
||||
},
|
||||
}])
|
||||
expect(result.summary.total).toBe(1)
|
||||
expect(result.items[0]).not.toHaveProperty('base_url')
|
||||
expect(result.items[0]).not.toHaveProperty('secret_ref')
|
||||
expect(result.items[0].last_scan).not.toHaveProperty('snapshot_sha256')
|
||||
})
|
||||
})
|
||||
|
||||
describe('fetchSourceConnections', () => {
|
||||
it('uses the fixed read-only source connection endpoint', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
data: [],
|
||||
summary: { total: 0, enabled: 0, disabled: 0, healthy: 0, degraded: 0, unhealthy: 0, unknown: 0 },
|
||||
}),
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
await fetchSourceConnections()
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/api/v1/source-connections',
|
||||
expect.objectContaining({ headers: { Accept: 'application/json' } }),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('triggerSourceScan', () => {
|
||||
it('posts to the encoded connection scan endpoint and normalizes the response', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
id: 'scan-safe', source_connection_id: 'conn/a', source_type: 'pp', state: 'pending',
|
||||
created_at: '2026-09-06T01:00:00Z', snapshot_sha256: 'must-strip',
|
||||
}),
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const scan = await triggerSourceScan('conn/a')
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/source-connections/conn%2Fa/scan', expect.objectContaining({ method: 'POST' }))
|
||||
expect(scan).toEqual({
|
||||
id: 'scan-safe', source_connection_id: 'conn/a', source_type: 'pp', state: 'pending', created_at: '2026-09-06T01:00:00Z',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('source scan history and details', () => {
|
||||
const scan = {
|
||||
id: 'scan-safe', state: 'completed', observed_items: 2, unchanged_items: 0,
|
||||
added_items: 1, updated_items: 0, over_limit_items: 0, missing_items: 1,
|
||||
planned_uploads: 1, error_code: '', created_at: '2026-09-06T06:00:00Z', completed_at: '2026-09-06T06:01:00Z',
|
||||
snapshot_sha256: 'must-be-dropped', stable_external_id: 'must-be-dropped',
|
||||
}
|
||||
|
||||
it('strictly parses safe history and detail projections', () => {
|
||||
expect(parseSourceScansResponse({ data: [scan], total: 1, limit: 20, offset: 0 })).toEqual({
|
||||
items: [{
|
||||
id: 'scan-safe', state: 'completed', observed_items: 2, unchanged_items: 0,
|
||||
added_items: 1, updated_items: 0, over_limit_items: 0, missing_items: 1,
|
||||
planned_uploads: 1, error_code: '', created_at: '2026-09-06T06:00:00Z', completed_at: '2026-09-06T06:01:00Z',
|
||||
}], total: 1, limit: 20, offset: 0,
|
||||
})
|
||||
expect(parseSourceScanDetailResponse({ data: {
|
||||
...scan,
|
||||
changes: [{
|
||||
id: 'chg-safe', source_item_id: 'si-safe', change_type: 'updated', observed_size_bytes: 42,
|
||||
created_at: '2026-09-06T06:01:00Z', previous_revision: 'must-be-dropped', observed_revision: 'must-be-dropped',
|
||||
}],
|
||||
}})).toEqual({
|
||||
id: 'scan-safe', state: 'completed', observed_items: 2, unchanged_items: 0,
|
||||
added_items: 1, updated_items: 0, over_limit_items: 0, missing_items: 1,
|
||||
planned_uploads: 1, error_code: '', created_at: '2026-09-06T06:00:00Z', completed_at: '2026-09-06T06:01:00Z',
|
||||
changes: [{ id: 'chg-safe', source_item_id: 'si-safe', change_type: 'updated', observed_size_bytes: 42, created_at: '2026-09-06T06:01:00Z' }],
|
||||
})
|
||||
})
|
||||
|
||||
it('requests connection-scoped history and details', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ data: [scan], total: 1, limit: 20, offset: 0 }), { status: 200 }))
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ data: { ...scan, changes: [] } }), { status: 200 }))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
await fetchSourceScans('conn / pp')
|
||||
await fetchSourceScanDetail('conn / pp', 'scan / one')
|
||||
expect(fetchMock.mock.calls[0][0]).toBe('/api/v1/source-connections/conn%20%2F%20pp/scans?limit=20&offset=0')
|
||||
expect(fetchMock.mock.calls[1][0]).toBe('/api/v1/source-connections/conn%20%2F%20pp/scans/scan%20%2F%20one')
|
||||
})
|
||||
})
|
||||
|
||||
describe('V1 source settings client', () => {
|
||||
it('projects the connection list without sensitive fields', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({
|
||||
data: [{ id: 'conn-1', source_type: 'alist', name: 'A', enabled: true, schedule_configured: true,
|
||||
health_status: 'healthy', item_count: 3, updated_at: '2026-09-12T01:00:00Z', next_refresh_at: '2026-09-12T09:00:00Z',
|
||||
base_url: 'https://strip.me', secret_ref: 'strip-too' }],
|
||||
}), { status: 200 }))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const items = await fetchSourceConnectionList()
|
||||
expect(items).toEqual([{ id: 'conn-1', source_type: 'alist', name: 'A', enabled: true, schedule_configured: true,
|
||||
health_status: 'healthy', item_count: 3, updated_at: '2026-09-12T01:00:00Z', next_refresh_at: '2026-09-12T09:00:00Z' }])
|
||||
expect(JSON.stringify(items)).not.toContain('strip')
|
||||
})
|
||||
it('rejects malformed connection items', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({
|
||||
data: [{ id: 'x' }],
|
||||
}), { status: 200 })))
|
||||
await expect(fetchSourceConnectionList()).rejects.toThrow('invalid source connection item')
|
||||
})
|
||||
it('creates and activates revisions with intent + idempotency headers and surfaces operation', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ data: { id: 'scr-2' }, operation: 'created' }), { status: 201 }))
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ data: { connection_id: 'c', revision_id: 'scr-2' }, operation: 'replayed' }), { status: 200 }))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
expect(await createSourceSettingsRevision('conn/1', { source_type: 'alist', name: 'A', endpoint: '', credential_ref: '', enabled: true, schedule: { refresh_interval_seconds: 3600 }, operator: 'zherom' })).toEqual({ operation: 'created', id: 'scr-2' })
|
||||
expect(await activateSourceSettingsRevision('conn/1', 'scr/2')).toEqual({ operation: 'replayed', id: null })
|
||||
const [createCall, activateCall] = fetchMock.mock.calls
|
||||
expect(createCall[0]).toBe('/api/v1/source-connections/conn%2F1/settings/revisions')
|
||||
expect((createCall[1] as RequestInit).headers).toMatchObject({ 'X-Governance-Action': 'source-settings' })
|
||||
expect(((createCall[1] as RequestInit).headers as Record<string, string>)['Idempotency-Key']).toMatch(/[0-9a-f-]{36}/)
|
||||
expect(activateCall[0]).toBe('/api/v1/source-connections/conn%2F1/settings/revisions/scr%2F2/activate')
|
||||
expect(createCall[1]).not.toBe(activateCall[1])
|
||||
})
|
||||
it('surfaces server error details on failure', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: 'manual sources cannot be scheduled' }), { status: 400 })))
|
||||
await expect(createSourceSettingsRevision('c', { source_type: 'manual', name: 'A', endpoint: '', credential_ref: '', enabled: true, schedule: { refresh_interval_seconds: 3600 }, operator: 'z' })).rejects.toThrow('保存来源设置草稿失败:manual sources cannot be scheduled')
|
||||
})
|
||||
it('parses revision history strictly', async () => {
|
||||
const revision = { id: 'scr-1', revision_number: 1, state: 'active', name: 'A', endpoint: 'http://x', credential_ref: 'ref', enabled: true, refresh_interval_seconds: '3600', created_by: 'z', created_at: '2026-09-12T01:00:00Z', validated_at: null, activated_at: '2026-09-12T01:00:00Z', retired_at: null }
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: [revision] }), { status: 200 })))
|
||||
const history = await fetchSourceSettingsRevisions('c')
|
||||
expect(history[0].state).toBe('active')
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: [{ ...revision, state: 'weird' }] }), { status: 200 })))
|
||||
await expect(fetchSourceSettingsRevisions('c')).rejects.toThrow('invalid source settings revision')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,378 @@
|
||||
import { newOperationID } from './operationKey'
|
||||
export type SourceConnectionType = 'pp' | 'alist' | 'dingtalk' | 'manual'
|
||||
export type SourceHealthStatus = 'unknown' | 'healthy' | 'degraded' | 'unhealthy'
|
||||
export type SourceScanState = 'pending' | 'running' | 'completed' | 'failed'
|
||||
|
||||
export interface SourceScanSummary {
|
||||
id: string
|
||||
state: SourceScanState
|
||||
observed_items: number
|
||||
unchanged_items: number
|
||||
added_items: number
|
||||
updated_items: number
|
||||
over_limit_items: number
|
||||
missing_items: number
|
||||
planned_uploads: number
|
||||
error_code: string
|
||||
created_at: string
|
||||
completed_at: string | null
|
||||
}
|
||||
|
||||
export interface TriggeredSourceScan {
|
||||
id: string
|
||||
source_connection_id: string
|
||||
source_type: SourceConnectionType
|
||||
state: SourceScanState
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export type SourceScanChangeType = 'added' | 'updated' | 'unavailable'
|
||||
|
||||
export interface SourceScanChangeView {
|
||||
id: string
|
||||
source_item_id: string | null
|
||||
change_type: SourceScanChangeType
|
||||
observed_size_bytes: number | null
|
||||
created_at: string
|
||||
}
|
||||
|
||||
export interface SourceScanDetail extends SourceScanSummary {
|
||||
changes: SourceScanChangeView[]
|
||||
}
|
||||
|
||||
export interface SourceScanPage {
|
||||
items: SourceScanSummary[]
|
||||
total: number
|
||||
limit: number
|
||||
offset: number
|
||||
}
|
||||
|
||||
export interface SourceConnectionView {
|
||||
id: string
|
||||
source_type: SourceConnectionType
|
||||
name: string
|
||||
enabled: boolean
|
||||
schedule_configured: boolean
|
||||
health_status: SourceHealthStatus
|
||||
item_count: number
|
||||
updated_at: string
|
||||
last_scan?: SourceScanSummary | null
|
||||
}
|
||||
|
||||
export interface SourceConnectionSummary {
|
||||
total: number
|
||||
enabled: number
|
||||
disabled: number
|
||||
healthy: number
|
||||
degraded: number
|
||||
unhealthy: number
|
||||
unknown: number
|
||||
}
|
||||
|
||||
export interface SourceConnectionPage {
|
||||
items: SourceConnectionView[]
|
||||
summary: SourceConnectionSummary
|
||||
}
|
||||
|
||||
const sourceTypes = new Set<SourceConnectionType>(['pp', 'alist', 'dingtalk', 'manual'])
|
||||
const healthStatuses = new Set<SourceHealthStatus>(['unknown', 'healthy', 'degraded', 'unhealthy'])
|
||||
const scanStates = new Set<SourceScanState>(['pending', 'running', 'completed', 'failed'])
|
||||
const scanChangeTypes = new Set<SourceScanChangeType>(['added', 'updated', 'unavailable'])
|
||||
const summaryKeys: ReadonlyArray<keyof SourceConnectionSummary> = [
|
||||
'total', 'enabled', 'disabled', 'healthy', 'degraded', 'unhealthy', 'unknown',
|
||||
]
|
||||
|
||||
export function parseSourceConnectionsResponse(value: unknown): SourceConnectionPage {
|
||||
if (!isRecord(value) || !Array.isArray(value.data) || !isRecord(value.summary)) {
|
||||
throw new Error('invalid source connections response')
|
||||
}
|
||||
const items = value.data.map((raw): SourceConnectionView => {
|
||||
if (!isRecord(raw) || typeof raw.id !== 'string' || typeof raw.source_type !== 'string' ||
|
||||
!sourceTypes.has(raw.source_type as SourceConnectionType) || typeof raw.name !== 'string' ||
|
||||
typeof raw.enabled !== 'boolean' || typeof raw.schedule_configured !== 'boolean' ||
|
||||
typeof raw.health_status !== 'string' || !healthStatuses.has(raw.health_status as SourceHealthStatus) ||
|
||||
!isCount(raw.item_count) || typeof raw.updated_at !== 'string') {
|
||||
throw new Error('invalid source connection item')
|
||||
}
|
||||
const lastScan = parseSourceScanSummary(raw.last_scan)
|
||||
return {
|
||||
id: raw.id,
|
||||
source_type: raw.source_type as SourceConnectionType,
|
||||
name: raw.name,
|
||||
enabled: raw.enabled,
|
||||
schedule_configured: raw.schedule_configured,
|
||||
health_status: raw.health_status as SourceHealthStatus,
|
||||
item_count: raw.item_count,
|
||||
updated_at: raw.updated_at,
|
||||
last_scan: lastScan,
|
||||
}
|
||||
})
|
||||
const summary = {} as SourceConnectionSummary
|
||||
for (const key of summaryKeys) {
|
||||
const count = value.summary[key]
|
||||
if (!isCount(count)) throw new Error('invalid source connection summary')
|
||||
summary[key] = count
|
||||
}
|
||||
return { items, summary }
|
||||
}
|
||||
|
||||
export interface SourceConnectionListItem {
|
||||
id: string
|
||||
source_type: SourceConnectionType
|
||||
name: string
|
||||
enabled: boolean
|
||||
schedule_configured: boolean
|
||||
health_status: string
|
||||
item_count: number
|
||||
updated_at: string
|
||||
next_refresh_at: string | null
|
||||
}
|
||||
|
||||
function parseConnectionList(raw: unknown): SourceConnectionListItem[] {
|
||||
if (!Array.isArray(raw)) throw new Error('invalid source connections list')
|
||||
return raw.map((item): SourceConnectionListItem => {
|
||||
if (!isRecord(item) || typeof item.id !== 'string' || typeof item.source_type !== 'string' ||
|
||||
typeof item.name !== 'string' || typeof item.enabled !== 'boolean' ||
|
||||
typeof item.schedule_configured !== 'boolean' || typeof item.item_count !== 'number' ||
|
||||
typeof item.updated_at !== 'string' ||
|
||||
(item.next_refresh_at !== null && typeof item.next_refresh_at !== 'string')) {
|
||||
throw new Error('invalid source connection item')
|
||||
}
|
||||
return {
|
||||
id: item.id, source_type: item.source_type as SourceConnectionType, name: item.name,
|
||||
enabled: item.enabled, schedule_configured: item.schedule_configured,
|
||||
health_status: typeof item.health_status === 'string' ? item.health_status : '',
|
||||
item_count: item.item_count, updated_at: item.updated_at,
|
||||
next_refresh_at: (item.next_refresh_at as string | null) ?? null,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export async function fetchSourceConnectionList(signal?: AbortSignal): Promise<SourceConnectionListItem[]> {
|
||||
const response = await fetch('/api/v1/source-connections', { headers: { Accept: 'application/json' }, signal })
|
||||
if (!response.ok) throw new Error(`加载来源连接失败(HTTP ${response.status})`)
|
||||
const value = await response.json() as unknown
|
||||
if (!isRecord(value) || !Array.isArray(value.data)) throw new Error('invalid source connections response')
|
||||
return parseConnectionList(value.data)
|
||||
}
|
||||
|
||||
export async function fetchSourceConnections(signal?: AbortSignal): Promise<SourceConnectionPage> {
|
||||
const response = await fetch('/api/v1/source-connections', {
|
||||
headers: { Accept: 'application/json' },
|
||||
signal,
|
||||
})
|
||||
if (!response.ok) {
|
||||
throw new Error(`加载来源连接失败(HTTP ${response.status})`)
|
||||
}
|
||||
return parseSourceConnectionsResponse(await response.json())
|
||||
}
|
||||
|
||||
export async function triggerSourceScan(connectionID: string): Promise<TriggeredSourceScan> {
|
||||
const response = await fetch(`/api/v1/source-connections/${encodeURIComponent(connectionID)}/scan`, {
|
||||
method: 'POST',
|
||||
headers: { Accept: 'application/json', 'Idempotency-Key': newOperationID() },
|
||||
})
|
||||
if (!response.ok) {
|
||||
throw new Error(response.status === 409 ? '该来源已有扫描正在运行' : `触发来源扫描失败(HTTP ${response.status})`)
|
||||
}
|
||||
const raw = await response.json() as unknown
|
||||
if (!isRecord(raw) || typeof raw.id !== 'string' || typeof raw.source_connection_id !== 'string' ||
|
||||
typeof raw.source_type !== 'string' || !sourceTypes.has(raw.source_type as SourceConnectionType) ||
|
||||
typeof raw.state !== 'string' || !scanStates.has(raw.state as SourceScanState) || typeof raw.created_at !== 'string') {
|
||||
throw new Error('invalid triggered source scan response')
|
||||
}
|
||||
return {
|
||||
id: raw.id,
|
||||
source_connection_id: raw.source_connection_id,
|
||||
source_type: raw.source_type as SourceConnectionType,
|
||||
state: raw.state as SourceScanState,
|
||||
created_at: raw.created_at,
|
||||
}
|
||||
}
|
||||
|
||||
export function parseSourceScansResponse(value: unknown): SourceScanPage {
|
||||
if (!isRecord(value) || !Array.isArray(value.data) || !isCount(value.total) ||
|
||||
!isCount(value.limit) || value.limit < 1 || !isCount(value.offset)) {
|
||||
throw new Error('invalid source scans response')
|
||||
}
|
||||
return {
|
||||
items: value.data.map((item) => {
|
||||
const parsed = parseSourceScanSummary(item)
|
||||
if (!parsed) throw new Error('invalid source scan summary')
|
||||
return parsed
|
||||
}),
|
||||
total: value.total,
|
||||
limit: value.limit,
|
||||
offset: value.offset,
|
||||
}
|
||||
}
|
||||
|
||||
export function parseSourceScanDetailResponse(value: unknown): SourceScanDetail {
|
||||
if (!isRecord(value) || !isRecord(value.data) || !Array.isArray(value.data.changes)) {
|
||||
throw new Error('invalid source scan detail response')
|
||||
}
|
||||
const summary = parseSourceScanSummary(value.data)
|
||||
if (!summary) throw new Error('invalid source scan detail response')
|
||||
const changes = value.data.changes.map((raw): SourceScanChangeView => {
|
||||
if (!isRecord(raw) || typeof raw.id !== 'string' ||
|
||||
(raw.source_item_id !== null && typeof raw.source_item_id !== 'string') ||
|
||||
typeof raw.change_type !== 'string' || !scanChangeTypes.has(raw.change_type as SourceScanChangeType) ||
|
||||
(raw.observed_size_bytes !== null && !isCount(raw.observed_size_bytes)) || typeof raw.created_at !== 'string') {
|
||||
throw new Error('invalid source scan change')
|
||||
}
|
||||
return {
|
||||
id: raw.id,
|
||||
source_item_id: raw.source_item_id as string | null,
|
||||
change_type: raw.change_type as SourceScanChangeType,
|
||||
observed_size_bytes: raw.observed_size_bytes as number | null,
|
||||
created_at: raw.created_at,
|
||||
}
|
||||
})
|
||||
return { ...summary, changes }
|
||||
}
|
||||
|
||||
export async function fetchSourceScans(connectionID: string, limit = 20, offset = 0, signal?: AbortSignal): Promise<SourceScanPage> {
|
||||
const params = new URLSearchParams({ limit: String(limit), offset: String(offset) })
|
||||
const response = await fetch(`/api/v1/source-connections/${encodeURIComponent(connectionID)}/scans?${params}`, {
|
||||
headers: { Accept: 'application/json' }, signal,
|
||||
})
|
||||
if (!response.ok) throw new Error(`加载扫描历史失败(HTTP ${response.status})`)
|
||||
return parseSourceScansResponse(await response.json())
|
||||
}
|
||||
|
||||
export async function fetchSourceScanDetail(connectionID: string, scanID: string, signal?: AbortSignal): Promise<SourceScanDetail> {
|
||||
const response = await fetch(`/api/v1/source-connections/${encodeURIComponent(connectionID)}/scans/${encodeURIComponent(scanID)}`, {
|
||||
headers: { Accept: 'application/json' }, signal,
|
||||
})
|
||||
if (!response.ok) throw new Error(`加载扫描详情失败(HTTP ${response.status})`)
|
||||
return parseSourceScanDetailResponse(await response.json())
|
||||
}
|
||||
|
||||
function parseSourceScanSummary(raw: unknown): SourceScanSummary | null {
|
||||
if (raw === null || raw === undefined) return null
|
||||
if (!isRecord(raw) || typeof raw.id !== 'string' || typeof raw.state !== 'string' ||
|
||||
!scanStates.has(raw.state as SourceScanState) || typeof raw.error_code !== 'string' ||
|
||||
typeof raw.created_at !== 'string' || (raw.completed_at !== null && typeof raw.completed_at !== 'string')) {
|
||||
throw new Error('invalid source scan summary')
|
||||
}
|
||||
const countKeys = ['observed_items', 'unchanged_items', 'added_items', 'updated_items', 'over_limit_items', 'missing_items', 'planned_uploads'] as const
|
||||
for (const key of countKeys) {
|
||||
if (!isCount(raw[key])) throw new Error('invalid source scan summary')
|
||||
}
|
||||
return {
|
||||
id: raw.id,
|
||||
state: raw.state as SourceScanState,
|
||||
observed_items: raw.observed_items as number,
|
||||
unchanged_items: raw.unchanged_items as number,
|
||||
added_items: raw.added_items as number,
|
||||
updated_items: raw.updated_items as number,
|
||||
over_limit_items: raw.over_limit_items as number,
|
||||
missing_items: raw.missing_items as number,
|
||||
planned_uploads: raw.planned_uploads as number,
|
||||
error_code: raw.error_code,
|
||||
created_at: raw.created_at,
|
||||
completed_at: raw.completed_at as string | null,
|
||||
}
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null
|
||||
}
|
||||
|
||||
function isCount(value: unknown): value is number {
|
||||
return typeof value === 'number' && Number.isInteger(value) && value >= 0
|
||||
}
|
||||
|
||||
// V1 source settings revisions -------------------------------------------------
|
||||
|
||||
export type SourceSettingsRevisionState = 'validated' | 'active' | 'retired' | 'failed'
|
||||
|
||||
export interface SourceSettingsRevision {
|
||||
id: string
|
||||
revision_number: number
|
||||
state: SourceSettingsRevisionState
|
||||
name: string
|
||||
endpoint: string
|
||||
credential_ref: string
|
||||
enabled: boolean
|
||||
refresh_interval_seconds: string
|
||||
created_by: string
|
||||
created_at: string
|
||||
validated_at: string | null
|
||||
activated_at: string | null
|
||||
retired_at: string | null
|
||||
}
|
||||
|
||||
export interface SourceSettingsDraftRequest {
|
||||
source_type: SourceConnectionType
|
||||
name: string
|
||||
endpoint: string
|
||||
credential_ref: string
|
||||
enabled: boolean
|
||||
schedule: { refresh_interval_seconds?: number | null }
|
||||
operator: string
|
||||
}
|
||||
|
||||
const revisionStates = new Set<SourceSettingsRevisionState>(['validated', 'active', 'retired', 'failed'])
|
||||
|
||||
function parseSettingsRevision(raw: unknown): SourceSettingsRevision {
|
||||
if (!isRecord(raw) || typeof raw.id !== 'string' || typeof raw.revision_number !== 'number' ||
|
||||
typeof raw.state !== 'string' || !revisionStates.has(raw.state as SourceSettingsRevisionState) ||
|
||||
typeof raw.name !== 'string' || typeof raw.endpoint !== 'string' || typeof raw.credential_ref !== 'string' ||
|
||||
typeof raw.enabled !== 'boolean' || typeof raw.refresh_interval_seconds !== 'string' ||
|
||||
typeof raw.created_by !== 'string' || typeof raw.created_at !== 'string' ||
|
||||
(raw.validated_at !== null && typeof raw.validated_at !== 'string') ||
|
||||
(raw.activated_at !== null && typeof raw.activated_at !== 'string') ||
|
||||
(raw.retired_at !== null && typeof raw.retired_at !== 'string')) {
|
||||
throw new Error('invalid source settings revision')
|
||||
}
|
||||
return {
|
||||
id: raw.id, revision_number: raw.revision_number, state: raw.state as SourceSettingsRevisionState,
|
||||
name: raw.name, endpoint: raw.endpoint, credential_ref: raw.credential_ref, enabled: raw.enabled,
|
||||
refresh_interval_seconds: raw.refresh_interval_seconds, created_by: raw.created_by, created_at: raw.created_at,
|
||||
validated_at: (raw.validated_at as string | null) ?? null,
|
||||
activated_at: (raw.activated_at as string | null) ?? null,
|
||||
retired_at: (raw.retired_at as string | null) ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchSourceSettingsRevisions(connectionID: string, signal?: AbortSignal): Promise<SourceSettingsRevision[]> {
|
||||
const response = await fetch(`/api/v1/source-connections/${encodeURIComponent(connectionID)}/settings/revisions`, {
|
||||
headers: { Accept: 'application/json' },
|
||||
signal,
|
||||
})
|
||||
if (!response.ok) throw new Error(`加载来源设置历史失败(HTTP ${response.status})`)
|
||||
const value = await response.json() as unknown
|
||||
if (!isRecord(value) || !Array.isArray(value.data)) throw new Error('invalid source settings revisions response')
|
||||
return value.data.map(parseSettingsRevision)
|
||||
}
|
||||
|
||||
async function postSourceSettings(path: string, body: string, errorMessage: string): Promise<{ operation: string; id: string | null }> {
|
||||
const response = await fetch(path, {
|
||||
method: 'POST',
|
||||
headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-Governance-Action': 'source-settings', 'Idempotency-Key': newOperationID() },
|
||||
body,
|
||||
})
|
||||
if (!response.ok) {
|
||||
let detail = ''
|
||||
try {
|
||||
const parsed = await response.json() as unknown
|
||||
if (isRecord(parsed) && typeof parsed.error === 'string') detail = parsed.error
|
||||
} catch { /* keep status-only message */ }
|
||||
throw new Error(detail ? `${errorMessage}:${detail}` : `${errorMessage}(HTTP ${response.status})`)
|
||||
}
|
||||
const value = await response.json() as unknown
|
||||
if (!isRecord(value) || (value.operation !== 'created' && value.operation !== 'replayed') || !isRecord(value.data)) throw new Error('invalid source settings response')
|
||||
const id = typeof value.data.id === 'string' ? value.data.id : null
|
||||
return { operation: value.operation, id }
|
||||
}
|
||||
|
||||
export async function createSourceSettingsRevision(connectionID: string, draft: SourceSettingsDraftRequest): Promise<{ operation: string; id: string }> {
|
||||
const result = await postSourceSettings(`/api/v1/source-connections/${encodeURIComponent(connectionID)}/settings/revisions`, JSON.stringify(draft), '保存来源设置草稿失败')
|
||||
if (!result.id) throw new Error('创建来源设置草稿未返回修订号')
|
||||
return result as { operation: string; id: string }
|
||||
}
|
||||
|
||||
export async function activateSourceSettingsRevision(connectionID: string, revisionID: string): Promise<{ operation: string }> {
|
||||
return postSourceSettings(`/api/v1/source-connections/${encodeURIComponent(connectionID)}/settings/revisions/${encodeURIComponent(revisionID)}/activate`, '{}', '启用来源设置修订失败')
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
.source-link-manager{max-width:1500px}.source-link-layout{display:grid;grid-template-columns:300px minmax(0,1fr);gap:18px}.source-link-list,.source-link-editor{min-width:0;border:1px solid var(--border-base);border-radius:14px;background:var(--bg-panel)}.source-link-list{max-height:calc(100vh - 260px);overflow:auto;padding:12px}.source-link-list h2{margin:5px 8px 12px;color:var(--ink-base);font-size:13px}.source-link-list button{display:flex;width:100%;align-items:center;justify-content:space-between;gap:10px;border:1px solid transparent;border-radius:9px;padding:11px;background:transparent;box-shadow:none;color:var(--ink-base);text-align:left}.source-link-list button.active{border-color:var(--c-run-border);background:var(--c-run-bg);color:var(--c-run)}.source-link-list button>span{display:grid;gap:4px}.source-link-list small{color:var(--ink-mute);font-size:10px}.source-link-list strong{font-size:10px}.source-link-editor{padding-bottom:18px}.source-link-title{display:flex;align-items:center;justify-content:space-between;gap:12px;border-bottom:1px solid var(--border-base);padding:15px 18px}.source-link-title>div{display:grid;gap:4px}.source-link-title h2{margin:0;color:var(--ink-base);font-size:16px}.source-link-title span{color:var(--ink-mute);font-size:10px}.connection-unverified{border-radius:6px;padding:5px 7px;background:var(--c-warn-bg)!important;color:var(--c-warn)!important;font-weight:700}.source-link-fields{display:grid;grid-template-columns:1fr 1fr;gap:12px;padding:18px}.source-link-fields label{display:grid;gap:6px;color:var(--ink-base);font-size:11px}.source-link-fields input{min-width:0;border:1px solid var(--border-strong);border-radius:8px;padding:10px;background:var(--bg-panel);color:var(--ink-base)}.source-link-fields input:read-only,.source-link-fields input:disabled{background:var(--bg-soft);color:var(--ink-mute)}.source-link-boundary{display:flex;flex-wrap:wrap;gap:8px;margin:0 18px 14px}.source-link-boundary>*{border-radius:6px;padding:6px 8px;background:var(--border-soft);color:var(--ink-mute);font-size:10px}.validate-source-link{margin:0 18px}.validation-results{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:7px;margin:16px 18px;border:1px solid var(--c-done-border);border-radius:10px;padding:12px;background:var(--c-done-bg)}.validation-results div{display:grid;gap:3px}.validation-results span{color:var(--ink-mute);font-size:9px}.validation-results b{color:var(--c-done);font-size:10px}.validation-results small{grid-column:1/-1;color:var(--c-warn);font-size:9px}.credential-note{margin:15px 18px 0;border-top:1px solid var(--border-base);padding-top:13px;color:var(--ink-mute);font-size:10px;line-height:1.6}@media(max-width:900px){.source-link-layout{grid-template-columns:1fr}.source-link-list{max-height:260px}}@media(max-width:650px){.source-link-fields{grid-template-columns:1fr}.validation-results{grid-template-columns:1fr 1fr}}
|
||||
+1916
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,28 @@
|
||||
.system-settings{max-width:1500px}.settings-role-strip{display:flex;gap:10px;margin-bottom:12px}.settings-role-strip span{border-radius:8px;padding:8px 11px;font-size:10px}.engineer-role{background:var(--c-run-bg);color:var(--c-run)}.admin-role{background:var(--bg-soft);color:var(--ink-mute)}.settings-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}.settings-panel{min-width:0;border:1px solid var(--border-base);border-radius:12px;padding:15px;background:var(--bg-panel)}.settings-panel.wide{grid-column:1/-1}.settings-panel h2{margin:0 0 12px;color:var(--ink-base);font-size:14px}.settings-panel dl{display:grid;grid-template-columns:1fr auto;gap:8px;margin:0;color:var(--ink-mute);font-size:10px}.settings-panel dd{margin:0;color:var(--ink-base);font-weight:700}.settings-panel dd.ok{color:var(--c-done)}.settings-panel dd.off,.settings-panel .production span{color:var(--c-fail)}.environment-cards{display:grid;grid-template-columns:1fr 1fr;gap:10px}.environment-cards article{display:grid;grid-template-columns:1fr auto;gap:6px;border:1px solid var(--border-base);border-radius:9px;padding:11px;background:var(--bg-soft)}.environment-cards b{color:var(--ink-base);font-size:11px}.environment-cards span{color:var(--c-done);font-size:10px}.environment-cards small{grid-column:1/-1;color:var(--ink-mute);font-size:9px}.environment-cards button{grid-column:2;padding:5px 7px}.mapping-row{display:flex;flex-wrap:wrap;gap:8px;margin-top:10px}.mapping-row>*{border-radius:6px;padding:6px 8px;background:var(--border-soft);color:var(--ink-mute);font-size:9px}.dependency-grid{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:8px}.dependency-grid article{display:grid;gap:4px;border-radius:8px;padding:9px;background:var(--bg-soft)}.dependency-grid span{color:var(--ink-mute);font-size:9px}.dependency-grid b{color:var(--ink-base);font-size:10px}.dependency-grid small{color:var(--ink-mute);font-size:8px;line-height:1.5}.target-list{display:grid;gap:7px;margin:0;padding:0;list-style:none}.target-list li{display:flex;justify-content:space-between;gap:10px;color:var(--ink-mute);font-size:10px}.target-list b{color:var(--c-fail)}.settings-panel>button{margin-top:12px;padding:7px 10px}.settings-panel>small{display:block;margin-top:7px;color:var(--ink-mute);font-size:8px}.safe-setting-grid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px}.safe-setting-grid label{display:grid;gap:6px;color:var(--ink-mute);font-size:10px}.safe-setting-grid select{border:1px solid var(--border-strong);border-radius:7px;padding:8px;background:var(--bg-panel);color:var(--ink-base)}.locked-gates{display:flex;flex-wrap:wrap;gap:7px;margin-top:11px}.locked-gates span{border-radius:6px;padding:6px 8px;background:var(--c-fail-bg);color:var(--c-fail);font-size:9px}@media(max-width:900px){.dependency-grid{grid-template-columns:repeat(3,minmax(0,1fr))}.safe-setting-grid{grid-template-columns:1fr 1fr}}@media(max-width:650px){.settings-grid,.environment-cards{grid-template-columns:1fr}.settings-panel.wide{grid-column:auto}.dependency-grid,.safe-setting-grid{grid-template-columns:1fr}.settings-role-strip{flex-direction:column}}
|
||||
.settings-section-heading{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;margin-bottom:14px}.settings-section-heading h2{margin-bottom:4px}.settings-section-heading p{margin:0;color:var(--ink-mute);font-size:10px}.settings-section-heading button{padding:7px 10px;box-shadow:none}.settings-source-list{display:grid;gap:9px}.settings-source-row{display:grid;grid-template-columns:minmax(170px,.8fr) minmax(420px,2fr) minmax(130px,.55fr) auto;align-items:center;gap:14px;border:1px solid var(--border-base);border-radius:10px;padding:12px;background:var(--bg-page)}.settings-source-name{display:grid;gap:4px}.settings-source-name strong{color:var(--ink-base);font-size:12px}.settings-source-name span{color:var(--ink-mute);font-size:9px}.settings-source-row dl{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:8px}.settings-source-row dl div{display:grid;gap:3px}.settings-source-row dt{color:var(--ink-mute);font-size:8px}.settings-source-row dd{overflow-wrap:anywhere;color:var(--ink-base);font-size:9px;font-weight:650}.settings-source-row label{display:grid;gap:5px;color:var(--ink-mute);font-size:9px}.settings-source-row select{border:1px solid #c9d9e4;border-radius:7px;padding:7px;background:var(--bg-panel);color:var(--ink-base)}.settings-source-row>button{padding:7px 9px;box-shadow:none}.dependency-grid{margin-top:12px}.storage-settings-grid{display:grid;grid-template-columns:1fr 1fr minmax(220px,.8fr);gap:14px}.storage-settings-grid>dl,.storage-settings-grid>.target-list{border:1px solid var(--border-base);border-radius:9px;padding:12px;background:var(--bg-soft)}@media(max-width:1100px){.settings-source-row{grid-template-columns:1fr 1fr}.settings-source-row dl{grid-column:1/-1}.storage-settings-grid{grid-template-columns:1fr 1fr}.storage-settings-grid>.target-list{grid-column:1/-1}}@media(max-width:700px){.settings-section-heading{flex-direction:column}.settings-source-row,.settings-source-row dl,.storage-settings-grid{grid-template-columns:1fr}.settings-source-row dl{grid-column:auto}.storage-settings-grid>.target-list{grid-column:auto}}.settings-layout{display:grid;grid-template-columns:200px minmax(0,1fr);gap:18px;align-items:start}
|
||||
.settings-nav{display:flex;flex-direction:column;gap:6px;position:sticky;top:16px}
|
||||
.settings-nav button{border:1px solid transparent;background:transparent;text-align:left;padding:9px 12px;border-radius:8px;font:inherit;cursor:pointer;color:var(--ink-base)}
|
||||
.settings-nav button:hover{background:var(--border-soft)}
|
||||
.settings-nav button.active{background:var(--c-run);color:var(--bg-panel);font-weight:600}
|
||||
.settings-content{display:flex;flex-direction:column;gap:14px;min-width:0}
|
||||
.source-schedule-form{display:flex;flex-wrap:wrap;gap:10px;align-items:end;padding-top:6px}
|
||||
.source-schedule-form label{display:flex;flex-direction:column;gap:4px;font-size:13px;color:var(--ink-base)}
|
||||
.source-schedule-form select,.source-schedule-form input{padding:6px 8px;border:1px solid var(--border-strong);border-radius:6px;font:inherit;background:var(--bg-panel)}
|
||||
.source-schedule-actions{display:flex;gap:8px;align-items:end}
|
||||
button.danger{background:var(--c-fail);color:var(--bg-panel);border:none;padding:8px 14px;border-radius:8px;font:inherit;cursor:pointer}
|
||||
button.danger:hover{background:var(--c-fail)}
|
||||
button.danger:disabled{background:var(--c-fail-border);cursor:not-allowed}
|
||||
button.link{background:none;border:none;color:var(--c-run);cursor:pointer;text-decoration:underline;font:inherit;padding:4px}
|
||||
.manual-source-note{color:var(--ink-mute);font-size:13px}
|
||||
.error-message{color:var(--c-fail);font-size:13px;margin:4px 0}
|
||||
.revision-list{list-style:none;margin:8px 0 0;padding:8px 10px;background:var(--bg-soft);border-radius:8px;display:flex;flex-direction:column;gap:6px;font-size:13px}
|
||||
.revision-list li{display:flex;gap:8px;align-items:baseline;flex-wrap:wrap}
|
||||
.revision-list span{color:var(--c-run);font-weight:600}
|
||||
.revision-list small{color:var(--ink-mute)}
|
||||
.empty-inline{color:var(--ink-mute);font-size:13px}
|
||||
.modal-backdrop{position:fixed;inset:0;background:rgba(10,25,40,.45);display:flex;align-items:center;justify-content:center;z-index:50;padding:16px}
|
||||
.modal-card{background:var(--bg-panel);border-radius:12px;padding:20px;max-width:420px;box-shadow:0 18px 48px rgba(9,28,46,.35)}
|
||||
.modal-card h3{margin:0 0 8px}
|
||||
.modal-card p{color:var(--ink-base);font-size:14px;line-height:1.6}
|
||||
.modal-actions{display:flex;gap:10px;justify-content:flex-end;margin-top:14px}
|
||||
@media (max-width:900px){.settings-layout{grid-template-columns:1fr}.settings-nav{position:static;flex-direction:row;flex-wrap:wrap}}
|
||||
@@ -0,0 +1,143 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { fetchAcceptanceResults, fetchTestPublications, parseTestPublicationsResponse, retryPublication, retryPublicationsBatch, startTestPublications, fetchJobFailures } from './testPublications'
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
describe('parseTestPublicationsResponse', () => {
|
||||
it('parses the safe publication projection envelope', () => {
|
||||
const result = parseTestPublicationsResponse({
|
||||
data: [{
|
||||
id: 'pub-safe', title: 'Safe title', ingest_state: 'failed',
|
||||
processing_state: 'failed', retrieval_state: 'unpublished',
|
||||
target_scope: 'external', change_set_id: 'cs-1', change_type: 'updated', can_start: false,
|
||||
retry_count: 2, last_error: 'remote_parse_failed', can_retry: true,
|
||||
updated_at: '2026-09-04T05:00:00Z', test_kb_id: 'must-drop',
|
||||
}],
|
||||
total: 1,
|
||||
limit: 25,
|
||||
offset: 0,
|
||||
})
|
||||
|
||||
expect(result.total).toBe(1)
|
||||
expect(result.items[0].can_retry).toBe(true)
|
||||
expect(result.items[0].target_scope).toBe('external')
|
||||
expect(result.items[0].change_type).toBe('updated')
|
||||
expect(result.items[0].last_error).toBe('remote_parse_failed')
|
||||
expect(result.items[0]).not.toHaveProperty('test_kb_id')
|
||||
})
|
||||
})
|
||||
|
||||
describe('fetchTestPublications', () => {
|
||||
it('requests the selected processing state and page', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ data: [], total: 0, limit: 25, offset: 0 }),
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
await fetchTestPublications({ processing_state: 'failed', limit: 25, offset: 0 })
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/api/v1/test-publications?processing_state=failed&limit=25&offset=0',
|
||||
expect.objectContaining({ headers: { Accept: 'application/json' } }),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('fetchAcceptanceResults', () => {
|
||||
it('reads the acceptance record list', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ data: [{ check_type: 'chunks_present', state: 'passed', observed_at: '2026-09-04T05:05:00Z' }] }),
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const records = await fetchAcceptanceResults('pub-safe')
|
||||
|
||||
expect(records).toHaveLength(1)
|
||||
expect(records[0].check_type).toBe('chunks_present')
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/api/v1/test-publications/pub-safe/acceptance',
|
||||
expect.objectContaining({ headers: { Accept: 'application/json' } }),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('retryPublication', () => {
|
||||
it('posts the retry request', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({ ok: true })
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
await retryPublication('pub-safe')
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
'/api/v1/test-publications/pub-safe/retry',
|
||||
expect.objectContaining({ method: 'POST' }),
|
||||
)
|
||||
})
|
||||
|
||||
it('surfaces the server error message', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
status: 409,
|
||||
json: async () => ({ error: 'publication is not in a retryable state' }),
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
await expect(retryPublication('pub-safe')).rejects.toThrow('publication is not in a retryable state')
|
||||
})
|
||||
})
|
||||
|
||||
describe('startTestPublications', () => {
|
||||
it('starts only the explicitly confirmed processing plans', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: { selected: 2, started: 1, already_started: 1, unavailable: 0 } }), { status: 202 }))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
await expect(startTestPublications(['pub-a', 'pub-b'], 'engineer-1', '已核对差异')).resolves.toEqual({ selected: 2, started: 1, already_started: 1, unavailable: 0 })
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/test-publications/start', expect.objectContaining({
|
||||
method: 'POST',
|
||||
headers: expect.objectContaining({ 'Idempotency-Key': expect.any(String) }),
|
||||
body: JSON.stringify({ publication_ids: ['pub-a', 'pub-b'], operator_ref: 'engineer-1', reason: '已核对差异' }),
|
||||
}))
|
||||
})
|
||||
})
|
||||
describe('retryPublicationsBatch', () => {
|
||||
it('sends one server-side batch request and parses per-item outcomes', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ data: { batch_key: 'op-1', total: 2, started: 1, already_running: 1, not_retryable: 0,
|
||||
outcomes: [{ publication_id: 'tp-1', result: 'started' }, { publication_id: 'tp-2', result: 'already_running' }] }, operation: 'created' }),
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const result = await retryPublicationsBatch(['tp-1', 'tp-2'], '姚工', '解析服务恢复')
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/test-publications/retry-batch',
|
||||
expect.objectContaining({ method: 'POST' }))
|
||||
const call = fetchMock.mock.calls[0] as [string, RequestInit]
|
||||
expect(JSON.parse(String(call[1].body))).toEqual({ publication_ids: ['tp-1', 'tp-2'], operator_ref: '姚工', reason: '解析服务恢复' })
|
||||
expect(result.started).toBe(1)
|
||||
expect(result.outcomes[1].result).toBe('already_running')
|
||||
})
|
||||
|
||||
it('rejects a malformed batch envelope', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: {} }) }))
|
||||
await expect(retryPublicationsBatch(['tp-1'], '姚工', 'r')).rejects.toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe('fetchJobFailures', () => {
|
||||
it('reads the open dead-letter projection', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ data: { items: [{ id: 'jf-1', job_id: 'job-1', job_type: 'test.upload', error_code: 'remote_permanent', attempt: 5, max_attempts_at_failure: 5, state: 'open', created_at: '2026-09-11T20:00:00Z' }], total: 1, limit: 50, offset: 0 } }),
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const items = await fetchJobFailures()
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith('/api/v1/job-failures?state=open&limit=50', expect.objectContaining({ headers: { Accept: 'application/json' } }))
|
||||
expect(items[0].error_code).toBe('remote_permanent')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,181 @@
|
||||
import { newOperationID } from './operationKey'
|
||||
export type IngestState = 'pending' | 'uploading' | 'uploaded' | 'failed'
|
||||
export type ProcessingState = 'pending' | 'processing' | 'finalizing' | 'completed' | 'failed' | 'stalled'
|
||||
|
||||
export interface TestPublication {
|
||||
id: string
|
||||
title: string
|
||||
ingest_state: IngestState
|
||||
processing_state: ProcessingState
|
||||
retrieval_state: string
|
||||
target_scope: 'internal' | 'external'
|
||||
change_set_id: string
|
||||
change_type: 'added' | 'updated'
|
||||
can_start: boolean
|
||||
retry_count: number
|
||||
last_error: string
|
||||
can_retry: boolean
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export interface TestPublicationPage {
|
||||
items: TestPublication[]
|
||||
total: number
|
||||
limit: number
|
||||
offset: number
|
||||
}
|
||||
|
||||
export interface AcceptanceRecord {
|
||||
check_type: string
|
||||
state: string
|
||||
policy_version: string
|
||||
evidence_summary: unknown
|
||||
observed_at: string
|
||||
}
|
||||
|
||||
export interface TestPublicationQuery {
|
||||
processing_state: ProcessingState | ''
|
||||
target_scope?: 'internal' | 'external' | ''
|
||||
limit: number
|
||||
offset: number
|
||||
}
|
||||
|
||||
export interface StartTestPublicationsResult {
|
||||
selected: number
|
||||
started: number
|
||||
already_started: number
|
||||
unavailable: number
|
||||
}
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null
|
||||
const isCount = (value: unknown): value is number => typeof value === 'number' && Number.isInteger(value) && value >= 0
|
||||
const ingestStates = new Set<IngestState>(['pending', 'uploading', 'uploaded', 'failed'])
|
||||
const processingStates = new Set<ProcessingState>(['pending', 'processing', 'finalizing', 'completed', 'failed', 'stalled'])
|
||||
|
||||
function parseTestPublication(value: unknown): TestPublication {
|
||||
if (!isRecord(value) || typeof value.id !== 'string' || typeof value.title !== 'string' ||
|
||||
typeof value.ingest_state !== 'string' || !ingestStates.has(value.ingest_state as IngestState) ||
|
||||
typeof value.processing_state !== 'string' || !processingStates.has(value.processing_state as ProcessingState) ||
|
||||
typeof value.retrieval_state !== 'string' || (value.target_scope !== 'internal' && value.target_scope !== 'external') ||
|
||||
typeof value.change_set_id !== 'string' ||
|
||||
(value.change_type !== 'added' && value.change_type !== 'updated') || typeof value.can_start !== 'boolean' ||
|
||||
!isCount(value.retry_count) || typeof value.last_error !== 'string' || typeof value.can_retry !== 'boolean' || typeof value.updated_at !== 'string') {
|
||||
throw new Error('invalid test publication response')
|
||||
}
|
||||
return {
|
||||
id: value.id,
|
||||
title: value.title,
|
||||
ingest_state: value.ingest_state as IngestState,
|
||||
processing_state: value.processing_state as ProcessingState,
|
||||
retrieval_state: value.retrieval_state,
|
||||
target_scope: value.target_scope,
|
||||
change_set_id: value.change_set_id,
|
||||
change_type: value.change_type,
|
||||
can_start: value.can_start,
|
||||
retry_count: value.retry_count,
|
||||
last_error: value.last_error,
|
||||
can_retry: value.can_retry,
|
||||
updated_at: value.updated_at,
|
||||
}
|
||||
}
|
||||
|
||||
export function parseTestPublicationsResponse(value: unknown): TestPublicationPage {
|
||||
if (!isRecord(value) || !Array.isArray(value.data) || !isCount(value.total) || !isCount(value.limit) || !isCount(value.offset)) {
|
||||
throw new Error('invalid test publications response')
|
||||
}
|
||||
return {
|
||||
items: value.data.map(parseTestPublication),
|
||||
total: value.total,
|
||||
limit: value.limit,
|
||||
offset: value.offset,
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchTestPublications(query: TestPublicationQuery, signal?: AbortSignal): Promise<TestPublicationPage> {
|
||||
const parameters = new URLSearchParams()
|
||||
if (query.processing_state) parameters.set('processing_state', query.processing_state)
|
||||
if (query.target_scope) parameters.set('target_scope', query.target_scope)
|
||||
parameters.set('limit', String(query.limit))
|
||||
parameters.set('offset', String(query.offset))
|
||||
const response = await fetch(`/api/v1/test-publications?${parameters.toString()}`, { headers: { Accept: 'application/json' }, signal })
|
||||
if (!response.ok) throw new Error(`加载测试发布失败(HTTP ${response.status})`)
|
||||
return parseTestPublicationsResponse(await response.json())
|
||||
}
|
||||
|
||||
export async function fetchAcceptanceResults(publicationId: string, signal?: AbortSignal): Promise<AcceptanceRecord[]> {
|
||||
const response = await fetch(`/api/v1/test-publications/${encodeURIComponent(publicationId)}/acceptance`, { headers: { Accept: 'application/json' }, signal })
|
||||
if (!response.ok) throw new Error(`加载验收结果失败(HTTP ${response.status})`)
|
||||
const value = await response.json() as unknown
|
||||
if (!isRecord(value) || !Array.isArray(value.data)) throw new Error('invalid acceptance response')
|
||||
return value.data as AcceptanceRecord[]
|
||||
}
|
||||
|
||||
export async function retryPublication(publicationId: string): Promise<void> {
|
||||
const response = await fetch(`/api/v1/test-publications/${encodeURIComponent(publicationId)}/retry`, { method: 'POST', headers: { Accept: 'application/json', 'Idempotency-Key': newOperationID() } })
|
||||
if (!response.ok) {
|
||||
const body = (await response.json().catch(() => null)) as { error?: string } | null
|
||||
throw new Error(body?.error ?? `重试失败(HTTP ${response.status})`)
|
||||
}
|
||||
}
|
||||
|
||||
export async function startTestPublications(publicationIds: string[], operatorRef: string, reason: string): Promise<StartTestPublicationsResult> {
|
||||
const response = await fetch('/api/v1/test-publications/start', {
|
||||
method: 'POST',
|
||||
headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Idempotency-Key': newOperationID() },
|
||||
body: JSON.stringify({ publication_ids: publicationIds, operator_ref: operatorRef, reason }),
|
||||
})
|
||||
if (!response.ok) {
|
||||
const body = (await response.json().catch(() => null)) as { error?: string } | null
|
||||
throw new Error(body?.error ?? `开始处理失败(HTTP ${response.status})`)
|
||||
}
|
||||
const value = await response.json() as unknown
|
||||
if (!isRecord(value) || !isRecord(value.data) || !isCount(value.data.selected) || !isCount(value.data.started) || !isCount(value.data.already_started) || !isCount(value.data.unavailable)) {
|
||||
throw new Error('invalid processing start response')
|
||||
}
|
||||
return {
|
||||
selected: value.data.selected,
|
||||
started: value.data.started,
|
||||
already_started: value.data.already_started,
|
||||
unavailable: value.data.unavailable,
|
||||
}
|
||||
}
|
||||
export interface RetryOutcome { publication_id: string; result: 'started' | 'already_running' | 'not_retryable'; detail?: string }
|
||||
export interface RetryPublicationsBatchResult { batch_key: string; total: number; started: number; already_running: number; not_retryable: number; outcomes: RetryOutcome[] }
|
||||
|
||||
export async function retryPublicationsBatch(publicationIds: string[], operatorRef: string, reason: string): Promise<RetryPublicationsBatchResult> {
|
||||
const response = await fetch('/api/v1/test-publications/retry-batch', {
|
||||
method: 'POST',
|
||||
headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Idempotency-Key': newOperationID() },
|
||||
body: JSON.stringify({ publication_ids: publicationIds, operator_ref: operatorRef, reason }),
|
||||
})
|
||||
if (!response.ok) {
|
||||
const body = (await response.json().catch(() => null)) as { error?: string } | null
|
||||
throw new Error(body?.error ?? `批量重试失败(HTTP ${response.status})`)
|
||||
}
|
||||
const value = await response.json() as unknown
|
||||
if (!isRecord(value) || !isRecord(value.data) || !Array.isArray(value.data.outcomes)) throw new Error('批量重试响应无效')
|
||||
const data = value.data as Record<string, unknown>
|
||||
const outcomes = Array.isArray(data.outcomes) ? data.outcomes : []
|
||||
return {
|
||||
batch_key: typeof data.batch_key === 'string' ? data.batch_key : '',
|
||||
total: isCount(data.total) ? data.total : 0,
|
||||
started: isCount(data.started) ? data.started : 0,
|
||||
already_running: isCount(data.already_running) ? data.already_running : 0,
|
||||
not_retryable: isCount(data.not_retryable) ? data.not_retryable : 0,
|
||||
outcomes: outcomes.filter(isRecord).map((item) => ({
|
||||
publication_id: typeof item.publication_id === 'string' ? item.publication_id : '',
|
||||
result: item.result === 'started' || item.result === 'already_running' || item.result === 'not_retryable' ? item.result : 'not_retryable',
|
||||
detail: typeof item.detail === 'string' ? item.detail : undefined,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
export interface JobFailure { id: string; job_id: string; job_type: string; publication_id?: string; source_item_id?: string; error_code: string; attempt: number; max_attempts_at_failure: number; change_set_id?: string; action?: string; target_kb_id?: string; state: 'open' | 'requeued' | 'abandoned'; created_at: string }
|
||||
|
||||
export async function fetchJobFailures(signal?: AbortSignal): Promise<JobFailure[]> {
|
||||
const response = await fetch('/api/v1/job-failures?state=open&limit=50', { headers: { Accept: 'application/json' }, signal })
|
||||
if (!response.ok) throw new Error(`加载失败队列失败(HTTP ${response.status})`)
|
||||
const value = await response.json() as unknown
|
||||
if (!isRecord(value) || !isRecord(value.data) || !Array.isArray(value.data.items)) throw new Error('失败队列响应无效')
|
||||
return value.data.items as JobFailure[]
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { activateUISettings, createUISettingsCandidate, fetchActiveUISettings, parseUISettingsResponse, settingsRefreshDelays } from './uiSettings'
|
||||
|
||||
const active = {
|
||||
id: 'settings-default', state: 'active', document_refresh_seconds: 15,
|
||||
resource_refresh_seconds: 30, stalled_after_seconds: 1800,
|
||||
finalizing_after_seconds: 7200, updated_by: 'system:migration',
|
||||
created_at: '2026-09-10T08:00:00Z', activated_at: '2026-09-10T08:00:00Z',
|
||||
retired_at: null, error_code: '',
|
||||
}
|
||||
|
||||
describe('UI settings API', () => {
|
||||
it('strictly rebuilds the safe revision projection', () => {
|
||||
expect(parseUISettingsResponse({ data: { ...active, secret: 'drop' } })).toEqual(active)
|
||||
expect(() => parseUISettingsResponse({ data: { ...active, document_refresh_seconds: 31 } })).toThrow('invalid UI settings response')
|
||||
})
|
||||
|
||||
it('converts the active revision into independent monitor delays', () => {
|
||||
expect(settingsRefreshDelays({ ...active, document_refresh_seconds: 30, resource_refresh_seconds: 60 })).toEqual({ documentMs: 30000, resourceMs: 60000 })
|
||||
})
|
||||
|
||||
it('creates a validated candidate then activates it through fixed endpoints', async () => {
|
||||
const candidate = { ...active, id: 'uis-candidate', state: 'validated', updated_by: 'engineer-1', activated_at: null }
|
||||
const fetchMock = vi.fn()
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ data: active }), { status: 200 }))
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ data: candidate }), { status: 201 }))
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ data: { ...candidate, state: 'active', activated_at: '2026-09-10T08:01:00Z' } }), { status: 200 }))
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
await fetchActiveUISettings()
|
||||
await createUISettingsCandidate({ document_refresh_seconds: 30, resource_refresh_seconds: 60, stalled_after_seconds: 3600, finalizing_after_seconds: 14400, updated_by: 'engineer-1' })
|
||||
await activateUISettings('uis-candidate')
|
||||
|
||||
expect(fetchMock.mock.calls[0][0]).toBe('/api/v1/ui-settings')
|
||||
expect(fetchMock.mock.calls[1][0]).toBe('/api/v1/ui-settings/candidates')
|
||||
expect(fetchMock.mock.calls[1][1]).toMatchObject({ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ document_refresh_seconds: 30, resource_refresh_seconds: 60, stalled_after_seconds: 3600, finalizing_after_seconds: 14400, updated_by: 'engineer-1' }) })
|
||||
expect(fetchMock.mock.calls[2][0]).toBe('/api/v1/ui-settings/uis-candidate/activate')
|
||||
expect(fetchMock.mock.calls[2][1]).toMatchObject({ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' })
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,84 @@
|
||||
import { newOperationID } from './operationKey'
|
||||
export interface UISettings {
|
||||
id: string
|
||||
state: 'validated' | 'active' | 'retired' | 'failed'
|
||||
document_refresh_seconds: 15 | 30 | 60
|
||||
resource_refresh_seconds: 30 | 60
|
||||
stalled_after_seconds: 1800 | 3600
|
||||
finalizing_after_seconds: 7200 | 14400
|
||||
updated_by: string
|
||||
created_at: string
|
||||
activated_at: string | null
|
||||
retired_at: string | null
|
||||
error_code: string
|
||||
}
|
||||
|
||||
export interface UISettingsCandidateInput {
|
||||
document_refresh_seconds: UISettings['document_refresh_seconds']
|
||||
resource_refresh_seconds: UISettings['resource_refresh_seconds']
|
||||
stalled_after_seconds: UISettings['stalled_after_seconds']
|
||||
finalizing_after_seconds: UISettings['finalizing_after_seconds']
|
||||
updated_by: string
|
||||
}
|
||||
|
||||
export function settingsRefreshDelays(settings: Pick<UISettings, 'document_refresh_seconds' | 'resource_refresh_seconds'>) {
|
||||
return { documentMs: settings.document_refresh_seconds * 1000, resourceMs: settings.resource_refresh_seconds * 1000 }
|
||||
}
|
||||
|
||||
const states = new Set(['validated', 'active', 'retired', 'failed'])
|
||||
const documentRefresh = new Set([15, 30, 60])
|
||||
const resourceRefresh = new Set([30, 60])
|
||||
const stalledAfter = new Set([1800, 3600])
|
||||
const finalizingAfter = new Set([7200, 14400])
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> => Boolean(value) && typeof value === 'object' && !Array.isArray(value)
|
||||
|
||||
export function parseUISettingsResponse(value: unknown): UISettings {
|
||||
if (!isRecord(value) || !isRecord(value.data)) throw new Error('invalid UI settings response')
|
||||
const item = value.data
|
||||
if (typeof item.id !== 'string' || !/^[A-Za-z0-9._:-]{2,36}$/.test(item.id) ||
|
||||
typeof item.state !== 'string' || !states.has(item.state) ||
|
||||
typeof item.document_refresh_seconds !== 'number' || !documentRefresh.has(item.document_refresh_seconds) ||
|
||||
typeof item.resource_refresh_seconds !== 'number' || !resourceRefresh.has(item.resource_refresh_seconds) ||
|
||||
typeof item.stalled_after_seconds !== 'number' || !stalledAfter.has(item.stalled_after_seconds) ||
|
||||
typeof item.finalizing_after_seconds !== 'number' || !finalizingAfter.has(item.finalizing_after_seconds) ||
|
||||
typeof item.updated_by !== 'string' || typeof item.created_at !== 'string' ||
|
||||
(item.activated_at !== null && typeof item.activated_at !== 'string') ||
|
||||
(item.retired_at !== null && typeof item.retired_at !== 'string') || typeof item.error_code !== 'string') {
|
||||
throw new Error('invalid UI settings response')
|
||||
}
|
||||
return {
|
||||
id: item.id,
|
||||
state: item.state as UISettings['state'],
|
||||
document_refresh_seconds: item.document_refresh_seconds as UISettings['document_refresh_seconds'],
|
||||
resource_refresh_seconds: item.resource_refresh_seconds as UISettings['resource_refresh_seconds'],
|
||||
stalled_after_seconds: item.stalled_after_seconds as UISettings['stalled_after_seconds'],
|
||||
finalizing_after_seconds: item.finalizing_after_seconds as UISettings['finalizing_after_seconds'],
|
||||
updated_by: item.updated_by,
|
||||
created_at: item.created_at,
|
||||
activated_at: item.activated_at as string | null,
|
||||
retired_at: item.retired_at as string | null,
|
||||
error_code: item.error_code,
|
||||
}
|
||||
}
|
||||
|
||||
async function readSettings(response: Response): Promise<UISettings> {
|
||||
if (!response.ok) throw new Error(`UI settings request failed (${response.status})`)
|
||||
return parseUISettingsResponse(await response.json())
|
||||
}
|
||||
|
||||
export async function fetchActiveUISettings(signal?: AbortSignal): Promise<UISettings> {
|
||||
return readSettings(await fetch('/api/v1/ui-settings', { signal }))
|
||||
}
|
||||
|
||||
export async function createUISettingsCandidate(input: UISettingsCandidateInput): Promise<UISettings> {
|
||||
return readSettings(await fetch('/api/v1/ui-settings/candidates', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Governance-Action': 'ui-settings', 'Idempotency-Key': newOperationID() }, body: JSON.stringify(input),
|
||||
}))
|
||||
}
|
||||
|
||||
export async function activateUISettings(revisionID: string): Promise<UISettings> {
|
||||
if (!/^[A-Za-z0-9._:-]{2,36}$/.test(revisionID)) throw new Error('invalid UI settings revision')
|
||||
return readSettings(await fetch(`/api/v1/ui-settings/${encodeURIComponent(revisionID)}/activate`, {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Governance-Action': 'ui-settings', 'Idempotency-Key': newOperationID() }, body: '{}',
|
||||
}))
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
.weknora-monitor{max-width:1800px}.simulation-banner{display:flex;align-items:center;gap:14px;margin-bottom:14px;border:1px solid var(--c-warn);border-radius:10px;padding:10px 14px;background:var(--c-warn-bg);color:var(--c-warn)}.simulation-banner strong{padding:4px 7px;border-radius:5px;background:var(--c-warn);color:var(--c-warn);font-size:12px}.simulation-banner span{font-size:12px}.monitor-health{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:10px;margin-bottom:16px}.monitor-health article{display:grid;gap:5px;border:1px solid var(--border-base);border-radius:11px;padding:13px;background:var(--bg-panel)}.monitor-health span{color:var(--ink-mute);font-size:11px}.monitor-health strong{color:var(--ink-strong);font-size:17px}.monitor-health small{color:var(--ink-mute);font-size:9px;line-height:1.5}.monitor-health .service-healthy{box-shadow:inset 0 3px var(--c-done)}.monitor-health .service-degraded,.monitor-health .service-unhealthy{box-shadow:inset 0 3px var(--c-warn)}.monitor-kb-layout{display:grid;grid-template-columns:285px minmax(0,1fr);gap:18px}.monitor-kb-list,.monitor-kb-detail{min-width:0;border:1px solid var(--border-base);border-radius:14px;background:var(--bg-panel)}.monitor-kb-list{padding:12px}.monitor-kb-list h2{margin:5px 8px 12px;color:var(--ink-base);font-size:13px}.monitor-kb-list button{display:flex;width:100%;align-items:center;justify-content:space-between;gap:10px;border:1px solid transparent;border-radius:9px;padding:12px;background:transparent;box-shadow:none;color:var(--ink-base);text-align:left}.monitor-kb-list button.active{border-color:var(--c-run-border);background:var(--c-run-bg);color:var(--c-run)}.monitor-kb-list button>span{display:grid;gap:4px}.monitor-kb-list small{color:var(--ink-mute);font-size:10px}.monitor-kb-list strong{font-size:10px}.monitor-kb-heading{display:flex;align-items:center;justify-content:space-between;gap:15px;border-bottom:1px solid var(--border-base);padding:15px 18px}.monitor-kb-heading>div{display:flex;align-items:center;gap:12px}.monitor-kb-heading h2{margin:0;color:var(--ink-strong);font-size:16px}.monitor-kb-heading span{color:var(--ink-mute);font-size:11px}.monitor-stage-tabs{display:flex;flex-wrap:wrap;gap:7px;padding:13px 18px}.monitor-stage-tabs button{border:1px solid var(--border-base);border-radius:8px;padding:7px 9px;background:var(--bg-soft);box-shadow:none;color:var(--ink-base);font-size:11px}.monitor-stage-tabs button.active{border-color:var(--c-run);background:var(--c-run-bg);color:var(--c-run)}.finalizing-note,.sample-note{margin:0 18px 10px;border-radius:7px;padding:8px 10px;background:var(--bg-soft);color:var(--ink-mute);font-size:10px;line-height:1.6}.sample-note{background:var(--c-warn-bg);color:var(--c-warn)}.monitor-file-wrap{max-height:calc(100vh - 540px);overflow:auto}.monitor-file-table{width:100%;table-layout:fixed}.monitor-file-table thead th{position:sticky;z-index:2;top:0;background:var(--bg-soft)}.monitor-file-table th,.monitor-file-table td{padding:12px 10px;white-space:normal;overflow-wrap:anywhere;font-size:11px}.monitor-file-table th:nth-child(1){width:22%}.monitor-file-table th:nth-child(2){width:20%}.monitor-file-table th:nth-child(3){width:11%}.monitor-file-table th:nth-child(4){width:11%}.monitor-file-table th:nth-child(5){width:9%}.monitor-file-table th:nth-child(6){width:27%}.monitor-file-table small{display:block;margin-top:4px;color:var(--c-warn)}.monitor-status{display:inline-block;border-radius:6px;padding:4px 6px;background:var(--bg-soft);color:var(--ink-mute);white-space:nowrap}.monitor-status.completed{background:var(--c-done-bg);color:var(--c-done)}.monitor-status.finalizing,.monitor-status.processing{background:var(--c-run-bg);color:var(--c-run)}.monitor-status.failed{background:var(--c-warn-bg);color:var(--c-warn)}@media(max-width:1200px){.monitor-health{grid-template-columns:repeat(3,minmax(0,1fr))}.monitor-kb-layout{grid-template-columns:230px minmax(0,1fr)}}@media(max-width:800px){.monitor-health{grid-template-columns:repeat(2,minmax(0,1fr))}.monitor-kb-layout{grid-template-columns:1fr}.monitor-file-table{min-width:800px}.monitor-kb-heading{align-items:flex-start;flex-direction:column}.monitor-kb-heading>div{flex-wrap:wrap}}
|
||||
.difference-panel{margin-bottom:18px;overflow:hidden;border:1px solid var(--c-run-border);border-radius:14px;background:var(--bg-panel)}.difference-heading{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:14px 16px;background:var(--c-run-bg)}.difference-heading h2{margin:0 0 4px;color:var(--ink-base);font-size:15px}.difference-heading p{margin:0;color:var(--ink-mute);font-size:10px}.difference-counts{display:flex;gap:7px}.difference-counts span{border-radius:7px;padding:7px 9px;background:var(--c-run-bg);color:var(--c-run);font-size:10px;font-weight:750;white-space:nowrap}.difference-panel details{border-top:1px solid var(--border-base)}.difference-panel summary{cursor:pointer;padding:10px 16px;color:var(--ink-base);font-size:10px;font-weight:750}.difference-table-wrap{max-height:260px;overflow:auto}.difference-table{width:100%;table-layout:fixed}.difference-table th,.difference-table td{padding:9px 12px;white-space:normal;overflow-wrap:anywhere;font-size:10px}.difference-confirmation{display:grid;grid-template-columns:minmax(150px,.6fr) minmax(280px,1.4fr) auto;align-items:end;gap:9px;border-top:1px solid var(--border-base);padding:12px 16px}.difference-confirmation label{display:grid;gap:4px;color:var(--ink-mute);font-size:9px}.difference-confirmation input{border:1px solid var(--border-strong);border-radius:7px;padding:8px;color:var(--ink-base)}.difference-confirmation button{padding:8px 11px}.difference-message{margin:0;border-top:1px solid var(--border-base);padding:9px 16px;background:var(--c-done-bg);color:var(--c-done);font-size:10px}@media(max-width:760px){.difference-heading{align-items:flex-start;flex-direction:column}.difference-counts{flex-wrap:wrap}.difference-confirmation{grid-template-columns:1fr}}
|
||||
.persisted-change-panel{margin-bottom:18px;overflow:hidden;border:1px solid var(--c-run-border);border-radius:12px;background:var(--bg-panel)}.persisted-change-heading{display:flex;align-items:center;justify-content:space-between;gap:14px;border-bottom:1px solid var(--border-base);padding:13px 16px;background:var(--bg-soft)}.persisted-change-heading h2{margin:0 0 4px;color:var(--ink-base);font-size:15px}.persisted-change-heading p{margin:0;color:var(--ink-mute);font-size:10px}.persisted-change-heading>span{border-radius:6px;padding:6px 8px;background:var(--c-run-bg);color:var(--c-run);font-size:10px;font-weight:750}.persisted-change-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px;padding:12px}.persisted-change-grid>article{min-width:0;border:1px solid var(--border-base);border-radius:9px;padding:11px;background:var(--bg-panel)}.persisted-change-grid>article>div:first-child{display:flex;align-items:center;justify-content:space-between;gap:8px}.persisted-change-grid strong{color:var(--ink-base);font-size:11px}.persisted-change-grid small{color:var(--ink-mute);font-size:9px}.persisted-change-counts{display:flex;flex-wrap:wrap;gap:5px;margin-top:8px}.persisted-change-counts span{border-radius:5px;padding:5px 7px;background:var(--border-soft);color:var(--ink-mute);font-size:9px}.persisted-change-counts span:nth-child(1){background:var(--c-done-bg);color:var(--c-done)}.persisted-change-counts span:nth-child(2),.persisted-change-counts span:nth-child(3){background:var(--c-run-bg);color:var(--c-run)}.persisted-change-counts span:nth-child(4){background:var(--c-fail-bg);color:var(--c-fail)}.persisted-change-grid details{margin-top:8px;border-top:1px solid var(--border-base)}.persisted-change-grid summary{cursor:pointer;padding-top:8px;color:var(--c-run);font-size:9px;font-weight:750}.persisted-change-grid details p{display:grid;grid-template-columns:auto minmax(100px,.7fr) minmax(160px,1.3fr);gap:7px;margin:7px 0 0;align-items:center}.persisted-change-grid details b{border-radius:4px;padding:3px 5px;background:var(--border-soft);color:var(--ink-mute);font-size:8px}.persisted-change-grid details span,.persisted-change-grid details small{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}@media(max-width:900px){.persisted-change-grid{grid-template-columns:1fr}}@media(max-width:600px){.persisted-change-heading{align-items:flex-start;flex-direction:column}.persisted-change-grid details p{grid-template-columns:auto 1fr}.persisted-change-grid details small{grid-column:1/-1}}
|
||||
.processing-queue-panel{margin-top:18px;overflow:hidden;border:1px solid var(--border-base);border-radius:14px;background:var(--bg-panel)}.queue-heading{display:flex;align-items:center;justify-content:space-between;gap:16px;border-bottom:1px solid var(--border-base);padding:14px 16px}.queue-heading h2{margin:0 0 4px;color:var(--ink-base);font-size:15px}.queue-heading p{margin:0;color:var(--ink-mute);font-size:10px}.queue-heading>div:last-child{display:flex;align-items:end;gap:8px}.queue-heading label{display:grid;gap:4px;color:var(--ink-mute);font-size:9px}.queue-heading select{border:1px solid var(--border-strong);border-radius:7px;padding:7px;background:var(--bg-panel);color:var(--ink-base)}.queue-heading button{padding:8px 10px;box-shadow:none}.pipeline-strip{overflow-x:auto;border-bottom:1px solid var(--border-base);padding:10px 16px;background:var(--bg-soft);color:var(--ink-base);font-size:10px;font-weight:750;white-space:nowrap}.queue-table-wrap{max-height:420px;overflow:auto}.processing-queue-table{min-width:940px;table-layout:fixed}.processing-queue-table th,.processing-queue-table td{padding:10px 8px;white-space:normal;overflow-wrap:anywhere;font-size:10px}.processing-queue-table th:nth-child(1){width:18%}.processing-queue-table th:nth-child(2){width:13%}.processing-queue-table th:nth-child(3){width:10%}.processing-queue-table th:nth-child(4){width:12%}.processing-queue-table th:nth-child(5){width:17%}.processing-queue-table th:nth-child(6){width:6%}.processing-queue-table th:nth-child(7){width:14%}.processing-queue-table th:nth-child(8){width:10%}.processing-queue-table .queue-problem{background:var(--c-fail-bg)}.processing-queue-table button{padding:6px 8px;box-shadow:none;font-size:9px}.monitor-status.stalled{background:var(--c-warn-bg);color:var(--c-warn)}@media(max-width:700px){.queue-heading{align-items:stretch;flex-direction:column}.queue-heading>div:last-child{align-items:stretch;flex-direction:column}}.changeset-selection{display:flex;flex-direction:column;gap:6px;margin-top:8px}
|
||||
.changeset-choice{display:flex;align-items:center;gap:8px;font-size:12px;color:var(--ink-base)}
|
||||
.changeset-choice b{flex:0 0 78px;font-weight:700;color:var(--ink-base)}
|
||||
.changeset-choice span{overflow-wrap:anywhere}
|
||||
.changeset-choice small{color:var(--ink-faint)}
|
||||
.changeset-confirm{display:flex;align-items:center;gap:10px;margin-top:10px}
|
||||
.changeset-confirm label{display:flex;align-items:center;gap:6px;font-size:11px;color:var(--ink-mute);font-weight:700}
|
||||
.changeset-confirm input{border:1px solid var(--border-strong);border-radius:7px;padding:6px 8px;background:var(--bg-panel);color:var(--ink-base);font:inherit}
|
||||
.queue-batch-controls{display:inline-flex;align-items:center;gap:8px;margin-left:10px}
|
||||
.queue-batch-controls input{width:130px}
|
||||
.queue-batch-message{margin:6px 0;color:var(--c-done)}
|
||||
.dlq-panel{margin-top:14px}
|
||||
.dlq-list{list-style:none;margin:8px 0 0;padding:0;display:flex;flex-direction:column;gap:6px}
|
||||
.dlq-list li{display:flex;align-items:center;gap:10px;padding:8px 10px;border:1px solid var(--border-strong);border-radius:8px;background:var(--bg-page)}
|
||||
.dlq-list small{margin-left:auto;color:var(--c-dead)}
|
||||
.run-metrics{margin-top:14px}
|
||||
.run-metrics-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:8px;margin-top:8px}
|
||||
.run-metrics-grid article{border:1px solid var(--border-strong);border-radius:8px;padding:8px 10px;background:var(--bg-panel);display:flex;flex-direction:column;gap:2px}
|
||||
.run-metrics-grid span{font-size:12px;color:var(--c-dead)}
|
||||
.run-metrics-grid strong{font-size:16px}
|
||||
.run-metrics-grid small{font-size:12px;color:var(--c-dead)}
|
||||
/* P7 direction B: task-inbox layout */
|
||||
.inbox-layout .hero.compact{display:flex;align-items:center;gap:14px}
|
||||
.monitor-meta{color:var(--c-dead);font-size:12px;margin-left:auto}
|
||||
.inbox-grid{display:grid;grid-template-columns:230px minmax(0,1fr);gap:14px;align-items:start;margin-top:12px}
|
||||
.inbox-nav{background:var(--bg-panel);border:1px solid var(--border-strong);border-radius:8px;position:sticky;top:14px;overflow:hidden}
|
||||
.inbox-nav h2{font-size:13px;margin:0;padding:10px 14px;border-bottom:1px solid var(--border-strong);color:var(--c-dead);font-weight:600}
|
||||
.inbox-nav button{display:flex;justify-content:space-between;align-items:center;width:100%;padding:9px 14px;border:none;border-bottom:1px solid var(--bg-soft);background:none;color:var(--ink-strong);font:inherit;font-size:13px;cursor:pointer;text-align:left}
|
||||
.inbox-nav button.active{background:var(--c-run-bg);border-left:3px solid var(--ink-strong);padding-left:11px;font-weight:600}
|
||||
.inbox-nav .lane-count{font-style:normal;font-size:12px;padding:0 8px;border-radius:999px;background:var(--c-dead-bg);color:var(--c-dead)}
|
||||
.inbox-nav button.blocked .lane-count{background:var(--c-fail-bg);color:var(--c-fail)}
|
||||
.inbox-nav button.okall .lane-count{background:var(--c-done-bg);color:var(--c-done)}
|
||||
.inbox-work{display:flex;flex-direction:column;gap:14px;min-width:0}
|
||||
.inbox-section{background:var(--bg-panel);border:1px solid var(--border-strong);border-radius:8px;padding-bottom:4px}
|
||||
.section-head{display:flex;align-items:center;gap:10px;padding:10px 14px;border-bottom:1px solid var(--border-strong);flex-wrap:wrap}
|
||||
.section-head h2{font-size:14px;margin:0}
|
||||
.section-head h3{font-size:13px;margin:0}
|
||||
.section-head .spacer{flex:1}
|
||||
.inbox-task{display:grid;grid-template-columns:28px minmax(0,1fr) auto;gap:12px;padding:12px 14px;border-bottom:1px solid var(--bg-soft);align-items:start}
|
||||
.inbox-task:last-child{border-bottom:none}
|
||||
.inbox-task h4{margin:0;font-size:14px;display:flex;align-items:center;gap:6px;flex-wrap:wrap}
|
||||
.inbox-task .why{font-size:12px;color:var(--c-dead);margin-top:3px}
|
||||
.task-chain{margin-top:8px;display:flex;gap:4px;align-items:center;flex-wrap:wrap;font-size:11px;color:var(--c-dead)}
|
||||
.chain-step{padding:2px 8px;border-radius:4px;border:1px solid var(--border-strong);background:var(--bg-page);white-space:nowrap}
|
||||
.chain-step.done{background:var(--c-done-bg);border-color:var(--c-done-border);color:var(--c-done)}
|
||||
.chain-step.bad{background:var(--c-fail-bg);border-color:var(--c-fail-border);color:var(--c-fail);font-weight:600}
|
||||
.chain-step.active{color:var(--c-run);border-color:var(--c-run-border);background:var(--c-run-bg)}
|
||||
.errline{margin-top:6px;font-size:12px;color:var(--c-fail)}
|
||||
.task-badge{font-size:12px;padding:1px 8px;border-radius:4px;border:1px solid var(--border-strong);white-space:nowrap}
|
||||
.task-badge.add{color:var(--c-done)}.task-badge.update{color:var(--c-run)}
|
||||
.inbox-task-actions{display:flex;flex-direction:column;gap:6px;align-items:flex-end}
|
||||
.inbox-task-actions .primary{background:var(--ink-strong);color:var(--bg-panel);border-color:var(--ink-strong)}
|
||||
button.danger{color:var(--c-fail)}
|
||||
.operator-input{font:inherit;padding:5px 8px;border:1px solid var(--border-strong);border-radius:6px;width:120px}
|
||||
.tiny{font-size:12px;color:var(--c-dead)}
|
||||
.monitor-strip{display:flex;overflow-x:auto;background:var(--bg-panel);border:1px solid var(--border-strong);border-radius:8px;font-size:12px}
|
||||
.monitor-strip div{padding:8px 16px;border-right:1px solid var(--border-strong);white-space:nowrap}
|
||||
.monitor-strip div:last-child{border-right:none}
|
||||
.monitor-strip .bad{color:var(--c-fail)}.monitor-strip .good{color:var(--c-done)}
|
||||
.dlq-list button{margin-left:auto;padding:2px 10px;border:1px solid var(--border-strong);border-radius:6px;background:var(--bg-panel);cursor:pointer;font-size:12px}
|
||||
@media (max-width: 900px){.inbox-grid{grid-template-columns:1fr}.inbox-nav{position:static}}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { closeModule, initialWorkspace, openModule, restoreWorkspace } from './workspace'
|
||||
|
||||
describe('openModule', () => {
|
||||
it('opens each module once and activates an existing tab', () => {
|
||||
const opened = openModule(initialWorkspace, 'tasks')
|
||||
const reopened = openModule(opened, 'tasks')
|
||||
|
||||
expect(reopened.openTabs).toEqual(['dashboard', 'tasks'])
|
||||
expect(reopened.activeTab).toBe('tasks')
|
||||
})
|
||||
})
|
||||
|
||||
describe('closeModule', () => {
|
||||
it('activates the nearest tab on the left after closing the active tab', () => {
|
||||
const result = closeModule(
|
||||
{ openTabs: ['dashboard', 'releases', 'tasks'], activeTab: 'tasks' },
|
||||
'tasks',
|
||||
)
|
||||
|
||||
expect(result).toEqual({ openTabs: ['dashboard', 'releases'], activeTab: 'releases' })
|
||||
})
|
||||
|
||||
it('keeps the dashboard tab pinned', () => {
|
||||
const result = closeModule(
|
||||
{ openTabs: ['dashboard', 'tasks'], activeTab: 'dashboard' },
|
||||
'dashboard',
|
||||
)
|
||||
|
||||
expect(result).toEqual({ openTabs: ['dashboard', 'tasks'], activeTab: 'dashboard' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('restoreWorkspace', () => {
|
||||
it('restores open tabs and the active tab from saved state', () => {
|
||||
const result = restoreWorkspace(
|
||||
JSON.stringify({ openTabs: ['dashboard', 'tasks', 'releases'], activeTab: 'tasks' }),
|
||||
)
|
||||
|
||||
expect(result).toEqual({ openTabs: ['dashboard', 'tasks', 'releases'], activeTab: 'tasks' })
|
||||
})
|
||||
|
||||
it('drops superseded source-link and pending-file tabs from saved state', () => {
|
||||
const result = restoreWorkspace(
|
||||
JSON.stringify({ openTabs: ['dashboard', 'sources', 'knowledge', 'settings'], activeTab: 'knowledge' }),
|
||||
)
|
||||
|
||||
expect(result).toEqual({ openTabs: ['dashboard', 'settings'], activeTab: 'dashboard' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,63 @@
|
||||
export type ModuleId = 'dashboard' | 'sources' | 'knowledge' | 'tasks' | 'releases' | 'settings'
|
||||
|
||||
export interface WorkspaceState {
|
||||
openTabs: ModuleId[]
|
||||
activeTab: ModuleId
|
||||
}
|
||||
|
||||
const moduleIds = new Set<ModuleId>([
|
||||
'dashboard',
|
||||
'tasks',
|
||||
'releases',
|
||||
'settings',
|
||||
])
|
||||
|
||||
export const initialWorkspace: WorkspaceState = {
|
||||
openTabs: ['dashboard'],
|
||||
activeTab: 'dashboard',
|
||||
}
|
||||
|
||||
export function openModule(state: WorkspaceState, moduleId: ModuleId): WorkspaceState {
|
||||
return {
|
||||
openTabs: state.openTabs.includes(moduleId) ? state.openTabs : [...state.openTabs, moduleId],
|
||||
activeTab: moduleId,
|
||||
}
|
||||
}
|
||||
|
||||
export function closeModule(state: WorkspaceState, moduleId: ModuleId): WorkspaceState {
|
||||
if (moduleId === 'dashboard') return state
|
||||
|
||||
const index = state.openTabs.indexOf(moduleId)
|
||||
if (index === -1) return state
|
||||
|
||||
const openTabs = state.openTabs.filter((tab) => tab !== moduleId)
|
||||
if (state.activeTab !== moduleId) return { ...state, openTabs }
|
||||
|
||||
return {
|
||||
openTabs,
|
||||
activeTab: openTabs[Math.max(0, index - 1)] ?? 'dashboard',
|
||||
}
|
||||
}
|
||||
|
||||
export function restoreWorkspace(raw: string | null): WorkspaceState {
|
||||
if (!raw) return initialWorkspace
|
||||
try {
|
||||
const saved = JSON.parse(raw) as { openTabs?: unknown; activeTab?: unknown }
|
||||
if (!Array.isArray(saved.openTabs)) return initialWorkspace
|
||||
const restoredTabs = saved.openTabs.filter(
|
||||
(value): value is ModuleId => typeof value === 'string' && moduleIds.has(value as ModuleId),
|
||||
)
|
||||
const openTabs = ['dashboard', ...restoredTabs.filter((tab) => tab !== 'dashboard')].filter(
|
||||
(tab, index, tabs) => tabs.indexOf(tab) === index,
|
||||
) as ModuleId[]
|
||||
const activeTab =
|
||||
typeof saved.activeTab === 'string' &&
|
||||
moduleIds.has(saved.activeTab as ModuleId) &&
|
||||
openTabs.includes(saved.activeTab as ModuleId)
|
||||
? (saved.activeTab as ModuleId)
|
||||
: 'dashboard'
|
||||
return { openTabs, activeTab }
|
||||
} catch {
|
||||
return initialWorkspace
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { WorkspaceContextTabsBar } from './workspaceContext'
|
||||
|
||||
describe('WorkspaceContextTabsBar',()=>{
|
||||
it('renders clickable source directory and file context after module tabs',()=>{
|
||||
const html=renderToStaticMarkup(<WorkspaceContextTabsBar tabs={[
|
||||
{key:'source',label:'PP公开文档',onActivate:vi.fn()},
|
||||
{key:'directory',label:'产品介绍',onActivate:vi.fn()},
|
||||
{key:'file',label:'手册.pdf',onActivate:vi.fn()},
|
||||
]} />)
|
||||
expect(html).toContain('aria-label="当前来源目录和文件"')
|
||||
for(const label of ['PP公开文档','产品介绍','手册.pdf']) expect(html).toContain(label)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,10 @@
|
||||
import { createContext } from 'react'
|
||||
import type { Dispatch, SetStateAction } from 'react'
|
||||
|
||||
export interface WorkspaceContextTab {key:string;label:string;onActivate:()=>void}
|
||||
export const WorkspaceContextTabsSetter=createContext<Dispatch<SetStateAction<WorkspaceContextTab[]>>>(()=>undefined)
|
||||
|
||||
export function WorkspaceContextTabsBar({tabs}:{tabs:WorkspaceContextTab[]}){
|
||||
if(!tabs.length)return null
|
||||
return <div className="workspace-context-tabs" aria-label="当前来源目录和文件">{tabs.map((tab,index)=><span key={tab.key}>{index?<i aria-hidden="true">/</i>:null}<button type="button" onClick={tab.onActivate}>{tab.label}</button></span>)}</div>
|
||||
}
|
||||
Reference in New Issue
Block a user