feat(web): 发布管理界面精简 + 系统设置审查修复
build / build (push) Successful in 1m51s

发布管理:状态卡 + 一个主按钮,准备动作与检查项分层次收纳,去掉重复入口。
系统设置:F02 停滞阈值接入活动配置;F03 分区保存边界;F05/F06 生产绑定分层与凭据说明;
F07 备份未接主机/未知证据如实显示;F09 分区独立加载与保存后重探;F10 文案精简;F11 重置密码对话框。
This commit is contained in:
dev
2026-11-17 15:23:29 +08:00
parent cbc6b981c6
commit 0fb78cfe26
20 changed files with 718 additions and 490 deletions
+18
View File
@@ -1,5 +1,23 @@
# Changelog
## 开发快照 0.1.383(发布管理精简 + 系统设置审查修复)
### Changed
- 发布管理:顶部改为「状态卡 + 下一步」,一个主按钮(启动同步/查看任务)+ 一个准备按钮
(封存/基线/签发授权);启动条件、检查清单、恢复验证收进「发布前检查」;
目标维护、差异明细、来源身份收进「高级与历史」。去掉重复的版本入口与说明。
### Fixed
- 服务配置与刷新策略各自保存边界:保存一方不再夹带另一方未保存的草稿(F03)。
- 系统设置分区独立加载:监控/目录失败不再挡住成员与备份入口;保存后重新探测服务状态(F09)。
- 解析停滞阈值接入活动配置(worker 60 秒内生效),收尾超时仍只保存并在页面标注未接入(F02)。
- 重置密码改为受控遮罩对话框,不再用浏览器 prompt(F11)。
- 生产绑定:文档级旧配置收进折叠区,凭据缺失时说明不影响整库执行器(F05/F06)。
- 备份:主机未接通时明确「当前计划不会执行」,无运行记录时失败库显示未知(F07)。
- 文案统一:生产租户 ID、备份执行主机、收尾超时告警;技术细节不再占据主视图(F10)。
## 开发快照 0.1.382(采集 agent 允许显式 peer uid)
### Added
+32
View File
@@ -10,6 +10,7 @@ import (
"os/signal"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
@@ -561,6 +562,11 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
Client: client,
PollDelay: config.TestWeKnoraPollInitial,
StallAfter: config.TestWeKnoraStalledAfter,
// 页面保存的停滞阈值在这里生效;每 60 秒重读一次活动配置,
// 读失败保留上一次值,再失败才回落到启动参数。
StallAfterSource: func() time.Duration {
return activeStalledAfter(context.Background(), store, config.TestWeKnoraStalledAfter)
},
})
if err != nil {
return nil, fmt.Errorf("create test poll handler: %w", err)
@@ -592,3 +598,29 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
handlers["test.remove"] = remove.Handle
return handlers, nil
}
// activeStalledAfter 读取活动 UI 配置里的解析停滞阈值(带 60 秒缓存)。
// 页面保存后无需重启 worker 即可生效;“保存即生效”不是文案,而是这里的读取。
var stalledAfterCache struct {
mu sync.Mutex
value time.Duration
fetchedAt time.Time
}
func activeStalledAfter(ctx context.Context, store *postgresstore.Store, fallback time.Duration) time.Duration {
stalledAfterCache.mu.Lock()
defer stalledAfterCache.mu.Unlock()
if time.Since(stalledAfterCache.fetchedAt) < time.Minute && stalledAfterCache.value > 0 {
return stalledAfterCache.value
}
settings, err := store.GetActiveUISettings(ctx)
if err != nil || settings.StalledAfterSeconds <= 0 {
if stalledAfterCache.value > 0 {
return stalledAfterCache.value
}
return fallback
}
stalledAfterCache.value = time.Duration(settings.StalledAfterSeconds) * time.Second
stalledAfterCache.fetchedAt = time.Now()
return stalledAfterCache.value
}
+8 -3
View File
@@ -35,7 +35,9 @@ type PollHandlerConfig struct {
Client PollClient
PollDelay time.Duration
StallAfter time.Duration
Now func() time.Time
// StallAfterSource 可选:返回当前生效的停滞阈值(来自活动 UI 配置)。
StallAfterSource func() time.Duration
Now func() time.Time
}
type PollHandler struct {
@@ -43,7 +45,10 @@ type PollHandler struct {
client PollClient
pollDelay time.Duration
stallAfter time.Duration
now func() time.Time
// stallAfterSource 存在时优先于 stallAfter:页面保存的“解析停滞阈值”
// 必须真的决定判定,而不是只写进数据库。
stallAfterSource func() time.Duration
now func() time.Time
}
type pollPayload struct {
@@ -60,7 +65,7 @@ func NewPollHandler(config PollHandlerConfig) (*PollHandler, error) {
}
return &PollHandler{
store: config.Store, client: config.Client, pollDelay: config.PollDelay,
stallAfter: config.StallAfter, now: config.Now,
stallAfter: config.StallAfter, stallAfterSource: config.StallAfterSource, now: config.Now,
}, nil
}
+1 -1
View File
@@ -81,7 +81,7 @@ describe('BackupScheduleView', () => {
const html = view()
for (const text of [
'存储与备份',
'目标库所在主机',
'备份执行主机',
'定时时间',
'储存天数',
'每月归档保留',
+14 -6
View File
@@ -104,7 +104,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
<div>
<h2>存储与备份</h2>
<p>
整库逻辑备份(pg_dump 目录格式)在<strong>目标库所在主机</strong>
整库逻辑备份(pg_dump 目录格式)在<strong>备份执行主机</strong>(同 VPC 直连 RDS)
上本地执行:这里设置定时时间与储存天数,保存即下发到主机 cron,并可读回主机上生效的计划与最近一次结果。
</p>
</div>
@@ -136,9 +136,11 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
<dd>
{schedule.host_next_run
? schedule.host_next_run
: schedule.host_schedule_enabled
? `已配置每日 ${schedule.host_schedule_time};尚未核验下一次实际执行(不以历史下发时间推算)`
: '未启用定时或未从主机读到计划'}
: !schedule.host_configured
? '未接通备份执行主机:当前计划不会执行'
: schedule.host_schedule_enabled
? `已配置每日 ${schedule.host_schedule_time};尚未核验下一次实际执行(不以历史下发时间推算)`
: '未启用定时或未从主机读到计划'}
</dd>
<dt>最近一次运行</dt>
<dd>
@@ -163,7 +165,13 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
<dt>覆盖的库</dt>
<dd>{schedule.last_run_databases.length ? schedule.last_run_databases.join('、') : '—'}</dd>
<dt>失败的库</dt>
<dd>{schedule.last_run_failed_databases.length ? schedule.last_run_failed_databases.join('、') : '无'}</dd>
<dd>
{schedule.last_run_failed_databases.length
? schedule.last_run_failed_databases.join('、')
: schedule.last_run_stamp
? '无'
: '未知(还没有读到运行记录,不能据此判断没有失败)'}
</dd>
<dt>主机上生效的计划</dt>
<dd>
{schedule.host_schedule_enabled
@@ -268,7 +276,7 @@ export function BackupScheduleView(props: BackupScheduleViewProps) {
)
}
// 容器:读取 + 下发 + 在途轮询。真正执行备份的是目标库所在主机(同 VPC 直连 RDS)。
// 容器:读取 + 下发 + 在途轮询。真正执行备份的是备份执行主机(同 VPC 直连 RDS)。
export function BackupScheduleSection() {
const auth = useOptionalAuth()
const isAdmin = auth?.identity?.role === 'admin'
+46 -9
View File
@@ -23,6 +23,9 @@ export function MembersSection() {
const [busy, setBusy] = useState<string | null>(null)
const [error, setError] = useState<string | null>(null)
const [message, setMessage] = useState<string | null>(null)
// 重置密码用受控对话框(遮罩输入),不再借浏览器 prompt 显示明文。
const [resetTarget, setResetTarget] = useState<{ id: string; username: string } | null>(null)
const [resetValue, setResetValue] = useState('')
const [form, setForm] = useState({
username: '',
display_name: '',
@@ -154,15 +157,8 @@ export function MembersSection() {
className="secondary-action"
disabled={busy === user.id}
onClick={() => {
const temporary = window.prompt(
`为 ${user.username} 生成一个临时密码(至少 8 位,对方首次登录必须更换)`
)
if (temporary)
void run(
user.id,
() => resetManagedUserPassword(user.id, temporary),
`${user.username} 的临时密码已生效`
)
setResetTarget({ id: user.id, username: user.username })
setResetValue('')
}}
>
重置密码
@@ -238,6 +234,47 @@ export function MembersSection() {
</button>
</div>
<small>停用不会删除任何业务记录,只禁止登录并立即撤销其在线会话。</small>
{resetTarget ? (
<div className="member-reset-dialog" role="dialog" aria-modal="true" aria-label="重置临时密码">
<h3>重置 {resetTarget.username} 的临时密码</h3>
<p>至少 8 位;对方首次登录必须更换,旧会话会立即失效。</p>
<PasswordInput
value={resetValue}
autoFocus
autoComplete="new-password"
onChange={(event) => setResetValue(event.target.value)}
/>
<div className="row-actions">
<button
type="button"
disabled={resetValue.length < 8 || busy === resetTarget.id}
onClick={() => {
const target = resetTarget
const value = resetValue
setResetTarget(null)
setResetValue('')
void run(
target.id,
() => resetManagedUserPassword(target.id, value),
`${target.username} 的临时密码已生效`
)
}}
>
确认重置
</button>
<button
type="button"
className="secondary-action"
onClick={() => {
setResetTarget(null)
setResetValue('')
}}
>
取消
</button>
</div>
</div>
) : null}
</section>
)
}
+1 -1
View File
@@ -65,7 +65,7 @@ describe('ProductionBindingsView', () => {
it('旧文档级绑定标成旧路径,不再声称"发布写入此库"', () => {
const html = view(bindings())
expect(html).toContain('文档级发布(单篇文档写生产)· 旧路径')
expect(html).toContain('仅文档级发布读取这组绑定;整库发布(封存/同步/恢复)不读它。')
expect(html).toContain('整库封存/同步/恢复不读取这组配置')
expect(html).toContain('对内文档级目标')
expect(html).not.toContain('发布写入此库')
})
+12 -12
View File
@@ -103,7 +103,9 @@ export function ProductionBindingsView(props: ProductionBindingsViewProps) {
</div>
{error ? (
<p className="error-message" role="alert">
{error}
{/api key file/i.test(error)
? '生产 API 读取凭据未配置:无法在此列出生产知识库。整库同步走独立执行器通道,不受这条读取凭据影响。'
: error}
</p>
) : null}
{bindings ? (
@@ -133,14 +135,16 @@ export function ProductionBindingsView(props: ProductionBindingsViewProps) {
</div>
) : null}
{bindings ? (
<div className="stack">
<h3>{bindings.legacy_scope || '文档级绑定(旧路径)'}</h3>
<p className="hint">仅文档级发布读取这组绑定;整库发布(封存/同步/恢复)不读它。</p>
<details className="stack legacy-bindings">
<summary>
{bindings.legacy_scope || '文档级发布(单篇文档写生产)· 旧路径'}
<span className="hint"> · 展开编辑;整库封存/同步/恢复不读取这组配置</span>
</summary>
<div className="kb-binding-grid">
{renderSide('对内文档级目标', bindings.internal_kb_id, bindings.internal_kb_name)}
{renderSide('对外文档级目标', bindings.external_kb_id, bindings.external_kb_name)}
</div>
</div>
</details>
) : null}
{bindings && !bindings.production_connected ? (
<p className="hint">
@@ -156,12 +160,8 @@ export function ProductionBindingsView(props: ProductionBindingsViewProps) {
) : null}
{isAdmin && bindings ? (
<div className="kb-binding-editor">
<label>
对内文档级目标 {editorFor(internalDraft, onInternalChange, '选择对内文档级目标库')}
</label>
<label>
对外文档级目标 {editorFor(externalDraft, onExternalChange, '选择对外文档级目标库')}
</label>
<label>对内文档级目标 {editorFor(internalDraft, onInternalChange, '选择对内文档级目标库')}</label>
<label>对外文档级目标 {editorFor(externalDraft, onExternalChange, '选择对外文档级目标库')}</label>
<p className="hint">保存时只改文档级绑定;整库发布目标由部署配置决定,本页不改它。</p>
<p className="hint">保存时会向生产端核对所选的库是否真实存在;对不上会拒收,生产端不可达则只提示。</p>
{sameSelection ? <p className="error-message">对内与对外必须绑定不同的生产知识库</p> : null}
@@ -259,4 +259,4 @@ export function ProductionBindingsSection() {
onReload={() => void load()}
/>
)
}
}
+203 -175
View File
@@ -958,39 +958,15 @@ function ProtectionCard({
<dt>恢复条件</dt>
<dd>{gate.reasons.length === 0 ? '已满足' : `缺 ${gate.reasons.length} 项`}</dd>
</dl>
<RestoreVerificationSection
scope={scope}
isAdmin={sync.canSign}
onAccepted={verification.onAccepted}
onComplete={verification.onComplete}
/>
{gate.reasons.length > 0 ? (
<ul className="rel-gate" aria-label="恢复与启动条件">
{gate.reasons.map((reason) => (
<li key={reason}>{reason}</li>
))}
</ul>
) : null}
<div className="rel-drawer-actions">
{sync.canSign && authorization.state !== 'active' && targetSealed ? (
<button type="button" className="rel-secondary" onClick={sync.onGrant} disabled={sync.pendingGrant}>
{sync.pendingGrant ? '签发中…' : '签发同步授权(30 分钟)'}
</button>
) : null}
{baseline.canStart && baselineNeeded ? (
<button type="button" className="rel-secondary" onClick={baseline.onStart} disabled={baseline.pending}>
{baseline.pending ? '投递中…' : '建立目标权威基线(维护隔离)'}
</button>
) : null}
</div>
<p className="rel-hint">
{gate.reasons.length > 0
? `启动与恢复条件还有 ${gate.reasons.length} 项未满足,见上方“发布前检查”。`
: '启动与恢复条件已满足。'}
</p>
{authorization.state !== 'active' && !sync.canSign ? (
<p className="rel-hint">同步授权只能由管理员按目标+快照签发;工程师看不到签发入口。</p>
) : null}
<p className="rel-hint">同步启动后,这里显示本次生产恢复点及备份进度,可直接查看对应快照。</p>
<button type="button" className="rel-secondary" onClick={onOpen}>
查看已有版本与快照 ›
</button>
<p className="rel-warn">恢复版本会恢复一整套生产知识状态,不回退测试知识库。</p>
<p className="rel-warn">恢复会回退整套生产知识状态,不回退测试知识库。</p>
</aside>
)
}
@@ -1040,7 +1016,6 @@ function ReadyBody({
return (
<>
<div className="rel-grid">
<ChangeTable diff={diff} />
<ProtectionCard
production={production}
productionNote={productionNote}
@@ -1077,18 +1052,7 @@ function ReadyBody({
: '还没有测试库封存。封存会短暂停住测试写入者,导出完整版本后恢复。'}
</p>
</div>
{canCapture ? (
<button
type="button"
className="rel-secondary"
onClick={onCapture}
disabled={pendingCapture || Boolean(view.activeJob)}
>
{pendingCapture ? '投递中…' : '封存测试版本'}
</button>
) : (
<span className="rel-hint">{captureHint(view, canWrite)}</span>
)}
<span className="rel-hint">{canCapture ? '封存入口在页面顶部“下一步”。' : captureHint(view, canWrite)}</span>
</div>
</>
)
@@ -1918,17 +1882,69 @@ export function ReleaseTargetsView(props: ViewProps) {
const gate = view.overview?.gate ?? { sync_allowed: false, reasons: ['整库状态接口不可用'] }
const authorization = view.overview?.authorization ?? { state: 'none' as const, reason: '整库状态接口不可用' }
const sealed = Boolean(view.snapshot)
const authorizationActive = authorization.state === 'active'
// 主按钮永远是"同步"或"查看当前任务";准备动作(封存/基线/恢复验证/授权)
// 作为次要按钮按状态出现,页面因此只有一个前进方向。
const primaryAction = runningJob
? {
label: '查看当前任务',
hint: `${jobKindText(runningJob.kind)}正在执行,不要重复启动。`,
disabled: false,
run: () => document.getElementById('rel-progress')?.scrollIntoView?.({ behavior: 'smooth', block: 'start' }),
}
: {
label: sync.pending ? '投递中…' : '▶ 启动同步',
hint: sync.canStart
? '先固定测试版本,再备份目标并写入;失败会停在维护窗口。'
: `暂不能启动:${gate.reasons.join(';') || '条件未满足'}`,
disabled: !sync.canStart || sync.pending,
run: sync.onStart,
}
const prepAction = !sealed
? canCapture
? {
label: pendingCapture ? '封存中…' : '封存测试版本',
hint: '只读导出测试库,生成一份可发布的整库版本。',
disabled: pendingCapture,
run: onCapture,
}
: { label: '尚无封存', hint: captureHint(view, canWrite), disabled: true, run: () => {} }
: productionClass === 'nonempty' && baseline.canStart
? {
label: baseline.pending ? '投递中…' : '建立目标权威基线(维护隔离)',
hint: '生产目标非空但还没有权威版本,先登记一份基线。',
disabled: baseline.pending,
run: baseline.onStart,
}
: !authorizationActive && sync.canSign
? {
label: sync.pendingGrant ? '签发中…' : '签发同步授权(30 分钟)',
hint: '授权后才允许写生产;一次授权只对当前目标+快照有效。',
disabled: sync.pendingGrant,
run: sync.onGrant,
}
: null
const productionText =
productionClass === 'known' && production?.version
? production.version.version_label || `生效 ${production.version.snapshot_id.slice(0, 12)}`
: productionClass === 'empty'
? '目标已读且为空'
: productionClass === 'unreachable'
? '读取失败'
: productionClass === 'nonempty'
? '目标非空,尚无权威版本'
: '未读取'
return (
<section className="release-targets" aria-label="发布管理">
<header className="rel-head page-header">
<div>
<h1 className="page-title">发布管理</h1>
<p className="page-subtitle">测试维护与验证,生产按知识库版本同步。</p>
<p className="page-subtitle">测试封存 → 生产同步:每一步只保留一个入口。</p>
</div>
<div className="rel-head-actions page-header-actions">
<button type="button" className="rel-secondary" onClick={() => onDrawer(true)}>
▣ 版本与快照
</button>
<button type="button" className="rel-secondary" onClick={onRefresh} disabled={loading}>
{loading ? '刷新中…' : '刷新'}
</button>
@@ -1969,128 +1985,87 @@ export function ReleaseTargetsView(props: ViewProps) {
) : null}
{notice ? <p className="rel-notice">{notice}</p> : null}
<div className="rel-panel rel-jobhead">
<div className="rel-between">
<h2>
{scopeName(scope)} ·{' '}
{active
? `${jobKindText(view.job?.kind)}进行中`
: view.snapshot
? '已封存,同步按条件放行'
: '尚无测试封存'}
</h2>
<div className="rel-head-actions">
<button type="button" className="rel-secondary" onClick={() => onDrawer(true)}>
版本与快照
</button>
<button
type="button"
className="rel-primary"
onClick={() => {
if (runningJob) {
document.getElementById('rel-progress')?.scrollIntoView?.({ behavior: 'smooth', block: 'start' })
return
}
sync.onStart()
}}
disabled={Boolean(runningJob) ? false : !sync.canStart || sync.pending}
title={
runningJob
? `${jobKindText(runningJob.kind)}正在执行;请查看当前任务,不要重复启动`
: sync.canStart
? '按已签发的同步授权启动:先固定测试版本,再备份目标并写入'
: `暂不能启动同步:${gate.reasons.join(';')}`
}
>
{runningJob ? '查看当前任务' : sync.pending ? '投递中…' : '▶ 启动同步'}
</button>
</div>
</div>
<p className="rel-target-identity" aria-label="实际目标实例">
目标实例 {view.overview?.target_instance || view.overview?.executor?.instance || '未读取'} · 项目{' '}
{view.overview?.target_project || view.overview?.executor?.project || '未读取'} · 知识库{' '}
{view.overview?.target_knowledge_base_id || target?.knowledge_base_id || '未读取'}({scopeName(scope)})
<div className="rel-panel rel-status">
<p className="rel-scope-state">
{scopeName(scope)} ·{' '}
{active ? `${jobKindText(view.job?.kind)}进行中` : sealed ? '已封存,同步按条件放行' : '尚无测试封存'}
{sealed ? '(需要新版本时点上方“封存测试版本”)' : ''}
</p>
<p className="rel-versionline">
目标当前{' '}
{productionClass === 'known' && production?.version ? (
<b>
{production.version.version_label || `生效 ${production.version.snapshot_id.slice(0, 12)}`}
{' · '}
快照 {production.version.snapshot_id.slice(0, 12)}
</b>
) : productionClass === 'empty' ? (
<b>目标已读且为空(首次发布)</b>
) : productionClass === 'unreachable' ? (
<b className="rel-unknown">读取失败:{production?.reason || '无法读取目标整库状态'}</b>
) : productionClass === 'nonempty' ? (
<b className="rel-unknown">目标非空,尚无权威版本</b>
) : (
<b className="rel-unknown">{productionNote}</b>
)}
{productionStale ? <em className="rel-scope">({STALE_NOTE})</em> : null} → 拟发布{' '}
<b>{target ? `封存 ${target.snapshot_id.slice(0, 12)} · ${stamp(target.created_at)}` : '还没有测试封存'}</b> ·{' '}
{publishStateText(view.job)}
</p>
<dl className="rel-metrics">
<dl className="rel-status-grid">
<div>
<dt>新增文档</dt>
<dd className={diff.state === 'computed' ? '' : 'rel-unknown'}>
{diff.state === 'computed' ? diff.added.length : '未接入'}
<dt>测试封存</dt>
<dd className={sealed ? '' : 'rel-unknown'}>
{sealed ? `快照 ${view.snapshot!.snapshot_id.slice(0, 12)}` : '尚无'}
</dd>
<small>{sealed ? stamp(view.snapshot!.created_at) : '先封存测试版本'}</small>
</div>
<div>
<dt>更新文档</dt>
<dd className={diff.state === 'computed' ? '' : 'rel-unknown'}>
{diff.state === 'computed' ? diff.updated.length : '未接入'}
</dd>
<dt>生产当前</dt>
<dd className={productionClass === 'known' ? '' : 'rel-unknown'}>{productionText}</dd>
<small>{publishStateText(view.job)}</small>
</div>
<div>
<dt>删除文档</dt>
<dd className={diff.state === 'computed' ? '' : 'rel-unknown'}>
{diff.state === 'computed' ? diff.removed.length : '未接入'}
</dd>
<dt>发布授权</dt>
<dd className={authorizationActive ? '' : 'rel-unknown'}>{authorizationActive ? '已签发' : '未签发'}</dd>
<small>
{authorizationActive
? `有效至 ${stamp(authorization.expires_at ?? '')}`
: sync.canSign
? '可在下方签发'
: '需管理员签发'}
</small>
</div>
<div>
<dt>Wiki 发布方式</dt>
<dd>{target ? '完整快照' : '未接入'}</dd>
<dt>最近预备份</dt>
<dd className={prebackup.state === 'known' ? '' : 'rel-unknown'}>
{prebackup.state === 'known' ? '已登记' : '无'}
</dd>
<small>
{prebackup.state === 'known' && prebackup.version
? stamp(prebackup.version.created_at)
: '同步时自动生成'}
</small>
</div>
</dl>
{target?.source_identity ? (
<details className="rel-source-identity">
<summary>来源身份与完整摘要</summary>
<p>
来源实例:{target.source_identity.project} / {target.source_identity.app}
</p>
<p>
来源租户 / 知识库:{target.source_identity.tenant_id} / {target.source_identity.knowledge_base_id}
</p>
<p>来源身份:{target.source_id}</p>
<p>快照摘要:{target.snapshot_id}</p>
</details>
<div className="rel-status-actions">
<p className="rel-next">
<span>下一步</span>
{prepAction && prepAction.disabled === false && !runningJob ? prepAction.hint : primaryAction.hint}
</p>
{prepAction && !runningJob ? (
<button
type="button"
className="rel-secondary"
onClick={prepAction.run}
disabled={prepAction.disabled}
title={prepAction.hint}
>
{prepAction.label}
</button>
) : null}
<button
type="button"
className="rel-primary"
onClick={primaryAction.run}
disabled={primaryAction.disabled}
title={primaryAction.hint}
>
{primaryAction.label}
</button>
<button type="button" className="rel-secondary" onClick={() => onDrawer(true)}>
版本与快照
</button>
</div>
{gate.reasons.length > 0 ? (
<p className="rel-hint">还差 {gate.reasons.length} 项条件,展开“发布前检查”查看原因。</p>
) : null}
<ul className="rel-checklist">
<li className={target ? 'ok' : 'unknown'}>
{target
? `✓ 文档解析与索引完整(${target.totals.chunks ?? 0} 分块 / ${target.totals.index_documents ?? 0} 索引)`
: '○ 文档解析与索引:未接入'}
{target ? (
<em className="rel-scope">
依据 {stamp(target.created_at)} 封存的测试库全库快照,不代表实时测试库已就绪
</em>
) : null}
</li>
<li className={target ? 'ok' : 'unknown'}>
{target ? `✓ Wiki 快照完整(${target.totals.wiki_pages ?? 0} 页)` : '○ Wiki 快照:未接入'}
{target ? <em className="rel-scope">同一份封存快照,不是实时 Wiki 队列状态</em> : null}
</li>
<li className={target ? 'ok' : 'unknown'}>
{target ? `✓ 清单与摘要登记:${target.parts.length} 项部件摘要已记录` : '○ 数据完整性:尚无封存可核验'}
{target ? (
<em className="rel-scope">封存时逐项哈希登记;列表只校验清单自身,字节级复核在同步/恢复执行前进行</em>
) : null}
</li>
</ul>
</div>
<details className="rel-check" id="rel-check" open={gate.reasons.length > 0}>
<summary>
发布前检查
{gate.reasons.length > 0 ? `(${gate.reasons.length} 项未满足)` : '(已满足)'}
</summary>
{gate.reasons.length > 0 ? (
<ul className="rel-gate" aria-label="启动同步的缺项">
{gate.reasons.map((reason) => (
@@ -2098,26 +2073,47 @@ export function ReleaseTargetsView(props: ViewProps) {
))}
</ul>
) : null}
<p className="rel-footnote">启动后先固定测试版本,再备份生产。备份失败或恢复条件不满足,不进入生产写入。</p>
</div>
<MaintenanceCard
maintenance={maintenance}
ownerJob={maintenanceOwnerJob}
scope={scope}
canWrite={canWrite}
onRecover={onRecover}
/>
<ul className="rel-checklist">
<li className={target ? 'ok' : 'unknown'}>
{target
? `✓ 文档解析与索引完整(${target.totals.chunks ?? 0} 分块 / ${target.totals.index_documents ?? 0} 索引)`
: '○ 文档解析与索引:未接入(尚无封存)'}
{target ? (
<em className="rel-scope">
依据 {stamp(target.created_at)} 封存的测试库全库快照,不代表实时测试库已就绪
</em>
) : null}
</li>
<li className={target ? 'ok' : 'unknown'}>
{target ? `✓ Wiki 快照完整(${target.totals.wiki_pages ?? 0} 页)` : '○ Wiki 快照:未接入(尚无封存)'}
{target ? <em className="rel-scope">同一份封存快照,不是实时 Wiki 队列状态</em> : null}
</li>
<li className={target ? 'ok' : 'unknown'}>
{target ? `✓ 清单与摘要登记:${target.parts.length} 项部件摘要` : '○ 数据完整性:未接入(尚无封存可核验)'}
{target ? (
<em className="rel-scope">封存时逐项哈希登记;列表只校验清单自身,字节级复核在同步/恢复执行前进行</em>
) : null}
</li>
</ul>
<RestoreVerificationSection
scope={scope}
isAdmin={sync.canSign}
onAccepted={verification.onAccepted}
onComplete={verification.onComplete}
/>
</details>
{active ? (
<ProgressBody
view={view}
now={now}
onOpen={() => onDrawer(true)}
canReconcileCapture={canReconcileCapture}
pendingReconcileCapture={pendingReconcileCapture}
onReconcileCapture={onReconcileCapture}
/>
<div id="rel-progress">
<ProgressBody
view={view}
now={now}
onOpen={() => onDrawer(true)}
canReconcileCapture={canReconcileCapture}
pendingReconcileCapture={pendingReconcileCapture}
onReconcileCapture={onReconcileCapture}
/>
</div>
) : (
<ReadyBody
view={view}
@@ -2139,6 +2135,38 @@ export function ReleaseTargetsView(props: ViewProps) {
/>
)}
<details className="rel-advanced">
<summary>高级与历史(目标维护、差异明细、来源身份)</summary>
<MaintenanceCard
maintenance={maintenance}
ownerJob={maintenanceOwnerJob}
scope={scope}
canWrite={canWrite}
onRecover={onRecover}
/>
<ChangeTable diff={diff} />
<p className="rel-target-identity" aria-label="实际目标实例">
目标实例 {view.overview?.target_instance || view.overview?.executor?.instance || '未读取'} · 项目{' '}
{view.overview?.target_project || view.overview?.executor?.project || '未读取'} · 知识库{' '}
{view.overview?.target_knowledge_base_id || target?.knowledge_base_id || '未读取'}({scopeName(scope)})
{productionStale ? <em className="rel-scope">({STALE_NOTE})</em> : null}
</p>
{target?.source_identity ? (
<details className="rel-source-identity">
<summary>来源身份与完整摘要</summary>
<p>
来源实例:{target.source_identity.project} / {target.source_identity.app}
</p>
<p>
来源租户 / 知识库:{target.source_identity.tenant_id} / {target.source_identity.knowledge_base_id}
</p>
<p>来源身份:{target.source_id}</p>
<p>快照摘要:{target.snapshot_id}</p>
</details>
) : null}
<p className="rel-footnote">同步会先固定测试版本,再备份生产;备份失败或恢复条件不满足时不进入生产写入。</p>
</details>
<Drawer
view={view}
page={page}
+2 -2
View File
@@ -273,9 +273,9 @@ describe('SystemSettingsView', () => {
'finalizing 2小时',
'文档状态刷新间隔',
'15秒',
'解析停滞判定',
'解析停滞阈值',
'30分钟',
'保存并应用刷新与告警参数',
'保存刷新与告警参数',
])
expect(refreshHtml).toContain(text)
expect(visibleSaveMessage('已保存', true)).toBeNull()
+75 -43
View File
@@ -183,21 +183,41 @@ export function SystemSettingsView({
productionTenantID.trim() !== settings.production_tenant_id ||
productionKnowledgeBaseID.trim() !== settings.production_knowledge_base_id)
)
const candidateInput = (overrides: Partial<UISettingsCandidateInput> = {}): UISettingsCandidateInput => ({
const refreshSettingsDirty = Boolean(
settings &&
(documentRefresh !== settings.document_refresh_seconds ||
resourceRefresh !== settings.resource_refresh_seconds ||
stalled !== settings.stalled_after_seconds ||
finalizing !== settings.finalizing_after_seconds ||
concurrency !== settings.ingestion_concurrency)
)
// 保存边界:服务分区只带上自己这一组的输入,另一组一律用服务器当前值。
// 否则“改了地址没保存、切到刷新策略保存”会把未确认的地址一起写进去。
const serviceInput = (): UISettingsCandidateInput => ({
document_refresh_seconds: settings?.document_refresh_seconds ?? documentRefresh,
resource_refresh_seconds: settings?.resource_refresh_seconds ?? resourceRefresh,
stalled_after_seconds: settings?.stalled_after_seconds ?? stalled,
finalizing_after_seconds: settings?.finalizing_after_seconds ?? finalizing,
ingestion_concurrency: settings?.ingestion_concurrency ?? concurrency,
test_weknora_base_url: testEndpoint.trim(),
production_weknora_base_url: endpoint.trim(),
production_tenant_id: productionTenantID.trim(),
production_knowledge_base_id: productionKnowledgeBaseID.trim(),
})
const refreshInput = (): UISettingsCandidateInput => ({
document_refresh_seconds: documentRefresh,
resource_refresh_seconds: resourceRefresh,
stalled_after_seconds: stalled,
finalizing_after_seconds: finalizing,
ingestion_concurrency: concurrency,
test_weknora_base_url: testEndpoint.trim(),
production_weknora_base_url: endpoint.trim(),
production_tenant_id: productionTenantID.trim(),
production_knowledge_base_id: productionKnowledgeBaseID.trim(),
...overrides,
test_weknora_base_url: settings?.test_weknora_base_url ?? '',
production_weknora_base_url: settings?.production_weknora_base_url ?? '',
production_tenant_id: settings?.production_tenant_id ?? '',
production_knowledge_base_id: settings?.production_knowledge_base_id ?? '',
})
const saveEndpoint = () => {
setDirty(false)
onSave(candidateInput())
onSave(serviceInput())
}
return (
<main className="page-shell system-settings">
@@ -211,7 +231,7 @@ export function SystemSettingsView({
{error}
</div>
) : null}
{monitor && settings ? (
{settings || monitor ? (
<div className="settings-layout">
<nav className="settings-nav" aria-label="系统设置分区">
{sections
@@ -258,14 +278,13 @@ export function SystemSettingsView({
<SourceManagementDetails connections={listedConnections} onSourcesChanged={onSourcesChanged} />
</section>
) : null}
{section === 'services' ? (
{section === 'services' && settings ? (
<section className="settings-panel wide" id="settings-services">
<div className="settings-section-heading">
<div>
<h2>服务配置</h2>
<p>
只配四项:测试地址、生产地址、生产 ID、知识库
ID。保存会先生成修订、验证后原子启用,旧版本保留用于审计;凭据只写不读。
四项可写:测试地址、生产地址、生产租户、生产知识库。保存前会做真实探活与列库核验,凭据只写不读。
</p>
</div>
</div>
@@ -274,7 +293,7 @@ export function SystemSettingsView({
<article>
<b>测试 WeKnora</b>
<span>{healthStateLabel(findHealth(monitor, 'WeKnora API'), undefined)}</span>
<small>{`${healthStateDetail(findHealth(monitor, 'WeKnora API'), undefined) || '端点探测:未配置'};解析队列 对内 ${routingCapabilities.internal_enabled ? '已配置' : '未配置'} · 对外 ${routingCapabilities.external_enabled ? '已配置' : '未配置'}`}</small>
<small>{`${healthStateDetail(findHealth(monitor, 'WeKnora API'), undefined) || '端点探测:未配置'};解析队列 对内 ${routingCapabilities.internal_enabled ? '已配置' : '未配置'} · 对外 ${routingCapabilities.external_enabled ? '已配置' : '未配置'};上传/解析执行器能力不在本卡片验证`}</small>
</article>
<article className="production">
<b>生产 WeKnora</b>
@@ -316,7 +335,7 @@ export function SystemSettingsView({
/>
</label>
<label>
生产 ID
生产租户 ID
<input
value={productionTenantID}
onChange={(event) => {
@@ -402,12 +421,12 @@ export function SystemSettingsView({
</>
) : null}
{section === 'members' && identity?.role === 'admin' ? <MembersSection /> : null}
{section === 'refresh' ? (
{section === 'refresh' && settings ? (
<section className="settings-panel wide" id="settings-refresh">
<div className="settings-section-heading">
<div>
<h2>刷新策略</h2>
<p>这些值保存在服务器活动版本中;保存不会修改端点、凭据或生产开关。</p>
<p>保存只改这一组参数,不会带上服务配置里未保存的地址。</p>
</div>
<span className="safe-badge">当前活动版本</span>
</div>
@@ -440,7 +459,7 @@ export function SystemSettingsView({
</select>
</label>
<label>
解析停滞判定
解析停滞阈值
<select
value={stalled}
onChange={(event) => {
@@ -453,7 +472,7 @@ export function SystemSettingsView({
</select>
</label>
<label>
finalizing 告警
收尾超时告警
<select
value={finalizing}
onChange={(event) => {
@@ -486,17 +505,20 @@ export function SystemSettingsView({
<button
onClick={() => {
setDirty(false)
onSave(candidateInput())
onSave(refreshInput())
}}
disabled={!canSave}
disabled={!canSave || !refreshSettingsDirty}
>
{saving ? '正在验证并应用…' : '保存并应用刷新与告警参数'}
{saving ? '正在验证并应用…' : '保存刷新与告警参数'}
</button>
{visibleSaveMessage(saveMessage, dirty) ? (
<p className="success-message" role="status">
{saveMessage}
</p>
) : null}
<p className="settings-warn">
解析停滞阈值保存后由 worker 在 1 分钟内生效;收尾超时告警目前只保存配置,判定尚未接入。
</p>
<small>
当前:文档 {secondsLabel(settings.document_refresh_seconds)}、资源{' '}
{secondsLabel(settings.resource_refresh_seconds)}、停滞 {secondsLabel(settings.stalled_after_seconds)}
@@ -529,35 +551,39 @@ export function SystemSettings() {
const [saveMessage, setSaveMessage] = useState<string | null>(null)
const [revision, setRevision] = useState(0)
// 六个请求彼此独立:任何一块失败只影响它自己,不能让成员、备份这些
// 互不相干的入口一起消失。设置本身读不到才阻断“设置”相关分区。
useEffect(() => {
const controller = new AbortController()
const failures: string[] = []
const track = <T,>(promise: Promise<T>, apply: (value: T) => void, label: string) =>
promise
.then((value) => {
if (!controller.signal.aborted) apply(value)
})
.catch((cause) => {
failures.push(`${label}:${cause instanceof Error ? cause.message : '读取失败'}`)
})
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)
track(fetchCatalogSources(controller.signal), setSources, '数据源'),
track(fetchSourceConnectionList(controller.signal), setConnections, '来源连接'),
track(fetchMonitorOverview(controller.signal), setMonitor, '监控'),
track(
fetchReleaseCapabilities(controller.signal),
(capabilities) => {
setProductionEnabled(capabilities.production_release_requests_enabled)
setProductionBackupRestoreVerified(capabilities.production_backup_restore_verified)
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)
})
},
'发布能力'
),
track(fetchCatalogRoutingCapabilities(controller.signal), setRoutingCapabilities, '路由能力'),
track(fetchActiveUISettings(controller.signal), setSettings, '系统设置'),
]).finally(() => {
if (controller.signal.aborted) return
setError(failures.length ? failures.join(';') : null)
setLoading(false)
})
return () => controller.abort()
}, [revision])
@@ -571,6 +597,12 @@ export function SystemSettings() {
const active = activated.settings
const verification = activated.verification ?? candidate.verification
setSettings(active)
// 保存成功后重新探测一次,卡片上的“最近检查”才不会停在旧结果。
try {
setMonitor(await fetchMonitorOverview())
} catch {
// 探测失败不影响保存结果,页面保留上一次观测。
}
setSaveMessage(
`设置已验证并启用:文档${secondsLabel(active.document_refresh_seconds)}、资源${secondsLabel(active.resource_refresh_seconds)}、停滞${secondsLabel(active.stalled_after_seconds)}、finalizing ${secondsLabel(active.finalizing_after_seconds)}、入库并发 ${active.ingestion_concurrency}、测试地址 ${active.test_weknora_base_url || '未配置'}、生产地址 ${active.production_weknora_base_url || '未配置'}、生产 ID ${active.production_tenant_id || '未配置'}、知识库 ID ${active.production_knowledge_base_id || '未配置'};旧版本已保留用于审计。${verification ? `核验:${verification.message}` : ''}`
)
+31 -35
View File
@@ -43,29 +43,27 @@ describe('monitor API', () => {
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,
})
)
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)
@@ -114,20 +112,18 @@ describe('monitor API', () => {
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 },
},
})
)
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()
})
+11 -13
View File
@@ -67,20 +67,18 @@ describe('production bindings API', () => {
it('reports an unverified save honestly instead of pretending it was checked', async () => {
vi.stubGlobal(
'fetch',
vi
.fn()
.mockResolvedValue(
new Response(
JSON.stringify({
data: {
...binding,
production_connected: false,
production_message: '生产 WeKnora 不可用:dial tcp: timeout',
},
}),
{ status: 200 }
)
vi.fn().mockResolvedValue(
new Response(
JSON.stringify({
data: {
...binding,
production_connected: false,
production_message: '生产 WeKnora 不可用:dial tcp: timeout',
},
}),
{ status: 200 }
)
)
)
const result = await saveProductionBindings({ internal_kb_id: 'kb-1', external_kb_id: '' })
expect(result.production_connected).toBe(false)
+77
View File
@@ -711,3 +711,80 @@
border-radius: 7px;
padding: 8px;
}
/* 发布管理精简版:一个状态卡 + 一个主按钮,其余收进折叠区。 */
.rel-status {
display: grid;
gap: 14px;
padding: 18px 20px;
}
.rel-status-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 14px;
margin: 0;
}
.rel-status-grid div {
border: 1px solid var(--border);
border-radius: 10px;
padding: 10px 12px;
background: var(--card);
}
.rel-status-grid dt {
font-size: 12px;
color: var(--muted-foreground);
margin-bottom: 4px;
}
.rel-status-grid dd {
margin: 0;
font-weight: 600;
font-size: 15px;
word-break: break-all;
}
.rel-status-grid small {
display: block;
margin-top: 4px;
color: var(--muted-foreground);
font-size: 12px;
}
.rel-status-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px;
}
.rel-next {
flex: 1 1 320px;
margin: 0;
color: var(--muted-foreground);
font-size: 13px;
}
.rel-next span {
display: inline-block;
margin-right: 8px;
padding: 1px 8px;
border-radius: 999px;
background: var(--accent);
color: var(--foreground);
font-size: 12px;
}
.rel-check,
.rel-advanced {
border: 1px solid var(--border);
border-radius: 12px;
padding: 4px 16px 12px;
background: var(--card);
}
.rel-check summary,
.rel-advanced summary {
cursor: pointer;
padding: 10px 0;
font-weight: 600;
}
.rel-check .rel-gate,
.rel-check .rel-checklist {
margin: 6px 0 10px;
}
.rel-advanced > * + * {
margin-top: 10px;
}
+32 -42
View File
@@ -400,22 +400,20 @@ describe('release change set (R1)', () => {
await expect(generateReleaseChangeSet('x')).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 }
)
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')
expect(confirmed.state).toBe('confirmed')
@@ -619,12 +617,10 @@ describe('审核策略的只读展示', () => {
describe('批量审核与建批即锁定', () => {
it('批量审核发送选中的条目与同一决定', async () => {
const fetchMock = vi
.fn()
.mockResolvedValue({
ok: true,
json: async () => ({ data: { selected: 2, decided: 2, skipped: 0, skipped_ids: [], reviews: [] } }),
})
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ data: { selected: 2, decided: 2, skipped: 0, skipped_ids: [], reviews: [] } }),
})
vi.stubGlobal('fetch', fetchMock)
const result = await reviewPublicationsBatch(['tp-a', 'tp-b'], 'approved', 'internal', 'approved_for_release')
expect(result).toEqual({ selected: 2, decided: 2, skipped: 0, skipped_ids: [] })
@@ -639,12 +635,10 @@ describe('批量审核与建批即锁定', () => {
})
it('如实回报被跳过的条目', async () => {
const fetchMock = vi
.fn()
.mockResolvedValue({
ok: true,
json: async () => ({ data: { selected: 3, decided: 2, skipped: 1, skipped_ids: ['tp-c'], reviews: [] } }),
})
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ data: { selected: 3, decided: 2, skipped: 1, skipped_ids: ['tp-c'], reviews: [] } }),
})
vi.stubGlobal('fetch', fetchMock)
const result = await reviewPublicationsBatch(
['tp-a', 'tp-b', 'tp-c'],
@@ -669,14 +663,12 @@ describe('批量审核与建批即锁定', () => {
describe('发布到生产(建批+锁定+授权合成一个动作)', () => {
it('提交条目与固定确认语句,回传批次与执行', async () => {
const fetchMock = vi
.fn()
.mockResolvedValue({
ok: true,
json: async () => ({
data: { batch: { id: 'rb-now', name: '立即发布 · 2026/10/10' }, execution: { id: 'rx-now' } },
}),
})
const fetchMock = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({
data: { batch: { id: 'rb-now', name: '立即发布 · 2026/10/10' }, execution: { id: 'rx-now' } },
}),
})
vi.stubGlobal('fetch', fetchMock)
const result = await runPublishNow(['tp-a', 'tp-b'], [], '立即发布 · 2026/10/10', 'publish-to-production')
expect(result).toEqual({ batch_id: 'rb-now', batch_name: '立即发布 · 2026/10/10', execution_id: 'rx-now' })
@@ -691,13 +683,11 @@ describe('发布到生产(建批+锁定+授权合成一个动作)', () => {
})
it('服务端拒绝时把原因带出来', async () => {
const fetchMock = vi
.fn()
.mockResolvedValue({
ok: false,
status: 412,
json: async () => ({ error: 'production backup restore verification is required' }),
})
const fetchMock = vi.fn().mockResolvedValue({
ok: false,
status: 412,
json: async () => ({ error: 'production backup restore verification is required' }),
})
vi.stubGlobal('fetch', fetchMock)
await expect(runPublishNow(['tp-a'], [], 'x', 'publish-to-production')).rejects.toThrow(
'production backup restore verification is required'
+29 -33
View File
@@ -5,26 +5,24 @@ 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 },
})
)
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)
@@ -34,22 +32,20 @@ describe('scope rule API', () => {
)
})
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',
},
})
)
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,
+85 -93
View File
@@ -59,57 +59,53 @@ describe('source catalog API', () => {
})
it('rejects a scanning source without progress instead of rendering a fake 0%', async () => {
const fetchMock = vi
.fn()
.mockResolvedValue(
new Response(
JSON.stringify({
data: [
{
connection_id: 'conn-scan',
source_type: 'dingtalk',
name: 'X',
root_node_id: '',
folder_count: 0,
file_count: 0,
observed_at: '2026-10-10T08:51:44Z',
snapshot_only: true,
snapshot_status: 'scanning',
last_refresh_duration_ms: 0,
},
],
summary: { total: 1 },
})
)
const fetchMock = vi.fn().mockResolvedValue(
new Response(
JSON.stringify({
data: [
{
connection_id: 'conn-scan',
source_type: 'dingtalk',
name: 'X',
root_node_id: '',
folder_count: 0,
file_count: 0,
observed_at: '2026-10-10T08:51:44Z',
snapshot_only: true,
snapshot_status: 'scanning',
last_refresh_duration_ms: 0,
},
],
summary: { total: 1 },
})
)
)
vi.stubGlobal('fetch', fetchMock)
await expect(fetchCatalogSources()).rejects.toThrow(/来源目录响应无效/)
})
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 },
})
)
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('公司级技术支持知识库')
@@ -248,22 +244,20 @@ describe('source catalog API', () => {
expect(fetchMock.mock.calls[1][1].headers['Idempotency-Key']).not.toBe('')
})
it('reports blocked items without planning anything', async () => {
const fetchMock = vi
.fn()
.mockResolvedValue(
new Response(
JSON.stringify({
data: {
selected_files: 2,
intents_recorded: 2,
fetch_queued: 0,
planned_publications: 0,
blocked_items: 2,
unbound_files: 0,
},
})
)
const fetchMock = vi.fn().mockResolvedValue(
new Response(
JSON.stringify({
data: {
selected_files: 2,
intents_recorded: 2,
fetch_queued: 0,
planned_publications: 0,
blocked_items: 2,
unbound_files: 0,
},
})
)
)
vi.stubGlobal('fetch', fetchMock)
const result = await routeCatalogFiles({
connection_id: 'conn-1',
@@ -301,40 +295,38 @@ describe('source catalog API', () => {
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',
},
})
)
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)
+25
View File
@@ -882,3 +882,28 @@ button.link {
font-size: 0.8rem;
line-height: 1.5;
}
.settings-warn {
margin: 8px 0 0;
color: #b45309;
font-size: 12px;
}
.member-reset-dialog {
margin-top: 16px;
border: 1px solid var(--border);
border-radius: 12px;
padding: 14px 16px;
background: var(--card);
display: grid;
gap: 8px;
}
.member-reset-dialog h3 {
margin: 0;
font-size: 15px;
}
.member-reset-dialog p {
margin: 0;
color: var(--muted-foreground);
font-size: 12px;
}
+10 -14
View File
@@ -127,13 +127,11 @@ describe('需下架条目的移除入口', () => {
})
it('带幂等键触发下架并回传任务号', async () => {
const fetchMock = vi
.fn()
.mockResolvedValue(
new Response(JSON.stringify({ publication_id: 'tp-1', job_id: 'job-remove-1', state: 'disabling' }), {
status: 202,
})
)
const fetchMock = vi.fn().mockResolvedValue(
new Response(JSON.stringify({ publication_id: 'tp-1', job_id: 'job-remove-1', state: 'disabling' }), {
status: 202,
})
)
vi.stubGlobal('fetch', fetchMock)
await expect(startPublicationRemoval('tp-1')).resolves.toEqual({ job_id: 'job-remove-1' })
@@ -155,13 +153,11 @@ describe('需下架条目的移除入口', () => {
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,
})
)
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'], '已核对差异')).resolves.toEqual({
+6 -8
View File
@@ -205,15 +205,13 @@ describe('UI settings API', () => {
}
vi.stubGlobal(
'fetch',
vi
.fn()
.mockImplementation(() =>
Promise.resolve(
new Response(JSON.stringify({ error: '未通过:生产地址上找不到知识库 ID「kb-prod-1」', verification }), {
status: 400,
})
)
vi.fn().mockImplementation(() =>
Promise.resolve(
new Response(JSON.stringify({ error: '未通过:生产地址上找不到知识库 ID「kb-prod-1」', verification }), {
status: 400,
})
)
)
)
await expect(createUISettingsCandidate(candidateInput)).rejects.toThrow('找不到知识库 ID')
const failure = await createUISettingsCandidate(candidateInput).catch((cause: unknown) => cause)