fix(ui): 修复F12-F16入口与追溯缺陷
build / build (push) Successful in 1m59s

Dockerfile 运行阶段补齐 dws_dingtalk_scan(F12),并新增 runtime-scripts 门禁
做脚本依赖闭包正负例;就绪探测每次解析当前端点/绑定/凭据并区分 404、未配置、
不可达(F13);路由写入来源路径与父目录,历史空值仅按同连接同 item 的意图读时
补齐(F14);目标筛选显示短 ID 与当前绑定/历史并提供快捷筛选(F15);刷新终态
移除后台运行、展示失败时间/旧快照/脱敏原因/作业 ID 与重试(F16)。

验证:make verify 17 项全过(identity 本地按设计 skipped);一次性 schema 的
Monitor 目录/路由集成用例通过;8088 部署与真实 UI 验收仍由父会话执行。
This commit is contained in:
姚章浩
2026-11-05 10:38:26 +08:00
parent dfbf3336b2
commit 1c80b07f2c
29 changed files with 1436 additions and 75 deletions
+18 -2
View File
@@ -2504,6 +2504,10 @@ export default function App() {
return initialWorkspace
}
})
// F14 往返定位:两个模块之间只传「可证明的身份」(来源连接 + 节点/文件名),
// 不共享业务状态,也不在 URL 或全局写入路径。
const [monitorFocus, setMonitorFocus] = useState<{ source: string; q: string } | null>(null)
const [sourceFocus, setSourceFocus] = useState<{ connectionID: string; nodeID: string } | null>(null)
const load = useCallback(async (signal?: AbortSignal) => {
setLoading(true)
@@ -2968,9 +2972,21 @@ export default function App() {
onOpen={(moduleId) => setWorkspace((current) => openModule(current, moduleId))}
>
{workspace.activeTab === 'dashboard' ? (
<SourceCatalogBrowser />
<SourceCatalogBrowser
focus={sourceFocus}
onViewProcessing={(source, node) => {
setMonitorFocus({ source: source.connection_id, q: node.name })
setWorkspace((current) => openModule(current, 'tasks'))
}}
/>
) : workspace.activeTab === 'tasks' ? (
<WeKnoraMonitor />
<WeKnoraMonitor
focus={monitorFocus}
onLocateSource={(sourceID, parentNodeID) => {
setSourceFocus({ connectionID: sourceID, nodeID: parentNodeID })
setWorkspace((current) => openModule(current, 'dashboard'))
}}
/>
) : workspace.activeTab === 'sources' ? (
<SourceLinkManager />
) : workspace.activeTab === 'settings' ? (
@@ -0,0 +1,96 @@
// @vitest-environment jsdom
import { act } from 'react'
import { createRoot } from 'react-dom/client'
import type { Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { SourceCatalogBrowserView } from './SourceCatalogBrowser'
import type { CatalogNode, CatalogNodePage, CatalogSource } from './sourceCatalog'
// F14 的界面入口:已导入的文件能从这里直接跳到解析监控(不再靠手抄文件名)。
const source: CatalogSource = {
connection_id: 'conn-atom',
source_type: 'dingtalk',
name: 'ATOM知识库',
root_node_id: 'root-1',
folder_count: 1,
file_count: 1,
observed_at: '2026-10-26T10:41:01Z',
snapshot_only: true,
snapshot_status: 'ready',
last_refresh_duration_ms: 0,
}
const file: CatalogNode = {
node_id: 'node-atom-file',
parent_node_id: 'node-atom-folder',
node_type: 'file',
name: '末端航插线序问题.adoc.docx',
direct_child_count: 0,
subtree_file_count: 1,
subtree_bytes: 1024,
size_bytes: 1024,
visibility: 'internal',
imported_count: 1,
parsed_count: 1,
active_count: 0,
failed_count: 0,
routable_count: 1,
}
const page: CatalogNodePage = {
current: {
...file,
node_id: 'node-atom-folder',
node_type: 'folder',
name: '售后机器出厂问题整改',
parent_node_id: undefined,
},
breadcrumbs: [
{ node_id: 'root-1', name: 'ATOM知识库' },
{ node_id: 'node-atom-folder', name: '售后机器出厂问题整改' },
],
items: [file],
total: 1,
limit: 50,
offset: 0,
}
let container: HTMLDivElement
let root: Root
beforeEach(() => {
;(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true
container = document.createElement('div')
document.body.appendChild(container)
root = createRoot(container)
})
afterEach(() => {
act(() => root.unmount())
container.remove()
})
describe('source directory to processing handoff', () => {
it('offers 查看处理 for an imported file and passes the exact node identity', () => {
const onViewProcessing = vi.fn()
act(() =>
root.render(
<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()}
onViewProcessing={onViewProcessing}
/>
)
)
const button = [...container.querySelectorAll('button')].find((item) => item.textContent === '查看处理')
expect(button).toBeTruthy()
act(() => button?.click())
expect(onViewProcessing).toHaveBeenCalledWith(file)
})
})
@@ -0,0 +1,100 @@
// @vitest-environment jsdom
import { act } from 'react'
import { createRoot } from 'react-dom/client'
import type { Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { SourceCatalogBrowserView } from './SourceCatalogBrowser'
import type { CatalogSource } from './sourceCatalog'
import type { Job } from './jobs'
// F16 的挂载级回归:同一个组件从 running 走到 failed/completed,
// 终态不能残留“后台运行”,失败要能看到时间/旧快照/原因/作业号并可重试。
const source: CatalogSource = {
connection_id: 'conn-atom',
source_type: 'dingtalk',
name: 'ATOM知识库',
root_node_id: 'root-1',
folder_count: 1,
file_count: 191,
observed_at: '2026-10-26T10:41:01Z',
snapshot_only: true,
snapshot_status: 'ready',
last_refresh_duration_ms: 12000,
}
const job = (state: Job['state'], extra: Partial<Job> = {}): Job => ({
id: 'job-6e18ea86dce10d5472978573a4022a1a',
type: 'source.catalog.refresh',
payload: { connection_id: 'conn-atom', progress: 0, stage: 'queued', message: '等待后台刷新' },
state,
priority: 0,
available_at: '2026-11-04T14:00:00Z',
attempt: 3,
max_attempts: 3,
last_error: 'ModuleNotFoundError: dws_dingtalk_scan',
idempotency_key: 'source.catalog.refresh:conn-atom',
created_at: '2026-11-04T14:00:00Z',
updated_at: '2026-11-04T14:03:30Z',
...extra,
})
let container: HTMLDivElement
let root: Root
const render = (refreshJob: Job) =>
act(() =>
root.render(
<SourceCatalogBrowserView
sources={[source]}
selectedSource={source}
page={null}
loading={false}
error={null}
refreshJob={refreshJob}
onSelectSource={vi.fn()}
onOpenFolder={vi.fn()}
onNavigateTo={vi.fn()}
onBack={vi.fn()}
onPageChange={vi.fn()}
onRefresh={vi.fn()}
onToggleRefreshHidden={vi.fn()}
/>
)
)
beforeEach(() => {
;(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true
container = document.createElement('div')
document.body.appendChild(container)
root = createRoot(container)
})
afterEach(() => {
act(() => root.unmount())
container.remove()
})
describe('SourceCatalogBrowser refresh terminal states', () => {
it('drops the background-running text when the same card turns failed', () => {
render(job('running'))
expect(container.textContent).toContain('后台运行')
render(job('failed'))
expect(container.textContent).not.toContain('后台运行')
expect(container.textContent).toContain('实时刷新失败')
expect(container.textContent).toContain('job-6e18ea86dce10d5472978573a4022a1a')
expect(container.textContent).toContain('旧快照')
expect(container.textContent).toContain('dws_dingtalk_scan')
const retry = [...container.querySelectorAll('button')].find((button) => button.textContent === '重试刷新')
expect(retry).toBeTruthy()
})
it('keeps the retry entry disabled while running and hides it when completed', () => {
render(job('running'))
const retryRunning = [...container.querySelectorAll('button')].find((button) => button.textContent === '重试刷新')
expect(retryRunning?.disabled).toBe(true)
render(job('completed', { last_error: '' }))
expect(container.textContent).not.toContain('后台运行')
expect([...container.querySelectorAll('button')].some((button) => button.textContent === '重试刷新')).toBe(false)
expect(container.textContent).toContain('实时快照已完成')
})
})
+50 -3
View File
@@ -46,6 +46,14 @@ const scope = (value: string) =>
: '未选择'
const progress = (node: CatalogNode) =>
node.imported_count ? `已解析 ${node.parsed_count} / 已导入 ${node.imported_count}` : '尚未导入'
const time = (value?: string) => (value ? new Date(value).toLocaleString('zh-CN', { hour12: false }) : '未记录')
// 失败原因可能带来源地址或凭据路径;界面只展示脱敏摘要,详细值留在作业表。
const sanitizeRefreshReason = (value?: string) =>
(value || '')
.replace(/https?:\/\/\S+/g, '[地址已隐藏]')
.replace(/\/run\/source-secrets\/\S+/g, '[凭据路径已隐藏]')
.replace(/\b(?:token|api[-_]?key|password|authorization|cookie|secret)=\S+/gi, '[凭据已隐藏]')
.slice(0, 160)
interface ViewProps {
sources: CatalogSource[]
@@ -79,6 +87,7 @@ interface ViewProps {
refreshHidden?: boolean
onToggleRefreshHidden?: () => void
onFiltersChanged?: () => void
onViewProcessing?: (node: CatalogNode) => void
}
export function SourceCatalogBrowserView({
sources,
@@ -101,6 +110,7 @@ export function SourceCatalogBrowserView({
refreshHidden = false,
onToggleRefreshHidden,
onFiltersChanged,
onViewProcessing,
}: ViewProps) {
const [selectedIDs, setSelectedIDs] = useState<string[]>([])
const [appliedPolicies, setAppliedPolicies] = useState<Record<string, CatalogPolicy>>({})
@@ -204,13 +214,22 @@ export function SourceCatalogBrowserView({
</div>
<progress max="100" value={refreshProgress} />
<small>
{refreshProgress}%{refreshEstimate ? '(估算)' : ''} · 后台运行,可以切换页面
{refreshActive
? `${refreshProgress}%${refreshEstimate ? '(估算)' : ''} · 后台运行,可以切换页面`
: refreshJob.state === 'completed'
? `完成于 ${time(refreshJob.updated_at)}`
: `失败于 ${time(refreshJob.updated_at)} · 旧快照 ${time(selectedSource?.observed_at)}`}
</small>
{refreshActive && onToggleRefreshHidden ? (
<button type="button" className="catalog-refresh-hide" onClick={onToggleRefreshHidden}>
隐藏到后台
</button>
) : null}
{refreshJob.state !== 'completed' ? (
<button type="button" className="catalog-refresh-retry" disabled={refreshActive} onClick={onRefresh}>
重试刷新
</button>
) : null}
</section>
{refreshActive && (refreshDirectory || refreshFiles) ? (
<div className="catalog-refresh-detail" aria-label="刷新明细">
@@ -220,7 +239,8 @@ export function SourceCatalogBrowserView({
) : null}
{refreshJob.state === 'failed' ? (
<p className="catalog-refresh-failed-note" role="status">
刷新失败;旧快照仍然保留,目录浏览与标注不受影响。
刷新失败;旧快照仍然保留,目录浏览与标注不受影响。原因:
{sanitizeRefreshReason(refreshJob.last_error) || '未提供'} · 作业 {refreshJob.id}
</p>
) : null}
</>
@@ -427,6 +447,15 @@ export function SourceCatalogBrowserView({
{node.failed_count ? (
<small className="problem-text">失败 {node.failed_count}</small>
) : null}
{onViewProcessing && node.node_type === 'file' && node.imported_count > 0 ? (
<button
type="button"
className="catalog-view-processing"
onClick={() => onViewProcessing(node)}
>
查看处理
</button>
) : null}
</td>
<td>
{node.modified_at
@@ -497,7 +526,13 @@ export function SourceCatalogBrowserView({
)
}
export function SourceCatalogBrowser() {
export function SourceCatalogBrowser({
focus,
onViewProcessing,
}: {
focus?: { connectionID: string; nodeID: string } | null
onViewProcessing?: (source: CatalogSource, node: CatalogNode) => void
} = {}) {
const [sources, setSources] = useState<CatalogSource[]>([])
const [selected, setSelected] = useState<CatalogSource | null>(null)
const [parentID, setParentID] = useState('')
@@ -621,6 +656,17 @@ export function SourceCatalogBrowser() {
return () => controller.abort()
}, [selected, parentID, offset, revision])
// 从解析监控“在来源与目录定位”进入:选中该来源并直接打开文件所在目录。
useEffect(() => {
if (!focus || !sources.length) return
const target = sources.find((source) => source.connection_id === focus.connectionID)
if (!target) return
setSelected(target)
setParentID(focus.nodeID || target.root_node_id)
setOffset(0)
setPage(null)
closeHistory()
}, [focus, sources])
// 有来源正在首次扫描时自动刷新列表:百分比会自己往前走,扫完那一行自动变成正式来源。
useEffect(() => {
if (!sources.some((source) => source.snapshot_status === 'scanning')) return
@@ -777,6 +823,7 @@ export function SourceCatalogBrowser() {
refreshHidden={refreshHidden}
onToggleRefreshHidden={() => setRefreshHidden((value) => !value)}
onFiltersChanged={() => setRevision((value) => value + 1)}
onViewProcessing={onViewProcessing && selected ? (node) => onViewProcessing(selected, node) : undefined}
/>
)
}
+67
View File
@@ -9,6 +9,8 @@ const page: MonitorTaskPage = {
id: 'tp-1',
title: '维护手册.pdf',
path: '产品/维护',
node_id: 'node-1',
parent_node_id: 'folder-1',
source_id: 's1',
source_name: '技术资料',
target_scope: 'internal',
@@ -27,6 +29,8 @@ const page: MonitorTaskPage = {
id: 'tp-2',
title: '过期资料.pdf',
path: '历史',
node_id: 'node-2',
parent_node_id: 'folder-2',
source_id: 's1',
source_name: '技术资料',
target_scope: 'external',
@@ -47,6 +51,7 @@ const page: MonitorTaskPage = {
offset: 0,
sources: [{ id: 's1', name: '技术资料' }],
targets: [],
bindings: { internal: '', external: '' },
retryable: 1,
}
const props = {
@@ -103,3 +108,65 @@ describe('unified monitor', () => {
expect(html).not.toContain('aria-label="选择过期资料.pdf"')
})
})
describe('target identity and probe attribution', () => {
it('labels same-named targets with short id and current/history state', () => {
const current = '0c84a098-d3ed-4b82-a165-e6de9691d6a8'
const historical = 'sc-ed1f812c4e5fabe817fc6351104938c4'
const withTargets = {
...page,
items: [
{ ...page.items[0], target_kb: current },
{ ...page.items[1], target_kb: historical },
],
targets: [
{ id: current, name: current, scope: 'internal' },
{ id: historical, name: historical, scope: 'internal' },
],
bindings: { internal: current, external: '' },
}
const html = renderToStaticMarkup(<WeKnoraMonitorView {...props} page={withTargets} />)
expect(html).toContain('0c84a098')
expect(html).toContain('当前绑定')
expect(html).toContain('sc-ed1f8')
expect(html).toContain('历史')
expect(html).toContain('产品/维护')
})
it('shows liveness and the sanitized probe target separately from readiness', () => {
const overview = {
mode: 'real',
simulated: false,
observed_at: '2026-11-05T02:00:00Z',
host: {
cpu_percent: 1,
memory_used_bytes: 1,
memory_total_bytes: 2,
disk_used_bytes: 1,
disk_total_bytes: 2,
gpu_state: 'none',
gpu_detail: '',
simulated: false,
},
services: [],
knowledge_bases: [],
health: [
{
key: 'weknora',
name: 'WeKnora API',
liveness: 'up',
readiness: 'blocked',
reason: 'WeKnora 探测目标知识库不存在(实例 weknora.test · 知识库 1b52c140)',
latency_ms: 3,
observed_at: '2026-11-05T02:00:00Z',
last_success_at: null,
consecutive_failures: 1,
probe_target: '实例 weknora.test · 知识库 1b52c140',
configured: true,
applicable: true,
},
],
}
const html = renderToStaticMarkup(<WeKnoraMonitorView {...props} overview={overview} />)
expect(html).toContain('存活 up')
expect(html).toContain('探测对象 实例 weknora.test · 知识库 1b52c140')
})
})
+70 -7
View File
@@ -8,6 +8,7 @@ import {
actionLabels,
stageLabels,
taskStatusLabels,
targetLabel,
} from './monitorTasks'
import type { MonitorFilters, MonitorTask, MonitorTaskPage } from './monitorTasks'
import { requeueJobFailure, retryPublicationsBatch } from './testPublications'
@@ -16,7 +17,16 @@ import { useOptionalAuth } from './auth'
import { WorkspaceContextTabsSetter } from './workspaceContext'
import './monitorWorkbench.css'
const emptyPage: MonitorTaskPage = { items: [], total: 0, limit: 20, offset: 0, sources: [], targets: [], retryable: 0 }
const emptyPage: MonitorTaskPage = {
items: [],
total: 0,
limit: 20,
offset: 0,
sources: [],
targets: [],
bindings: { internal: '', external: '' },
retryable: 0,
}
const time = (value: string) => (value ? new Date(value).toLocaleString('zh-CN', { hour12: false }) : '—')
const percent = (value: number | null | undefined) => (value == null ? '—' : `${value}%`)
const seconds = (value: number | null | undefined) => (value == null ? '—' : `${Number(value.toFixed(1))} 秒`)
@@ -51,6 +61,7 @@ interface ViewProps {
onRetry: (rows: MonitorTask[]) => void
onDetail: (row: MonitorTask) => void
onRefresh: () => void
onLocateSource?: (sourceID: string, parentNodeID: string) => void
}
export function WeKnoraMonitorView(p: ViewProps) {
const { overview, metrics, page, filters, selected, busy, loading } = p
@@ -63,6 +74,8 @@ export function WeKnoraMonitorView(p: ViewProps) {
const selectedIDs = new Set(selected.map((r) => r.id))
const allPage = eligible.length > 0 && eligible.every((r) => selectedIDs.has(r.id))
const kbName = (id: string) => overview?.knowledge_bases.find((k) => k.id === id)?.name || id
const bindings = page.bindings
const scopeBinding = filters.scope === 'external' ? bindings.external : bindings.internal
return (
<main className="page-shell monitor-workbench">
<header className="monitor-heading">
@@ -180,7 +193,8 @@ export function WeKnoraMonitorView(p: ViewProps) {
</summary>
<p>{s.reason || '未提供状态说明'}</p>
<small>
检测:{time(s.observed_at)} · {s.latency_ms} ms
检测:{time(s.observed_at)} · {s.latency_ms} ms · 存活 {s.liveness || '未确认'}
{s.probe_target ? ` · 探测对象 ${s.probe_target}` : ''}
</small>
</details>
))
@@ -234,10 +248,23 @@ export function WeKnoraMonitorView(p: ViewProps) {
<option value="">全部目标知识库</option>
{page.targets.map((t) => (
<option key={t.id} value={t.id}>
{kbName(t.id)}
{targetLabel(kbName(t.id), t.id, t.scope || '', bindings)}
</option>
))}
</select>
<button
type="button"
className="monitor-link"
disabled={busy || !scopeBinding}
title={
scopeBinding
? `当前${filters.scope === 'external' ? '对外' : '对内'}绑定:${scopeBinding}`
: '尚未配置当前绑定'
}
onClick={() => scopeBinding && patchFilter('target', scopeBinding)}
>
仅当前绑定
</button>
<select
aria-label="处理动作"
value={filters.action}
@@ -407,7 +434,9 @@ export function WeKnoraMonitorView(p: ViewProps) {
<td>{item.source_name}</td>
<td>
<span className="monitor-scope">{item.target_scope === 'internal' ? '对内' : '对外'}</span>
<small title={kbName(item.target_kb)}>{kbName(item.target_kb)}</small>
<small title={item.target_kb}>
{targetLabel(kbName(item.target_kb), item.target_kb, item.target_scope, bindings)}
</small>
</td>
<td>{actionLabels[item.action]}</td>
<td>{stageLabels[item.stage]}</td>
@@ -466,7 +495,15 @@ export function WeKnoraMonitorView(p: ViewProps) {
</main>
)
}
function TaskDetail({ item, onClose }: { item: MonitorTask; onClose: () => void }) {
function TaskDetail({
item,
onClose,
onLocateSource,
}: {
item: MonitorTask
onClose: () => void
onLocateSource?: (sourceID: string, parentNodeID: string) => void
}) {
const ref = useRef<HTMLDialogElement>(null)
useEffect(() => {
ref.current?.showModal()
@@ -483,6 +520,7 @@ function TaskDetail({ item, onClose }: { item: MonitorTask; onClose: () => void
<dl>
{[
['来源', item.source_name],
['来源连接', item.source_id],
['目录', item.path],
['目标知识库', item.target_kb],
['处理动作', actionLabels[item.action]],
@@ -499,6 +537,17 @@ function TaskDetail({ item, onClose }: { item: MonitorTask; onClose: () => void
</div>
))}
</dl>
{onLocateSource ? (
<button
type="button"
className="monitor-link"
disabled={!item.parent_node_id}
title={item.parent_node_id ? '回到该文件所在的来源目录' : '该记录没有可定位的来源目录'}
onClick={() => onLocateSource(item.source_id, item.parent_node_id)}
>
在来源与目录定位
</button>
) : null}
{item.history?.length ? (
<section className="monitor-history">
<h3>版本与重试记录</h3>
@@ -522,7 +571,13 @@ function TaskDetail({ item, onClose }: { item: MonitorTask; onClose: () => void
</dialog>
)
}
export function WeKnoraMonitor() {
export function WeKnoraMonitor({
focus,
onLocateSource,
}: {
focus?: { source: string; q: string } | null
onLocateSource?: (sourceID: string, parentNodeID: string) => void
} = {}) {
const auth = useOptionalAuth()
const canOperate = auth?.identity?.role === 'admin' || auth?.identity?.role === 'engineer'
const [overview, setOverview] = useState<MonitorOverview | null>(null),
@@ -544,6 +599,13 @@ export function WeKnoraMonitor() {
setTabs([])
return () => setTabs([])
}, [setTabs])
// 从来源目录“查看处理”进入:一次性套用来源+文件名定位,之后由用户自行改筛选。
useEffect(() => {
if (!focus) return
setFilters((current) => ({ ...current, q: focus.q, source: focus.source, target: '', scope: '' }))
setOffset(0)
setSelected([])
}, [focus])
useEffect(() => {
const c = new AbortController()
void fetchActiveUISettings(c.signal)
@@ -742,8 +804,9 @@ export function WeKnoraMonitor() {
.catch((e) => setMessage(e instanceof Error ? e.message : '读取详情失败'))
}}
onRefresh={refresh}
onLocateSource={onLocateSource}
/>
{detail ? <TaskDetail item={detail} onClose={() => setDetail(null)} /> : null}
{detail ? <TaskDetail item={detail} onClose={() => setDetail(null)} onLocateSource={onLocateSource} /> : null}
</>
)
}
+1
View File
@@ -47,6 +47,7 @@ export interface ServiceHealth {
observed_at: string
last_success_at: string | null
consecutive_failures: number
probe_target?: string
configured: boolean
applicable: boolean
}
+17 -1
View File
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { fetchMonitorTasks } from './monitorTasks'
import { fetchMonitorTasks, isCurrentTarget, targetLabel } from './monitorTasks'
import { healthLabel } from './WeKnoraMonitor'
import type { ServiceHealth } from './monitor'
afterEach(() => vi.unstubAllGlobals())
@@ -44,3 +44,19 @@ describe('monitor table contract', () => {
expect(healthLabel({ ...s, readiness: 'blocked' })).toBe('阻断')
})
})
describe('target identity labels (F15)', () => {
const bindings = { internal: '0c84a098-d3ed-4b82-a165-e6de9691d6a8', external: 'ext-11112222-3333' }
it('distinguishes same-named knowledge bases by short id and binding state', () => {
const current = targetLabel('对内知识库', bindings.internal, 'internal', bindings)
const historical = targetLabel('对内知识库', 'sc-ed1f812c4e5fabe817fc6351104938c4', 'internal', bindings)
expect(current).toContain('0c84a098')
expect(current).toContain('当前绑定')
expect(historical).toContain('sc-ed1f8')
expect(historical).toContain('历史')
expect(current).not.toBe(historical)
})
it('never treats an env/unknown target as the current binding', () => {
expect(isCurrentTarget('1b52c140-2e18-4676-afc5-4c7d8d190a8c', 'internal', bindings)).toBe(false)
})
})
+26 -2
View File
@@ -3,6 +3,8 @@ export interface MonitorTask {
id: string
title: string
path: string
node_id: string
parent_node_id: string
source_id: string
source_name: string
target_scope: string
@@ -23,9 +25,22 @@ export interface MonitorTaskPage {
limit: number
offset: number
sources: { id: string; name: string }[]
targets: { id: string; name: string }[]
targets: { id: string; name: string; scope?: string }[]
bindings: MonitorBindings
retryable: number
}
export interface MonitorBindings {
internal: string
external: string
}
export const shortID = (id: string) => (id.length > 8 ? id.slice(0, 8) : id)
export const isCurrentTarget = (id: string, scope: string, bindings: MonitorBindings) =>
Boolean(id) &&
(scope === 'external' ? bindings.external === id : scope === 'internal' ? bindings.internal === id : false)
// 同名目标(例如两个“对内知识库”)只靠名称无法区分:名称 + 短 ID,
// 并明确当前绑定/历史;完整 ID 留在详情里。
export const targetLabel = (name: string, id: string, scope: string, bindings: MonitorBindings) =>
`${name || '目标知识库'} · ${shortID(id)}${isCurrentTarget(id, scope, bindings) ? ' · 当前绑定' : ' · 历史'}`
export interface MonitorFilters {
q: string
source: string
@@ -102,6 +117,8 @@ export async function fetchMonitorTasks(
'id',
'title',
'path',
'node_id',
'parent_node_id',
'source_id',
'source_name',
'target_scope',
@@ -125,5 +142,12 @@ export async function fetchMonitorTasks(
for (const option of [...d.sources, ...d.targets])
if (!record(option) || typeof option.id !== 'string' || typeof option.name !== 'string')
throw new Error('文件处理筛选项无效')
return d as unknown as MonitorTaskPage
const bindings = record(d.bindings) ? d.bindings : {}
return {
...d,
bindings: {
internal: typeof bindings.internal === 'string' ? bindings.internal : '',
external: typeof bindings.external === 'string' ? bindings.external : '',
},
} as unknown as MonitorTaskPage
}